feat(app): health_save_report, Markdown and JSON where the user asked

CODE-HEALTH-SPEC §5's *Save report*, and §7's argument for it: the JSON export is what lets
users wire their own CI annotations, which is why "no CI annotations in v1" is a non-goal
rather than a gap. Two files from one prompt, because asking twice for what is conceptually
one action spends a click on nothing.

**Written in Rust, not through `tauri-plugin-fs`.** A general `fs:allow-write-text-file` is a
write-anywhere primitive granted to the webview of a tool that already runs subprocesses
against the user's interpreters. `dialog:allow-save` only lets the webview *ask* for a path;
it still has no permission to read or write a single file. The grant says so where the next
person will look for it.

`markdown()` lives in `health/report.rs` rather than in the bridge, so a future
`pipdock health --format md` reuses it instead of growing a second renderer that drifts. That
flag is deliberately not built now — one consumer is not a reason to design for two.

The renderer makes the same three-way distinction the tabs do, and for a sharper reason: a
saved report is read months later, away from the screen that produced it. An empty section
says `_Not run._`, `_Did not finish — see Problems above._` or `_No findings._`, because a
document claiming "no findings" about a ruff that could not be spawned would be read as proof
the code was fine. The deptry caveat travels with the findings it qualifies for the same
reason — the saved file is the one place it cannot be left implicit.

Both names are derived from the chosen path's stem rather than from what was typed, so the
pair always matches even if the user names the file `report` or `report.txt`.

