diff --git a/crates/squid-platform/Cargo.toml b/crates/squid-platform/Cargo.toml index af72749..c0e114d 100644 --- a/crates/squid-platform/Cargo.toml +++ b/crates/squid-platform/Cargo.toml @@ -22,4 +22,4 @@ libc.workspace = true [target.'cfg(windows)'.dependencies] winreg = "0.52" sysinfo.workspace = true -windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security"] } +windows-sys = { version = "0.59", features = ["Win32_System_Console", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_Security", "Win32_System_Threading"] } diff --git a/crates/squid-platform/src/lib.rs b/crates/squid-platform/src/lib.rs index 0dd5ba6..bc53097 100644 --- a/crates/squid-platform/src/lib.rs +++ b/crates/squid-platform/src/lib.rs @@ -14,6 +14,7 @@ pub mod apps; pub mod console; pub mod currency; pub mod leftovers; +pub mod process; #[cfg(unix)] pub mod volumes; diff --git a/crates/squid-platform/src/process.rs b/crates/squid-platform/src/process.rs new file mode 100644 index 0000000..2afad43 --- /dev/null +++ b/crates/squid-platform/src/process.rs @@ -0,0 +1,340 @@ +//! Stopping one process, because the interface is allowed to ask for it. +//! +//! A file cleaner that can list what is running can also be asked to stop what +//! is running, and the ask is honest: a hung app is the reason people open a +//! dashboard at all. The two halves of the job are not equally interesting. +//! +//! The *how* is boring and short. Unix sends `SIGKILL`; Windows opens the +//! process for `PROCESS_TERMINATE` and calls `TerminateProcess`. Both are the +//! same promise — this process stops now and saves nothing — which is why the +//! interface calls it a forced stop on every platform instead of a polite quit +//! it did not perform. +//! +//! The *whether* is where the damage is, so it is answered twice. First here, +//! by rule: squid never stops itself, never stops the first process of the +//! machine, and on Windows never stops the handful of processes a boot rests +//! on. Those rules exist because the OS does not enforce all of them. An +//! unelevated process on macOS cannot reach `WindowServer` anyway, but 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. A +//! guard that costs six names is cheaper than that conversation. +//! +//! Then by the operating system, whose answer is the only one that carries any +//! authority about this user, this token, this moment. The reason it says no is +//! kept: `EPERM` and `ERROR_ACCESS_DENIED` mean "you are not that user", which +//! tells the reader to reach for an elevated terminal, while `ESRCH` means the +//! process already left on its own, which asks for nothing at all. Guessing one +//! message for both is how a tool teaches people to distrust its errors. +//! +//! Note that this module answers for a pid and nothing else. Whether the pid in +//! front of the user is still the process they read the name of is a question +//! about the sample that produced it, and it is asked where the samples live +//! (`squid_stats::Sampler::stop`). + +use std::fmt; + +/// The rule that stands between squid and a process. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OffLimits { + /// The process is this squid. Stopping it would end the answer along with + /// the question. + Itself, + /// The first process of the machine: the kernel and `init`/`launchd` on + /// unix, the System Idle Process and `System` on Windows. + First, + /// A Windows process the session or the boot depends on, named here so the + /// message can say which. + Boot(&'static str), +} + +impl OffLimits { + /// The rule in English, for logs and for the command line. The interface + /// translates the *rule*, not this sentence, so that one rule cannot drift + /// into two wordings. + pub fn reason(self) -> &'static str { + match self { + OffLimits::Itself => "this is squid itself", + OffLimits::First => "the first process of the machine", + OffLimits::Boot(name) => name, + } + } +} + +/// Why a process was not stopped. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StopError { + /// It was already gone: either it exited between the list being drawn and + /// the key being pressed, or the pid now belongs to something else. + Gone { pid: u32 }, + /// A rule in this module declined, before anything was attempted. + Refused(OffLimits), + /// The operating system refused, in its own words. + Denied { reason: String }, +} + +impl fmt::Display for StopError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + StopError::Gone { pid } => write!(f, "process {pid} is no longer running"), + StopError::Refused(rule) => write!(f, "refused: {}", rule.reason()), + StopError::Denied { reason } => f.write_str(reason), + } + } +} + +impl std::error::Error for StopError {} + +/// The processes a Windows session cannot afford to lose, without their +/// extension. `svchost` is deliberately absent: it hosts services a user may +/// genuinely need to restart, and the machine survives it. +#[cfg(windows)] +const CRITICAL: [&str; 6] = ["csrss", "smss", "wininit", "services", "lsass", "winlogon"]; + +/// The half of the rule a pid answers on its own, before anything is read +/// about it. +/// +/// Split from [`refusal`] because the two halves get asked at different moments: +/// this one is asked of the number the interface is holding, where the name +/// rule needs the process that is really behind the number. A process that is +/// off limits should be refused as that, rather than reported as missing merely +/// because no listing happened to describe it. +pub fn pid_refusal(pid: u32) -> Option { + if pid == std::process::id() { + return Some(OffLimits::Itself); + } + // Unix: 0 is the kernel, 1 is init. Windows: 0 is the System Idle Process + // and 4 is the System process, and both show up in a memory-sorted list. + if pid <= 1 || (cfg!(windows) && pid == 4) { + return Some(OffLimits::First); + } + None +} + +/// Which rule declines this process, if one does. +/// +/// `name` is what the process calls itself, which is the only thing the user +/// read. The comparison is on the extensionless stem because a listing may or +/// may not carry `.exe` depending on where it was taken from. +pub fn refusal(pid: u32, name: &str) -> Option { + if let Some(rule) = pid_refusal(pid) { + return Some(rule); + } + // The name decides anything only on Windows, where a process is named as + // firmly as it is numbered. Taking it anyway keeps one question — "may this + // pid be stopped" — answerable from one place on every platform. + let _ = &name; + #[cfg(windows)] + { + let stem = name + .rsplit(['\\', '/']) + .next() + .unwrap_or(name) + .to_lowercase(); + let stem = stem.strip_suffix(".exe").unwrap_or(&stem); + if let Some(found) = CRITICAL.iter().copied().find(|critical| *critical == stem) { + return Some(OffLimits::Boot(found)); + } + } + None +} + +/// Force a process to stop, now. +/// +/// Only the pid is passed, so a caller that knows the name it displayed has to +/// check the name itself — which is the point: `refusal` and a fresh read of the +/// pid are the caller's job, and this function makes no promises about *which* +/// process the pid belongs to today. +pub fn force_stop(pid: u32) -> Result<(), StopError> { + // `cfg` rather than `cfg!`, because the halves of this function are not two + // branches of one program: on Windows there is no `unix` module to name, and + // on macOS there is no `windows` one. An `if` would ask both to exist. + #[cfg(unix)] + { + unix::force_stop(pid) + } + #[cfg(windows)] + { + windows::force_stop(pid) + } + #[cfg(not(any(unix, windows)))] + { + Err(StopError::Denied { + reason: "stopping processes is not implemented for this platform".into(), + }) + } +} + +#[cfg(unix)] +mod unix { + use super::StopError; + + pub fn force_stop(pid: u32) -> Result<(), StopError> { + let rc = unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }; + if rc == 0 { + return Ok(()); + } + let error = std::io::Error::last_os_error(); + // ESRCH: nothing answers to this pid any more. The user asked to stop a + // process and there is no process; that is a report, not a failure to + // explain away. + if error.raw_os_error() == Some(libc::ESRCH) { + return Err(StopError::Gone { pid }); + } + Err(StopError::Denied { + reason: error.to_string(), + }) + } +} + +#[cfg(windows)] +mod windows { + use super::StopError; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}; + + /// The exit status a forced stop reports. `1` is what Task Manager's + /// "End task" leaves behind, and nothing reads it: the process is simply + /// not running afterwards. + const FORCED: u32 = 1; + + pub fn force_stop(pid: u32) -> Result<(), StopError> { + let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) }; + if handle.is_null() { + return Err(denied(pid)); + } + let ok = unsafe { TerminateProcess(handle, FORCED) }; + unsafe { CloseHandle(handle) }; + if ok == 0 { + return Err(denied(pid)); + } + Ok(()) + } + + /// The message the system gave, in the words it gives the user: "Access is + /// denied." for a process owned by another account, "The parameter is + /// incorrect." once the pid has stopped existing. + fn denied(pid: u32) -> StopError { + let error = std::io::Error::last_os_error(); + if error.raw_os_error().is_some_and(|code| code == 87) { + // ERROR_INVALID_PARAMETER: no such process. + return StopError::Gone { pid }; + } + StopError::Denied { + reason: error.to_string(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Child, Command, Stdio}; + + #[test] + fn squid_never_stops_itself() { + let here = std::process::id(); + assert_eq!(refusal(here, "squid"), Some(OffLimits::Itself)); + } + + #[test] + fn the_first_processes_are_off_limits_everywhere() { + assert_eq!(pid_refusal(0), Some(OffLimits::First)); + assert_eq!(pid_refusal(1), Some(OffLimits::First)); + assert_eq!(refusal(0, "kernel_task"), Some(OffLimits::First)); + assert_eq!(refusal(1, "launchd"), Some(OffLimits::First)); + // A normal process, on any platform, is fair game. + assert_eq!(refusal(4_242, "TextEdit"), None); + } + + #[cfg(windows)] + #[test] + fn the_processes_a_boot_rests_on_are_named_not_guessed() { + assert_eq!(refusal(4, "System"), Some(OffLimits::First)); + assert_eq!( + refusal(520, "C:\\Windows\\System32\\csrss.exe"), + Some(OffLimits::Boot("csrss")) + ); + // Extensionless, upper case, and the folder it was read from must not + // change the answer. + assert_eq!(refusal(640, "LSASS"), Some(OffLimits::Boot("lsass"))); + // `svchost` hosts services a user may need to restart, and the machine + // survives losing one, so the guard stays out of the way. + assert_eq!(refusal(1234, "svchost.exe"), None); + } + + /// The whole point of the feature: a process that is running stops. + /// + /// `ping` against the loopback is used because it exists on every platform + /// this runs on, takes a minute, and losing it hurts nothing. The test + /// waits for the exit rather than trusting the return code of the kill: on + /// Windows the kill is synchronous but the handle we spawned through is + /// not, and a zombie that has stopped running is still a stopped process. + #[test] + fn a_running_process_stops_when_it_is_asked() { + let mut child = sleeper(); + let pid = child.id(); + assert!( + child.try_wait().expect("child is running").is_none(), + "the child died before being asked" + ); + let outcome = force_stop(pid); + if outcome.is_err() { + let _ = child.kill(); + } + outcome.expect("stopping a child of this test must be allowed"); + let status = child.wait().expect("the child is reaped"); + assert!( + !status.success(), + "a killed process reported success: {status:?}" + ); + } + + fn sleeper() -> Child { + let mut command = if cfg!(windows) { + let mut command = Command::new("ping"); + command.args(["-n", "60", "127.0.0.1"]); + command + } else { + let mut command = Command::new("sleep"); + command.arg("60"); + command + }; + command + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("a loopback ping / sleep should start") + } + + /// `ESRCH` and `EPERM` ask for opposite things from the reader — one says + /// "nothing to do", the other says "become a more privileged user" — so the + /// two must not arrive as the same message. A pid nobody owns is the + /// reproducible half of that pair. + #[cfg(unix)] + #[test] + fn a_pid_that_is_not_there_reports_itself_as_gone() { + let vacant = first_vacant_pid(); + assert!(refusal(vacant, "Nothing").is_none()); + let error = force_stop(vacant).expect_err("nothing owns this pid"); + assert!( + matches!(error, StopError::Gone { pid } if pid == vacant), + "expected Gone({vacant}), got {error:?}" + ); + } + + /// PIDs are handed out upwards and then wrap, so just below the ceiling the + /// range is empty. The ceiling itself is not usable: `pid_t` is an `i32` on + /// macOS, and `kill` answers `EINVAL` rather than `ESRCH` outside its range. + #[cfg(unix)] + fn first_vacant_pid() -> u32 { + let top = if cfg!(target_os = "macos") { + 999_999 + } else { + 4_194_304 + }; + (top - 64..top) + .filter(|pid| *pid != std::process::id()) + .find(|pid| unsafe { libc::getpgid(*pid as libc::pid_t) } != 0) + .expect("a vacant pid near the top of the range") + } +} diff --git a/crates/squid-stats/src/lib.rs b/crates/squid-stats/src/lib.rs index 4f81f52..ad4ddb1 100644 --- a/crates/squid-stats/src/lib.rs +++ b/crates/squid-stats/src/lib.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; use squid_core::{Bytes, Volume}; +use squid_platform::process::StopError; use std::collections::VecDeque; use std::path::PathBuf; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -317,6 +318,59 @@ impl Sampler { self.had_first_sample } + /// The row the panel would draw for one pid right now, or `None` once no + /// process holds that number. + /// + /// Re-reading one pid is cheap, and it is the only way to find out whether a + /// sample taken on an earlier beat still describes what is running: a row is + /// a claim about a moment, not about a process, because pids are handed out + /// again. [`Sampler::stop`] asks this question before it kills anything, and + /// a test or an interface that wants one honest row asks it the same way. + pub fn sample_of(&mut self, pid: u32) -> Option { + let key = sysinfo::Pid::from_u32(pid); + self.system.refresh_processes_specifics( + ProcessesToUpdate::Some(&[key]), + true, + ProcessRefreshKind::nothing().with_cpu().with_memory(), + ); + let process = self.system.process(key)?; + Some(ProcessSample { + pid, + name: shown_name(process.name()), + cpu: process.cpu_usage(), + memory: Bytes(process.memory()), + }) + } + + /// Force the process behind one sample to stop. + /// + /// The sample is what the user read; the pid inside it is what would be + /// killed, and those two are not the same promise. Pids are recycled, so a + /// list drawn a second ago can already be pointing a name at somebody + /// else's process. The pid is therefore read again here, the rule from + /// [`squid_platform::process::refusal`] is applied to the process that is + /// really there, and a name that no longer matches is reported as *gone* — + /// the thing that was pointed at is gone, whichever direction the pid moved. + /// + /// Nothing here asks the process politely. There is no TERM-then-KILL + /// handshake, because the interface says 强制结束 / force quit and a dialog + /// that promises the bytes on disk are the only thing kept. + pub fn stop(&mut self, target: &ProcessSample) -> Result<(), StopError> { + if let Some(rule) = squid_platform::process::pid_refusal(target.pid) { + return Err(StopError::Refused(rule)); + } + let Some(current) = self.sample_of(target.pid) else { + return Err(StopError::Gone { pid: target.pid }); + }; + if let Some(rule) = squid_platform::process::refusal(target.pid, ¤t.name) { + return Err(StopError::Refused(rule)); + } + if current.name != target.name { + return Err(StopError::Gone { pid: target.pid }); + } + squid_platform::process::force_stop(target.pid) + } + /// Per-application CPU totals. iStat Menus shows this next to the gauges. pub fn applications(&mut self, limit: usize) -> Vec { self.system.refresh_processes_specifics( @@ -327,13 +381,7 @@ impl Sampler { let mut merged: std::collections::HashMap = std::collections::HashMap::new(); for process in self.system.processes().values() { - let name = process - .name() - .to_string_lossy() - .split('/') - .next_back() - .unwrap_or("?") - .to_string(); + let name = shown_name(process.name()); let entry = merged .entry(name) .or_insert((0.0, 0, 0, process.pid().as_u32())); @@ -587,19 +635,29 @@ fn disk_rates(disks: &Disks, seconds: f64) -> DiskRate { } } +/// The name a process is listed by: the last component of whatever the OS +/// handed over, which is a path on macOS and already a bare name on Windows. +/// +/// One function because the name is also the proof. A sample is a snapshot of a +/// pid at one moment, and pids are recycled; before squid stops anything it +/// re-reads the pid and compares, which only means something if both sides +/// spell the name the same way. +fn shown_name(name: &std::ffi::OsStr) -> String { + name.to_string_lossy() + .split(['/', '\\']) + .next_back() + .filter(|part| !part.is_empty()) + .unwrap_or("?") + .to_string() +} + fn top_processes(system: &System, limit: usize) -> Vec { let mut processes: Vec = system .processes() .values() .map(|process| ProcessSample { pid: process.pid().as_u32(), - name: process - .name() - .to_string_lossy() - .split('/') - .next_back() - .unwrap_or("?") - .to_string(), + name: shown_name(process.name()), cpu: process.cpu_usage(), memory: Bytes(process.memory()), }) @@ -791,4 +849,101 @@ mod tests { }; assert_eq!(stats.percent_used(), 100); } + + /// The feature, end to end: a sample that still describes its pid stops it. + #[test] + fn a_process_stops_when_its_sample_asks_it_to() { + let mut sampler = Sampler::new(); + let mut child = sleeper(); + let sample = sample_of(&mut sampler, child.id()); + assert!( + child.try_wait().expect("child is running").is_none(), + "the sleeper died on its own: {}", + sample.name + ); + sampler + .stop(&sample) + .expect("stopping a child of this test must be allowed"); + let status = child.wait().expect("the child is reaped"); + assert!(!status.success(), "a stopped process exited cleanly"); + } + + /// The guard, end to end: a pid that no longer belongs to the name the user + /// read stops nothing at all. + /// + /// Pids are recycled, so this is not a hypothetical race — a list is drawn + /// when the panel opens and read from seconds later, which is long enough + /// for an app to close and a new one to be handed its number. Killing on the + /// number alone would punish whoever inherited it. + #[test] + fn a_sample_that_no_longer_describes_its_pid_stops_nothing() { + let mut sampler = Sampler::new(); + let mut child = sleeper(); + let pid = child.id(); + let mut sample = sample_of(&mut sampler, pid); + sample.name = "WhateverWasOnScreen".into(); + let error = sampler + .stop(&sample) + .expect_err("the name does not belong to this pid"); + assert!( + matches!(error, StopError::Gone { pid: gone } if gone == pid), + "expected Gone({pid}), got {error:?}" + ); + assert!( + child.try_wait().expect("child is still running").is_none(), + "the process that inherited the pid was punished for it" + ); + let _ = child.kill(); + let _ = child.wait(); + } + + /// The rules are checked against the process that is really there, which is + /// why this one needs no name to be right: pid zero answers to the kernel on + /// unix and to the System Idle Process on Windows, and neither is a target. + #[test] + fn squid_leaves_the_untouchable_processes_alone() { + let mut sampler = Sampler::new(); + let myself = ProcessSample { + pid: std::process::id(), + name: "whatever the list said".into(), + cpu: 0.0, + memory: Bytes(0), + }; + assert_eq!( + sampler.stop(&myself).expect_err("this is the test itself"), + StopError::Refused(squid_platform::process::OffLimits::Itself) + ); + let first = ProcessSample { pid: 0, ..myself }; + assert_eq!( + sampler.stop(&first).expect_err("pid zero"), + StopError::Refused(squid_platform::process::OffLimits::First) + ); + } + + /// A process long enough to be seen, harmless enough to lose. + fn sleeper() -> std::process::Child { + let mut command = if cfg!(windows) { + let mut command = std::process::Command::new("ping"); + command.args(["-n", "60", "127.0.0.1"]); + command + } else { + let mut command = std::process::Command::new("sleep"); + command.arg("60"); + command + }; + command + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("a loopback ping / sleep should start") + } + + /// The row as the panel would have drawn it, name included: read from + /// the operating system rather than guessed, because the name is the proof + /// `stop` checks and a guessed name would fail for the wrong reason. + fn sample_of(sampler: &mut Sampler, pid: u32) -> ProcessSample { + sampler + .sample_of(pid) + .expect("a child of this test is a process") + } } diff --git a/crates/squid-tui/src/app.rs b/crates/squid-tui/src/app.rs index dcb130e..c2cbd1c 100644 --- a/crates/squid-tui/src/app.rs +++ b/crates/squid-tui/src/app.rs @@ -19,7 +19,8 @@ use squid_engine::delete::DeleteJob; use squid_engine::delete::DeleteOutcome; use squid_engine::Engine; use squid_engine::{analyze, clean, delete, purge, uninstall}; -use squid_stats::{Sampler, SystemSnapshot, TrendStore}; +use squid_platform::process::{OffLimits, StopError}; +use squid_stats::{ProcessSample, Sampler, SystemSnapshot, TrendStore}; use std::collections::{HashMap, HashSet, VecDeque}; use std::path::PathBuf; use std::time::Instant; @@ -465,6 +466,11 @@ pub enum ConfirmAction { Purge, Uninstall, UndoSession(String), + /// Stop one process the system panel is listing. The sample travels with + /// the approval, not just the pid: the pid is what would be killed and the + /// sample is what the user read, and telling those apart is the whole + /// safety of the operation. + StopProcess(ProcessSample), } /// What the user approved, carrying everything needed to carry it out. @@ -485,6 +491,7 @@ pub enum Approval { }, Plan(UninstallPlan), UndoSession(String), + StopProcess(ProcessSample), } #[derive(Clone, Debug)] @@ -1538,7 +1545,7 @@ impl App { items: chosen, purge: false, }, - ConfirmAction::UndoSession(_) => return, + ConfirmAction::UndoSession(_) | ConfirmAction::StopProcess(_) => return, }; self.pending = Some(approval); self.confirm = Some(Confirm { @@ -1547,6 +1554,72 @@ impl App { action, }); } + + /// Ask before stopping the process the system panel is pointing at. + /// + /// The same gate as a delete, for the same reason: what the user pressed is + /// a key on a row, and what happens next is irreversible. The row says + /// `pid 4242`, and a pid is a seat number rather than a person — the process + /// that sat there when the list was drawn may have left and handed the seat + /// to another. That is why the sample, not the number, is what travels into + /// the approval, and why [`squid_stats::Sampler::stop`] reads the pid again + /// before it acts on it. + pub fn ask_stop_process(&mut self) { + if self.confirm.is_some() || self.busy_refusal(Slot::Delete) { + return; + } + if self.panel != Panel::Stats { + self.toast( + self.strings.t("no process list here", "这里没有进程列表"), + ToastKind::Info, + ); + return; + } + let Some(process) = self + .stats + .snapshot + .as_ref() + .and_then(|snapshot| snapshot.top_processes.get(self.stats.cursor)) + .cloned() + else { + self.toast( + self.strings + .t("press r to take a reading first", "先按 r 采样一次"), + ToastKind::Info, + ); + return; + }; + // The rules squid applies to itself are checked here as well as in the + // sampler. Asking permission for a stop that a rule will refuse is worse + // than pressing the key on an empty row: it teaches the user that the + // dialog is theatre. + if let Some(rule) = squid_platform::process::refusal(process.pid, &process.name) { + let text = self.stop_refusal(&StopError::Refused(rule)); + self.toast(text, ToastKind::Warn); + return; + } + let lines = vec![ + format!( + "pid {} · {:.1}% · {}", + process.pid, + process.cpu, + process.memory.human() + ), + self.strings.t( + "it gets no chance to save anything", + "它不会有机会保存任何内容", + ), + ]; + self.pending = Some(Approval::StopProcess(process.clone())); + self.confirm = Some(Confirm { + title: self.strings.t( + &format!("Stop {}?", process.name), + &format!("结束 {}?", process.name), + ), + lines, + action: ConfirmAction::StopProcess(process), + }); + } } // ------------------------------------------------------------------ commands @@ -1624,6 +1697,69 @@ impl App { self.toast(err.to_string(), ToastKind::Warn); } }, + Approval::StopProcess(sample) => self.stop_process(sample), + } + } + + /// Carry out the kill the dialog just approved. + /// + /// The reading is taken again afterwards whatever the outcome. A process + /// that stopped has to leave the list, and a process that refused has to + /// stay in it looking exactly as it did; a stale row in between the two is + /// a row the user then points at twice. + fn stop_process(&mut self, sample: ProcessSample) { + let outcome = self.stats.sampler.stop(&sample); + self.stats.refresh(); + let left = self.list_len(); + self.stats.cursor = self.stats.cursor.min(left.saturating_sub(1)); + match outcome { + Ok(()) => { + let text = self.strings.t( + &format!("{} stopped", sample.name), + &format!("已结束 {}", sample.name), + ); + self.toast(text.clone(), ToastKind::Good); + self.push_log(format!("stop {} · pid {}", sample.name, sample.pid)); + } + Err(error) => { + let text = self.stop_refusal(&error); + self.toast(text.clone(), ToastKind::Warn); + self.push_log(format!( + "stop {} · pid {} · refused: {text}", + sample.name, sample.pid + )); + } + } + } + + /// Why a process could not be stopped, in the language the interface is + /// speaking. + /// + /// The rule variants are matched rather than printed through their + /// `Display`, so one rule cannot end up meaning two things; the operating + /// system's own words are quoted inside a sentence this program owns, + /// because those words arrive in the language of the OS and translate no + /// further than the frame around them. + fn stop_refusal(&self, error: &StopError) -> String { + match error { + StopError::Gone { .. } => self + .strings + .t("that process had already stopped", "该进程已经退出了"), + StopError::Refused(OffLimits::Itself) => self + .strings + .t("squid cannot stop itself", "squid 不能结束自己"), + StopError::Refused(OffLimits::First) => self.strings.t( + "that is the first process of the machine", + "那是系统的第一个进程,不能结束", + ), + StopError::Refused(OffLimits::Boot(name)) => self.strings.t( + &format!("{name} is a process Windows needs to start"), + &format!("{name} 是 Windows 启动必需的进程,不能结束"), + ), + StopError::Denied { reason } => self.strings.t( + &format!("the system refused: {reason}"), + &format!("系统拒绝了请求:{reason}"), + ), } } @@ -2093,10 +2229,22 @@ impl App { self.scan(); Action::Redraw } - KeyCode::Char('d') | KeyCode::Char('x') => { + KeyCode::Char('d') => { self.ask_delete(); Action::Redraw } + // `x` means "the thing under the cursor goes away". On the three + // file panels that is a delete; on the system panel there is + // nothing to delete and there is a process, so the same finger + // reaches the same verb and the verb means stopping it. + KeyCode::Char('x') => { + if self.panel == Panel::Stats { + self.ask_stop_process(); + } else { + self.ask_delete(); + } + Action::Redraw + } KeyCode::Char('a') | KeyCode::Char('A') => { self.toggle_all(); Action::Redraw @@ -3380,4 +3528,204 @@ mod tests { ); let _ = std::fs::remove_dir_all(&dir); } + + /// A process long enough to be seen and harmless enough to lose. The same + /// twelve lines live in `squid-platform` and `squid-stats` for the same + /// reason: the thing being tested has to be a process, and pretending with a + /// struct is how a kill feature ships without ever killing. + fn sleeper() -> std::process::Child { + let mut command = if cfg!(windows) { + let mut command = std::process::Command::new("ping"); + command.args(["-n", "60", "127.0.0.1"]); + command + } else { + let mut command = std::process::Command::new("sleep"); + command.arg("60"); + command + }; + command + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .expect("a loopback ping / sleep should start") + } + + /// Whether the child really left, without hanging the suite if it did not. + fn waits_for_exit(child: &mut std::process::Child) -> bool { + let started = Instant::now(); + loop { + if child + .try_wait() + .expect("the child belongs to this test") + .is_some() + { + return true; + } + if started.elapsed() > Duration::from_secs(10) { + return false; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + + /// The system panel adds a second door into something irreversible, and + /// every door in this interface has the same two failures available: the + /// dialog opens and nothing happens, or something happens to the wrong row. + /// Both are tried here against a real process, since a row is only as honest + /// as the number inside it. + #[test] + fn the_system_panel_stops_the_process_the_row_named() { + isolate_state(); + let mut app = App::new().expect("app"); + app.strings = Strings::for_lang(crate::theme::Lang::En); + app.toast = None; + let mut child = sleeper(); + let row = app + .stats + .sampler + .sample_of(child.id()) + .expect("a child of this test is a process"); + app.panel = Panel::Stats; + app.stats.snapshot = Some(SystemSnapshot { + top_processes: vec![row.clone()], + ..Default::default() + }); + app.stats.cursor = 0; + + app.handle_key(KeyCode::Char('x'), KeyModifiers::empty()); + assert!( + matches!(app.pending, Some(Approval::StopProcess(_))), + "x on a process row must ask about stopping a process, not about deleting one: {:?}", + app.confirm.as_ref().map(|confirm| confirm.title.clone()) + ); + let title = app + .confirm + .as_ref() + .expect("x must ask before killing anything") + .title + .clone(); + assert!( + title.contains(&row.name), + "the dialog must name what it is about to stop: {title}" + ); + + app.handle_key(KeyCode::Char('y'), KeyModifiers::empty()); + assert!(app.confirm.is_none(), "answering must close the dialog"); + assert!( + app.toast + .as_ref() + .is_some_and(|toast| toast.text.contains(&row.name)), + "the panel must report the process it stopped, got {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + assert!( + waits_for_exit(&mut child), + "the dialog said it stopped and nothing stopped" + ); + } + + /// A row is a claim about a moment rather than a process: pids are handed out + /// again, so the name the user read can already belong to somebody else by + /// the time `y` is pressed. The answer is to say so — never to kill whoever + /// inherited the number. + #[test] + fn a_row_that_no_longer_describes_its_pid_kills_nobody() { + isolate_state(); + let mut app = App::new().expect("app"); + app.strings = Strings::for_lang(crate::theme::Lang::En); + app.toast = None; + let mut child = sleeper(); + let mut row = app + .stats + .sampler + .sample_of(child.id()) + .expect("a child of this test is a process"); + row.name = "WhateverWasOnScreen".into(); + app.panel = Panel::Stats; + app.stats.snapshot = Some(SystemSnapshot { + top_processes: vec![row.clone()], + ..Default::default() + }); + app.stats.cursor = 0; + + app.handle_key(KeyCode::Char('x'), KeyModifiers::empty()); + assert!( + app.confirm.is_some(), + "a row that looks ordinary must still be asked about" + ); + app.handle_key(KeyCode::Char('y'), KeyModifiers::empty()); + assert!(app.confirm.is_none()); + assert!( + app.toast + .as_ref() + .is_some_and(|toast| toast.text.contains("already stopped")), + "a row whose process left should be reported as gone, got {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + assert!( + child.try_wait().expect("the child is ours").is_none(), + "the process that inherited the pid was punished for it" + ); + let _ = child.kill(); + let _ = child.wait(); + } + + /// The rules are applied before the question, not after the answer. Asking + /// permission for something a rule will refuse anyway teaches the user that + /// the dialog is theatre, which is worth less than the toast that says why. + #[test] + fn an_untouchable_process_is_refused_before_it_is_asked_about() { + isolate_state(); + let mut app = App::new().expect("app"); + app.strings = Strings::for_lang(crate::theme::Lang::En); + app.toast = None; + app.panel = Panel::Stats; + app.stats.snapshot = Some(SystemSnapshot { + top_processes: vec![ProcessSample { + pid: std::process::id(), + name: "squid".into(), + cpu: 0.0, + memory: Bytes(0), + }], + ..Default::default() + }); + app.handle_key(KeyCode::Char('x'), KeyModifiers::empty()); + assert!( + app.confirm.is_none() && app.pending.is_none(), + "squid must not ask permission to stop itself" + ); + assert!( + app.toast + .as_ref() + .is_some_and(|toast| toast.text.contains("itself")), + "the refusal should say which rule applied, got {:?}", + app.toast.as_ref().map(|toast| toast.text.clone()) + ); + } + + /// `x` has meant "the row under the cursor goes away" on the file panels + /// since the first version; meeting a process table must not have moved the + /// finger that was already there. + #[test] + fn x_is_still_the_delete_key_on_a_list_of_files() { + isolate_state(); + let dir = scratch("x-still-deletes"); + let (info, items) = fake_app(&dir); + let mut app = App::new().expect("app"); + app.delete_mode = DeleteMode::Permanent; + app.panel = Panel::Uninstall; + app.uninstall.view = UninstallView::Plan; + app.uninstall.plan = Some(UninstallPlan { + app: info, + items, + warnings: Vec::new(), + }); + app.handle_key(KeyCode::Char('x'), KeyModifiers::empty()); + assert!( + matches!(app.pending, Some(Approval::Plan(_))), + "x on a plan must still approve deleting files: {:?}", + app.confirm.as_ref().map(|confirm| confirm.title.clone()) + ); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/squid-tui/src/views.rs b/crates/squid-tui/src/views.rs index 98babba..842689c 100644 --- a/crates/squid-tui/src/views.rs +++ b/crates/squid-tui/src/views.rs @@ -626,7 +626,10 @@ fn hint_text(app: &App) -> String { parts.push(s.t("enter open · f files", "回车进入 · f 大文件")); parts.push(s.t("r refresh", "r 刷新")); } - Panel::Stats => parts.push(s.t("r refresh", "r 刷新")), + Panel::Stats => { + parts.push(s.t("r refresh", "r 刷新")); + parts.push(s.t("x stop process", "x 结束进程")); + } Panel::History => { parts.push(s.t("u restore", "u 还原")); parts.push(s.t("r refresh", "r 刷新")); @@ -1821,6 +1824,13 @@ fn draw_help(frame: &mut Frame, area: Rect, app: &App) { "d".to_string(), s.t("clean what is checked", "清理已勾选项"), ), + ( + "x".to_string(), + s.t( + "stop the process on the system panel", + "在系统状态面板结束进程", + ), + ), ( "m".to_string(), s.bin_t("{bin} ⇄ permanent", "{bin} ⇄ 永久"), diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5ce6acd..8ff7278 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -34,7 +34,7 @@ └──────┬─────┘ └─┬────────┘ │ │ │ │ ┌────▼─────────▼───────┐ │ ┌────────────┐ - │ squid-engine │◄─┼───┤ squid-stats│ ← 只依赖 core + │ squid-engine │◄─┼───┤ squid-stats│ ← 依赖 core 与 platform └────┬────────────┬────┘ │ └─────┬──────┘ ┌───────▼──┐ ┌────▼───────▼──┐ │ │ squid-tui│ │ squid-cli │◄─────┘ @@ -80,6 +80,8 @@ fn running_executables(&self) -> Vec; // 供 skip_if_ `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` 把控制台自己的几个数字写进文件留证。 +`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 待着的地方。 + ### squid-rules 规则是 TOML,内置于 `crates/squid-rules/rules/macos.toml`(39 条),通过 `include_str!` 编译进二进制;用户规则从 `/rules/*.toml` 合并,同 `id` 覆盖内置。 @@ -112,6 +114,8 @@ note = "Xcode 会重新生成。" `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 式细节。 +界面既然能列出谁在跑,就会被要求停掉谁,`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 原因、不弹确认框:为一个规则注定会拒绝的动作去要许可,是把确认框变成戏剧。 + ### squid-engine | 引擎 | 做法 | @@ -246,7 +250,7 @@ TUI 的「按 d → 确认 → 执行」曾经出过一次典型的静默失败 修复方式不是补一行赋值,而是让非法状态无法表达:两个字段合并成 `pending: Option`,`Approval` 是 `Items { items, purge } | Plan(UninstallPlan) | -UndoSession(String)` 三个变体。`ask_delete()` 必须构造其中一个才能打开确认框;确认框能打开, +UndoSession(String) | StopProcess(ProcessSample)` 四个变体。多出来的那个是系统状态面板的「强制结束进程」,它同样必须先构造出自己才问得出确认框;它带的是 sample 而不是 pid,因为 pid 是重复发放的座位号、不是人:用户读到的是名字,会被杀掉的是号码,把两者分开的唯一办法是把它们一起带到执行处(复核在 `squid_stats::Sampler::stop`)。`ask_delete()` 与 `ask_stop_process()` 都必须构造其中一个才问得出确认框;确认框能打开, 就必然有可执行的内容。`confirm_delete()` 对 `None` 的情况显式 toast「没有待确认的内容,请重新按 d」, 把「静默」变成「可见」。`app.rs` 里那三个回归测试直接驱动 `ask_delete() → confirm_delete() → poll()` 到任务结束,断言 `outcome.summary.removed == N`,覆盖卸载、清理/深度清理、以及空确认框三条路径。