diff --git a/crates/squid-cli/src/main.rs b/crates/squid-cli/src/main.rs index 38f535f..c2c59ec 100644 --- a/crates/squid-cli/src/main.rs +++ b/crates/squid-cli/src/main.rs @@ -594,7 +594,7 @@ fn with_progress( ), ); } - Event::Bucket { .. } | Event::Done(_) => {} + Event::Bucket { .. } | Event::Metered { .. } | Event::Done(_) => {} } } if stop_now { diff --git a/crates/squid-core/src/fs.rs b/crates/squid-core/src/fs.rs index d790c0e..4dcc08d 100644 --- a/crates/squid-core/src/fs.rs +++ b/crates/squid-core/src/fs.rs @@ -30,6 +30,8 @@ pub struct SizeInfo { pub files: u64, pub dirs: u64, pub unreadable: u32, + /// Newest last-modified seen while walking (unix seconds). `0` = unknown. + pub newest_write: u64, } impl SizeInfo { @@ -56,6 +58,7 @@ impl SizeInfo { self.files += other.files; self.dirs += other.dirs; self.unreadable += other.unreadable; + self.newest_write = self.newest_write.max(other.newest_write); } /// "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() { info.files += 1; info.logical += Bytes(meta.len()); + info.newest_write = mtime_secs(&meta); return info; } match kind { @@ -214,6 +218,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info.files += 1; info.logical += Bytes(meta.len()); info.allocated += Bytes(allocated_bytes(path, &meta)); + info.newest_write = mtime_secs(&meta); return info; } ItemKind::Path | ItemKind::Contents => {} @@ -222,6 +227,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info.files += 1; info.logical += Bytes(meta.len()); info.allocated += Bytes(allocated_bytes(path, &meta)); + info.newest_write = mtime_secs(&meta); return info; } @@ -251,6 +257,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { info.files += 1; info.logical += Bytes(meta.len()); info.allocated += Bytes(allocated_bytes(entry.path(), &meta)); + info.newest_write = info.newest_write.max(mtime_secs(&meta)); } Err(_) => info.unreadable += 1, } @@ -261,6 +268,14 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo { 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. /// `Path` for folders (and anything that should be removed recursively), /// `File` for plain files and symlinks. @@ -280,7 +295,7 @@ pub fn kind_of(path: &Path) -> crate::model::ItemKind { pub fn measure_all( targets: &[(PathBuf, ItemKind)], cancel: &CancelToken, - on_unit: impl Fn(usize, &SizeInfo) + Send + Sync, + on_unit: impl Fn(usize, usize, &SizeInfo) + Send + Sync, ) -> Vec { let pool = rayon::ThreadPoolBuilder::new() .num_threads(measure_threads()) @@ -297,14 +312,18 @@ pub fn measure_all( let results: Vec = pool.install(|| { targets .par_iter() - .map(|(path, kind)| { + .enumerate() + .map(|(index, (path, kind))| { if cancel.is_cancelled() { cancelled.store(true, Ordering::Relaxed); return SizeInfo::default(); } let info = measure(path, *kind); - let idx = done.fetch_add(1, Ordering::Relaxed) as usize; - emit(idx, &info); + let completed = done.fetch_add(1, Ordering::Relaxed) as usize + 1; + // (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 }) .collect() @@ -369,6 +388,7 @@ pub fn remove_item_with( files: 0, dirs: 0, unreadable: 0, + newest_write: 0, }; Ok(freed.on_disk().max(Bytes::ZERO)) } diff --git a/crates/squid-core/src/model.rs b/crates/squid-core/src/model.rs index 722e6a6..5c163cd 100644 --- a/crates/squid-core/src/model.rs +++ b/crates/squid-core/src/model.rs @@ -165,6 +165,21 @@ pub struct CleanupItem { /// stale or hand-edited item can never escape its sandbox. #[serde(default)] pub anchors: Vec, + /// 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, + /// 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:`, `record:`, `record-missing`, + /// `modified:`, `git:ignored|untracked|none|tracked`, `age:`, + /// `busy`. The UI renders each token as a ✓/! line in a detail panel. + #[serde(default)] + pub evidence: Vec, } impl CleanupItem { @@ -187,6 +202,9 @@ impl CleanupItem { lock: lock_default(kind), note: None, anchors: Vec::new(), + last_write_secs: None, + file_count: 0, + evidence: Vec::new(), } } diff --git a/crates/squid-core/src/progress.rs b/crates/squid-core/src/progress.rs index 29cd704..f6ac574 100644 --- a/crates/squid-core/src/progress.rs +++ b/crates/squid-core/src/progress.rs @@ -30,6 +30,12 @@ pub enum Event { total: Bytes, 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 { path: PathBuf, freed: Bytes, diff --git a/crates/squid-core/src/settings.rs b/crates/squid-core/src/settings.rs index af534ca..4e58e61 100644 --- a/crates/squid-core/src/settings.rs +++ b/crates/squid-core/src/settings.rs @@ -161,6 +161,13 @@ impl Settings { .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 { + 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 { if self.whitelist.is_empty() { return false; diff --git a/crates/squid-engine/src/analyze.rs b/crates/squid-engine/src/analyze.rs index 2be4723..32a401f 100644 --- a/crates/squid-engine/src/analyze.rs +++ b/crates/squid-engine/src/analyze.rs @@ -16,6 +16,7 @@ use std::path::{Path, PathBuf}; const CHILD_CAP: usize = 512; #[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct Node { pub path: PathBuf, pub logical: Bytes, @@ -196,9 +197,9 @@ pub fn expand( }) .collect(); 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( - index as u64 + 1, + completed as u64, Some(targets.len() as u64), targets.get(index).map(|(path, _)| path.clone()), ); diff --git a/crates/squid-engine/src/assets.rs b/crates/squid-engine/src/assets.rs new file mode 100644 index 0000000..2abab57 --- /dev/null +++ b/crates/squid-engine/src/assets.rs @@ -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 { + 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()); + } +} diff --git a/crates/squid-engine/src/clean.rs b/crates/squid-engine/src/clean.rs index caba765..b2191d8 100644 --- a/crates/squid-engine/src/clean.rs +++ b/crates/squid-engine/src/clean.rs @@ -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 { measure(engine, &mut report, progress, cancel)?; } @@ -201,7 +215,7 @@ fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec rules.into_iter().map(PreparedRule::new).collect() } -fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option { +pub fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option { if rule.skip_if_running.is_empty() { return None; } @@ -334,15 +348,42 @@ fn measure( .iter() .map(|item| (item.path.clone(), item.kind)) .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 = measure_all(&targets, cancel, |index, _info| { - progress.tick( - index as u64 + 1, - Some(targets.len() as u64), - targets.get(index).map(|(path, _)| path.clone()), - ); - }); + // Cumulative counters for the live status line; the callback runs on + // rayon worker threads, hence the mutex. Emissions are throttled to + // ~10/s so the IPC stays a whisper while the walk screams. + let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now())); + let results: Vec = + 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() { return Err(SquidError::Other( "measurement returned an unexpected number of results".into(), @@ -351,6 +392,17 @@ fn measure( for (item, info) in report.items.iter_mut().zip(results) { item.size = info.logical; 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() { item.note = Some(format!("{} entries unreadable", info.unreadable)); } else if info.files > 0 && item.note.is_none() { diff --git a/crates/squid-engine/src/insights.rs b/crates/squid-engine/src/insights.rs new file mode 100644 index 0000000..e2a9288 --- /dev/null +++ b/crates/squid-engine/src/insights.rs @@ -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, + pub hint: String, +} + +fn home() -> Option { + 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 { + 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")); + } + } +} diff --git a/crates/squid-engine/src/lib.rs b/crates/squid-engine/src/lib.rs index 63a24a8..704693a 100644 --- a/crates/squid-engine/src/lib.rs +++ b/crates/squid-engine/src/lib.rs @@ -12,15 +12,17 @@ //! and the safety net impossible to bypass. pub mod analyze; +pub mod assets; pub mod clean; pub mod delete; +pub mod insights; pub mod purge; pub mod uninstall; pub mod updates; use globset::GlobMatcher; use squid_core::settings::Settings; -use squid_core::{CleanupItem, SafetyPolicy}; +use squid_core::{CleanupItem, SafetyPolicy, ScanReport}; use squid_platform::Platform; use squid_rules::RuleSet; use std::path::Path; @@ -121,6 +123,13 @@ impl Engine { /// Why this item cannot be deleted, if it cannot. Rules pass the anchor they /// declared; everything else falls back to the default anchors. pub fn block_reason(&self, item: &CleanupItem) -> Option { + // 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() { squid_core::fs::default_anchors() } else { @@ -131,6 +140,107 @@ impl Engine { } 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 = 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 { + (!item.path.exists() && !std::fs::symlink_metadata(&item.path).is_ok()) + .then(|| item.path.clone()) } /// True when the process may touch system-owned paths. diff --git a/crates/squid-engine/src/purge.rs b/crates/squid-engine/src/purge.rs index b0909c1..dddacc0 100644 --- a/crates/squid-engine/src/purge.rs +++ b/crates/squid-engine/src/purge.rs @@ -222,11 +222,13 @@ pub fn scan( ); 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 { - let project_root = match project_with_git(&candidate.path) { - Some(dir) => dir, - None => candidate.project.clone(), - }; + let project_root = evidence_project.clone(); let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) { Some((_, state)) => *state, None => { @@ -237,14 +239,22 @@ pub fn scan( }; match state { GitState::Tracked => { + item.evidence.push("git:tracked".into()); item = item .locked(LockReason::Protected) .with_note("tracked by git — pass --all to delete anyway"); } - GitState::Ignored => item.note = Some("git-ignored build output".into()), - GitState::Untracked => item.note = Some("untracked by git".into()), + GitState::Ignored => { + 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 => { - let age = age_days(&candidate.path); + item.evidence.push("git:none".into()); + let age = evidence_age; match age { Some(age) if age >= min_age as f64 => { item.note = Some(format!("no git repo · {:.0} days old", age)); @@ -288,6 +298,7 @@ pub fn scan( .locked(LockReason::NotOwned) .with_note("owned by another user"); } + collect_evidence(&mut item, &evidence_project, evidence_age); report.items.push(item); } @@ -310,6 +321,77 @@ pub fn scan( 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 { + 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) { + 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 { let category = if candidate.name.eq_ignore_ascii_case("DerivedData") { Category::Developer @@ -554,9 +636,31 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) { return; } 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( - index as u64 + 1, + completed as u64, Some(targets.len() as u64), 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) { item.size = info.logical; 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 { let suffix = format!("{} entries unreadable", info.unreadable); item.note = Some(match item.note.take() { diff --git a/crates/squid-engine/src/uninstall.rs b/crates/squid-engine/src/uninstall.rs index fc4db77..2f629c4 100644 --- a/crates/squid-engine/src/uninstall.rs +++ b/crates/squid-engine/src/uninstall.rs @@ -248,9 +248,9 @@ fn measure( .iter() .map(|item| (item.path.clone(), item.kind)) .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( - index as u64 + 1, + completed as u64, Some(targets.len() as u64), targets.get(index).map(|(path, _)| path.clone()), ); diff --git a/crates/squid-platform/src/permissions.rs b/crates/squid-platform/src/permissions.rs index 8f41d9e..41d3148 100644 --- a/crates/squid-platform/src/permissions.rs +++ b/crates/squid-platform/src/permissions.rs @@ -266,21 +266,104 @@ mod windows { list: &str, value_name: &str, enabled: bool, - ) -> Result<(), String> { + ) -> std::io::Result<()> { let hive = RegKey::predef(if machine { HKEY_LOCAL_MACHINE } else { HKEY_CURRENT_USER }); - let (key, _) = hive - .create_subkey(format!(r"{base}\Explorer\StartupApproved\{list}")) - .map_err(registry_error)?; + // Minimal rights only: several security suites (and locked-down + // profiles) deny KEY_ALL_ACCESS-style opens on the startup trees even + // 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 { bytes: approved_marker(enabled), vtype: RegType::REG_BINARY, }; 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::>() + .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 { @@ -1455,7 +1538,7 @@ mod windows { } else { name.to_string() }; - write_approved(machine, &base, list, &marker, enabled) + flip_approved(machine, &base, list, &marker, enabled) } "folder" => { let file = Path::new(rest) @@ -1463,7 +1546,7 @@ mod windows { .map(|n| n.to_string_lossy().to_string()) .ok_or_else(|| "启动文件夹项目路径无效".to_string())?; let machine = rest.contains("ProgramData"); - write_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled) + flip_approved(machine, CURRENT_VERSION, "StartupFolder", &file, enabled) } "task" => { use std::os::windows::process::CommandExt; @@ -1478,23 +1561,79 @@ mod windows { .output() .map_err(|error| format!("无法调用 schtasks:{error}"))?; if output.status.success() { - Ok(()) - } else { - Err(format!( + return Ok(()); + } + 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() - )) + )); } + run_elevated( + "schtasks.exe", + &[ + "/Change".to_string(), + "/TN".to_string(), + rest.to_string(), + if enabled { "/Enable" } else { "/Disable" }.to_string(), + ], + )?; + Ok(()) } "svc" => { // 开 = Automatic(2),关 = Manual(3):保留按需启动能力, // 与管家的“禁止开机自启”语义一致;HKLM 写入需要管理员。 - let key = RegKey::predef(HKEY_LOCAL_MACHINE) - .open_subkey_with_flags(format!(r"{SERVICES_KEY}\{rest}"), KEY_READ | KEY_WRITE) - .map_err(registry_error)?; - key.set_value("Start", &(if enabled { 2u32 } else { 3u32 })) - .map_err(registry_error)?; - let _ = service_control(rest, if enabled { "auto" } else { "demand" }); + let start = if enabled { 2u32 } else { 3u32 }; + let key_path = format!(r"{SERVICES_KEY}\{rest}"); + let direct = (|| -> std::io::Result<()> { + let key = RegKey::predef(HKEY_LOCAL_MACHINE) + .open_subkey_with_flags(&key_path, KEY_READ | KEY_WRITE)?; + 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::("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(()) } _ => Err("未知的启动项来源".to_string()), @@ -1913,9 +2052,56 @@ mod windows { #[cfg(test)] mod tests { use super::{ - clean_module_path, exe_from_command, friendly_program_name, has_cjk, - is_placeholder_label, module_folder_name, parse_csv_line, task_settings_enabled, + approved_enabled, clean_module_path, exe_from_command, friendly_program_name, has_cjk, + 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] fn command_paths_survive_quotes_and_arguments() { diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs index af1dda3..0cd2b6c 100644 --- a/crates/squid-tui/src/app.rs +++ b/crates/squid-tui/src/app.rs @@ -889,6 +889,7 @@ impl App { }; panel.buckets.insert(category, (total, count)); } + Event::Metered { .. } => {} Event::Deleted { path, freed } => { self.push_log(format!( "removed {} ({})", diff --git a/release/0.1.10/RELEASE_NOTES.md b/release/0.1.10/RELEASE_NOTES.md index 23cb82b..4a8e4bb 100644 --- a/release/0.1.10/RELEASE_NOTES.md +++ b/release/0.1.10/RELEASE_NOTES.md @@ -1,6 +1,31 @@ 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 里的安装包 (微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。 只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件 @@ -21,6 +46,10 @@ Squid 0.1.10 更新说明 开着时 Squid 全家 CPU 占用接近 0%。 修复 +- 权限管理:修复开机启动项开关点了没反应 / 立刻弹回的问题——所有启动项 + (当前用户、所有用户、32 位、启动文件夹、服务、计划任务)统一改用最小 + 注册表权限写入,遇到「拒绝访问」自动发起一次系统管理员授权(UAC)后重试 + 并回读核实;开关失败时现在有红色气泡提示原因(此前只在页面顶部一闪而过)。 - 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题 出现一次,子行文字与标题对齐)。 - 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有 diff --git a/release/0.1.10/SHA256SUMS.txt b/release/0.1.10/SHA256SUMS.txt index 711db3e..ed2637e 100644 --- a/release/0.1.10/SHA256SUMS.txt +++ b/release/0.1.10/SHA256SUMS.txt @@ -1,2 +1,2 @@ -046b0e2ad7e3a9dd8558d7ff673d5bd8b4d78c8337055847f7a789003cc31ef5 Squid-Setup-0.1.10-win-x64.exe -587c70cc7bbbd48f29ee659baf86e30de16c3c13d9aa02c9c0b188f615d0027d Squid-0.1.10-portable-win-x64.zip \ No newline at end of file +1ddd17bd66a982cfdfbf15e187c213ef005619b7f6fee16ffc72dce47f105705 Squid-Setup-0.1.10-win-x64.exe +8e814c57ebb7fb6f887abfd2fd2290ad75ba0b8dc7e9694ff747fb530d19e59e Squid-0.1.10-portable-win-x64.zip diff --git a/release/0.1.10/Squid-0.1.10-portable-win-x64.zip b/release/0.1.10/Squid-0.1.10-portable-win-x64.zip new file mode 100644 index 0000000..b310e80 Binary files /dev/null and b/release/0.1.10/Squid-0.1.10-portable-win-x64.zip differ diff --git a/release/0.1.10/Squid-Setup-0.1.10-win-x64.exe b/release/0.1.10/Squid-Setup-0.1.10-win-x64.exe index 5d87ea7..a8ab561 100644 Binary files a/release/0.1.10/Squid-Setup-0.1.10-win-x64.exe and b/release/0.1.10/Squid-Setup-0.1.10-win-x64.exe differ diff --git a/release/0.1.10/squid-update.json b/release/0.1.10/squid-update.json index 10605a1..9088780 100644 --- a/release/0.1.10/squid-update.json +++ b/release/0.1.10/squid-update.json @@ -1,13 +1,13 @@ { "schema": 1, "version": "0.1.10", - "date": "2026-11-19", - "notes": "Squid 0.1.10\n\n新增\n- 清理新增「升级安装包」分类:找出应用升级完成后留在 AppData 里的安装包\n (微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。\n 只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件\n 不会被误删;应用正在运行时相关安装包自动锁定。删除确认时会提示升级包数量\n 与大小,可一键「跳过升级包,只删其余」。\n- 桌面小工具新增「CPU」面板:总体占用率历史曲线 + 整行渐变占用柱,一根柱对应\n 一个逻辑核心;柱色随占用率在绿→黄→橙→红之间连续渐变(含柱内纵向微渐变),\n 悬停显示「核心 N: xx%」(编号与任务管理器一致从 0 开始);核心较多时柱宽自动\n 收窄。管理页与桌面设置弹层可独立开关该面板。\n\n优化\n- 桌面常驻 CPU 占用大幅下降(实测本机构从约 8.5% 全机总占用降至 0.2%):\n 小工具改用轻量采样(跳过全机逐进程枚举,那是旧版每秒最贵的一步)、两个\n 窗口共享同一次采样、小工具折叠或主窗口收进托盘后完全停止采样。实时监控\n 页打开时才有完整进程表,功能不受影响。\n- 修复小工具窗口自身的自适应尺寸回环(尺寸→重锚定→再触发自适应无限循环),\n 该回环会让主进程与小工具渲染进程空转互叫并频繁写配置文件;修复后小工具\n 开着时 Squid 全家 CPU 占用接近 0%。\n\n修复\n- 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题出现一次,子行文字与标题对齐)。\n- 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有进入结果列表的派生缓存,点击后视图停留在扫描瞬间);「可选」角标不再遮挡复选框。\n- 权限管理:修复大量启动项/服务显示通用图标的问题——服务壳程序(如微软 Edge 提权服务、电脑管家 qmbsrv、H3C SpaceAgent)自身不含图标资源,现改为回退读取注册表 App Paths、卸载信息 DisplayIcon 与同目录主程序图标。\n- 深度清理:默认检查目录(~/code 等 macOS 风格)在本机全都不存在时不再报\n 「请先选择目录」,自动回退到用户主目录扫描;「要检查的项目目录」旁新增\n 「浏览…」按钮可直接多选文件夹;扫描出错信息此前会被静默吞掉,现在会以\n 红色横幅显示。\n- 托盘交互:左键单击/双击图标 = 直接打开主界面,右键 = 弹出菜单(原先\n 左键也会弹菜单)。\n\n调整\n- 空间清理对齐电脑管家的「清理点」粒度:规则类分类(系统垃圾/日志/浏览器缓存等)展开后先按清理点汇总(如「Windows 更新下载缓存 441 MB · 1 个位置」),点开清理点才显示具体路径;悬停清理点可「忽略」(加入保护名单,可随时撤销)或「查看路径」;受安全策略保护、无法删除的项目默认不再刷屏,折叠为一行说明并提供「仍然显示」;应用正在运行、需要管理员等可操作锁定仍照常显示原因。「回收站 / 项目产物 / 开发文件」保持平铺。\n- 空间清理改版(参照电脑管家布局):取消「分类卡片 + 下方大列表」双层结构,分类即列表、一屏一层;分「已为你默认勾选 / 需要你手动勾选」两区,点击分类行展开该分类子项(再点收起),点击子项整行直接在资源管理器中定位文件位置,只有点小方框才改勾选;顶部常驻「已选中 xxx 可清理文件」汇总条(取消全选/立即清理随时可点)。\n- 「日常清理」与「深度清理」合并为一个「空间清理」页:一次扫描同时检查缓存\n 垃圾与项目构建目录,结果汇总为一份清单。默认只勾选日常清理项,「升级安装\n 包 / 项目产物 / 开发文件」三类为可选(虚线卡片 + 可选角标),勾选后与日常\n 项合并成一次清理。深度扫描目录、文件年龄(3/7/30 天)、Git 保护收进页面\n 顶部设置栏;扫描与删除全程有步骤条与实时进度;侧边栏与托盘菜单同步精简,\n 快捷键重排(Ctrl+2 = 空间清理)。\n- 桌面小工具 Win+D 常驻:按下「显示桌面」后小工具约 2 秒内自动回到桌面\n (窗口保持桌面层:在壁纸与图标之上、其他软件窗口之下;自己关闭/折叠\n 不会把它叫回来)。\n- Windows 上所有「废纸篓」文案改为「回收站」(清理、卸载、历史、设置等随系统\n 名称联动);macOS 仍为「废纸篓」。", + "date": "2026-11-20", + "notes": "Squid 0.1.10 更新说明\n\n新增\n- 空间清理全面对齐专业清理工具的扫描体验(借鉴 Mole):\n · 扫描时实时显示「已统计 12.8 万个文件 · 38.2 GB」滚动计数,进度条在真正\n 完成前最多走到 99%,不再出现「满了但还在转」的错觉;\n · 各分类不再干等:哪个分类先算完就先在扫描界面出现(项数 + 大小);\n · 清理点与文件行显示「12 个月未使用」休眠标签(超过 90 天没再写入的绿色\n 标注),配合大小一起帮你决定删不删;\n · node_modules 等项目产物新增「可删依据」面板:锁文件 / 安装记录 / 有无\n 手工修改 / Git 状态 / 目录年龄逐条列出,被手改过的目录会红色警示;\n · 低风险清理(≤40 项、不含升级包、复核全部通过)不再弹窗,底部绿色\n 确认条一步完成(Esc 取消);含升级包或大批量仍走确认对话框,对话框内\n 新增「刚刚逐路径复核过 N 项」折叠面板,展示删除前的最后一轮锁 / 白名单\n / 应用运行 / 路径消失复核结果;\n · 清理完成后新增「有 N 项本次未处理」分组页:按原因(应用正在运行 /\n 需要管理员 / 已消失 / 白名单 / 受保护)归类,每组给下一步操作按钮;\n · 结果列表可一键「导出清单」,生成 Markdown 文件(含每一项路径、大小、\n 依据与受保护项),方便留档或反馈。\n- 存储空间页新增「隐藏的吃空间大户」:Windows 更新缓存、休眠文件、页面文件、\n WinSxS 组件库、手机备份、90 天前的下载,逐项给出大小与下一步(查看 /\n 复制释放命令);同页文件夹测量结果缓存 10 分钟,秒开时标注「缓存数据 ·\n 上次测量 X 分钟前」并可一键重新测量,删除文件后缓存自动作废。\n- 微信 / QQ 聊天文件、浏览器离线应用数据(IndexedDB)、搜狗词库等「看起来像\n 缓存、实际是你的文件」的目录,现在会以待解锁行出现在扫描结果里并写明原因,\n 引擎在删除层也强制拒删。\n- 设置 → 受保护的位置新增「消费审计」:每条白名单规则标注最近扫描是否命中,\n 从未命中的过期规则一眼可见。\n- 清理新增「升级安装包」分类:找出应用升级完成后留在 AppData 里的安装包\n (微信、企业微信、WPS、网易邮箱等已知应用精确规则 + AppData 启发式扫描)。\n 只匹配安装包形态(exe/msi/zip/7z 等)且放置超过 7 天的文件,微信运行库组件\n 不会被误删;应用正在运行时相关安装包自动锁定。删除确认时会提示升级包数量\n 与大小,可一键「跳过升级包,只删其余」。\n- 桌面小工具新增「CPU」面板:总体占用率历史曲线 + 整行渐变占用柱,一根柱对应\n 一个逻辑核心;柱色随占用率在绿→黄→橙→红之间连续渐变(含柱内纵向微渐变),\n 悬停显示「核心 N: xx%」(编号与任务管理器一致从 0 开始);核心较多时柱宽自动\n 收窄。管理页与桌面设置弹层可独立开关该面板。\n\n优化\n- 桌面常驻 CPU 占用大幅下降(实测本机构从约 8.5% 全机总占用降至 0.2%):\n 小工具改用轻量采样(跳过全机逐进程枚举,那是旧版每秒最贵的一步)、两个\n 窗口共享同一次采样、小工具折叠或主窗口收进托盘后完全停止采样。实时监控\n 页打开时才有完整进程表,功能不受影响。\n- 修复小工具窗口自身的自适应尺寸回环(尺寸→重锚定→再触发自适应无限循环),\n 该回环会让主进程与小工具渲染进程空转互叫并频繁写配置文件;修复后小工具\n 开着时 Squid 全家 CPU 占用接近 0%。\n\n修复\n- 权限管理:修复开机启动项开关点了没反应 / 立刻弹回的问题——所有启动项\n (当前用户、所有用户、32 位、启动文件夹、服务、计划任务)统一改用最小\n 注册表权限写入,遇到「拒绝访问」自动发起一次系统管理员授权(UAC)后重试\n 并回读核实;开关失败时现在有红色气泡提示原因(此前只在页面顶部一闪而过)。\n- 权限管理:开机启动项每个子行不再重复显示软件图标(图标只在软件分组标题\n 出现一次,子行文字与标题对齐)。\n- 空间清理:修复扫描后分类卡片与复选框全部不可点击的问题(勾选状态没有\n 进入结果列表的派生缓存,点击后视图停留在扫描瞬间);「可选」角标不再\n 遮挡复选框。\n- 权限管理:修复大量启动项/服务显示通用图标的问题——服务壳程序(如微软\n Edge 提权服务、电脑管家 qmbsrv、H3C SpaceAgent)自身不含图标资源,\n 现改为回退读取注册表 App Paths、卸载信息 DisplayIcon 与同目录主程序\n 图标,让每一行显示真正的软件图标。\n- 深度清理:默认检查目录(~/code 等 macOS 风格)在本机全都不存在时不再报\n 「请先选择目录」,自动回退到用户主目录扫描;「要检查的项目目录」旁新增\n 「浏览…」按钮可直接多选文件夹;扫描出错信息此前会被静默吞掉,现在会以\n 红色横幅显示。\n- 托盘交互:左键单击/双击图标 = 直接打开主界面,右键 = 弹出菜单(原先\n 左键也会弹菜单)。\n\n调整\n- 空间清理对齐电脑管家的「清理点」粒度:规则类分类(系统垃圾 / 日志 /\n 浏览器缓存等)展开后先按清理点汇总(如「Windows 更新下载缓存 441 MB ·\n 1 个位置」),点开清理点才显示具体路径;悬停清理点可「忽略」(加入保护\n 名单,可随时撤销)或「查看路径」;受安全策略保护、无法删除的项目默认\n 不再刷屏,折叠为一行说明并提供「仍然显示」;应用正在运行、需要管理员\n 等可操作锁定仍照常显示原因。「回收站 / 项目产物 / 开发文件」保持平铺。\n- 空间清理改版(参照电脑管家布局):取消「分类卡片 + 下方大列表」双层\n 结构,分类即列表、一屏一层;分「已为你默认勾选 / 需要你手动勾选」两区,\n 点击分类行展开该分类子项(再点收起),点击子项整行直接在资源管理器中\n 定位文件位置,只有点小方框才改勾选;顶部常驻「已选中 xxx 可清理文件」\n 汇总条(取消全选 / 立即清理随时可点)。\n- 「日常清理」与「深度清理」合并为一个「空间清理」页:一次扫描同时检查缓存\n 垃圾与项目构建目录,结果汇总为一份清单。默认只勾选日常清理项,「升级安装\n 包 / 项目产物 / 开发文件」三类为可选(虚线卡片 + 可选角标),勾选后与日常\n 项合并成一次清理。深度扫描目录、文件年龄(3/7/30 天)、Git 保护收进页面\n 顶部设置栏;扫描与删除全程有步骤条与实时进度;侧边栏与托盘菜单同步精简,\n 快捷键重排(Ctrl+2 = 空间清理)。\n- 桌面小工具 Win+D 常驻:按下「显示桌面」后小工具约 2 秒内自动回到桌面\n (窗口保持桌面层:在壁纸与图标之上、其他软件窗口之下;自己关闭/折叠\n 不会把它叫回来)。\n- Windows 上所有「废纸篓」文案改为「回收站」(清理、卸载、历史、设置等随系统\n 名称联动);macOS 仍为「废纸篓」。", "artifacts": { "windows": { "file": "Squid-Setup-0.1.10-win-x64.exe", - "sha256": "046b0e2ad7e3a9dd8558d7ff673d5bd8b4d78c8337055847f7a789003cc31ef5", - "size": 3580842 + "sha256": "1ddd17bd66a982cfdfbf15e187c213ef005619b7f6fee16ffc72dce47f105705", + "size": 3640983 } } -} \ No newline at end of file +} diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs index 3fc0456..bbf2fef 100644 --- a/src-tauri/src/app.rs +++ b/src-tauri/src/app.rs @@ -35,6 +35,11 @@ pub struct AppState { /// Last light snapshot, so the widget window and the main window polling /// a beat apart share one refresh instead of paying for two. snapshot_cache: Mutex>, + /// 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>, + clean_epoch: std::sync::atomic::AtomicU64, } impl AppState { @@ -44,6 +49,16 @@ impl AppState { .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 { if job_id.trim().is_empty() { 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, 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, }; let _ = app.emit("squid://progress", payload); @@ -213,6 +239,9 @@ pub struct CleanupItemView { selected: bool, lock: Option, note: Option, + last_write_secs: Option, + file_count: u64, + evidence: Vec, } impl From<&CleanupItem> for CleanupItemView { @@ -230,6 +259,9 @@ impl From<&CleanupItem> for CleanupItemView { selected: item.selected, lock: item.lock, 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::().scans.lock() { scans.remove(&scan_id); } + app.state::().invalidate_storage_cache(); Ok(DeleteResultView::from_outcome(outcome)) } @@ -591,6 +624,7 @@ pub async fn purge_delete( if let Ok(mut scans) = app.state::().scans.lock() { scans.remove(&scan_id); } + app.state::().invalidate_storage_cache(); Ok(DeleteResultView::from_outcome(outcome)) } @@ -759,9 +793,24 @@ pub async fn app_uninstall( if let Ok(mut plans) = app.state::().plans.lock() { plans.remove(&plan_id); } + app.state::().invalidate_storage_cache(); 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, +} + +const STORAGE_TTL: std::time::Duration = std::time::Duration::from_secs(600); + #[tauri::command] pub async fn storage_explore( app: AppHandle, @@ -769,7 +818,8 @@ pub async fn storage_explore( path: Option, depth: Option, top: Option, -) -> Result { + force: Option, +) -> Result { let token = app.state::().begin(&job_id)?; let progress = Progress::new(); let reporter = @@ -783,20 +833,114 @@ pub async fn storage_explore( reporter.finish(); 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::(); + 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::().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 || { - analyze::explore( - &root, - depth.unwrap_or(1).clamp(1, 3), - top.unwrap_or(16), - &token, - &progress, - ) + analyze::explore(&root, depth, top, &token, &progress) }) .await .map_err(|error| format!("Storage analysis failed: {error}"))?; reporter.finish(); app.state::().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, + hint: String, +} + +/// Hidden-space insights for the storage page's curated section (A⑤). +#[tauri::command] +pub async fn storage_insights() -> Result, 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, +) -> Result { + let report = app + .state::() + .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::>(), + }) + }) + .await + .map_err(|error| error.to_string())?; + Ok(view) } #[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()) } +/// 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 { + let rows: Vec = tauri::async_runtime::spawn_blocking(|| { + Engine::new() + .audit_whitelist() + .into_iter() + .map(|(pattern, live)| serde_json::json!({ "pattern": pattern, "live": live })) + .collect::>() + }) + .await + .map_err(|error| error.to_string())?; + Ok(serde_json::Value::Array(rows)) +} + #[tauri::command] pub fn history_list(limit: Option) -> Vec { ledger::load_sessions(limit.unwrap_or(60).clamp(1, 500)) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dd1d7fb..8646d15 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -122,12 +122,15 @@ pub fn run() { app::cancel_job, app::cleanup_scan, app::cleanup_delete, + app::cleanup_preflight, app::purge_scan, app::purge_delete, app::apps_scan, app::app_plan, app::app_uninstall, app::storage_explore, + app::storage_insights, + app::write_text_file, app::storage_largest_files, app::system_snapshot, app::stop_process, @@ -136,6 +139,7 @@ pub fn run() { app::settings_save, app::whitelist_add, app::whitelist_remove, + app::whitelist_audit, app::reveal_path, app::open_trash, permissions::permission_status, diff --git a/src/components/ui.tsx b/src/components/ui.tsx index bfda236..67e41ff 100644 --- a/src/components/ui.tsx +++ b/src/components/ui.tsx @@ -274,11 +274,18 @@ export function ProgressCard({ title, onCancel, compact = false, + liveLine, + capAt99 = false, }: { progress: JobProgress | null; title: string; onCancel?: () => void; 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 phase = useMemo(() => { @@ -301,7 +308,9 @@ export function ProgressCard({ const denominator = progress?.total ?? 0; const done = progress?.done ?? 0; 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 || ""; return ( @@ -330,6 +339,11 @@ export function ProgressCard({ > + {liveLine ? ( +
+ {liveLine} +
+ ) : null}
{detail || t("Working safely in the background…", "正在后台安全处理…")}
diff --git a/src/hooks/usePermissionsWorkspace.ts b/src/hooks/usePermissionsWorkspace.ts index ac48ac0..ef8792a 100644 --- a/src/hooks/usePermissionsWorkspace.ts +++ b/src/hooks/usePermissionsWorkspace.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, useState } from "react"; import { api } from "../lib/api"; import { isCancelled, messageFrom } from "../lib/format"; +import { useToast } from "../components/ui"; import type { ManageView, PopupWindowItem } from "../types"; export type PermissionsTab = "startup" | "extensions" | "popup"; @@ -36,6 +37,7 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { const [error, setError] = useState(null); const [closedTotal, setClosedTotal] = useState(0); const [recentClosed, setRecentClosed] = useState<{ process: string; title: string }[]>([]); + const { push } = useToast(); const scan = useCallback(async () => { setScanning(true); @@ -101,12 +103,16 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace { await api.startupSetEnabled(id, enabled); await scan(); } 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 { setBusyId(null); } }, - [scan], + [push, scan], ); const toggleExtension = useCallback( diff --git a/src/hooks/useScanWorkspace.ts b/src/hooks/useScanWorkspace.ts index 9285d85..c6913bc 100644 --- a/src/hooks/useScanWorkspace.ts +++ b/src/hooks/useScanWorkspace.ts @@ -35,6 +35,10 @@ export interface ScanWorkspace { result: ScanResult | null; selected: Set; 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>; scanning: boolean; deleting: boolean; error: string | null; @@ -73,6 +77,10 @@ export function useScanWorkspace( const [result, setResult] = useState(null); const [selected, setSelected] = useState>(new Set()); const [progress, setProgress] = useState(null); + const [stats, setStats] = useState<{ files: number; bytes: number } | null>(null); + const [buckets, setBuckets] = useState< + Partial> + >({}); const [scanning, setScanning] = useState(false); const [deleting, setDeleting] = useState(false); const [error, setError] = useState(null); @@ -94,7 +102,28 @@ export function useScanWorkspace( setError(null); setSummary(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 { const next = kind === "cleanup" @@ -115,6 +144,7 @@ export function useScanWorkspace( if (activeJob.current === id) { setScanning(false); setProgress(null); + setStats(null); setCurrentJob(null); } } @@ -276,6 +306,8 @@ export function useScanWorkspace( result, selected, progress, + stats, + buckets, scanning, deleting, error, diff --git a/src/hooks/useStorageWorkspace.ts b/src/hooks/useStorageWorkspace.ts index 73299f5..d7022de 100644 --- a/src/hooks/useStorageWorkspace.ts +++ b/src/hooks/useStorageWorkspace.ts @@ -1,7 +1,7 @@ import { useCallback, useRef, useState } from "react"; import { api, subscribeJobProgress } from "../lib/api"; import { isCancelled, messageFrom } from "../lib/format"; -import type { JobProgress, LargestFile, StorageNode } from "../types"; +import type { ExploreResult, JobProgress, LargestFile, StorageNode } from "../types"; function jobId(): string { return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`; @@ -9,12 +9,15 @@ function jobId(): string { export interface StorageWorkspace { node: StorageNode | null; + /** Freshness of the current node (A⑥ size cache). */ + cached: boolean; + measuredAtMs: number | null; files: LargestFile[]; progress: JobProgress | null; exploring: boolean; scanningFiles: boolean; error: string | null; - explore: (path?: string | null) => Promise; + explore: (path?: string | null, force?: boolean) => Promise; largestFiles: (path: string) => Promise; cancel: () => Promise; clearError: () => void; @@ -23,6 +26,8 @@ export interface StorageWorkspace { export function useStorageWorkspace(): StorageWorkspace { const [node, setNode] = useState(null); + const [cached, setCached] = useState(false); + const [measuredAtMs, setMeasuredAtMs] = useState(null); const [files, setFiles] = useState([]); const [progress, setProgress] = useState(null); const [exploring, setExploring] = useState(false); @@ -30,7 +35,7 @@ export function useStorageWorkspace(): StorageWorkspace { const [error, setError] = useState(null); const activeJob = useRef(null); - const explore = useCallback(async (path?: string | null) => { + const explore = useCallback(async (path?: string | null, force = false) => { if (exploring || scanningFiles) return; const id = jobId(); activeJob.current = id; @@ -40,9 +45,11 @@ export function useStorageWorkspace(): StorageWorkspace { setFiles([]); const stop = await subscribeJobProgress(id, setProgress); 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; - setNode(next); + setNode(next.node); + setCached(next.cached); + setMeasuredAtMs(next.measuredAtMs); } catch (reason) { if (!isCancelled(reason)) setError(messageFrom(reason)); } finally { @@ -89,6 +96,8 @@ export function useStorageWorkspace(): StorageWorkspace { return { node, + cached, + measuredAtMs, files, progress, exploring, diff --git a/src/lib/api.ts b/src/lib/api.ts index ed562a6..0bab13b 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -5,6 +5,7 @@ import type { Bootstrap, DeleteMode, DeleteResult, + ExploreResult, HistorySession, JobProgress, LargestFile, @@ -14,9 +15,10 @@ import type { PlanResult, PopupClosedEvent, PopupWindowItem, + PreflightResult, ScanResult, SettingsView, - StorageNode, + SpaceInsight, SystemSnapshot, UndoResult, UpdateCheckResult, @@ -52,6 +54,8 @@ export const api = { }), cleanupDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) => invoke("cleanup_delete", { jobId, scanId, selected, mode }), + cleanupPreflight: (scanId: string, selected: number[]) => + invoke("cleanup_preflight", { scanId, selected }), purgeScan: (jobId: string, roots: string[] = [], minAgeDays: number | null = null, force = false) => invoke("purge_scan", { jobId, roots, minAgeDays, force }), purgeDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) => @@ -60,8 +64,9 @@ export const api = { appPlan: (jobId: string, appKey: string) => invoke("app_plan", { jobId, appKey }), appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) => invoke("app_uninstall", { jobId, planId, selected, mode }), - storageExplore: (jobId: string, path?: string | null, depth = 1, top = 16) => - invoke("storage_explore", { jobId, path, depth, top }), + storageExplore: (jobId: string, path?: string | null, depth = 1, top = 16, force = false) => + invoke("storage_explore", { jobId, path, depth, top, force }), + storageInsights: () => invoke("storage_insights"), storageLargestFiles: (jobId: string, path: string, limit = 40) => invoke("storage_largest_files", { jobId, path, limit }), systemSnapshot: (full = false) => invoke("system_snapshot", { full }), @@ -72,6 +77,9 @@ export const api = { settingsSave: (patch: SettingsPatch) => invoke("settings_save", { patch }), whitelistAdd: (path: string) => invoke("whitelist_add", { path }), whitelistRemove: (pattern: string) => invoke("whitelist_remove", { pattern }), + whitelistAudit: () => invoke<{ pattern: string; live: boolean }[]>("whitelist_audit"), + writeTextFile: (path: string, contents: string) => + invoke("write_text_file", { path, contents }), revealPath: (path: string) => invoke("reveal_path", { path }), openTrash: () => invoke("open_trash"), permissionStatus: () => invoke("permission_status"), diff --git a/src/lib/format.ts b/src/lib/format.ts index c39e6b5..3b0b75c 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -98,3 +98,45 @@ export function isCancelled(error: unknown): boolean { const text = messageFrom(error).toLowerCase(); 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, ","); +} diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index 87f26fd..dcb05d3 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -58,6 +58,29 @@ export function SettingsPage({ const [error, setError] = useState(null); const [permission, setPermission] = useState(null); 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 | 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 () => { setCheckingPermission(true); @@ -384,6 +407,30 @@ export function SettingsPage({ {t("Add", "添加")} + {settings.whitelist.length > 0 ? ( +
+ + {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} 条命中过已知缓存位置`, + )} + + +
+ ) : null}
{settings.whitelist.length === 0 ? (

@@ -396,6 +443,25 @@ export function SettingsPage({ {shortPath(pattern, 88)} + {audit ? ( + + {audit.get(pattern) + ? t("Recently matched", "最近命中") + : t("Never matched", "从未命中")} + + ) : null} + ) : null} + {!item.lock && item.note ? ( + {item.note} + ) : null} + {formatBytes(item.onDisk)} + +

+ {showEvidence ? ( +
+ {t("Why Squid judges this folder", "Squid 对该目录的判定依据")} +
    + {evidenceLines(evidence, t).map((line) => ( +
  • + {line.text} +
  • + ))} +
+
) : null} - {formatBytes(item.onDisk)} - - + ); } @@ -289,6 +482,10 @@ export function SpacePage({ if (scanning || deleting || inFlight.current) return; inFlight.current = true; 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 .split(/\r?\n/) .map((root) => root.trim()) @@ -570,6 +767,8 @@ export function SpacePage({ } finally { setBusy(false); setConfirming(false); + setInlineConfirm(false); + setPreflight(null); } setResult(merged); push( @@ -582,12 +781,150 @@ export function SpacePage({ }; 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> = {}; + 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 ? t("Scanning caches and junk", "第一步 · 扫描缓存与垃圾") : purge.scanning ? t("Scanning project folders", "第二步 · 扫描项目目录") : 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(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; if (result) { @@ -626,6 +963,57 @@ export function SpacePage({ + {result.skipped && result.skipped.length > 0 ? ( +
+
+ {t( + `${result.skipped.length} item(s) were skipped`, + `有 ${result.skipped.length} 项本次未处理`, + )} +
+ {Object.entries( + result.skipped.reduce>( + (groups, row) => { + const key = skipGroupOf(row.reason).key; + (groups[key] ??= []).push(row); + return groups; + }, + {}, + ), + ).map(([key, rows]) => { + const group = skipGroupOf(rows[0].reason); + return ( +
+
+ {t(group.title[0], group.title[1])} + {rows.length} +
+
    + {rows.slice(0, 5).map((row) => ( +
  • + {row.path} + {row.reason} +
  • + ))} + {rows.length > 5 ? ( +
  • + {t(`… ${rows.length - 5} more`, `… 另有 ${rows.length - 5} 项`)} +
  • + ) : null} +
+
+ {t(group.hint[0], group.hint[1])} + {group.action === "rescan" ? ( + + ) : null} +
+
+ ); + })} +
+ ) : null} ); } @@ -722,8 +1110,31 @@ export function SpacePage({ void (cleanup.scanning ? cleanup.cancel() : purge.cancel())} /> + {Object.keys(liveBuckets).length > 0 ? ( +
+ {CATEGORY_ORDER.filter((category) => liveBuckets[category]).map((category) => { + const bucket = liveBuckets[category]!; + const meta = CATEGORY_META[category]; + const Icon = meta.icon; + return ( +
+ + + + {categoryLabel(category, lang, bin)} + + {t(`${formatCount(bucket.count)} items`, `${formatCount(bucket.count)} 项`)} + + {formatBytes(bucket.total)} +
+ ); + })} +
+ ) : null} ) : null} @@ -793,24 +1204,84 @@ export function SpacePage({ )} + - + {inlineConfirm ? ( +
+ + + + {mode === "trash" + ? t( + `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)}`, + )} + + {preflight && preflight.blocked.length > 0 ? ( + + {t( + `${preflight.blocked.length} items changed since the scan and were dropped from this run`, + `其中 ${preflight.blocked.length} 项在扫描后情况变化,本次已自动移出`, + )} + + ) : ( + + {t( + "Esc cancels · every path was re-checked just now", + "按 Esc 取消 · 刚才已逐路径复核", + )} + + )} + + + +
+ ) : ( + + )} {(["daily", "optional"] as const).map((section) => { @@ -1065,6 +1536,39 @@ export function SpacePage({ ) : null} + {preflight && preflight.checked > 0 ? ( +
+ + + {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} 项 — 全部仍可安全删除`, + )} + + {preflight.blocked.length > 0 ? ( +
    + {preflight.blocked.slice(0, 8).map((row) => ( +
  • + {row.path} + {row.reason} +
  • + ))} +
+ ) : ( +

+ {t( + "Locks, whitelist, running apps and vanished paths were all re-verified at the click of this button.", + "锁、白名单、运行中的应用与已消失的路径,都在点击瞬间重新核验过。", + )} +

+ )} +
+ ) : null} ); diff --git a/src/pages/StoragePage.tsx b/src/pages/StoragePage.tsx index d777d41..179861c 100644 --- a/src/pages/StoragePage.tsx +++ b/src/pages/StoragePage.tsx @@ -1,27 +1,31 @@ import { ArrowLeft, ChevronRight, + Copy, ExternalLink, FileArchive, FolderOpen, FolderSearch, HardDrive, + Lightbulb, LoaderCircle, RefreshCw, ScanSearch, + TimerReset, } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import * as apiClient from "../lib/api"; import { useI18n } from "../i18n"; import { + agoLabel, basename, formatBytes, formatCount, percent, shortPath, } from "../lib/format"; -import type { Bootstrap, StorageNode } from "../types"; +import type { Bootstrap, SpaceInsight, StorageNode } from "../types"; import { useStorageWorkspace } from "../hooks/useStorageWorkspace"; import { Button, @@ -29,6 +33,7 @@ import { PageHeader, ProgressCard, SectionTitle, + useToast, } from "../components/ui"; 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 }) { - const { t } = useI18n(); + const { t, lang } = useI18n(); + const { push } = useToast(); const workspace = useStorageWorkspace(); const [pathInput, setPathInput] = useState(""); const [manualPath, setManualPath] = useState(false); + const [insights, setInsights] = useState(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(() => { if (workspace.node && !manualPath) setPathInput(workspace.node.path); @@ -89,10 +112,19 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { }; 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); }; + 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; return ( @@ -180,6 +212,32 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { + {workspace.cached ? ( +
+ + + {t( + `Instant open · cached measurement${ + workspace.measuredAtMs + ? ` · taken ${agoLabel(workspace.measuredAtMs, lang)}` + : "" + }`, + `秒开 · 缓存数据${ + workspace.measuredAtMs + ? ` · 上次测量 ${agoLabel(workspace.measuredAtMs, lang)}` + : "" + }`, + )} + + +
+ ) : null} + {children.length > 0 ? ( <>
@@ -197,10 +255,10 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {

{t( `${workspace.node.folded} smaller folders (${formatBytes( - workspace.node.folded_size, + workspace.node.foldedSize, )}) are folded into the remainder.`, `${workspace.node.folded} 个较小文件夹(${formatBytes( - workspace.node.folded_size, + workspace.node.foldedSize, )})已合并显示。`, )}

@@ -213,7 +271,7 @@ export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) { + ) : null} + {insight.action === "cleanable" ? ( + + ) : null} + {insight.action === "command" && insight.command ? ( + + ) : null} + +
+ ))} + + + ) : null} + {!workspace.node && !workspace.exploring ? (