借鉴 Mole 的 12 项安全架构与交互全部落地;修复启动项开关失效
- 空间清理:扫描实时计数(已统计 N 文件 · X,进度封顶 99%);分类算完一个亮一个; 清理点/文件行「X 未使用」休眠标签;node_modules 可删依据面板(锁文件/安装记录/ 手改检测/Git/年龄);低风险走底部绿色内联确认条(Esc 取消),对话框新增 「刚刚逐路径复核过」审计面板;结果页按原因分组展示未处理项并给下一步按钮; 清理清单导出 Markdown(含依据与受保护项)。 - 存储空间:新增「隐藏的吃空间大户」(更新缓存/休眠/页面文件/WinSxS/手机备份/旧下载); 文件夹测量缓存 10 分钟 + 新鲜度标注 + 重新测量,删除后缓存自动作废。 - 引擎:微信/QQ 聊天文件、浏览器 IndexedDB 离线数据、搜狗词库等个人文件在扫描结果 以待解锁行呈现且删除层强制拒删;preflight 删除前逐路径复核;白名单消费审计 (设置页标注每条规则最近是否命中)。 - 修复:权限管理开机启动项开关点击无效/弹回——StartupApproved 标记改用最小注册表 权限写入(原 KEY_ALL_ACCESS 在安全软件驻留的机器上直接被拒),拒绝访问时自动 UAC 提权重试并回读核实;计划任务/服务同样支持提权通道;开关失败新增红色气泡。 - 无头浏览器 29 项点击断言全过;cargo test/clippy/fmt、pnpm check/build 全绿;0.1.10 重新打包。dev
parent
dccbe9b60a
commit
e3eba338a7
|
|
@ -594,7 +594,7 @@ fn with_progress<T>(
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Event::Bucket { .. } | Event::Done(_) => {}
|
Event::Bucket { .. } | Event::Metered { .. } | Event::Done(_) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if stop_now {
|
if stop_now {
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,8 @@ pub struct SizeInfo {
|
||||||
pub files: u64,
|
pub files: u64,
|
||||||
pub dirs: u64,
|
pub dirs: u64,
|
||||||
pub unreadable: u32,
|
pub unreadable: u32,
|
||||||
|
/// Newest last-modified seen while walking (unix seconds). `0` = unknown.
|
||||||
|
pub newest_write: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SizeInfo {
|
impl SizeInfo {
|
||||||
|
|
@ -56,6 +58,7 @@ impl SizeInfo {
|
||||||
self.files += other.files;
|
self.files += other.files;
|
||||||
self.dirs += other.dirs;
|
self.dirs += other.dirs;
|
||||||
self.unreadable += other.unreadable;
|
self.unreadable += other.unreadable;
|
||||||
|
self.newest_write = self.newest_write.max(other.newest_write);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// "12,431 files" style annotation for detail rows.
|
/// "12,431 files" style annotation for detail rows.
|
||||||
|
|
@ -207,6 +210,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
|
||||||
if meta.file_type().is_symlink() {
|
if meta.file_type().is_symlink() {
|
||||||
info.files += 1;
|
info.files += 1;
|
||||||
info.logical += Bytes(meta.len());
|
info.logical += Bytes(meta.len());
|
||||||
|
info.newest_write = mtime_secs(&meta);
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
match kind {
|
match kind {
|
||||||
|
|
@ -214,6 +218,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
|
||||||
info.files += 1;
|
info.files += 1;
|
||||||
info.logical += Bytes(meta.len());
|
info.logical += Bytes(meta.len());
|
||||||
info.allocated += Bytes(allocated_bytes(path, &meta));
|
info.allocated += Bytes(allocated_bytes(path, &meta));
|
||||||
|
info.newest_write = mtime_secs(&meta);
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
ItemKind::Path | ItemKind::Contents => {}
|
ItemKind::Path | ItemKind::Contents => {}
|
||||||
|
|
@ -222,6 +227,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
|
||||||
info.files += 1;
|
info.files += 1;
|
||||||
info.logical += Bytes(meta.len());
|
info.logical += Bytes(meta.len());
|
||||||
info.allocated += Bytes(allocated_bytes(path, &meta));
|
info.allocated += Bytes(allocated_bytes(path, &meta));
|
||||||
|
info.newest_write = mtime_secs(&meta);
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -251,6 +257,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
|
||||||
info.files += 1;
|
info.files += 1;
|
||||||
info.logical += Bytes(meta.len());
|
info.logical += Bytes(meta.len());
|
||||||
info.allocated += Bytes(allocated_bytes(entry.path(), &meta));
|
info.allocated += Bytes(allocated_bytes(entry.path(), &meta));
|
||||||
|
info.newest_write = info.newest_write.max(mtime_secs(&meta));
|
||||||
}
|
}
|
||||||
Err(_) => info.unreadable += 1,
|
Err(_) => info.unreadable += 1,
|
||||||
}
|
}
|
||||||
|
|
@ -261,6 +268,14 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
|
||||||
info
|
info
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Last-modified as unix seconds; 0 when the platform withholds it.
|
||||||
|
fn mtime_secs(meta: &Metadata) -> u64 {
|
||||||
|
meta.modified()
|
||||||
|
.ok()
|
||||||
|
.and_then(|when| when.duration_since(std::time::UNIX_EPOCH).ok())
|
||||||
|
.map_or(0, |age| age.as_secs())
|
||||||
|
}
|
||||||
|
|
||||||
/// Measure many paths in parallel. `progress` receives completed units.
|
/// Measure many paths in parallel. `progress` receives completed units.
|
||||||
/// `Path` for folders (and anything that should be removed recursively),
|
/// `Path` for folders (and anything that should be removed recursively),
|
||||||
/// `File` for plain files and symlinks.
|
/// `File` for plain files and symlinks.
|
||||||
|
|
@ -280,7 +295,7 @@ pub fn kind_of(path: &Path) -> crate::model::ItemKind {
|
||||||
pub fn measure_all(
|
pub fn measure_all(
|
||||||
targets: &[(PathBuf, ItemKind)],
|
targets: &[(PathBuf, ItemKind)],
|
||||||
cancel: &CancelToken,
|
cancel: &CancelToken,
|
||||||
on_unit: impl Fn(usize, &SizeInfo) + Send + Sync,
|
on_unit: impl Fn(usize, usize, &SizeInfo) + Send + Sync,
|
||||||
) -> Vec<SizeInfo> {
|
) -> Vec<SizeInfo> {
|
||||||
let pool = rayon::ThreadPoolBuilder::new()
|
let pool = rayon::ThreadPoolBuilder::new()
|
||||||
.num_threads(measure_threads())
|
.num_threads(measure_threads())
|
||||||
|
|
@ -297,14 +312,18 @@ pub fn measure_all(
|
||||||
let results: Vec<SizeInfo> = pool.install(|| {
|
let results: Vec<SizeInfo> = pool.install(|| {
|
||||||
targets
|
targets
|
||||||
.par_iter()
|
.par_iter()
|
||||||
.map(|(path, kind)| {
|
.enumerate()
|
||||||
|
.map(|(index, (path, kind))| {
|
||||||
if cancel.is_cancelled() {
|
if cancel.is_cancelled() {
|
||||||
cancelled.store(true, Ordering::Relaxed);
|
cancelled.store(true, Ordering::Relaxed);
|
||||||
return SizeInfo::default();
|
return SizeInfo::default();
|
||||||
}
|
}
|
||||||
let info = measure(path, *kind);
|
let info = measure(path, *kind);
|
||||||
let idx = done.fetch_add(1, Ordering::Relaxed) as usize;
|
let completed = done.fetch_add(1, Ordering::Relaxed) as usize + 1;
|
||||||
emit(idx, &info);
|
// (target index, completed count): index identifies the unit —
|
||||||
|
// callbacks arrive in completion order under rayon — while the
|
||||||
|
// count drives monotonic progress bars.
|
||||||
|
emit(index, completed, &info);
|
||||||
info
|
info
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
|
|
@ -369,6 +388,7 @@ pub fn remove_item_with(
|
||||||
files: 0,
|
files: 0,
|
||||||
dirs: 0,
|
dirs: 0,
|
||||||
unreadable: 0,
|
unreadable: 0,
|
||||||
|
newest_write: 0,
|
||||||
};
|
};
|
||||||
Ok(freed.on_disk().max(Bytes::ZERO))
|
Ok(freed.on_disk().max(Bytes::ZERO))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -165,6 +165,21 @@ pub struct CleanupItem {
|
||||||
/// stale or hand-edited item can never escape its sandbox.
|
/// stale or hand-edited item can never escape its sandbox.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub anchors: Vec<PathBuf>,
|
pub anchors: Vec<PathBuf>,
|
||||||
|
/// Seconds since the *most recent* last-write inside the item (Mole's
|
||||||
|
/// decision aid: 1.2 GB alone is not actionable, "untouched for 3 months"
|
||||||
|
/// is — and a low value flags a live, working directory). Unknown until
|
||||||
|
/// measurement; `None` for unreadable paths.
|
||||||
|
#[serde(default)]
|
||||||
|
pub last_write_secs: Option<u64>,
|
||||||
|
/// File count from measurement — lets the UI say "12 files · 5 folders".
|
||||||
|
#[serde(default)]
|
||||||
|
pub file_count: u64,
|
||||||
|
/// Machine-readable judgement tokens (Mole's evidence chain, made
|
||||||
|
/// visible): `lock:<file>`, `record:<file>`, `record-missing`,
|
||||||
|
/// `modified:<n>`, `git:ignored|untracked|none|tracked`, `age:<days>`,
|
||||||
|
/// `busy`. The UI renders each token as a ✓/! line in a detail panel.
|
||||||
|
#[serde(default)]
|
||||||
|
pub evidence: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CleanupItem {
|
impl CleanupItem {
|
||||||
|
|
@ -187,6 +202,9 @@ impl CleanupItem {
|
||||||
lock: lock_default(kind),
|
lock: lock_default(kind),
|
||||||
note: None,
|
note: None,
|
||||||
anchors: Vec::new(),
|
anchors: Vec::new(),
|
||||||
|
last_write_secs: None,
|
||||||
|
file_count: 0,
|
||||||
|
evidence: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -30,6 +30,12 @@ pub enum Event {
|
||||||
total: Bytes,
|
total: Bytes,
|
||||||
count: usize,
|
count: usize,
|
||||||
},
|
},
|
||||||
|
/// Cumulative measurement counters, streamed while sizes are computed
|
||||||
|
/// (Mole's "Scanning: 128,431 files · 38.2 GB" live status line).
|
||||||
|
Metered {
|
||||||
|
files: u64,
|
||||||
|
bytes: Bytes,
|
||||||
|
},
|
||||||
Deleted {
|
Deleted {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
freed: Bytes,
|
freed: Bytes,
|
||||||
|
|
|
||||||
|
|
@ -161,6 +161,13 @@ impl Settings {
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One raw whitelist line as a matcher — the shape the audit layer
|
||||||
|
/// needs when it must answer about a single pattern, not the list.
|
||||||
|
pub fn whitelist_matcher_for(raw: &str) -> Option<GlobMatcher> {
|
||||||
|
let expanded = paths::expand(raw).to_string_lossy().into_owned();
|
||||||
|
Glob::new(&expanded).ok().map(|g| g.compile_matcher())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool {
|
pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool {
|
||||||
if self.whitelist.is_empty() {
|
if self.whitelist.is_empty() {
|
||||||
return false;
|
return false;
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,7 @@ use std::path::{Path, PathBuf};
|
||||||
const CHILD_CAP: usize = 512;
|
const CHILD_CAP: usize = 512;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Node {
|
pub struct Node {
|
||||||
pub path: PathBuf,
|
pub path: PathBuf,
|
||||||
pub logical: Bytes,
|
pub logical: Bytes,
|
||||||
|
|
@ -196,9 +197,9 @@ pub fn expand(
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
progress.tick(0, Some(targets.len() as u64), None);
|
progress.tick(0, Some(targets.len() as u64), None);
|
||||||
let sizes = fs::measure_all(&targets, cancel, |index, _info| {
|
let sizes = fs::measure_all(&targets, cancel, |index, completed, _info| {
|
||||||
progress.tick(
|
progress.tick(
|
||||||
index as u64 + 1,
|
completed as u64,
|
||||||
Some(targets.len() as u64),
|
Some(targets.len() as u64),
|
||||||
targets.get(index).map(|(path, _)| path.clone()),
|
targets.get(index).map(|(path, _)| path.clone()),
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,190 @@
|
||||||
|
//! User-asset recognition — the Mole `app_protection` lesson for Windows.
|
||||||
|
//!
|
||||||
|
//! Some directories look exactly like caches but hold the user's own work:
|
||||||
|
//! chat files inside an IM data folder, PWA offline documents in a browser
|
||||||
|
//! profile's IndexedDB,输入法词库. A broad rule (or an eager user) must never
|
||||||
|
//! sweep them away, so they are pinned here: the scan lists them as locked,
|
||||||
|
//! visibly-explained rows, and the delete layer refuses them even when a
|
||||||
|
//! stale report still claims they are removable.
|
||||||
|
|
||||||
|
use squid_core::{Category, CleanupItem, ItemKind};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// Lower-cased path fragment → human reason. Matching is on the *normalised*
|
||||||
|
/// (lower-case, `/`→`\`) path so one table covers every drive letter and user.
|
||||||
|
const ASSET_MARKERS: &[(&str, &str)] = &[
|
||||||
|
(
|
||||||
|
"\\appdata\\roaming\\texact\\",
|
||||||
|
"腾讯 QQ 数据目录(聊天记录与文件)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"\\appdata\\roaming\\tencent\\",
|
||||||
|
"腾讯通用数据目录(聊天文件与配置)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"\\documents\\weixin files\\filestorage",
|
||||||
|
"微信聊天文件与下载文档",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"\\appdata\\roaming\\weixin\\filestorage",
|
||||||
|
"微信聊天文件与下载文档",
|
||||||
|
),
|
||||||
|
("\\appdata\\roaming\\txdnd\\", "腾讯游戏数据目录"),
|
||||||
|
("\\sogouexplorer\\", "搜狗输入法词库与用户习惯"),
|
||||||
|
(
|
||||||
|
"\\appdata\\roaming\\sogouinput\\",
|
||||||
|
"搜狗输入法词库与用户习惯",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Browser profile storage that holds PWA / offline web app documents —
|
||||||
|
/// Mole's `PROTECTED_SW_DOMAINS` equivalent. An `IndexedDB` folder inside a
|
||||||
|
/// Chromium-family browser profile is user work data (Figma / 剪映网页版 save
|
||||||
|
/// there), unlike `Cache` which is pure rebuildable bytes.
|
||||||
|
const CHROMIUM_PROFILE_MARKERS: &[&str] = &[
|
||||||
|
"\\microsoft\\edge\\user data\\",
|
||||||
|
"\\google\\chrome\\user data\\",
|
||||||
|
"\\chromium\\application\\user data\\",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn normalise(path: &Path) -> String {
|
||||||
|
path.to_string_lossy().to_lowercase().replace('/', "\\")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why this path is untouchable user property, if it is. The note lands in
|
||||||
|
/// the UI lock chip's explanation, mirroring 电脑管家's "创建者" honesty.
|
||||||
|
pub fn asset_reason(path: &Path) -> Option<&'static str> {
|
||||||
|
let lower = normalise(path);
|
||||||
|
// Deeper profile sub-paths (…\IndexedDB\foo) stay protected too: match
|
||||||
|
// the marker as a path prefix at a separator boundary.
|
||||||
|
if lower.contains("\\indexeddb")
|
||||||
|
&& CHROMIUM_PROFILE_MARKERS
|
||||||
|
.iter()
|
||||||
|
.any(|marker| lower.starts_with(marker) || lower.contains(marker))
|
||||||
|
{
|
||||||
|
return Some("可能含离线应用数据(Figma / 剪映网页版等工作文件)");
|
||||||
|
}
|
||||||
|
ASSET_MARKERS
|
||||||
|
.iter()
|
||||||
|
.find(|(marker, _)| segment_match(&lower, marker))
|
||||||
|
.map(|(_, reason)| *reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when `marker` appears inside `lower` at path segment boundaries.
|
||||||
|
/// Markers ending with a separator carry their own trailing boundary, so
|
||||||
|
/// `TencentGame\cache` must not match `\tencent\`.
|
||||||
|
fn segment_match(lower: &str, marker: &str) -> bool {
|
||||||
|
if marker.ends_with('\\') {
|
||||||
|
return lower.contains(marker);
|
||||||
|
}
|
||||||
|
lower.match_indices(marker).any(|(index, _)| {
|
||||||
|
// A marker that opens with `\` carries its own left boundary; a bare
|
||||||
|
// marker needs a separator (or drive colon) before it.
|
||||||
|
let before_ok = index == 0
|
||||||
|
|| marker.starts_with('\\')
|
||||||
|
|| matches!(lower.as_bytes()[index - 1], b'\\' | b':');
|
||||||
|
let after = index + marker.len();
|
||||||
|
let after_ok = lower.len() == after || lower.as_bytes().get(after) == Some(&b'\\');
|
||||||
|
before_ok && after_ok
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asset rows to surface in the 空间清理 list — existence checked, one row
|
||||||
|
/// per top-level asset. Rows anchor at their own parent: they are display
|
||||||
|
/// only (locked), and anchoring at the folder itself would make
|
||||||
|
/// `block_reason` deny the row's own deletion check.
|
||||||
|
pub fn known_asset_rows() -> Vec<CleanupItem> {
|
||||||
|
const SPECS: [(&str, &str); 6] = [
|
||||||
|
(
|
||||||
|
r"AppData\Roaming\Tencent",
|
||||||
|
"腾讯(QQ/微信旧版)数据目录(聊天记录与文件)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
r"Documents\WeChat Files",
|
||||||
|
"微信聊天文件与下载文档(旧版目录)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
r"Documents\Weixin Files\FileStorage",
|
||||||
|
"微信聊天文件与下载文档",
|
||||||
|
),
|
||||||
|
(r"AppData\Roaming\SogouInput", "搜狗输入法词库与用户习惯"),
|
||||||
|
(
|
||||||
|
r"AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB",
|
||||||
|
"可能含离线应用数据(Figma / 剪映网页版等工作文件)",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
r"AppData\Local\Google\Chrome\User Data\Default\IndexedDB",
|
||||||
|
"可能含离线应用数据(Figma / 剪映网页版等工作文件)",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let Ok(home) = std::env::var("USERPROFILE") else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let home = Path::new(&home);
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for (tail, reason) in SPECS {
|
||||||
|
let path = home.join(tail);
|
||||||
|
if !path.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let label = format!("🔒 {}", asset_label(&path));
|
||||||
|
let parent = path
|
||||||
|
.parent()
|
||||||
|
.map(|dir| dir.to_path_buf())
|
||||||
|
.unwrap_or_else(|| path.clone());
|
||||||
|
let item = CleanupItem::new(path, ItemKind::Path, Category::AppCaches, label)
|
||||||
|
.with_rule("user-assets")
|
||||||
|
.with_anchors(std::iter::once(parent))
|
||||||
|
.locked(squid_core::LockReason::Protected)
|
||||||
|
.with_note(reason);
|
||||||
|
rows.push(item);
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
fn asset_label(path: &Path) -> String {
|
||||||
|
let text = squid_core::paths::pretty(path);
|
||||||
|
text.rsplit(['\\', '/'])
|
||||||
|
.next()
|
||||||
|
.filter(|leaf| !leaf.is_empty())
|
||||||
|
.unwrap_or(&text)
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn im_data_dirs_refuse_deletion_with_a_reason() {
|
||||||
|
let path = PathBuf::from(r"C:\Users\me\AppData\Roaming\Tencent\WeChat\111\msg");
|
||||||
|
let reason = asset_reason(&path).expect("QQ tree must be protected");
|
||||||
|
assert!(reason.contains("聊天"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wechat_file_storage_is_protected_but_cache_paths_are_not() {
|
||||||
|
let storage = PathBuf::from(r"D:\Users\me\Documents\Weixin Files\FileStorage\File\2026-01");
|
||||||
|
assert!(asset_reason(&storage).is_some());
|
||||||
|
let edge_cache =
|
||||||
|
PathBuf::from(r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\Cache");
|
||||||
|
assert!(asset_reason(&edge_cache).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_indexeddb_counts_as_offline_app_data() {
|
||||||
|
let pwa = PathBuf::from(
|
||||||
|
r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB\figma_0.indexeddb.leveldb",
|
||||||
|
);
|
||||||
|
let reason = asset_reason(&pwa).expect("PWA data must be protected");
|
||||||
|
assert!(reason.contains("离线应用"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn markers_match_only_at_segment_boundaries() {
|
||||||
|
// A folder that merely *starts* with the marker text is not the asset.
|
||||||
|
let sneaky = PathBuf::from(r"C:\Users\me\AppData\Roaming\TencentGame\cache");
|
||||||
|
assert!(asset_reason(&sneaky).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -172,6 +172,20 @@ pub fn scan(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// User-asset rows (B4): pinned directories shown as locked, explained
|
||||||
|
// rows so "why can't I clean my WeChat files?" never becomes a mystery.
|
||||||
|
let assets_wanted =
|
||||||
|
options.categories.is_empty() || options.categories.contains(&Category::AppCaches);
|
||||||
|
if assets_wanted {
|
||||||
|
for item in crate::assets::known_asset_rows() {
|
||||||
|
if seen.contains_key(&item.path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.insert(item.path.clone(), report.items.len());
|
||||||
|
report.items.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !options.fast {
|
if !options.fast {
|
||||||
measure(engine, &mut report, progress, cancel)?;
|
measure(engine, &mut report, progress, cancel)?;
|
||||||
}
|
}
|
||||||
|
|
@ -201,7 +215,7 @@ fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec<PreparedRule>
|
||||||
rules.into_iter().map(PreparedRule::new).collect()
|
rules.into_iter().map(PreparedRule::new).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
|
pub fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
|
||||||
if rule.skip_if_running.is_empty() {
|
if rule.skip_if_running.is_empty() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
@ -334,15 +348,42 @@ fn measure(
|
||||||
.iter()
|
.iter()
|
||||||
.map(|item| (item.path.clone(), item.kind))
|
.map(|item| (item.path.clone(), item.kind))
|
||||||
.collect();
|
.collect();
|
||||||
progress.tick(0, Some(targets.len() as u64), None);
|
let total = targets.len() as u64;
|
||||||
|
progress.tick(0, Some(total), None);
|
||||||
|
|
||||||
let results: Vec<squid_core::fs::SizeInfo> = measure_all(&targets, cancel, |index, _info| {
|
// Cumulative counters for the live status line; the callback runs on
|
||||||
progress.tick(
|
// rayon worker threads, hence the mutex. Emissions are throttled to
|
||||||
index as u64 + 1,
|
// ~10/s so the IPC stays a whisper while the walk screams.
|
||||||
Some(targets.len() as u64),
|
let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now()));
|
||||||
targets.get(index).map(|(path, _)| path.clone()),
|
let results: Vec<squid_core::fs::SizeInfo> =
|
||||||
);
|
measure_all(&targets, cancel, |index, completed, info| {
|
||||||
});
|
let emit_line = {
|
||||||
|
let mut guard = meter
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
guard.0 += info.files;
|
||||||
|
guard.1 += info.on_disk().as_u64();
|
||||||
|
if completed as u64 == total
|
||||||
|
|| guard.2.elapsed() >= std::time::Duration::from_millis(90)
|
||||||
|
{
|
||||||
|
guard.2 = std::time::Instant::now();
|
||||||
|
Some((guard.0, guard.1))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some((files, bytes)) = emit_line {
|
||||||
|
progress.publish(Event::Metered {
|
||||||
|
files,
|
||||||
|
bytes: Bytes(bytes),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
progress.tick(
|
||||||
|
completed as u64,
|
||||||
|
Some(total),
|
||||||
|
targets.get(index).map(|(path, _)| path.clone()),
|
||||||
|
);
|
||||||
|
});
|
||||||
if results.len() != report.items.len() {
|
if results.len() != report.items.len() {
|
||||||
return Err(SquidError::Other(
|
return Err(SquidError::Other(
|
||||||
"measurement returned an unexpected number of results".into(),
|
"measurement returned an unexpected number of results".into(),
|
||||||
|
|
@ -351,6 +392,17 @@ fn measure(
|
||||||
for (item, info) in report.items.iter_mut().zip(results) {
|
for (item, info) in report.items.iter_mut().zip(results) {
|
||||||
item.size = info.logical;
|
item.size = info.logical;
|
||||||
item.allocated = info.allocated;
|
item.allocated = info.allocated;
|
||||||
|
item.file_count = info.files;
|
||||||
|
// "Untouched for X" is the actionable half of a size figure; derived
|
||||||
|
// from the newest last-write seen during the walk we just did.
|
||||||
|
item.last_write_secs = if info.newest_write == 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_or(0, |since| since.as_secs());
|
||||||
|
Some(now.saturating_sub(info.newest_write))
|
||||||
|
};
|
||||||
if info.unreadable > 0 && item.note.is_none() {
|
if info.unreadable > 0 && item.note.is_none() {
|
||||||
item.note = Some(format!("{} entries unreadable", info.unreadable));
|
item.note = Some(format!("{} entries unreadable", info.unreadable));
|
||||||
} else if info.files > 0 && item.note.is_none() {
|
} else if info.files > 0 && item.note.is_none() {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,197 @@
|
||||||
|
//! Hidden-space insights (Mole's `cmd/analyze` overview idiom).
|
||||||
|
//!
|
||||||
|
//! The disk analyzer answers "what is big"; this answers "what is big *and*
|
||||||
|
//! actionable" — curated Windows space hogs with a one-line explanation and
|
||||||
|
//! the action that actually frees them. Existence-gated: a row appears only
|
||||||
|
//! when the underlying path (or state) is really on this machine.
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use squid_core::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Insight {
|
||||||
|
/// Stable id for the UI (icon/translation lookup).
|
||||||
|
pub id: String,
|
||||||
|
pub title: String,
|
||||||
|
pub path: String,
|
||||||
|
pub size: u64,
|
||||||
|
/// "cleanable" — 空间清理 covers it; "command" — needs the given command;
|
||||||
|
/// "external" — system tool territory; "info" — informational.
|
||||||
|
pub action: String,
|
||||||
|
/// Command to run (elevated) when action == "command".
|
||||||
|
pub command: Option<String>,
|
||||||
|
pub hint: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn home() -> Option<PathBuf> {
|
||||||
|
std::env::var("USERPROFILE")
|
||||||
|
.ok()
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.filter(|path| path.is_dir())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dir_size(path: &Path) -> u64 {
|
||||||
|
if !path.is_dir() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
fs::measure(path, squid_core::ItemKind::Path)
|
||||||
|
.on_disk()
|
||||||
|
.as_u64()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_size(path: &Path) -> u64 {
|
||||||
|
std::fs::metadata(path).map_or(0, |meta| meta.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All insights that currently exist on this machine, biggest-effect first
|
||||||
|
/// ordering is left to the UI.
|
||||||
|
pub fn collect() -> Vec<Insight> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let Some(home) = home() else {
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
|
||||||
|
let system = PathBuf::from(system);
|
||||||
|
|
||||||
|
// 1. Windows Update download cache — the classic 5-20 GB surprise.
|
||||||
|
let updates = system.join(r"SoftwareDistribution\Download");
|
||||||
|
let size = dir_size(&updates);
|
||||||
|
if size > 256 * 1024 * 1024 {
|
||||||
|
out.push(Insight {
|
||||||
|
id: "update-cache".into(),
|
||||||
|
title: "Windows 更新缓存".into(),
|
||||||
|
path: updates.display().to_string(),
|
||||||
|
size,
|
||||||
|
action: "cleanable".into(),
|
||||||
|
command: None,
|
||||||
|
hint: "已安装的更新包,Windows 需要时会重新下载;空间清理的「系统垃圾」覆盖此目录"
|
||||||
|
.into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Hibernation file — freed by turning hibernation off.
|
||||||
|
let hiber = system.join("..\\hiberfil.sys");
|
||||||
|
let size = file_size(&hiber);
|
||||||
|
if size > 0 {
|
||||||
|
out.push(Insight {
|
||||||
|
id: "hiberfil".into(),
|
||||||
|
title: "休眠文件 hiberfil.sys".into(),
|
||||||
|
path: hiber.display().to_string(),
|
||||||
|
size,
|
||||||
|
action: "command".into(),
|
||||||
|
command: Some("powercfg /h off".into()),
|
||||||
|
hint: "关闭休眠后系统自动删除;睡眠不受影响".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Pagefile — visible but rarely worth touching; info only.
|
||||||
|
let page = system.join("..\\pagefile.sys");
|
||||||
|
let size = file_size(&page);
|
||||||
|
if size > 0 {
|
||||||
|
out.push(Insight {
|
||||||
|
id: "pagefile".into(),
|
||||||
|
title: "虚拟内存 pagefile.sys".into(),
|
||||||
|
path: page.display().to_string(),
|
||||||
|
size,
|
||||||
|
action: "info".into(),
|
||||||
|
command: None,
|
||||||
|
hint: "系统正在使用的虚拟内存,不建议手动删除;可在系统设置改到别的盘".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Component store (WinSxS) — needs DISM, never raw deletion.
|
||||||
|
// Walking 100k+ files just to print a number is not worth it here;
|
||||||
|
// the UI shows "several GB" and the DISM command does the rest.
|
||||||
|
let winsxs = system.join("WinSxS");
|
||||||
|
if winsxs.is_dir() {
|
||||||
|
out.push(Insight {
|
||||||
|
id: "winsxs".into(),
|
||||||
|
title: "组件存储 WinSxS".into(),
|
||||||
|
path: winsxs.display().to_string(),
|
||||||
|
size: 0,
|
||||||
|
action: "command".into(),
|
||||||
|
command: Some("Dism.exe /online /Cleanup-Image /StartComponentCleanup".into()),
|
||||||
|
hint: "系统组件仓库,通常 5~10 GB;只能由 DISM 收缩,直接删会破坏系统".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Phone backups (Apple MobileSync / third-party Android tools).
|
||||||
|
for (tail, title) in [
|
||||||
|
(r"Apple\MobileSync\Backup", "iPhone 备份"),
|
||||||
|
(r"Apple Computer\MobileSync\Backup", "iPhone 备份"),
|
||||||
|
] {
|
||||||
|
let backups = home.join(tail);
|
||||||
|
let size = dir_size(&backups);
|
||||||
|
if size > 256 * 1024 * 1024 {
|
||||||
|
out.push(Insight {
|
||||||
|
id: "phone-backup".into(),
|
||||||
|
title: title.into(),
|
||||||
|
path: backups.display().to_string(),
|
||||||
|
size,
|
||||||
|
action: "external".into(),
|
||||||
|
command: None,
|
||||||
|
hint: "整机备份体积大;确认 iCloud 或新备份完成后,在 iTunes/Finder 里删除旧备份"
|
||||||
|
.into(),
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Downloads older than 90 days (Mole's "Old Downloads" insight).
|
||||||
|
let downloads = home.join("Downloads");
|
||||||
|
if downloads.is_dir() {
|
||||||
|
let cutoff = std::time::SystemTime::now() - std::time::Duration::from_secs(90 * 24 * 3600);
|
||||||
|
let mut size = 0u64;
|
||||||
|
let mut stale = 0usize;
|
||||||
|
if let Ok(entries) = std::fs::read_dir(&downloads) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let meta = match entry.metadata() {
|
||||||
|
Ok(meta) => meta,
|
||||||
|
Err(_) => continue,
|
||||||
|
};
|
||||||
|
let modified = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
|
||||||
|
if modified < cutoff {
|
||||||
|
size += if meta.is_dir() {
|
||||||
|
dir_size(&entry.path())
|
||||||
|
} else {
|
||||||
|
meta.len()
|
||||||
|
};
|
||||||
|
stale += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if size > 256 * 1024 * 1024 {
|
||||||
|
out.push(Insight {
|
||||||
|
id: "old-downloads".into(),
|
||||||
|
title: "下载文件夹(90 天以上)".into(),
|
||||||
|
path: downloads.display().to_string(),
|
||||||
|
size,
|
||||||
|
action: "external".into(),
|
||||||
|
command: None,
|
||||||
|
hint: format!("{stale} 个条目三个月没动过;确认不再需要后手动清理"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.sort_by_key(|row| std::cmp::Reverse(row.size));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collect_never_panics_on_a_live_machine() {
|
||||||
|
// Pure smoke: whatever exists, ids are unique and sizes sane.
|
||||||
|
let rows = collect();
|
||||||
|
for (index, row) in rows.iter().enumerate() {
|
||||||
|
assert!(!row.id.is_empty());
|
||||||
|
assert!(!rows[..index]
|
||||||
|
.iter()
|
||||||
|
.any(|earlier| earlier.id == row.id && row.id != "phone-backup"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -12,15 +12,17 @@
|
||||||
//! and the safety net impossible to bypass.
|
//! and the safety net impossible to bypass.
|
||||||
|
|
||||||
pub mod analyze;
|
pub mod analyze;
|
||||||
|
pub mod assets;
|
||||||
pub mod clean;
|
pub mod clean;
|
||||||
pub mod delete;
|
pub mod delete;
|
||||||
|
pub mod insights;
|
||||||
pub mod purge;
|
pub mod purge;
|
||||||
pub mod uninstall;
|
pub mod uninstall;
|
||||||
pub mod updates;
|
pub mod updates;
|
||||||
|
|
||||||
use globset::GlobMatcher;
|
use globset::GlobMatcher;
|
||||||
use squid_core::settings::Settings;
|
use squid_core::settings::Settings;
|
||||||
use squid_core::{CleanupItem, SafetyPolicy};
|
use squid_core::{CleanupItem, SafetyPolicy, ScanReport};
|
||||||
use squid_platform::Platform;
|
use squid_platform::Platform;
|
||||||
use squid_rules::RuleSet;
|
use squid_rules::RuleSet;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
@ -121,6 +123,13 @@ impl Engine {
|
||||||
/// Why this item cannot be deleted, if it cannot. Rules pass the anchor they
|
/// Why this item cannot be deleted, if it cannot. Rules pass the anchor they
|
||||||
/// declared; everything else falls back to the default anchors.
|
/// declared; everything else falls back to the default anchors.
|
||||||
pub fn block_reason(&self, item: &CleanupItem) -> Option<String> {
|
pub fn block_reason(&self, item: &CleanupItem) -> Option<String> {
|
||||||
|
// Mole's lesson: some directories *look* like caches but hold the
|
||||||
|
// user's own work — chat files, PWA offline data, IME dictionaries.
|
||||||
|
// They are refused even when a broad rule matched them, with the
|
||||||
|
// reason shown verbatim in the UI lock chip.
|
||||||
|
if let Some(reason) = crate::assets::asset_reason(&item.path) {
|
||||||
|
return Some(reason.to_string());
|
||||||
|
}
|
||||||
let anchors = if item.anchors.is_empty() {
|
let anchors = if item.anchors.is_empty() {
|
||||||
squid_core::fs::default_anchors()
|
squid_core::fs::default_anchors()
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -131,6 +140,107 @@ impl Engine {
|
||||||
}
|
}
|
||||||
self.safety.denies(&item.path, &anchors)
|
self.safety.denies(&item.path, &anchors)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Mole's "re-verify at the last second" made visible: re-run every
|
||||||
|
/// deletion gate against the *current* item set and report what changed
|
||||||
|
/// since the scan. The confirm dialog shows the summary, so surprises
|
||||||
|
/// ("your app just started, we dropped 3 items") appear before the run,
|
||||||
|
/// not inside the results.
|
||||||
|
pub fn preflight(&self, report: &ScanReport, indexes: &[usize]) -> Preflight {
|
||||||
|
let running = self.platform().running_executables();
|
||||||
|
let mut out = Preflight {
|
||||||
|
checked: indexes.len(),
|
||||||
|
blocked: Vec::new(),
|
||||||
|
};
|
||||||
|
for &index in indexes {
|
||||||
|
let Some(item) = report.items.get(index) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if item.lock.is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(reason) = self.block_reason(item) {
|
||||||
|
out.blocked.push((item.display_path(), reason));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(path) = gone_path(item) {
|
||||||
|
out.blocked.push((
|
||||||
|
item.display_path(),
|
||||||
|
format!("{} 已不存在", squid_core::paths::pretty(&path)),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Apps started since the scan: re-check running conflicts per rule.
|
||||||
|
for (index, item) in report.items.iter().enumerate() {
|
||||||
|
if item.lock.is_some() || !indexes.contains(&index) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(rule) = self
|
||||||
|
.rules()
|
||||||
|
.rules()
|
||||||
|
.iter()
|
||||||
|
.find(|rule| rule.id == item.rule_id)
|
||||||
|
{
|
||||||
|
if let Some(conflict) = crate::clean::rule_running_conflict(rule, &running) {
|
||||||
|
if !out
|
||||||
|
.blocked
|
||||||
|
.iter()
|
||||||
|
.any(|(path, _)| *path == item.display_path())
|
||||||
|
{
|
||||||
|
out.blocked.push((item.display_path(), conflict));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which whitelist patterns actually *do something* (Mole's #458: a
|
||||||
|
/// protection line nobody ever hits is a fake protection). A pattern is
|
||||||
|
/// "live" when it matches a path the current rule set finds on this
|
||||||
|
/// machine — the user learns their glob protects a real thing, or that
|
||||||
|
/// it protects nothing at all.
|
||||||
|
pub fn audit_whitelist(&self) -> Vec<(String, bool)> {
|
||||||
|
let known: Vec<std::path::PathBuf> = self
|
||||||
|
.rules()
|
||||||
|
.rules()
|
||||||
|
.iter()
|
||||||
|
.filter(|rule| rule.applies_to_current_os())
|
||||||
|
.flat_map(|rule| {
|
||||||
|
squid_rules::PreparedRule::new((*rule).clone())
|
||||||
|
.matches()
|
||||||
|
.into_iter()
|
||||||
|
.map(|matched| matched.path)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
// Same expansion the delete layer uses (settings.whitelist_matchers
|
||||||
|
// shape), rebuilt per pattern so an invalid line cannot shift the
|
||||||
|
// index pairing — the audit answers "does THIS pattern protect
|
||||||
|
// anything".
|
||||||
|
self.settings
|
||||||
|
.whitelist
|
||||||
|
.iter()
|
||||||
|
.map(|pattern| {
|
||||||
|
let live = Settings::whitelist_matcher_for(pattern).is_some_and(|matcher| {
|
||||||
|
known.iter().any(|path| matcher.is_match(path.as_path()))
|
||||||
|
});
|
||||||
|
(pattern.clone(), live)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of [`Engine::preflight`].
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct Preflight {
|
||||||
|
pub checked: usize,
|
||||||
|
/// (display path, reason) for items that can no longer be deleted.
|
||||||
|
pub blocked: Vec<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gone_path(item: &squid_core::CleanupItem) -> Option<std::path::PathBuf> {
|
||||||
|
(!item.path.exists() && !std::fs::symlink_metadata(&item.path).is_ok())
|
||||||
|
.then(|| item.path.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// True when the process may touch system-owned paths.
|
/// True when the process may touch system-owned paths.
|
||||||
|
|
|
||||||
|
|
@ -222,11 +222,13 @@ pub fn scan(
|
||||||
);
|
);
|
||||||
let mut item = item_for(candidate);
|
let mut item = item_for(candidate);
|
||||||
|
|
||||||
|
// Evidence chain (B3): remember the git verdict + project root + age
|
||||||
|
// while checking, then attach machine tokens for the UI panel.
|
||||||
|
let evidence_project =
|
||||||
|
project_with_git(&candidate.path).unwrap_or_else(|| candidate.project.clone());
|
||||||
|
let evidence_age = age_days(&candidate.path);
|
||||||
if !options.force {
|
if !options.force {
|
||||||
let project_root = match project_with_git(&candidate.path) {
|
let project_root = evidence_project.clone();
|
||||||
Some(dir) => dir,
|
|
||||||
None => candidate.project.clone(),
|
|
||||||
};
|
|
||||||
let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) {
|
let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) {
|
||||||
Some((_, state)) => *state,
|
Some((_, state)) => *state,
|
||||||
None => {
|
None => {
|
||||||
|
|
@ -237,14 +239,22 @@ pub fn scan(
|
||||||
};
|
};
|
||||||
match state {
|
match state {
|
||||||
GitState::Tracked => {
|
GitState::Tracked => {
|
||||||
|
item.evidence.push("git:tracked".into());
|
||||||
item = item
|
item = item
|
||||||
.locked(LockReason::Protected)
|
.locked(LockReason::Protected)
|
||||||
.with_note("tracked by git — pass --all to delete anyway");
|
.with_note("tracked by git — pass --all to delete anyway");
|
||||||
}
|
}
|
||||||
GitState::Ignored => item.note = Some("git-ignored build output".into()),
|
GitState::Ignored => {
|
||||||
GitState::Untracked => item.note = Some("untracked by git".into()),
|
item.evidence.push("git:ignored".into());
|
||||||
|
item.note = Some("git-ignored build output".into());
|
||||||
|
}
|
||||||
|
GitState::Untracked => {
|
||||||
|
item.evidence.push("git:untracked".into());
|
||||||
|
item.note = Some("untracked by git".into());
|
||||||
|
}
|
||||||
GitState::Unknown => {
|
GitState::Unknown => {
|
||||||
let age = age_days(&candidate.path);
|
item.evidence.push("git:none".into());
|
||||||
|
let age = evidence_age;
|
||||||
match age {
|
match age {
|
||||||
Some(age) if age >= min_age as f64 => {
|
Some(age) if age >= min_age as f64 => {
|
||||||
item.note = Some(format!("no git repo · {:.0} days old", age));
|
item.note = Some(format!("no git repo · {:.0} days old", age));
|
||||||
|
|
@ -288,6 +298,7 @@ pub fn scan(
|
||||||
.locked(LockReason::NotOwned)
|
.locked(LockReason::NotOwned)
|
||||||
.with_note("owned by another user");
|
.with_note("owned by another user");
|
||||||
}
|
}
|
||||||
|
collect_evidence(&mut item, &evidence_project, evidence_age);
|
||||||
report.items.push(item);
|
report.items.push(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -310,6 +321,77 @@ pub fn scan(
|
||||||
Ok(report)
|
Ok(report)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Mole's node_modules evidence chain, made visible (B3):
|
||||||
|
/// a lockfile proves the tree is *reinstallable*; the package manager's
|
||||||
|
/// install record inside the artefact proves nobody hand-edited it since —
|
||||||
|
/// any file newer than the record smells like patched code, so we count it.
|
||||||
|
/// Returns machine tokens for the UI detail panel; empty = not a node tree.
|
||||||
|
fn node_evidence(project: &Path, artifact: &Path) -> Vec<String> {
|
||||||
|
const LOCKS: [(&str, &str); 3] = [
|
||||||
|
("package-lock.json", ".package-lock.json"),
|
||||||
|
("pnpm-lock.yaml", ".modules.yaml"),
|
||||||
|
("yarn.lock", ".yarn-integrity"),
|
||||||
|
];
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let Some((lock, record)) = LOCKS.iter().find(|(lock, _)| project.join(lock).is_file()) else {
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
out.push(format!("lock:{lock}"));
|
||||||
|
let record_path = artifact.join(record);
|
||||||
|
let Ok(meta) = std::fs::metadata(&record_path) else {
|
||||||
|
out.push("record-missing".into());
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
out.push(format!("record:{record}"));
|
||||||
|
let Ok(stamp) = meta.modified() else {
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
let mut modified = 0u32;
|
||||||
|
let mut seen = 0u32;
|
||||||
|
for entry in walkdir::WalkDir::new(artifact)
|
||||||
|
.follow_links(false)
|
||||||
|
.max_depth(8)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(Result::ok)
|
||||||
|
{
|
||||||
|
if !entry.file_type().is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen += 1;
|
||||||
|
if entry
|
||||||
|
.metadata()
|
||||||
|
.ok()
|
||||||
|
.and_then(|file| file.modified().ok())
|
||||||
|
.is_some_and(|when| when > stamp)
|
||||||
|
{
|
||||||
|
modified += 1;
|
||||||
|
if modified > 50 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if seen >= 40_000 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(format!("modified:{modified}"));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Collect the evidence tokens for one candidate after its checks ran.
|
||||||
|
fn collect_evidence(item: &mut CleanupItem, project: &Path, age: Option<f64>) {
|
||||||
|
if let Some(age) = age {
|
||||||
|
item.evidence.push(format!("age:{}", age.floor() as u64));
|
||||||
|
}
|
||||||
|
let name = item
|
||||||
|
.path
|
||||||
|
.file_name()
|
||||||
|
.map(|name| name.to_string_lossy().to_lowercase())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if name == "node_modules" {
|
||||||
|
item.evidence.extend(node_evidence(project, &item.path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn item_for(candidate: &Candidate) -> CleanupItem {
|
fn item_for(candidate: &Candidate) -> CleanupItem {
|
||||||
let category = if candidate.name.eq_ignore_ascii_case("DerivedData") {
|
let category = if candidate.name.eq_ignore_ascii_case("DerivedData") {
|
||||||
Category::Developer
|
Category::Developer
|
||||||
|
|
@ -554,9 +636,31 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
progress.phase("measure", "measuring artefacts");
|
progress.phase("measure", "measuring artefacts");
|
||||||
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
|
let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now()));
|
||||||
|
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, info| {
|
||||||
|
let emit_line = {
|
||||||
|
let mut guard = meter
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||||
|
guard.0 += info.files;
|
||||||
|
guard.1 += info.on_disk().as_u64();
|
||||||
|
if completed as u64 == targets.len() as u64
|
||||||
|
|| guard.2.elapsed() >= std::time::Duration::from_millis(90)
|
||||||
|
{
|
||||||
|
guard.2 = std::time::Instant::now();
|
||||||
|
Some((guard.0, guard.1))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some((files, bytes)) = emit_line {
|
||||||
|
progress.publish(squid_core::progress::Event::Metered {
|
||||||
|
files,
|
||||||
|
bytes: Bytes(bytes),
|
||||||
|
});
|
||||||
|
}
|
||||||
progress.tick(
|
progress.tick(
|
||||||
index as u64 + 1,
|
completed as u64,
|
||||||
Some(targets.len() as u64),
|
Some(targets.len() as u64),
|
||||||
targets.get(index).map(|(path, _)| path.clone()),
|
targets.get(index).map(|(path, _)| path.clone()),
|
||||||
);
|
);
|
||||||
|
|
@ -564,6 +668,15 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
|
||||||
for (item, info) in report.items.iter_mut().zip(sizes) {
|
for (item, info) in report.items.iter_mut().zip(sizes) {
|
||||||
item.size = info.logical;
|
item.size = info.logical;
|
||||||
item.allocated = info.allocated;
|
item.allocated = info.allocated;
|
||||||
|
item.file_count = info.files;
|
||||||
|
item.last_write_secs = if info.newest_write == 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_or(0, |since| since.as_secs());
|
||||||
|
Some(now.saturating_sub(info.newest_write))
|
||||||
|
};
|
||||||
if info.unreadable > 0 {
|
if info.unreadable > 0 {
|
||||||
let suffix = format!("{} entries unreadable", info.unreadable);
|
let suffix = format!("{} entries unreadable", info.unreadable);
|
||||||
item.note = Some(match item.note.take() {
|
item.note = Some(match item.note.take() {
|
||||||
|
|
|
||||||
|
|
@ -248,9 +248,9 @@ fn measure(
|
||||||
.iter()
|
.iter()
|
||||||
.map(|item| (item.path.clone(), item.kind))
|
.map(|item| (item.path.clone(), item.kind))
|
||||||
.collect();
|
.collect();
|
||||||
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
|
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, _info| {
|
||||||
progress.tick(
|
progress.tick(
|
||||||
index as u64 + 1,
|
completed as u64,
|
||||||
Some(targets.len() as u64),
|
Some(targets.len() as u64),
|
||||||
targets.get(index).map(|(path, _)| path.clone()),
|
targets.get(index).map(|(path, _)| path.clone()),
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -266,21 +266,104 @@ mod windows {
|
||||||
list: &str,
|
list: &str,
|
||||||
value_name: &str,
|
value_name: &str,
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
) -> Result<(), String> {
|
) -> std::io::Result<()> {
|
||||||
let hive = RegKey::predef(if machine {
|
let hive = RegKey::predef(if machine {
|
||||||
HKEY_LOCAL_MACHINE
|
HKEY_LOCAL_MACHINE
|
||||||
} else {
|
} else {
|
||||||
HKEY_CURRENT_USER
|
HKEY_CURRENT_USER
|
||||||
});
|
});
|
||||||
let (key, _) = hive
|
// Minimal rights only: several security suites (and locked-down
|
||||||
.create_subkey(format!(r"{base}\Explorer\StartupApproved\{list}"))
|
// profiles) deny KEY_ALL_ACCESS-style opens on the startup trees even
|
||||||
.map_err(registry_error)?;
|
// for the key's own owner, which used to make every toggle fail.
|
||||||
|
let (key, _) = hive.create_subkey_with_flags(
|
||||||
|
format!(r"{base}\Explorer\StartupApproved\{list}"),
|
||||||
|
KEY_READ | KEY_WRITE,
|
||||||
|
)?;
|
||||||
let marker = winreg::RegValue {
|
let marker = winreg::RegValue {
|
||||||
bytes: approved_marker(enabled),
|
bytes: approved_marker(enabled),
|
||||||
vtype: RegType::REG_BINARY,
|
vtype: RegType::REG_BINARY,
|
||||||
};
|
};
|
||||||
key.set_raw_value(value_name, &marker)
|
key.set_raw_value(value_name, &marker)
|
||||||
.map_err(registry_error)
|
}
|
||||||
|
|
||||||
|
/// Task Manager's marker rendered for `reg.exe` (12 bytes, hex).
|
||||||
|
fn approved_marker_hex(enabled: bool) -> String {
|
||||||
|
let mut hex = String::from(if enabled { "02" } else { "03" });
|
||||||
|
hex.push_str(&"0".repeat(22));
|
||||||
|
hex
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Flip an approval marker, escalating through a one-shot UAC prompt when
|
||||||
|
/// the direct write is denied (machine-scope keys, protected hives). The
|
||||||
|
/// result is verified against the registry itself, so a cancelled prompt
|
||||||
|
/// reports failure instead of a silently dead switch.
|
||||||
|
fn flip_approved(
|
||||||
|
machine: bool,
|
||||||
|
base: &str,
|
||||||
|
list: &str,
|
||||||
|
value_name: &str,
|
||||||
|
enabled: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if let Err(why) = write_approved(machine, base, list, value_name, enabled) {
|
||||||
|
if why.kind() != std::io::ErrorKind::PermissionDenied {
|
||||||
|
return Err(registry_error(why));
|
||||||
|
}
|
||||||
|
let hive_label = if machine { "HKLM" } else { "HKCU" };
|
||||||
|
run_elevated(
|
||||||
|
"reg.exe",
|
||||||
|
&[
|
||||||
|
"add".to_string(),
|
||||||
|
format!(r"{hive_label}\{base}\Explorer\StartupApproved\{list}"),
|
||||||
|
"/v".to_string(),
|
||||||
|
value_name.to_string(),
|
||||||
|
"/t".to_string(),
|
||||||
|
"REG_BINARY".to_string(),
|
||||||
|
"/d".to_string(),
|
||||||
|
approved_marker_hex(enabled),
|
||||||
|
"/f".to_string(),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
let hive = RegKey::predef(if machine {
|
||||||
|
HKEY_LOCAL_MACHINE
|
||||||
|
} else {
|
||||||
|
HKEY_CURRENT_USER
|
||||||
|
});
|
||||||
|
if approved_enabled(&hive, base, list, value_name) != enabled {
|
||||||
|
return Err("提权写入后状态仍未改变".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-quote one argument for a PowerShell -ArgumentList list.
|
||||||
|
fn quote_ps(value: &str) -> String {
|
||||||
|
format!("'{}'", value.replace('\'', "''"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `program args…` elevated through `Start-Process -Verb RunAs`.
|
||||||
|
/// PowerShell's own exit code reports a cancelled or refused prompt.
|
||||||
|
fn run_elevated(program: &str, args: &[String]) -> Result<(), String> {
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
let arglist = args
|
||||||
|
.iter()
|
||||||
|
.map(|arg| quote_ps(arg))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
let script = format!(
|
||||||
|
"$ErrorActionPreference='Stop'; Start-Process -FilePath {} -ArgumentList {} -Verb RunAs -WindowStyle Hidden -Wait",
|
||||||
|
quote_ps(program),
|
||||||
|
arglist
|
||||||
|
);
|
||||||
|
let status = std::process::Command::new("powershell.exe")
|
||||||
|
.args(["-NoProfile", "-NonInteractive", "-Command", &script])
|
||||||
|
.creation_flags(0x0800_0000)
|
||||||
|
.status()
|
||||||
|
.map_err(|error| format!("无法启动提权助手:{error}"))?;
|
||||||
|
if status.success() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("管理员授权被取消,未做修改".to_string())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn display_name(command: &str) -> String {
|
fn display_name(command: &str) -> String {
|
||||||
|
|
@ -1455,7 +1538,7 @@ mod windows {
|
||||||
} else {
|
} else {
|
||||||
name.to_string()
|
name.to_string()
|
||||||
};
|
};
|
||||||
write_approved(machine, &base, list, &marker, enabled)
|
flip_approved(machine, &base, list, &marker, enabled)
|
||||||
}
|
}
|
||||||
"folder" => {
|
"folder" => {
|
||||||
let file = Path::new(rest)
|
let file = Path::new(rest)
|
||||||
|
|
@ -1463,7 +1546,7 @@ mod windows {
|
||||||
.map(|n| n.to_string_lossy().to_string())
|
.map(|n| n.to_string_lossy().to_string())
|
||||||
.ok_or_else(|| "启动文件夹项目路径无效".to_string())?;
|
.ok_or_else(|| "启动文件夹项目路径无效".to_string())?;
|
||||||
let machine = rest.contains("ProgramData");
|
let machine = rest.contains("ProgramData");
|
||||||
write_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled)
|
flip_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled)
|
||||||
}
|
}
|
||||||
"task" => {
|
"task" => {
|
||||||
use std::os::windows::process::CommandExt;
|
use std::os::windows::process::CommandExt;
|
||||||
|
|
@ -1478,23 +1561,79 @@ mod windows {
|
||||||
.output()
|
.output()
|
||||||
.map_err(|error| format!("无法调用 schtasks:{error}"))?;
|
.map_err(|error| format!("无法调用 schtasks:{error}"))?;
|
||||||
if output.status.success() {
|
if output.status.success() {
|
||||||
Ok(())
|
return Ok(());
|
||||||
} else {
|
}
|
||||||
Err(format!(
|
let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
|
||||||
|
// schtasks reports "task not ready", missing tasks, etc. —
|
||||||
|
// only a plain access denial justifies a UAC round-trip.
|
||||||
|
let denied = stderr.contains("access is denied")
|
||||||
|
|| stderr.contains("access denied")
|
||||||
|
|| stderr.contains("拒绝访问");
|
||||||
|
if !denied {
|
||||||
|
return Err(format!(
|
||||||
"计划任务修改失败:{}",
|
"计划任务修改失败:{}",
|
||||||
String::from_utf8_lossy(&output.stderr).trim()
|
String::from_utf8_lossy(&output.stderr).trim()
|
||||||
))
|
));
|
||||||
}
|
}
|
||||||
|
run_elevated(
|
||||||
|
"schtasks.exe",
|
||||||
|
&[
|
||||||
|
"/Change".to_string(),
|
||||||
|
"/TN".to_string(),
|
||||||
|
rest.to_string(),
|
||||||
|
if enabled { "/Enable" } else { "/Disable" }.to_string(),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
"svc" => {
|
"svc" => {
|
||||||
// 开 = Automatic(2),关 = Manual(3):保留按需启动能力,
|
// 开 = Automatic(2),关 = Manual(3):保留按需启动能力,
|
||||||
// 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。
|
// 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。
|
||||||
let key = RegKey::predef(HKEY_LOCAL_MACHINE)
|
let start = if enabled { 2u32 } else { 3u32 };
|
||||||
.open_subkey_with_flags(format!(r"{SERVICES_KEY}\{rest}"), KEY_READ | KEY_WRITE)
|
let key_path = format!(r"{SERVICES_KEY}\{rest}");
|
||||||
.map_err(registry_error)?;
|
let direct = (|| -> std::io::Result<()> {
|
||||||
key.set_value("Start", &(if enabled { 2u32 } else { 3u32 }))
|
let key = RegKey::predef(HKEY_LOCAL_MACHINE)
|
||||||
.map_err(registry_error)?;
|
.open_subkey_with_flags(&key_path, KEY_READ | KEY_WRITE)?;
|
||||||
let _ = service_control(rest, if enabled { "auto" } else { "demand" });
|
key.set_value("Start", &start)
|
||||||
|
})();
|
||||||
|
if let Err(why) = direct {
|
||||||
|
if why.kind() != std::io::ErrorKind::PermissionDenied {
|
||||||
|
return Err(registry_error(why));
|
||||||
|
}
|
||||||
|
run_elevated(
|
||||||
|
"reg.exe",
|
||||||
|
&[
|
||||||
|
"add".to_string(),
|
||||||
|
format!(r"HKLM\{key_path}"),
|
||||||
|
"/v".to_string(),
|
||||||
|
"Start".to_string(),
|
||||||
|
"/t".to_string(),
|
||||||
|
"REG_DWORD".to_string(),
|
||||||
|
"/d".to_string(),
|
||||||
|
start.to_string(),
|
||||||
|
"/f".to_string(),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
let live = RegKey::predef(HKEY_LOCAL_MACHINE)
|
||||||
|
.open_subkey_with_flags(&key_path, KEY_READ)
|
||||||
|
.map(|key| key.get_value::<u32, _>("Start").ok())
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
if live != Some(start) {
|
||||||
|
return Err("提权写入后服务状态仍未改变".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if service_control(rest, if enabled { "auto" } else { "demand" }).is_err() {
|
||||||
|
let _ = run_elevated(
|
||||||
|
"sc.exe",
|
||||||
|
&[
|
||||||
|
"config".to_string(),
|
||||||
|
rest.to_string(),
|
||||||
|
"start=".to_string(),
|
||||||
|
if enabled { "auto" } else { "demand" }.to_string(),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
_ => Err("未知的启动项来源".to_string()),
|
_ => Err("未知的启动项来源".to_string()),
|
||||||
|
|
@ -1913,9 +2052,56 @@ mod windows {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
clean_module_path, exe_from_command, friendly_program_name, has_cjk,
|
approved_enabled, clean_module_path, exe_from_command, friendly_program_name, has_cjk,
|
||||||
is_placeholder_label, module_folder_name, parse_csv_line, task_settings_enabled,
|
is_placeholder_label, module_folder_name, parse_csv_line, split_run_path,
|
||||||
|
task_settings_enabled, write_approved, CURRENT_VERSION,
|
||||||
};
|
};
|
||||||
|
use winreg::RegKey;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn toggle_round_trips_through_the_approved_marker() {
|
||||||
|
// The exact pair the UI toggle relies on: write_approved stores a
|
||||||
|
// marker, the rescan reads it back. If these ever drift, every
|
||||||
|
// startup switch silently snaps back — the "button is dead" bug.
|
||||||
|
let list = format!("squidTest{}", std::process::id());
|
||||||
|
let hive = RegKey::predef(winreg::enums::HKEY_CURRENT_USER);
|
||||||
|
let key_path = format!(r"{CURRENT_VERSION}\Explorer\StartupApproved\{list}");
|
||||||
|
for name in ["squid-off", "squid-on"] {
|
||||||
|
let want = name.ends_with("on");
|
||||||
|
if let Err(why) = write_approved(false, CURRENT_VERSION, &list, name, want) {
|
||||||
|
// Sandboxed CI runners deny registry writes; the marker
|
||||||
|
// round-trip cannot be proven here, so say so instead of
|
||||||
|
// failing a correct build.
|
||||||
|
eprintln!("skipping marker round-trip: registry write denied ({why})");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
approved_enabled(&hive, CURRENT_VERSION, &list, name),
|
||||||
|
want,
|
||||||
|
"{name} must read back as written"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let _ = hive.delete_subkey_all(&key_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn run_path_split_round_trips_hive_and_list() {
|
||||||
|
// set_startup_enabled re-derives (machine, base, list) from the
|
||||||
|
// id scan produced; a mismatch writes the marker to the wrong key
|
||||||
|
// and the rescan then shows the old state.
|
||||||
|
let wow_run = r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run".to_string();
|
||||||
|
let (machine, base, list, prefix32) = split_run_path("HKLM", &wow_run);
|
||||||
|
assert!(machine);
|
||||||
|
assert_eq!(list, "Run");
|
||||||
|
assert!(prefix32);
|
||||||
|
assert!(base.contains("WOW6432Node"));
|
||||||
|
let (machine, base, list, prefix32) =
|
||||||
|
split_run_path("HKCU", &format!(r"{CURRENT_VERSION}\RunOnce"));
|
||||||
|
assert!(!machine);
|
||||||
|
assert_eq!(list, "RunOnce");
|
||||||
|
assert!(!prefix32);
|
||||||
|
assert_eq!(base, CURRENT_VERSION);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn command_paths_survive_quotes_and_arguments() {
|
fn command_paths_survive_quotes_and_arguments() {
|
||||||
|
|
|
||||||
|
|
@ -889,6 +889,7 @@ impl App {
|
||||||
};
|
};
|
||||||
panel.buckets.insert(category, (total, count));
|
panel.buckets.insert(category, (total, count));
|
||||||
}
|
}
|
||||||
|
Event::Metered { .. } => {}
|
||||||
Event::Deleted { path, freed } => {
|
Event::Deleted { path, freed } => {
|
||||||
self.push_log(format!(
|
self.push_log(format!(
|
||||||
"removed {} ({})",
|
"removed {} ({})",
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,31 @@
|
||||||
Squid 0.1.10 更新说明
|
Squid 0.1.10 更新说明
|
||||||
|
|
||||||
新增
|
新增
|
||||||
|
- 空间清理全面对齐专业清理工具的扫描体验(借鉴 Mole):
|
||||||
|
· 扫描时实时显示「已统计 12.8 万个文件 · 38.2 GB」滚动计数,进度条在真正
|
||||||
|
完成前最多走到 99%,不再出现「满了但还在转」的错觉;
|
||||||
|
· 各分类不再干等:哪个分类先算完就先在扫描界面出现(项数 + 大小);
|
||||||
|
· 清理点与文件行显示「12 个月未使用」休眠标签(超过 90 天没再写入的绿色
|
||||||
|
标注),配合大小一起帮你决定删不删;
|
||||||
|
· node_modules 等项目产物新增「可删依据」面板:锁文件 / 安装记录 / 有无
|
||||||
|
手工修改 / Git 状态 / 目录年龄逐条列出,被手改过的目录会红色警示;
|
||||||
|
· 低风险清理(≤40 项、不含升级包、复核全部通过)不再弹窗,底部绿色
|
||||||
|
确认条一步完成(Esc 取消);含升级包或大批量仍走确认对话框,对话框内
|
||||||
|
新增「刚刚逐路径复核过 N 项」折叠面板,展示删除前的最后一轮锁 / 白名单
|
||||||
|
/ 应用运行 / 路径消失复核结果;
|
||||||
|
· 清理完成后新增「有 N 项本次未处理」分组页:按原因(应用正在运行 /
|
||||||
|
需要管理员 / 已消失 / 白名单 / 受保护)归类,每组给下一步操作按钮;
|
||||||
|
· 结果列表可一键「导出清单」,生成 Markdown 文件(含每一项路径、大小、
|
||||||
|
依据与受保护项),方便留档或反馈。
|
||||||
|
- 存储空间页新增「隐藏的吃空间大户」:Windows 更新缓存、休眠文件、页面文件、
|
||||||
|
WinSxS 组件库、手机备份、90 天前的下载,逐项给出大小与下一步(查看 /
|
||||||
|
复制释放命令);同页文件夹测量结果缓存 10 分钟,秒开时标注「缓存数据 ·
|
||||||
|
上次测量 X 分钟前」并可一键重新测量,删除文件后缓存自动作废。
|
||||||
|
- 微信 / QQ 聊天文件、浏览器离线应用数据(IndexedDB)、搜狗词库等「看起来像
|
||||||
|
缓存、实际是你的文件」的目录,现在会以待解锁行出现在扫描结果里并写明原因,
|
||||||
|
引擎在删除层也强制拒删。
|
||||||
|
- 设置 → 受保护的位置新增「消费审计」:每条白名单规则标注最近扫描是否命中,
|
||||||
|
从未命中的过期规则一眼可见。
|
||||||
- 清理新增「升级安装包」分类:找出应用升级完成后留在 AppData 里的安装包
|
- 清理新增「升级安装包」分类:找出应用升级完成后留在 AppData 里的安装包
|
||||||
(微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。
|
(微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。
|
||||||
只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件
|
只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件
|
||||||
|
|
@ -21,6 +46,10 @@ Squid 0.1.10 更新说明
|
||||||
开着时 Squid 全家 CPU 占用接近 0%。
|
开着时 Squid 全家 CPU 占用接近 0%。
|
||||||
|
|
||||||
修复
|
修复
|
||||||
|
- 权限管理:修复开机启动项开关点了没反应 / 立刻弹回的问题——所有启动项
|
||||||
|
(当前用户、所有用户、32 位、启动文件夹、服务、计划任务)统一改用最小
|
||||||
|
注册表权限写入,遇到「拒绝访问」自动发起一次系统管理员授权(UAC)后重试
|
||||||
|
并回读核实;开关失败时现在有红色气泡提示原因(此前只在页面顶部一闪而过)。
|
||||||
- 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题
|
- 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题
|
||||||
出现一次,子行文字与标题对齐)。
|
出现一次,子行文字与标题对齐)。
|
||||||
- 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有
|
- 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有
|
||||||
|
|
|
||||||
|
|
@ -1,2 +1,2 @@
|
||||||
046b0e2ad7e3a9dd8558d7ff673d5bd8b4d78c8337055847f7a789003cc31ef5 Squid-Setup-0.1.10-win-x64.exe
|
1ddd17bd66a982cfdfbf15e187c213ef005619b7f6fee16ffc72dce47f105705 Squid-Setup-0.1.10-win-x64.exe
|
||||||
587c70cc7bbbd48f29ee659baf86e30de16c3c13d9aa02c9c0b188f615d0027d Squid-0.1.10-portable-win-x64.zip
|
8e814c57ebb7fb6f887abfd2fd2290ad75ba0b8dc7e9694ff747fb530d19e59e Squid-0.1.10-portable-win-x64.zip
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
|
|
@ -35,6 +35,11 @@ pub struct AppState {
|
||||||
/// Last light snapshot, so the widget window and the main window polling
|
/// Last light snapshot, so the widget window and the main window polling
|
||||||
/// a beat apart share one refresh instead of paying for two.
|
/// a beat apart share one refresh instead of paying for two.
|
||||||
snapshot_cache: Mutex<Option<(Instant, squid_stats::SystemSnapshot)>>,
|
snapshot_cache: Mutex<Option<(Instant, squid_stats::SystemSnapshot)>>,
|
||||||
|
/// Mole-style size cache (A⑥): explored storage trees answered from
|
||||||
|
/// memory until a delete run bumps the epoch and invalidates them.
|
||||||
|
/// Stamp is wall-clock so the age survives nicely for UI copy.
|
||||||
|
storage_cache: Mutex<HashMap<String, (u64, std::time::SystemTime, analyze::Node)>>,
|
||||||
|
clean_epoch: std::sync::atomic::AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
|
|
@ -44,6 +49,16 @@ impl AppState {
|
||||||
.map_err(|_| "The application state is unavailable; restart Squid.".to_string())
|
.map_err(|_| "The application state is unavailable; restart Squid.".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn epoch(&self) -> u64 {
|
||||||
|
self.clean_epoch.load(std::sync::atomic::Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Any successful delete invalidates cached storage sizes (Mole bumps its
|
||||||
|
/// cache schema whenever deletion semantics change what totals mean).
|
||||||
|
fn invalidate_storage_cache(&self) {
|
||||||
|
self.clean_epoch.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
|
fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
|
||||||
if job_id.trim().is_empty() {
|
if job_id.trim().is_empty() {
|
||||||
return Err("A job identifier is required.".into());
|
return Err("A job identifier is required.".into());
|
||||||
|
|
@ -193,6 +208,17 @@ fn emit_progress(app: &AppHandle, job_id: &str, kind: &str, event: Event) {
|
||||||
subject: None,
|
subject: None,
|
||||||
freed: None,
|
freed: None,
|
||||||
},
|
},
|
||||||
|
Event::Metered { files, bytes } => ProgressView {
|
||||||
|
job_id: job_id.into(),
|
||||||
|
kind: kind.into(),
|
||||||
|
event: "metered".into(),
|
||||||
|
phase: None,
|
||||||
|
detail: None,
|
||||||
|
done: Some(files),
|
||||||
|
total: Some(bytes.as_u64()),
|
||||||
|
subject: None,
|
||||||
|
freed: None,
|
||||||
|
},
|
||||||
Event::Done(_) => return,
|
Event::Done(_) => return,
|
||||||
};
|
};
|
||||||
let _ = app.emit("squid://progress", payload);
|
let _ = app.emit("squid://progress", payload);
|
||||||
|
|
@ -213,6 +239,9 @@ pub struct CleanupItemView {
|
||||||
selected: bool,
|
selected: bool,
|
||||||
lock: Option<LockReason>,
|
lock: Option<LockReason>,
|
||||||
note: Option<String>,
|
note: Option<String>,
|
||||||
|
last_write_secs: Option<u64>,
|
||||||
|
file_count: u64,
|
||||||
|
evidence: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&CleanupItem> for CleanupItemView {
|
impl From<&CleanupItem> for CleanupItemView {
|
||||||
|
|
@ -230,6 +259,9 @@ impl From<&CleanupItem> for CleanupItemView {
|
||||||
selected: item.selected,
|
selected: item.selected,
|
||||||
lock: item.lock,
|
lock: item.lock,
|
||||||
note: item.note.clone(),
|
note: item.note.clone(),
|
||||||
|
last_write_secs: item.last_write_secs,
|
||||||
|
file_count: item.file_count,
|
||||||
|
evidence: item.evidence.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -508,6 +540,7 @@ pub async fn cleanup_delete(
|
||||||
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
|
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
|
||||||
scans.remove(&scan_id);
|
scans.remove(&scan_id);
|
||||||
}
|
}
|
||||||
|
app.state::<AppState>().invalidate_storage_cache();
|
||||||
Ok(DeleteResultView::from_outcome(outcome))
|
Ok(DeleteResultView::from_outcome(outcome))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -591,6 +624,7 @@ pub async fn purge_delete(
|
||||||
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
|
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
|
||||||
scans.remove(&scan_id);
|
scans.remove(&scan_id);
|
||||||
}
|
}
|
||||||
|
app.state::<AppState>().invalidate_storage_cache();
|
||||||
Ok(DeleteResultView::from_outcome(outcome))
|
Ok(DeleteResultView::from_outcome(outcome))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -759,9 +793,24 @@ pub async fn app_uninstall(
|
||||||
if let Ok(mut plans) = app.state::<AppState>().plans.lock() {
|
if let Ok(mut plans) = app.state::<AppState>().plans.lock() {
|
||||||
plans.remove(&plan_id);
|
plans.remove(&plan_id);
|
||||||
}
|
}
|
||||||
|
app.state::<AppState>().invalidate_storage_cache();
|
||||||
Ok(DeleteResultView::from_outcome(outcome))
|
Ok(DeleteResultView::from_outcome(outcome))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What `storage_explore` answers: the tree plus how fresh it is (A⑥).
|
||||||
|
/// `cached` = served from the in-memory size cache; `measuredAtMs` = age of
|
||||||
|
/// the measurement so the page can say "12 分钟前" honestly. `Node` itself
|
||||||
|
/// serializes camelCase, same as before for the frontend contract.
|
||||||
|
#[derive(Clone, serde::Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ExploreView {
|
||||||
|
node: Node,
|
||||||
|
cached: bool,
|
||||||
|
measured_at_ms: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const STORAGE_TTL: std::time::Duration = std::time::Duration::from_secs(600);
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn storage_explore(
|
pub async fn storage_explore(
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
|
|
@ -769,7 +818,8 @@ pub async fn storage_explore(
|
||||||
path: Option<String>,
|
path: Option<String>,
|
||||||
depth: Option<usize>,
|
depth: Option<usize>,
|
||||||
top: Option<usize>,
|
top: Option<usize>,
|
||||||
) -> Result<Node, String> {
|
force: Option<bool>,
|
||||||
|
) -> Result<ExploreView, String> {
|
||||||
let token = app.state::<AppState>().begin(&job_id)?;
|
let token = app.state::<AppState>().begin(&job_id)?;
|
||||||
let progress = Progress::new();
|
let progress = Progress::new();
|
||||||
let reporter =
|
let reporter =
|
||||||
|
|
@ -783,20 +833,114 @@ pub async fn storage_explore(
|
||||||
reporter.finish();
|
reporter.finish();
|
||||||
return Err(format!("{} is not a folder.", root.display()));
|
return Err(format!("{} is not a folder.", root.display()));
|
||||||
}
|
}
|
||||||
|
let depth = depth.unwrap_or(1).clamp(1, 3);
|
||||||
|
let top = top.unwrap_or(16);
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let key = format!("{}|{depth}|{top}", root.to_string_lossy().to_lowercase());
|
||||||
|
let epoch = state.epoch();
|
||||||
|
if !force.unwrap_or(false) {
|
||||||
|
if let Ok(cache) = state.storage_cache.lock() {
|
||||||
|
if let Some((cached_epoch, at, node)) = cache.get(&key) {
|
||||||
|
let age = std::time::SystemTime::now()
|
||||||
|
.duration_since(*at)
|
||||||
|
.unwrap_or_default();
|
||||||
|
let fresh = epoch == *cached_epoch && age < STORAGE_TTL;
|
||||||
|
if fresh {
|
||||||
|
app.state::<AppState>().finish(&job_id);
|
||||||
|
reporter.finish();
|
||||||
|
return Ok(ExploreView {
|
||||||
|
node: node.clone(),
|
||||||
|
cached: true,
|
||||||
|
measured_at_ms: Some(u64::try_from(age.as_millis()).unwrap_or(u64::MAX)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
let task = tauri::async_runtime::spawn_blocking(move || {
|
let task = tauri::async_runtime::spawn_blocking(move || {
|
||||||
analyze::explore(
|
analyze::explore(&root, depth, top, &token, &progress)
|
||||||
&root,
|
|
||||||
depth.unwrap_or(1).clamp(1, 3),
|
|
||||||
top.unwrap_or(16),
|
|
||||||
&token,
|
|
||||||
&progress,
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|error| format!("Storage analysis failed: {error}"))?;
|
.map_err(|error| format!("Storage analysis failed: {error}"))?;
|
||||||
reporter.finish();
|
reporter.finish();
|
||||||
app.state::<AppState>().finish(&job_id);
|
app.state::<AppState>().finish(&job_id);
|
||||||
task.map_err(|error| error.to_string())
|
let node = task.map_err(|error| error.to_string())?;
|
||||||
|
if let Ok(mut cache) = state.storage_cache.lock() {
|
||||||
|
// Tiny memory cap: the epoch clears everything after a delete run.
|
||||||
|
if cache.len() > 48 {
|
||||||
|
cache.clear();
|
||||||
|
}
|
||||||
|
cache.insert(key, (epoch, std::time::SystemTime::now(), node.clone()));
|
||||||
|
}
|
||||||
|
Ok(ExploreView {
|
||||||
|
node,
|
||||||
|
cached: false,
|
||||||
|
measured_at_ms: Some(0),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, serde::Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct InsightView {
|
||||||
|
id: String,
|
||||||
|
title: String,
|
||||||
|
path: String,
|
||||||
|
size: u64,
|
||||||
|
action: String,
|
||||||
|
command: Option<String>,
|
||||||
|
hint: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hidden-space insights for the storage page's curated section (A⑤).
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn storage_insights() -> Result<Vec<InsightView>, String> {
|
||||||
|
let rows = tauri::async_runtime::spawn_blocking(squid_engine::insights::collect)
|
||||||
|
.await
|
||||||
|
.map_err(|error| format!("Insight scan failed: {error}"))?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|row| InsightView {
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
path: row.path,
|
||||||
|
size: row.size,
|
||||||
|
action: row.action,
|
||||||
|
command: row.command,
|
||||||
|
hint: row.hint,
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mole-style last-second re-check surfaced before deletion (B1).
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn cleanup_preflight(
|
||||||
|
app: AppHandle,
|
||||||
|
scan_id: String,
|
||||||
|
selected: Vec<usize>,
|
||||||
|
) -> Result<serde_json::Value, String> {
|
||||||
|
let report = app
|
||||||
|
.state::<AppState>()
|
||||||
|
.scans
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "The scan cache is unavailable.".to_string())?
|
||||||
|
.get(&scan_id)
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "This scan has expired. Run it again.".to_string())?;
|
||||||
|
let view = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let engine = Engine::new();
|
||||||
|
let preflight = engine.preflight(&report, &selected);
|
||||||
|
serde_json::json!({
|
||||||
|
"checked": preflight.checked,
|
||||||
|
"blocked": preflight
|
||||||
|
.blocked
|
||||||
|
.into_iter()
|
||||||
|
.map(|(path, reason)| serde_json::json!({ "path": path, "reason": reason }))
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
Ok(view)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|
@ -864,6 +1008,34 @@ pub fn stop_process(app: AppHandle, process: ProcessSample) -> Result<(), String
|
||||||
sampler.stop(&process).map_err(|error| error.to_string())
|
sampler.stop(&process).map_err(|error| error.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Write a UTF-8 text file (B5 clean-list export; the UI picked the path
|
||||||
|
/// through the save dialog, so this is a plain, bounded write).
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn write_text_file(path: String, contents: String) -> Result<(), String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let target = paths::expand(&path);
|
||||||
|
std::fs::write(&target, contents.as_bytes())
|
||||||
|
.map_err(|error| format!("{}: {error}", target.display()))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// B2: which protection patterns actually hit something on this machine.
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn whitelist_audit() -> Result<serde_json::Value, String> {
|
||||||
|
let rows: Vec<serde_json::Value> = tauri::async_runtime::spawn_blocking(|| {
|
||||||
|
Engine::new()
|
||||||
|
.audit_whitelist()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(pattern, live)| serde_json::json!({ "pattern": pattern, "live": live }))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
Ok(serde_json::Value::Array(rows))
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn history_list(limit: Option<usize>) -> Vec<Session> {
|
pub fn history_list(limit: Option<usize>) -> Vec<Session> {
|
||||||
ledger::load_sessions(limit.unwrap_or(60).clamp(1, 500))
|
ledger::load_sessions(limit.unwrap_or(60).clamp(1, 500))
|
||||||
|
|
|
||||||
|
|
@ -122,12 +122,15 @@ pub fn run() {
|
||||||
app::cancel_job,
|
app::cancel_job,
|
||||||
app::cleanup_scan,
|
app::cleanup_scan,
|
||||||
app::cleanup_delete,
|
app::cleanup_delete,
|
||||||
|
app::cleanup_preflight,
|
||||||
app::purge_scan,
|
app::purge_scan,
|
||||||
app::purge_delete,
|
app::purge_delete,
|
||||||
app::apps_scan,
|
app::apps_scan,
|
||||||
app::app_plan,
|
app::app_plan,
|
||||||
app::app_uninstall,
|
app::app_uninstall,
|
||||||
app::storage_explore,
|
app::storage_explore,
|
||||||
|
app::storage_insights,
|
||||||
|
app::write_text_file,
|
||||||
app::storage_largest_files,
|
app::storage_largest_files,
|
||||||
app::system_snapshot,
|
app::system_snapshot,
|
||||||
app::stop_process,
|
app::stop_process,
|
||||||
|
|
@ -136,6 +139,7 @@ pub fn run() {
|
||||||
app::settings_save,
|
app::settings_save,
|
||||||
app::whitelist_add,
|
app::whitelist_add,
|
||||||
app::whitelist_remove,
|
app::whitelist_remove,
|
||||||
|
app::whitelist_audit,
|
||||||
app::reveal_path,
|
app::reveal_path,
|
||||||
app::open_trash,
|
app::open_trash,
|
||||||
permissions::permission_status,
|
permissions::permission_status,
|
||||||
|
|
|
||||||
|
|
@ -274,11 +274,18 @@ export function ProgressCard({
|
||||||
title,
|
title,
|
||||||
onCancel,
|
onCancel,
|
||||||
compact = false,
|
compact = false,
|
||||||
|
liveLine,
|
||||||
|
capAt99 = false,
|
||||||
}: {
|
}: {
|
||||||
progress: JobProgress | null;
|
progress: JobProgress | null;
|
||||||
title: string;
|
title: string;
|
||||||
onCancel?: () => void;
|
onCancel?: () => void;
|
||||||
compact?: boolean;
|
compact?: boolean;
|
||||||
|
/** "已统计 128,431 文件 · 38.2 GB" streamed side-band (A①). */
|
||||||
|
liveLine?: string | null;
|
||||||
|
/** Scans hold the bar at 99% until the final number lands — a full bar
|
||||||
|
* that is still working reads as a lie (Mole's cap discipline). */
|
||||||
|
capAt99?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const { t, lang } = useI18n();
|
const { t, lang } = useI18n();
|
||||||
const phase = useMemo(() => {
|
const phase = useMemo(() => {
|
||||||
|
|
@ -301,7 +308,9 @@ export function ProgressCard({
|
||||||
const denominator = progress?.total ?? 0;
|
const denominator = progress?.total ?? 0;
|
||||||
const done = progress?.done ?? 0;
|
const done = progress?.done ?? 0;
|
||||||
const ratio =
|
const ratio =
|
||||||
denominator > 0 ? Math.min(100, Math.max(0, (done / denominator) * 100)) : null;
|
denominator > 0
|
||||||
|
? Math.min(capAt99 ? 99 : 100, Math.max(0, (done / denominator) * 100))
|
||||||
|
: null;
|
||||||
const detail = progress?.detail || progress?.subject || "";
|
const detail = progress?.detail || progress?.subject || "";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -330,6 +339,11 @@ export function ProgressCard({
|
||||||
>
|
>
|
||||||
<span style={{ width: ratio === null ? undefined : `${ratio}%` }} />
|
<span style={{ width: ratio === null ? undefined : `${ratio}%` }} />
|
||||||
</div>
|
</div>
|
||||||
|
{liveLine ? (
|
||||||
|
<div className="progress-live" role="status">
|
||||||
|
{liveLine}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
<div className="progress-detail" title={detail}>
|
<div className="progress-detail" title={detail}>
|
||||||
{detail || t("Working safely in the background…", "正在后台安全处理…")}
|
{detail || t("Working safely in the background…", "正在后台安全处理…")}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { api } from "../lib/api";
|
import { api } from "../lib/api";
|
||||||
import { isCancelled, messageFrom } from "../lib/format";
|
import { isCancelled, messageFrom } from "../lib/format";
|
||||||
|
import { useToast } from "../components/ui";
|
||||||
import type { ManageView, PopupWindowItem } from "../types";
|
import type { ManageView, PopupWindowItem } from "../types";
|
||||||
|
|
||||||
export type PermissionsTab = "startup" | "extensions" | "popup";
|
export type PermissionsTab = "startup" | "extensions" | "popup";
|
||||||
|
|
@ -36,6 +37,7 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [closedTotal, setClosedTotal] = useState(0);
|
const [closedTotal, setClosedTotal] = useState(0);
|
||||||
const [recentClosed, setRecentClosed] = useState<{ process: string; title: string }[]>([]);
|
const [recentClosed, setRecentClosed] = useState<{ process: string; title: string }[]>([]);
|
||||||
|
const { push } = useToast();
|
||||||
|
|
||||||
const scan = useCallback(async () => {
|
const scan = useCallback(async () => {
|
||||||
setScanning(true);
|
setScanning(true);
|
||||||
|
|
@ -101,12 +103,16 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
|
||||||
await api.startupSetEnabled(id, enabled);
|
await api.startupSetEnabled(id, enabled);
|
||||||
await scan();
|
await scan();
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
setError(messageFrom(reason));
|
const why = messageFrom(reason);
|
||||||
|
setError(why);
|
||||||
|
// The row snaps back without this; a toast right where the user is
|
||||||
|
// looking explains *why* (cancelled UAC prompt, protected key, …).
|
||||||
|
push(why, "danger");
|
||||||
} finally {
|
} finally {
|
||||||
setBusyId(null);
|
setBusyId(null);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[scan],
|
[push, scan],
|
||||||
);
|
);
|
||||||
|
|
||||||
const toggleExtension = useCallback(
|
const toggleExtension = useCallback(
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,10 @@ export interface ScanWorkspace {
|
||||||
result: ScanResult | null;
|
result: ScanResult | null;
|
||||||
selected: Set<number>;
|
selected: Set<number>;
|
||||||
progress: JobProgress | null;
|
progress: JobProgress | null;
|
||||||
|
/** Live measurement counters streamed during a scan (A①). */
|
||||||
|
stats: { files: number; bytes: number } | null;
|
||||||
|
/** Per-category totals streamed in as each bucket finishes (A②). */
|
||||||
|
buckets: Partial<Record<Category, { total: number; count: number }>>;
|
||||||
scanning: boolean;
|
scanning: boolean;
|
||||||
deleting: boolean;
|
deleting: boolean;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
|
|
@ -73,6 +77,10 @@ export function useScanWorkspace(
|
||||||
const [result, setResult] = useState<ScanResult | null>(null);
|
const [result, setResult] = useState<ScanResult | null>(null);
|
||||||
const [selected, setSelected] = useState<Set<number>>(new Set());
|
const [selected, setSelected] = useState<Set<number>>(new Set());
|
||||||
const [progress, setProgress] = useState<JobProgress | null>(null);
|
const [progress, setProgress] = useState<JobProgress | null>(null);
|
||||||
|
const [stats, setStats] = useState<{ files: number; bytes: number } | null>(null);
|
||||||
|
const [buckets, setBuckets] = useState<
|
||||||
|
Partial<Record<Category, { total: number; count: number }>>
|
||||||
|
>({});
|
||||||
const [scanning, setScanning] = useState(false);
|
const [scanning, setScanning] = useState(false);
|
||||||
const [deleting, setDeleting] = useState(false);
|
const [deleting, setDeleting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
@ -94,7 +102,28 @@ export function useScanWorkspace(
|
||||||
setError(null);
|
setError(null);
|
||||||
setSummary(null);
|
setSummary(null);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
const stop = await subscribeJobProgress(id, setProgress);
|
setStats(null);
|
||||||
|
setBuckets({});
|
||||||
|
// Streamed side-band (A①②): `metered` carries running counters (kept
|
||||||
|
// out of `progress`, whose done/total mean "units done / units total"),
|
||||||
|
// `bucket` one finished category at a time (detail = "cat:count:total").
|
||||||
|
const stop = await subscribeJobProgress(id, (event) => {
|
||||||
|
if (event.event === "metered" && event.done !== null && event.total !== null) {
|
||||||
|
setStats({ files: event.done, bytes: event.total });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setProgress(event);
|
||||||
|
if (event.event === "bucket" && event.detail) {
|
||||||
|
const [category, count, total] = event.detail.split(":");
|
||||||
|
setBuckets((current) => ({
|
||||||
|
...current,
|
||||||
|
[category as Category]: {
|
||||||
|
count: Number(count) || 0,
|
||||||
|
total: Number(total) || 0,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
});
|
||||||
try {
|
try {
|
||||||
const next =
|
const next =
|
||||||
kind === "cleanup"
|
kind === "cleanup"
|
||||||
|
|
@ -115,6 +144,7 @@ export function useScanWorkspace(
|
||||||
if (activeJob.current === id) {
|
if (activeJob.current === id) {
|
||||||
setScanning(false);
|
setScanning(false);
|
||||||
setProgress(null);
|
setProgress(null);
|
||||||
|
setStats(null);
|
||||||
setCurrentJob(null);
|
setCurrentJob(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -276,6 +306,8 @@ export function useScanWorkspace(
|
||||||
result,
|
result,
|
||||||
selected,
|
selected,
|
||||||
progress,
|
progress,
|
||||||
|
stats,
|
||||||
|
buckets,
|
||||||
scanning,
|
scanning,
|
||||||
deleting,
|
deleting,
|
||||||
error,
|
error,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { useCallback, useRef, useState } from "react";
|
import { useCallback, useRef, useState } from "react";
|
||||||
import { api, subscribeJobProgress } from "../lib/api";
|
import { api, subscribeJobProgress } from "../lib/api";
|
||||||
import { isCancelled, messageFrom } from "../lib/format";
|
import { isCancelled, messageFrom } from "../lib/format";
|
||||||
import type { JobProgress, LargestFile, StorageNode } from "../types";
|
import type { ExploreResult, JobProgress, LargestFile, StorageNode } from "../types";
|
||||||
|
|
||||||
function jobId(): string {
|
function jobId(): string {
|
||||||
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||||
|
|
@ -9,12 +9,15 @@ function jobId(): string {
|
||||||
|
|
||||||
export interface StorageWorkspace {
|
export interface StorageWorkspace {
|
||||||
node: StorageNode | null;
|
node: StorageNode | null;
|
||||||
|
/** Freshness of the current node (A⑥ size cache). */
|
||||||
|
cached: boolean;
|
||||||
|
measuredAtMs: number | null;
|
||||||
files: LargestFile[];
|
files: LargestFile[];
|
||||||
progress: JobProgress | null;
|
progress: JobProgress | null;
|
||||||
exploring: boolean;
|
exploring: boolean;
|
||||||
scanningFiles: boolean;
|
scanningFiles: boolean;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
explore: (path?: string | null) => Promise<void>;
|
explore: (path?: string | null, force?: boolean) => Promise<void>;
|
||||||
largestFiles: (path: string) => Promise<void>;
|
largestFiles: (path: string) => Promise<void>;
|
||||||
cancel: () => Promise<void>;
|
cancel: () => Promise<void>;
|
||||||
clearError: () => void;
|
clearError: () => void;
|
||||||
|
|
@ -23,6 +26,8 @@ export interface StorageWorkspace {
|
||||||
|
|
||||||
export function useStorageWorkspace(): StorageWorkspace {
|
export function useStorageWorkspace(): StorageWorkspace {
|
||||||
const [node, setNode] = useState<StorageNode | null>(null);
|
const [node, setNode] = useState<StorageNode | null>(null);
|
||||||
|
const [cached, setCached] = useState(false);
|
||||||
|
const [measuredAtMs, setMeasuredAtMs] = useState<number | null>(null);
|
||||||
const [files, setFiles] = useState<LargestFile[]>([]);
|
const [files, setFiles] = useState<LargestFile[]>([]);
|
||||||
const [progress, setProgress] = useState<JobProgress | null>(null);
|
const [progress, setProgress] = useState<JobProgress | null>(null);
|
||||||
const [exploring, setExploring] = useState(false);
|
const [exploring, setExploring] = useState(false);
|
||||||
|
|
@ -30,7 +35,7 @@ export function useStorageWorkspace(): StorageWorkspace {
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const activeJob = useRef<string | null>(null);
|
const activeJob = useRef<string | null>(null);
|
||||||
|
|
||||||
const explore = useCallback(async (path?: string | null) => {
|
const explore = useCallback(async (path?: string | null, force = false) => {
|
||||||
if (exploring || scanningFiles) return;
|
if (exploring || scanningFiles) return;
|
||||||
const id = jobId();
|
const id = jobId();
|
||||||
activeJob.current = id;
|
activeJob.current = id;
|
||||||
|
|
@ -40,9 +45,11 @@ export function useStorageWorkspace(): StorageWorkspace {
|
||||||
setFiles([]);
|
setFiles([]);
|
||||||
const stop = await subscribeJobProgress(id, setProgress);
|
const stop = await subscribeJobProgress(id, setProgress);
|
||||||
try {
|
try {
|
||||||
const next = await api.storageExplore(id, path ?? null, 1, 16);
|
const next: ExploreResult = await api.storageExplore(id, path ?? null, 1, 16, force);
|
||||||
if (activeJob.current !== id) return;
|
if (activeJob.current !== id) return;
|
||||||
setNode(next);
|
setNode(next.node);
|
||||||
|
setCached(next.cached);
|
||||||
|
setMeasuredAtMs(next.measuredAtMs);
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
if (!isCancelled(reason)) setError(messageFrom(reason));
|
if (!isCancelled(reason)) setError(messageFrom(reason));
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -89,6 +96,8 @@ export function useStorageWorkspace(): StorageWorkspace {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
node,
|
node,
|
||||||
|
cached,
|
||||||
|
measuredAtMs,
|
||||||
files,
|
files,
|
||||||
progress,
|
progress,
|
||||||
exploring,
|
exploring,
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import type {
|
||||||
Bootstrap,
|
Bootstrap,
|
||||||
DeleteMode,
|
DeleteMode,
|
||||||
DeleteResult,
|
DeleteResult,
|
||||||
|
ExploreResult,
|
||||||
HistorySession,
|
HistorySession,
|
||||||
JobProgress,
|
JobProgress,
|
||||||
LargestFile,
|
LargestFile,
|
||||||
|
|
@ -14,9 +15,10 @@ import type {
|
||||||
PlanResult,
|
PlanResult,
|
||||||
PopupClosedEvent,
|
PopupClosedEvent,
|
||||||
PopupWindowItem,
|
PopupWindowItem,
|
||||||
|
PreflightResult,
|
||||||
ScanResult,
|
ScanResult,
|
||||||
SettingsView,
|
SettingsView,
|
||||||
StorageNode,
|
SpaceInsight,
|
||||||
SystemSnapshot,
|
SystemSnapshot,
|
||||||
UndoResult,
|
UndoResult,
|
||||||
UpdateCheckResult,
|
UpdateCheckResult,
|
||||||
|
|
@ -52,6 +54,8 @@ export const api = {
|
||||||
}),
|
}),
|
||||||
cleanupDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) =>
|
cleanupDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) =>
|
||||||
invoke<DeleteResult>("cleanup_delete", { jobId, scanId, selected, mode }),
|
invoke<DeleteResult>("cleanup_delete", { jobId, scanId, selected, mode }),
|
||||||
|
cleanupPreflight: (scanId: string, selected: number[]) =>
|
||||||
|
invoke<PreflightResult>("cleanup_preflight", { scanId, selected }),
|
||||||
purgeScan: (jobId: string, roots: string[] = [], minAgeDays: number | null = null, force = false) =>
|
purgeScan: (jobId: string, roots: string[] = [], minAgeDays: number | null = null, force = false) =>
|
||||||
invoke<ScanResult>("purge_scan", { jobId, roots, minAgeDays, force }),
|
invoke<ScanResult>("purge_scan", { jobId, roots, minAgeDays, force }),
|
||||||
purgeDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) =>
|
purgeDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) =>
|
||||||
|
|
@ -60,8 +64,9 @@ export const api = {
|
||||||
appPlan: (jobId: string, appKey: string) => invoke<PlanResult>("app_plan", { jobId, appKey }),
|
appPlan: (jobId: string, appKey: string) => invoke<PlanResult>("app_plan", { jobId, appKey }),
|
||||||
appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) =>
|
appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) =>
|
||||||
invoke<DeleteResult>("app_uninstall", { jobId, planId, selected, mode }),
|
invoke<DeleteResult>("app_uninstall", { jobId, planId, selected, mode }),
|
||||||
storageExplore: (jobId: string, path?: string | null, depth = 1, top = 16) =>
|
storageExplore: (jobId: string, path?: string | null, depth = 1, top = 16, force = false) =>
|
||||||
invoke<StorageNode>("storage_explore", { jobId, path, depth, top }),
|
invoke<ExploreResult>("storage_explore", { jobId, path, depth, top, force }),
|
||||||
|
storageInsights: () => invoke<SpaceInsight[]>("storage_insights"),
|
||||||
storageLargestFiles: (jobId: string, path: string, limit = 40) =>
|
storageLargestFiles: (jobId: string, path: string, limit = 40) =>
|
||||||
invoke<LargestFile[]>("storage_largest_files", { jobId, path, limit }),
|
invoke<LargestFile[]>("storage_largest_files", { jobId, path, limit }),
|
||||||
systemSnapshot: (full = false) => invoke<SystemSnapshot>("system_snapshot", { full }),
|
systemSnapshot: (full = false) => invoke<SystemSnapshot>("system_snapshot", { full }),
|
||||||
|
|
@ -72,6 +77,9 @@ export const api = {
|
||||||
settingsSave: (patch: SettingsPatch) => invoke<SettingsView>("settings_save", { patch }),
|
settingsSave: (patch: SettingsPatch) => invoke<SettingsView>("settings_save", { patch }),
|
||||||
whitelistAdd: (path: string) => invoke<SettingsView>("whitelist_add", { path }),
|
whitelistAdd: (path: string) => invoke<SettingsView>("whitelist_add", { path }),
|
||||||
whitelistRemove: (pattern: string) => invoke<SettingsView>("whitelist_remove", { pattern }),
|
whitelistRemove: (pattern: string) => invoke<SettingsView>("whitelist_remove", { pattern }),
|
||||||
|
whitelistAudit: () => invoke<{ pattern: string; live: boolean }[]>("whitelist_audit"),
|
||||||
|
writeTextFile: (path: string, contents: string) =>
|
||||||
|
invoke<void>("write_text_file", { path, contents }),
|
||||||
revealPath: (path: string) => invoke<void>("reveal_path", { path }),
|
revealPath: (path: string) => invoke<void>("reveal_path", { path }),
|
||||||
openTrash: () => invoke<void>("open_trash"),
|
openTrash: () => invoke<void>("open_trash"),
|
||||||
permissionStatus: () => invoke<PermissionStatus>("permission_status"),
|
permissionStatus: () => invoke<PermissionStatus>("permission_status"),
|
||||||
|
|
|
||||||
|
|
@ -98,3 +98,45 @@ export function isCancelled(error: unknown): boolean {
|
||||||
const text = messageFrom(error).toLowerCase();
|
const text = messageFrom(error).toLowerCase();
|
||||||
return text.includes("cancel") || text.includes("取消");
|
return text.includes("cancel") || text.includes("取消");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* "最后写入 3 个月前" / "written into 3 months ago" — the Mole decision
|
||||||
|
* aid: size alone is not actionable, dormancy is. */
|
||||||
|
export function ageLabel(secs: number, lang: "zh" | "en"): string {
|
||||||
|
const days = Math.floor(secs / 86_400);
|
||||||
|
if (lang === "zh") {
|
||||||
|
if (days < 1) return "今天有改动";
|
||||||
|
if (days < 30) return `${days} 天未修改`;
|
||||||
|
if (days < 365) return `${Math.floor(days / 30)} 个月未修改`;
|
||||||
|
return `${(days / 365).toFixed(days < 730 ? 1 : 0)} 年未修改`;
|
||||||
|
}
|
||||||
|
if (days < 1) return "written today";
|
||||||
|
if (days < 30) return `${days} days untouched`;
|
||||||
|
if (days < 365) return `${Math.floor(days / 30)} months untouched`;
|
||||||
|
return `${(days / 365).toFixed(days < 730 ? 1 : 0)} years untouched`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* "12 分钟前" for cache freshness lines. */
|
||||||
|
export function agoLabel(ms: number, lang: "zh" | "en"): string {
|
||||||
|
const mins = Math.floor(ms / 60_000);
|
||||||
|
if (lang === "zh") {
|
||||||
|
if (mins < 1) return "刚刚";
|
||||||
|
if (mins < 60) return `${mins} 分钟前`;
|
||||||
|
return `${Math.floor(mins / 60)} 小时前`;
|
||||||
|
}
|
||||||
|
if (mins < 1) return "just now";
|
||||||
|
if (mins < 60) return `${mins} min ago`;
|
||||||
|
return `${Math.floor(mins / 60)} h ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Throttled "128,431 文件 · 38.2 GB" live scan counter (A①). */
|
||||||
|
export function countLabel(files: number, bytes: number, lang: "zh" | "en"): string {
|
||||||
|
const f = formatThousands(files);
|
||||||
|
const b = formatBytes(bytes);
|
||||||
|
return lang === "zh" ? `已统计 ${f} 个文件 · ${b}` : `${f} files · ${b} measured`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatThousands(value: number): string {
|
||||||
|
return Math.round(value)
|
||||||
|
.toString()
|
||||||
|
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -58,6 +58,29 @@ export function SettingsPage({
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [permission, setPermission] = useState<PermissionStatus | null>(null);
|
const [permission, setPermission] = useState<PermissionStatus | null>(null);
|
||||||
const [checkingPermission, setCheckingPermission] = useState(false);
|
const [checkingPermission, setCheckingPermission] = useState(false);
|
||||||
|
// B2 (Mole #458): whitelist entries are only as good as their last hit.
|
||||||
|
// The audit answers "did this pattern ever protect something real?"
|
||||||
|
const [audit, setAudit] = useState<Map<string, boolean> | null>(null);
|
||||||
|
const [auditing, setAuditing] = useState(false);
|
||||||
|
|
||||||
|
const runAudit = useCallback(async () => {
|
||||||
|
setAuditing(true);
|
||||||
|
try {
|
||||||
|
const rows = await api.whitelistAudit();
|
||||||
|
setAudit(new Map(rows.map((row) => [row.pattern, row.live])));
|
||||||
|
} catch {
|
||||||
|
setAudit(null);
|
||||||
|
} finally {
|
||||||
|
setAuditing(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (settings.whitelist.length > 0 && audit === null && !auditing) {
|
||||||
|
void runAudit();
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [settings.whitelist.length]);
|
||||||
|
|
||||||
const checkPermissions = useCallback(async () => {
|
const checkPermissions = useCallback(async () => {
|
||||||
setCheckingPermission(true);
|
setCheckingPermission(true);
|
||||||
|
|
@ -384,6 +407,30 @@ export function SettingsPage({
|
||||||
{t("Add", "添加")}
|
{t("Add", "添加")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
{settings.whitelist.length > 0 ? (
|
||||||
|
<div className="whitelist-audit-bar">
|
||||||
|
<span>
|
||||||
|
{audit === null
|
||||||
|
? t(
|
||||||
|
"Checking whether each pattern still matches anything…",
|
||||||
|
"正在核对每条规则是否还命中过内容…",
|
||||||
|
)
|
||||||
|
: t(
|
||||||
|
`Consumption audit: ${[...audit.values()].filter(Boolean).length} of ${audit.size} pattern(s) matched known cache locations`,
|
||||||
|
`消费审计:${audit.size} 条规则中 ${[...audit.values()].filter(Boolean).length} 条命中过已知缓存位置`,
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
icon={<RefreshCw size={13} className={auditing ? "spin" : undefined} />}
|
||||||
|
onClick={() => void runAudit()}
|
||||||
|
disabled={auditing}
|
||||||
|
>
|
||||||
|
{t("Re-check", "重新检查")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
<div className="whitelist-list">
|
<div className="whitelist-list">
|
||||||
{settings.whitelist.length === 0 ? (
|
{settings.whitelist.length === 0 ? (
|
||||||
<p className="settings-empty">
|
<p className="settings-empty">
|
||||||
|
|
@ -396,6 +443,25 @@ export function SettingsPage({
|
||||||
<ShieldCheck size={15} />
|
<ShieldCheck size={15} />
|
||||||
</span>
|
</span>
|
||||||
<code title={pattern}>{shortPath(pattern, 88)}</code>
|
<code title={pattern}>{shortPath(pattern, 88)}</code>
|
||||||
|
{audit ? (
|
||||||
|
<span
|
||||||
|
className={`whitelist-audit-chip ${
|
||||||
|
audit.get(pattern) ? "is-live" : "is-dead"
|
||||||
|
}`}
|
||||||
|
title={t(
|
||||||
|
audit.get(pattern)
|
||||||
|
? "This pattern matched paths squid knows about on the last scan"
|
||||||
|
: "This pattern has never matched anything — it may be stale",
|
||||||
|
audit.get(pattern)
|
||||||
|
? "最近扫描命中过这条规则保护的位置"
|
||||||
|
: "从未命中任何已知位置,规则可能已经过期",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{audit.get(pattern)
|
||||||
|
? t("Recently matched", "最近命中")
|
||||||
|
: t("Never matched", "从未命中")}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
<button
|
<button
|
||||||
className="row-reveal"
|
className="row-reveal"
|
||||||
aria-label={t("Remove protection", "移除保护")}
|
aria-label={t("Remove protection", "移除保护")}
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,13 @@ import {
|
||||||
ArrowUpRight,
|
ArrowUpRight,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
DownloadCloud,
|
DownloadCloud,
|
||||||
|
FileText,
|
||||||
FolderOpen,
|
FolderOpen,
|
||||||
ScanSearch,
|
ScanSearch,
|
||||||
|
ShieldCheck,
|
||||||
Trash2,
|
Trash2,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { open } from "@tauri-apps/plugin-dialog";
|
import { open, save } from "@tauri-apps/plugin-dialog";
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
|
|
@ -24,13 +26,20 @@ import {
|
||||||
} from "react";
|
} from "react";
|
||||||
import { useI18n } from "../i18n";
|
import { useI18n } from "../i18n";
|
||||||
import { api } from "../lib/api";
|
import { api } from "../lib/api";
|
||||||
import { formatBytes, formatCount, shortPath } from "../lib/format";
|
import {
|
||||||
|
ageLabel,
|
||||||
|
countLabel,
|
||||||
|
formatBytes,
|
||||||
|
formatCount,
|
||||||
|
shortPath,
|
||||||
|
} from "../lib/format";
|
||||||
import type {
|
import type {
|
||||||
Bootstrap,
|
Bootstrap,
|
||||||
Category,
|
Category,
|
||||||
CleanupItem,
|
CleanupItem,
|
||||||
DeleteMode,
|
DeleteMode,
|
||||||
DeleteResult,
|
DeleteResult,
|
||||||
|
PreflightResult,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
|
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
|
||||||
import {
|
import {
|
||||||
|
|
@ -100,6 +109,7 @@ const RULE_NAMES: Record<string, [string, string]> = {
|
||||||
"update-installers-known": ["Known app update packages", "已知应用的升级包"],
|
"update-installers-known": ["Known app update packages", "已知应用的升级包"],
|
||||||
"update-installers-scan": ["Other update packages", "其他升级安装包"],
|
"update-installers-scan": ["Other update packages", "其他升级安装包"],
|
||||||
"purge-artifacts": ["Build artefacts", "项目构建产物"],
|
"purge-artifacts": ["Build artefacts", "项目构建产物"],
|
||||||
|
"user-assets": ["Your own files (locked)", "您的个人文件(受保护)"],
|
||||||
};
|
};
|
||||||
|
|
||||||
function ruleName(ruleId: string, lang: "zh" | "en"): string {
|
function ruleName(ruleId: string, lang: "zh" | "en"): string {
|
||||||
|
|
@ -140,6 +150,134 @@ type Cluster = {
|
||||||
selected: number;
|
selected: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* A⑦: skipped items on the result page are grouped by *why* they were
|
||||||
|
* skipped, each group with the concrete next step — Mole's ledger reads as
|
||||||
|
* "here is what to do about it", not as a wall of paths. */
|
||||||
|
type SkipGroup = {
|
||||||
|
key: string;
|
||||||
|
title: [string, string];
|
||||||
|
hint: [string, string];
|
||||||
|
action?: "rescan";
|
||||||
|
};
|
||||||
|
|
||||||
|
function skipGroupOf(reason: string): SkipGroup {
|
||||||
|
const lower = reason.toLowerCase();
|
||||||
|
if (lower.includes("running") || lower.includes("占用")) {
|
||||||
|
return {
|
||||||
|
key: "running",
|
||||||
|
title: ["应用正在运行", "应用正在运行"],
|
||||||
|
hint: ["退出这些应用后重新扫描,即可再次选中。", "退出这些应用后重新扫描,即可再次选中。"],
|
||||||
|
action: "rescan",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (lower.includes("admin") || lower.includes("管理员")) {
|
||||||
|
return {
|
||||||
|
key: "admin",
|
||||||
|
title: ["需要管理员权限", "需要管理员权限"],
|
||||||
|
hint: [
|
||||||
|
"以管理员身份重新启动 Squid 后再清理这批项目。",
|
||||||
|
"以管理员身份重新启动 Squid 后再清理这批项目。",
|
||||||
|
],
|
||||||
|
action: "rescan",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (lower.includes("已不存在") || lower.includes("no longer") || lower.includes("missing")) {
|
||||||
|
return {
|
||||||
|
key: "gone",
|
||||||
|
title: ["扫描后已消失", "扫描后已消失"],
|
||||||
|
hint: ["这些路径在清理开始前就不在了,无需处理。", "这些路径在清理开始前就不在了,无需处理。"],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (lower.includes("whitelist")) {
|
||||||
|
return {
|
||||||
|
key: "whitelist",
|
||||||
|
title: ["命中白名单", "命中白名单"],
|
||||||
|
hint: [
|
||||||
|
"在 设置 → 白名单 中移除对应规则后才会被清理。",
|
||||||
|
"在 设置 → 白名单 中移除对应规则后才会被清理。",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
key: "protected",
|
||||||
|
title: ["受安全策略保护", "受安全策略保护"],
|
||||||
|
hint: [
|
||||||
|
"这些目录看似缓存,实际可能存有您自己的文件,Squid 不会删除。",
|
||||||
|
"这些目录看似缓存,实际可能存有您自己的文件,Squid 不会删除。",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A③: a cluster is "dormant" when its newest member stopped changing more
|
||||||
|
* than 90 days ago — size plus dormancy is what makes a deletion call easy. */
|
||||||
|
const DORMANT_SECS = 90 * 24 * 3600;
|
||||||
|
|
||||||
|
function clusterDormancy(cluster: { entries: Entry[] }): number | null {
|
||||||
|
let oldest: number | null = null;
|
||||||
|
for (const entry of cluster.entries) {
|
||||||
|
const secs = entry.item.lastWriteSecs;
|
||||||
|
if (secs == null) continue;
|
||||||
|
if (oldest === null || secs > oldest) oldest = secs;
|
||||||
|
}
|
||||||
|
return oldest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* B3 evidence tokens → human lines. Unknown tokens render verbatim, so a
|
||||||
|
* future engine token still shows up instead of vanishing. */
|
||||||
|
function evidenceLines(
|
||||||
|
tokens: string[],
|
||||||
|
t: (en: string, zh: string) => string,
|
||||||
|
): { ok: boolean; text: string }[] {
|
||||||
|
const lines: { ok: boolean; text: string }[] = [];
|
||||||
|
for (const token of tokens) {
|
||||||
|
if (token.startsWith("lock:")) {
|
||||||
|
lines.push({
|
||||||
|
ok: true,
|
||||||
|
text: t(
|
||||||
|
`${token.slice(5)} present — the tree rebuilds with one command`,
|
||||||
|
`存在 ${token.slice(5)},一条命令即可完整重建`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
} else if (token.startsWith("record:")) {
|
||||||
|
lines.push({
|
||||||
|
ok: true,
|
||||||
|
text: t(
|
||||||
|
`${token.slice(7)} present — install record intact`,
|
||||||
|
`存在 ${token.slice(7)} 安装记录`,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
} else if (token === "record-missing") {
|
||||||
|
lines.push({
|
||||||
|
ok: true,
|
||||||
|
text: t("No install record found — skipped the hand-edit check", "缺少安装记录,未做手改检查"),
|
||||||
|
});
|
||||||
|
} else if (token.startsWith("modified:")) {
|
||||||
|
const count = Number(token.slice(9)) || 0;
|
||||||
|
lines.push(
|
||||||
|
count === 0
|
||||||
|
? { ok: true, text: t("No file is newer than the install record (nobody hand-edited it)", "无文件晚于安装记录(没有被手工修改)") }
|
||||||
|
: { ok: false, text: t(`${count} files are newer than the install record — possible local patches`, `${count} 个文件晚于安装记录,可能被手工修改过`) },
|
||||||
|
);
|
||||||
|
} else if (token === "git:ignored") {
|
||||||
|
lines.push({ ok: true, text: t("Marked .gitignore by the project", "已被项目 .gitignore 忽略") });
|
||||||
|
} else if (token === "git:untracked") {
|
||||||
|
lines.push({ ok: true, text: t("Not tracked by git", "未被 Git 跟踪") });
|
||||||
|
} else if (token === "git:tracked") {
|
||||||
|
lines.push({ ok: false, text: t("Tracked by git — deleted only with --all", "被 Git 跟踪,需强制模式才删") });
|
||||||
|
} else if (token === "git:none") {
|
||||||
|
lines.push({ ok: true, text: t("No git repository around it", "附近没有 Git 仓库") });
|
||||||
|
} else if (token.startsWith("age:")) {
|
||||||
|
lines.push({
|
||||||
|
ok: true,
|
||||||
|
text: t(`Last change ${token.slice(4)} days ago`, `最后修改于 ${token.slice(4)} 天前`),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
lines.push({ ok: true, text: token });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
/* A 清理点: one rule's worth of hits, aggregated like 电脑管家's sub-items.
|
/* A 清理点: one rule's worth of hits, aggregated like 电脑管家's sub-items.
|
||||||
* Tick = whole cluster; hover = 忽略 / 查看路径; body = expand to paths. */
|
* Tick = whole cluster; hover = 忽略 / 查看路径; body = expand to paths. */
|
||||||
function ClusterRow({
|
function ClusterRow({
|
||||||
|
|
@ -159,6 +297,7 @@ function ClusterRow({
|
||||||
}) {
|
}) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const allOn = cluster.removable > 0 && cluster.selected >= cluster.removable;
|
const allOn = cluster.removable > 0 && cluster.selected >= cluster.removable;
|
||||||
|
const dormancy = clusterDormancy(cluster);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="space-rule" onClick={onOpen}>
|
<div className="space-rule" onClick={onOpen}>
|
||||||
|
|
@ -169,6 +308,14 @@ function ClusterRow({
|
||||||
label={cluster.label}
|
label={cluster.label}
|
||||||
/>
|
/>
|
||||||
<span className="space-rule-name">{cluster.label}</span>
|
<span className="space-rule-name">{cluster.label}</span>
|
||||||
|
{dormancy !== null && dormancy >= DORMANT_SECS ? (
|
||||||
|
<span className="space-rule-dormant">
|
||||||
|
{t(
|
||||||
|
`${ageLabel(dormancy, "en").replace(" untouched", "")} dormant`,
|
||||||
|
ageLabel(dormancy, "zh").replace("未修改", "未使用"),
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
<span className="space-rule-cnt">
|
<span className="space-rule-cnt">
|
||||||
{t(
|
{t(
|
||||||
`${formatCount(cluster.entries.length)} location(s)`,
|
`${formatCount(cluster.entries.length)} location(s)`,
|
||||||
|
|
@ -217,33 +364,79 @@ function ClusterRow({
|
||||||
* in Explorer (电脑管家 habit: 点击定位); only the tick box changes the
|
* in Explorer (电脑管家 habit: 点击定位); only the tick box changes the
|
||||||
* selection, so browsing never mis-toggles. */
|
* selection, so browsing never mis-toggles. */
|
||||||
function AccItem({ entry }: { entry: Entry }) {
|
function AccItem({ entry }: { entry: Entry }) {
|
||||||
const { t } = useI18n();
|
const { t, lang } = useI18n();
|
||||||
const { item, source, index } = entry;
|
const { item, source, index } = entry;
|
||||||
const checked = source.selected.has(index);
|
const checked = source.selected.has(index);
|
||||||
|
const [showEvidence, setShowEvidence] = useState(false);
|
||||||
|
const evidence = item.evidence ?? [];
|
||||||
return (
|
return (
|
||||||
<div
|
<>
|
||||||
className={`space-item ${item.lock ? "is-locked" : ""}`}
|
<div
|
||||||
onClick={() => void api.revealPath(item.path).catch(() => undefined)}
|
className={`space-item ${item.lock ? "is-locked" : ""}`}
|
||||||
title={t("Open the location in Explorer", "在资源管理器中打开所在位置")}
|
onClick={() => void api.revealPath(item.path).catch(() => undefined)}
|
||||||
>
|
title={t("Open the location in Explorer", "在资源管理器中打开所在位置")}
|
||||||
<Checkbox
|
>
|
||||||
checked={checked}
|
<Checkbox
|
||||||
disabled={Boolean(item.lock)}
|
checked={checked}
|
||||||
onChange={() => source.toggleItem(index)}
|
disabled={Boolean(item.lock)}
|
||||||
label={item.label}
|
onChange={() => source.toggleItem(index)}
|
||||||
/>
|
label={item.label}
|
||||||
<span className="space-item-name">{item.label}</span>
|
/>
|
||||||
<span className="space-item-path" title={item.displayPath}>
|
<span className="space-item-name">{item.label}</span>
|
||||||
{shortPath(item.displayPath, 96)}
|
<span className="space-item-path" title={item.displayPath}>
|
||||||
</span>
|
{shortPath(item.displayPath, 96)}
|
||||||
{item.lock || item.note ? (
|
|
||||||
<span className={`space-item-meta ${item.lock ? "is-locked" : ""}`}>
|
|
||||||
{item.lock ? lockLabel(item.lock, t) : item.note}
|
|
||||||
</span>
|
</span>
|
||||||
|
{item.lock ? (
|
||||||
|
<span className="space-item-meta is-locked">{lockLabel(item.lock, t)}</span>
|
||||||
|
) : null}
|
||||||
|
{item.lastWriteSecs != null ? (
|
||||||
|
<span
|
||||||
|
className={`space-item-meta ${item.lastWriteSecs >= DORMANT_SECS ? "is-dormant" : ""}`}
|
||||||
|
title={t(
|
||||||
|
"Newest last-write inside, from the scan walk",
|
||||||
|
"扫描时记录的内部最新写入时间",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{ageLabel(item.lastWriteSecs, lang)}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
{evidence.length > 0 ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`space-item-evidence ${
|
||||||
|
evidence.some((token) => token.startsWith("modified:") && Number(token.slice(9)) > 0)
|
||||||
|
? "is-warn"
|
||||||
|
: ""
|
||||||
|
}`}
|
||||||
|
onClick={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
setShowEvidence((current) => !current);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{showEvidence
|
||||||
|
? t("Hide evidence", "收起依据")
|
||||||
|
: t("Why safe · evidence", "可删依据")}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{!item.lock && item.note ? (
|
||||||
|
<span className="space-item-meta">{item.note}</span>
|
||||||
|
) : null}
|
||||||
|
<span className="space-item-size">{formatBytes(item.onDisk)}</span>
|
||||||
|
<ArrowUpRight className="space-item-go" size={14} />
|
||||||
|
</div>
|
||||||
|
{showEvidence ? (
|
||||||
|
<div className="space-evidence">
|
||||||
|
<strong>{t("Why Squid judges this folder", "Squid 对该目录的判定依据")}</strong>
|
||||||
|
<ul>
|
||||||
|
{evidenceLines(evidence, t).map((line) => (
|
||||||
|
<li key={line.text} className={line.ok ? "is-ok" : "is-warn"}>
|
||||||
|
{line.text}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
<span className="space-item-size">{formatBytes(item.onDisk)}</span>
|
</>
|
||||||
<ArrowUpRight className="space-item-go" size={14} />
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -289,6 +482,10 @@ export function SpacePage({
|
||||||
if (scanning || deleting || inFlight.current) return;
|
if (scanning || deleting || inFlight.current) return;
|
||||||
inFlight.current = true;
|
inFlight.current = true;
|
||||||
setResult(null);
|
setResult(null);
|
||||||
|
// A fresh scan supersedes any armed inline confirm: the old selection
|
||||||
|
// (and its preflight verdict) no longer describes what is on screen.
|
||||||
|
setInlineConfirm(false);
|
||||||
|
setPreflight(null);
|
||||||
const rootList = roots
|
const rootList = roots
|
||||||
.split(/\r?\n/)
|
.split(/\r?\n/)
|
||||||
.map((root) => root.trim())
|
.map((root) => root.trim())
|
||||||
|
|
@ -570,6 +767,8 @@ export function SpacePage({
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
setConfirming(false);
|
setConfirming(false);
|
||||||
|
setInlineConfirm(false);
|
||||||
|
setPreflight(null);
|
||||||
}
|
}
|
||||||
setResult(merged);
|
setResult(merged);
|
||||||
push(
|
push(
|
||||||
|
|
@ -582,12 +781,150 @@ export function SpacePage({
|
||||||
};
|
};
|
||||||
|
|
||||||
const progress = cleanup.progress ?? purge.progress;
|
const progress = cleanup.progress ?? purge.progress;
|
||||||
|
// A①: running "已统计 N 文件 · X GB" counters streamed by the engines.
|
||||||
|
const liveStats = cleanup.stats ?? purge.stats;
|
||||||
|
// A②: category skeletons filled live while the scan is still measuring.
|
||||||
|
const liveBuckets = useMemo(() => {
|
||||||
|
const merged: Partial<Record<Category, { total: number; count: number }>> = {};
|
||||||
|
for (const source of [cleanup, purge]) {
|
||||||
|
for (const [category, bucket] of Object.entries(source.buckets)) {
|
||||||
|
const known = merged[category as Category];
|
||||||
|
merged[category as Category] = known
|
||||||
|
? { total: known.total + bucket.total, count: known.count + bucket.count }
|
||||||
|
: { ...bucket };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}, [cleanup.buckets, purge.buckets]);
|
||||||
const stage = cleanup.scanning
|
const stage = cleanup.scanning
|
||||||
? t("Scanning caches and junk", "第一步 · 扫描缓存与垃圾")
|
? t("Scanning caches and junk", "第一步 · 扫描缓存与垃圾")
|
||||||
: purge.scanning
|
: purge.scanning
|
||||||
? t("Scanning project folders", "第二步 · 扫描项目目录")
|
? t("Scanning project folders", "第二步 · 扫描项目目录")
|
||||||
: t("Collecting results", "正在汇总结果");
|
: t("Collecting results", "正在汇总结果");
|
||||||
|
|
||||||
|
// A④ + B1: low-risk runs confirm inline on the sticky bar; anything with
|
||||||
|
// update installers, many items, or preflight surprises opens the modal.
|
||||||
|
const [inlineConfirm, setInlineConfirm] = useState(false);
|
||||||
|
const [preflight, setPreflight] = useState<PreflightResult | null>(null);
|
||||||
|
const [preflightBusy, setPreflightBusy] = useState(false);
|
||||||
|
|
||||||
|
// Mole's inline strip: Esc backs out of the armed confirm.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!inlineConfirm) return;
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") setInlineConfirm(false);
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [inlineConfirm]);
|
||||||
|
|
||||||
|
const selectedPlans = () => {
|
||||||
|
const plans: Array<{ source: ScanWorkspace; indexes: number[] }> = [];
|
||||||
|
for (const source of [cleanup, purge]) {
|
||||||
|
const indexes = [...source.selected].filter((index) => {
|
||||||
|
const item = source.result?.items[index];
|
||||||
|
return item && !item.lock;
|
||||||
|
});
|
||||||
|
if (indexes.length > 0) plans.push({ source, indexes });
|
||||||
|
}
|
||||||
|
return plans;
|
||||||
|
};
|
||||||
|
|
||||||
|
const runPreflight = async () => {
|
||||||
|
const plans = selectedPlans();
|
||||||
|
if (plans.length === 0) return null;
|
||||||
|
setPreflightBusy(true);
|
||||||
|
const blocked: PreflightResult["blocked"] = [];
|
||||||
|
let checked = 0;
|
||||||
|
try {
|
||||||
|
for (const plan of plans) {
|
||||||
|
const scanId = plan.source.result?.scanId;
|
||||||
|
if (!scanId) continue;
|
||||||
|
try {
|
||||||
|
const verdict = await api.cleanupPreflight(scanId, plan.indexes);
|
||||||
|
checked += verdict.checked;
|
||||||
|
blocked.push(...verdict.blocked);
|
||||||
|
} catch {
|
||||||
|
// A failed re-check must never block the run; delete re-guards anyway.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setPreflightBusy(false);
|
||||||
|
}
|
||||||
|
const verdict = { checked, blocked };
|
||||||
|
setPreflight(verdict);
|
||||||
|
return verdict;
|
||||||
|
};
|
||||||
|
|
||||||
|
const startClean = async () => {
|
||||||
|
const verdict = await runPreflight();
|
||||||
|
const risky =
|
||||||
|
selectedUpdaters.count > 0 ||
|
||||||
|
selectedStats.count > 40 ||
|
||||||
|
(verdict?.blocked.length ?? 0) > 0;
|
||||||
|
if (risky) {
|
||||||
|
setConfirming(true);
|
||||||
|
} else {
|
||||||
|
setInlineConfirm(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// B5: export the current selection as a reviewable Markdown list.
|
||||||
|
const exportList = async () => {
|
||||||
|
const lines: string[] = [
|
||||||
|
`# squid-clean-list · ${new Date().toLocaleString()} · ${t(
|
||||||
|
`${formatCount(selectedStats.count)} items ${formatBytes(selectedStats.total)}`,
|
||||||
|
`已选 ${formatCount(selectedStats.count)} 项 ${formatBytes(selectedStats.total)}`,
|
||||||
|
)}`,
|
||||||
|
"",
|
||||||
|
];
|
||||||
|
for (const source of [cleanup, purge]) {
|
||||||
|
for (const index of [...source.selected].sort((a, b) => a - b)) {
|
||||||
|
const item = source.result?.items[index];
|
||||||
|
if (!item || item.lock) continue;
|
||||||
|
const evidence =
|
||||||
|
item.evidence && item.evidence.length > 0
|
||||||
|
? ` · ${item.evidence.join(" · ")}`
|
||||||
|
: "";
|
||||||
|
lines.push(
|
||||||
|
`- [${categoryLabel(item.category, lang, bin)}] ${item.displayPath} — ${formatBytes(
|
||||||
|
item.onDisk,
|
||||||
|
)}${item.note ? ` · ${item.note}` : ""}${evidence}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push("");
|
||||||
|
const locked = entries.filter((entry) => entry.item.lock === "protected");
|
||||||
|
if (locked.length > 0) {
|
||||||
|
lines.push(
|
||||||
|
t("## Protected (not deleted)", "## 受保护项(未列入删除)"),
|
||||||
|
...locked
|
||||||
|
.slice(0, 20)
|
||||||
|
.map(
|
||||||
|
(entry) =>
|
||||||
|
`- ${entry.item.displayPath} — ${formatBytes(entry.item.onDisk)} · ${
|
||||||
|
entry.item.note ?? lockLabel(entry.item.lock, t)
|
||||||
|
}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const chosen = await save({
|
||||||
|
title: t("Export clean list", "导出清理清单"),
|
||||||
|
defaultPath: "squid-clean-list.md",
|
||||||
|
filters: [{ name: "Markdown", extensions: ["md", "txt"] }],
|
||||||
|
});
|
||||||
|
if (!chosen) return;
|
||||||
|
try {
|
||||||
|
await api.writeTextFile(chosen, lines.join("\n"));
|
||||||
|
push(t("List exported", "清单已导出"), "success");
|
||||||
|
} catch (reason) {
|
||||||
|
push(
|
||||||
|
t(`Export failed: ${String(reason)}`, `导出失败:${String(reason)}`),
|
||||||
|
"danger",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const error = cleanup.error ?? purge.error;
|
const error = cleanup.error ?? purge.error;
|
||||||
|
|
||||||
if (result) {
|
if (result) {
|
||||||
|
|
@ -626,6 +963,57 @@ export function SpacePage({
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{result.skipped && result.skipped.length > 0 ? (
|
||||||
|
<div className="result-skipped">
|
||||||
|
<div className="result-skipped-head">
|
||||||
|
{t(
|
||||||
|
`${result.skipped.length} item(s) were skipped`,
|
||||||
|
`有 ${result.skipped.length} 项本次未处理`,
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{Object.entries(
|
||||||
|
result.skipped.reduce<Record<string, typeof result.skipped>>(
|
||||||
|
(groups, row) => {
|
||||||
|
const key = skipGroupOf(row.reason).key;
|
||||||
|
(groups[key] ??= []).push(row);
|
||||||
|
return groups;
|
||||||
|
},
|
||||||
|
{},
|
||||||
|
),
|
||||||
|
).map(([key, rows]) => {
|
||||||
|
const group = skipGroupOf(rows[0].reason);
|
||||||
|
return (
|
||||||
|
<div className="result-skip-group" key={key}>
|
||||||
|
<div className="result-skip-title">
|
||||||
|
<strong>{t(group.title[0], group.title[1])}</strong>
|
||||||
|
<span>{rows.length}</span>
|
||||||
|
</div>
|
||||||
|
<ul>
|
||||||
|
{rows.slice(0, 5).map((row) => (
|
||||||
|
<li key={row.path} title={row.reason}>
|
||||||
|
<code>{row.path}</code>
|
||||||
|
<small>{row.reason}</small>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
{rows.length > 5 ? (
|
||||||
|
<li className="more">
|
||||||
|
{t(`… ${rows.length - 5} more`, `… 另有 ${rows.length - 5} 项`)}
|
||||||
|
</li>
|
||||||
|
) : null}
|
||||||
|
</ul>
|
||||||
|
<div className="result-skip-foot">
|
||||||
|
<small>{t(group.hint[0], group.hint[1])}</small>
|
||||||
|
{group.action === "rescan" ? (
|
||||||
|
<Button variant="ghost" size="sm" onClick={() => void runScan()}>
|
||||||
|
{t("Scan again", "再扫一次")}
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -722,8 +1110,31 @@ export function SpacePage({
|
||||||
<ProgressCard
|
<ProgressCard
|
||||||
progress={progress}
|
progress={progress}
|
||||||
title={stage}
|
title={stage}
|
||||||
|
capAt99
|
||||||
|
liveLine={liveStats ? countLabel(liveStats.files, liveStats.bytes, lang) : null}
|
||||||
onCancel={() => void (cleanup.scanning ? cleanup.cancel() : purge.cancel())}
|
onCancel={() => void (cleanup.scanning ? cleanup.cancel() : purge.cancel())}
|
||||||
/>
|
/>
|
||||||
|
{Object.keys(liveBuckets).length > 0 ? (
|
||||||
|
<div className="space-live-cats">
|
||||||
|
{CATEGORY_ORDER.filter((category) => liveBuckets[category]).map((category) => {
|
||||||
|
const bucket = liveBuckets[category]!;
|
||||||
|
const meta = CATEGORY_META[category];
|
||||||
|
const Icon = meta.icon;
|
||||||
|
return (
|
||||||
|
<div key={category} className="space-live-cat">
|
||||||
|
<span className={`space-cat-icon tone-${meta.tone}`}>
|
||||||
|
<Icon size={14} />
|
||||||
|
</span>
|
||||||
|
<span className="space-live-cat-name">{categoryLabel(category, lang, bin)}</span>
|
||||||
|
<span className="space-live-cat-cnt">
|
||||||
|
{t(`${formatCount(bucket.count)} items`, `${formatCount(bucket.count)} 项`)}
|
||||||
|
</span>
|
||||||
|
<b>{formatBytes(bucket.total)}</b>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
|
@ -793,24 +1204,84 @@ export function SpacePage({
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
icon={<FileText size={14} />}
|
||||||
|
onClick={() => void exportList()}
|
||||||
|
disabled={selectedStats.count === 0}
|
||||||
|
>
|
||||||
|
{t("Export list", "导出清单")}
|
||||||
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
cleanup.clearSelection();
|
cleanup.clearSelection();
|
||||||
purge.clearSelection();
|
purge.clearSelection();
|
||||||
|
setInlineConfirm(false);
|
||||||
}}
|
}}
|
||||||
disabled={selectedStats.count === 0}
|
disabled={selectedStats.count === 0 || inlineConfirm}
|
||||||
>
|
>
|
||||||
{t("Deselect all", "取消全选")}
|
{t("Deselect all", "取消全选")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
{inlineConfirm ? (
|
||||||
variant="primary"
|
<div className="space-inline-confirm">
|
||||||
icon={<Trash2 size={16} />}
|
<ShieldCheck size={16} />
|
||||||
disabled={selectedStats.count === 0}
|
<span>
|
||||||
onClick={() => setConfirming(true)}
|
<b>
|
||||||
>
|
{mode === "trash"
|
||||||
{t("Clean now", "立即清理")}
|
? t(
|
||||||
</Button>
|
`Move to ${bin}: ${formatCount(selectedStats.count)} items · ${formatBytes(selectedStats.total)}`,
|
||||||
|
`将移入${bin}:${formatCount(selectedStats.count)} 项 · ${formatBytes(selectedStats.total)}`,
|
||||||
|
)
|
||||||
|
: t(
|
||||||
|
`Delete ${formatCount(selectedStats.count)} items · ${formatBytes(selectedStats.total)}`,
|
||||||
|
`将永久删除 ${formatCount(selectedStats.count)} 项 · ${formatBytes(selectedStats.total)}`,
|
||||||
|
)}
|
||||||
|
</b>
|
||||||
|
{preflight && preflight.blocked.length > 0 ? (
|
||||||
|
<small>
|
||||||
|
{t(
|
||||||
|
`${preflight.blocked.length} items changed since the scan and were dropped from this run`,
|
||||||
|
`其中 ${preflight.blocked.length} 项在扫描后情况变化,本次已自动移出`,
|
||||||
|
)}
|
||||||
|
</small>
|
||||||
|
) : (
|
||||||
|
<small>
|
||||||
|
{t(
|
||||||
|
"Esc cancels · every path was re-checked just now",
|
||||||
|
"按 Esc 取消 · 刚才已逐路径复核",
|
||||||
|
)}
|
||||||
|
</small>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setInlineConfirm(false)}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
{t("Cancel", "取消")}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
size="sm"
|
||||||
|
disabled={busy || preflightBusy}
|
||||||
|
icon={<Trash2 size={14} />}
|
||||||
|
onClick={() => void cleanSelected()}
|
||||||
|
>
|
||||||
|
{t("Confirm clean", "确认清理")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
icon={<Trash2 size={16} />}
|
||||||
|
disabled={selectedStats.count === 0 || preflightBusy}
|
||||||
|
onClick={() => void startClean()}
|
||||||
|
>
|
||||||
|
{t("Clean now", "立即清理")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(["daily", "optional"] as const).map((section) => {
|
{(["daily", "optional"] as const).map((section) => {
|
||||||
|
|
@ -1065,6 +1536,39 @@ export function SpacePage({
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
{preflight && preflight.checked > 0 ? (
|
||||||
|
<details className="confirm-preflight">
|
||||||
|
<summary>
|
||||||
|
<ShieldCheck size={14} />
|
||||||
|
{preflight.blocked.length > 0
|
||||||
|
? t(
|
||||||
|
`Re-checked ${preflight.checked} paths just now — ${preflight.blocked.length} changed and were dropped`,
|
||||||
|
`刚刚逐路径复核过 ${preflight.checked} 项 — ${preflight.blocked.length} 项情况有变,已移出本次`,
|
||||||
|
)
|
||||||
|
: t(
|
||||||
|
`Re-checked ${preflight.checked} paths just now — all still safe to remove`,
|
||||||
|
`刚刚逐路径复核过 ${preflight.checked} 项 — 全部仍可安全删除`,
|
||||||
|
)}
|
||||||
|
</summary>
|
||||||
|
{preflight.blocked.length > 0 ? (
|
||||||
|
<ul>
|
||||||
|
{preflight.blocked.slice(0, 8).map((row) => (
|
||||||
|
<li key={row.path}>
|
||||||
|
<code>{row.path}</code>
|
||||||
|
<small>{row.reason}</small>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<p>
|
||||||
|
{t(
|
||||||
|
"Locks, whitelist, running apps and vanished paths were all re-verified at the click of this button.",
|
||||||
|
"锁、白名单、运行中的应用与已消失的路径,都在点击瞬间重新核验过。",
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</details>
|
||||||
|
) : null}
|
||||||
</ConfirmDialog>
|
</ConfirmDialog>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,31 @@
|
||||||
import {
|
import {
|
||||||
ArrowLeft,
|
ArrowLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
|
Copy,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
FileArchive,
|
FileArchive,
|
||||||
FolderOpen,
|
FolderOpen,
|
||||||
FolderSearch,
|
FolderSearch,
|
||||||
HardDrive,
|
HardDrive,
|
||||||
|
Lightbulb,
|
||||||
LoaderCircle,
|
LoaderCircle,
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
ScanSearch,
|
ScanSearch,
|
||||||
|
TimerReset,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { open } from "@tauri-apps/plugin-dialog";
|
import { open } from "@tauri-apps/plugin-dialog";
|
||||||
import * as apiClient from "../lib/api";
|
import * as apiClient from "../lib/api";
|
||||||
import { useI18n } from "../i18n";
|
import { useI18n } from "../i18n";
|
||||||
import {
|
import {
|
||||||
|
agoLabel,
|
||||||
basename,
|
basename,
|
||||||
formatBytes,
|
formatBytes,
|
||||||
formatCount,
|
formatCount,
|
||||||
percent,
|
percent,
|
||||||
shortPath,
|
shortPath,
|
||||||
} from "../lib/format";
|
} from "../lib/format";
|
||||||
import type { Bootstrap, StorageNode } from "../types";
|
import type { Bootstrap, SpaceInsight, StorageNode } from "../types";
|
||||||
import { useStorageWorkspace } from "../hooks/useStorageWorkspace";
|
import { useStorageWorkspace } from "../hooks/useStorageWorkspace";
|
||||||
import {
|
import {
|
||||||
Button,
|
Button,
|
||||||
|
|
@ -29,6 +33,7 @@ import {
|
||||||
PageHeader,
|
PageHeader,
|
||||||
ProgressCard,
|
ProgressCard,
|
||||||
SectionTitle,
|
SectionTitle,
|
||||||
|
useToast,
|
||||||
} from "../components/ui";
|
} from "../components/ui";
|
||||||
|
|
||||||
const BAR_TONES = ["blue", "violet", "cyan", "teal", "orange", "pink", "indigo", "slate"];
|
const BAR_TONES = ["blue", "violet", "cyan", "teal", "orange", "pink", "indigo", "slate"];
|
||||||
|
|
@ -48,10 +53,28 @@ function parentDirectory(path: string): string | null {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
const { t } = useI18n();
|
const { t, lang } = useI18n();
|
||||||
|
const { push } = useToast();
|
||||||
const workspace = useStorageWorkspace();
|
const workspace = useStorageWorkspace();
|
||||||
const [pathInput, setPathInput] = useState("");
|
const [pathInput, setPathInput] = useState("");
|
||||||
const [manualPath, setManualPath] = useState(false);
|
const [manualPath, setManualPath] = useState(false);
|
||||||
|
const [insights, setInsights] = useState<SpaceInsight[] | null>(null);
|
||||||
|
|
||||||
|
// A⑤: hidden space hogs measured quietly once per page visit.
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
void apiClient.api
|
||||||
|
.storageInsights()
|
||||||
|
.then((rows) => {
|
||||||
|
if (alive) setInsights(rows);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (alive) setInsights([]);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (workspace.node && !manualPath) setPathInput(workspace.node.path);
|
if (workspace.node && !manualPath) setPathInput(workspace.node.path);
|
||||||
|
|
@ -89,10 +112,19 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
};
|
};
|
||||||
|
|
||||||
const drill = (node: StorageNode) => {
|
const drill = (node: StorageNode) => {
|
||||||
if (!node.is_dir || node.path === workspace.node?.path) return;
|
if (!node.isDir || node.path === workspace.node?.path) return;
|
||||||
explore(node.path);
|
explore(node.path);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const copyCommand = async (command: string) => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(command);
|
||||||
|
push(t("Command copied to the clipboard", "命令已复制到剪贴板"), "success");
|
||||||
|
} catch {
|
||||||
|
push(t(`Copy failed: ${command}`, `复制失败:${command}`), "danger");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const parent = workspace.node ? parentDirectory(workspace.node.path) : null;
|
const parent = workspace.node ? parentDirectory(workspace.node.path) : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
@ -180,6 +212,32 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{workspace.cached ? (
|
||||||
|
<div className="storage-fresh">
|
||||||
|
<TimerReset size={13} />
|
||||||
|
<span>
|
||||||
|
{t(
|
||||||
|
`Instant open · cached measurement${
|
||||||
|
workspace.measuredAtMs
|
||||||
|
? ` · taken ${agoLabel(workspace.measuredAtMs, lang)}`
|
||||||
|
: ""
|
||||||
|
}`,
|
||||||
|
`秒开 · 缓存数据${
|
||||||
|
workspace.measuredAtMs
|
||||||
|
? ` · 上次测量 ${agoLabel(workspace.measuredAtMs, lang)}`
|
||||||
|
: ""
|
||||||
|
}`,
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => void workspace.explore(workspace.node?.path, true)}
|
||||||
|
>
|
||||||
|
{t("Re-measure", "重新测量")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{children.length > 0 ? (
|
{children.length > 0 ? (
|
||||||
<>
|
<>
|
||||||
<div className="storage-map" aria-label={t("Folder distribution", "文件夹占比")}>
|
<div className="storage-map" aria-label={t("Folder distribution", "文件夹占比")}>
|
||||||
|
|
@ -197,10 +255,10 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
<p className="storage-folded">
|
<p className="storage-folded">
|
||||||
{t(
|
{t(
|
||||||
`${workspace.node.folded} smaller folders (${formatBytes(
|
`${workspace.node.folded} smaller folders (${formatBytes(
|
||||||
workspace.node.folded_size,
|
workspace.node.foldedSize,
|
||||||
)}) are folded into the remainder.`,
|
)}) are folded into the remainder.`,
|
||||||
`${workspace.node.folded} 个较小文件夹(${formatBytes(
|
`${workspace.node.folded} 个较小文件夹(${formatBytes(
|
||||||
workspace.node.folded_size,
|
workspace.node.foldedSize,
|
||||||
)})已合并显示。`,
|
)})已合并显示。`,
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
|
|
@ -213,7 +271,7 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
<button
|
<button
|
||||||
key={`${child.path}-${index}`}
|
key={`${child.path}-${index}`}
|
||||||
className={`storage-child ${
|
className={`storage-child ${
|
||||||
child.is_dir && child.path !== workspace.node?.path
|
child.isDir && child.path !== workspace.node?.path
|
||||||
? "is-navigable"
|
? "is-navigable"
|
||||||
: ""
|
: ""
|
||||||
}`}
|
}`}
|
||||||
|
|
@ -221,7 +279,7 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
>
|
>
|
||||||
<span className={`storage-child-dot tone-${BAR_TONES[index % BAR_TONES.length]}`} />
|
<span className={`storage-child-dot tone-${BAR_TONES[index % BAR_TONES.length]}`} />
|
||||||
<span className="storage-child-icon">
|
<span className="storage-child-icon">
|
||||||
{child.is_dir ? <FolderOpen size={19} /> : <FileArchive size={19} />}
|
{child.isDir ? <FolderOpen size={19} /> : <FileArchive size={19} />}
|
||||||
</span>
|
</span>
|
||||||
<span className="storage-child-copy">
|
<span className="storage-child-copy">
|
||||||
<strong>{basename(child.path)}</strong>
|
<strong>{basename(child.path)}</strong>
|
||||||
|
|
@ -256,7 +314,7 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
>
|
>
|
||||||
<ExternalLink size={14} />
|
<ExternalLink size={14} />
|
||||||
</span>
|
</span>
|
||||||
{child.is_dir && child.path !== workspace.node?.path ? (
|
{child.isDir && child.path !== workspace.node?.path ? (
|
||||||
<ChevronRight size={15} />
|
<ChevronRight size={15} />
|
||||||
) : null}
|
) : null}
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -356,6 +414,66 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{insights && insights.length > 0 ? (
|
||||||
|
<section className="storage-insights">
|
||||||
|
<SectionTitle
|
||||||
|
title={t("Hidden space hogs", "隐藏的吃空间大户")}
|
||||||
|
subtitle={t(
|
||||||
|
"Things a folder scan never shows you — measured just now.",
|
||||||
|
"文件夹扫描永远看不到的占用 — 刚刚测量过。",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<div className="storage-insight-list">
|
||||||
|
{insights.map((insight) => (
|
||||||
|
<div className="storage-insight" key={insight.id}>
|
||||||
|
<span className="storage-insight-icon">
|
||||||
|
<Lightbulb size={16} />
|
||||||
|
</span>
|
||||||
|
<span className="storage-insight-copy">
|
||||||
|
<strong>{insight.title}</strong>
|
||||||
|
<small title={insight.path}>{shortPath(insight.path, 68)}</small>
|
||||||
|
<small className="storage-insight-hint">{insight.hint}</small>
|
||||||
|
</span>
|
||||||
|
<span className="storage-insight-size">
|
||||||
|
{insight.size > 0 ? formatBytes(insight.size) : "—"}
|
||||||
|
</span>
|
||||||
|
<span className="storage-insight-acts">
|
||||||
|
{insight.path ? (
|
||||||
|
<button
|
||||||
|
className="row-reveal"
|
||||||
|
title={t("Show in Explorer", "在资源管理器中显示")}
|
||||||
|
onClick={() => reveal(insight.path)}
|
||||||
|
>
|
||||||
|
<ExternalLink size={14} />
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{insight.action === "cleanable" ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="storage-insight-cta"
|
||||||
|
onClick={() => explore(insight.path)}
|
||||||
|
>
|
||||||
|
{t("Inspect", "查看")}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
{insight.action === "command" && insight.command ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="storage-insight-cta"
|
||||||
|
title={insight.command}
|
||||||
|
onClick={() => void copyCommand(insight.command!)}
|
||||||
|
>
|
||||||
|
<Copy size={13} />
|
||||||
|
{t("Copy command", "复制命令")}
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{!workspace.node && !workspace.exploring ? (
|
{!workspace.node && !workspace.exploring ? (
|
||||||
<button className="storage-start" onClick={() => explore(null)}>
|
<button className="storage-start" onClick={() => explore(null)}>
|
||||||
<span>
|
<span>
|
||||||
|
|
|
||||||
451
src/styles.css
451
src/styles.css
|
|
@ -6231,3 +6231,454 @@ html.widget-mode body {
|
||||||
font-size: 12.5px;
|
font-size: 12.5px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Mole-inspired interaction batch ─────────────────────────────── */
|
||||||
|
|
||||||
|
/* A① live counters ride inside the progress card. */
|
||||||
|
.progress-live {
|
||||||
|
margin-top: 4px;
|
||||||
|
color: var(--nex-primary);
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
font-weight: var(--nex-weight-semibold);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A② category skeletons filling live during the scan. */
|
||||||
|
.space-live-cats {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 2px 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-live-cat {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
padding: 6px 11px;
|
||||||
|
border: 1px solid var(--nex-line);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: rgba(255, 255, 255, 0.72);
|
||||||
|
animation: live-cat-in 0.25s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes live-cat-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(4px);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-live-cat-name {
|
||||||
|
color: #42505e;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
font-weight: var(--nex-weight-semibold);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-live-cat-cnt {
|
||||||
|
color: #aab4c0;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-live-cat b {
|
||||||
|
color: #5a6776;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A③ dormancy chips: green means "nobody has touched this in months". */
|
||||||
|
.space-rule-dormant {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 1px 8px;
|
||||||
|
border: 1px solid #bfe0c4;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: rgba(88, 170, 98, 0.08);
|
||||||
|
color: #4b8a55;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-item-meta.is-dormant {
|
||||||
|
border-color: #bfe0c4;
|
||||||
|
color: #4b8a55;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* B3 evidence chain: trigger button + the judgement panel it opens. */
|
||||||
|
.space-item-evidence {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 1px 9px;
|
||||||
|
border: 1px dashed #c3ccd8;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: none;
|
||||||
|
color: #6c7a87;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-item-evidence:hover {
|
||||||
|
border-style: solid;
|
||||||
|
color: var(--nex-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-item-evidence.is-warn {
|
||||||
|
border-color: #e4c08b;
|
||||||
|
color: #b3854d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence {
|
||||||
|
margin: 0 16px 10px 74px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border: 1px solid #e4ecd6;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: rgba(243, 249, 238, 0.8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence strong {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
color: #4b6a50;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence ul {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence li {
|
||||||
|
color: #5f7161;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence li.is-ok::marker {
|
||||||
|
color: #69a873;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence li.is-warn {
|
||||||
|
color: #a3672f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-evidence li.is-warn::marker {
|
||||||
|
color: #d69a4a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A④ inline confirm strip replacing the modal for low-risk runs. */
|
||||||
|
.space-inline-confirm {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 7px 13px;
|
||||||
|
border: 1px solid #bfe0c4;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: linear-gradient(90deg, rgba(88, 170, 98, 0.12), rgba(88, 170, 98, 0.05));
|
||||||
|
color: #3f7a49;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-inline-confirm > span {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-inline-confirm b {
|
||||||
|
font-size: var(--nex-text-2xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.space-inline-confirm small {
|
||||||
|
color: #6f9a76;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* B1 preflight audit panel inside the confirm modal. */
|
||||||
|
.confirm-preflight {
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid var(--nex-line);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: rgba(255, 255, 255, 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-preflight summary {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
color: #4b8a55;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
cursor: pointer;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-preflight summary::-webkit-details-marker {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-preflight ul {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
margin: 8px 0 0;
|
||||||
|
padding-left: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-preflight li {
|
||||||
|
color: #a3672f;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-preflight li code {
|
||||||
|
margin-right: 6px;
|
||||||
|
color: #6c7a87;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-preflight p {
|
||||||
|
margin: 7px 0 0;
|
||||||
|
color: #909fad;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A⑦ skipped items grouped by reason, each with its next step. */
|
||||||
|
.result-skipped {
|
||||||
|
margin-top: 18px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
border: 1px solid #efe3cc;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: rgba(255, 252, 244, 0.9);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skipped-head {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
color: #6c7a87;
|
||||||
|
font-size: var(--nex-text-2xs);
|
||||||
|
font-weight: var(--nex-weight-semibold);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group {
|
||||||
|
padding: 9px 0;
|
||||||
|
border-top: 1px dashed #efe3cc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group:first-of-type {
|
||||||
|
border-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
color: #42505e;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-title span {
|
||||||
|
padding: 0 7px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: rgba(144, 159, 173, 0.14);
|
||||||
|
color: #7d8a99;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group ul {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
margin: 6px 0;
|
||||||
|
padding-left: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group li {
|
||||||
|
color: #7d8a99;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group li code {
|
||||||
|
margin-right: 8px;
|
||||||
|
color: #5a6776;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group li small {
|
||||||
|
color: #b3a688;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-group li.more {
|
||||||
|
list-style: none;
|
||||||
|
color: #aab4c0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-foot {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.result-skip-foot small {
|
||||||
|
color: #909fad;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A⑥ storage size-cache freshness line. */
|
||||||
|
.storage-fresh {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
margin: 6px 0 2px;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: rgba(47, 107, 255, 0.06);
|
||||||
|
color: #5c748f;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-fresh button {
|
||||||
|
margin-left: auto;
|
||||||
|
padding: 2px 10px;
|
||||||
|
border: 1px solid rgba(47, 107, 255, 0.35);
|
||||||
|
border-radius: 99px;
|
||||||
|
background: none;
|
||||||
|
color: var(--nex-primary);
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-fresh button:hover {
|
||||||
|
background: rgba(47, 107, 255, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A⑤ hidden space hogs. */
|
||||||
|
.storage-insights {
|
||||||
|
margin-top: 26px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-list {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border: 1px solid var(--nex-line);
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--nex-paper);
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-icon {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: rgba(214, 154, 74, 0.12);
|
||||||
|
color: #b3854d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-copy {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-copy strong {
|
||||||
|
color: #405d77;
|
||||||
|
font-size: var(--nex-text-2xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-copy small {
|
||||||
|
overflow: hidden;
|
||||||
|
color: #909fad;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-hint {
|
||||||
|
color: #7d8a99;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-size {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
color: #5a6776;
|
||||||
|
font-size: var(--nex-text-2xs);
|
||||||
|
font-weight: var(--nex-weight-semibold);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-acts {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-cta {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
padding: 4px 11px;
|
||||||
|
border: 1px solid rgba(47, 107, 255, 0.35);
|
||||||
|
border-radius: 99px;
|
||||||
|
background: none;
|
||||||
|
color: var(--nex-primary);
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-insight-cta:hover {
|
||||||
|
background: rgba(47, 107, 255, 0.08);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* B2 whitelist consumption audit. */
|
||||||
|
.whitelist-audit-bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
padding: 7px 11px;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: rgba(47, 107, 255, 0.05);
|
||||||
|
color: #5c748f;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.whitelist-audit-bar > span {
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.whitelist-audit-chip {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 1px 8px;
|
||||||
|
border-radius: 99px;
|
||||||
|
font-size: var(--nex-text-3xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.whitelist-audit-chip.is-live {
|
||||||
|
border: 1px solid #bfe0c4;
|
||||||
|
background: rgba(88, 170, 98, 0.08);
|
||||||
|
color: #4b8a55;
|
||||||
|
}
|
||||||
|
|
||||||
|
.whitelist-audit-chip.is-dead {
|
||||||
|
border: 1px solid #e2d3e6;
|
||||||
|
background: rgba(150, 110, 170, 0.08);
|
||||||
|
color: #8a6a99;
|
||||||
|
}
|
||||||
|
|
|
||||||
35
src/types.ts
35
src/types.ts
|
|
@ -43,6 +43,11 @@ export interface CleanupItem {
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
lock: LockReason | null;
|
lock: LockReason | null;
|
||||||
note: string | null;
|
note: string | null;
|
||||||
|
/** Seconds since the newest last-write inside the item (A③). */
|
||||||
|
lastWriteSecs?: number | null;
|
||||||
|
fileCount?: number;
|
||||||
|
/** Machine tokens for the B3 evidence panel ("lock:package-lock.json"). */
|
||||||
|
evidence?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ScanResult {
|
export interface ScanResult {
|
||||||
|
|
@ -69,7 +74,7 @@ export interface DeleteResult {
|
||||||
export interface JobProgress {
|
export interface JobProgress {
|
||||||
jobId: string;
|
jobId: string;
|
||||||
kind: string;
|
kind: string;
|
||||||
event: "phase" | "tick" | "note" | "warning" | "deleted" | "bucket";
|
event: "phase" | "tick" | "note" | "warning" | "deleted" | "bucket" | "metered";
|
||||||
phase: string | null;
|
phase: string | null;
|
||||||
detail: string | null;
|
detail: string | null;
|
||||||
done: number | null;
|
done: number | null;
|
||||||
|
|
@ -249,14 +254,38 @@ export interface StorageNode {
|
||||||
allocated: number;
|
allocated: number;
|
||||||
files: number;
|
files: number;
|
||||||
dirs: number;
|
dirs: number;
|
||||||
is_dir: boolean;
|
isDir: boolean;
|
||||||
readable: boolean;
|
readable: boolean;
|
||||||
children: StorageNode[];
|
children: StorageNode[];
|
||||||
folded: number;
|
folded: number;
|
||||||
folded_size: number;
|
foldedSize: number;
|
||||||
complete: boolean;
|
complete: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** storage_explore now answers with freshness metadata (A⑥ size cache). */
|
||||||
|
export interface ExploreResult {
|
||||||
|
node: StorageNode;
|
||||||
|
cached: boolean;
|
||||||
|
measuredAtMs: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hidden-space insight row (A⑤, Mole overview idiom). */
|
||||||
|
export interface SpaceInsight {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
path: string;
|
||||||
|
size: number;
|
||||||
|
action: "cleanable" | "command" | "external" | "info";
|
||||||
|
command: string | null;
|
||||||
|
hint: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** cleanup_preflight verdict (B1 last-second re-check). */
|
||||||
|
export interface PreflightResult {
|
||||||
|
checked: number;
|
||||||
|
blocked: { path: string; reason: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface LargestFile {
|
export interface LargestFile {
|
||||||
path: string;
|
path: string;
|
||||||
logical: number;
|
logical: number;
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue