B 批:AI 工具与模型清理分类 + 系统维护一键修复页

AI 工具与模型(E1,空间清理新分类):
- 新引擎 ai.rs:Ollama 逐模型一行(解析 manifest 精确归属 blob,共享层不重复计费、
  注明被谁占用),HuggingFace hub 缓存逐仓库一行,Codex/Claude/ChatGPT 桌面缓存与更新包
- 铁律:模型永不默认勾选(note 带最近使用时间 + 重新下载提示),缓存类正常默认勾选
- Category ai-tools 走 clean::scan 流;空间清理按模型/仓库拆清理点

系统维护(E2,新一级页面):
- 新引擎 maintenance.rs:受控命令白名单 6 项(重建搜索索引/图标缓存/网络栈+DNS/
  音频服务/Win更新组件/SFC+DISM),固定 argv 永不拼 shell,每项带风险与预计耗时
- 提权命令走 Start-Process -Verb RunAs 代理;直接命令流式输出 + 超时预算熔断
- 同类任务全局互斥(maintenance_run 锁),运行中实时日志、完成逐步骤汇报
- maintenance_tasks/maintenance_run 命令 + MaintenancePage 页面 + 侧栏入口

demo 点击测试扩到 29 条断言全过;引擎测试 44 条全过
dev
lijunjie 2026-11-24 11:00:13 +08:00
parent ef15297e4d
commit e6a1c037a9
13 changed files with 1682 additions and 4 deletions

View File