Read the rendered document rather than only asserting on fragments of it: headings, the
per-file grouping, the whole-file location with no dangling colon, and "3 of 6 carry a safe
fix, across 2 file(s)" against a fixture carrying exactly that.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-13 18:49:59 +07:00
1 parent aa839545c2
commit fc74edfc0c
10 files changed
+345 -10

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ pub use run::{RunOptions, has_findings, run_steps};
pub use project::{DeclaredSource, declared_source};
pub use report::{
DeptryIssue, FixApplicability, HealthReport, RuffFinding, RuffFindings, SourceLocation,
ToolProblem, VultureFinding,
ToolProblem, VultureFinding, markdown,
};
use std::collections::BTreeMap;
+239
View File
@@ -196,6 +196,149 @@ pub enum FixApplicability {
Display,
}
/// Render a report as Markdown, for CODE-HEALTH-SPEC §5's *Save report*.
///
/// **In core rather than in the GUI**, so a future `pipdock health --format md` reuses it instead
/// of growing a second renderer that drifts from this one. That flag is deliberately not built
/// yet — one consumer is not a reason to design an interface for two.
///
/// Everything the tools said is reproduced verbatim, including deptry's module names and ruff's
/// rule codes: the file is a record of what was found, and rewording it here would make it a
/// record of what PipDock thought about what was found. The `DEP003` caveat is included for the
/// reason the CLI and the screen both carry it — a saved report is read away from both.
#[must_use]
pub fn markdown(report: &HealthReport) -> String {
use std::fmt::Write as _;
let mut out = String::new();
// Infallible: writing to a String cannot fail. `let _` rather than `?`, so this function
// needs no Result for a failure mode it does not have.
let _ = writeln!(out, "# Code Health\n");
let _ = writeln!(out, "- Project: `{}`", report.project);
let _ = writeln!(out, "- Environment: `{}`", report.env);
let _ = writeln!(out, "- Checked: {}", report.ran_at);
let versions: Vec<String> = report
.tool_versions
.iter()
.map(|(tool, version)| format!("{tool} {version}"))
.collect();
let _ = writeln!(out, "- Tools: {}", versions.join(", "));
let _ = writeln!(out, "- Declared in: {}", declared_label(&report.declared));
let _ = writeln!(out, "- Ran: {}", report.ran.join(", "));
if !report.problems.is_empty() {
let _ = writeln!(out, "\n## Problems\n");
for problem in &report.problems {
let _ = writeln!(
out,
"- **{}** `{}` — {}",
problem.tool,
problem.code.as_str(),
problem.message
);
}
let _ = writeln!(
out,
"\nA tool that failed reports nothing; the others still report. Any section below \
whose tool is listed here is empty because it did not finish, not because it found \
nothing."
);
}
let _ = writeln!(out, "\n## Dependencies (deptry)\n");
if report.deptry.is_empty() {
let _ = writeln!(out, "{}", nothing_for("deptry", report));
} else {
for issue in &report.deptry {
let _ = writeln!(
out,
"- **{}** `{}` — {}",
issue.code, issue.dep, issue.message
);
for loc in &issue.locations {
let _ = match loc.line {
Some(line) => writeln!(out, " - `{}:{}`", loc.file, line),
None => writeln!(out, " - `{}`", loc.file),
};
}
}
let _ = writeln!(
out,
"\n> deptry compares imports against PipDock's own tools environment, not this one — \
DEP001 and DEP003 can be swapped for packages it happens to hold."
);
}
let _ = writeln!(out, "\n## Dead code (vulture)\n");
if report.vulture.is_empty() {
let _ = writeln!(out, "{}", nothing_for("vulture", report));
} else {
for finding in &report.vulture {
let _ = writeln!(
out,
"- `{}:{}` — {} ({}% confidence)",
finding.path, finding.line, finding.message, finding.confidence
);
}
let _ = writeln!(
out,
"\n> Confidence below 100% can be a false positive. Review before deleting."
);
}
let _ = writeln!(out, "\n## Lint (ruff)\n");
if report.ruff.findings.is_empty() {
let _ = writeln!(out, "{}", nothing_for("ruff", report));
} else {
for finding in &report.ruff.findings {
let code = finding.code.as_deref().unwrap_or(&finding.name);
let _ = writeln!(
out,
"- `{}:{}:{}` **{}** — {}",
finding.filename, finding.row, finding.column, code, finding.message
);
}
let _ = writeln!(
out,
"\n{} of {} carry a safe fix, across {} file(s).",
report.ruff.fixable,
report.ruff.findings.len(),
report.ruff.fixable_files
);
}
// CODE-HEALTH-SPEC §7's footer. A constant, so it is written here rather than carried on the
// wire — see `PdHealthReport` for the same decision on the screen.
let _ = writeln!(
out,
"\n---\n\nJupyter notebooks (`.ipynb`) are excluded from every report."
);
out
}
/// Why a section is empty: the tool found nothing, failed, or was never asked.
///
/// The same three-way distinction the tabs make, and for the same reason — an empty section that
/// says "no findings" about a tool that never ran is the one sentence in the document that would
/// be false.
fn nothing_for(tool: &str, report: &HealthReport) -> &'static str {
if !report.ran.iter().any(|t| t == tool) {
"_Not run._"
} else if report.problems.iter().any(|p| p.tool == tool) {
"_Did not finish — see Problems above._"
} else {
"_No findings._"
}
}
fn declared_label(declared: &DeclaredSource) -> String {
match declared {
DeclaredSource::Pyproject => "pyproject.toml".to_owned(),
DeclaredSource::Requirements { files } => files.join(", "),
DeclaredSource::None => "nothing found".to_owned(),
}
}
impl RuffFindings {
/// Recount `fixable` and `fixable_files` from `findings`.
///
@@ -218,3 +361,99 @@ impl RuffFindings {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
fn report() -> HealthReport {
HealthReport {
project: r"C:\proj".to_owned(),
env: r"c:\proj\.venv\scripts\python.exe".to_owned(),
ran_at: "2026-08-13T09:00:00Z".to_owned(),
tool_versions: BTreeMap::new(),
declared: DeclaredSource::Pyproject,
ran: vec!["deptry".to_owned(), "vulture".to_owned()],
deptry: Vec::new(),
vulture: Vec::new(),
ruff: RuffFindings::default(),
problems: Vec::new(),
}
}
/// The one sentence a saved report could get wrong, three ways.
///
/// An empty section is not evidence of a clean project: the tool may have failed, or may
/// never have been asked. A document that said "no findings" for a ruff that could not be
/// spawned would be read months later as proof the code was fine.
#[test]
fn an_empty_section_says_which_kind_of_empty_it_is() {
let mut r = report();
// Never asked: ruff is not in `ran`.
assert!(markdown(&r).contains("_Not run._"));
// Asked and clean.
r.ran.push("ruff".to_owned());
assert!(markdown(&r).contains("_No findings._"));
// Asked and broken.
r.problems.push(ToolProblem {
tool: "ruff".to_owned(),
code: Code::HltToolMissing,
message: "could not be run".to_owned(),
stderr_tail: None,
});
let out = markdown(&r);
assert!(out.contains("_Did not finish"));
assert!(
!out.contains("_No findings._\n\n---"),
"ruff must not read as clean"
);
}
/// The caveat travels with the findings it qualifies.
///
/// A saved report is read away from both the screen and the CLI, so it is the one place the
/// deptry limitation cannot be left implicit.
#[test]
fn the_deptry_caveat_is_saved_with_the_findings() {
let mut r = report();
assert!(
!markdown(&r).contains("DEP001 and DEP003"),
"no findings, no caveat"
);
r.deptry.push(DeptryIssue {
code: "DEP002".to_owned(),
dep: "httpx".to_owned(),
message: "unused".to_owned(),
locations: Vec::new(),
});
assert!(markdown(&r).contains("DEP001 and DEP003 can be swapped"));
}
#[test]
fn a_whole_file_finding_is_rendered_without_a_dangling_colon() {
let mut r = report();
r.deptry.push(DeptryIssue {
code: "DEP002".to_owned(),
dep: "httpx".to_owned(),
message: "unused".to_owned(),
locations: vec![
SourceLocation {
file: "pyproject.toml".to_owned(),
line: None,
column: None,
},
SourceLocation {
file: "a.py".to_owned(),
line: Some(4),
column: Some(1),
},
],
});
let out = markdown(&r);
assert!(out.contains("- `pyproject.toml`"));
assert!(out.contains("- `a.py:4`"));
}
}
+3 -2
View File
@@ -1,10 +1,11 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Minimal capability set for the Phase 0 shell. Permissions are added per feature, never broadened preemptively (docs/SECURITY.md §2).",
"description": "Minimal capability set for the shell. Permissions are added per feature, never broadened preemptively (docs/SECURITY.md §2). dialog:allow-open is Code Health's project-folder picker and the manual Browse… path; dialog:allow-save is Save report. BOTH ONLY ASK FOR A PATH — no fs permission is granted, so the webview cannot read or write a single file. Save report hands its path to a Rust command that writes the two files, because a general fs:allow-write-text-file would be a write-anywhere primitive in the webview of a tool that already runs subprocesses against the user's interpreters.",
"windows": ["main"],
"permissions": [
"core:default",
"dialog:allow-open"
"dialog:allow-open",
"dialog:allow-save"
]
}
+48
View File
@@ -940,6 +940,54 @@ pub async fn health_run(
}
}
/// Write a finished report beside the path the user named, as Markdown **and** JSON.
///
/// CODE-HEALTH-SPEC §5's *Save report*. Two files from one prompt: the Markdown is for reading and
/// the JSON is what §7 means by "the JSON export enables users to wire their own" CI annotations,
/// and asking twice for what is conceptually one action would spend a click on nothing.
///
/// **Written in Rust rather than through `tauri-plugin-fs`.** A general `fs:allow-write-text-file`
/// is a write-anywhere primitive granted to the webview of a tool that already runs subprocesses
/// against the user's interpreters; this needs the webview to have no write permission at all.
/// `dialog:allow-save` only lets it *ask* for a path.
///
/// Takes the report from the frontend rather than the parked session on purpose: what the user
/// asked to save is what is on their screen. Nothing is executed from it, so the trust question
/// that makes `health_fix` read server-side does not arise here.
///
/// # Errors
/// `PD-SYS-002` when either file cannot be written; the path is the user's own choice, so a
/// failure is a real filesystem answer rather than something to retry.
#[tauri::command]
pub async fn health_save_report(
report: pipdock_core::health::HealthReport,
path: String,
) -> Wire<Vec<String>> {
let base = std::path::PathBuf::from(&path);
// The picker suggests `.md`, but the user may type anything or nothing; deriving both names
// from the stem means the pair always matches rather than depending on what was typed.
let md = base.with_extension("md");
let json = base.with_extension("json");
let body = pipdock_core::health::markdown(&report);
let document = serde_json::to_string_pretty(&report).map_err(|e| {
PdError::new(
pipdock_core::errors::Code::IntUnexpected,
format!("serialize report: {e}"),
)
})?;
for (target, contents) in [(&md, body), (&json, document)] {
std::fs::write(target, contents).map_err(|e| {
PdError::new(
pipdock_core::errors::Code::SysDiskFull,
format!("write {}: {e}", target.display()),
)
})?;
}
Ok(vec![md.display().to_string(), json.display().to_string()])
}
/// Upgrade pip inside `env` (PRD P0-10).
///
/// **`PipEngine` unconditionally**, never `engine::for_id(settings.engine)`. Upgrading pip is a pip
+1
View File
@@ -71,6 +71,7 @@ pub fn run() {
commands::engine_info,
commands::pip_upgrade,
commands::health_run,
commands::health_save_report,
commands::index_search,
commands::index_refresh,
commands::pkg_metadata,
+16 -1
View File
@@ -13,7 +13,7 @@
import { invoke } from '@tauri-apps/api/core'
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
import { open } from '@tauri-apps/plugin-dialog'
import { open, save } from '@tauri-apps/plugin-dialog'
import type {
Decision,
@@ -69,6 +69,7 @@ export const COMMANDS = [
'snapshot_rollback',
'health_run',
'health_fix',
'health_save_report',
'engine_info',
'pip_upgrade',
'settings_get',
@@ -394,6 +395,16 @@ export const pipUpgrade = (env: PyEnv): Promise<StepResult> => invoke('pip_upgra
export const healthRun = (env: PyEnv, project: string): Promise<HealthReport> =>
invoke('health_run', { env, project })
/**
* Write the report beside `path`, as Markdown and JSON. Returns the two paths written.
*
* The webview has no filesystem permission at all: `dialog:allow-save` only lets it *ask* for a
* path, and Rust does the writing. A general write permission here would be a write-anywhere
* primitive in a tool that already runs subprocesses.
*/
export const healthSaveReport = (report: HealthReport, path: string): Promise<string[]> =>
invoke('health_save_report', { report, path })
/**
* Subscribe to execution progress. Returns the unlisten function.
*
@@ -438,6 +449,10 @@ export const pickProjectFolder = async (
return typeof chosen === 'string' ? chosen : null
}
/** Ask the OS where to save a report. `null` when the user cancelled. */
export const pickSavePath = async (title: string, defaultName: string): Promise<string | null> =>
(await save({ title, defaultPath: defaultName })) ?? null
/** Subscribe to discovery progress. Returns the unlisten function. */
export const onScanProgress = (handler: (progress: ScanProgress) => void): Promise<UnlistenFn> =>
listen<ScanProgress>('scan-progress', (event) => {
+4 -1
View File
@@ -248,7 +248,10 @@
"ruffFileCount_other": "{{count}} findings",
"showRemaining_one": "Show {{count}} more finding",
"showRemaining_other": "Show {{count}} more findings",
"log": "Log"
"log": "Log",
"save": "Save report",
"saveTitle": "Save the Code Health report",
"saved": "Saved {{files}}"
},
"uninstall": {
"title": "Remove packages",
+4 -1
View File
@@ -229,7 +229,10 @@
"unsafeBadge": "sửa không an toàn",
"ruffFileCount_other": "{{count}} phát hiện",
"showRemaining_other": "Hiện thêm {{count}} phát hiện",
"log": "Nhật ký"
"log": "Nhật ký",
"save": "Lưu báo cáo",
"saveTitle": "Lưu báo cáo Sức khỏe mã",
"saved": "Đã lưu {{files}}"
},
"uninstall": {
"title": "Gỡ gói",
+25 -4
View File
@@ -11,14 +11,14 @@
* between UI-SPEC §5's budget of 3 and the 4 a first run actually takes.
*/
import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { PdConsoleDrawer } from '@/components/PdConsoleDrawer'
import { PdEmptyState } from '@/components/PdEmptyState'
import { PdErrorRow } from '@/components/PdErrorRow'
import { PdHealthReport } from '@/components/PdHealthReport'
import { pickProjectFolder } from '@/ipc'
import { healthSaveReport, pickProjectFolder, pickSavePath } from '@/ipc'
import type { PdError, ToolProblem } from '@/ipc'
import { useEnvPackages } from '@/screens/useEnvPackages'
import { freshReport, useEnvStore, useHealthStore, usePlanStore } from '@/stores'
@@ -88,6 +88,10 @@ export function PdHealth() {
// environment's findings after the user switched to another.
const shown = row === undefined ? null : freshReport({ report, reportFor, folder }, row.envHash)
// Where the last save went, so the confirmation names the files rather than just claiming
// success. Screen state, not store state: it describes an action, not a report.
const [saved, setSaved] = useState<string[] | null>(null)
const choose = () => {
void pickProjectFolder(t('health.pickerTitle'), folder ?? undefined).then((chosen) => {
if (chosen !== null) setFolder(chosen)
@@ -131,6 +135,20 @@ export function PdHealth() {
>
{running ? t('health.running') : t('health.run')}
</button>
<button
type="button"
className="rounded-pd border border-border px-2 py-1 text-data hover:bg-surface-2 disabled:opacity-50"
disabled={shown === null}
onClick={() => {
if (shown === null) return
void pickSavePath(t('health.saveTitle'), 'code-health.md').then((target) => {
if (target === null) return
void healthSaveReport(shown, target).then(setSaved)
})
}}
>
{t('health.save')}
</button>
<button
type="button"
className="rounded-pd border border-border px-2 py-1 text-data text-text-dim hover:bg-surface-2"
@@ -142,9 +160,12 @@ export function PdHealth() {
</button>
</div>
{/* One live region for the screen, announcing the same `done/total` the drawer shows. */}
{/* One live region for the screen: progress while running, then where a save landed.
Two regions would serialize against each other unpredictably. */}
<p aria-live="polite" className="mt-2 shrink-0 text-data text-text-dim">
{running && total > 0 ? t('plan.progress', { done, total }) : ''}
{running && total > 0 ? t('plan.progress', { done, total }) : null}
{/* Paths are data and are never localized (I18N §2). */}
{!running && saved !== null ? t('health.saved', { files: saved.join(', ') }) : null}
</p>
{/* A run that failed outright — distinct from a *tool* that failed, which is below. */}
+4
View File
@@ -44,6 +44,8 @@ export interface IpcMock {
healthRun: ReturnType<typeof vi.fn>
onHealthProgress: ReturnType<typeof vi.fn>
pickProjectFolder: ReturnType<typeof vi.fn>
pickSavePath: ReturnType<typeof vi.fn>
healthSaveReport: ReturnType<typeof vi.fn>
isPdError: (value: unknown) => boolean
}
@@ -76,6 +78,8 @@ export function ipcMock(): IpcMock {
// Cancelled by default. A picker that silently returned a folder would let a test assert a
// run it never actually asked for.
pickProjectFolder: vi.fn().mockResolvedValue(null),
pickSavePath: vi.fn().mockResolvedValue(null),
healthSaveReport: vi.fn().mockResolvedValue([]),
// 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 =>