Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(dead-code): one confidence scale, a reopen path, and shared primitives (#993)
Raghav Chamadiyac694bf43bf15
diff --git a/packages/types/src/dead-code.ts b/packages/types/src/dead-code.tsindex 673884060..7552538b5 100644--- a/packages/types/src/dead-code.ts+++ b/packages/types/src/dead-code.ts@@ -9,6 +9,34 @@export type DeadCodeStatus = "open" | "acknowledged" | "resolved" | "false_positive";+/**+ * The one set of confidence boundaries, mirroring the engine.+ *+ * `HIGH` is `SAFE_CONFIDENCE_THRESHOLD` in+ * `core/analysis/dead_code/risk_factors.py`: below it nothing is ever+ * deletion-ready, and the summary endpoint counts the same way+ * (`persistence/crud/analysis/dead_code.py`). `MEDIUM` is the list endpoint's+ * default `min_confidence` floor, so anything under it is normally never+ * fetched at all.+ *+ * Three surfaces used to disagree about these numbers, which put one 0.72+ * finding in "high" on the summary card, "Medium" in the breakdown grid, and+ * an unremarkable colour in the table while wearing a green Candidate badge.+ */+export const DEAD_CODE_CONFIDENCE = {+ /** Deletion-ready floor; matches SAFE_CONFIDENCE_THRESHOLD. */+ HIGH: 0.7,+ /** The list endpoint's default floor; below this findings are not fetched. */+ MEDIUM: 0.4,+} as const;++/** Which tier a confidence falls in, using the boundaries above. */+export function deadCodeConfidenceTier(confidence: number): "high" | "medium" | "low" {+ if (confidence >= DEAD_CODE_CONFIDENCE.HIGH) return "high";+ if (confidence >= DEAD_CODE_CONFIDENCE.MEDIUM) return "medium";+ return "low";+}+export interface DeadCodeFinding {id: string;kind: string;diff --git a/packages/ui/COMPONENT_CONTRACTS.md b/packages/ui/COMPONENT_CONTRACTS.mdindex 8ec922d7a..7336d9500 100644--- a/packages/ui/COMPONENT_CONTRACTS.md+++ b/packages/ui/COMPONENT_CONTRACTS.md@@ -193,10 +193,137 @@ Filter unions:----## `dead-code/summary-bar` — `SummaryBar`+## `dead-code/dead-code-view` - `DeadCodeView`-Four-tile summary header for a dead-code report: total findings,-deletable lines, breakdown by kind, breakdown by confidence band.+The whole Dead Code page: summary tiles, the safe-to-delete pile, the+"where it clusters" rollups, and the drill-down findings table. Owns the+optimistic patch + undo toast, bulk resolve, the AI cleanup prompt modal,+Re-analyze, and the status filter that switches which slice the table shows.++| Prop | Type | Required | Notes |+|------|------|----------|-------|+| `adapter` | `DeadCodeAdapter` | yes | Everything host-specific: fetching, mutation, links, navigation. |++Behaviour worth knowing:+- Two fetches. The open slice feeds the pile, the rollups and the table;+ a second, conditional fetch backs the status filter when it is not "open".+ Both are capped at 500 rows. The open slice has a repo-wide total to+ compare against, so its hint says "Showing N of M"; a non-open status has+ no server-side total, so its hint can only say "First N".+- A failed fetch with nothing to show renders a retry card and nothing else:+ it must never fall through to an empty state, which would read as a clean+ repository. A failed refresh over rows already in hand keeps the table and+ puts the card above it.+- Optimistic row state lives here, not in the table, so resolving a row moves+ the pile and the rollups with it and undo can put it back.++---++## `dead-code/dead-code-adapter` - `DeadCodeAdapter`++The host injection point. Hosted consumes this, so treat it as public API:+adding a required member is a breaking change for every consumer.++| Member | Type | Required | Notes |+|--------|------|----------|-------|+| `cacheKey` | `string` | yes | Seeds the view's SWR keys. Keep stable per repo/snapshot. |+| `repoId` | `string` | yes | Repo identity for hosts that need it. Nothing in this package reads it today; links come from `fileHref` / `graphHref`. |+| `getSummary` | `() => Promise<DeadCodeSummary>` | yes | |+| `listFindings` | `(opts?: { limit?: number; status?: DeadCodeStatus }) => Promise<DeadCodeFinding[]>` | yes | `status` defaults to `"open"` server-side. |+| `analyze` | `() => Promise<{ job_id?: string } \| void>` | yes | Returning a `job_id` lets the view wait and refresh itself. |+| `waitForAnalysis` | `(jobId: string) => Promise<void>` | no | Without it the view cannot know when to refetch, and says so in its toast. |+| `patchFinding` | `(id: string, patch: DeadCodePatchInput) => Promise<DeadCodeFinding>` | yes | Must return the updated finding; the view stores it as the optimistic override. |+| `fileHref` | `(path: string) => string` | yes | Makes the path a link and the row clickable. |+| `graphHref` | `(path: string) => string` | no | Omit and the per-row Graph action disappears, which keeps app routes out of this package. |+| `navigate` | `(href: string) => void` | yes | Host router push. |++---++## `dead-code/findings-table` - `FindingsTable`++The drill-down table: kind tabs driven by the data, a search box, sortable+columns, the confidence slider, a cleanup-ready switch, bulk resolve, and+per-row status actions. Built on `shared/responsive-table` with+`stacked="sm"` and windowed rows.++| Prop | Type | Required | Notes |+|------|------|----------|-------|+| `findings` | `DeadCodeFinding[]` | yes | One status slice; the table filters it by kind / confidence / safety client-side. |+| `onPatch` | `(id, { status }) => Promise<DeadCodeFinding>` | yes | Host owns the API call and the undo toast. |+| `onBulkResolve` | `(ids: string[]) => Promise<string[]>` | no | Must return the ids that actually resolved, not the ids it was given. The table reconciles against that, never against position. |+| `fileHref` | `(path: string) => string` | no | |+| `onNavigate` | `(href: string) => void` | no | Needed alongside `fileHref` for client-side row clicks. |+| `graphHref` | `(path: string) => string` | no | |+| `onGeneratePrompt` | `(ids: string[]) => void` | no | Drives both the per-row icon button and "AI prompt for N selected". |+| `status` | `DeadCodeStatus` | no | Which slice is on screen. Defaults to `"open"`; bulk resolve only appears there. |+| `isLoading` | `boolean` | no | Shows a skeleton instead of an empty state during the first fetch. |++Selection is always intersected with the rows currently visible, so raising+the confidence slider after selecting cannot resolve rows the user can no+longer see.++---++## `dead-code/finding-cells` - cell renderers++`FindingIdentity`, `FindingConfidence`, `FindingSafety` and+`FindingRowActions` back the table's columns. `FindingRowActions` is separate+because it owns per-row pending/confirm state that a plain `render(row)`+closure cannot hold; it offers resolve/ack/FP on an open finding and Reopen+on anything already actioned. `DEAD_CODE_STATUS_LABELS` is the shared label+map for the status filter.++---++## `dead-code/safe-to-delete-pile` - `SafeToDeletePile`++The "what do I delete" punchline: per-file rollup of the cleanup-ready+findings with the AI cleanup CTA.++| Prop | Type | Required | Notes |+|------|------|----------|-------|+| `findings` | `SafeToDeletePileFinding[]` | yes | Caller passes the safe slice; structural subset of `DeadCodeFinding`. |+| `onPropose` | `(ids: string[]) => void` | no | Opens the AI prompt modal; omit and the CTA disappears. |+| `onSelect` | `(finding: DeadCodeFinding) => void` | no | Row click. |+| `reclaimableLines` | `number` | no | The repo-wide total. Pass it only when the findings are not a capped slice, otherwise it sits next to counts describing a different population. |++---++## `dead-code/owner-leaderboard` - `OwnerLeaderboard`++Inline bar chart of dead-code lines per primary contributor. No charting+dependency.++| Prop | Type | Required | Notes |+|------|------|----------|-------|+| `findings` | `OwnerLeaderboardFinding[]` | yes | Structural subset of `DeadCodeFinding`. |+| `topN` | `number` | no | Default 8. |+| `safeOnly` | `boolean` | no | Count only cleanup-ready findings. |+| `onSelect` | `(owner: string) => void` | no | Turns each bar into a button. |+| `className` | `string` | no | |++---++## `dead-code/findings-breakdown-grid` - `FindingsBreakdownGrid`++Confidence-tier by kind heat matrix. Its own `<table>` is deliberate:+this is a matrix, not a list, so `ResponsiveTable` is the wrong primitive.+Tier boundaries come from `DEAD_CODE_CONFIDENCE` in+`@repowise-dev/types/dead-code`, which mirrors the engine's+`SAFE_CONFIDENCE_THRESHOLD`. The low row renders only when something is in+it, since the list endpoint floors at the medium boundary.++| Prop | Type | Required | Notes |+|------|------|----------|-------|+| `findings` | `FindingsBreakdownItem[]` | yes | Needs only `kind` and `confidence`. |+| `className` | `string` | no | |++---++## `dead-code/summary-bar` - `SummaryBar`++Four-tile summary header for a dead-code report: total findings, candidate+lines, breakdown by kind, breakdown by confidence band.| Prop | Type | Required | Notes ||------|------|----------|-------|diff --git a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx b/packages/ui/__tests__/dead-code/dead-code-view.test.tsxindex 2c857f99d..b8aaa78ab 100644--- a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx+++ b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx@@ -176,7 +176,7 @@ describe("DeadCodeView", () => {});renderView(<DeadCodeView adapter={adapter} />);- expect(await screen.findByText("Couldn't load summary.")).toBeInTheDocument();+ expect(await screen.findByText("Couldn't load summary")).toBeInTheDocument();expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();});@@ -198,14 +198,81 @@ describe("DeadCodeView", () => {// A failed fetch must never render as a clean repository, so the retry// card has to be the whole story: no table, no "no findings" underneath it.- expect(await screen.findByText("Couldn't load findings.")).toBeInTheDocument();+ expect(await screen.findByText("Couldn't load findings")).toBeInTheDocument();expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();expect(- screen.queryByText("No open dead-code findings for this repository."),+ screen.queryByText(/No open dead-code findings/),).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: /All findings/ })).not.toBeInTheDocument();});+ it("reviews and reopens an acknowledged finding, which the toast alone could not", async () => {+ const acked: DeadCodeFinding = { ...FINDINGS[0]!, status: "acknowledged" };+ const listFindings = vi.fn(async (opts?: { status?: string }) =>+ opts?.status === "acknowledged" ? [acked] : [],+ );+ const adapter = makeAdapter({ listFindings });+ renderView(<DeadCodeView adapter={adapter} />);++ // With no open findings the page still has to offer the way back in, not+ // just the "no dead code found" state.+ fireEvent.change(await screen.findByLabelText("Status"), {+ target: { value: "acknowledged" },+ });++ await waitFor(() =>+ expect(listFindings).toHaveBeenCalledWith(+ expect.objectContaining({ status: "acknowledged" }),+ ),+ );++ fireEvent.click(await findRowButton("Reopen src/old/legacy.ts"));+ fireEvent.click(await screen.findByRole("button", { name: "Reopen" }));++ await waitFor(() =>+ expect(adapter.patchFinding).toHaveBeenCalledWith("f1", { status: "open" }),+ );+ // Reopened, so it leaves the acknowledged slice it was being reviewed in.+ await waitFor(() =>+ expect(queryRowButton("Reopen src/old/legacy.ts")).not.toBeInTheDocument(),+ );++ // ...and it has to arrive in the open slice. The open payload predates the+ // reopen and does not contain it, so without merging the override in, the+ // finding is open on the server and invisible in the UI until a reload.+ fireEvent.change(screen.getByLabelText("Status"), { target: { value: "open" } });++ expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();+ // It is cleanup-ready, so a pile now exists and the section mounts closed.+ fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));+ expect(await findRowButton("Resolve src/old/legacy.ts")).toBeInTheDocument();+ });++ it("keeps the table when a refresh fails over rows already on screen", async () => {+ let calls = 0;+ const listFindings = vi.fn(async () => {+ calls += 1;+ if (calls > 1) throw new Error("Service unavailable");+ return FINDINGS;+ });+ const adapter = makeAdapter({+ listFindings,+ analyze: vi.fn(async () => ({ job_id: "job-1" })),+ waitForAnalysis: vi.fn(async () => {}),+ });+ renderView(<DeadCodeView adapter={adapter} />);++ fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));+ expect(await findRowButton("Resolve src/old/legacy.ts")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));++ // A transient failure on the refresh must not take the working table away+ // and lose the user's place; it reports itself above the rows.+ expect(await screen.findByText("Couldn't refresh findings")).toBeInTheDocument();+ expect(rowButton("Resolve src/old/legacy.ts")).toBeInTheDocument();+ });+it("keeps the table mounted when the last row is resolved, so undo can restore it", async () => {const only: DeadCodeFinding = { ...FINDINGS[0]!, safe_to_delete: false };const adapter = makeAdapter({ listFindings: vi.fn(async () => [only]) });diff --git a/packages/ui/src/dead-code/dead-code-adapter.ts b/packages/ui/src/dead-code/dead-code-adapter.tsindex b760e2cf1..59c2a8250 100644--- a/packages/ui/src/dead-code/dead-code-adapter.ts+++ b/packages/ui/src/dead-code/dead-code-adapter.ts@@ -1,6 +1,7 @@import type {DeadCodeFinding,DeadCodePatchInput,+ DeadCodeStatus,DeadCodeSummary,} from "@repowise-dev/types/dead-code";@@ -23,7 +24,13 @@ export interface DeadCodeAdapter {repoId: string;getSummary(): Promise<DeadCodeSummary>;- listFindings(opts?: { limit?: number }): Promise<DeadCodeFinding[]>;+ /**+ * List findings. `status` defaults to `"open"` server-side; the view passes+ * it explicitly so an acknowledged or false-positive finding can be reviewed+ * and reopened, which was otherwise only possible from a toast that expires+ * after six seconds.+ */+ listFindings(opts?: { limit?: number; status?: DeadCodeStatus }): Promise<DeadCodeFinding[]>;/*** Kick off a fresh analysis pass (host owns auth + job dispatch). Returning* the job id lets the view wait for the pass and refresh itself; hosts thatdiff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsxindex 60127d074..ce1fe7db1 100644--- a/packages/ui/src/dead-code/dead-code-view.tsx+++ b/packages/ui/src/dead-code/dead-code-view.tsx@@ -25,6 +25,7 @@ import { Trash2 } from "lucide-react";import { Button } from "../ui/button";import { Skeleton } from "../ui/skeleton";+import { ApiError } from "../shared/api-error";import { CollapsibleSection } from "../shared/collapsible-section";import { EmptyState } from "../shared/empty-state";import { AiPromptModal } from "../health/ai-prompt-modal";@@ -35,6 +36,7 @@ import { SafeToDeletePile } from "./safe-to-delete-pile";import { OwnerLeaderboard } from "./owner-leaderboard";import { FindingsBreakdownGrid } from "./findings-breakdown-grid";import { FindingsTable } from "./findings-table";+import { DEAD_CODE_STATUS_LABELS } from "./finding-cells";import type { DeadCodeAdapter } from "./dead-code-adapter";import { toFriendlyMessage } from "../lib/errors";@@ -45,21 +47,27 @@ import { toFriendlyMessage } from "../lib/errors";*/const FINDINGS_LIMIT = 500;+/** Order of the status filter; "open" first because it is the working list. */+const STATUS_ORDER: DeadCodeStatus[] = ["open", "acknowledged", "resolved", "false_positive"];+/** The one failure card both fetches use, so a broken load never reads as "clean". */-function RetryCard({ message, onRetry }: { message: string; onRetry: () => void }) {- return (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">- <span>{message}</span>- <Button size="sm" variant="outline" onClick={onRetry}>- Retry- </Button>- </div>- );+function RetryCard({+ title,+ error,+ onRetry,+}: {+ title: string;+ error: unknown;+ onRetry: () => void;+}) {+ return <ApiError title={title} message={toFriendlyMessage(error)} onRetry={onRetry} />;}export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const [analyzing, setAnalyzing] = useState(false);const [promptIds, setPromptIds] = useState<string[] | null>(null);+ /** Which slice the drill-down table shows; everything above it stays open-only. */+ const [statusFilter, setStatusFilter] = useState<DeadCodeStatus>("open");// Optimistic row state lives here, not in the table: the pile, the cluster// rollups and the table all read one slice, so resolving a row (or undoing// it) moves every surface together.@@ -89,30 +97,74 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {{ revalidateOnFocus: false },);+ // Reviewing an already-actioned finding is a second, narrower question than+ // "what can I delete", so it gets its own fetch and leaves the pile, the+ // rollups and the summary reading the open slice they have always read.+ const {+ data: reviewFindings,+ isLoading: loadingReview,+ error: reviewError,+ mutate: mutateReview,+ } = useSWR<DeadCodeFinding[]>(+ statusFilter === "open"+ ? null+ : `dead-code-findings:${adapter.cacheKey}:${statusFilter}`,+ () => adapter.listFindings({ limit: FINDINGS_LIMIT, status: statusFilter }),+ { revalidateOnFocus: false },+ );+const fetched = useMemo(() => findings ?? [], [findings]);// The server hands back at most FINDINGS_LIMIT rows with no total, so a full// page means "there may be more" and the counts below have to be scoped.const truncated = fetched.length >= FINDINGS_LIMIT;- const findingsList = useMemo(- () => fetched.map((f) => overrides[f.id] ?? f).filter((f) => f.status === "open"),- [fetched, overrides],- );+ const findingsList = useMemo(() => {+ const inPayload = new Set(fetched.map((f) => f.id));+ // A finding reopened from the review list is not in the open payload, but+ // it is open now and belongs in the pile and the rollups. Refetching+ // instead would race the optimistic override that is masking it.+ const reopened = Object.values(overrides).filter((f) => !inPayload.has(f.id));+ return [...fetched.map((f) => overrides[f.id] ?? f), ...reopened].filter(+ (f) => f.status === "open",+ );+ }, [fetched, overrides]);const safeFindings = useMemo(() => findingsList.filter((f) => f.safe_to_delete),[findingsList],);+ // What the drill-down table renders. Same override + status treatment as the+ // open slice, so reopening a row drops it out of the review list immediately.+ const tableFindings = useMemo(() => {+ if (statusFilter === "open") return findingsList;+ return (reviewFindings ?? [])+ .map((f) => overrides[f.id] ?? f)+ .filter((f) => f.status === statusFilter);+ }, [statusFilter, findingsList, reviewFindings, overrides]);++ const tableLoading = statusFilter === "open" ? loadingFindings : loadingReview;+ const tableError = statusFilter === "open" ? findingsError : reviewError;+ const retryTable = () => void (statusFilter === "open" ? mutateFindings() : mutateReview());+ // The review fetch is capped the same way, and there is no server-side total+ // for a non-open status, so the hint can only say the count is a first page.+ const reviewTruncated = (reviewFindings?.length ?? 0) >= FINDINGS_LIMIT;+// "Propose cleanup" opens the shared AI-prompt modal seeded with the safe// pile — same agent-flavor picker (incl. repowise MCP) and copy affordance as// every other AI action in the dashboard.const handlePropose = (findingIds: string[]) => setPromptIds(findingIds);- // Seeded from the whole open slice, not just the safe pile: a per-row or- // per-selection prompt can name any finding the table can show.- const promptFindings = promptIds- ? findingsList.filter((f) => promptIds.includes(f.id))- : [];+ // Seeded from both slices: the pile's CTA names open findings even while the+ // table is showing a review slice, and an empty modal is worse than none.+ const promptFindings = useMemo(() => {+ if (!promptIds) return [];+ const pool = new Map<string, DeadCodeFinding>();+ for (const f of [...findingsList, ...tableFindings]) pool.set(f.id, f);+ return promptIds.flatMap((id) => {+ const f = pool.get(id);+ return f ? [f] : [];+ });+ }, [promptIds, findingsList, tableFindings]);const handleAnalyze = async () => {// Guard here rather than on each button: the empty-state action cannot@@ -151,7 +203,7 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {await adapter.waitForAnalysis(jobId);// The pass rewrites the findings, so local optimistic state is stale.setOverrides({});- await Promise.all([mutateSummary(), mutateFindings()]);+ await Promise.all([mutateSummary(), mutateFindings(), mutateReview()]);toast.success("Dead-code findings refreshed.");} catch (err) {toast.error(@@ -164,10 +216,15 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {// Row-level patch with optimistic undo toast; injected into the table.const handlePatch = async (id: string, patch: { status: DeadCodeStatus }) => {- const finding = findingsList.find((f) => f.id === id);+ // Look in the slice on screen: reopening acts on the review list,+ // resolving on the open one.+ const finding = tableFindings.find((f) => f.id === id);const previousStatus: DeadCodeStatus = finding?.status ?? "open";const updated = await adapter.patchFinding(id, patch);setOverrides((prev) => ({ ...prev, [id]: updated }));+ // The tiles are server-derived counts of the open slice; without this they+ // drift by one on every row action and quietly disagree with the table.+ void mutateSummary();toast.success(`Finding ${patch.status.replace(/_/g, " ")}`, {action: {label: "Undo",@@ -177,6 +234,7 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {// Put the row back on screen; a server-confirmed revert that only// lands in the database is indistinguishable from a failed undo.setOverrides((prev) => ({ ...prev, [id]: reverted }));+ void mutateSummary();} catch (err) {toast.error(`Couldn't undo: ${toFriendlyMessage(err)}`);}@@ -202,12 +260,13 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const confirmed = new Set(succeededIds);setOverrides((prev) => {const next = { ...prev };- for (const f of findingsList) {+ for (const f of tableFindings) {if (confirmed.has(f.id)) next[f.id] = { ...f, status: "resolved" as DeadCodeStatus };}return next;});}+ if (succeededIds.length > 0) void mutateSummary();const succeeded = succeededIds.length;if (succeeded === ids.length) {toast.success(`Resolved ${succeeded} finding${succeeded === 1 ? "" : "s"}`);@@ -221,7 +280,29 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {return (<div className="space-y-6">- <div className="flex items-center justify-end">+ <div className="flex flex-wrap items-center justify-end gap-3">+ {/* The way back to an acknowledged or false-positive finding, which was+ otherwise reachable only from a toast that expires in six seconds.+ It sits here rather than among the table's own filters because a+ clean repository swaps the table out for an empty state, and a+ control living inside it would go with it. */}+ <div className="flex items-center gap-2">+ <label htmlFor="finding-status" className="text-xs text-[var(--color-text-secondary)]">+ Status+ </label>+ <select+ id="finding-status"+ value={statusFilter}+ onChange={(e) => setStatusFilter(e.target.value as DeadCodeStatus)}+ className="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-secondary)]"+ >+ {STATUS_ORDER.map((s) => (+ <option key={s} value={s}>+ {DEAD_CODE_STATUS_LABELS[s]}+ </option>+ ))}+ </select>+ </div><Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>{analyzing ? "Analyzing…" : "Re-analyze"}</Button>@@ -236,14 +317,13 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {) : summary ? (<SummaryBar summary={summary} />) : summaryError ? (- <RetryCard message="Couldn't load summary." onRetry={() => void mutateSummary()} />+ <RetryCard+ title="Couldn't load summary"+ error={summaryError}+ onRetry={() => void mutateSummary()}+ />) : null}- {/* A failed findings fetch must never render as an empty repository. */}- {findingsError && !loadingFindings && (- <RetryCard message="Couldn't load findings." onRetry={() => void mutateFindings()} />- )}-{/* Act now: the single "what do I delete" surface. */}{findings && safeFindings.length > 0 && (<SafeToDeletePile@@ -282,16 +362,28 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {</CollapsibleSection>)}- {/* A failed fetch already showed its retry card above; showing a table or+ {/* Everything below routes off the slice actually on screen, not the open+ fetch: a failed open fetch used to blank the table even when the user+ had switched the filter to a slice that loaded fine.++ A failure with nothing to show has to be the whole story - a table oran empty state underneath it would restate the failure as "clean". */}- {findingsError && !findings ? null : loadingFindings && !findings ? (+ {tableError && tableFindings.length === 0 && !tableLoading ? (+ <RetryCard+ title="Couldn't load findings"+ error={tableError}+ onRetry={retryTable}+ />+ ) : tableLoading && tableFindings.length === 0 ? (<Skeleton className="h-40 w-full rounded-lg" />) : /* A clean repository gets said out loud, with the way to re-check it.Keyed off the fetched payload, not the locally filtered list: resolvingthe last row must not swap the table out for an empty state, becauseundoing it would then bring the row back into a section that- remounted collapsed. */- fetched.length === 0 ? (+ remounted collapsed. Only for the open slice — swapping the table out+ while reviewing acknowledged findings would take the status filter+ with it and strand the user there. */+ statusFilter === "open" && fetched.length === 0 && findingsList.length === 0 ? (<EmptyStateicon={<Trash2 className="h-6 w-6" />}title="No dead code found"@@ -303,27 +395,47 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {Rendered only once the findings settle so `defaultOpen` sees the realpile: mounted mid-load it would always read "no pile" and open. */<CollapsibleSection+ // Remount on a status switch: defaultOpen is read once, so without this+ // picking "Acknowledged" while the section sits collapsed changes only+ // the hint text and the filter reads as broken.+ key={statusFilter}title="All findings"hint={- loadingFindings+ tableLoading? "Loading…"- : truncated && summary- ? `Showing ${findingsList.length} of ${summary.total_findings} findings`- : `${findingsList.length} findings`+ : statusFilter !== "open"+ ? `${reviewTruncated ? `First ${tableFindings.length}` : tableFindings.length} ${DEAD_CODE_STATUS_LABELS[statusFilter].toLowerCase()}`+ : truncated && summary+ ? `Showing ${findingsList.length} of ${summary.total_findings} findings`+ : `${findingsList.length} findings`}// With no safe pile above it this is the only content on the page, so- // a collapsed section reads as an empty screen.- defaultOpen={safeFindings.length === 0}+ // a collapsed section reads as an empty screen. A review slice is+ // always opened: the user asked for it explicitly.+ defaultOpen={statusFilter !== "open" || safeFindings.length === 0}>+ {/* A failed refresh over data we already hold: say so, but keep the+ rows. Replacing a working table with an error card loses the user's+ place over a transient blip. */}+ {tableError && (+ <div className="mb-3">+ <RetryCard+ title="Couldn't refresh findings"+ error={tableError}+ onRetry={retryTable}+ />+ </div>+ )}<FindingsTable- findings={findingsList}+ findings={tableFindings}onPatch={handlePatch}onBulkResolve={handleBulkResolve}onGeneratePrompt={handlePropose}fileHref={(p) => adapter.fileHref(p)}onNavigate={(href) => adapter.navigate(href)}{...(adapter.graphHref ? { graphHref: (p: string) => adapter.graphHref!(p) } : {})}- isLoading={loadingFindings}+ status={statusFilter}+ isLoading={tableLoading}/></CollapsibleSection>)}diff --git a/packages/ui/src/dead-code/finding-cells.tsx b/packages/ui/src/dead-code/finding-cells.tsxindex 118c7791c..877bb8b48 100644--- a/packages/ui/src/dead-code/finding-cells.tsx+++ b/packages/ui/src/dead-code/finding-cells.tsx@@ -11,7 +11,11 @@ import { AiPromptButton } from "../health/ai-prompt-button";import { formatConfidence } from "../lib/format";import { toFriendlyMessage } from "../lib/errors";import { cn } from "../lib/cn";-import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";+import {+ deadCodeConfidenceTier,+ type DeadCodeFinding,+ type DeadCodeStatus,+} from "@repowise-dev/types/dead-code";/*** The cell renderers behind the findings table's columns. They live apart from@@ -45,6 +49,20 @@ const STATUS_LABELS: Record<confirmLabel: "Mark FP",destructive: true,},+ open: {+ title: "Reopen finding?",+ description: "Put this finding back on the open list so cleanup picks it up again.",+ confirmLabel: "Reopen",+ destructive: false,+ },+};++/** Human labels for the status filter and the section hint beside it. */+export const DEAD_CODE_STATUS_LABELS: Record<DeadCodeStatus, string> = {+ open: "Open",+ acknowledged: "Acknowledged",+ resolved: "Resolved",+ false_positive: "False positive",};export interface FindingIdentityProps {@@ -110,15 +128,16 @@ export function FindingIdentity({ finding, href, onNavigate }: FindingIdentityPr);}-/** Confidence, coloured on the shared tier boundaries. */+/** Confidence, coloured on the shared tier boundaries rather than local ones. */export function FindingConfidence({ finding }: { finding: DeadCodeFinding }) {+ const tier = deadCodeConfidenceTier(finding.confidence);return (<spanclassName={cn("font-medium tabular-nums text-xs",- finding.confidence >= 0.8+ tier === "high"? "text-[var(--color-error)]"- : finding.confidence >= 0.6+ : tier === "medium"? "text-[var(--color-warning)]": "text-[var(--color-text-secondary)]",)}@@ -155,7 +174,11 @@ export interface FindingRowActionsProps {onGeneratePrompt?: ((id: string) => void) | undefined;}-/** Per-row status actions: resolve, acknowledge, or mark false positive. */+/**+ * Per-row status actions: resolve, acknowledge or mark false positive while a+ * finding is open, and the way back once it is not. Reopening used to be+ * reachable only from a toast that expires after six seconds.+ */export function FindingRowActions({finding,onPatch,@@ -196,7 +219,7 @@ export function FindingRowActions({actions={[{ icon: GitBranch, label: "Graph", href: graphHref(finding.file_path) }]}/>)}- {finding.status === "open" && (+ {finding.status === "open" ? (<><Buttonsize="sm"@@ -229,6 +252,17 @@ export function FindingRowActions({FP</Button></>+ ) : (+ <Button+ size="sm"+ variant="ghost"+ disabled={pending}+ onClick={() => setConfirmStatus("open")}+ className="h-6 px-2 text-xs"+ aria-label={`Reopen ${finding.file_path}`}+ >+ Reopen+ </Button>)}</span>{confirmConfig && (diff --git a/packages/ui/src/dead-code/findings-breakdown-grid.tsx b/packages/ui/src/dead-code/findings-breakdown-grid.tsxindex 332897197..beaefd02d 100644--- a/packages/ui/src/dead-code/findings-breakdown-grid.tsx+++ b/packages/ui/src/dead-code/findings-breakdown-grid.tsx@@ -1,6 +1,11 @@"use client";import * as React from "react";+import {+ DEAD_CODE_CONFIDENCE,+ deadCodeConfidenceTier,+} from "@repowise-dev/types/dead-code";+import { EmptyState } from "../shared/empty-state";import { cn } from "../lib/cn";export interface FindingsBreakdownItem {@@ -13,10 +18,14 @@ interface FindingsBreakdownGridProps {className?: string;}+/** Rows of the matrix, on the shared boundaries rather than a local guess. */const CONFIDENCE_TIERS = [- { id: "high", label: "High (≥0.8)", min: 0.8 },- { id: "med", label: "Medium (0.5–0.8)", min: 0.5 },- { id: "low", label: "Low (<0.5)", min: 0 },+ { id: "high", label: `High (≥${DEAD_CODE_CONFIDENCE.HIGH})` },+ {+ id: "medium",+ label: `Medium (${DEAD_CODE_CONFIDENCE.MEDIUM}–${DEAD_CODE_CONFIDENCE.HIGH})`,+ },+ { id: "low", label: `Low (<${DEAD_CODE_CONFIDENCE.MEDIUM})` },] as const;const KIND_LABELS: Record<string, string> = {@@ -26,23 +35,18 @@ const KIND_LABELS: Record<string, string> = {zombie_package: "Zombie package",};-function tierFor(confidence: number) {- for (const t of CONFIDENCE_TIERS) if (confidence >= t.min) return t.id;- return "low";-}-/*** Confidence-tier × kind matrix for dead-code findings — surfaces where the* concentration is so reviewers know whether to start with high-confidence* file removals or low-confidence symbol pruning.*/export function FindingsBreakdownGrid({ findings, className }: FindingsBreakdownGridProps) {- const { kinds, counts, max } = React.useMemo(() => {+ const { kinds, counts, max, tiers } = React.useMemo(() => {const kindSet = new Set<string>();const counts: Record<string, Record<string, number>> = {};let max = 0;for (const f of findings) {- const tier = tierFor(f.confidence);+ const tier = deadCodeConfidenceTier(f.confidence);const kind = f.kind ?? "unknown";kindSet.add(kind);counts[tier] ??= {};@@ -50,19 +54,21 @@ export function FindingsBreakdownGrid({ findings, className }: FindingsBreakdownif (counts[tier][kind] > max) max = counts[tier][kind];}const ordered = Array.from(kindSet).sort();- return { kinds: ordered, counts, max };+ // The list endpoint floors at MEDIUM, so the low row is normally an empty+ // band across the whole matrix. Show it only when something is in it.+ const tiers = CONFIDENCE_TIERS.filter(+ (t) => t.id !== "low" || Object.keys(counts["low"] ?? {}).length > 0,+ );+ return { kinds: ordered, counts, max, tiers };}, [findings]);if (kinds.length === 0) {return (- <div- className={cn(- "rounded-md border border-dashed border-[var(--color-border-default)] p-4 text-center text-xs text-[var(--color-text-tertiary)]",- className,- )}- >- No findings yet.- </div>+ <EmptyState+ title="No findings yet"+ description="Nothing to break down until an analysis has produced dead-code findings."+ {...(className ? { className } : {})}+ />);}@@ -90,7 +96,7 @@ export function FindingsBreakdownGrid({ findings, className }: FindingsBreakdown</tr></thead><tbody>- {CONFIDENCE_TIERS.map((tier) => (+ {tiers.map((tier) => (<tr key={tier.id} className="border-t border-[var(--color-border-default)]"><td className="px-3 py-2 text-[var(--color-text-secondary)]">{tier.label}</td>{kinds.map((k) => {@@ -101,13 +107,13 @@ export function FindingsBreakdownGrid({ findings, className }: FindingsBreakdownconst tierToken =tier.id === "high"? "var(--color-error)"- : tier.id === "med"+ : tier.id === "medium"? "var(--color-warning)": "var(--color-text-tertiary)";const alphaPct =tier.id === "high"? Math.round((0.12 + intensity * 0.55) * 100)- : tier.id === "med"+ : tier.id === "medium"? Math.round((0.1 + intensity * 0.5) * 100): Math.round((0.08 + intensity * 0.4) * 100);const bg =diff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsxindex e44863c5e..9ee08e380 100644--- a/packages/ui/src/dead-code/findings-table.tsx+++ b/packages/ui/src/dead-code/findings-table.tsx@@ -19,8 +19,13 @@ import {FindingConfidence,FindingSafety,FindingRowActions,+ DEAD_CODE_STATUS_LABELS,} from "./finding-cells";-import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";+import {+ DEAD_CODE_CONFIDENCE,+ type DeadCodeFinding,+ type DeadCodeStatus,+} from "@repowise-dev/types/dead-code";/*** Display names and tab order for the kinds we know about. Any other kind the@@ -65,7 +70,7 @@ function sortValue(f: DeadCodeFinding, key: SortKey): string | number {}export interface FindingsTableProps {- /** Full open-findings slice; the table filters by kind / confidence / safety client-side. */+ /** One status slice; the table filters by kind / confidence / safety client-side. */findings: DeadCodeFinding[];/** Injected mutation — host owns the API call, optimistic toast + undo. */onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;@@ -79,6 +84,12 @@ export interface FindingsTableProps {graphHref?: ((path: string) => string) | undefined;/** Open an AI cleanup prompt for the given findings (one row, or the selection). */onGeneratePrompt?: ((ids: string[]) => void) | undefined;+ /**+ * Which status slice is on screen. The host owns both the fetch and the+ * control that switches it, because a clean repository replaces this table+ * with an empty state and a control living in here would go with it.+ */+ status?: DeadCodeStatus | undefined;isLoading?: boolean;}@@ -102,10 +113,13 @@ export function FindingsTable({onNavigate,graphHref,onGeneratePrompt,+ status = "open",isLoading,}: FindingsTableProps) {const [activeTab, setActiveTab] = useState<string | null>(null);- const [minConfidence, setMinConfidence] = useState(0.4);+ // The slider floor is the server's own `min_confidence` default: nothing+ // below it is ever fetched, so a lower floor would be a control over nothing.+ const [minConfidence, setMinConfidence] = useState<number>(DEAD_CODE_CONFIDENCE.MEDIUM);const [safeOnly, setSafeOnly] = useState(false);const [query, setQuery] = useState("");const [sortKey, setSortKey] = useState<SortKey>("confidence");@@ -203,12 +217,12 @@ export function FindingsTable({};const resetFilters = () => {- setMinConfidence(0.4);+ setMinConfidence(DEAD_CODE_CONFIDENCE.MEDIUM);setSafeOnly(false);setQuery("");};- const filtersActive = minConfidence > 0.4 || safeOnly || query.trim() !== "";+ const filtersActive = minConfidence > DEAD_CODE_CONFIDENCE.MEDIUM || safeOnly || query.trim() !== "";const resolveSelected = async () => {if (!onBulkResolve) return;@@ -248,6 +262,11 @@ export function FindingsTable({<inputtype="checkbox"checked={allVisibleSelected}+ // A partial selection read as "nothing selected" before, so+ // clicking through it silently discarded the user's picks.+ ref={(el) => {+ if (el) el.indeterminate = selectedCount > 0 && !allVisibleSelected;+ }}onChange={toggleSelectAll}aria-label="Select all findings"className="rounded border-[var(--color-border-default)]"@@ -345,6 +364,7 @@ export function FindingsTable({// the injected callbacks.}, [selected,+ selectedCount,allVisibleSelected,fileHref,onNavigate,@@ -374,16 +394,18 @@ export function FindingsTable({/></div><div className="flex items-center gap-2">- <label htmlFor="min-confidence" className="text-xs text-[var(--color-text-secondary)]">+ {/* A live value readout, not a <label>: the thing it describes is a+ Radix span with role="slider", which htmlFor cannot reach. The+ accessible name rides on the thumb's aria-label instead. */}+ <span className="text-xs text-[var(--color-text-secondary)]">Min confidence: {Math.round(minConfidence * 100)}%- </label>+ </span><Slider- id="min-confidence"- min={0.4}+ min={DEAD_CODE_CONFIDENCE.MEDIUM}max={1}step={0.05}value={[minConfidence]}- onValueChange={([v]) => setMinConfidence(v ?? 0.4)}+ onValueChange={([v]) => setMinConfidence(v ?? DEAD_CODE_CONFIDENCE.MEDIUM)}aria-label="Minimum confidence"className="w-28"/>@@ -393,7 +415,8 @@ export function FindingsTable({Cleanup-ready only</label>- {onBulkResolve && selectedCount > 0 && (+ {/* Bulk resolve only makes sense on findings that are still open. */}+ {onBulkResolve && status === "open" && selectedCount > 0 && (<Buttonsize="sm"variant="outline"@@ -427,7 +450,7 @@ export function FindingsTable({) : tabs.length === 0 ? (<EmptyStatetitle="No findings"- description="No open dead-code findings for this repository."+ description={`No ${DEAD_CODE_STATUS_LABELS[status].toLowerCase()} dead-code findings for this repository.`}/>) : (<Tabs@@ -480,7 +503,7 @@ export function FindingsTable({empty={<EmptyStatetitle="No findings"- description="No open findings for this category with current filters."+ description="No findings in this category with the current filters."{...(filtersActive? { action: { label: "Reset filters", onClick: resetFilters } }: {})}diff --git a/packages/ui/src/dead-code/owner-leaderboard.tsx b/packages/ui/src/dead-code/owner-leaderboard.tsxindex 2b6027dac..1ffaafa6b 100644--- a/packages/ui/src/dead-code/owner-leaderboard.tsx+++ b/packages/ui/src/dead-code/owner-leaderboard.tsx@@ -1,6 +1,7 @@"use client";import * as React from "react";+import { EmptyState } from "../shared/empty-state";import { cn } from "../lib/cn";export interface OwnerLeaderboardFinding {@@ -51,14 +52,11 @@ export function OwnerLeaderboard({if (tallies.length === 0) {return (- <div- className={cn(- "rounded-md border border-dashed border-[var(--color-border-default)] p-4 text-center text-xs text-[var(--color-text-tertiary)]",- className,- )}- >- No owner attribution yet — run analysis to populate.- </div>+ <EmptyState+ title="No owner attribution yet"+ description="Run the analysis to attribute dead code to its primary contributors."+ {...(className ? { className } : {})}+ />);}diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsxindex fdf35ae86..f9aa99364 100644--- a/packages/ui/src/health/triage-view.tsx+++ b/packages/ui/src/health/triage-view.tsx@@ -22,7 +22,8 @@ import type {} from "@repowise-dev/types/health";import { Skeleton } from "../ui/skeleton";-import { Button } from "../ui/button";+import { ApiError } from "../shared/api-error";+import { toFriendlyMessage } from "../lib/errors";import { HealthKpiCards } from "./kpi-cards";import { BiomarkerList } from "./biomarker-list";@@ -159,10 +160,11 @@ export function TriageView({</div></div>) : error ? (- <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">- <span>Couldn't load health data. Index this repo to populate it.</span>- <Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button>- </div>+ <ApiError+ title="Couldn't load health data"+ message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}+ onRetry={() => void mutate()}+ />) : overview ? (<>{/* Proof, up front: the defect-validated headline that sets this scorediff --git a/packages/ui/src/shared/row-actions.tsx b/packages/ui/src/shared/row-actions.tsxindex dd7a9d8c5..d24bc730d 100644--- a/packages/ui/src/shared/row-actions.tsx+++ b/packages/ui/src/shared/row-actions.tsx@@ -20,6 +20,10 @@ export function RowActions({ actions, className }: RowActionsProps) {key={action.label}href={action.href}title={action.label}+ // The text is hidden below lg, leaving an icon-only link whose only+ // name was a title attribute — which screen readers do not reliably+ // announce and touch users never see.+ aria-label={action.label}className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] hover:bg-[var(--color-bg-elevated)] transition-colors"><action.icon className="h-3 w-3" />diff --git a/packages/ui/src/ui/slider.tsx b/packages/ui/src/ui/slider.tsxindex 012fb54e1..e9634adec 100644--- a/packages/ui/src/ui/slider.tsx+++ b/packages/ui/src/ui/slider.tsx@@ -3,8 +3,16 @@import * as SliderPrimitive from "@radix-ui/react-slider";import { cn } from "../lib/cn";+/**+ * Radix puts `role="slider"` on the Thumb, so a naming prop spread onto the+ * Root labels an element assistive tech never announces and leaves the actual+ * control anonymous. Both naming props are forwarded to the Thumb instead.+ * (`<label htmlFor>` reaches neither: they are spans, not labelable elements.)+ */export function Slider({className,+ "aria-label": ariaLabel,+ "aria-labelledby": ariaLabelledBy,...props}: React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>) {return (@@ -19,6 +27,8 @@ export function Slider({<SliderPrimitive.Range className="absolute h-full bg-[var(--color-accent-primary)]" /></SliderPrimitive.Track><SliderPrimitive.Thumb+ aria-label={ariaLabel}+ aria-labelledby={ariaLabelledBy}className={cn("block h-4 w-4 rounded-full border border-[var(--color-accent-primary)] bg-[var(--color-bg-surface)] shadow","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]",diff --git a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx b/packages/web/src/components/dashboard/quick-actions-wrapper.tsxindex cb8c8c8ac..e985f0bff 100644--- a/packages/web/src/components/dashboard/quick-actions-wrapper.tsx+++ b/packages/web/src/components/dashboard/quick-actions-wrapper.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useMemo, useState } from "react";+import { useRouter } from "next/navigation";import { toast } from "sonner";import {QuickActions as QuickActionsShell,@@ -29,6 +30,13 @@ interface Props {docsMode?: RepoResponse["docs_mode"];}+/** Human label for an action key, for toast copy. */+function labelFor(key: QuickActionKey): string {+ return (+ [GENERATE_DOCS_ACTION, ...DEFAULT_QUICK_ACTIONS].find((a) => a.key === key)?.label ?? key+ );+}+export function QuickActionsWrapper({repoId,repoName,@@ -38,7 +46,11 @@ export function QuickActionsWrapper({lastResyncAt,docsMode,}: Props) {+ const router = useRouter();const [activeJobId, setActiveJobId] = useState<string | null>(null);+ // Which action started the job on screen, so its completion can be reported+ // and refreshed in its own terms rather than as a generic doc generation.+ const [activeKey, setActiveKey] = useState<QuickActionKey | null>(null);const bulk = useBulkGenerate(repoId);// Hydrate from any in-flight job so refreshes don't lose progress visibility.@@ -70,6 +82,26 @@ export function QuickActionsWrapper({[docsMode],);+ function startWatching(jobId: string, key: QuickActionKey | null) {+ setActiveJobId(jobId);+ setActiveKey(key);+ }++ function handleJobDone(status: "completed" | "failed" | "cancelled") {+ const key = activeKey;+ setActiveJobId(null);+ setActiveKey(null);+ bulk.clearJob();+ if (key === "dead-code") {+ if (status === "completed") toast.success("Dead code scan finished");+ else if (status === "failed") toast.error("Dead code scan failed");+ }+ // This page is server-rendered: without a refresh the "Dead Exports" tile+ // the scan exists to move keeps showing its pre-scan number, and the same+ // goes for every stat a sync, re-index or bulk generate just changed.+ if (status === "completed") router.refresh();+ }+async function handleAction(key: QuickActionKey) {if (key === "generate-docs") {bulk.begin(@@ -81,15 +113,15 @@ export function QuickActionsWrapper({try {if (key === "sync") {const job = await syncRepo(repoId);- setActiveJobId(job.id);+ startWatching(job.id, key);toast.info(`Sync started${repoName ? ` — ${repoName}` : ""}`);} else if (key === "resync") {const job = await fullResyncRepo(repoId);- setActiveJobId(job.id);+ startWatching(job.id, key);toast.info(`Full resync started${repoName ? ` — ${repoName}` : ""}`);} else if (key === "dead-code") {const { job_id } = await analyzeDeadCode(repoId);- setActiveJobId(job_id);+ startWatching(job_id, key);toast.info("Dead code analysis started");}} catch (e) {@@ -102,7 +134,8 @@ export function QuickActionsWrapper({]);const inflight = running[0] ?? pending[0];if (inflight) {- setActiveJobId(inflight.id);+ // Someone else's job: watch it, but do not claim it as this action.+ startWatching(inflight.id, null);toast.info("Showing progress for the in-flight job. Cancel it from the panel to start a new one.",);@@ -112,7 +145,7 @@ export function QuickActionsWrapper({// fall through}}- toast.error(`${key} failed`, { description: msg });+ toast.error(`${labelFor(key)} failed`, { description: msg });}}@@ -122,10 +155,11 @@ export function QuickActionsWrapper({<GenerationProgressWrapperjobId={jobId}repoName={repoName}- onDone={() => {- setActiveJobId(null);- bulk.clearJob();- }}+ // A dead-code scan runs the index-only pipeline, so the generic+ // "Documentation updated - 0 pages generated" toast would describe it+ // wrongly. It reports itself below instead.+ quiet={activeKey === "dead-code"}+ onDone={handleJobDone}/>) : null;diff --git a/packages/web/src/components/jobs/generation-progress-wrapper.tsx b/packages/web/src/components/jobs/generation-progress-wrapper.tsxindex e3f05b8dd..a8f2bfd5b 100644--- a/packages/web/src/components/jobs/generation-progress-wrapper.tsx+++ b/packages/web/src/components/jobs/generation-progress-wrapper.tsx@@ -12,7 +12,9 @@ import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";interface Props {jobId: string;repoName?: string;- onDone?: () => void;+ /** Fired once the job reaches a terminal state, with which one it reached+ * so the host can tell "finished" from "failed" without re-reading the job. */+ onDone?: (status: "completed" | "failed" | "cancelled") => void;/** Start a fresh run after a failure or cancellation. */onRetry?: () => void;/** Suppress the completion/failure toasts (when the host surface renders@@ -55,7 +57,7 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, qudescription: `${formatNumber(job.completed_pages)} pages generated`,});}- onDone?.();+ onDone?.("completed");} else if (job?.status === "failed") {notifiedRef.current = true;if (!quiet) {@@ -63,7 +65,7 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, qudescription: job.error_message ?? "Unknown error",});}- onDone?.();+ onDone?.("failed");} else if (job?.status === "cancelled") {notifiedRef.current = true;if (!quiet) {@@ -71,7 +73,7 @@ export function GenerationProgressWrapper({ jobId, repoName, onDone, onRetry, qudescription: "The pipeline was stopped before completion.",});}- onDone?.();+ onDone?.("cancelled");}}, [job?.status, job?.completed_pages, job?.error_message, repoName, onDone, quiet]);