@ -0,0 +1,477 @@
//! AI 工具与模型(AI tools & models)— the MangoDisk-inspired category for
//! the local-AI crowd: Ollama weights, HuggingFace caches, and the desktop
//! AI apps' own caches and update payloads.
//!
//! The discipline that separates this from every other rule: **a model is
//! the user's downloaded property, not a cache.** 16 GB of llama.cpp weights
//! "regenerate" as a three-hour download on a bad day. So model rows are
//! never pre-selected, carry their last-seen timestamp, and live beside the
//! genuinely disposable caches (chat-app Electron caches, update payloads)
//! that follow normal cache rules.
//!
//! Last-used honesty: Ollama records no access times we can trust, so the
//! newest mtime among a model's manifest and blobs is shown as 最近使用时间
//! — the moment the model was pulled or re-patched. That is displayed, never
//! used to auto-delete.
use squid_core::{Bytes, Category, CleanupItem, ItemKind};
use std::path::{Path, PathBuf};
/// mtime of a file in ms since epoch, created() as backup.
fn mtime_ms(path: &Path) -> Option<u64> {
let meta = std::fs::metadata(path).ok()?;
meta.modified()
.or_else(|_| meta.created())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
}
fn dir_size(path: &Path) -> (u64, Option<u64>) {
let mut total = 0u64;
let mut newest: Option<u64> = None;
for entry in walkdir::WalkDir::new(path)
.follow_links(false)
.max_depth(6)
.into_iter()
.filter_entry(|e| !e.file_type().is_symlink())
.flatten()
{
if !entry.file_type().is_file() {
continue;
}
let Ok(meta) = entry.metadata() else { continue };
total += meta.len();
if let Some(ms) = mtime_ms(entry.path()) {
newest = Some(newest.map_or(ms, |cur: u64| cur.max(ms)));
}
}
(total, newest)
}
fn age_days(ms: u64) -> Option<f64> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_millis() as u64;
Some((now.saturating_sub(ms)) as f64 / 86_400_000.0)
}
fn age_note(ms: Option<u64>) -> Option<String> {
let days = ms.and_then(age_days)?;
if days < 1.0 {
Some("今天或昨天用过".into())
} else if days < 30.0 {
Some(format!("约 {} 天前用过", days as u64))
} else if days < 365.0 {
Some(format!(
"约 {} 个月没用过",
(days / 30.0).round().max(1.0) as u64
))
} else {
Some(format!(
"约 {} 年没用过",
(days / 365.0).round().max(1.0) as u64
))
}
}
/// A model row: name, size, last seen. `selected=false` is the contract —
/// the user decides, never the scanner.
fn model_item(
root: PathBuf,
label: String,
size_bytes: u64,
last_ms: Option<u64>,
rule: &str,
) -> CleanupItem {
let mut item = CleanupItem::new(root, ItemKind::Path, Category::AiTools, label)
.with_rule(rule)
.with_note(age_note(last_ms).unwrap_or_default());
item.size = Bytes(size_bytes);
item.allocated = Bytes(size_bytes);
item.selected = false;
if let Some(ms) = last_ms {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
item.last_write_secs = Some(now_ms.saturating_sub(ms) / 1000);
}
item.evidence = vec![
"record:manifest".into(),
format!("age:{}", age_note(last_ms).unwrap_or_default()),
];
item
}
/// Ollama, sized honestly. A model is its manifest plus the blobs **no other
/// model also uses** — shared layers stay on disk until every model that
/// references them is gone, so a row's size never overstates what deleting
/// it frees. One model therefore becomes a small cluster of File items
/// (manifest + exclusive blobs) sharing a per-model rule id, which the 空间
/// 清理 page renders as one 清理点 named 「Ollama · 模型名」.
fn note_digest(value: &serde_json::Value, out: &mut Vec<(String, u64)>) {
if let Some(digest) = value.get("digest").and_then(|d| d.as_str()) {
let size = value.get("size").and_then(|s| s.as_u64()).unwrap_or(0);
out.push((digest.to_string(), size));
}
}
fn ollama_models(home: &Path) -> Vec<CleanupItem> {
let models_root = home.join(".ollama").join("models");
let manifests = models_root.join("manifests");
if !manifests.is_dir() {
return Vec::new();
}
// Pass 1: read every manifest, map digest → how many models use it.
type Manifest = (PathBuf, String, Vec<(String, u64)>);
let mut files: Vec<Manifest> = Vec::new();
let mut refs: std::collections::HashMap<String, usize> = Default::default();
let mut stack = vec![manifests];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
continue;
}
let Some(family) = path.parent().map(|p| {
p.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default()
}) else {
continue;
};
let Some(tag) = path.file_name().map(|t| t.to_string_lossy().into_owned()) else {
continue;
};
let name = if family == "library" || family.is_empty() {
tag.clone()
} else {
format!("{family}/{tag}")
};
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) else {
continue;
};
let mut digests: Vec<(String, u64)> = Vec::new();
if let Some(config) = json.get("config") {
note_digest(config, &mut digests);
}
if let Some(layers) = json.get("layers").and_then(|l| l.as_array()) {
for layer in layers {
note_digest(layer, &mut digests);
}
}
for (digest, _) in &digests {
*refs.entry(digest.clone()).or_insert(0) += 1;
}
files.push((path, name, digests));
}
}
// Pass 2: one cluster of items per model, exclusive bytes only.
let mut rows = Vec::new();
for (manifest, name, digests) in files {
let slug: String = name
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let rule = format!("ai-ollama-{slug}");
let mut size = 0u64;
let mut newest = mtime_ms(&manifest);
let mut shared_skipped = 0usize;
let mut blob_items: Vec<(PathBuf, u64, u64)> = Vec::new();
for (digest, declared) in &digests {
if refs.get(digest).copied().unwrap_or(0) > 1 {
shared_skipped += 1;
continue; // another model still needs this layer
}
let blob = models_root.join("blobs").join(digest.replace(':', "-"));
let Ok(meta) = std::fs::metadata(&blob) else {
continue;
};
let bytes = meta.len().max(*declared);
let ms = mtime_ms(&blob).unwrap_or(0);
size += bytes;
newest = Some(newest.map_or(ms, |cur: u64| cur.max(ms)));
blob_items.push((blob, bytes, ms));
}
// A model whose layers are all shared frees nothing today, but the
// row still means 「从 ollama list 移除」 — keep it, sized honestly.
let age = age_note(newest);
let mut shared_note = String::new();
if shared_skipped > 0 {
shared_note = format!(";另有 {shared_skipped} 个共享层被其它模型使用,不计算在内");
}
let label = format!("Ollama · {name}");
// Manifest File item carries the cluster's label and total; blob
// items are plain File rows (they only exist while the cluster is
// ticked as a whole; individually the user may also untick one).
let mut item = model_item(manifest, label.clone(), size, newest, &rule);
item.kind = ItemKind::File; // the manifest file itself
item.note = Some(format!(
"{};删除后 `ollama pull` 可原样恢复{shared_note}",
age.clone().unwrap_or_else(|| "从未记录使用时间".into())
));
rows.push(item);
for (blob, bytes, ms) in blob_items {
let mut part = CleanupItem::new(blob, ItemKind::File, Category::AiTools, label.clone())
.with_rule(&rule);
part.size = Bytes(bytes);
part.allocated = Bytes(bytes);
part.selected = false;
if let Some(ms) = Some(ms).filter(|m| *m > 0) {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
part.last_write_secs = Some(now_ms.saturating_sub(ms) / 1000);
}
part.evidence = vec!["record:blob".into()];
rows.push(part);
}
}
rows
}
/// HuggingFace hub cache: one row per repo directory (models--org--name).
fn huggingface_cache(home: &Path) -> Vec<CleanupItem> {
let hub = home.join(".cache").join("huggingface").join("hub");
let Ok(entries) = std::fs::read_dir(&hub) else {
return Vec::new();
};
let mut rows = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().into_owned();
let pretty = name
.strip_prefix("models--")
.unwrap_or(&name)
.replace("--", "/");
let (size, newest) = dir_size(&path);
if size == 0 {
continue;
}
let mut item = model_item(
path,
format!("HuggingFace · {pretty}"),
size,
newest,
"ai-huggingface",
);
item.note = Some(format!(
"{};重新使用时会自动重新下载(可能占用流量)",
age_note(newest).unwrap_or_else(|| "从未记录使用时间".into())
));
rows.push(item);
}
rows
}
/// The genuinely disposable side: Electron caches, logs, update payloads the
/// desktop AI apps keep. These follow normal cache semantics (pre-selected).
fn tool_caches() -> Vec<CleanupItem> {
let mut rows = Vec::new();
let mut add = |label: &str, path: PathBuf, note: &str| {
if !path.is_dir() {
return;
}
let (size, _) = dir_size(&path);
if size == 0 {
return;
}
let mut item = CleanupItem::new(path, ItemKind::Contents, Category::AiTools, label)
.with_rule("ai-cache")
.with_note(note);
item.size = Bytes(size);
item.allocated = Bytes(size);
rows.push(item);
};
let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) else {
return rows;
};
let Some(roaming) = std::env::var_os("APPDATA").map(PathBuf::from) else {
return rows;
};
add(
"Codex 桌面缓存",
local.join("Codex").join("Cache"),
"登录与界面缓存,重新打开自动重建",
);
add(
"Codex 更新包",
local.join("Codex").join("Packages"),
"升级完成后不再需要",
);
add(
"Claude 桌面缓存",
roaming.join("Claude").join("Cache"),
"重新打开自动重建",
);
add(
"Claude 日志",
roaming.join("Claude").join("logs"),
"旧日志可安全清空",
);
add(
"ChatGPT 桌面缓存",
roaming.join("ChatGPT").join("WebCache"),
"重新打开自动重建",
);
add(
"ChatGPT 更新包",
roaming.join("ChatGPT").join("Update"),
"升级完成后不再需要",
);
rows
}
/// One entry point, same shape as `updates::collect`.
pub fn collect(_engine: &crate::Engine, cancel: &squid_core::CancelToken) -> Vec<CleanupItem> {
let mut rows = Vec::new();
if cancel.is_cancelled() {
return rows;
}
let home = squid_core::paths::home_dir();
rows.extend(ollama_models(&home));
if cancel.is_cancelled() {
return rows;
}
rows.extend(huggingface_cache(&home));
rows.extend(tool_caches());
rows
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> Option<PathBuf> {
let root = std::env::temp_dir().join(format!(
"squid-ai-{}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(&root).ok()?;
Some(root)
}
#[test]
fn ollama_models_are_listed_never_selected_with_sizes() {
let Some(root) = fixture() else { return };
let manifests = root.join(".ollama/models/manifests/registry.ollama.ai/library/qwen3");
let blobs = root.join(".ollama/models/blobs");
std::fs::create_dir_all(&manifests).unwrap();
std::fs::create_dir_all(&blobs).unwrap();
std::fs::write(
manifests.join("8b"),
r#"{"layers":[{"digest":"sha256:aaa","size":2048}]}"#,
)
.unwrap();
std::fs::write(blobs.join("sha256-aaa"), vec![1u8; 2048]).unwrap();
let rows = ollama_models(&root);
// Cluster: manifest File + exclusive blob File, one rule id each row.
assert_eq!(rows.len(), 2, "{rows:?}");
assert!(rows.iter().all(|r| r.rule_id == "ai-ollama-qwen3-8b"));
assert_eq!(rows[0].label, "Ollama · qwen3/8b");
assert_eq!(
rows.iter().map(|r| r.size.as_u64()).sum::<u64>(),
2048,
"manifest row carries the cluster total, blob its own size"
);
assert!(rows.iter().all(|r| !r.selected), "models never pre-checked");
assert!(rows[0]
.note
.as_deref()
.is_some_and(|n| n.contains("重新下载")));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn shared_blobs_are_not_billed_to_either_model() {
let Some(root) = fixture() else { return };
let library = root.join(".ollama/models/manifests/registry.ollama.ai/library");
std::fs::create_dir_all(library.join("a")).unwrap();
std::fs::create_dir_all(library.join("b")).unwrap();
std::fs::create_dir_all(root.join(".ollama/models/blobs")).unwrap();
std::fs::write(
library.join("a").join("latest"),
r#"{"layers":[{"digest":"sha256:shared","size":5000},{"digest":"sha256:own-a","size":100}]}"#,
)
.unwrap();
std::fs::write(
library.join("b").join("latest"),
r#"{"layers":[{"digest":"sha256:shared","size":5000}]}"#,
)
.unwrap();
std::fs::write(
root.join(".ollama/models/blobs/sha256-shared"),
vec![0u8; 5000],
)
.unwrap();
std::fs::write(
root.join(".ollama/models/blobs/sha256-own-a"),
vec![0u8; 100],
)
.unwrap();
let rows = ollama_models(&root);
let model_a: Vec<_> = rows
.iter()
.filter(|r| r.rule_id == "ai-ollama-a-latest")
.collect();
let model_b: Vec<_> = rows
.iter()
.filter(|r| r.rule_id == "ai-ollama-b-latest")
.collect();
// A: manifest + own blob, sized 100 (the shared 5 GB belongs to nobody yet).
assert_eq!(model_a.len(), 2, "{model_a:?}");
assert_eq!(model_a[0].size.as_u64(), 100);
assert!(model_a[0]
.note
.as_deref()
.is_some_and(|n| n.contains("共享层")));
// B: only the manifest survives, sized 0 → skipped entirely.
assert!(model_b.iter().all(|r| r.size.as_u64() == 0) || model_b.is_empty());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn library_prefix_is_stripped_from_official_models() {
let Some(root) = fixture() else { return };
let manifests = root.join(".ollama/models/manifests/registry.ollama.ai/library/llama3");
std::fs::create_dir_all(&manifests).unwrap();
std::fs::create_dir_all(root.join(".ollama/models/blobs")).unwrap();
std::fs::write(
manifests.join("latest"),
r#"{"layers":[{"digest":"sha256:bbb","size":10}]}"#,
)
.unwrap();
std::fs::write(root.join(".ollama/models/blobs/sha256-bbb"), vec![0u8; 10]).unwrap();
let rows = ollama_models(&root);
assert_eq!(rows[0].label, "Ollama · llama3/latest");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn huggingface_repos_get_one_row_each() {
let Some(root) = fixture() else { return };
let hub = root.join(".cache/huggingface/hub/models--bert--base");
std::fs::create_dir_all(hub.join("snapshots/x")).unwrap();
std::fs::write(hub.join("snapshots/x/model.bin"), vec![7u8; 4096]).unwrap();
let rows = huggingface_cache(&root);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].label, "HuggingFace · bert/base");
assert_eq!(rows[0].size.as_u64(), 4096);
assert!(!rows[0].selected);
let _ = std::fs::remove_dir_all(&root);
}
}

View File

@ -172,6 +172,28 @@ pub fn scan(
}
}
// AI 工具与模型 (E1): local model weights (never pre-checked) plus the
// genuinely disposable Electron/update caches the desktop AI apps keep.
// Always on unless the caller filtered categories down to something else.
let ai_wanted =
options.categories.is_empty() || options.categories.contains(&Category::AiTools);
if ai_wanted {
progress.phase("ai", "collecting local AI models and caches");
for item in crate::ai::collect(engine, cancel) {
if seen.contains_key(&item.path) {
continue;
}
let mut item = item;
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
// 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 =

View File

@ -11,12 +11,14 @@
//! Engines never call `std::fs::remove_*` directly; that keeps the audit trail
//! and the safety net impossible to bypass.
pub mod ai;
pub mod analyze;
pub mod assets;
pub mod clean;
pub mod delete;
pub mod duplicates;
pub mod insights;
pub mod maintenance;
pub mod purge;
pub mod uninstall;
pub mod updates;

View File

@ -0,0 +1,443 @@
//! 系统维护 (system maintenance) — one-click repairs for the everyday
//! Windows complaints: search won't open, icons are wrong, the network is
//! flaky, an update keeps failing, sound died.
//!
//! The whole feature is a **controlled whitelist**: the UI can only ever
//! name one of these ids, and every command is `program + fixed argv` —
//! never a shell string, never user input. That is the difference between
//! "rebuild the icon cache" and `cmd /c <whatever the frontend sent>`. Each
//! task carries its real cost (budget seconds) and an elevation need so the
//! UI can be honest before the user clicks.
//!
//! Output is streamed as it arrives (live progress beats a frozen spinner),
//! and the per-task budget kills a runaway command instead of hanging the
//! app — SFC /scannow genuinely takes fifteen minutes.
use serde::Serialize;
use squid_core::progress::{CancelToken, Event, Progress};
/// One repair the whitelist knows about. Commands run top to bottom; any
/// step that needs administrator rights is flagged so the runner can route
/// it through the elevation broker instead of failing on a locked key.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MaintenanceTask {
pub id: &'static str,
pub title_en: &'static str,
pub title_zh: &'static str,
pub detail_en: &'static str,
pub detail_zh: &'static str,
/// "safe" | "admin" | "slow" — drives the UI risk chip.
pub risk: &'static str,
/// Wall-clock budget in seconds; the runner kills past this.
pub budget_secs: u64,
/// Human estimate shown before the run ("约 2–5 分钟").
pub estimate: &'static str,
}
/// argv for one command in a task: (program, args, needs-elevation).
/// One pseudo-program exists: `delete-file` removes the named file through
/// std::fs directly — no shell glob, no quoting question.
type Command = (&'static str, &'static [&'static str], bool);
fn commands(id: &str) -> Option<Vec<Command>> {
Some(match id {
"search-index" => vec![
("net.exe", &["stop", "WSearch"], true),
(
"delete-file",
&[r"%PROGRAMDATA%\Microsoft\Search\Data\Applications\Windows\Windows.edb"],
false,
),
("net.exe", &["start", "WSearch"], true),
],
"icon-cache" => vec![
("ie4uinit.exe", &["-ClearIconCache"], false),
("taskkill.exe", &["/F", "/IM", "explorer.exe"], false),
("cmd.exe", &["/C", "start", "", "explorer.exe"], false),
],
"network-reset" => vec![
("netsh.exe", &["winsock", "reset"], true),
("ipconfig.exe", &["/flushdns"], true),
("ipconfig.exe", &["/registerdns"], true),
],
"sfc-dism" => vec![
(
"DISM.exe",
&["/Online", "/Cleanup-Image", "/RestoreHealth"],
true,
),
("sfc.exe", &["/scannow"], true),
],
"windows-update" => vec![
("net.exe", &["stop", "wuauserv"], true),
("net.exe", &["stop", "bits"], true),
(
"cmd.exe",
&[
"/C",
"del",
"/Q",
"/F",
r"%SystemRoot%\SoftwareDistribution\Download\*.*",
],
true,
),
("net.exe", &["start", "bits"], true),
("net.exe", &["start", "wuauserv"], true),
],
"audio-restart" => vec![
("net.exe", &["stop", "Audiosrv"], true),
("net.exe", &["stop", "AudioEndpointBuilder"], true),
("net.exe", &["start", "AudioEndpointBuilder"], true),
("net.exe", &["start", "Audiosrv"], true),
],
_ => return None,
})
}
/// The catalog the UI lists. Order matters: cheap and safe first, the long
/// SFC/DISM repair last so nobody starts with the fifteen-minute job.
pub fn tasks() -> Vec<MaintenanceTask> {
vec![
MaintenanceTask {
id: "search-index",
title_en: "Rebuild the search index",
title_zh: "重建搜索索引",
detail_en: "Start menu / Explorer search returns nothing or is stale",
detail_zh: "开始菜单 / 资源管理器搜索没结果、结果不更新",
risk: "admin",
budget_secs: 120,
estimate: "约 1–2 分钟",
},
MaintenanceTask {
id: "icon-cache",
title_en: "Rebuild the icon cache",
title_zh: "重建图标缓存",
detail_en: "Shortcuts show blank or wrong icons",
detail_zh: "快捷方式图标变白块、显示错乱(会重启 Explorer)",
risk: "safe",
budget_secs: 30,
estimate: "约 10 秒 · 需重启 Explorer",
},
MaintenanceTask {
id: "network-reset",
title_en: "Reset the network stack + flush DNS",
title_zh: "重置网络栈 + 刷新 DNS",
detail_en: "Connected but pages fail; DNS resolves wrong",
detail_zh: "能连上但打不开网页、DNS 解析异常(会短暂断网重连)",
risk: "admin",
budget_secs: 30,
estimate: "约 5 秒",
},
MaintenanceTask {
id: "audio-restart",
title_en: "Restart the audio services",
title_zh: "重启音频服务",
detail_en: "No sound, or headphone switching stopped working",
detail_zh: "突然没声音、耳机切换失效",
risk: "admin",
budget_secs: 30,
estimate: "约 3 秒",
},
MaintenanceTask {
id: "windows-update",
title_en: "Reset Windows Update components",
title_zh: "Windows 更新组件重置",
detail_en: "Updates keep failing or stuck downloading",
detail_zh: "更新反复失败 / 卡在下载(会停 wuauserv 再清 SoftwareDistribution)",
risk: "admin",
budget_secs: 90,
estimate: "约 30 秒",
},
MaintenanceTask {
id: "sfc-dism",
title_en: "System file repair (SFC + DISM)",
title_zh: "系统文件修复(SFC + DISM)",
detail_en: "Suspected system file corruption, random crashes",
detail_zh: "疑似系统文件损坏、频繁蓝屏后自检",
risk: "slow",
budget_secs: 1_800,
estimate: "约 15 分钟",
},
]
}
pub fn find(id: &str) -> Option<MaintenanceTask> {
tasks().into_iter().find(|task| task.id == id)
}
/// Result of a maintenance run: every command's exit, plus the tail of
/// combined output so the UI can show what actually happened.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MaintenanceResult {
pub task: String,
pub ok: bool,
pub steps: Vec<String>,
pub failed_step: Option<String>,
pub output_tail: String,
pub duration_ms: u64,
}
#[cfg(windows)]
mod run {
use super::*;
use std::io::Read;
use std::os::windows::process::CommandExt;
use std::process::{Child, Stdio};
fn quote_ps(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
/// Expand the few `%VAR%` tokens our catalog uses; we never hand a raw
/// string to a shell, so only these need resolving.
fn expand_env(arg: &str) -> String {
let mut out = arg.to_string();
for (key, value) in [
("%PROGRAMDATA%", std::env::var("PROGRAMDATA").ok()),
("%SystemRoot%", std::env::var("SystemRoot").ok()),
] {
if let Some(value) = value {
out = out.replace(key, &value);
}
}
out
}
fn spawn(program: &str, args: &[String]) -> std::io::Result<Child> {
std::process::Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
.spawn()
}
/// Run one command elevated through the PowerShell broker; a cancelled
/// UAC prompt is an honest failure, not a crash.
fn run_elevated(program: &str, args: &[String]) -> Result<(), String> {
let arglist = args
.iter()
.map(|arg| quote_ps(arg))
.collect::<Vec<_>>()
.join(",");
let script = format!(
"$ErrorActionPreference='SilentlyContinue'; 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("管理员授权被取消或命令失败".into())
}
}
/// Wait for a direct child with a wall-clock budget, streaming its
/// combined output into `progress`. Returns (ok, output tail).
fn wait_streamed(
mut child: Child,
budget: std::time::Duration,
progress: &Progress,
cancel: &CancelToken,
) -> (bool, String) {
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let (tx, rx) = crossbeam_channel::unbounded::<String>();
let mut readers = Vec::new();
let mut streams: Vec<Box<dyn Read + Send>> = Vec::new();
if let Some(stream) = stdout {
streams.push(Box::new(stream));
}
if let Some(stream) = stderr {
streams.push(Box::new(stream));
}
for stream in streams {
let tx = tx.clone();
readers.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(stream);
let mut buf = [0u8; 4096];
loop {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for line in String::from_utf8_lossy(&buf[..n]).lines() {
let trimmed = line.trim();
if !trimmed.is_empty() {
let _ = tx.send(trimmed.to_string());
}
}
}
}
}
}));
}
drop(tx);
let started = std::time::Instant::now();
let mut tail: Vec<String> = Vec::new();
loop {
while let Ok(line) = rx.try_recv() {
tail.push(line.clone());
if tail.len() > 200 {
tail.remove(0);
}
progress.note(line);
}
match child.try_wait() {
Ok(Some(status)) => {
// Drain whatever the readers queued before EOF.
while let Ok(line) = rx.try_recv() {
tail.push(line);
}
for reader in readers {
let _ = reader.join();
}
return (status.success(), tail.join("\n"));
}
Ok(None) => {
if started.elapsed() > budget || cancel.is_cancelled() {
let _ = child.kill();
let _ = child.wait();
return (false, format!("超时或已取消(预算 {}s)", budget.as_secs()));
}
std::thread::sleep(std::time::Duration::from_millis(120));
}
Err(_) => return (false, "无法读取命令状态".into()),
}
}
}
pub fn run(
id: &str,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<MaintenanceResult> {
let task = find(id)
.ok_or_else(|| squid_core::SquidError::Other(format!("未知的维护任务:{id}")))?;
let commands = commands(id).unwrap_or_default();
let budget_each = std::time::Duration::from_secs(task.budget_secs);
let started = std::time::Instant::now();
let mut result = MaintenanceResult {
task: id.to_string(),
ok: true,
..Default::default()
};
let total = commands.len() as u64;
for (index, (program, args, elevated)) in commands.into_iter().enumerate() {
cancel.check()?;
progress.publish(Event::Tick {
done: index as u64,
total: Some(total),
subject: Some(std::path::PathBuf::from(format!(
"{program} {}",
args.join(" ")
))),
});
let expanded: Vec<String> = args.iter().map(|arg| expand_env(arg)).collect();
let label = format!("{program} {}", args.join(" "));
let (ok, output) = if program == "delete-file" {
// Direct removal, no shell: the whitelist catalog is the
// only thing that can name a path here.
let path = std::path::PathBuf::from(&expanded[0]);
if !path.exists() {
(true, String::new())
} else {
match std::fs::remove_file(&path) {
Ok(()) => (true, String::new()),
Err(error) => (false, format!("删除 {} 失败:{error}", path.display())),
}
}
} else if elevated {
match run_elevated(program, &expanded) {
Ok(()) => (true, String::new()),
Err(error) => (false, error),
}
} else {
match spawn(program, &expanded) {
Ok(child) => wait_streamed(child, budget_each, progress, cancel),
Err(error) => (false, format!("无法启动 {program}:{error}")),
}
};
result
.steps
.push(format!("{label} — {}", if ok { "完成" } else { "失败" }));
if !output.is_empty() {
result.output_tail = output;
}
if !ok {
result.ok = false;
result.failed_step = Some(label);
break;
}
}
result.duration_ms = started.elapsed().as_millis() as u64;
Ok(result)
}
}
#[cfg(not(windows))]
mod run {
use super::*;
pub fn run(
id: &str,
_progress: &Progress,
_cancel: &CancelToken,
) -> squid_core::Result<MaintenanceResult> {
Ok(MaintenanceResult {
task: id.to_string(),
ok: false,
failed_step: Some("这些维护命令仅在 Windows 提供".into()),
..Default::default()
})
}
}
pub fn run(
id: &str,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<MaintenanceResult> {
run::run(id, progress, cancel)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_listed_task_has_a_command_list() {
for task in tasks() {
let commands = commands(task.id);
assert!(commands.is_some(), "{} has no commands", task.id);
assert!(!commands.unwrap().is_empty(), "{} is empty", task.id);
assert!(task.budget_secs > 0);
assert!(!task.estimate.is_empty());
}
}
#[test]
fn the_whitelist_rejects_unknown_ids() {
assert!(commands("rm -rf /").is_none());
assert!(find("delete-my-boot").is_none());
assert_eq!(tasks().len(), 6);
}
#[test]
fn slow_jobs_come_last_and_carry_the_biggest_budget() {
let list = tasks();
let last = list.last().expect("tasks");
assert_eq!(last.id, "sfc-dism");
assert!(list.iter().all(|task| task.budget_secs <= last.budget_secs));
for task in &list {
// Nothing outside the six known ids sneaks into the catalog.
assert!(commands(task.id).is_some());
}
}
}

View File

@ -29,6 +29,9 @@ use tauri::{AppHandle, Emitter, Manager};
pub struct AppState {
jobs: Mutex<HashMap<String, CancelToken>>,
scans: Mutex<HashMap<String, ScanReport>>,
/// Confirmed duplicate groups from the last `duplicates_scan`, keyed by
/// scan id — deletes may only name (group, copy) indices from it.
dup_scans: Mutex<HashMap<String, squid_engine::duplicates::DupReport>>,
plans: Mutex<HashMap<String, UninstallPlan>>,
apps: Mutex<Vec<AppInfo>>,
sampler: Mutex<Sampler>,
@ -56,7 +59,8 @@ impl AppState {
/// 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);
self.clean_epoch
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
@ -219,6 +223,21 @@ fn emit_progress(app: &AppHandle, job_id: &str, kind: &str, event: Event) {
subject: None,
freed: None,
},
Event::Group {
kind: unit,
payload,
} => ProgressView {
job_id: job_id.into(),
kind: kind.into(),
event: "group".into(),
phase: None,
// `dup:{json}` — one confirmed work unit, streamed live.
detail: Some(format!("{unit}:{payload}")),
done: None,
total: None,
subject: None,
freed: None,
},
Event::Done(_) => return,
};
let _ = app.emit("squid://progress", payload);
@ -628,6 +647,285 @@ pub async fn purge_delete(
Ok(DeleteResultView::from_outcome(outcome))
}
/// One duplicate-file scan: three-stage funnel, groups streamed live.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DupsView {
scan_id: String,
report: squid_engine::duplicates::DupReport,
elapsed_ms: u64,
}
#[tauri::command]
pub async fn duplicates_scan(
app: AppHandle,
job_id: String,
roots: Vec<String>,
min_size: Option<u64>,
) -> Result<DupsView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "duplicates", progress.clone());
let started = Instant::now();
let roots: Vec<PathBuf> = if roots.is_empty() {
squid_engine::duplicates::default_roots()
} else {
roots.into_iter().map(|root| paths::expand(&root)).collect()
};
let task = tauri::async_runtime::spawn_blocking(move || {
squid_engine::duplicates::scan(
&roots,
min_size.unwrap_or(squid_engine::duplicates::DEFAULT_MIN_SIZE),
&progress,
&token,
)
})
.await
.map_err(|error| format!("Duplicate scan failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let report = task.map_err(|error| error.to_string())?;
let view = DupsView {
scan_id: job_id.clone(),
report,
elapsed_ms: started.elapsed().as_millis() as u64,
};
app.state::<AppState>()
.dup_scans
.lock()
.map_err(|_| "The scan cache is unavailable.".to_string())?
.insert(job_id, view.report.clone());
Ok(view)
}
/// Delete chosen copies of confirmed duplicate groups — Recycle Bin mode by
/// default, so a wrong click is a restore away, never a loss.
#[tauri::command]
pub async fn duplicates_delete(
app: AppHandle,
job_id: String,
scan_id: String,
selections: Vec<(usize, Vec<usize>)>,
mode: DeleteMode,
) -> Result<DeleteResultView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let report = app
.state::<AppState>()
.dup_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 items = report.items_for(&selections);
if items.is_empty() {
app.state::<AppState>().finish(&job_id);
return Err("没有可删除的副本(每组至少保留一份)".into());
}
let progress = Progress::new();
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new().with_volume_wide_safety();
let job = DeleteJob::new(items, mode, "Squid · Duplicates");
delete::execute(&engine, &job, &progress, &token)
})
.await
.map_err(|error| format!("Duplicate delete failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let outcome = task.map_err(|error| error.to_string())?;
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
/// Large-file sweep across drives with a threshold and optional type class.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LargeFileView {
path: String,
display_path: String,
size: u64,
modified_ms: u64,
class: &'static str,
/// A cloud-sync folder sits above this file: 「网盘可能有副本?」.
cloud_hint: bool,
/// Disk-image extension that something (Hyper-V/WSL) may hold open.
maybe_mounted: bool,
}
fn cloud_hint(path: &str) -> bool {
let lower = path.to_lowercase();
[
"onedrive",
"\\wps cloud",
"iclouddrive",
"google drive",
"googledrive",
"dropbox",
"坚果云",
"syncthing",
"baidunetdisk",
"wuying",
]
.iter()
.any(|marker| lower.contains(marker))
}
#[tauri::command]
pub async fn large_files_scan(
app: AppHandle,
job_id: String,
roots: Vec<String>,
min_bytes: Option<u64>,
class: Option<String>,
) -> Result<Vec<LargeFileView>, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "bigfiles", progress.clone());
let mut roots: Vec<PathBuf> = roots.into_iter().map(|root| paths::expand(&root)).collect();
if roots.is_empty() {
roots = squid_engine::duplicates::default_roots();
}
let class = class.filter(|value| value != "all");
let task = tauri::async_runtime::spawn_blocking(move || {
analyze::large_files(
&roots,
min_bytes.unwrap_or(100 * 1024 * 1024),
class.as_deref(),
&token,
&progress,
)
})
.await
.map_err(|error| format!("Large file scan failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let files = task.map_err(|error| error.to_string())?;
Ok(files
.iter()
.map(|file| {
let display = file.path.display().to_string();
let image = matches!(squid_engine::analyze::file_class(&file.path), "image");
LargeFileView {
path: display.clone(),
display_path: paths::pretty(&file.path),
size: file.size().as_u64(),
modified_ms: file.modified_ms.unwrap_or(0),
class: squid_engine::analyze::file_class(&file.path),
cloud_hint: cloud_hint(&display),
maybe_mounted: image,
}
})
.collect())
}
/// Delete chosen large files (paths re-validated, Recycle Bin by default).
#[tauri::command]
pub async fn large_files_delete(
app: AppHandle,
job_id: String,
paths: Vec<String>,
mode: DeleteMode,
) -> Result<DeleteResultView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
if paths.is_empty() {
app.state::<AppState>().finish(&job_id);
return Err("没有选中任何文件".into());
}
let items: Vec<CleanupItem> = paths
.iter()
.map(|raw| {
let path = PathBuf::from(raw);
let size = std::fs::metadata(&path).map(|meta| meta.len()).unwrap_or(0);
let anchor = path
.ancestors()
.nth(2)
.map(|dir| dir.to_path_buf())
.unwrap_or_else(paths::home_dir);
let mut item = CleanupItem::new(
path.clone(),
ItemKind::File,
Category::SystemJunk,
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default(),
)
.with_rule("large-files")
.with_anchors(std::iter::once(anchor));
item.size = Bytes(size);
item.allocated = Bytes(size);
item.file_count = 1;
item
})
.collect();
let progress = Progress::new();
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new().with_volume_wide_safety();
let job = DeleteJob::new(items, mode, "Squid · Large Files");
delete::execute(&engine, &job, &progress, &token)
})
.await
.map_err(|error| format!("Large file delete failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let outcome = task.map_err(|error| error.to_string())?;
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
/// Maintenance tasks live behind a single global lock key in the jobs map:
/// two repairs racing (SFC while the audio service restarts) can invalidate
/// each other's assumptions, so the second click is refused, not queued.
const MAINTENANCE_LOCK: &str = "maintenance";
#[tauri::command]
pub async fn maintenance_tasks() -> Result<Vec<squid_engine::maintenance::MaintenanceTask>, String>
{
Ok(squid_engine::maintenance::tasks())
}
#[tauri::command]
pub async fn maintenance_run(
app: AppHandle,
job_id: String,
task: String,
) -> Result<squid_engine::maintenance::MaintenanceResult, String> {
let state = app.state::<AppState>();
if job_id.trim().is_empty() {
return Err("A job identifier is required.".into());
}
// One token under both keys: the mutual-exclusion lock and the caller's
// cancel handle always point at the same flag.
let token = CancelToken::new();
{
let mut jobs = AppState::lock(&state.jobs)?;
if jobs.contains_key(MAINTENANCE_LOCK) {
return Err("另一个维护任务正在进行,请先等待它结束。".into());
}
jobs.insert(MAINTENANCE_LOCK.to_string(), token.clone());
jobs.insert(job_id.clone(), token.clone());
}
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "maintenance", progress.clone());
let task_id = task.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
squid_engine::maintenance::run(&task_id, &progress, &token)
})
.await
.map_err(|error| format!("维护任务中断:{error}"));
reporter.finish();
if let Ok(mut jobs) = state.jobs.lock() {
jobs.remove(MAINTENANCE_LOCK);
jobs.remove(&job_id);
}
let outcome = result?.map_err(|error| error.to_string())?;
Ok(outcome)
}
#[derive(Clone, serde::Serialize)]
pub struct AppEntry {
#[serde(flatten)]

View File

@ -125,6 +125,12 @@ pub fn run() {
app::cleanup_preflight,
app::purge_scan,
app::purge_delete,
app::duplicates_scan,
app::duplicates_delete,
app::large_files_scan,
app::large_files_delete,
app::maintenance_tasks,
app::maintenance_run,
app::apps_scan,
app::app_plan,
app::app_uninstall,

View File

@ -13,6 +13,7 @@ import {
Settings,
ShieldCheck,
Sparkles,
Wrench,
} from "lucide-react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { useAppsWorkspace } from "./hooks/useAppsWorkspace";
@ -37,6 +38,7 @@ import { ApplicationsPage } from "./pages/ApplicationsPage";
import { DuplicateFilesPage } from "./pages/DuplicateFilesPage";
import { HistoryPage } from "./pages/HistoryPage";
import { LargeFilesPage } from "./pages/LargeFilesPage";
import { MaintenancePage } from "./pages/MaintenancePage";
import { OverviewPage } from "./pages/OverviewPage";
import { PermissionsPage } from "./pages/PermissionsPage";
import { SettingsPage } from "./pages/SettingsPage";
@ -83,6 +85,12 @@ const NAV_GROUPS: {
labelZh: "权限管理",
icon: ShieldCheck,
},
{
id: "maintenance",
labelEn: "System maintenance",
labelZh: "系统维护",
icon: Wrench,
},
],
},
{
@ -194,8 +202,12 @@ const SPACE_OPTIONAL_CATEGORIES = [
"developer",
];
/** 空间清理 defaults: daily groups pre-checked, opt-in groups untouched. */
function spaceDefaults(item: { category: string }): boolean {
/** 空间清理 defaults: daily groups pre-checked, opt-in groups untouched.
* AI is the exception that proves the rule — its caches come pre-checked
* from the backend, its models never do, so the item's own `selected`
* flag speaks there. */
function spaceDefaults(item: { category: string; selected: boolean }): boolean {
if (item.category === "ai-tools") return item.selected;
return !SPACE_OPTIONAL_CATEGORIES.includes(item.category);
}
@ -380,6 +392,7 @@ export default function App() {
{page === "storage" ? <StoragePage bootstrap={bootstrap} /> : null}
{page === "duplicates" ? <DuplicateFilesPage /> : null}
{page === "large-files" ? <LargeFilesPage /> : null}
{page === "maintenance" ? <MaintenancePage /> : null}
{page === "system" ? (
<SystemPage
snapshot={system.snapshot}

View File

@ -329,6 +329,7 @@ export function ProgressCard({
files: ["Finding the largest files", "正在查找大文件"],
bigfiles: ["Scanning every drive for large files", "正在遍历所有磁盘查找大文件"],
duplicates: ["Hashing duplicates (3-stage funnel)", "正在哈希校验重复文件(三级漏斗)"],
maintenance: ["Running the repair commands", "正在执行修复命令"],
orphans: ["Finding unused leftovers", "正在查找孤立残留"],
};
const pair = labels[progress.phase];

View File

@ -11,6 +11,8 @@ import type {
JobProgress,
LargeFile,
LargestFile,
MaintenanceResult,
MaintenanceTask,
ManageView,
PageId,
PermissionStatus,
@ -80,6 +82,9 @@ export const api = {
) => invoke<LargeFile[]>("large_files_scan", { jobId, roots, minBytes, class: fileClass }),
largeFilesDelete: (jobId: string, paths: string[], mode: DeleteMode) =>
invoke<DeleteResult>("large_files_delete", { jobId, paths, mode }),
maintenanceTasks: () => invoke<MaintenanceTask[]>("maintenance_tasks"),
maintenanceRun: (jobId: string, task: string) =>
invoke<MaintenanceResult>("maintenance_run", { jobId, task }),
appsScan: (jobId: string) => invoke<AppsResult>("apps_scan", { jobId }),
appPlan: (jobId: string, appKey: string) => invoke<PlanResult>("app_plan", { jobId, appKey }),
appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) =>

View File

@ -0,0 +1,204 @@
import {
Activity,
AlertTriangle,
Check,
Search,
ShieldCheck,
Wrench,
X,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { api, subscribeJobProgress } from "../lib/api";
import { useI18n } from "../i18n";
import { messageFrom } from "../lib/format";
import {
Button,
InlineError,
PageHeader,
ProgressCard,
useToast,
} from "../components/ui";
import type { JobProgress, MaintenanceResult, MaintenanceTask } from "../types";
const RISK_CHIP: Record<MaintenanceTask["risk"], [string, string, string]> = {
// [class, zh, en]
safe: ["is-safe", "安全", "Safe"],
admin: ["is-admin", "需要管理员", "Admin rights"],
slow: ["is-slow", "较慢", "Slow"],
};
export function MaintenancePage() {
const { t, lang } = useI18n();
const { push } = useToast();
const [tasks, setTasks] = useState<MaintenanceTask[]>([]);
const [running, setRunning] = useState<string | null>(null);
const [progress, setProgress] = useState<JobProgress | null>(null);
const [logs, setLogs] = useState<string[]>([]);
const [result, setResult] = useState<MaintenanceResult | null>(null);
const [error, setError] = useState<string | null>(null);
const job = useRef<string | null>(null);
useEffect(() => {
let alive = true;
void api
.maintenanceTasks()
.then((list) => alive && setTasks(list))
.catch((reason) => alive && setError(messageFrom(reason)));
return () => {
alive = false;
};
}, []);
const runTask = useCallback(
async (task: MaintenanceTask) => {
if (running) return;
const id = crypto.randomUUID?.() ?? String(Date.now());
job.current = id;
setRunning(task.id);
setResult(null);
setError(null);
setLogs([]);
setProgress(null);
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "note" && event.detail) {
setLogs((current) => [...current.slice(-200), event.detail as string]);
}
setProgress(event);
});
try {
const outcome = await api.maintenanceRun(id, task.id);
setResult(outcome);
if (outcome.ok) {
push(
lang === "zh"
? `${task.titleZh}:完成(用时 ${Math.round(outcome.durationMs / 1000)} 秒)`
: `${task.titleEn}: done (${Math.round(outcome.durationMs / 1000)}s)`,
"success",
);
} else {
push(
lang === "zh"
? `${task.titleZh}:在「${outcome.failedStep ?? "某一步"}」失败`
: `${task.titleEn}: failed at ${outcome.failedStep ?? "a step"}`,
"danger",
);
}
} catch (reason) {
setError(messageFrom(reason));
} finally {
stop();
setRunning(null);
setProgress(null);
job.current = null;
}
},
[lang, push, running],
);
return (
<div className="page maintenance-page">
<PageHeader
title={t("System maintenance", "系统维护")}
description={t(
"One-click repairs for the everyday complaints. Every command comes from a fixed whitelist — nothing here accepts free-form input.",
"常见故障一键修复。所有命令来自固定白名单,可显示原始输出;同类任务互斥执行。",
)}
/>
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<div className="maint-summary">
<ShieldCheck size={15} />
<span>
{t(
"All repairs below touch only system caches / services / indexes — never your documents.",
"以下修复只影响系统缓存 / 服务 / 索引,不碰你的文档。",
)}
</span>
</div>
<ul className="maint-list">
{tasks.map((task) => {
const [chipClass, chipZh, chipEn] = RISK_CHIP[task.risk];
const isRunning = running === task.id;
return (
<li key={task.id} className={`maint-row ${isRunning ? "is-running" : ""}`}>
<span className="maint-icon">
<Wrench size={16} />
</span>
<div className="maint-copy">
<b>{lang === "zh" ? task.titleZh : task.titleEn}</b>
<small>{lang === "zh" ? task.detailZh : task.detailEn}</small>
{isRunning && progress ? (
<ProgressCard
progress={progress}
title={lang === "zh" ? task.titleZh : task.titleEn}
compact
onCancel={() => {
if (job.current) void api.cancelJob(job.current);
}}
/>
) : null}
{isRunning && logs.length > 0 ? (
<pre className="maint-log" role="status">
{logs.slice(-8).join("\n")}
</pre>
) : null}
</div>
<span className="maint-estimate">{task.estimate}</span>
<span className={`maint-risk ${chipClass}`}>{lang === "zh" ? chipZh : chipEn}</span>
{isRunning ? (
<Button variant="ghost" size="sm" onClick={() => job.current && void api.cancelJob(job.current)}>
{t("Cancel", "取消")}
</Button>
) : (
<Button
variant="primary"
size="sm"
disabled={running !== null}
onClick={() => void runTask(task)}
>
{t("Repair", "修复")}
</Button>
)}
</li>
);
})}
{tasks.length === 0 && !error ? (
<li className="maint-row is-muted">
<Search size={16} />
{t("Loading the repair list…", "正在加载修复清单…")}
</li>
) : null}
</ul>
{result ? (
<div className={`maint-result ${result.ok ? "is-ok" : "is-fail"}`}>
{result.ok ? <Check size={15} /> : <AlertTriangle size={15} />}
<div>
<b>
{result.ok
? t("Repair completed", "修复完成")
: t("Repair stopped early", "修复提前停止")}
</b>
<ul>
{result.steps.map((step, index) => (
<li key={index}>
<Activity size={11} /> {step}
</li>
))}
</ul>
{result.outputTail ? (
<details>
<summary>{t("Command output", "命令输出")}</summary>
<pre>{result.outputTail}</pre>
</details>
) : null}
</div>
<Button variant="ghost" size="sm" onClick={() => setResult(null)}>
<X size={13} />
</Button>
</div>
) : null}
</div>
);
}

View File

@ -109,6 +109,7 @@ const RULE_NAMES: Record<string, [string, string]> = {
"update-installers-scan": ["Other update packages", "其他升级安装包"],
"purge-artifacts": ["Build artefacts", "项目构建产物"],
"user-assets": ["Your own files (locked)", "您的个人文件(受保护)"],
"ai-cache": ["AI app caches & update payloads", "AI 应用缓存与更新包"],
};
function ruleName(ruleId: string, lang: "zh" | "en"): string {
@ -119,11 +120,15 @@ function ruleName(ruleId: string, lang: "zh" | "en"): string {
}
/* Flat rule id → a normalised cluster key. Update installers cluster per
* app ("<app> · <file>" labels) so the list matches how people think. */
* app ("<app> · <file>" labels) so the list matches how people think;
* HuggingFace repos share one rule id but deserve one 清理点 each. */
function clusterKey(item: CleanupItem): string {
if (item.ruleId.startsWith("update-installers")) {
return `update:${item.label.split(" · ")[0] ?? item.label}`;
}
if (item.ruleId === "ai-huggingface") {
return `hf:${item.label}`;
}
return item.ruleId;
}
@ -137,6 +142,10 @@ function clusterLabel(item: CleanupItem, lang: "zh" | "en"): string {
const app = item.label.split(" · ")[0] ?? item.label;
return lang === "zh" ? `${app} 升级包` : `${app} installers`;
}
// AI model clusters carry a human label already ("Ollama · qwen3/8b").
if (item.ruleId.startsWith("ai-ollama-") || item.ruleId === "ai-huggingface") {
return item.label;
}
return ruleName(item.ruleId, lang);
}

View File

@ -7521,3 +7521,179 @@ html.widget-mode body {
color: #97826c;
font-size: var(--nex-text-3xs);
}
/* ---- system maintenance (系统维护) -------------------------------------- */
.maint-summary {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
border: 1px solid #bfe0c4;
border-radius: 12px;
background: rgba(88, 170, 98, 0.06);
color: #4b8a55;
font-size: var(--nex-text-3xs);
}
.maint-list {
margin: 12px 0 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
gap: 8px;
}
.maint-row {
display: flex;
align-items: center;
gap: 12px;
padding: 13px 15px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--card, #fffdf8);
}
.maint-row.is-running {
border-color: rgba(224, 95, 33, 0.4);
align-items: flex-start;
}
.maint-row.is-muted {
color: #97826c;
font-size: var(--nex-text-3xs);
}
.maint-icon {
flex: 0 0 auto;
display: inline-flex;
padding: 8px;
border-radius: 10px;
background: rgba(224, 95, 33, 0.08);
color: #b8531c;
}
.maint-copy {
flex: 1 1 auto;
min-width: 0;
}
.maint-copy b {
display: block;
color: #55493a;
font-size: var(--nex-text-2xs);
}
.maint-copy small {
display: block;
margin-top: 2px;
color: #8b94a0;
font-size: var(--nex-text-3xs);
}
.maint-log {
margin: 8px 0 0;
padding: 8px 10px;
border-radius: 8px;
background: #2b2620;
color: #d9cbb8;
font-family: var(--nex-font-mono, monospace);
font-size: 11px;
line-height: 1.5;
max-height: 120px;
overflow: auto;
white-space: pre-wrap;
}
.maint-estimate {
flex: 0 0 auto;
color: #97826c;
font-size: var(--nex-text-3xs);
white-space: nowrap;
}
.maint-risk {
flex: 0 0 auto;
padding: 2px 9px;
border-radius: 99px;
font-size: var(--nex-text-3xs);
white-space: nowrap;
}
.maint-risk.is-safe {
border: 1px solid #bfe0c4;
background: rgba(88, 170, 98, 0.08);
color: #4b8a55;
}
.maint-risk.is-admin {
border: 1px solid #ecd3bd;
background: rgba(224, 95, 33, 0.08);
color: #b8531c;
}
.maint-risk.is-slow {
border: 1px solid #d8cbe0;
background: rgba(150, 110, 170, 0.08);
color: #8a6a99;
}
.maint-result {
display: flex;
align-items: flex-start;
gap: 10px;
margin-top: 12px;
padding: 12px 15px;
border-radius: 13px;
font-size: var(--nex-text-3xs);
}
.maint-result.is-ok {
border: 1px solid #bfe0c4;
background: rgba(88, 170, 98, 0.06);
color: #4b8a55;
}
.maint-result.is-fail {
border: 1px solid #e6c2b8;
background: rgba(194, 84, 56, 0.06);
color: #b0563d;
}
.maint-result > div {
flex: 1 1 auto;
min-width: 0;
}
.maint-result ul {
margin: 6px 0 0;
padding: 0;
list-style: none;
color: #6d5b48;
}
.maint-result li {
display: flex;
align-items: center;
gap: 5px;
padding: 1px 0;
}
.maint-result details {
margin-top: 6px;
color: #6d7683;
}
.maint-result pre {
margin: 6px 0 0;
padding: 8px 10px;
border-radius: 8px;
background: #2b2620;
color: #d9cbb8;
font-family: var(--nex-font-mono, monospace);
font-size: 11px;
white-space: pre-wrap;
max-height: 200px;
overflow: auto;
}

View File

@ -344,6 +344,28 @@ export interface DupsResult {
elapsedMs: number;
}
// ---- system maintenance (系统维护) ---------------------------------------
export interface MaintenanceTask {
id: string;
titleEn: string;
titleZh: string;
detailEn: string;
detailZh: string;
risk: "safe" | "admin" | "slow";
budgetSecs: number;
estimate: string;
}
export interface MaintenanceResult {
task: string;
ok: boolean;
steps: string[];
failedStep: string | null;
outputTail: string;
durationMs: number;
}
// ---- large files (大文件) -------------------------------------------------
export interface LargeFile {