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
fix(dead-code): correct the findings table and give it an AI prompt, links and reasons (#990)
Raghav Chamadiya7483d7cd8499
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 8d0697378..430ffb877 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -1102,8 +1102,9 @@ class DeadCodeAnalyzer:) -> list[DeadCodeFindingData]:"""Detect private/internal symbols with zero incoming call edges.- Off by default (higher false-positive rate). Enable with- ``detect_unused_internals=True`` in the config dict.+ On by default. These carry a higher false-positive rate than the other+ detectors, which is why they land at a lower confidence. Disable with+ ``detect_unused_internals=False`` in the config dict."""findings: list[DeadCodeFindingData] = []diff --git a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx b/packages/ui/__tests__/dead-code/dead-code-view.test.tsxindex 76d430abe..6bd0c330b 100644--- a/packages/ui/__tests__/dead-code/dead-code-view.test.tsx+++ b/packages/ui/__tests__/dead-code/dead-code-view.test.tsx@@ -9,6 +9,14 @@ import type {DeadCodeSummary,} from "@repowise-dev/types/dead-code";+// jsdom has no layout engine → stub ResizeObserver so the Radix slider mounts.+class RO {+ observe() {}+ unobserve() {}+ disconnect() {}+}+vi.stubGlobal("ResizeObserver", RO);+// Capture sonner toasts so we can assert the undo affordance without a Toaster.const toastSuccess = vi.fn();const toastError = vi.fn();@@ -103,6 +111,20 @@ function renderView(node: ReactElement) {);}+/**+ * The most recent toast that actually carries an Undo action. Selecting by+ * shape rather than by position keeps this immune to an unrelated toast (a+ * refresh notice, say) landing last.+ */+function lastUndoAction(): { label: string; onClick: () => Promise<void> } {+ const call = toastSuccess.mock.calls+ .filter((c) => (c[1] as { action?: unknown } | undefined)?.action)+ .at(-1);+ const action = (call?.[1] as { action: { label: string; onClick: () => Promise<void> } }).action;+ expect(action.label).toBe("Undo");+ return action;+}+beforeEach(() => {toastSuccess.mockClear();toastError.mockClear();@@ -149,4 +171,140 @@ describe("DeadCodeView", () => {expect(await screen.findByText("AI cleanup prompt")).toBeInTheDocument();});++ it("surfaces a retry affordance when the findings fetch fails", async () => {+ const adapter = makeAdapter({+ listFindings: vi.fn(async () => {+ throw new Error("boom");+ }),+ });+ renderView(<DeadCodeView adapter={adapter} />);++ // 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(screen.queryByText("No dead code found")).not.toBeInTheDocument();+ expect(+ screen.queryByText("No open dead-code findings for this repository."),+ ).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /All findings/ })).not.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]) });+ renderView(<DeadCodeView adapter={adapter} />);++ // No safe pile above it, so the section leads the page already open.+ fireEvent.click(await screen.findByRole("button", { name: "Resolve src/old/legacy.ts" }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));++ // Emptying the list locally must not swap in the "No dead code found"+ // state: that unmounts the section, and undo would restore the row into a+ // section that remounted collapsed.+ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "Resolve src/old/legacy.ts" }),+ ).not.toBeInTheDocument(),+ );+ expect(screen.queryByText("No dead code found")).not.toBeInTheDocument();++ const undo = lastUndoAction();+ await undo.onClick();++ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Resolve src/old/legacy.ts" })).toBeInTheDocument(),+ );+ });++ it("waits for the analysis job and refetches when it finishes", async () => {+ let resolveJob: (() => void) | undefined;+ const adapter = makeAdapter({+ analyze: vi.fn(async () => ({ job_id: "job-1" })),+ waitForAnalysis: vi.fn(+ () =>+ new Promise<void>((res) => {+ resolveJob = res;+ }),+ ),+ });+ renderView(<DeadCodeView adapter={adapter} />);+ await screen.findByText("lines in cleanup candidates");++ const listCallsBefore = (adapter.listFindings as ReturnType<typeof vi.fn>).mock.calls.length;+ fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));++ await waitFor(() => expect(adapter.waitForAnalysis).toHaveBeenCalledWith("job-1"));+ resolveJob?.();++ // Without this the toast promised fresh results over an unchanged fetch.+ await waitFor(() =>+ expect(+ (adapter.listFindings as ReturnType<typeof vi.fn>).mock.calls.length,+ ).toBeGreaterThan(listCallsBefore),+ );+ // Settle the refresh before the test ends: leaving it in flight lets a+ // late toast land inside a later test and pick up its assertions.+ await waitFor(() =>+ expect(toastSuccess).toHaveBeenCalledWith("Dead-code findings refreshed."),+ );+ expect((adapter.getSummary as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(1);+ });++ it("blames the watch, not the launch, when the job fails after it started", async () => {+ const adapter = makeAdapter({+ analyze: vi.fn(async () => ({ job_id: "job-1" })),+ waitForAnalysis: vi.fn(async () => {+ throw new Error("Gateway timeout");+ }),+ });+ renderView(<DeadCodeView adapter={adapter} />);++ fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));++ // The job is running; "Couldn't start analysis" would be a false statement.+ await waitFor(() => expect(toastError).toHaveBeenCalled());+ expect(String(toastError.mock.calls[0]?.[0])).toMatch(/stopped tracking it/);+ expect(String(toastError.mock.calls[0]?.[0])).not.toMatch(/start analysis/);+ });++ it("reports a 409 as another job running rather than a generic failure", async () => {+ const conflict = Object.assign(new Error("A job is already in progress"), { status: 409 });+ const adapter = makeAdapter({+ analyze: vi.fn(async () => {+ throw conflict;+ }),+ });+ renderView(<DeadCodeView adapter={adapter} />);++ fireEvent.click(screen.getByRole("button", { name: "Re-analyze" }));++ await waitFor(() => expect(toastError).toHaveBeenCalled());+ expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Another job is already running/);+ });++ it("undo puts the row back on screen, not just in the database", async () => {+ const adapter = makeAdapter();+ renderView(<DeadCodeView adapter={adapter} />);++ // Open the drill-down table (collapsed by default).+ fireEvent.click(await screen.findByRole("button", { name: /All findings/ }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve src/old/legacy.ts" }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));++ // Optimistically gone from the table.+ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "Resolve src/old/legacy.ts" }),+ ).not.toBeInTheDocument(),+ );++ // The toast's Undo action re-patches; the row has to come back with it.+ const undo = lastUndoAction();+ await undo.onClick();++ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Resolve src/old/legacy.ts" })).toBeInTheDocument(),+ );+ });});diff --git a/packages/ui/__tests__/dead-code/findings-table.test.tsx b/packages/ui/__tests__/dead-code/findings-table.test.tsxnew file mode 100644index 000000000..d96a3351e--- /dev/null+++ b/packages/ui/__tests__/dead-code/findings-table.test.tsx@@ -0,0 +1,269 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { FindingsTable } from "../../src/dead-code/findings-table.js";+import type { DeadCodeFinding } from "@repowise-dev/types/dead-code";++// jsdom has no layout engine → stub ResizeObserver so the Radix slider mounts.+class RO {+ observe() {}+ unobserve() {}+ disconnect() {}+}+vi.stubGlobal("ResizeObserver", RO);++const toastError = vi.fn();+vi.mock("sonner", () => ({+ toast: {+ success: vi.fn(),+ error: (...a: unknown[]) => toastError(...a),+ warning: vi.fn(),+ },+}));++function finding(over: Partial<DeadCodeFinding> & { id: string }): DeadCodeFinding {+ return {+ kind: "unreachable_file",+ file_path: `src/${over.id}.ts`,+ symbol_name: null,+ symbol_kind: null,+ confidence: 0.9,+ reason: "No importers",+ lines: 10,+ safe_to_delete: true,+ risk_factors: [],+ primary_owner: "alice",+ status: "open",+ note: null,+ ...over,+ };+}++const noopPatch = vi.fn(async (id: string) => finding({ id, status: "resolved" }));++const noopBulk = vi.fn(async (ids: string[]) => ids);++function renderTable(findings: DeadCodeFinding[], props: Record<string, unknown> = {}) {+ return render(+ <FindingsTable+ findings={findings}+ onPatch={noopPatch}+ onBulkResolve={noopBulk}+ {...props}+ />,+ );+}++beforeEach(() => {+ toastError.mockClear();+ noopPatch.mockClear();+});++describe("FindingsTable kind bucketing", () => {+ it("gives every kind present a tab, including ones with no hardcoded label", () => {+ renderTable([+ finding({ id: "a", kind: "unreachable_file" }),+ finding({ id: "b", kind: "unused_internal" }),+ finding({ id: "c", kind: "some_future_kind" }),+ ]);++ // The regression this guards: a fixed three-kind allowlist silently dropped+ // unused_internal findings that every other surface was counting.+ expect(screen.getByRole("tab", { name: /Unreachable Files/ })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Unused Internals/ })).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: /Some Future Kind/ })).toBeInTheDocument();+ });++ it("shows no tab for a kind that is absent from the data", () => {+ renderTable([finding({ id: "a", kind: "unreachable_file" })]);++ expect(screen.queryByRole("tab", { name: /Zombie Packages/ })).not.toBeInTheDocument();+ });++ it("renders an empty state rather than tabs when there are no findings", () => {+ renderTable([]);++ expect(screen.getByText("No findings")).toBeInTheDocument();+ expect(screen.queryByRole("tab")).not.toBeInTheDocument();+ });++ it("tab counts follow the confidence filter while the tab itself stays put", async () => {+ renderTable([+ finding({ id: "a", kind: "unreachable_file", confidence: 1 }),+ finding({ id: "b", kind: "unreachable_file", confidence: 0.45 }),+ ]);++ expect(screen.getByRole("tab", { name: /Unreachable Files 2/ })).toBeInTheDocument();++ const slider = screen.getByLabelText("Minimum confidence");+ for (let i = 0; i < 12; i++) fireEvent.keyDown(slider, { key: "ArrowRight" });++ // The count drops, but the tab does not disappear from under the pointer.+ await waitFor(() =>+ expect(screen.getByRole("tab", { name: /Unreachable Files 1/ })).toBeInTheDocument(),+ );+ });+});++describe("FindingsTable selection", () => {+ it("select-all covers the visible rows and not the filtered-out ones", async () => {+ const onBulkResolve = vi.fn(async (ids: string[]) => ids);+ renderTable(+ [+ finding({ id: "a", confidence: 1 }),+ finding({ id: "hidden", confidence: 0.45 }),+ finding({ id: "b", confidence: 1 }),+ ],+ { onBulkResolve },+ );++ // Push the low-confidence row out of view first, then select all.+ const slider = screen.getByLabelText("Minimum confidence");+ for (let i = 0; i < 12; i++) fireEvent.keyDown(slider, { key: "ArrowRight" });+ await waitFor(() =>+ expect(screen.queryByLabelText("Select finding src/hidden.ts")).not.toBeInTheDocument(),+ );++ fireEvent.click(screen.getByLabelText("Select all findings"));+ expect(screen.getByRole("button", { name: "Resolve 2 selected" })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Resolve 2 selected" }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve all" }));++ await waitFor(() => expect(onBulkResolve).toHaveBeenCalledWith(["a", "b"]));+ });++ it("drops selected rows the confidence filter has hidden", async () => {+ const onBulkResolve = vi.fn(async (ids: string[]) => ids);+ renderTable(+ [finding({ id: "a", confidence: 1 }), finding({ id: "b", confidence: 0.45 })],+ { onBulkResolve },+ );++ fireEvent.click(screen.getByLabelText("Select all findings"));+ expect(screen.getByRole("button", { name: "Resolve 2 selected" })).toBeInTheDocument();++ // Raise the floor past the second finding: it leaves the table, so it must+ // leave the selection too — otherwise "Resolve N selected" resolves rows+ // the user can no longer see.+ const slider = screen.getByLabelText("Minimum confidence");+ for (let i = 0; i < 12; i++) fireEvent.keyDown(slider, { key: "ArrowRight" });++ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Resolve 1 selected" })).toBeInTheDocument(),+ );++ fireEvent.click(screen.getByRole("button", { name: "Resolve 1 selected" }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve all" }));++ await waitFor(() => expect(onBulkResolve).toHaveBeenCalledWith(["a"]));+ });++ it("clears selection when switching tabs", () => {+ renderTable([+ finding({ id: "a", kind: "unreachable_file" }),+ finding({ id: "b", kind: "unused_export" }),+ ]);++ fireEvent.click(screen.getByLabelText("Select all findings"));+ expect(screen.getByRole("button", { name: "Resolve 1 selected" })).toBeInTheDocument();++ // Radix activates a tab on mousedown, not click.+ fireEvent.mouseDown(screen.getByRole("tab", { name: /Unused Exports/ }));++ expect(screen.queryByRole("button", { name: /Resolve \d+ selected/ })).not.toBeInTheDocument();+ });+});++describe("FindingsTable row affordances", () => {+ it("links the file path and opens the row through the host router", () => {+ const onNavigate = vi.fn();+ renderTable([finding({ id: "a" })], {+ fileHref: (p: string) => `/repos/repo-1/files/${p}`,+ onNavigate,+ });++ const link = screen.getByRole("link", { name: "src/a.ts" });+ expect(link).toHaveAttribute("href", "/repos/repo-1/files/src/a.ts");++ fireEvent.click(screen.getByRole("row", { name: /src\/a\.ts/ }));+ expect(onNavigate).toHaveBeenCalledWith("/repos/repo-1/files/src/a.ts");++ // A plain click on the name routes through the host too, rather than+ // falling through to a full page load inside a client-routed row.+ onNavigate.mockClear();+ fireEvent.click(link, { button: 0 });+ expect(onNavigate).toHaveBeenCalledWith("/repos/repo-1/files/src/a.ts");+ });++ it("does not navigate when the checkbox is clicked", () => {+ const onNavigate = vi.fn();+ renderTable([finding({ id: "a" })], { fileHref: (p: string) => `/f/${p}`, onNavigate });++ fireEvent.click(screen.getByLabelText("Select finding src/a.ts"));++ expect(onNavigate).not.toHaveBeenCalled();+ });++ it("shows the detector's reason, which previously only the AI prompt saw", () => {+ renderTable([finding({ id: "a", reason: "No importers in the dependency graph" })]);++ expect(screen.getByText("No importers in the dependency graph")).toBeInTheDocument();+ });++ it("offers an AI prompt per row and for the current selection", () => {+ const onGeneratePrompt = vi.fn();+ renderTable([finding({ id: "a" }), finding({ id: "b" })], { onGeneratePrompt });++ fireEvent.click(screen.getByRole("button", { name: "AI cleanup prompt for src/a.ts" }));+ expect(onGeneratePrompt).toHaveBeenCalledWith(["a"]);++ fireEvent.click(screen.getByLabelText("Select all findings"));+ fireEvent.click(screen.getByRole("button", { name: "AI prompt for 2 selected" }));+ expect(onGeneratePrompt).toHaveBeenLastCalledWith(["a", "b"]);+ });++ it("renders the graph action from the host's route, and hides it without one", () => {+ const { unmount } = renderTable([finding({ id: "a" })], {+ graphHref: (p: string) => `/repos/repo-1/architecture?node=${encodeURIComponent(p)}`,+ });+ expect(screen.getByRole("link", { name: "Graph" })).toHaveAttribute(+ "href",+ "/repos/repo-1/architecture?node=src%2Fa.ts",+ );+ unmount();++ // No graph route on the host (the hosted frontend today) means no action,+ // rather than a link into a page that does not exist there.+ renderTable([finding({ id: "a" })]);+ expect(screen.queryByRole("link", { name: "Graph" })).not.toBeInTheDocument();+ });++ it("reports a rejecting bulk resolve instead of wedging the dialog open", async () => {+ const onBulkResolve = vi.fn(async () => {+ throw new Error("Service unavailable");+ });+ renderTable([finding({ id: "a" })], { onBulkResolve });++ fireEvent.click(screen.getByLabelText("Select all findings"));+ fireEvent.click(screen.getByRole("button", { name: "Resolve 1 selected" }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve all" }));++ await waitFor(() => expect(toastError).toHaveBeenCalled());+ expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Couldn't resolve findings/);+ });+});++describe("FindingsTable row actions", () => {+ it("surfaces a toast instead of an unhandled rejection when a patch fails", async () => {+ const onPatch = vi.fn(async () => {+ throw new Error("Network request failed");+ });+ renderTable([finding({ id: "a" })], { onPatch });++ fireEvent.click(screen.getByRole("button", { name: "Resolve src/a.ts" }));+ fireEvent.click(await screen.findByRole("button", { name: "Resolve" }));++ await waitFor(() => expect(toastError).toHaveBeenCalled());+ expect(String(toastError.mock.calls[0]?.[0])).toMatch(/Couldn't update finding/);+ });+});diff --git a/packages/ui/src/dead-code/dead-code-adapter.ts b/packages/ui/src/dead-code/dead-code-adapter.tsindex d59012884..b760e2cf1 100644--- a/packages/ui/src/dead-code/dead-code-adapter.ts+++ b/packages/ui/src/dead-code/dead-code-adapter.ts@@ -24,8 +24,18 @@ export interface DeadCodeAdapter {getSummary(): Promise<DeadCodeSummary>;listFindings(opts?: { limit?: number }): Promise<DeadCodeFinding[]>;- /** Kick off a fresh analysis pass (host owns auth + job dispatch). */- analyze(): Promise<void>;+ /**+ * 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 that+ * cannot observe the job may return nothing, and the view falls back to+ * "results will appear shortly".+ */+ analyze(): Promise<{ job_id?: string } | void>;+ /**+ * Resolve once the analysis job reaches a terminal state, rejecting if it+ * fails. Optional: without it the view cannot know when to refetch.+ */+ waitForAnalysis?(jobId: string): Promise<void>;patchFinding(findingId: string,patch: DeadCodePatchInput,@@ -33,6 +43,12 @@ export interface DeadCodeAdapter {/** Build an href to a file detail page. */fileHref(path: string): string;+ /**+ * Build an href to the dependency graph focused on a file. Optional: hosts+ * without a graph surface omit it and the row action disappears, which keeps+ * the app's route map out of this package.+ */+ graphHref?(path: string): string;/** Navigate to an href (host wires this to its router). */navigate(href: string): void;}diff --git a/packages/ui/src/dead-code/dead-code-view.tsx b/packages/ui/src/dead-code/dead-code-view.tsxindex 332a9a5fe..60127d074 100644--- a/packages/ui/src/dead-code/dead-code-view.tsx+++ b/packages/ui/src/dead-code/dead-code-view.tsx@@ -12,7 +12,7 @@* and hosted render the same view from one source.*/-import { useState } from "react";+import { useMemo, useState } from "react";import useSWR from "swr";import { toast } from "sonner";import type {@@ -21,9 +21,12 @@ import type {DeadCodeSummary,} from "@repowise-dev/types/dead-code";+import { Trash2 } from "lucide-react";+import { Button } from "../ui/button";import { Skeleton } from "../ui/skeleton";import { CollapsibleSection } from "../shared/collapsible-section";+import { EmptyState } from "../shared/empty-state";import { AiPromptModal } from "../health/ai-prompt-modal";import { buildDeadCodeAiPrompt } from "../health/ai-prompt-builder";@@ -35,9 +38,32 @@ import { FindingsTable } from "./findings-table";import type { DeadCodeAdapter } from "./dead-code-adapter";import { toFriendlyMessage } from "../lib/errors";+/**+ * Server ceiling for one findings page (`limit` is clamped to 500 server-side).+ * Hitting it means the table shows a slice, and every count derived from that+ * slice has to say so rather than reading as the whole repository.+ */+const FINDINGS_LIMIT = 500;++/** 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>+ );+}+export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const [analyzing, setAnalyzing] = useState(false);const [promptIds, setPromptIds] = useState<string[] | null>(null);+ // 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.+ const [overrides, setOverrides] = useState<Record<string, DeadCodeFinding>>({});const {data: summary,@@ -52,34 +78,84 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {// Single findings fetch feeds the pile, the cluster views, AND the drill-down// table (which filters this slice client-side) — no second fetch.- const { data: findings, isLoading: loadingFindings } = useSWR<DeadCodeFinding[]>(+ const {+ data: findings,+ isLoading: loadingFindings,+ error: findingsError,+ mutate: mutateFindings,+ } = useSWR<DeadCodeFinding[]>(`dead-code-findings:${adapter.cacheKey}:all`,- () => adapter.listFindings({ limit: 500 }),+ () => adapter.listFindings({ limit: FINDINGS_LIMIT }),{ revalidateOnFocus: false },);- const findingsList = findings ?? [];- const safeFindings = findingsList.filter((f) => f.safe_to_delete);+ 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 safeFindings = useMemo(+ () => findingsList.filter((f) => f.safe_to_delete),+ [findingsList],+ );// "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- ? safeFindings.filter((f) => promptIds.includes(f.id))+ ? findingsList.filter((f) => promptIds.includes(f.id)): [];const handleAnalyze = async () => {+ // Guard here rather than on each button: the empty-state action cannot+ // disable itself, and two clicks would race a second job into a 409.+ if (analyzing) return;setAnalyzing(true);+ let jobId: string | undefined;try {- await adapter.analyze();- toast.success("Analysis started — results will appear shortly.");+ const started = await adapter.analyze();+ jobId = started?.job_id;+ toast.success(+ jobId && adapter.waitForAnalysis+ ? "Analysis started — this page refreshes when it finishes."+ : "Analysis started — results will appear shortly.",+ );} catch (err) {+ // 409 is the one failure with a specific remedy: wait for the other job.+ const status = (err as { status?: number } | null)?.status;toast.error(- err instanceof Error- ? `Couldn't start analysis: ${toFriendlyMessage(err)}`- : "Couldn't start analysis",+ status === 409+ ? "Another job is already running for this repository. Try again once it finishes."+ : `Couldn't start analysis: ${toFriendlyMessage(err)}`,+ );+ setAnalyzing(false);+ return;+ }++ // Separate from the launch above: the job is running now, so a failure+ // past this point is a failure to *watch* it, not to start it, and saying+ // "couldn't start analysis" about a live job would be wrong.+ if (!jobId || !adapter.waitForAnalysis) {+ setAnalyzing(false);+ return;+ }+ try {+ await adapter.waitForAnalysis(jobId);+ // The pass rewrites the findings, so local optimistic state is stale.+ setOverrides({});+ await Promise.all([mutateSummary(), mutateFindings()]);+ toast.success("Dead-code findings refreshed.");+ } catch (err) {+ toast.error(+ `Analysis is running, but this page stopped tracking it: ${toFriendlyMessage(err)}`,);} finally {setAnalyzing(false);@@ -91,16 +167,18 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {const finding = findingsList.find((f) => f.id === id);const previousStatus: DeadCodeStatus = finding?.status ?? "open";const updated = await adapter.patchFinding(id, patch);+ setOverrides((prev) => ({ ...prev, [id]: updated }));toast.success(`Finding ${patch.status.replace(/_/g, " ")}`, {action: {label: "Undo",onClick: async () => {try {- await adapter.patchFinding(id, { status: previousStatus });+ const reverted = await adapter.patchFinding(id, { status: previousStatus });+ // 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 }));} catch (err) {- toast.error(- `Couldn't undo: ${toFriendlyMessage(err)}`,- );+ toast.error(`Couldn't undo: ${toFriendlyMessage(err)}`);}},},@@ -119,6 +197,17 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {// continue; report partial below}}+ // Reflect only the rows the server confirmed — never a positional guess.+ if (succeededIds.length > 0) {+ const confirmed = new Set(succeededIds);+ setOverrides((prev) => {+ const next = { ...prev };+ for (const f of findingsList) {+ if (confirmed.has(f.id)) next[f.id] = { ...f, status: "resolved" as DeadCodeStatus };+ }+ return next;+ });+ }const succeeded = succeededIds.length;if (succeeded === ids.length) {toast.success(`Resolved ${succeeded} finding${succeeded === 1 ? "" : "s"}`);@@ -134,7 +223,7 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {<div className="space-y-6"><div className="flex items-center justify-end"><Button size="sm" variant="outline" onClick={handleAnalyze} disabled={analyzing}>- {analyzing ? "Starting…" : "Re-analyze"}+ {analyzing ? "Analyzing…" : "Re-analyze"}</Button></div>@@ -147,21 +236,24 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {) : summary ? (<SummaryBar summary={summary} />) : summaryError ? (- <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 summary.</span>- <Button size="sm" variant="outline" onClick={() => mutateSummary()}>- Retry- </Button>- </div>+ <RetryCard message="Couldn't load summary." 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 && (<SafeToDeletePilefindings={safeFindings}onPropose={handlePropose}onSelect={(f) => adapter.navigate(adapter.fileHref(f.file_path))}- {...(summary ? { reclaimableLines: summary.deletable_lines } : {})}+ // The summary total covers the whole repo; the file and finding+ // counts beside it come from a capped slice. Only pass it when the+ // two describe the same population.+ {...(summary && !truncated ? { reclaimableLines: summary.deletable_lines } : {})}/>)}@@ -190,20 +282,51 @@ export function DeadCodeView({ adapter }: { adapter: DeadCodeAdapter }) {</CollapsibleSection>)}- {/* Drill-down: the full interactive table, the single confidence control. */}+ {/* A failed fetch already showed its retry card above; showing a table or+ an empty state underneath it would restate the failure as "clean". */}+ {findingsError && !findings ? null : loadingFindings && !findings ? (+ <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: resolving+ the last row must not swap the table out for an empty state, because+ undoing it would then bring the row back into a section that+ remounted collapsed. */+ fetched.length === 0 ? (+ <EmptyState+ icon={<Trash2 className="h-6 w-6" />}+ title="No dead code found"+ description="Nothing in this repository is currently flagged as unreachable, unused or zombie. Re-run the analysis after a large refactor."+ action={{ label: analyzing ? "Analyzing…" : "Re-analyze", onClick: () => void handleAnalyze() }}+ />+ ) : (+ /* Drill-down: the full interactive table, the single confidence control.+ Rendered only once the findings settle so `defaultOpen` sees the real+ pile: mounted mid-load it would always read "no pile" and open. */<CollapsibleSectiontitle="All findings"- hint={`${findingsList.length} findings`}- defaultOpen={false}+ hint={+ loadingFindings+ ? "Loading…"+ : 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}><FindingsTablefindings={findingsList}- repoId={adapter.repoId}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}/></CollapsibleSection>+ )}<AiPromptModalopen={promptIds !== null}diff --git a/packages/ui/src/dead-code/finding-row.tsx b/packages/ui/src/dead-code/finding-row.tsxindex c106dd6e2..935df8cd2 100644--- a/packages/ui/src/dead-code/finding-row.tsx+++ b/packages/ui/src/dead-code/finding-row.tsx@@ -1,12 +1,16 @@"use client";-import { useState } from "react";-import { GitBranch, Code2 } from "lucide-react";+import { useState, type MouseEvent } from "react";+import { GitBranch } from "lucide-react";+import { toast } from "sonner";import { Button } from "../ui/button";import { Badge } from "../ui/badge";import { ConfirmDialog } from "../ui/confirm-dialog";import { RowActions } from "../shared/row-actions";+import { clickableRowProps, CLICKABLE_ROW_CLS } from "../shared/responsive-table";+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";@@ -28,48 +32,58 @@ const STATUS_LABELS: Record<},false_positive: {title: "Mark as false positive?",- description:- "This finding will be excluded from future analyses. You can undo from the toast.",+ // Deliberately does not promise exclusion from future analyses: a+ // re-analysis re-inserts every detected finding under a fresh id, so the+ // marking does not carry across passes. Upgrade path is a stable finding+ // identity server-side, then this copy can make the stronger promise.+ description: "This finding will be hidden from the list. You can undo from the toast.",confirmLabel: "Mark FP",destructive: true,},};-const STATUS_COLORS: Record<string, string> = {- open: "bg-[var(--color-error)]/10 text-[var(--color-error)] border-[var(--color-error)]/20",- acknowledged:- "bg-[var(--color-warning)]/10 text-[var(--color-warning)] border-[var(--color-warning)]/20",- resolved:- "bg-[var(--color-success)]/10 text-[var(--color-success)] border-[var(--color-success)]/20",- false_positive:- "bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] border-[var(--color-border-default)]",-};-export interface FindingRowProps {finding: DeadCodeFinding;- /** Repo base path used to build the Graph / Symbol action links. */- repoId: string;selected: boolean;onToggle: (id: string) => void;/** Injected mutation — returns the updated finding (host owns the API + toasts). */onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;- onUpdate: (updated: DeadCodeFinding) => void;+ /** Href for the file detail page; the path becomes a link and the row opens it. */+ fileHref?: ((path: string) => string) | undefined;+ /** Client-side navigation for a row click (falls back to the anchor alone). */+ onNavigate?: ((href: string) => void) | undefined;+ /** Href for the dependency graph focused on this file; omit to hide the action. */+ graphHref?: ((path: string) => string) | undefined;+ /** When set, the row offers an AI cleanup prompt scoped to this finding. */+ onGeneratePrompt?: ((id: string) => void) | undefined;}/*** Pure dead-code findings row: presentation + row-level status actions. The host* injects the patch mutation so this component carries no data/transport deps.*/-export function FindingRow({ finding, repoId, selected, onToggle, onPatch, onUpdate }: FindingRowProps) {+export function FindingRow({+ finding,+ selected,+ onToggle,+ onPatch,+ fileHref,+ onNavigate,+ graphHref,+ onGeneratePrompt,+}: FindingRowProps) {const [pending, setPending] = useState(false);const [confirmStatus, setConfirmStatus] = useState<string | null>(null);const applyPatch = async (status: string) => {setPending(true);try {- const updated = await onPatch(finding.id, { status: status as DeadCodeStatus });- onUpdate(updated);+ await onPatch(finding.id, { status: status as DeadCodeStatus });setConfirmStatus(null);+ } catch (err) {+ // Without this the rejection escapes to the console and the dialog sits+ // open with no explanation of why nothing happened.+ toast.error(`Couldn't update finding: ${toFriendlyMessage(err)}`);} finally {setPending(false);}@@ -78,14 +92,32 @@ export function FindingRow({ finding, repoId, selected, onToggle, onPatch, onUpdconst requestPatch = (status: string) => setConfirmStatus(status);const confirmConfig = confirmStatus ? STATUS_LABELS[confirmStatus] : null;+ const href = fileHref?.(finding.file_path);+ // Row click navigates only when the host can route; the anchor still carries+ // a real href so middle-click and "open in new tab" keep working.+ const openFile = href && onNavigate ? () => onNavigate(href) : undefined;++ // Hand a plain left click on the file name to the host router too, so it does+ // not fall through to a full page load while the row around it routes+ // client-side. Modified and non-primary clicks keep the browser's behavior.+ const onLinkClick = (e: MouseEvent<HTMLAnchorElement>) => {+ e.stopPropagation();+ if (!openFile) return;+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;+ e.preventDefault();+ openFile();+ };+return (<trclassName={cn("border-b border-[var(--color-table-divider)] transition-colors last:border-0",selected ? "bg-[var(--color-accent-muted)]" : "hover:bg-[var(--color-bg-elevated)]",+ openFile && CLICKABLE_ROW_CLS,)}+ {...(openFile ? clickableRowProps(openFile) : {})}>- <td className="px-4 py-2.5">+ <td className="px-4 py-2.5" onClick={(e) => e.stopPropagation()}><inputtype="checkbox"checked={selected}@@ -95,14 +127,35 @@ export function FindingRow({ finding, repoId, selected, onToggle, onPatch, onUpd/></td><td className="px-4 py-2.5 font-mono text-xs text-[var(--color-text-primary)] min-w-[200px] max-w-[480px]">- <span className="truncate block" title={finding.file_path}>- {finding.file_path}- </span>+ {href ? (+ <a+ href={href}+ onClick={onLinkClick}+ className="truncate block hover:text-[var(--color-accent-primary)] hover:underline"+ title={finding.file_path}+ >+ {finding.file_path}+ </a>+ ) : (+ <span className="truncate block" title={finding.file_path}>+ {finding.file_path}+ </span>+ )}{finding.symbol_name && (<span className="block truncate text-[var(--color-text-tertiary)]" title={finding.symbol_name}>{finding.symbol_name}</span>)}+ {/* The detector's justification. It was already being fed to the AI+ prompt builder, so the model saw the reasoning and the human did not. */}+ {finding.reason && (+ <span+ className="mt-0.5 block truncate font-sans text-[11px] text-[var(--color-text-tertiary)]"+ title={finding.reason}+ >+ {finding.reason}+ </span>+ )}</td><td className="px-4 py-2.5 text-xs text-[var(--color-text-secondary)] tabular-nums"><span@@ -140,30 +193,26 @@ export function FindingRow({ finding, repoId, selected, onToggle, onPatch, onUpd</Badge>)}</td>- <td className="px-4 py-2.5 hidden sm:table-cell">- <span- className={cn(- "inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium",- STATUS_COLORS[finding.status] ?? STATUS_COLORS.open,- )}- >- {finding.status.replace(/_/g, " ")}- </span>- </td>- <td className="px-4 py-2.5">+ <td className="px-4 py-2.5" onClick={(e) => e.stopPropagation()}><div className="flex items-center gap-1 flex-wrap justify-end">- <RowActions- actions={[- {- icon: GitBranch,- label: "Graph",- href: `/repos/${repoId}/architecture?view=graph&node=${encodeURIComponent(finding.file_path)}`,- },- ...(finding.symbol_name- ? [{ icon: Code2, label: "Symbol", href: `/repos/${repoId}/architecture?view=symbols` }]- : []),- ]}- />+ {onGeneratePrompt && (+ <AiPromptButton+ variant="icon"+ label={`AI cleanup prompt for ${finding.file_path}`}+ onClick={() => onGeneratePrompt(finding.id)}+ />+ )}+ {graphHref && (+ <RowActions+ actions={[+ {+ icon: GitBranch,+ label: "Graph",+ href: graphHref(finding.file_path),+ },+ ]}+ />+ )}{finding.status === "open" && (<div className="flex items-center gap-1 flex-wrap justify-end"><Buttondiff --git a/packages/ui/src/dead-code/findings-table.tsx b/packages/ui/src/dead-code/findings-table.tsxindex cbd3e7a2e..9cf3eaeb6 100644--- a/packages/ui/src/dead-code/findings-table.tsx+++ b/packages/ui/src/dead-code/findings-table.tsx@@ -1,6 +1,7 @@"use client";import { useMemo, useState } from "react";+import { toast } from "sonner";import { Tabs, TabsList, TabsTrigger, TabsContent } from "../ui/tabs";import { Button } from "../ui/button";import { Slider } from "../ui/slider";@@ -8,26 +9,52 @@ import { Switch } from "../ui/switch";import { TableSkeleton } from "../shared/loading-skeletons";import { ConfirmDialog } from "../ui/confirm-dialog";import { EmptyState } from "../shared/empty-state";+import { toFriendlyMessage } from "../lib/errors";+import { AiPromptButton } from "../health/ai-prompt-button";import { FindingRow } from "./finding-row";import type { DeadCodeFinding, DeadCodeStatus } from "@repowise-dev/types/dead-code";-type Kind = "unreachable_file" | "unused_export" | "zombie_package";+/**+ * Display names and tab order for the kinds we know about. Any other kind the+ * detector emits still gets a tab, labelled from its own identifier — a hard+ * allowlist here once hid every `unused_internal` finding, which the summary+ * card and the breakdown grid were counting all along.+ */+const KIND_LABELS: Record<string, string> = {+ unreachable_file: "Unreachable Files",+ unused_export: "Unused Exports",+ unused_internal: "Unused Internals",+ zombie_package: "Zombie Packages",+};-const TABS: Array<{ value: Kind; label: string }> = [- { value: "unreachable_file", label: "Unreachable Files" },- { value: "unused_export", label: "Unused Exports" },- { value: "zombie_package", label: "Zombie Packages" },-];+const KIND_ORDER = Object.keys(KIND_LABELS);++/** "unused_internal" -> "Unused Internals" for kinds we have no name for. */+function labelForKind(kind: string): string {+ const known = KIND_LABELS[kind];+ if (known) return known;+ return kind+ .split(/[_\-\s]+/)+ .filter(Boolean)+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))+ .join(" ");+}export interface FindingsTableProps {/** Full open-findings slice; the table filters by kind / confidence / safety client-side. */findings: DeadCodeFinding[];- /** Repo base path used to build row action links. */- repoId: string;/** Injected mutation — host owns the API call, optimistic toast + undo. */onPatch: (id: string, patch: { status: DeadCodeStatus }) => Promise<DeadCodeFinding>;/** Injected bulk resolve — host owns the toast/partial-failure messaging. Returns the ids that actually resolved. */onBulkResolve?: (ids: string[]) => Promise<string[]>;+ /** Href for a file detail page; makes the path a link and the row clickable. */+ fileHref?: ((path: string) => string) | undefined;+ /** Client-side navigation for a row click. */+ onNavigate?: ((href: string) => void) | undefined;+ /** Href for the dependency graph focused on a file; omit to hide the action. */+ graphHref?: ((path: string) => string) | undefined;+ /** Open an AI cleanup prompt for the given findings (one row, or the selection). */+ onGeneratePrompt?: ((ids: string[]) => void) | undefined;isLoading?: boolean;}@@ -37,43 +64,61 @@ export interface FindingsTableProps {* and per-row status actions. Pure presentation — the host injects the data* slice and the patch/bulk mutations, so this propagates via the package.*/-export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoading }: FindingsTableProps) {- const [activeTab, setActiveTab] = useState<Kind>("unreachable_file");+export function FindingsTable({+ findings,+ onPatch,+ onBulkResolve,+ fileHref,+ onNavigate,+ graphHref,+ onGeneratePrompt,+ isLoading,+}: FindingsTableProps) {+ const [activeTab, setActiveTab] = useState<string | null>(null);const [minConfidence, setMinConfidence] = useState(0.4);const [safeOnly, setSafeOnly] = useState(false);const [selected, setSelected] = useState<Set<string>>(new Set());- const [overrides, setOverrides] = useState<Record<string, DeadCodeFinding>>({});const [bulkPending, setBulkPending] = useState(false);const [bulkConfirmOpen, setBulkConfirmOpen] = useState(false);- // Apply local optimistic overrides over the host-supplied slice so a resolved- // row updates without a refetch.- const merged = useMemo(- () => findings.map((f) => overrides[f.id] ?? f),- [findings, overrides],- );+ // Tabs come from the unfiltered slice so the set stays put while the+ // confidence slider empties a bucket, instead of tabs appearing and+ // vanishing under the pointer.+ const tabs = useMemo(() => {+ const present = new Set(findings.map((f) => f.kind));+ const known = KIND_ORDER.filter((k) => present.has(k));+ const extra = [...present].filter((k) => !KIND_LABELS[k]).sort();+ return [...known, ...extra].map((value) => ({ value, label: labelForKind(value) }));+ }, [findings]);const byKind = useMemo(() => {- const buckets: Record<Kind, DeadCodeFinding[]> = {- unreachable_file: [],- unused_export: [],- zombie_package: [],- };- for (const f of merged) {- if (f.status !== "open") continue;+ const buckets: Record<string, DeadCodeFinding[]> = {};+ for (const t of tabs) buckets[t.value] = [];+ for (const f of findings) {if (f.confidence < minConfidence) continue;if (safeOnly && !f.safe_to_delete) continue;- const kind = f.kind as Kind;- if (kind in buckets) buckets[kind].push(f);+ buckets[f.kind]?.push(f);}return buckets;- }, [merged, minConfidence, safeOnly]);+ }, [findings, tabs, minConfidence, safeOnly]);- const current = byKind[activeTab];+ // The active tab can disappear when the slice changes (a refetch, a resolved+ // last row); fall back to the first tab rather than rendering nothing.+ const effectiveTab =+ activeTab && tabs.some((t) => t.value === activeTab) ? activeTab : (tabs[0]?.value ?? null);+ const current = useMemo(+ () => (effectiveTab ? (byKind[effectiveTab] ?? []) : []),+ [byKind, effectiveTab],+ );- const handleUpdate = (updated: DeadCodeFinding) => {- setOverrides((prev) => ({ ...prev, [updated.id]: updated }));- };+ // Selection is scoped to what is on screen. Without this, raising the+ // confidence slider after selecting rows would resolve findings the user can+ // no longer see.+ const visibleSelected = useMemo(() => {+ const visible = new Set(current.map((f) => f.id));+ return Array.from(selected).filter((id) => visible.has(id));+ }, [current, selected]);+ const selectedCount = visibleSelected.length;const toggleSelect = (id: string) => {setSelected((prev) => {@@ -84,31 +129,24 @@ export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoad});};+ const allVisibleSelected = current.length > 0 && selectedCount === current.length;+const toggleSelectAll = () => {- if (selected.size === current.length) {- setSelected(new Set());- } else {- setSelected(new Set(current.map((f) => f.id)));- }+ setSelected(allVisibleSelected ? new Set() : new Set(current.map((f) => f.id)));};const resolveSelected = async () => {if (!onBulkResolve) return;- const ids = Array.from(selected);setBulkPending(true);try {- const succeededIds = await onBulkResolve(ids);- // Reflect only the rows that actually resolved — never a positional guess.- const resolvedIds = new Set(succeededIds);- setOverrides((prev) => {- const next = { ...prev };- for (const f of merged) {- if (resolvedIds.has(f.id)) next[f.id] = { ...f, status: "resolved" as DeadCodeStatus };- }- return next;- });+ // Send the visible intersection, which is what the confirm dialog counted.+ await onBulkResolve(visibleSelected);setSelected(new Set());setBulkConfirmOpen(false);+ } catch (err) {+ // The prop contract does not promise a host that swallows its own+ // failures; without this the dialog wedges open on a rejection.+ toast.error(`Couldn't resolve findings: ${toFriendlyMessage(err)}`);} finally {setBulkPending(false);}@@ -138,7 +176,7 @@ export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoadCleanup-ready only</label>- {onBulkResolve && selected.size > 0 && (+ {onBulkResolve && selectedCount > 0 && (<Buttonsize="sm"variant="outline"@@ -146,47 +184,64 @@ export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoadonClick={() => setBulkConfirmOpen(true)}className="text-[var(--color-success)] border-[var(--color-success)]/30 hover:bg-[var(--color-success)]/10">- {bulkPending ? "Resolving…" : `Resolve ${selected.size} selected`}+ {bulkPending ? "Resolving…" : `Resolve ${selectedCount} selected`}</Button>)}++ {onGeneratePrompt && selectedCount > 0 && (+ <AiPromptButton+ label={`AI prompt for ${selectedCount} selected`}+ onClick={() => onGeneratePrompt(visibleSelected)}+ />+ )}</div><ConfirmDialogopen={bulkConfirmOpen}onOpenChange={setBulkConfirmOpen}- title={`Resolve ${selected.size} finding${selected.size === 1 ? "" : "s"}?`}+ title={`Resolve ${selectedCount} finding${selectedCount === 1 ? "" : "s"}?`}description="This will mark each selected finding as resolved."confirmLabel="Resolve all"loading={bulkPending}onConfirm={resolveSelected}/>+ {isLoading && findings.length === 0 ? (+ <TableSkeleton className="mt-2" />+ ) : tabs.length === 0 ? (+ <EmptyState+ title="No findings"+ description="No open dead-code findings for this repository."+ />+ ) : (<Tabs- value={activeTab}+ // Non-null in this branch: tabs is non-empty, so effectiveTab resolved.+ value={effectiveTab ?? ""}onValueChange={(v) => {- setActiveTab(v as Kind);+ setActiveTab(v);// Selection is per-kind; clearing on tab change keeps "Resolve N// selected" and the select-all checkbox scoped to the visible rows.setSelected(new Set());}}><TabsList>- {TABS.map((t) => (+ {tabs.map((t) => (<TabsTrigger key={t.value} value={t.value}>{t.label}- {byKind[t.value].length > 0 && (+ {(byKind[t.value]?.length ?? 0) > 0 && (<span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">- {byKind[t.value].length}+ {byKind[t.value]?.length}</span>)}</TabsTrigger>))}</TabsList>- {TABS.map((t) => (- <TabsContent key={t.value} value={t.value}>- {isLoading && current.length === 0 ? (- <TableSkeleton className="mt-2" />- ) : current.length === 0 ? (+ {/* One content panel for the active tab only. Rendering a panel per tab+ and filling each with the *active* tab's rows happened to work+ because Radix unmounts inactive content, which is a trap waiting on+ whoever adds forceMount. */}+ <TabsContent value={effectiveTab ?? ""}>+ {current.length === 0 ? (<EmptyStatetitle="No findings"description="No open findings for this category with current filters."@@ -200,7 +255,7 @@ export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoad<th scope="col" className="px-4 py-2.5 w-8"><inputtype="checkbox"- checked={selected.size === current.length && current.length > 0}+ checked={allVisibleSelected}onChange={toggleSelectAll}aria-label="Select all findings"className="rounded border-[var(--color-border-default)]"@@ -221,9 +276,8 @@ export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoad<th scope="col" className="px-4 py-2.5 w-20 hidden sm:table-cell"><span className="sr-only">Safety</span></th>- <th scope="col" className="px-4 py-2.5 w-24 hidden sm:table-cell">- <span className="sr-only">Status</span>- </th>+ {/* No status column: the fetch only ever asks for open+ findings, so the badge could only ever say "open". */}<th scope="col" className="px-4 py-2.5 w-36"><span className="sr-only">Actions</span></th>@@ -234,20 +288,24 @@ export function FindingsTable({ findings, repoId, onPatch, onBulkResolve, isLoad<FindingRowkey={f.id}finding={f}- repoId={repoId}selected={selected.has(f.id)}onToggle={toggleSelect}onPatch={onPatch}- onUpdate={handleUpdate}+ fileHref={fileHref}+ onNavigate={onNavigate}+ graphHref={graphHref}+ {...(onGeneratePrompt+ ? { onGeneratePrompt: (id: string) => onGeneratePrompt([id]) }+ : {})}/>))}</tbody></table></div>)}- </TabsContent>- ))}+ </TabsContent></Tabs>+ )}</div>);}diff --git a/packages/ui/src/dead-code/safe-to-delete-pile.tsx b/packages/ui/src/dead-code/safe-to-delete-pile.tsxindex bfd7489ad..b274ac7ac 100644--- a/packages/ui/src/dead-code/safe-to-delete-pile.tsx+++ b/packages/ui/src/dead-code/safe-to-delete-pile.tsx@@ -1,7 +1,8 @@"use client";import * as React from "react";-import { Trash2, ArrowRight, Sparkles } from "lucide-react";+import { Trash2, ArrowRight } from "lucide-react";+import { AiPromptButton } from "../health/ai-prompt-button";import { cn } from "../lib/cn";export interface SafeToDeletePileFinding {@@ -102,17 +103,14 @@ export function SafeToDeletePile({</p></div>{onPropose && findings.length > 0 && (- <button- type="button"+ // The canonical AI affordance, not a bespoke red button: every other+ // "hand this to an agent" action in the dashboard is this pill, and+ // red read as destructive on a button that only writes a prompt.+ <AiPromptButton+ label="Propose cleanup"onClick={() => onPropose(findings.map((f) => f.id))}- className={cn(- "inline-flex items-center gap-1.5 rounded-md border border-[var(--color-error)]/40 bg-[var(--color-error)]/10 px-3 py-1.5",- "text-xs font-medium text-[var(--color-error)] transition hover:bg-[var(--color-error)]/20",- )}- >- <Sparkles className="h-3.5 w-3.5" />- Propose cleanup- </button>+ className="shrink-0"+ />)}</div>diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsxindex 9b67cd423..0e28f660d 100644--- a/packages/web/src/components/risk/dead-code-tab.tsx+++ b/packages/web/src/components/risk/dead-code-tab.tsx@@ -17,6 +17,31 @@ import {analyzeDeadCode,patchDeadCodeFinding,} from "@/lib/api/dead-code";+import { getJob } from "@/lib/api/jobs";++const POLL_INTERVAL_MS = 3_000;+/** Give up watching after this long; the job may still be running server-side. */+const POLL_TIMEOUT_MS = 15 * 60_000;++/**+ * Resolve once the analysis job finishes. Polling rather than SSE: the view+ * only needs the terminal state to know when to refetch, and a plain promise+ * keeps the shared view free of any streaming dependency.+ */+async function waitForJob(jobId: string): Promise<void> {+ const deadline = Date.now() + POLL_TIMEOUT_MS;+ for (;;) {+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));+ const job = await getJob(jobId);+ if (job.status === "completed") return;+ if (job.status === "failed" || job.status === "cancelled") {+ throw new Error(job.error_message || `Analysis ${job.status}`);+ }+ if (Date.now() > deadline) {+ throw new Error("Analysis is taking longer than expected. Reload to see the results.");+ }+ }+}export function DeadCodeTab({ repoId }: { repoId: string }) {const router = useRouter();@@ -27,11 +52,12 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {repoId,getSummary: () => getDeadCodeSummary(repoId),listFindings: (opts) => listDeadCode(repoId, opts),- analyze: async () => {- await analyzeDeadCode(repoId);- },+ analyze: () => analyzeDeadCode(repoId),+ waitForAnalysis: waitForJob,patchFinding: (findingId, patch) => patchDeadCodeFinding(findingId, patch),fileHref: (path) => fileEntityPath(prefix, path),+ graphHref: (path) =>+ `${prefix}/architecture?view=graph&node=${encodeURIComponent(path)}`,navigate: (href) => router.push(href),};