2026-10-13 09:00:50 +00:00
|
|
|
|
# squid 架构
|
|
|
|
|
|
|
|
|
|
|
|
本文描述 squid 的模块划分、数据流、安全不变量与跨平台方案。阅读顺序建议:先读「两条铁律」,再看 crate 图,最后按需查各引擎。
|
|
|
|
|
|
|
|
|
|
|
|
## 设计目标
|
|
|
|
|
|
|
|
|
|
|
|
1. **一台机器可以只有 245 GB,但用户的文件必须是无价的。** 所有设计里优先级最高的一条。
|
|
|
|
|
|
2. **单二进制、零常驻。** 没有 daemon、没有 launch agent、没有后台上传;`squid` 退出后不留痕迹。
|
|
|
|
|
|
3. **CLI 与 TUI 共用同一套引擎。** 终端界面不是玩具前端,`squid clean` 与 TUI 里的「清理」面板调用的是同一个函数。
|
|
|
|
|
|
4. **可脚本化。** 任何命令都能 `--json`、`--dry-run`、`--quiet`,退出码稳定。
|
|
|
|
|
|
|
|
|
|
|
|
非目标:不做实时文件系统监听、不做定时任务、不做 GUI(AppKit/SwiftUI)、不做云同步。
|
|
|
|
|
|
|
|
|
|
|
|
## 两条铁律(不变量)
|
|
|
|
|
|
|
|
|
|
|
|
**铁律一:扫描不删除。**
|
|
|
|
|
|
每个引擎都遵循 `Scan → Approve → Delete` 契约。`scan()` 只产出 `ScanReport`(一组 `CleanupItem`),幂等、无副作用,可以随时中断,可以对着 1 TB 的目录跑十次。
|
|
|
|
|
|
|
|
|
|
|
|
**铁律二:只有 `squid_engine::delete::execute` 能删东西。**
|
|
|
|
|
|
`squid-engine` 内部禁止直接调用 `std::fs::remove_*`。删除必须经过这一个函数,因此「安全校验 + 账本 + 废纸篓可还原」在架构上无法被绕过——新增引擎时想跳过检查,就只能显式地写出一条很难看代码评审的语句。
|
|
|
|
|
|
|
|
|
|
|
|
`execute` 做的事:丢弃嵌套重复项(父目录先删会让子项 ENOENT、体积重复计数)→ 对每个条目重新执行 `Engine::block_reason()`(锁、白名单、`SafetyPolicy`)→ 预先计算废纸篓目标路径 → 删除 → 写 ledger 会话。之所以要"重新校验",是因为一次扫描可能跑了几分钟,磁盘早就不一样了。
|
|
|
|
|
|
|
|
|
|
|
|
## crate 依赖图
|
|
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
┌──────────────┐
|
|
|
|
|
|
│ squid-core │ 模型 / 字节 / 路径 / 安全策略 / 设置 / 账本 / 进度
|
|
|
|
|
|
└──────┬───────┘
|
|
|
|
|
|
┌─────────┼──────────┐
|
|
|
|
|
|
┌──────▼─────┐ ┌─▼────────┐ │
|
|
|
|
|
|
│ squid- │ │ squid- │ │ ← 只依赖 core
|
|
|
|
|
|
│ platform │ │ rules │ │
|
|
|
|
|
|
└──────┬─────┘ └─┬────────┘ │
|
|
|
|
|
|
│ │ │
|
|
|
|
|
|
┌────▼─────────▼───────┐ │ ┌────────────┐
|
The system panel may stop a process, once it has asked who is sitting at that number
The system panel has listed processes for a while, and a list of what is running
gets one question asked of it more than any other: this one is wedged, make it
stop. A panel that can name the hung app and then shrugs is scenery, so the
answer here is yes — spent through the machinery the interface already has for
irreversible things, a dialog that names what it is about to do and a log line
afterwards that says what it did.
The *how* is two lines and not very interesting: `kill(2)` with `SIGKILL`, or
`OpenProcess(PROCESS_TERMINATE)` followed by `TerminateProcess`. Both are the
same promise, which is why `squid_platform::process::force_stop` is called a
forced stop on every platform and the dialog says 强制结束 rather than anything
about saving. There is no TERM-then-KILL handshake in here, because there is no
polite promise to keep: the second line of the dialog is 它不会有机会保存任何内容.
`squid_stats::Sampler::stop` does not use `sysinfo`'s own `Process::kill`, and
the reason is the shape of its answer. It returns `false` for every way a stop
can fail, and two of those ways want opposite things from the reader. `ESRCH`
means the process left on its own and nothing is owed but a redraw; `EPERM`
means it is alive and the reader should go find an elevated terminal. Windows
serves the same pair up as `ERROR_INVALID_PARAMETER` and `ERROR_ACCESS_DENIED`.
A bool cannot carry that difference, so squid makes the call itself and keeps
the words the OS gave, quoted inside a sentence this program owns — the OS's
sentence arrives in the language of the OS, and translates no further than its
own frame.
The *whether* is where the damage is, so it is answered twice. First by rule, in
`squid-platform`: never this squid, never the first process of the machine, and
on Windows never one of the six names a boot rests on. Those rules exist because
the operating system does not enforce all of them. An unelevated squid on macOS
cannot reach `WindowServer` whatever it tries; an elevated squid on Windows
*can* open `csrss.exe` for termination, and the reward for one misplaced Enter
is a machine that reboots without asking. Six names is the whole cost of that
guard. `svchost` is deliberately absent from it, because it hosts services a
user may genuinely need to restart and the machine survives losing one — which
is the test a name has to pass before it belongs on that list.
Then by the operating system, whose answer is the only one with any authority
over this user, this token, this moment. Between the two sits the question the
platform module cannot answer, because it is a question about a sample rather
than about a pid: is the process holding this number still the process whose
name the user read? Pids are seat numbers, handed out again, and a process table
is drawn the moment the panel opens and read from seconds later. So
`squid_stats::Sampler::stop` reads the pid again through the new `sample_of`,
applies the rules to the process that is really there, and calls a name that no
longer matches *gone* — the thing that was pointed at really is gone, whichever
direction the pid moved. `shown_name` is why that comparison means anything:
macOS hands over a path and Windows a bare name, and the process table had been
trimming with `split('/')`, which does nothing at all to a Windows path. Nothing
was wrong on screen, because the name was already short there; it became
evidence, and evidence has to be spelled one way.
`x` is the same verb it has always been. On the three file panels it makes the
row under the cursor go away; the system panel has nothing to delete and does
have a process, so the same finger reaches the same meaning, and
`x_is_still_the_delete_key_on_a_list_of_files` pins the old meaning down so that
this one cannot push it aside. `d` still deletes everywhere. The rules are
applied in `ask_stop_process` *before* the dialog rather than after the answer:
a dialog that can only be answered "no" teaches the user that the dialog is
theatre, and the toast that names the rule says the same thing in less time.
Three crates now each hold a `sleeper()`, which is a duplication worth keeping
on purpose. The thing under test has to be a process — `sleep 60`, or
`ping -n 60 127.0.0.1` where `sleep` is not — and a kill feature tested against
a struct is a kill feature that has never killed anything. Twelve tests come
with this: five in the platform module, including the boot list and a vacant pid
reporting itself as gone; three in the sampler, one of which hands a pid to
`stop` under the wrong name and then checks that the innocent process is still
running; four in the interface, walking `x`, `y`, and a refusal from the key
press to the corpse being reaped. 190 tests green across the workspace, with
`cargo fmt --check` and `cargo clippy --workspace --all-targets` clean for the
host and for `x86_64-pc-windows-msvc` — the target where the boot list,
`TerminateProcess` and the parameter-is-incorrect mapping compile at all, which
is also where `the_processes_a_boot_rests_on_are_named_not_guessed` exists.
The Windows 10/11 box carries the part a mac can only compile. `squid.exe`
there builds with `Win32_System_Threading`, clippy clean under `-D warnings`,
185 tests green; and the dialog was read off the screen rather than off the
buffer — `TUI_COLS=140 TUI_ROWS=35 TUI_CP=936`, 2604 samples of the raw ConPTY
stream, 291 settled frames, 0 of them failing the layout judge, including the
confirm itself: `╭ 结束 iNodeCmn.exe? ╮` / `pid 9080 · 1.2% · 15.4 MB` /
`它不会有机会保存任何内容` / `回车 / y 确认 · n / esc 取消`, and 「已取消」 after `n`.
`docs/ARCHITECTURE.md` gains the module and the key, and one of its diagrams
finally admits that `squid-stats` has depended on `squid-platform` for weeks.
2026-10-16 03:49:10 +00:00
|
|
|
|
│ squid-engine │◄─┼───┤ squid-stats│ ← 依赖 core 与 platform
|
2026-10-13 09:00:50 +00:00
|
|
|
|
└────┬────────────┬────┘ │ └─────┬──────┘
|
|
|
|
|
|
┌───────▼──┐ ┌────▼───────▼──┐ │
|
|
|
|
|
|
│ squid-tui│ │ squid-cli │◄─────┘
|
|
|
|
|
|
└──────────┘ └───────────────┘
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
依赖方向严格单向,`squid-core` 不知道其它任何 crate 的存在。
|
|
|
|
|
|
|
|
|
|
|
|
### squid-core
|
|
|
|
|
|
|
|
|
|
|
|
| 模块 | 关键类型 | 职责 |
|
|
|
|
|
|
| --- | --- | --- |
|
|
|
|
|
|
| `model` | `CleanupItem`, `Category`, `ItemKind`, `DeleteMode`, `LockReason`, `CleanSummary`, `ScanReport` | 唯一的数据货币。`CleanupItem{path, kind, size, category, label, rule_id, selected, allocated, lock, note, anchors}` |
|
|
|
|
|
|
| `bytes` | `Bytes`, `format_thousands` | 逻辑大小 vs 实际占盘大小(`st_blocks * 512`)两套口径 |
|
|
|
|
|
|
| `paths` | `expand`, `home_dir`, `pretty`, `label_for` | `~` 展开、`~/…` 显示、中文安全的路径缩短 |
|
|
|
|
|
|
| `fs` | `measure`, `measure_all`, `kind_of`, `remove_item_with`, `trash_path`, `trash_target_for`, `empty_trash` | 体积测量(walkdir + rayon 并行,忽略符号链接)、安全删除、跨卷回收站 |
|
|
|
|
|
|
| `safety` | `SafetyPolicy` | 见「安全模型」 |
|
|
|
|
|
|
| `settings` | `Settings`, `locale()` | `config.toml`、白名单、规则开关、`SQUID_CONFIG_DIR`/`SQUID_STATE_DIR` |
|
|
|
|
|
|
| `ledger` | `Session`, `LedgerEntry`, `write_session`, `load_sessions`, `restore` | 删除账本与 `undo` |
|
|
|
|
|
|
| `progress` | `Progress`, `Event`, `CancelToken` | 引擎与 UI 之间唯一的沟通渠道;跨线程通道,取消是协作式的 |
|
|
|
|
|
|
|
|
|
|
|
|
### squid-platform
|
|
|
|
|
|
|
|
|
|
|
|
`Platform` trait 把「这个操作系统上 App 装在哪、残留放在哪、卷怎么枚举、删除前要不要先停服务」抽象出来:
|
|
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
|
fn app_sources(&self) -> Vec<AppSource>;
|
|
|
|
|
|
fn list_apps(&self, cancel: &CancelToken, size_apps: bool) -> Result<Vec<AppInfo>>;
|
|
|
|
|
|
fn leftover_roots(&self) -> Vec<LeftoverRoot>;
|
|
|
|
|
|
fn prepare_uninstall(&self, app: &AppInfo) -> LifecycleReport; // 停 launchd / 注销 Launch Services
|
|
|
|
|
|
fn finish_uninstall(&self, app: &AppInfo, removed: &[PathBuf]) -> LifecycleReport;
|
|
|
|
|
|
fn volumes(&self) -> Result<Vec<Volume>>;
|
|
|
|
|
|
fn protected_prefixes(&self) -> Vec<PathBuf>;
|
|
|
|
|
|
fn running_executables(&self) -> Vec<String>; // 供 skip_if_running 使用
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
`LeftoverRoot { dir, naming, deep, category }` 描述一个残留目录以及它的命名方式(`BundleId` / `AppName` / `Either` / `GroupContainer`)。`deep` 默认 false —— `Application Support` 这种目录只匹配直接子项,绝不递归。
|
|
|
|
|
|
|
|
|
|
|
|
`leftovers::match_name` 负责把 `Xmind.app` 与 `com.xmind.win_zen.bundle`、`Xmind-state`、`Xmind Saved Application State` 之类关联起来。这里有两个曾经踩过的坑,回归测试已经锁住:
|
|
|
|
|
|
|
|
|
|
|
|
- 匹配前大小写要归一化(`Xmind` vs `xmind`);
|
|
|
|
|
|
- `KNOWN_SUFFIXES` 带点而文件名切分后不带点,两侧必须用同一种归一化形式比较(`has_known_suffix`)。另外 `.pdf/.png/.mp3` 这类文档后缀绝不能出现在「按名称匹配」的后缀表里,否则 `Xmind-notes.pdf` 会被当成残留删掉。
|
|
|
|
|
|
|
The command line pays for its chrome at the same counter
Three rounds were spent on a TUI that drew several frames over each other on
a cp936 console, and the fix worked: the interface asks the console what it
charges, per character, and draws ASCII where the console charges more than
the layout paid. Meanwhile `squid status`, printed in the same window on the
same machine, still produced a Storage table whose rows were each a screen
and a half long. Nothing in `main.rs` had ever asked what a `█` costs. It
repeats that character twenty-eight times for a gauge and lets the console
do the arithmetic, and the console's arithmetic is different.
`priced` is where a line stops being text and starts being cells, and `row!`
is the one door the body of every report prints through: the eleven places
that draw this program's chrome — the status key/value rows, the volume
gauges, the process table, the tree, the history rows, the whitelist
bullets, the rule headings and their `●`, the doctor's table — all of them
now go through it. It is a macro rather than a helper so the format
arguments stay where they were written, and one door rather than twelve
`println!`s of which eleven remember the console, because the twelfth is the
bug this whole thing is about.
Two refusals are the interesting part.
Nobody is stopped from seeing what a report actually says. Point the output
at a file or a pipe and the text comes back exactly as it was, because a
file is not a console: whatever glass reads the archive tomorrow may well
afford the `█`, and an archive of `#` is a worse record for the sake of a
screen that was never looking. The gate is the same tty question the live
progress line already asked — may this line overwrite a line — so
`live_stream_is_tty` is now `human_stream_is_tty`, since the two questions
have the same answer and deserve one function that says what it is asked.
And `--json` prints data, never through this: rewriting a person's report to
flatter their terminal is a different bug with the same fingerprint.
The price is not measured, even though measuring is what the interface does,
for the reason in `console::prices_unasked`: measurement spends characters,
and a command line is a guest on the screen it is printed to, sitting in a
pipeline or in front of a shell waiting for its next prompt. So it takes the
pessimistic answer the code page implies, which costs it a plainer gauge on
a console whose code page overcharges characters its font could have
carried. `█` becomes `#` there. A table that fits is worth more than a
prettier one that does not.
`no_line_of_chrome_escapes_the_counter` reads the file, with strings,
character literals and comments blanked, and demands that every `print!`,
`println!` and `eprintln!` either go through `priced` or print JSON or print
nothing. The scan exists because this mistake cannot be seen from the
machine it was made on: `println!(" {}", plan)` standing among eleven `row!`
calls is correct on every terminal that charges one cell for everything,
including the one it was typed on, and arrives folded over in front of
somebody else. It reads character literals as literals only when they close
again promptly, because `'static` is not the start of a character literal
and blanking from a lifetime to the next quote hides half a file from an
audit whose entire job is to look at all of it.
On the box, same pseudo-console, same 100x30 window, three reports per
capture and every one of them complete to `MARK_QUIT 0`. On cp936 — the code
page the user's own window is on — the decoded stream contains no `█`, no
`░`, no `─`, no `·`, no `…`, no arrow: the gauge reads
`[#######################.....]` and the headings are underlined with `-`.
On 65001 the same report keeps 104 `█`, 120 `░`, 236 `─`, 32 `·` and both
arrows. Same bytes of intent, two currencies, and the receipt is now in
both.
`win-tui-capture.sh` takes `TUI_ARGS=` so this evidence is repeatable rather
than hand-built: the default still captures the interface and judges it
frame by frame, and `TUI_ARGS="status"` captures a report, where the judge
is simply how many `█` survived.
The architecture document tells the story as one paragraph now, because it
is one story: `console::prices` measures and hands the answers to the
interface, `console::prices_unasked` guesses from the code page and hands
them to the command line, and each side has a test that keeps the characters
it draws and the characters it priced the same list.
178 tests here, two of them this commit's, clean under clippy for the host
and for `x86_64-pc-windows-msvc`, `cargo doc -D warnings` quiet over the
platform and the command line.
2026-10-16 02:32:05 +00:00
|
|
|
|
`console` 不在 `Platform` trait 里,但它回答的是同一类问题——「这台机器上的现实是什么」:控制台自称的窗口尺寸、它背后那块屏幕缓冲区的尺寸、它最大允许多大的窗口,以及一个「按 Unicode 只有 1 列宽」的字符在这里到底占几格。legacy conhost 在这两件事上都会给出错答案:进备用屏换掉的只是「正在显示的那块缓冲区」,进程的 stdout 句柄仍指着没人看的那一块,于是窗口比真正存在的格子更宽,写出一行的格子就落到下一行开头;cp936 码页又把 `─│·…↑↓✓` 这批 East Asian Ambiguous 字符收两格,而 ratatui 按一格排版。两者最后都表现为同一种花屏——屏上同时留着好几帧。所以 TUI 每一拍重新量一次尺寸(缓冲区被滚走、窗口被人拖大都算变化,只有真的变了才擦屏重画)。字形的价格归 `currency`:`Exchange` 按码位存一张兑换表,只在控制台确实多收钱时建,`afford` 在单格终端上原样返回。价是谁问的要分开说——`console::prices` 逐字符把答案量回来给界面,`squid_tui::glyphs` 因此只剩 ratatui 那一半:`witnesses` 从界面源码和 widget 里收集本界面会画的所有歧义字符,`Carry` 走一遍成品帧把付不起的字符换成 ASCII;`console::prices_unasked` 只取码页隐含的悲观答案给命令行,因为测量要往控制台上正显示的东西写一个字符再擦掉,而命令行是那台屏幕上的客人,它不该买这个答案,代价是在单格终端被码页误伤的机器上少一个 `█`、多一个 `#`。两边各有一条测试钉住「画的字符」与「问过的字符」是同一份:界面是 `every_glyph_this_interface_draws_has_a_price` 和 `the_probe_asks_the_price_of_everything_that_ends_up_on_the_screen`,命令行是 `no_line_of_chrome_escapes_the_counter`,它扫描 `main.rs`,要求除 JSON 和空行之外每个 print 都过 `priced`。`SQUID_SYMBOL_CELLS` 供人强制指定,`SQUID_CONSOLE_TRACE` 把控制台自己的几个数字写进文件留证。
|
2026-10-15 13:23:38 +00:00
|
|
|
|
|
The system panel may stop a process, once it has asked who is sitting at that number
The system panel has listed processes for a while, and a list of what is running
gets one question asked of it more than any other: this one is wedged, make it
stop. A panel that can name the hung app and then shrugs is scenery, so the
answer here is yes — spent through the machinery the interface already has for
irreversible things, a dialog that names what it is about to do and a log line
afterwards that says what it did.
The *how* is two lines and not very interesting: `kill(2)` with `SIGKILL`, or
`OpenProcess(PROCESS_TERMINATE)` followed by `TerminateProcess`. Both are the
same promise, which is why `squid_platform::process::force_stop` is called a
forced stop on every platform and the dialog says 强制结束 rather than anything
about saving. There is no TERM-then-KILL handshake in here, because there is no
polite promise to keep: the second line of the dialog is 它不会有机会保存任何内容.
`squid_stats::Sampler::stop` does not use `sysinfo`'s own `Process::kill`, and
the reason is the shape of its answer. It returns `false` for every way a stop
can fail, and two of those ways want opposite things from the reader. `ESRCH`
means the process left on its own and nothing is owed but a redraw; `EPERM`
means it is alive and the reader should go find an elevated terminal. Windows
serves the same pair up as `ERROR_INVALID_PARAMETER` and `ERROR_ACCESS_DENIED`.
A bool cannot carry that difference, so squid makes the call itself and keeps
the words the OS gave, quoted inside a sentence this program owns — the OS's
sentence arrives in the language of the OS, and translates no further than its
own frame.
The *whether* is where the damage is, so it is answered twice. First by rule, in
`squid-platform`: never this squid, never the first process of the machine, and
on Windows never one of the six names a boot rests on. Those rules exist because
the operating system does not enforce all of them. An unelevated squid on macOS
cannot reach `WindowServer` whatever it tries; an elevated squid on Windows
*can* open `csrss.exe` for termination, and the reward for one misplaced Enter
is a machine that reboots without asking. Six names is the whole cost of that
guard. `svchost` is deliberately absent from it, because it hosts services a
user may genuinely need to restart and the machine survives losing one — which
is the test a name has to pass before it belongs on that list.
Then by the operating system, whose answer is the only one with any authority
over this user, this token, this moment. Between the two sits the question the
platform module cannot answer, because it is a question about a sample rather
than about a pid: is the process holding this number still the process whose
name the user read? Pids are seat numbers, handed out again, and a process table
is drawn the moment the panel opens and read from seconds later. So
`squid_stats::Sampler::stop` reads the pid again through the new `sample_of`,
applies the rules to the process that is really there, and calls a name that no
longer matches *gone* — the thing that was pointed at really is gone, whichever
direction the pid moved. `shown_name` is why that comparison means anything:
macOS hands over a path and Windows a bare name, and the process table had been
trimming with `split('/')`, which does nothing at all to a Windows path. Nothing
was wrong on screen, because the name was already short there; it became
evidence, and evidence has to be spelled one way.
`x` is the same verb it has always been. On the three file panels it makes the
row under the cursor go away; the system panel has nothing to delete and does
have a process, so the same finger reaches the same meaning, and
`x_is_still_the_delete_key_on_a_list_of_files` pins the old meaning down so that
this one cannot push it aside. `d` still deletes everywhere. The rules are
applied in `ask_stop_process` *before* the dialog rather than after the answer:
a dialog that can only be answered "no" teaches the user that the dialog is
theatre, and the toast that names the rule says the same thing in less time.
Three crates now each hold a `sleeper()`, which is a duplication worth keeping
on purpose. The thing under test has to be a process — `sleep 60`, or
`ping -n 60 127.0.0.1` where `sleep` is not — and a kill feature tested against
a struct is a kill feature that has never killed anything. Twelve tests come
with this: five in the platform module, including the boot list and a vacant pid
reporting itself as gone; three in the sampler, one of which hands a pid to
`stop` under the wrong name and then checks that the innocent process is still
running; four in the interface, walking `x`, `y`, and a refusal from the key
press to the corpse being reaped. 190 tests green across the workspace, with
`cargo fmt --check` and `cargo clippy --workspace --all-targets` clean for the
host and for `x86_64-pc-windows-msvc` — the target where the boot list,
`TerminateProcess` and the parameter-is-incorrect mapping compile at all, which
is also where `the_processes_a_boot_rests_on_are_named_not_guessed` exists.
The Windows 10/11 box carries the part a mac can only compile. `squid.exe`
there builds with `Win32_System_Threading`, clippy clean under `-D warnings`,
185 tests green; and the dialog was read off the screen rather than off the
buffer — `TUI_COLS=140 TUI_ROWS=35 TUI_CP=936`, 2604 samples of the raw ConPTY
stream, 291 settled frames, 0 of them failing the layout judge, including the
confirm itself: `╭ 结束 iNodeCmn.exe? ╮` / `pid 9080 · 1.2% · 15.4 MB` /
`它不会有机会保存任何内容` / `回车 / y 确认 · n / esc 取消`, and 「已取消」 after `n`.
`docs/ARCHITECTURE.md` gains the module and the key, and one of its diagrams
finally admits that `squid-stats` has depended on `squid-platform` for weeks.
2026-10-16 03:49:10 +00:00
|
|
|
|
`process` 也只回答一个「这台机器上怎么停掉一个进程」的问题,而它值一个模块的理由是「为什么没停掉」必须由操作系统来回答。`force_stop(pid)` 在 unix 上发 `SIGKILL`,在 Windows 上 `OpenProcess(PROCESS_TERMINATE)` + `TerminateProcess`,两边是同一个承诺:立刻停,不保存任何东西——所以界面在三套系统上都写「强制结束」,而不是它并没做过的「退出」。`sysinfo` 的 `Process::kill()` 也能办成这件事,但它只回一个 `false`,而 `EPERM`(你不是那个用户 → 换个提权的终端)和 `ESRCH`(它自己早走了 → 什么都不用做)要求的动作恰恰相反,把两种结果压成同一句报错,等于教用户从此不再信报错。规则也放在这里,因为操作系统并不拦下一切:非提权进程本来就碰不到 macOS 的 `WindowServer`,但提权后的 `squid` 在 Windows 上是真的能打开 `csrss.exe` 的,一次按错的回车换来一次不带询问的重启,六个名字的表换这个结果是划算的(`svchost` 故意不在表里:它承载的服务用户确实可能要重启,且少一个也不至于起不来)。`pid_refusal` 与 `refusal` 拆成两个问题,因为它们被问的时刻不同:前者问的是界面手里那个数字,后者要等真正读到进程的名字。这个模块只对着 pid 说话——「此刻的 pid 还是不是用户读到的那个进程」是关于 sample 的问题,问在 sample 待着的地方。
|
|
|
|
|
|
|
2026-10-13 09:00:50 +00:00
|
|
|
|
### squid-rules
|
|
|
|
|
|
|
|
|
|
|
|
规则是 TOML,内置于 `crates/squid-rules/rules/macos.toml`(39 条),通过 `include_str!` 编译进二进制;用户规则从 `<config_dir>/rules/*.toml` 合并,同 `id` 覆盖内置。
|
|
|
|
|
|
|
|
|
|
|
|
```toml
|
|
|
|
|
|
[[rule]]
|
|
|
|
|
|
id = "xcode-derived-data"
|
|
|
|
|
|
category = "developer"
|
|
|
|
|
|
patterns = ["~/Library/Developer/Xcode/DerivedData/*"]
|
|
|
|
|
|
mode = "path" # path = 删除条目本身;contents = 只清空目录内容
|
|
|
|
|
|
os = ["macos"]
|
|
|
|
|
|
protect = ["SomeKeep", "SomeKeep/*"]
|
|
|
|
|
|
min_age_days = 3
|
|
|
|
|
|
select_by_default = true
|
|
|
|
|
|
needs_admin = false
|
|
|
|
|
|
skip_if_running = ["Docker Desktop", "com.docker.backend"]
|
|
|
|
|
|
risky = true
|
|
|
|
|
|
note = "Xcode 会重新生成。"
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
核心是 `expand_pattern(pattern) -> Vec<Match{path, anchor}>`:
|
|
|
|
|
|
|
|
|
|
|
|
- `*` **不跨越路径分隔符**(globset 语义),所以 `~/Library/Caches/*` 只会命中一层;
|
|
|
|
|
|
- 每条匹配都携带 **anchor(锚点)** —— 模式的最长字面量前缀。锚点是删除时的权限边界:`SafetyPolicy` 只允许在锚点之下删除,且拒绝锚点自身。这条设计使得「一条规则写错」的最坏后果被限制在该规则自己的目录里;
|
|
|
|
|
|
- 不含通配符的字面模式(如 `~/.cargo/.package-cache`)匹配的是这个文件本身、锚点取其父目录。曾经有个 bug 是把锚点当成了匹配结果,等于提出删除整个 `~/.cargo`——已有回归测试 `wildcard_free_patterns_match_the_file_not_the_parent`。
|
|
|
|
|
|
|
|
|
|
|
|
`risky` 与 `skip_if_running` 是给「体积巨大但语义危险」的规则准备的刹车,典型是 `container-images`:Docker 的 VM 磁盘可能有 1 TB,一旦正在运行还去删就是数据事故,所以它既不默认勾选、又在检测到 Docker/OrbStack 进程时直接锁定。
|
|
|
|
|
|
|
|
|
|
|
|
### squid-stats
|
|
|
|
|
|
|
|
|
|
|
|
`Sampler::{new, prime, refresh}` 基于 `sysinfo`,两次采样之间才有 CPU%/网速,因此 `prime()` 是必须的预热步骤。产出 `SystemSnapshot{cpu, memory, network, disk, uptime_secs, top_processes, volumes, battery, host}` 与 `TrendStore`(滚动历史,给 TUI 的迷你折线/柱状图)。`battery.rs`、`human_uptime()` 提供 iStat 式细节。
|
|
|
|
|
|
|
The system panel may stop a process, once it has asked who is sitting at that number
The system panel has listed processes for a while, and a list of what is running
gets one question asked of it more than any other: this one is wedged, make it
stop. A panel that can name the hung app and then shrugs is scenery, so the
answer here is yes — spent through the machinery the interface already has for
irreversible things, a dialog that names what it is about to do and a log line
afterwards that says what it did.
The *how* is two lines and not very interesting: `kill(2)` with `SIGKILL`, or
`OpenProcess(PROCESS_TERMINATE)` followed by `TerminateProcess`. Both are the
same promise, which is why `squid_platform::process::force_stop` is called a
forced stop on every platform and the dialog says 强制结束 rather than anything
about saving. There is no TERM-then-KILL handshake in here, because there is no
polite promise to keep: the second line of the dialog is 它不会有机会保存任何内容.
`squid_stats::Sampler::stop` does not use `sysinfo`'s own `Process::kill`, and
the reason is the shape of its answer. It returns `false` for every way a stop
can fail, and two of those ways want opposite things from the reader. `ESRCH`
means the process left on its own and nothing is owed but a redraw; `EPERM`
means it is alive and the reader should go find an elevated terminal. Windows
serves the same pair up as `ERROR_INVALID_PARAMETER` and `ERROR_ACCESS_DENIED`.
A bool cannot carry that difference, so squid makes the call itself and keeps
the words the OS gave, quoted inside a sentence this program owns — the OS's
sentence arrives in the language of the OS, and translates no further than its
own frame.
The *whether* is where the damage is, so it is answered twice. First by rule, in
`squid-platform`: never this squid, never the first process of the machine, and
on Windows never one of the six names a boot rests on. Those rules exist because
the operating system does not enforce all of them. An unelevated squid on macOS
cannot reach `WindowServer` whatever it tries; an elevated squid on Windows
*can* open `csrss.exe` for termination, and the reward for one misplaced Enter
is a machine that reboots without asking. Six names is the whole cost of that
guard. `svchost` is deliberately absent from it, because it hosts services a
user may genuinely need to restart and the machine survives losing one — which
is the test a name has to pass before it belongs on that list.
Then by the operating system, whose answer is the only one with any authority
over this user, this token, this moment. Between the two sits the question the
platform module cannot answer, because it is a question about a sample rather
than about a pid: is the process holding this number still the process whose
name the user read? Pids are seat numbers, handed out again, and a process table
is drawn the moment the panel opens and read from seconds later. So
`squid_stats::Sampler::stop` reads the pid again through the new `sample_of`,
applies the rules to the process that is really there, and calls a name that no
longer matches *gone* — the thing that was pointed at really is gone, whichever
direction the pid moved. `shown_name` is why that comparison means anything:
macOS hands over a path and Windows a bare name, and the process table had been
trimming with `split('/')`, which does nothing at all to a Windows path. Nothing
was wrong on screen, because the name was already short there; it became
evidence, and evidence has to be spelled one way.
`x` is the same verb it has always been. On the three file panels it makes the
row under the cursor go away; the system panel has nothing to delete and does
have a process, so the same finger reaches the same meaning, and
`x_is_still_the_delete_key_on_a_list_of_files` pins the old meaning down so that
this one cannot push it aside. `d` still deletes everywhere. The rules are
applied in `ask_stop_process` *before* the dialog rather than after the answer:
a dialog that can only be answered "no" teaches the user that the dialog is
theatre, and the toast that names the rule says the same thing in less time.
Three crates now each hold a `sleeper()`, which is a duplication worth keeping
on purpose. The thing under test has to be a process — `sleep 60`, or
`ping -n 60 127.0.0.1` where `sleep` is not — and a kill feature tested against
a struct is a kill feature that has never killed anything. Twelve tests come
with this: five in the platform module, including the boot list and a vacant pid
reporting itself as gone; three in the sampler, one of which hands a pid to
`stop` under the wrong name and then checks that the innocent process is still
running; four in the interface, walking `x`, `y`, and a refusal from the key
press to the corpse being reaped. 190 tests green across the workspace, with
`cargo fmt --check` and `cargo clippy --workspace --all-targets` clean for the
host and for `x86_64-pc-windows-msvc` — the target where the boot list,
`TerminateProcess` and the parameter-is-incorrect mapping compile at all, which
is also where `the_processes_a_boot_rests_on_are_named_not_guessed` exists.
The Windows 10/11 box carries the part a mac can only compile. `squid.exe`
there builds with `Win32_System_Threading`, clippy clean under `-D warnings`,
185 tests green; and the dialog was read off the screen rather than off the
buffer — `TUI_COLS=140 TUI_ROWS=35 TUI_CP=936`, 2604 samples of the raw ConPTY
stream, 291 settled frames, 0 of them failing the layout judge, including the
confirm itself: `╭ 结束 iNodeCmn.exe? ╮` / `pid 9080 · 1.2% · 15.4 MB` /
`它不会有机会保存任何内容` / `回车 / y 确认 · n / esc 取消`, and 「已取消」 after `n`.
`docs/ARCHITECTURE.md` gains the module and the key, and one of its diagrams
finally admits that `squid-stats` has depended on `squid-platform` for weeks.
2026-10-16 03:49:10 +00:00
|
|
|
|
界面既然能列出谁在跑,就会被要求停掉谁,`Sampler::stop(sample)` 是这件事唯一的入口。它先按 pid 挡掉 squid 自己、机器的第一个进程和 Windows 的 System,再用 `sample_of(pid)` 重读一次:读不到就是「已经不在了」,读到的名字对不上也算「已经不在了」(用户指着的那个进程确实没了,无论 pid 朝哪个方向移动),只有名字仍然相符,才轮到 `squid_platform::process::force_stop`。名字之所以能当这个凭据,靠的是 `top_processes`、`applications` 与 `sample_of` 共用同一个 `shown_name`——三处各自截一次尾段,凭据就有三份写法。`sample_of` 是公开的:它给的正是界面此刻会为这个 pid 画出来的那一行,测试拿它造一条诚实的行,界面将来只重画一行也用得上。键位是 `x`:它在文件面板上一直是「删除」,系统状态面板上没有可删的东西、只有进程,同样的手指落到同样的动词上。规则当场命中的那些(自己、第一个进程、Windows 的引导进程)直接 toast 原因、不弹确认框:为一个规则注定会拒绝的动作去要许可,是把确认框变成戏剧。
|
|
|
|
|
|
|
2026-10-13 09:00:50 +00:00
|
|
|
|
### squid-engine
|
|
|
|
|
|
|
|
|
|
|
|
| 引擎 | 做法 |
|
|
|
|
|
|
| --- | --- |
|
|
|
|
|
|
| `clean` | 遍历规则 → `expand_pattern` → `protect`/年龄/白名单/运行中过滤 → `measure_all` 并行测体积 → `sort_for_display` 按分组排序。`--orphans` 会额外调用平台残留匹配,寻找已消失 App 的孤儿目录 |
|
|
|
|
|
|
| `uninstall` | `scan_apps` 建立 App 清单(名称、bundle id、体积、是否运行中、Homebrew cask)→ `find` 模糊定位 → `build_plan` 生成「本体 + 按 bundle id/名称匹配的残留」→ 用户确认 → `remove_plan`(含平台 `prepare_uninstall`/`finish_uninstall` 钩子)。共享给同厂商多个安装的残留会被 `LockReason::SharedWithOtherInstall` 锁住 |
|
|
|
|
|
|
| `purge` | 遍历 `purge_roots`(或用户给定路径,默认深度 6、最多 30 万目录),把 `ALWAYS`(node_modules、target、DerivedData、`.venv`…)识别为可再生;`AMBIGUOUS`(dist、build、out、venv…)只有当同目录存在 `package.json`/`Cargo.toml`/`go.mod` 等 PROJECT_MARKERS、或用户显式 `--all` 时才提出。`DO_NOT_DESCEND` 阻止进入 `.git`、Library、挂载点等。附带 APFS 本地快照(`com.apple.TimeMachine*`)与旧 iOS 备份、磁盘镜像等非目录项 |
|
|
|
|
|
|
| `analyze` | DaisyDisk 式体积树:`explore`/`expand` 逐层展开、`largest_files`、`buckets` 分类聚合。总量在遍历超限时标记为下限而非真值 |
|
|
|
|
|
|
|
|
|
|
|
|
### squid-tui
|
|
|
|
|
|
|
|
|
|
|
|
ratatui + crossterm。六个面板 `Cleanup / Uninstall / Purge / Storage / Stats / History`,`App` 是唯一状态机,键盘事件 → `Action` → 重绘。
|
|
|
|
|
|
|
|
|
|
|
|
- **绝不阻塞 UI**:每个引擎调用都通过 `job::spawn` 跑到独立线程,返回 `JobHandle<T>`;`Progress` 事件与最终结果走两条 crossbeam 通道,事件循环 `poll()` 非阻塞取结果。取消是协作式的 `CancelToken`。
|
|
|
|
|
|
- 每个 job 自己 `Engine::new()`,避免跨线程借用,代价是每次扫描重读一遍小 TOML。
|
|
|
|
|
|
- `theme::Strings::t(en, zh)` 集中管理双语文案,`Palette`/`card()` 复刻 CleanMyMac 的暗色卡片观感(背景 `Rgb(16,18,23)`、强调色 `Rgb(86,182,246)`、圆角卡片)。
|
|
|
|
|
|
调色板只写 RGB,输出一律经 `Palette::resolve`:`SQUID_TRUECOLOR` → `COLORTERM` → `TERM_PROGRAM` → `TERM`
|
|
|
|
|
|
依次探测真彩色能力,不支持时映射到 xterm-256(灰阶走 24 级灰条)。Terminal.app 只认 256 色,
|
|
|
|
|
|
少了这一步它会把 `48;2;…` 当文字打出来,暗色主题直接变成白底黑字。
|
|
|
|
|
|
- **选中状态不能只靠颜色**:`Palette::selected_for(truecolor)` 在真彩色下是强调色条,降级终端里是
|
|
|
|
|
|
`REVERSED | BOLD`(反白由终端自身的前景色/背景色完成,灰度终端同样成立);勾选状态另有加粗 `●`
|
|
|
|
|
|
与细体 `○` 两条冗余通道。`close_gaps` 负责让高亮行成为连续的一整条:列分隔用的是无样式
|
|
|
|
|
|
`Span::raw(" ")`,反白时会在行里留下一道道暗缝,所以只在「整行非空白 span 样式一致」时把空白也染上;
|
|
|
|
|
|
路径列只截断不补齐,因此 `item_row` 末尾还会按显示宽度补一段同色空格,让高亮条一直顶到卡片右边框。
|
The app list counted its own header as a row, and the cursor paid for it
Uninstall came back from the Windows box saying the thing it had already said
on macOS: once there are more apps than a page, paging down leaves the list
with no highlight anywhere. Two consoles that have spent this branch being
taught what a `█` costs agree with each other about nothing, so a complaint
that survives both of them is not standing in the console. It was standing in
`draw_uninstall`, and it had been there since the panel was written.
The panel pushes its column header — `size name version source`, plus a filter
chip while a filter is standing — into the same `List` widget that holds the
apps, and paints the highlight by asking whether `row == cursor`, where `row`
counts the apps that `visible()` returned. `ListState::selected` is handed that
same `app.uninstall.cursor`: a number in the space of visible apps, in a widget
whose rows are that space plus one, plus two with the chip. ratatui spends
`selected` on exactly one thing in this configuration, because `highlight_style`
is empty on purpose — the row paints its own highlight so that a cursor survives
a terminal with no colour at all — so the disagreement cannot mispaint a row.
What it can do is decide which rows exist on screen: the scroll window is
positioned around the row one above the cursor. While the list fits in the card,
or while the cursor is high enough in a list that does not, the cursor is inside
the window either way and the header costs nothing. That is why this needed a
machine with more installed apps than a fixture has, and why the same binary
lied the same way on both platforms.
`ScanPanel::lines` has never shown the symptom, and the reason is worth naming
rather than admiring: it holds entries and nothing else, because the heading of
that card lives on the `Block`. One widget, one index space, nothing to drift.
The uninstall *plan* was taught the same lesson from the other direction — it
used to swap item zero for a bundle heading, which held only while the `.app`
was the largest thing in the plan, until a container outgrew it and every row
under the heading sat one line away from its cursor. The app list was the third
place a header had been allowed to spend a row, and the only one nobody had
asked about.
The fix declines to count anything. `chrome` and the entries are two constraints
of one vertical `Layout`: the `Paragraph` takes the first rectangle, the `List`
gets a rectangle holding entries only, and `selected` and `band()` are back to
describing the same rows. Nowhere in the file is `cursor + header_lines` written
down, because an offset is the thing that just went wrong, and the next line of
chrome added to this header would need one of its own.
`the_app_under_the_cursor_is_the_row_that_is_on_screen` is the regression test,
and it loops over every cursor position rather than picking a deep one, because
whether one deep cursor fails depends on how tall the card happens to be where
the test is running — which is a measurement of a machine, not an invariant. For
each position it draws 140x34 and asks the buffer two questions: is the app under
the cursor on the screen at all, and is the cell it landed on wearing the accent
background and the bold that a highlight paints. The series runs twice, once with
the filter chip on screen, because the chip is the second row of the two index
spaces that were drifting apart. Before the fix it stops at cursor 25 with "the
app under the cursor is off screen". Nothing on the screen had been drawn
wrongly, which is the shape of this bug: every row was correct, and the only
thing missing was the cursor.
68 tests in the interface crate, one of them this one, green; `cargo fmt
--check` and `cargo clippy --workspace --all-targets` clean for the host.
2026-10-16 03:17:18 +00:00
|
|
|
|
- **一个 widget 只有一套下标**:`ListState::selected` 是 ratatui 用来定位滚动窗口的行号,高亮却由每一行自己画,两者必须数同一批行。卸载列表把「大小/名称/版本」表头(筛选时还多一行 filter chip)和条目一起塞进同一个 `List`,`selected` 就此比样式多算了一两行:第一屏看不出来,列表一超过一页,窗口按「光标上面那一行」定位,高亮行被挤出可视区,用户看到的是「下翻之后没有高亮了」——Mac 与 Windows 同因,因为它跟终端无关。清理面板从不出现这个现象,`ScanPanel::lines` 里只有条目,标题挂在 card 的 block 上。现在的写法把表头和 filter chip 当作 chrome 单独走一段 `Layout`:`Paragraph` 拿上面,`List` 只拿条目。`the_app_under_the_cursor_is_the_row_that_is_on_screen` 遍历每一个光标位置(含筛选态)断言「光标那一行就是屏幕上那一行、且带着强调色与加粗」,因为它无法靠猜某个卡片高度通过。
|
2026-10-13 09:00:50 +00:00
|
|
|
|
|
|
|
|
|
|
### squid-cli
|
|
|
|
|
|
|
|
|
|
|
|
clap derive。约定:
|
|
|
|
|
|
|
|
|
|
|
|
- `--json` 时 stdout 只允许是数据。所有人类可读输出经 `DIAG_STDERR` 改道 stderr,`squid clean --json | jq` 永远干净;
|
|
|
|
|
|
- stdin 不是 TTY 且没有 `-y/--yes` 时,拒绝执行真实删除;
|
|
|
|
|
|
- 输出宽度按 `terminal_width()` 自适应,列宽用显示宽度(CJK 占两列)对齐,`clip` 截断 + `fit` 补空格。
|
|
|
|
|
|
|
|
|
|
|
|
## 安全模型(分层)
|
|
|
|
|
|
|
|
|
|
|
|
| 层 | 位置 | 拦截什么 |
|
|
|
|
|
|
| --- | --- | --- |
|
|
|
|
|
|
| 规则自我约束 | `squid-rules` | `protect`、`min_age_days`、`select_by_default=false`、`risky`、`skip_if_running`、`os` |
|
|
|
|
|
|
| 锚点边界 | `CleanupItem::anchors` + `SafetyPolicy::check` | 只允许在规则声明的锚点之下删除,且永不删除锚点自身 |
|
|
|
|
|
|
| 硬性禁区 | `safety::HARD_DENY` | `/`、`/usr`、`/System`、`/Library`、`/Applications`、`/private/var/folders`、`/Volumes`… 无论什么规则都拒绝 |
|
|
|
|
|
|
| 危险目录 | `safety::DENY_EXACT` | `~/Library`、`~/Documents`、`~/.ssh`、`~/.aws`、`~/Library/Application Support/MobileSync`… 允许删子项、禁止整目录递归删 |
|
|
|
|
|
|
| 深度 / 家目录 / 符号链接 | `SafetyPolicy{min_depth, allow_system_paths, follow_symlinks}` | 非 root 时拒绝家目录之外的路径(`OUTSIDE_HOME_OK` 例外);递归删除必须有最小深度;永不跟随符号链接 |
|
|
|
|
|
|
| 卷 | `forbidden_mounts` | 由 `platform.volumes()` 注入,不删别的卷 |
|
|
|
|
|
|
| 用户白名单 | `Engine::is_whitelisted` | glob 命中即永不选中 |
|
|
|
|
|
|
| 运行时状态 | `LockReason` | App 正在运行、被其它安装共享、权限不属于当前用户 |
|
|
|
|
|
|
| 兜底 | 默认 Trash + `--dry-run` + 账本 + `undo` | 前面全漏了还能还原 |
|
|
|
|
|
|
|
|
|
|
|
|
`Engine::new()` 会根据是否 root 选择 `SafetyPolicy::system()` 或 `user_only()`,后者拒绝家目录之外的路径,
|
|
|
|
|
|
例外只有 `OUTSIDE_HOME_OK = ["/Applications"]`:管理员组的普通用户在 Finder 里把 App 拖进废纸篓不需要密码,
|
|
|
|
|
|
卸载器必须做同一件事。例外只覆盖 `/Applications` **里的条目**(目录本身仍在 `HARD_DENY`),
|
|
|
|
|
|
且 root 拥有的 App 早在 `build_plan` 就被 `writable_by_us` 锁住了。
|
|
|
|
|
|
|
|
|
|
|
|
### 事故记录:卸载「成功」了,App 还在
|
|
|
|
|
|
|
|
|
|
|
|
一次用户反馈「选中 Chatbox → d → 确认 → 毫无反应」,最后挖出四层独立原因,每一层都足以让事故静默:
|
|
|
|
|
|
|
|
|
|
|
|
1. `pending_plan` 从未被赋值(见下一节);
|
|
|
|
|
|
2. 任务运行期间所有变更键被 `if self.busy() { return }` 静默吞掉,`confirm_delete()` 还会顺手清空
|
|
|
|
|
|
`confirm` + `pending`——用户的「是」被吃掉了。现在统一走 `App::busy_refusal()`,明确提示「上一个任务
|
|
|
|
|
|
还在进行,或按 c 取消」,并且**保留**审批;
|
|
|
|
|
|
3. **App 本体的锚点不存在**:`.app` 条目过去复用 `default_anchors()`,而那份锚点表里根本没有
|
|
|
|
|
|
`/Applications`——它是「squid 被允许进去打扫的文件夹」清单,应用程序目录不是。于是每个卸载计划都是
|
|
|
|
|
|
批准 6 项、删除 5 项,`.app` 带着「outside every declared cleanup anchor」被跳过。现在
|
|
|
|
|
|
`bundle_anchors()` 取 bundle 的**父目录**作为锚点,既最小又不越权;
|
|
|
|
|
|
4. **非 root 走不到 `/Applications`**:`user_only()` 的家目录规则把系统 App 一律拒绝。见上面的
|
|
|
|
|
|
`OUTSIDE_HOME_OK`。
|
|
|
|
|
|
|
|
|
|
|
|
同一次排查还修了 Plan 视图的一个隐性错位:它用 `index == 0` 认定第一行是「应用本体」,而
|
|
|
|
|
|
`build_plan` 是按体积降序排序的——一旦某个容器比 App 大,就有一项残留被藏进表头、下面每行都错一位。
|
|
|
|
|
|
现在按 `rule_id == "uninstall-bundle"` 识别,行与光标严格一一对应。
|
|
|
|
|
|
|
|
|
|
|
|
教训写进断言里:`the_bundle_itself_passes_the_safety_policy`、
|
|
|
|
|
|
`a_plain_user_can_still_uninstall_into_applications`、`a_busy_app_answers_instead_of_ignoring_you`、
|
|
|
|
|
|
`the_plan_view_shows_the_bundle_and_every_leftover`(后者读回测试缓冲区:三项计划必须画出三个勾选行、
|
|
|
|
|
|
表头文案不得占据其中任何一行、加粗的那一行永远是 `.app`、光标落在哪一行就高亮哪一行)。
|
|
|
|
|
|
删除路径的测试必须把沙盒建在**真实形态**的位置上:早先的卸载测试把假 App 放在 `~/Library/Caches/…` 下,
|
|
|
|
|
|
正好落在锚点里,所以这个 bug 一路绿灯。
|
|
|
|
|
|
|
|
|
|
|
|
## 数据流
|
|
|
|
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
config.toml ─┐
|
|
|
|
|
|
├─► Engine{platform, settings, rules, safety, whitelist}
|
|
|
|
|
|
rules/*.toml ┘ │
|
|
|
|
|
|
├── scan() ─► Vec<CleanupItem> ─► CLI 表格 / TUI 面板
|
|
|
|
|
|
│ │ 用户勾选
|
|
|
|
|
|
│ ▼
|
|
|
|
|
|
└── delete::execute(DeleteJob) ─► SafetyPolicy 复检
|
|
|
|
|
|
│ fs::remove_item_with
|
|
|
|
|
|
│ ledger::write_session
|
|
|
|
|
|
▼
|
|
|
|
|
|
~/Library/Application Support/squid/history/<session>.json
|
|
|
|
|
|
│
|
|
|
|
|
|
squid undo ─► ledger::restore ─► rename 回原路径
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## 性能
|
|
|
|
|
|
|
|
|
|
|
|
体积测量是这类工具唯一的重活。做法:`walkdir`(`contents_first(false)`、`max_open(64)`、跳过符号链接)单目录内顺序遍历,`measure_all` 在条目之间用 rayon 并行(线程数 `clamp(4,16)`),每完成一个条目就发一次进度事件,所以 UI 的进度条是真实进度而不是假动画。`purge` 用 `max_entries` 限制单项目文件数、`MAX_DIRS` 限制总目录数,超限时明确标注结果是下限。实测 `clean --dry-run` 在 18 万条目 / 30 GB 量级上约 5 秒。
|
|
|
|
|
|
|
|
|
|
|
|
## 跨平台移植指南
|
|
|
|
|
|
|
|
|
|
|
|
新增一个平台 = 实现 `Platform` + 提供规则文件,**引擎与 UI 一行都不用改**。
|
|
|
|
|
|
|
|
|
|
|
|
1. 新建 `squid-platform/src/<os>.rs`,实现 `Platform`;在 `lib.rs::current()` 里返回它。
|
|
|
|
|
|
2. 决定 `app_sources()` 与 `leftover_roots()`:命名方式(bundle id / 名称 / 容器)决定残留匹配器怎么配。
|
|
|
|
|
|
3. 补 `safety::HARD_DENY` / `DENY_EXACT` 里该系统的禁区(Windows:`C:\Windows`、`C:\Program Files`;Linux:`/snap`、`/nix`、`/var/lib`)。
|
|
|
|
|
|
4. 新增 `crates/squid-rules/rules/<os>.toml`,并在 `RuleSet::builtins()` 里 `include_str!`。规则里的 `os = [...]` 字段决定它在哪个平台生效。
|
|
|
|
|
|
5. 回收站语义:`fs::trash_target_for` 需要该系统的回收站位置与命名规则(macOS 是 `~/.Trash` 与卷根 `.Trashes/<uid>`;Linux 是 XDG `~/.local/share/Trash/files`;Windows 需要 `$Recycle.Bin` 或 Shell API)。
|
|
|
|
|
|
6. 提权:macOS/Linux 用 `sudo` 重跑(`needs_admin` 的规则在非 root 时只报告不执行);Windows 需要 UAC。
|
|
|
|
|
|
|
2026-10-15 13:23:38 +00:00
|
|
|
|
现状:macOS 完整;Linux 有 `.desktop`/Flatpak/Snap 与 XDG 残留实现,缺规则文件与真机验证;Windows 平台层已实现并在真机跑通(注册表卸载表、AppData 残留、卷枚举、`IFileOperation` 回收站、`console` 的尺寸与字形探测),缺 UAC 提权与长路径 manifest。
|
2026-10-13 09:00:50 +00:00
|
|
|
|
|
|
|
|
|
|
## 测试策略
|
|
|
|
|
|
|
2026-10-15 13:23:38 +00:00
|
|
|
|
166 个测试(`cargo test --workspace`)。三类:
|
2026-10-13 09:00:50 +00:00
|
|
|
|
|
|
|
|
|
|
- **纯逻辑**:字节格式化、glob 与锚点、规则解析、名称匹配、安全策略拒绝表 —— 这些是最有价值的,因为它们把「曾经出过的事故」变成断言。
|
|
|
|
|
|
- **引擎级**:在临时目录 / `~/Library/Caches/squid-delete-test-*` 里搭沙盒,跑真实 scan + delete。
|
|
|
|
|
|
- **状态隔离**:删除类测试必须调用 `isolate_state()`,用 `SQUID_STATE_DIR` 把账本重定向到临时目录,否则测试会话会污染用户真实的 `squid history`。
|
|
|
|
|
|
|
|
|
|
|
|
约定:CI 门禁是 `cargo clippy --workspace --all-targets -- -D warnings` + `cargo test --workspace --no-fail-fast`。任何删除相关改动必须同时提供 Trash 往返(delete → undo → 字节一致)测试。
|
|
|
|
|
|
|
|
|
|
|
|
### 确认框背后的不变量:`Approval` 枚举
|
|
|
|
|
|
|
|
|
|
|
|
TUI 的「按 d → 确认 → 执行」曾经出过一次典型的静默失败:`App` 上有两个平行字段
|
|
|
|
|
|
`pending: Option<Vec<CleanupItem>>` 与 `pending_plan: Option<UninstallPlan>`,卸载流程只写了
|
|
|
|
|
|
后者对应的读逻辑,`pending_plan` 从来没被赋成 `Some`,于是 `confirm_delete()` 里
|
|
|
|
|
|
`let Some(plan) = self.pending_plan.take() else { return }` 直接返回——用户按了回车,什么也没发生,
|
|
|
|
|
|
什么也没说。
|
|
|
|
|
|
|
|
|
|
|
|
修复方式不是补一行赋值,而是让非法状态无法表达:两个字段合并成
|
|
|
|
|
|
`pending: Option<Approval>`,`Approval` 是 `Items { items, purge } | Plan(UninstallPlan) |
|
The system panel may stop a process, once it has asked who is sitting at that number
The system panel has listed processes for a while, and a list of what is running
gets one question asked of it more than any other: this one is wedged, make it
stop. A panel that can name the hung app and then shrugs is scenery, so the
answer here is yes — spent through the machinery the interface already has for
irreversible things, a dialog that names what it is about to do and a log line
afterwards that says what it did.
The *how* is two lines and not very interesting: `kill(2)` with `SIGKILL`, or
`OpenProcess(PROCESS_TERMINATE)` followed by `TerminateProcess`. Both are the
same promise, which is why `squid_platform::process::force_stop` is called a
forced stop on every platform and the dialog says 强制结束 rather than anything
about saving. There is no TERM-then-KILL handshake in here, because there is no
polite promise to keep: the second line of the dialog is 它不会有机会保存任何内容.
`squid_stats::Sampler::stop` does not use `sysinfo`'s own `Process::kill`, and
the reason is the shape of its answer. It returns `false` for every way a stop
can fail, and two of those ways want opposite things from the reader. `ESRCH`
means the process left on its own and nothing is owed but a redraw; `EPERM`
means it is alive and the reader should go find an elevated terminal. Windows
serves the same pair up as `ERROR_INVALID_PARAMETER` and `ERROR_ACCESS_DENIED`.
A bool cannot carry that difference, so squid makes the call itself and keeps
the words the OS gave, quoted inside a sentence this program owns — the OS's
sentence arrives in the language of the OS, and translates no further than its
own frame.
The *whether* is where the damage is, so it is answered twice. First by rule, in
`squid-platform`: never this squid, never the first process of the machine, and
on Windows never one of the six names a boot rests on. Those rules exist because
the operating system does not enforce all of them. An unelevated squid on macOS
cannot reach `WindowServer` whatever it tries; an elevated squid on Windows
*can* open `csrss.exe` for termination, and the reward for one misplaced Enter
is a machine that reboots without asking. Six names is the whole cost of that
guard. `svchost` is deliberately absent from it, because it hosts services a
user may genuinely need to restart and the machine survives losing one — which
is the test a name has to pass before it belongs on that list.
Then by the operating system, whose answer is the only one with any authority
over this user, this token, this moment. Between the two sits the question the
platform module cannot answer, because it is a question about a sample rather
than about a pid: is the process holding this number still the process whose
name the user read? Pids are seat numbers, handed out again, and a process table
is drawn the moment the panel opens and read from seconds later. So
`squid_stats::Sampler::stop` reads the pid again through the new `sample_of`,
applies the rules to the process that is really there, and calls a name that no
longer matches *gone* — the thing that was pointed at really is gone, whichever
direction the pid moved. `shown_name` is why that comparison means anything:
macOS hands over a path and Windows a bare name, and the process table had been
trimming with `split('/')`, which does nothing at all to a Windows path. Nothing
was wrong on screen, because the name was already short there; it became
evidence, and evidence has to be spelled one way.
`x` is the same verb it has always been. On the three file panels it makes the
row under the cursor go away; the system panel has nothing to delete and does
have a process, so the same finger reaches the same meaning, and
`x_is_still_the_delete_key_on_a_list_of_files` pins the old meaning down so that
this one cannot push it aside. `d` still deletes everywhere. The rules are
applied in `ask_stop_process` *before* the dialog rather than after the answer:
a dialog that can only be answered "no" teaches the user that the dialog is
theatre, and the toast that names the rule says the same thing in less time.
Three crates now each hold a `sleeper()`, which is a duplication worth keeping
on purpose. The thing under test has to be a process — `sleep 60`, or
`ping -n 60 127.0.0.1` where `sleep` is not — and a kill feature tested against
a struct is a kill feature that has never killed anything. Twelve tests come
with this: five in the platform module, including the boot list and a vacant pid
reporting itself as gone; three in the sampler, one of which hands a pid to
`stop` under the wrong name and then checks that the innocent process is still
running; four in the interface, walking `x`, `y`, and a refusal from the key
press to the corpse being reaped. 190 tests green across the workspace, with
`cargo fmt --check` and `cargo clippy --workspace --all-targets` clean for the
host and for `x86_64-pc-windows-msvc` — the target where the boot list,
`TerminateProcess` and the parameter-is-incorrect mapping compile at all, which
is also where `the_processes_a_boot_rests_on_are_named_not_guessed` exists.
The Windows 10/11 box carries the part a mac can only compile. `squid.exe`
there builds with `Win32_System_Threading`, clippy clean under `-D warnings`,
185 tests green; and the dialog was read off the screen rather than off the
buffer — `TUI_COLS=140 TUI_ROWS=35 TUI_CP=936`, 2604 samples of the raw ConPTY
stream, 291 settled frames, 0 of them failing the layout judge, including the
confirm itself: `╭ 结束 iNodeCmn.exe? ╮` / `pid 9080 · 1.2% · 15.4 MB` /
`它不会有机会保存任何内容` / `回车 / y 确认 · n / esc 取消`, and 「已取消」 after `n`.
`docs/ARCHITECTURE.md` gains the module and the key, and one of its diagrams
finally admits that `squid-stats` has depended on `squid-platform` for weeks.
2026-10-16 03:49:10 +00:00
|
|
|
|
UndoSession(String) | StopProcess(ProcessSample)` 四个变体。多出来的那个是系统状态面板的「强制结束进程」,它同样必须先构造出自己才问得出确认框;它带的是 sample 而不是 pid,因为 pid 是重复发放的座位号、不是人:用户读到的是名字,会被杀掉的是号码,把两者分开的唯一办法是把它们一起带到执行处(复核在 `squid_stats::Sampler::stop`)。`ask_delete()` 与 `ask_stop_process()` 都必须构造其中一个才问得出确认框;确认框能打开,
|
2026-10-13 09:00:50 +00:00
|
|
|
|
就必然有可执行的内容。`confirm_delete()` 对 `None` 的情况显式 toast「没有待确认的内容,请重新按 d」,
|
|
|
|
|
|
把「静默」变成「可见」。`app.rs` 里那三个回归测试直接驱动 `ask_delete() → confirm_delete() → poll()`
|
|
|
|
|
|
到任务结束,断言 `outcome.summary.removed == N`,覆盖卸载、清理/深度清理、以及空确认框三条路径。
|
|
|
|
|
|
|
2026-10-15 02:05:34 +00:00
|
|
|
|
## 许可证
|
2026-10-13 09:00:50 +00:00
|
|
|
|
|
2026-10-15 02:05:34 +00:00
|
|
|
|
squid 以 `GPL-3.0-only` 发布,全文见仓库根目录的 [`LICENSE`](../LICENSE)。七个 crate 通过
|
|
|
|
|
|
`[workspace.package] license` 继承同一份许可,`scripts/release.sh` 把 `LICENSE` 与 `README.md`
|
|
|
|
|
|
一起打进发布包,`packaging/homebrew/squid.rb` 声明同一 SPDX 标识符。
|