From 01426b97a8e4e6309f2bab94a2fe06d6e455c241 Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Wed, 12 Aug 2026 23:19:06 +0700 Subject: [PATCH] feat(app): health_run, and a progress forwarder that knows its own channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NOT_YET is down to three, and only health_fix is still Phase 3's. forward_progress hardcoded "plan-progress". It now takes the channel as a `&'static str` rather than a String, because the names are the closed set in EVENTS — a literal typo becomes a compile error instead of an event nobody is listening for, which is the failure that leaves a progress bar at zero while the work runs to completion behind it. The health slot is its own, not Sessions. A run mutates nothing, so refusing it while an install streams would be a lock with no invariant behind it — and S5 bug 1 is the standing warning about claims that wedge. But two Run clicks would put six subprocesses over one folder, so it needs *a* slot. Sessions was already generic and already tested with a u32. It is typed Sessions rather than Sessions<()> deliberately: P5's health_fix has to check the user's consent against a report the *server* holds — a count arriving from the frontend proves nothing about what the frontend displayed — which is the same shape ack_ok checks a GuardAck against the guard that produced it. Typing it now means P5 does not redo the slot. The implicit tools-venv sync runs on the same channel, so a first run on a fresh install shows the ~15 s bootstrap rather than an unexplained pause, and the total is decided before the first event because whether a sync is owed is exactly what changes it. Co-Authored-By: Claude Opus 5 --- src-tauri/src/commands.rs | 96 +++++++++++++++++++++++++++++++++++---- src-tauri/src/lib.rs | 2 +- src-tauri/src/state.rs | 27 +++++++++++ ui/src/ipc/index.ts | 29 ++++++++++++ ui/src/test/ipc.ts | 4 ++ 5 files changed, 149 insertions(+), 9 deletions(-) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 3fea2dc..985b7a6 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -503,7 +503,7 @@ pub async fn plan_execute( }; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - forward_progress(&app, rx); + forward_progress(&app, "plan-progress", rx); let result = flow.execute(tx).await; state.release().await; @@ -611,7 +611,7 @@ pub async fn uninstall_execute( }; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - forward_progress(&app, rx); + forward_progress(&app, "plan-progress", rx); let result = flow.execute(ack, tx).await; state.release().await; @@ -745,7 +745,7 @@ pub async fn snapshot_rollback( }; let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); - forward_progress(&app, rx); + forward_progress(&app, "plan-progress", rx); let result = rollback.execute(tx).await; state.release().await; @@ -756,13 +756,19 @@ pub async fn snapshot_rollback( }) } -/// Forward `plan-progress` to the webview, teeing every line into the log ring. +/// Forward progress to the webview on `channel`, teeing every line into the log ring. /// -/// One helper for all three executing commands. A UI that stopped listening is not a reason to -/// abandon an install, so the emit result is dropped; the ring is fed regardless, because the -/// report is most wanted precisely when nobody was watching. +/// One helper for every streaming command. A UI that stopped listening is not a reason to abandon +/// an install, so the emit result is dropped; the ring is fed regardless, because the report is +/// most wanted precisely when nobody was watching. +/// +/// `channel` is a `&'static str` rather than a `String` because the names are the closed set in +/// `ui/src/ipc/index.ts`'s `EVENTS`. A literal typo is then a compile error instead of an event +/// nobody is listening for — which is the failure mode that leaves a progress bar at zero while the +/// work runs to completion behind it. fn forward_progress( app: &tauri::AppHandle, + channel: &'static str, mut rx: tokio::sync::mpsc::UnboundedReceiver, ) { let emitter = app.clone(); @@ -773,11 +779,85 @@ fn forward_progress( if let Some(line) = event.line() { log.push(line); } - let _ = emitter.emit("plan-progress", &event); + let _ = emitter.emit(channel, &event); } }); } +/// Run Code Health over `project`, streaming `health-progress` (PRD P0-11). +/// +/// Syncs the tools venv first when one is owed — CODE-HEALTH-SPEC §2's "on first Health run (or +/// pin-set change)" — on the same channel, so the first run on a fresh install shows the ~15 s +/// bootstrap rather than an unexplained pause. The sink's total is decided before the first event +/// because whether a sync is owed is exactly what changes it. +/// +/// Claims the **health** slot, not the mutation slot: a run touches no environment, so refusing it +/// while an install streams would be a lock with no invariant behind it. Two Run clicks would +/// otherwise put six subprocesses over one folder. +/// +/// # Errors +/// `PD-ENV-003` when `project` cannot be read, `PD-HLT-004`/`PD-NET-011` from the implicit sync, +/// `PD-RES-003` when a run is already going. **A single tool failing is not an error** — it lands +/// in `HealthReport.problems` and the others still report. +#[tauri::command] +pub async fn health_run( + app: tauri::AppHandle, + state: tauri::State<'_, AppState>, + env: PyEnv, + project: String, +) -> Wire { + use pipdock_core::health; + + state.health.claim().await?; + + let project = std::path::PathBuf::from(&project); + let tools_dir = health::tools_dir(&state.app_data); + let opts = health::RunOptions::default(); + + let outcome = async { + let sync_needed = health::needs_sync(&tools_dir)?.is_needed(); + let total = health::run_steps(&opts) + if sync_needed { health::SYNC_STEPS } else { 0 }; + + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + forward_progress(&app, "health-progress", rx); + let sink = engine::ProgressSink::new(tx, total, CancellationToken::new()); + + if sync_needed { + let (python, _) = health::choose_tools_python(&envs::scan().await).await?; + health::sync_tools_venv(&tools_dir, &python, &sink).await?; + } + health::run_tools( + &tools_dir, + &project, + &env, + &opts, + &sink.at(if sync_needed { health::SYNC_STEPS } else { 0 }), + ) + .await + } + .await; + + match outcome { + Ok(report) => { + // Parked rather than dropped: P5 checks its consent against this exact report, and the + // folder it ran in is what a fix would rewrite. + state + .health + .park(crate::state::HealthSession { + project, + env, + report: report.clone(), + }) + .await; + Ok(report) + } + Err(e) => { + state.health.release().await; + Err(e.into()) + } + } +} + /// Upgrade pip inside `env` (PRD P0-10). /// /// **`PipEngine` unconditionally**, never `engine::for_id(settings.engine)`. Upgrading pip is a pip diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 75d05c9..97870d5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -24,7 +24,6 @@ pub mod state; /// `COMMANDS` and reality disagree in either direction. pub const NOT_YET: &[(&str, &str)] = &[ ("env_add_manual", "M3 — Browse… has no surface yet"), - ("health_run", "Phase 3 P3 — the runners"), ("health_fix", "Phase 3 P5 — the gated ruff --fix"), ("logs_tail", "M3 — needs the logging subsystem"), ]; @@ -71,6 +70,7 @@ pub fn run() { commands::report_bug_url, commands::engine_info, commands::pip_upgrade, + commands::health_run, commands::index_search, commands::index_refresh, commands::pkg_metadata, diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 4fc3827..bb2e95b 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -53,6 +53,21 @@ impl SessionKind { } } +/// A finished Code Health run, parked so the fix path can be checked against it. +/// +/// The report is held **server-side** on purpose. P5's `health_fix` must confirm that what it is +/// about to rewrite is what the user was shown, and a count that arrives from the frontend proves +/// nothing about what the frontend displayed. Same reasoning as `GuardReport`: the artefact is +/// produced in one call and consumed in another, so the consuming call reads it from here. +pub struct HealthSession { + /// The folder the tools ran in. + pub project: std::path::PathBuf, + /// The environment the report was produced against. + pub env: pipdock_core::PyEnv, + /// What they found. + pub report: pipdock_core::health::HealthReport, +} + /// The mutation flow the slot is holding between two IPC calls. /// /// All three variants exist from the moment the slot stops being `UpdateFlow`-shaped, rather than @@ -398,6 +413,17 @@ pub struct AppState { pub index: std::sync::Mutex, /// The mutation being driven across several IPC calls. pub sessions: Sessions, + /// The Code Health run in flight, and the report it produced. + /// + /// **Not the mutation slot.** A health run touches no environment, so refusing it while an + /// install streams would be a lock with no invariant behind it — and S5 bug 1 is the standing + /// warning about claims that wedge. It still needs a slot of its own, because two Run clicks + /// would put six subprocesses over one folder. + /// + /// `Sessions` rather than `Sessions<()>` because P5's `health_fix` has to check + /// the user's consent against a report **the server** is holding — the same shape `ack_ok` + /// checks a `GuardAck` against the guard that produced it. Typed now so P5 does not redo it. + pub health: Sessions, /// Engine output from the current plan, for the bug-report deep link. pub log: std::sync::Arc, } @@ -415,6 +441,7 @@ impl AppState { store: tokio::sync::Mutex::new(store), index: std::sync::Mutex::new(IndexSlot::Cold), sessions: Sessions::default(), + health: Sessions::default(), log: std::sync::Arc::new(LogRing::default()), }) } diff --git a/ui/src/ipc/index.ts b/ui/src/ipc/index.ts index 85f1ea2..5f8e720 100644 --- a/ui/src/ipc/index.ts +++ b/ui/src/ipc/index.ts @@ -32,6 +32,7 @@ import type { Pin, ProgressEvent, PyEnv, + HealthReport, RefreshReport, RollbackPreview, SnapshotMeta, @@ -363,6 +364,19 @@ export const engineInfo = (env: PyEnv): Promise => invoke('engine_ */ export const pipUpgrade = (env: PyEnv): Promise => invoke('pip_upgrade', { env }) +/** + * Run Code Health over a project folder (PRD P0-11). + * + * Streams `health-progress`, and on a fresh install syncs the tools venv first — so the first run + * is the ~15 s bootstrap plus the tools, and the progress total already accounts for both. + * + * **A tool that fails does not fail the run.** It lands in `report.problems` and the others still + * report, which is what `PD-HLT-003`'s "partial report" means. An empty `deptry` array is only + * "clean" when `deptry` is in `report.ran`. + */ +export const healthRun = (env: PyEnv, project: string): Promise => + invoke('health_run', { env, project }) + /** * Subscribe to execution progress. Returns the unlisten function. * @@ -388,3 +402,18 @@ export const onScanProgress = (handler: (progress: ScanProgress) => void): Promi listen('scan-progress', (event) => { handler(event.payload) }) + +/** + * Subscribe to Code Health progress. Returns the unlisten function. + * + * The same `ProgressEvent` payload `plan-progress` carries, on its own channel — ARCHITECTURE §7 + * lists `health-progress` as a channel, not a payload, and CLI-SPEC §6 already requires `health` + * to emit the same shape. A second event type would cost a schema, a golden and a second console + * renderer for nothing. + */ +export const onHealthProgress = ( + handler: (event: ProgressEvent) => void, +): Promise => + listen('health-progress', (event) => { + handler(event.payload) + }) diff --git a/ui/src/test/ipc.ts b/ui/src/test/ipc.ts index 5e1f240..849f5cc 100644 --- a/ui/src/test/ipc.ts +++ b/ui/src/test/ipc.ts @@ -41,6 +41,8 @@ export interface IpcMock { envScan: ReturnType envProbe: ReturnType pipUpgrade: ReturnType + healthRun: ReturnType + onHealthProgress: ReturnType isPdError: (value: unknown) => boolean } @@ -68,6 +70,8 @@ export function ipcMock(): IpcMock { envScan: vi.fn().mockResolvedValue([]), envProbe: vi.fn(), pipUpgrade: vi.fn().mockResolvedValue(undefined), + healthRun: vi.fn(), + onHealthProgress: vi.fn().mockResolvedValue(() => undefined), // Real, not a spy: the stores decide whether a rejection carries a catalog code by asking it, // and a stub that always answered one way would make every error test agree with itself. isPdError: (value: unknown): boolean =>