feat(app): health_run, and a progress forwarder that knows its own channel

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<Session>. 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<T> was already generic and already tested
with a u32.

It is typed Sessions<HealthSession> 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 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-12 23:31:37 +07:00
1 parent 2673da05e5
commit 01426b97a8
5 files changed
+149 -9

No files matched your search

+88 -8
View File
@@ -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<pipdock_core::engine::ProgressEvent>,
) {
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<pipdock_core::health::HealthReport> {
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
+1 -1
View File
@@ -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,
+27
View File
@@ -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<IndexSlot>,
/// The mutation being driven across several IPC calls.
pub sessions: Sessions<Session>,
/// 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<HealthSession>` 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<HealthSession>,
/// Engine output from the current plan, for the bug-report deep link.
pub log: std::sync::Arc<LogRing>,
}
@@ -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()),
})
}
+29
View File
@@ -32,6 +32,7 @@ import type {
Pin,
ProgressEvent,
PyEnv,
HealthReport,
RefreshReport,
RollbackPreview,
SnapshotMeta,
@@ -363,6 +364,19 @@ export const engineInfo = (env: PyEnv): Promise<EngineInfo[]> => invoke('engine_
*/
export const pipUpgrade = (env: PyEnv): Promise<StepResult> => 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<HealthReport> =>
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<ScanProgress>('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<UnlistenFn> =>
listen<ProgressEvent>('health-progress', (event) => {
handler(event.payload)
})
+4
View File
@@ -41,6 +41,8 @@ export interface IpcMock {
envScan: ReturnType<typeof vi.fn>
envProbe: ReturnType<typeof vi.fn>
pipUpgrade: ReturnType<typeof vi.fn>
healthRun: ReturnType<typeof vi.fn>
onHealthProgress: ReturnType<typeof vi.fn>
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 =>