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(savings): rebuild the costs page as an evidence-led scan surface (#2432)
Raghav Chamadiya55258b2135dd
diff --git a/packages/ui/__tests__/savings/savings-surface.test.tsx b/packages/ui/__tests__/savings/savings-surface.test.tsxnew file mode 100644index 000000000..37d59da58--- /dev/null+++ b/packages/ui/__tests__/savings/savings-surface.test.tsx@@ -0,0 +1,671 @@+import { describe, it, expect, beforeAll, vi } from "vitest";+import { fireEvent, render, screen, within } from "@testing-library/react";++import { SavingsLede } from "../../src/savings/savings-lede";+import { SavingsSourceTable } from "../../src/savings/savings-source-table";+import {+ OpportunityList,+ buildOpportunities,+} from "../../src/savings/opportunity-list";+import {+ SavingsTimeline,+ MIN_DAYS_FOR_CHART,+} from "../../src/savings/savings-timeline";+import { SpendSummary } from "../../src/savings/spend-summary";+import { UsageDetails } from "../../src/savings/usage-details";+import {+ SavingsMethodology,+ SavingsResetNotice,+} from "../../src/savings/savings-methodology";+import { surfaceLabel, type SavingsView, type SpendView } from "../../src/savings/types";++// jsdom has no scrollIntoView; `ViewTabs` keeps the active tab in view on mount.+beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn();+});++function makeSavings(overrides: Partial<SavingsView> = {}): SavingsView {+ return {+ available: true,+ window_days: null,+ as_of: "2026-09-19T00:00:00Z",+ first_event_at: "2026-09-01T00:00:00Z",+ last_event_at: "2026-09-19T00:00:00Z",+ unique_events: 120,+ successful_or_usable_partial_events: 118,+ saving_interactions: 90,+ mcp_queries_answered: 75,+ dead_ends: 2,+ saved_input_tokens: 1_000_000,+ measured_saved_input_tokens: 250_000,+ inferred_saved_input_tokens: 750_000,+ priced_saved_input_tokens: 400_000,+ unpriced_saved_input_tokens: 600_000,+ priced_input_savings_usd: 1.25,+ saved_output_tokens: null,+ priced_saved_output_tokens: 0,+ unpriced_saved_output_tokens: 0,+ priced_output_savings_usd: 0,+ per_operation: [+ { group: "get_answer", events: 40, saved_input_tokens: 600_000 },+ { group: "get_context", events: 20, saved_input_tokens: 400_000 },+ ],+ per_surface: [+ { group: "mcp", events: 50, saved_input_tokens: 750_000 },+ { group: "distill", events: 10, saved_input_tokens: 250_000 },+ ],+ per_agent: [+ {+ agent: "claude_code",+ agent_display_name: "Claude Code",+ events: 50,+ saved_input_tokens: 700_000,+ },+ {+ agent: "codex",+ agent_display_name: null,+ events: 10,+ saved_input_tokens: 300_000,+ },+ ],+ per_model: [+ { group: "claude-opus-5", events: 30, saved_input_tokens: 400_000 },+ { group: null, events: 30, saved_input_tokens: 600_000 },+ ],+ per_day: [+ { group: "2026-09-16", events: 10, saved_input_tokens: 100_000 },+ { group: "2026-09-17", events: 10, saved_input_tokens: 300_000 },+ { group: "2026-09-18", events: 10, saved_input_tokens: 200_000 },+ { group: "2026-09-19", events: 10, saved_input_tokens: 400_000 },+ ],+ opportunity_count: 0,+ opportunity_tokens_excluded: 0,+ per_opportunity_kind: [],+ missed_events: 213,+ missed_tokens_est: 96_000,+ missed_window_days: 7,+ reread_events: 5,+ reread_tokens_est: 635,+ ...overrides,+ };+}++describe("SavingsLede", () => {+ it("calls the total estimated while any of it is inferred", () => {+ render(<SavingsLede data={makeSavings()} />);+ expect(screen.getByText("Estimated agent savings")).toBeInTheDocument();+ });++ it("drops 'estimated' only when every token is measured", () => {+ render(+ <SavingsLede+ data={makeSavings({+ measured_saved_input_tokens: 1_000_000,+ inferred_saved_input_tokens: 0,+ })}+ />,+ );+ expect(screen.getByText("Agent savings")).toBeInTheDocument();+ expect(screen.queryByText("Estimated agent savings")).not.toBeInTheDocument();+ });++ it("keeps measured and inferred as separate figures", () => {+ render(<SavingsLede data={makeSavings()} />);+ const measured = screen.getByText("Measured").closest("div");+ const inferred = screen.getByText("Inferred").closest("div");++ expect(within(measured as HTMLElement).getByText("250K")).toBeInTheDocument();+ expect(within(inferred as HTMLElement).getByText("750K")).toBeInTheDocument();+ });++ it("says the dollar figure covers only the priced part", () => {+ render(<SavingsLede data={makeSavings()} />);+ // 600K of 1.0M carries no rate, so the value must not read as covering+ // the whole total.+ expect(screen.getByText(/600K of those tokens carry no rate/)).toBeInTheDocument();+ expect(screen.getByText("on 400K of 1.0M")).toBeInTheDocument();+ });++ it("claims full coverage only when nothing is unpriced", () => {+ render(+ <SavingsLede+ data={makeSavings({+ priced_saved_input_tokens: 1_000_000,+ unpriced_saved_input_tokens: 0,+ })}+ />,+ );+ // "values the whole total" overclaimed: the figure prices input tokens,+ // and output savings are reported separately.+ expect(screen.getByText(/values all of these input tokens/)).toBeInTheDocument();+ expect(screen.queryByText(/the whole total/)).not.toBeInTheDocument();+ expect(screen.getByText("on all savings")).toBeInTheDocument();+ });++ it("characterises nothing when nothing was recorded", () => {+ render(+ <SavingsLede+ data={makeSavings({+ saved_input_tokens: 0,+ measured_saved_input_tokens: 0,+ inferred_saved_input_tokens: 0,+ priced_saved_input_tokens: 0,+ unpriced_saved_input_tokens: 0,+ priced_input_savings_usd: 0,+ })}+ />,+ );+ // Saying "every part of the total is measured" about an empty set is a+ // claim with no subject.+ expect(screen.getByText(/Nothing has been recorded in this window yet/)).toBeInTheDocument();+ expect(screen.queryByText(/measured before and after/)).not.toBeInTheDocument();+ expect(screen.queryByText(/carry no rate/)).not.toBeInTheDocument();+ });++ it("keeps the coverage date and methodology link beside the total", () => {+ render(<SavingsLede data={makeSavings()} methodologyHref="/method" />);+ // This is the line that survives the reset notice being dismissed.+ expect(screen.getByText(/Measured since Sep 1, 2026\./)).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Method and limits" })).toHaveAttribute(+ "href",+ "/method",+ );+ });++ it("states the window instead of a start date when one is set", () => {+ render(<SavingsLede data={makeSavings({ window_days: 30 })} />);+ expect(screen.getByText(/Covering the last 30 days\./)).toBeInTheDocument();+ expect(screen.queryByText(/Measured since/)).not.toBeInTheDocument();+ });++ it("omits the date rather than printing one it cannot parse", () => {+ render(<SavingsLede data={makeSavings({ first_event_at: "not a date" })} />);+ expect(screen.queryByText(/Measured since/)).not.toBeInTheDocument();+ });++ it("counts interactions, not tokens, under the interaction figure", () => {+ render(<SavingsLede data={makeSavings()} />);+ // "90 saved tokens" beside a token total reads as ninety tokens.+ expect(screen.getByText("90 produced a saving")).toBeInTheDocument();+ });++ it("shows no share percentages when the total is zero", () => {+ render(+ <SavingsLede+ data={makeSavings({+ saved_input_tokens: 0,+ measured_saved_input_tokens: 0,+ inferred_saved_input_tokens: 0,+ })}+ />,+ );+ // "0% of total" would be a claim about a distribution that does not exist.+ expect(screen.queryByText(/% of total/)).not.toBeInTheDocument();+ });+});++describe("SavingsSourceTable", () => {+ const rows = [+ { label: "MCP", events: 50, savedInputTokens: 750_000 },+ { label: "Distill", events: 10, savedInputTokens: 250_000 },+ ];++ it("renders each source with its own share of the page total", () => {+ render(+ <SavingsSourceTable+ rows={rows}+ total={1_000_000}+ nameHeader="Surface"+ caption="Savings by surface"+ />,+ );+ expect(screen.getByText("75%")).toBeInTheDocument();+ expect(screen.getByText("25%")).toBeInTheDocument();+ });++ it("normalises to the passed total, not to the largest row", () => {+ // The caller passes the report total so two tables on one page stay+ // comparable. Normalising per table would render this row as 100%.+ render(+ <SavingsSourceTable+ rows={[{ label: "MCP", events: 1, savedInputTokens: 250_000 }]}+ total={1_000_000}+ nameHeader="Surface"+ caption="Savings by surface"+ />,+ );+ expect(screen.getByText("25%")).toBeInTheDocument();+ expect(screen.queryByText("100%")).not.toBeInTheDocument();+ });++ it("does not round a contributing row down to nothing", () => {+ const { container } = render(+ <SavingsSourceTable+ rows={[{ label: "Hooks", events: 1, savedInputTokens: 100 }]}+ total={1_000_000}+ nameHeader="Surface"+ caption="Savings by surface"+ />,+ );+ // 0.01% is real but not "0%": a source that contributed must not read as+ // one that did not.+ expect(screen.getByText("<1%")).toBeInTheDocument();++ // And the bar itself must be visible, which is separate logic from the+ // text. Without the floor this renders at 0.01% wide, i.e. nothing.+ const bar = container.querySelector<HTMLElement>(+ "span[style*='width'] , span[class*='rounded-full'][style]",+ );+ expect(bar?.style.width).toBe("1.5%");+ });++ it("clamps a row that exceeds the total instead of overflowing its track", () => {+ const { container } = render(+ <SavingsSourceTable+ rows={[{ label: "MCP", events: 1, savedInputTokens: 1_400_000 }]}+ total={1_000_000}+ nameHeader="Surface"+ caption="Savings by surface"+ />,+ );+ // Breakdowns can count differently from the total; an unclamped bar then+ // runs past its track while the label claims 140%.+ expect(screen.getByText("100%")).toBeInTheDocument();+ expect(screen.queryByText("140%")).not.toBeInTheDocument();+ const bar = container.querySelector<HTMLElement>("span[style*='width']");+ expect(bar?.style.width).toBe("100%");+ });++ it("does not present a negative row as a small positive one", () => {+ render(+ <SavingsSourceTable+ rows={[{ label: "MCP", events: 1, savedInputTokens: -500 }]}+ total={1_000_000}+ nameHeader="Surface"+ caption="Savings by surface"+ />,+ );+ // A negative fell through to the "<1%" branch and read as a contribution.+ expect(screen.getByText("0%")).toBeInTheDocument();+ expect(screen.queryByText("<1%")).not.toBeInTheDocument();+ });++ it("keeps the share readable when there is no denominator", () => {+ render(+ <SavingsSourceTable+ rows={[{ label: "MCP", events: 1, savedInputTokens: 0 }]}+ total={0}+ nameHeader="Surface"+ caption="Savings by surface"+ />,+ );+ // A bare dash left a screen reader with an empty cell.+ expect(screen.getByText("No share")).toBeInTheDocument();+ });++ it("renders a caption for a reader who cannot see the section heading", () => {+ render(+ <SavingsSourceTable+ rows={rows}+ total={1_000_000}+ nameHeader="Surface"+ caption="Savings by the surface that produced them"+ />,+ );+ expect(+ screen.getByRole("table", { name: "Savings by the surface that produced them" }),+ ).toBeInTheDocument();+ });++ it("renders the empty node instead of a headed table with no rows", () => {+ render(+ <SavingsSourceTable+ rows={[]}+ total={0}+ nameHeader="Surface"+ caption="Savings by surface"+ empty={<p>No savings carry a surface.</p>}+ />,+ );+ expect(screen.queryByRole("table")).not.toBeInTheDocument();+ expect(screen.getByText("No savings carry a surface.")).toBeInTheDocument();+ });+});++describe("OpportunityList", () => {+ it("renders no buttons: every row is guidance", () => {+ render(+ <OpportunityList+ items={buildOpportunities(makeSavings(), { distillDocsHref: "/distill" })}+ />,+ );+ // The previous surface styled a docs link as an in-product control. A row+ // here may link; it may never look like something that acts.+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ });++ it("renders a guidance link as an ordinary link", () => {+ render(+ <OpportunityList+ items={buildOpportunities(makeSavings(), { distillDocsHref: "/distill" })}+ />,+ );+ expect(+ screen.getByRole("link", { name: "See the distillation setup guide" }),+ ).toHaveAttribute("href", "/distill");+ });++ it("omits the link entirely when no docs href is supplied", () => {+ render(<OpportunityList items={buildOpportunities(makeSavings())} />);+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ });++ it("labels potential as an opportunity, never as a saving", () => {+ render(<OpportunityList items={buildOpportunities(makeSavings())} />);+ expect(screen.getByText("Observed opportunity: ~96K tokens")).toBeInTheDocument();+ // Every row makes the same kind of claim and now says so the same way.+ // "Potentially avoid" promised a future saving from a past observation.+ expect(screen.getByText("Observed opportunity: ~635 tokens")).toBeInTheDocument();+ expect(screen.queryByText(/Potentially avoid/)).not.toBeInTheDocument();+ });++ it("does not report a sub-day window as zero days", () => {+ render(+ <OpportunityList+ items={buildOpportunities(makeSavings({ missed_window_days: 0.4 }))}+ />,+ );+ // missed_window_days is a float; rounding printed "over the last 0 days".+ expect(screen.getByText(/in the last day/)).toBeInTheDocument();+ expect(screen.queryByText(/last 0 days/)).not.toBeInTheDocument();+ });++ it("gives two opportunity kinds that render alike distinct keys", () => {+ // Keying a row on its rendered title collided here: an empty kind renders+ // an empty title, and React drops the duplicate.+ const items = buildOpportunities(+ makeSavings({+ missed_events: 0,+ reread_events: 0,+ per_opportunity_kind: [+ { kind: "", observations: 2, estimated_potential_input_tokens: 10 },+ { kind: "_", observations: 3, estimated_potential_input_tokens: 20 },+ ],+ }),+ );+ expect(new Set(items.map((i) => i.id)).size).toBe(2);+ render(<OpportunityList items={items} />);+ expect(screen.getAllByText(/Observed \d+ times/)).toHaveLength(2);+ });++ it("describes re-reads as observed, without claiming what would have replaced them", () => {+ render(<OpportunityList items={buildOpportunities(makeSavings())} />);+ expect(screen.getByText(/were observed\./)).toBeInTheDocument();+ expect(screen.queryByText(/would have replaced/)).not.toBeInTheDocument();+ });++ it("keeps a ledger opportunity kind grammatical whatever it is called", () => {+ render(+ <OpportunityList+ items={buildOpportunities(+ makeSavings({+ missed_events: 0,+ reread_events: 0,+ per_opportunity_kind: [+ {+ kind: "hook_replacement_declined",+ observations: 12,+ estimated_potential_input_tokens: 41_000,+ },+ ],+ }),+ )}+ />,+ );+ // Kinds are an open vocabulary off the ledger, so counting in front of+ // the slug produces "12 hook replacement declined".+ expect(screen.getByText("Hook replacement declined")).toBeInTheDocument();+ expect(screen.getByText(/Observed 12 times/)).toBeInTheDocument();+ expect(screen.queryByText("12 hook replacement declined")).not.toBeInTheDocument();+ });++ it("renders nothing when nothing was observed", () => {+ const { container } = render(+ <OpportunityList+ items={buildOpportunities(+ makeSavings({ missed_events: 0, reread_events: 0, per_opportunity_kind: [] }),+ )}+ />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it("agrees with the singular case", () => {+ render(+ <OpportunityList+ items={buildOpportunities(+ makeSavings({ missed_events: 1, reread_events: 1, missed_window_days: 1 }),+ )}+ />,+ );+ expect(screen.getByText("1 command bypassed distillation")).toBeInTheDocument();+ expect(screen.getByText("1 unchanged-file re-read")).toBeInTheDocument();+ expect(screen.getByText(/last 1 day\b/)).toBeInTheDocument();+ expect(screen.getByText(/One full re-read .* was observed\./)).toBeInTheDocument();+ });+});++describe("SavingsTimeline", () => {+ it("draws the chart and summarises it in text", () => {+ render(<SavingsTimeline days={makeSavings().per_day} />);+ // Assert the chart is actually there: without this the whole recharts+ // block could be deleted and the summary assertions would still pass.+ const chart = screen.getByRole("img");+ expect(chart).toHaveAccessibleName(/Savings per day, 4 days/);+ expect(chart).toHaveAccessibleName(/Largest 400K tokens on 2026-09-19/);++ expect(+ screen.getByText(/4 days recorded a saving between 2026-09-16 and 2026-09-19\./),+ ).toBeInTheDocument();+ expect(screen.getByText(/largest was 400K tokens on 2026-09-19/)).toBeInTheDocument();+ });++ it("declines to draw a chart from too few points", () => {+ const sparse = makeSavings().per_day.slice(0, MIN_DAYS_FOR_CHART - 1);+ render(<SavingsTimeline days={sparse} />);+ // Three bars in a wide empty box is decoration, not a distribution.+ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ expect(screen.getByText(/3 days recorded a saving/)).toBeInTheDocument();+ });++ it("ignores days that recorded nothing", () => {+ render(+ <SavingsTimeline+ days={[+ { group: "2026-09-16", events: 0, saved_input_tokens: 0 },+ { group: "2026-09-17", events: 10, saved_input_tokens: 100 },+ ]}+ />,+ );+ expect(screen.getByText(/1 day recorded a saving/)).toBeInTheDocument();+ });++ it("does not render a single day as a range between itself", () => {+ render(+ <SavingsTimeline+ days={[{ group: "2026-09-18", events: 4, saved_input_tokens: 3169 }]}+ />,+ );+ expect(screen.getByText("1 day recorded a saving on 2026-09-18.")).toBeInTheDocument();+ expect(screen.queryByText(/between 2026-09-18 and 2026-09-18/)).not.toBeInTheDocument();+ // "The largest was" needs something to be largest than.+ expect(screen.queryByText(/largest/)).not.toBeInTheDocument();+ });++ it("says so when no day recorded a saving", () => {+ render(<SavingsTimeline days={[]} />);+ expect(screen.getByText("No day in this window recorded a saving.")).toBeInTheDocument();+ });+});++describe("SpendSummary", () => {+ const spend: SpendView = {+ total_cost_usd: 4.2,+ total_calls: 310,+ total_input_tokens: 1_200_000,+ total_output_tokens: 90_000,+ since: "2026-08-01T00:00:00Z",+ };++ it("names the whole of the model work, not just indexing", () => {+ render(<SpendSummary spend={spend} />);+ // "Indexing cost" named a subset and counted the whole.+ expect(+ screen.getByText(/indexing, page generation and other model-backed operations/),+ ).toBeInTheDocument();+ });++ it("says spend is never subtracted from savings", () => {+ render(<SpendSummary spend={spend} />);+ expect(screen.getByText(/never subtracted from them/)).toBeInTheDocument();+ });++ it("reports nothing spent rather than a row of zeroes", () => {+ render(+ <SpendSummary+ spend={{ ...spend, total_calls: 0, total_cost_usd: 0 }}+ />,+ );+ expect(screen.getByText(/nothing has been spent/)).toBeInTheDocument();+ });+});++describe("UsageDetails", () => {+ it("offers one tab per dimension of the same dataset", () => {+ render(<UsageDetails data={makeSavings()} />);+ for (const name of [/By day/, /Operations/, /Models/, /Agents/]) {+ expect(screen.getByRole("tab", { name })).toBeInTheDocument();+ }+ });++ it("switches dimension without changing scope", () => {+ render(<UsageDetails data={makeSavings()} />);+ fireEvent.click(screen.getByRole("tab", { name: /Operations/ }));+ expect(screen.getByRole("table", { name: /by the operation/ })).toBeInTheDocument();+ });++ it("names the unpriced model bucket instead of dropping it", () => {+ render(<UsageDetails data={makeSavings()} />);+ fireEvent.click(screen.getByRole("tab", { name: /Models/ }));+ // The null-model bucket is how much saving carries no rate evidence.+ expect(screen.getByText("No rate recorded")).toBeInTheDocument();+ });++ it("falls back to the agent slug when the registry resolved no display name", () => {+ render(<UsageDetails data={makeSavings()} />);+ fireEvent.click(screen.getByRole("tab", { name: /Agents/ }));+ expect(screen.getByText("Claude Code")).toBeInTheDocument();+ expect(screen.getByText("codex")).toBeInTheDocument();+ });++ it("carries no count on a dimension with no rows", () => {+ render(<UsageDetails data={makeSavings({ per_model: [] })} />);+ const tab = screen.getByRole("tab", { name: /Models/ });+ // A zero badge reads as a reported count rather than an empty dimension.+ expect(tab).not.toHaveTextContent("0");+ });++ it("explains an empty dimension instead of rendering an empty table", () => {+ render(<UsageDetails data={makeSavings({ per_model: [] })} />);+ fireEvent.click(screen.getByRole("tab", { name: /Models/ }));+ expect(screen.getByText("No savings in this window carry a model.")).toBeInTheDocument();+ expect(screen.queryByRole("table")).not.toBeInTheDocument();+ });++ it("still switches when the host only observes the selection", () => {+ const onValueChange = vi.fn();+ // A host passing onValueChange without value is an ordinary "tell me+ // when it changes" usage. Treating the callback as the controlled signal+ // froze the tabs: every click notified and nothing moved.+ render(<UsageDetails data={makeSavings()} onValueChange={onValueChange} />);++ fireEvent.click(screen.getByRole("tab", { name: /Models/ }));++ expect(onValueChange).toHaveBeenCalledWith("model");+ expect(screen.getByText("No rate recorded")).toBeInTheDocument();+ });++ it("can be driven by the host", () => {+ const onValueChange = vi.fn();+ render(+ <UsageDetails data={makeSavings()} value="model" onValueChange={onValueChange} />,+ );+ expect(screen.getByText("No rate recorded")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("tab", { name: /Agents/ }));+ expect(onValueChange).toHaveBeenCalledWith("agent");+ // Controlled: the selection does not move until the host moves it.+ expect(screen.getByText("No rate recorded")).toBeInTheDocument();+ });+});++describe("SavingsResetNotice", () => {+ it("says what restarted and what was kept", () => {+ render(<SavingsResetNotice onDismiss={vi.fn()} />);+ expect(screen.getByText("Savings accounting has been upgraded.")).toBeInTheDocument();+ expect(screen.getByText(/were not deleted/)).toBeInTheDocument();+ });++ it("never calls itself a cost reset", () => {+ render(<SavingsResetNotice onDismiss={vi.fn()} />);+ // No money moved and no spend record changed.+ expect(screen.getByRole("status").textContent ?? "").not.toMatch(/cost reset/i);+ });++ it("offers the methodology as an ordinary link", () => {+ render(<SavingsResetNotice onDismiss={vi.fn()} methodologyHref="/method" />);+ expect(screen.getByRole("link", { name: "See what changed" })).toHaveAttribute(+ "href",+ "/method",+ );+ });++ it("hands dismissal to the host", () => {+ const onDismiss = vi.fn();+ render(<SavingsResetNotice onDismiss={onDismiss} />);+ fireEvent.click(screen.getByRole("button", { name: /dismiss/i }));+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });+});++describe("SavingsMethodology", () => {+ it("keeps the working available without leading with it", () => {+ render(<SavingsMethodology />);+ const toggle = screen.getByRole("button", { name: /method and limits/i });+ expect(toggle).toBeInTheDocument();++ fireEvent.click(toggle);+ expect(screen.getByText(/deliberately undersell/)).toBeInTheDocument();+ expect(screen.getByText(/never added to achieved savings/)).toBeInTheDocument();+ expect(screen.getByText(/stays here/)).toBeInTheDocument();+ });+});++describe("surfaceLabel", () => {+ it("names the surfaces the accounting contract defines", () => {+ expect(surfaceLabel("distill")).toBe("Distill");+ expect(surfaceLabel("hook")).toBe("Hooks");+ expect(surfaceLabel("mcp")).toBe("MCP");+ expect(surfaceLabel("vscode_lm")).toBe("VS Code");+ });++ it("shows an unrecognised surface as itself rather than hiding it", () => {+ // A future surface is a real one this build has no word for; collapsing it+ // to "Unknown" would lose which it was.+ expect(surfaceLabel("jetbrains_lm")).toBe("jetbrains_lm");+ });++ it("names an absent surface Unknown", () => {+ expect(surfaceLabel(null)).toBe("Unknown");+ });+});diff --git a/packages/ui/__tests__/shared/dismissible-notice.test.tsx b/packages/ui/__tests__/shared/dismissible-notice.test.tsxnew file mode 100644index 000000000..962483dbd--- /dev/null+++ b/packages/ui/__tests__/shared/dismissible-notice.test.tsx@@ -0,0 +1,97 @@+import { describe, it, expect, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";++import { DismissibleNotice } from "../../src/shared/dismissible-notice";++describe("DismissibleNotice", () => {+ it("announces as status, not as an alert", () => {+ render(<DismissibleNotice>Accounting changed.</DismissibleNotice>);+ // role="alert" is assertive and interrupts a screen reader mid-sentence.+ // A methodology note is news about numbers already on the page.+ expect(screen.getByRole("status")).toHaveTextContent("Accounting changed.");+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ it("renders no dismiss control when no handler is given", () => {+ render(<DismissibleNotice>Permanent note.</DismissibleNotice>);+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ });++ it("calls onDismiss and leaves the notice rendered", () => {+ const onDismiss = vi.fn();+ render(<DismissibleNotice onDismiss={onDismiss}>Dismiss me.</DismissibleNotice>);++ fireEvent.click(screen.getByRole("button", { name: /dismiss/i }));++ expect(onDismiss).toHaveBeenCalledTimes(1);+ // The component is controlled: it does not hide itself, because whether+ // this notice comes back is a question only the host can answer. A version+ // that self-hid would pass a naive test and still reappear on reload.+ expect(screen.getByRole("status")).toBeInTheDocument();+ });++ it("activates the dismiss control from the keyboard", () => {+ const onDismiss = vi.fn();+ render(<DismissibleNotice onDismiss={onDismiss}>Keyboard.</DismissibleNotice>);+ const button = screen.getByRole("button", { name: /dismiss/i });++ // A real button, not a click-handling div: focusable, and Enter and Space+ // both fire it. Asserting the Tailwind class name instead would have+ // restated the implementation and passed against any styling at all.+ button.focus();+ expect(button).toHaveFocus();+ expect(button).toHaveAttribute("type", "button");++ fireEvent.click(button);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it("puts the action ahead of the dismiss control in the tab order", () => {+ render(+ <DismissibleNotice onDismiss={vi.fn()} action={<a href="/method">See what changed</a>}>+ With an action.+ </DismissibleNotice>,+ );++ const link = screen.getByRole("link", { name: "See what changed" });+ const button = screen.getByRole("button", { name: /dismiss/i });++ // Neither carries a tabindex, so document order is tab order: a reader+ // should reach the explanation before the control that removes it.+ expect(link.compareDocumentPosition(button)).toBe(+ Node.DOCUMENT_POSITION_FOLLOWING,+ );+ });++ it("renders no action element when none is passed", () => {+ render(<DismissibleNotice onDismiss={vi.fn()}>Bare.</DismissibleNotice>);+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ });++ it("names the dismiss control for the notice it closes", () => {+ render(+ <DismissibleNotice onDismiss={vi.fn()} dismissLabel="Dismiss the savings notice">+ Named.+ </DismissibleNotice>,+ );+ expect(+ screen.getByRole("button", { name: "Dismiss the savings notice" }),+ ).toBeInTheDocument();+ });++ it("touches no browser storage", () => {+ const getItem = vi.spyOn(Storage.prototype, "getItem");+ const setItem = vi.spyOn(Storage.prototype, "setItem");++ render(<DismissibleNotice onDismiss={vi.fn()}>No storage.</DismissibleNotice>);+ fireEvent.click(screen.getByRole("button", { name: /dismiss/i }));++ // Persistence belongs to the host, keyed by repository and accounting+ // version. A primitive that remembered dismissals itself could only ever+ // key them one way.+ expect(getItem).not.toHaveBeenCalled();+ expect(setItem).not.toHaveBeenCalled();+ getItem.mockRestore();+ setItem.mockRestore();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 9f5fabe21..9b968f453 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -91,6 +91,9 @@"./costs": "./src/costs/index.ts","./costs/chart-height": "./src/costs/chart-height.ts","./costs/*": "./src/costs/*.tsx",+ "./savings": "./src/savings/index.ts",+ "./savings/types": "./src/savings/types.ts",+ "./savings/*": "./src/savings/*.tsx","./security": "./src/security/index.ts","./security/*": "./src/security/*.tsx","./onboarding": "./src/onboarding/index.ts",diff --git a/packages/ui/src/savings/index.ts b/packages/ui/src/savings/index.tsnew file mode 100644index 000000000..ce15f02e2--- /dev/null+++ b/packages/ui/src/savings/index.ts@@ -0,0 +1,53 @@+/**+ * The shared savings surface.+ *+ * Data and callbacks only: nothing here fetches, routes, reads storage or+ * branches on which host is rendering it. A host maps its response onto+ * `SavingsView`, supplies links through `LinkComponent`, and owns whether the+ * reset notice is showing.+ *+ * Nothing here computes a saving. The server's report service is the only+ * thing that aggregates or prices; these components read fields.+ */+export {+ surfaceLabel,+ agentLabel,+ modelLabel,+ type SavingsView,+ type SpendView,+ type SavingsBreakdownRow,+ type SavingsAgentRow,+ type SavingsOpportunityRow,+} from "./types";+export { SavingsLede, type SavingsLedeProps } from "./savings-lede";+export {+ SavingsSourceTable,+ type SavingsSourceTableProps,+ type SourceRow,+} from "./savings-source-table";+export {+ OpportunityList,+ buildOpportunities,+ type OpportunityListProps,+ type OpportunityItem,+ type BuildOpportunitiesOptions,+} from "./opportunity-list";+export {+ SavingsTimeline,+ MIN_DAYS_FOR_CHART,+ TIMELINE_HEIGHT,+ type SavingsTimelineProps,+} from "./savings-timeline";+export { SpendSummary, type SpendSummaryProps } from "./spend-summary";+export {+ UsageDetails,+ type UsageDetailsProps,+ type UsageDetailTab,+} from "./usage-details";+export {+ SavingsMethodology,+ SavingsResetNotice,+ ACCOUNTING_METHOD_VERSION,+ type SavingsMethodologyProps,+ type SavingsResetNoticeProps,+} from "./savings-methodology";diff --git a/packages/ui/src/savings/opportunity-list.tsx b/packages/ui/src/savings/opportunity-list.tsxnew file mode 100644index 000000000..6df2b1201--- /dev/null+++ b/packages/ui/src/savings/opportunity-list.tsx@@ -0,0 +1,199 @@+"use client";++import * as React from "react";++import { formatTokens } from "../lib/format";+import type { SavingsView } from "./types";++export interface OpportunityItem {+ /**+ * Stable list key. Separate from `title` because a ledger kind is an open+ * vocabulary: two kinds can render the same phrase, and an empty kind+ * renders an empty one, so keying on the rendered text collides.+ */+ id: string;+ /** What was observed, as a heading-weight phrase. */+ title: string;+ /** The evidence, in a sentence. */+ detail: React.ReactNode;+ /** The potential, pre-formatted. Omit where there is no estimate. */+ potential?: string | undefined;+ /** An ordinary documentation link. Deliberately not an action: see below. */+ href?: string | undefined;+ linkLabel?: string | undefined;+}++export interface OpportunityListProps {+ items: OpportunityItem[];+ LinkComponent?: React.ElementType | undefined;+}++/**+ * Behaviour that could have been optimised and was not.+ *+ * Never part of the savings total, and the section says so rather than+ * relying on the reader to infer it from placement.+ *+ * **Every row here is guidance, and is built so it cannot look like anything+ * else.** The previous version rendered "Enable auto-capture" in a bordered,+ * amber, icon-led block that read as an in-product control and only opened a+ * documentation page when pressed. Decoration teaches a reader that an element+ * responds, so a dead path styled as a control is a lie told in CSS. These+ * rows are plain text with, at most, an ordinary link.+ *+ * If one of these ever earns a real action -- something that performs a local+ * setup rather than describing one -- it gets a real button then, and the+ * button goes here rather than this styling going anywhere else.+ */+export function OpportunityList({ items, LinkComponent }: OpportunityListProps) {+ if (items.length === 0) return null;+ const A = LinkComponent ?? "a";++ return (+ <ul className="flex flex-col">+ {items.map((item) => (+ <li+ key={item.id}+ className="flex flex-col gap-1 border-b border-[var(--color-border-default)] py-3.5 last:border-b-0"+ >+ <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">+ <span className="min-w-0 text-sm font-medium text-[var(--color-text-primary)]">+ {item.title}+ </span>+ {item.potential && (+ <span className="shrink-0 text-sm tabular-nums text-[var(--color-text-secondary)]">+ {item.potential}+ </span>+ )}+ </div>+ <p className="max-w-[72ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {item.detail}+ {item.href && (+ <>+ {" "}+ <A+ href={item.href}+ {...(isExternal(item.href)+ ? { target: "_blank", rel: "noreferrer" }+ : {})}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ {item.linkLabel ?? "Read more"}+ </A>+ </>+ )}+ </p>+ </li>+ ))}+ </ul>+ );+}++function isExternal(href: string): boolean {+ return /^https?:\/\//.test(href);+}++export interface BuildOpportunitiesOptions {+ /** Where the distillation setup guide lives. */+ distillDocsHref?: string | undefined;+}++/**+ * The transcript-mined opportunities, as rows.+ *+ * A function rather than prop-drilling five fields through the component, and+ * exported so the copy is asserted directly by a test instead of through a+ * render. The wording is cautious on purpose: these are observations of what+ * was not saved, and the page must not claim a Repowise call *would have*+ * replaced them.+ */+export function buildOpportunities(+ data: SavingsView,+ { distillDocsHref }: BuildOpportunitiesOptions = {},+): OpportunityItem[] {+ const items: OpportunityItem[] = [];++ if (data.missed_events > 0) {+ items.push({+ id: "missed_distill",+ title: `${data.missed_events.toLocaleString()} command${+ data.missed_events === 1 ? "" : "s"+ } bypassed distillation`,+ potential: `Observed opportunity: ~${formatTokens(data.missed_tokens_est)} tokens`,+ detail: (+ <>+ Commands that ran raw {windowPhrase(data.missed_window_days)} would have been+ candidates for distillation. Nothing was saved on them.+ </>+ ),+ ...(distillDocsHref+ ? {+ href: distillDocsHref,+ linkLabel: "See the distillation setup guide",+ }+ : {}),+ });+ }++ if (data.reread_events > 0) {+ items.push({+ id: "reread",+ title: `${data.reread_events.toLocaleString()} unchanged-file re-read${+ data.reread_events === 1 ? "" : "s"+ }`,+ // "Potentially avoid" promised a future saving from an observation of+ // past behaviour. Every row in this section is the same kind of claim+ // and now says so the same way.+ potential: `Observed opportunity: ~${formatTokens(data.reread_tokens_est)} tokens`,+ detail: (+ <>+ {data.reread_events === 1 ? "One full re-read" : "Full re-reads"} of files that had+ not changed {data.reread_events === 1 ? "was" : "were"} observed.+ </>+ ),+ });+ }++ for (const row of data.per_opportunity_kind) {+ // The count goes in the sentence, not in front of the kind. Opportunity+ // kinds are an open vocabulary read straight off the ledger, so+ // `"12 " + slug` yields "12 hook replacement declined" for any kind that+ // is not already plural. Naming the kind and counting it separately stays+ // grammatical whatever a future surface records, without this file+ // keeping a label map of kinds it cannot know.+ items.push({+ id: `kind:${row.kind}`,+ title: sentenceCase(row.kind.replace(/_/g, " ")) || "Unnamed opportunity",+ potential: `Observed opportunity: ~${formatTokens(+ row.estimated_potential_input_tokens,+ )} tokens`,+ detail: (+ <>+ Observed {row.observations.toLocaleString()} time+ {row.observations === 1 ? "" : "s"}, and recorded by a capture surface as an+ opportunity rather than a saving.+ </>+ ),+ });+ }++ return items;+}++function sentenceCase(text: string): string {+ return text.charAt(0).toUpperCase() + text.slice(1);+}++/**+ * Name the miner's window without asserting a day count it does not have.+ *+ * `missed_window_days` is a float on the wire, so a freshly indexed+ * repository can report a fraction of a day. Rounding it printed "over the+ * last 0 days", which reads as a bug and understates the window besides.+ */+function windowPhrase(days: number): string {+ if (!Number.isFinite(days) || days <= 0) return "recently";+ if (days < 1) return "in the last day";+ const whole = Math.round(days);+ return `over the last ${whole} day${whole === 1 ? "" : "s"}`;+}diff --git a/packages/ui/src/savings/savings-lede.tsx b/packages/ui/src/savings/savings-lede.tsxnew file mode 100644index 000000000..41945d1b2--- /dev/null+++ b/packages/ui/src/savings/savings-lede.tsx@@ -0,0 +1,186 @@+"use client";++import * as React from "react";++import { PageLede } from "../shared/page-lede";+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";+import { formatCost, formatDate, formatTokens, parseDate } from "../lib/format";+import type { SavingsView } from "./types";++export interface SavingsLedeProps {+ data: SavingsView;+ /** Where "Method and limits" goes. Omit and the link is not rendered. */+ methodologyHref?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+}++/**+ * The page's subject: what agents avoided, and what the figure rests on.+ *+ * The distinctive element here is the evidence, not the size of the number.+ * The total is one figure at lede weight and everything beside it exists to+ * qualify it: how much is measured against how much is inferred, how much of+ * it carries a rate, and since when. A bigger number with none of that would+ * be a worse page.+ *+ * Performs no arithmetic beyond percentages of figures the report already+ * computed. Every quantity shown is a field.+ */+export function SavingsLede({ data, methodologyHref, LinkComponent }: SavingsLedeProps) {+ const total = data.saved_input_tokens;+ const measured = data.measured_saved_input_tokens;+ const inferred = data.inferred_saved_input_tokens;+ const unpriced = data.unpriced_saved_input_tokens;++ // "Estimated" for as long as any part of the total rests on a counterfactual+ // rather than a known before and after. The word is the honest one and it+ // costs nothing; dropping it once inferred evidence is present is how a+ // headline starts overclaiming.+ const label = inferred > 0 ? "Estimated agent savings" : "Agent savings";++ const stats: RibbonStat[] = [+ {+ label: "Measured",+ value: formatTokens(measured),+ hint: "A known before and after: the tokens an operation that actually ran removed.",+ sub: pctOf(measured, total),+ },+ {+ label: "Inferred",+ value: formatTokens(inferred),+ hint: "A documented counterfactual: the exploration a Repowise answer replaced.",+ sub: pctOf(inferred, total),+ },+ {+ label: "Valued",+ value: formatCost(data.priced_input_savings_usd),+ hint: "Each event is priced at the rate recorded when it happened, so this covers only events that carried one.",+ sub:+ unpriced > 0+ ? `on ${formatTokens(data.priced_saved_input_tokens)} of ${formatTokens(total)}`+ : "on all savings",+ },+ {+ label: "Interactions",+ value: data.unique_events.toLocaleString(),+ hint: "Logical agent interactions recorded. One interaction contributes to the total once.",+ // "9 saved tokens" reads as nine tokens. It is nine interactions.+ sub: `${data.saving_interactions.toLocaleString()} produced a saving`,+ },+ {+ label: "MCP answered",+ value: data.mcp_queries_answered.toLocaleString(),+ hint: "MCP calls that returned an answer. Dead ends are counted separately and save nothing.",+ ...(data.dead_ends > 0 ? { sub: `${data.dead_ends.toLocaleString()} dead ends` } : {}),+ },+ ];++ return (+ <div className="flex flex-col gap-6">+ <PageLede+ label={label}+ labelHint="Input tokens your agent never had to read."+ value={formatTokens(total)}+ unit="input tokens"+ layout="beside"+ >+ <p>+ These are input tokens your agent never had to read, recorded one event per+ interaction across the <code>repowise distill</code> path, the replacement hooks+ and MCP calls.{" "}+ {/* Nothing measured means nothing to characterise. Claiming "every+ part of the total is measured" about an empty set is a statement+ with no subject. */}+ {total <= 0+ ? "Nothing has been recorded in this window yet."+ : inferred > 0+ ? "Part of the total is inferred, so the figure is an estimate rather than a measurement."+ : "Every part of the total is a measured before and after."}+ </p>+ <p>+ {total <= 0 ? null : unpriced > 0 ? (+ <>+ {formatTokens(unpriced)} of those tokens carry no rate, so the dollar figure+ values the rest and not all of them.{" "}+ </>+ ) : (+ <>+ {/* "the whole total" was not true: the figure prices input+ tokens, and output savings are reported separately. */}+ Every event carried a rate, so the dollar figure values all of these input+ tokens.{" "}+ </>+ )}+ <Coverage+ data={data}+ methodologyHref={methodologyHref}+ LinkComponent={LinkComponent}+ />+ </p>+ </PageLede>++ <StatRibbon stats={stats} />+ </div>+ );+}++/**+ * The quiet permanent line: what window the figures cover, and where the+ * method is written down.+ *+ * Stays visible after the reset notice is dismissed, which is the whole+ * requirement -- a reader who dismissed an explanation months ago still needs+ * to know these figures do not reach back past a date. Worded as coverage and+ * read from `first_event_at` rather than from a hardcoded reset date, so it+ * describes the data actually rendered instead of a constant no test can+ * check.+ */+function Coverage({+ data,+ methodologyHref,+ LinkComponent,+}: {+ data: SavingsView;+ methodologyHref?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+}) {+ const A = LinkComponent ?? "a";+ const since = safeDate(data.first_event_at);+ const window =+ data.window_days === null+ ? since+ ? `Measured since ${since}.`+ : null+ : `Covering the last ${data.window_days} days.`;++ return (+ <span className="text-[var(--color-text-tertiary)]">+ {window}+ {window && methodologyHref ? " " : null}+ {methodologyHref && (+ <A+ href={methodologyHref}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ Method and limits+ </A>+ )}+ </span>+ );+}++/** A share, or nothing. A denominator of zero has no percentage, and "0%"+ * would be a claim rather than an absence. */+function pctOf(part: number, whole: number): string | undefined {+ if (whole <= 0) return undefined;+ return `${Math.round((part / whole) * 100)}% of total`;+}++/** Render a timestamp, or nothing if it is absent or unparseable. A date is+ * qualifying a published number, so a bad one is worse than none. */+function safeDate(iso: string | null): string | null {+ if (!iso) return null;+ const d = parseDate(iso);+ if (Number.isNaN(d.getTime())) return null;+ return formatDate(d);+}diff --git a/packages/ui/src/savings/savings-methodology.tsx b/packages/ui/src/savings/savings-methodology.tsxnew file mode 100644index 000000000..da7efbcaf--- /dev/null+++ b/packages/ui/src/savings/savings-methodology.tsx@@ -0,0 +1,128 @@+"use client";++import * as React from "react";++import { CollapsibleSection } from "../shared/collapsible-section";+import { DismissibleNotice } from "../shared/dismissible-notice";++/**+ * The accounting-method version this build reports under.+ *+ * Hosts key the reset notice's dismissal on repository plus this value, so a+ * later methodology change announces itself once more to a reader who+ * dismissed the previous one. Bump it when the way a saving is counted+ * changes, not when a component moves.+ */+export const ACCOUNTING_METHOD_VERSION = 1;++export interface SavingsResetNoticeProps {+ /** Where "See what changed" goes. */+ methodologyHref?: string | undefined;+ onDismiss: () => void;+ LinkComponent?: React.ElementType | undefined;+}++/**+ * Said once, when a repository's reader has not yet seen it.+ *+ * Restarting savings history is a methodology change, not silent data loss,+ * so it is disclosed rather than absorbed. Three things the copy has to do:+ * name what restarted, say plainly that nothing else was deleted, and avoid+ * calling itself a cost reset -- no money moved and no spend record changed.+ *+ * The host decides whether this renders and remembers the dismissal. This+ * component only knows how to say it.+ */+export function SavingsResetNotice({+ methodologyHref,+ onDismiss,+ LinkComponent,+}: SavingsResetNoticeProps) {+ const A = LinkComponent ?? "a";+ return (+ <DismissibleNotice+ tone="info"+ onDismiss={onDismiss}+ dismissLabel="Dismiss the savings accounting notice"+ {...(methodologyHref+ ? {+ action: (+ <A+ href={methodologyHref}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ See what changed+ </A>+ ),+ }+ : {})}+ >+ <span className="font-medium text-[var(--color-text-primary)]">+ Savings accounting has been upgraded.+ </span>{" "}+ Savings are now recorded one event per interaction, with the evidence behind each+ figure kept alongside it. Estimates produced by the earlier method could not be+ converted, so they were restarted rather than carried over. Your omission history and+ everything else in this repository were not deleted.+ </DismissibleNotice>+ );+}++export interface SavingsMethodologyProps {+ /** Link to the full accounting document. */+ href?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+}++/**+ * How the numbers on this page were arrived at, folded away by default.+ *+ * Quiet rather than absent: a page that asks to be trusted about token counts+ * has to be able to show its working, but the working is not what a reader+ * came for. Collapsed, at the end, in full.+ */+export function SavingsMethodology({ href, LinkComponent }: SavingsMethodologyProps) {+ const A = LinkComponent ?? "a";+ return (+ <CollapsibleSection title="Method and limits">+ <div className="flex max-w-[72ch] flex-col gap-3 text-[13px] leading-relaxed text-[var(--color-text-secondary)]">+ <p>+ A saving is input tokens your agent never had to read. One logical interaction+ produces one event and contributes to the total once, whether it passed through{" "}+ <code>repowise distill</code>, a replacement hook, or an MCP call.+ </p>+ <p>+ <strong className="font-medium text-[var(--color-text-primary)]">Measured</strong>{" "}+ figures compare a known before and after from an operation that actually ran.{" "}+ <strong className="font-medium text-[var(--color-text-primary)]">Inferred</strong>{" "}+ figures are a documented estimate of the exploration a Repowise answer replaced.+ They are reported apart because they are different evidence, and the headline says+ Estimated for as long as any inferred figure is in it.+ </p>+ <p>+ Observed opportunities are behaviour that could have been optimised and was not.+ They are never added to achieved savings.+ </p>+ <p>+ Each event is valued at the rate recorded at the moment it happened, so history is+ never repriced from today's rates. An event recorded before a rate could be+ resolved is counted in tokens and left unvalued, which is why priced and unpriced+ totals are shown separately.+ </p>+ <p>+ Token counts are estimates from character length and deliberately undersell.+ Dead ends and errors save nothing and are counted separately from answered+ queries. Everything on this page was recorded on this machine and stays here.+ {href && (+ <>+ {" "}+ <A href={href} className="text-[var(--color-accent-primary)] hover:underline">+ Read the full accounting document+ </A>+ </>+ )}+ </p>+ </div>+ </CollapsibleSection>+ );+}diff --git a/packages/ui/src/savings/savings-source-table.tsx b/packages/ui/src/savings/savings-source-table.tsxnew file mode 100644index 000000000..92eeb5e65--- /dev/null+++ b/packages/ui/src/savings/savings-source-table.tsx@@ -0,0 +1,171 @@+"use client";++import * as React from "react";++import { formatTokens } from "../lib/format";+import { cn } from "../lib/cn";++export interface SourceRow {+ /** The row's name, already resolved. A component here does not own a label+ * map: the caller knows whether it is holding surfaces, operations, models+ * or agents. */+ label: string;+ events: number;+ savedInputTokens: number;+}++export interface SavingsSourceTableProps {+ rows: SourceRow[];+ /**+ * Denominator for the proportion bars. The caller passes the report's total+ * rather than the largest row, so bars stay comparable between two tables on+ * one page -- normalising each table to its own max makes a small source+ * look as large as the biggest one.+ */+ total: number;+ /** Column header for the name column. */+ nameHeader: string;+ /** Rendered when `rows` is empty. */+ empty?: React.ReactNode;+ /** Accessible caption. Required: the table is a data claim and a screen+ * reader arriving at it needs to know what it counts. */+ caption: string;+ className?: string;+}++/**+ * Where the savings came from, as full-width rows.+ *+ * A table rather than a chart because the question is "how much did each+ * source contribute", which is exact comparison, and there are four surfaces.+ * The bar is a second read of the same number in the same row, not a separate+ * encoding: one family, quieter step, no category palette. The previous+ * version tinted rows from the language-token ramp, which gave operations the+ * colours that mean Python and Rust elsewhere in the product.+ */+export function SavingsSourceTable({+ rows,+ total,+ nameHeader,+ empty,+ caption,+ className,+}: SavingsSourceTableProps) {+ if (rows.length === 0) {+ return empty ? <>{empty}</> : null;+ }++ return (+ // Scrolls inside its own container so the document never scrolls sideways+ // at 390px.+ <div className={cn("w-full overflow-x-auto", className)}>+ {/* Narrow enough that all four columns land inside a 390px viewport's+ content box. At 22rem the token column sat half off the edge and read+ as broken even though the container scrolled correctly. */}+ <table className="w-full min-w-[19rem] border-collapse text-sm">+ <caption className="sr-only">{caption}</caption>+ <thead>+ <tr className="border-b border-[var(--color-border-default)] text-left">+ <Th className="w-[30%]">{nameHeader}</Th>+ <Th className="w-[34%]">Share</Th>+ <Th align="right">Events</Th>+ {/* Wraps to two lines when narrow rather than dropping the unit:+ "Saved" alone does not say saved what. */}+ <Th align="right">Tokens saved</Th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => (+ <tr+ key={row.label}+ className="border-b border-[var(--color-border-default)] last:border-b-0"+ >+ <td className="py-2.5 pr-3 text-[var(--color-text-primary)]">{row.label}</td>+ <td className="py-2.5 pr-3">+ <Share value={row.savedInputTokens} total={total} label={row.label} />+ </td>+ <td className="py-2.5 pr-3 text-right tabular-nums text-[var(--color-text-secondary)]">+ {row.events.toLocaleString()}+ </td>+ <td className="py-2.5 text-right tabular-nums text-[var(--color-text-primary)]">+ {formatTokens(row.savedInputTokens)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}++function Th({+ children,+ align = "left",+ className,+}: {+ children: React.ReactNode;+ align?: "left" | "right";+ className?: string;+}) {+ return (+ <th+ scope="col"+ className={cn(+ "py-2 font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]",+ align === "right" ? "pl-3 text-right" : "pr-3 text-left",+ className,+ )}+ >+ {children}+ </th>+ );+}++/**+ * The row's share of the total, as a bar with its percentage in text.+ *+ * The number is written out rather than left to the bar alone: a 2% bar and a+ * 4% bar are indistinguishable at this width, and the percentage is the thing+ * a reader is comparing.+ */+function Share({ value, total, label }: { value: number; total: number; label: string }) {+ // No denominator means no share. Say so in words rather than with a dash+ // alone, which left a screen reader with an empty cell.+ if (!(total > 0) || !Number.isFinite(value)) {+ return <span className="text-xs text-[var(--color-text-tertiary)]">No share</span>;+ }++ const raw = (value / total) * 100;+ // Clamped at both ends. A breakdown whose rows are counted differently from+ // the total can exceed it, and an unclamped bar then overflows its track+ // while the label claims "140%"; a negative would print as "<1%", reading+ // as a small positive contribution.+ const pct = Math.min(Math.max(raw, 0), 100);+ // A contributing row never renders as an empty track: below about half a+ // percent the bar rounds to nothing and the row reads as zero.+ const width = pct > 0 ? Math.max(pct, 1.5) : 0;+ const text = pct <= 0 ? "0%" : pct >= 1 ? `${Math.round(pct)}%` : "<1%";++ return (+ <span className="flex items-center gap-2">+ <span+ aria-hidden+ className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-[var(--color-bg-inset)]"+ >+ <span+ className="block h-full rounded-full bg-[var(--color-accent-fill)]"+ style={{ width: `${width}%` }}+ />+ </span>+ <span+ aria-hidden+ className="w-10 shrink-0 text-right text-xs tabular-nums text-[var(--color-text-tertiary)]"+ >+ {text}+ </span>+ <span className="sr-only">+ {label}: {pct.toFixed(1)}% of total savings+ </span>+ </span>+ );+}diff --git a/packages/ui/src/savings/savings-timeline.tsx b/packages/ui/src/savings/savings-timeline.tsxnew file mode 100644index 000000000..87c69461e--- /dev/null+++ b/packages/ui/src/savings/savings-timeline.tsx@@ -0,0 +1,143 @@+"use client";++import * as React from "react";+import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from "recharts";++import { formatTokens } from "../lib/format";+import type { SavingsBreakdownRow } from "./types";++/** Below this many days with a recorded saving, a bar chart is two or three+ * bars in a wide empty box: the shape carries nothing a sentence does not.+ * The design language says to measure the distribution before drawing it, so+ * the component measures it and declines. */+export const MIN_DAYS_FOR_CHART = 4;++export const TIMELINE_HEIGHT = 220;++export interface SavingsTimelineProps {+ /** The report's `per_day` series. */+ days: SavingsBreakdownRow[];+ height?: number;+}++/** The day rows worth drawing: named days that actually recorded a saving. */+function plottable(days: SavingsBreakdownRow[]): Array<{ day: string; tokens: number }> {+ return days+ .filter((d) => d.group !== null && d.saved_input_tokens > 0)+ .map((d) => ({ day: d.group as string, tokens: d.saved_input_tokens }))+ .sort((a, b) => a.day.localeCompare(b.day));+}++/**+ * Savings over time, when there is enough of it to have a shape.+ *+ * Returns a sentence instead of a chart under {@link MIN_DAYS_FOR_CHART}, and+ * renders a textual summary beside the chart in every case. A canvas without+ * an equivalent reading is unreachable for anyone not looking at it, and this+ * one's important result -- that savings accrue, and roughly how evenly -- is+ * a sentence anyway.+ */+export function SavingsTimeline({ days, height = TIMELINE_HEIGHT }: SavingsTimelineProps) {+ const data = React.useMemo(() => plottable(days), [days]);++ if (data.length === 0) {+ return (+ <p className="text-sm text-[var(--color-text-secondary)]">+ No day in this window recorded a saving.+ </p>+ );+ }++ const first = data[0] as { day: string; tokens: number };+ const last = data[data.length - 1] as { day: string; tokens: number };+ const busiest = data.reduce((a, b) => (b.tokens > a.tokens ? b : a), first);++ // "between 2026-09-18 and 2026-09-18" is how a range reads when there is+ // only one day in it.+ const span =+ first.day === last.day ? (+ <>on {first.day}</>+ ) : (+ <>+ between {first.day} and {last.day}+ </>+ );++ const summary = (+ <p className="text-[13px] leading-relaxed text-[var(--color-text-secondary)]">+ {data.length} day{data.length === 1 ? "" : "s"} recorded a saving {span}.+ {data.length > 1 && (+ <>+ {" "}+ The largest was {formatTokens(busiest.tokens)} tokens on {busiest.day}.+ </>+ )}+ </p>+ );++ if (data.length < MIN_DAYS_FOR_CHART) {+ // Too few points for a bar chart to mean anything. The sentence above is+ // the whole result, so it is rendered on its own rather than as a caption+ // under an almost-empty plot.+ return summary;+ }++ return (+ <div className="flex flex-col gap-3">+ {/* The plot box is reserved before recharts measures it: a bare+ ResponsiveContainer renders nothing until its ResizeObserver fires,+ so the section grew into place on every mount. */}+ <div style={{ height }} role="img" aria-label={ariaLabel(data, busiest)}>+ <ResponsiveContainer width="100%" height="100%">+ <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>+ <XAxis+ dataKey="day"+ tick={{ fill: "var(--color-text-tertiary)", fontSize: 11 }}+ axisLine={false}+ tickLine={false}+ interval="preserveStartEnd"+ minTickGap={24}+ tickFormatter={shortDay}+ />+ <YAxis+ tick={{ fill: "var(--color-text-tertiary)", fontSize: 10 }}+ axisLine={false}+ tickLine={false}+ tickFormatter={(v: number) => formatTokens(v)}+ />+ <Tooltip+ cursor={{ fill: "var(--color-bg-elevated)" }}+ contentStyle={{+ background: "var(--color-bg-overlay)",+ border: "1px solid var(--color-border-default)",+ borderRadius: "6px",+ fontSize: "12px",+ color: "var(--color-text-primary)",+ }}+ formatter={(value) => [`${formatTokens(Number(value))} tokens`, "Saved"]}+ labelFormatter={(label) => String(label)}+ />+ <Bar dataKey="tokens" fill="var(--color-accent-fill)" radius={[3, 3, 0, 0]} />+ </BarChart>+ </ResponsiveContainer>+ </div>+ {summary}+ </div>+ );+}++/** `2026-09-19` reads as `9/19` on a crowded axis. Anything else is left+ * alone rather than mangled. */+function shortDay(value: string): string {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);+ return m ? `${Number(m[2])}/${Number(m[3])}` : value;+}++function ariaLabel(+ data: Array<{ day: string; tokens: number }>,+ busiest: { day: string; tokens: number },+): string {+ return `Savings per day, ${data.length} days. Largest ${formatTokens(+ busiest.tokens,+ )} tokens on ${busiest.day}.`;+}diff --git a/packages/ui/src/savings/spend-summary.tsx b/packages/ui/src/savings/spend-summary.tsxnew file mode 100644index 000000000..b49599235--- /dev/null+++ b/packages/ui/src/savings/spend-summary.tsx@@ -0,0 +1,77 @@+"use client";++import * as React from "react";++import { formatCost, formatDate, formatNumber, formatTokens, parseDate } from "../lib/format";+import type { SpendView } from "./types";++export interface SpendSummaryProps {+ spend: SpendView;+}++/**+ * What Repowise's own model work cost.+ *+ * Called "Repowise model spend" and not "Indexing cost", because the+ * `llm_costs` table it reads records generation and other model-backed+ * operations too: the old label named a subset and counted the whole.+ *+ * A definition list, not a card grid. Four near-identical bordered tiles+ * claimed four separate subjects where there is one, and a `<dl>` is what+ * labelled values are.+ *+ * Deliberately adjacent to savings and never netted against them. They are+ * different accounts -- one is what agents avoided, the other is what Repowise+ * charged a provider -- and a single "net" figure would imply a settlement+ * that never happens.+ */+export function SpendSummary({ spend }: SpendSummaryProps) {+ const since = safeDate(spend.since);++ if (spend.total_calls === 0) {+ return (+ <p className="text-sm text-[var(--color-text-secondary)]">+ No model calls recorded for this repository, so nothing has been spent.+ </p>+ );+ }++ return (+ <div className="flex flex-col gap-3">+ <dl className="grid grid-cols-2 gap-x-8 gap-y-4 sm:grid-cols-4">+ <Item label="Spent" value={formatCost(spend.total_cost_usd)} />+ <Item label="Calls" value={formatNumber(spend.total_calls)} />+ {/* Compact, like every other token figure on the page. Spelled out,+ 9,400,000 sits beside a 12.9M savings total and the two read as+ different units. */}+ <Item label="Input tokens" value={formatTokens(spend.total_input_tokens)} />+ <Item label="Output tokens" value={formatTokens(spend.total_output_tokens)} />+ </dl>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Metered provider spend for indexing, page generation and other model-backed+ operations{since ? `, since ${since}` : ""}. Reported beside agent savings, never+ subtracted from them.+ </p>+ </div>+ );+}++function Item({ label, value }: { label: string; value: string }) {+ return (+ <div className="flex min-w-0 flex-col gap-1">+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {label}+ </dt>+ <dd className="text-[22px] font-semibold leading-none tabular-nums text-[var(--color-text-primary)]">+ {value}+ </dd>+ </div>+ );+}++function safeDate(iso: string | null): string | null {+ if (!iso) return null;+ const d = parseDate(iso);+ if (Number.isNaN(d.getTime())) return null;+ return formatDate(d);+}diff --git a/packages/ui/src/savings/types.ts b/packages/ui/src/savings/types.tsnew file mode 100644index 000000000..998217805--- /dev/null+++ b/packages/ui/src/savings/types.ts@@ -0,0 +1,130 @@+/**+ * The savings report, as the shared surface consumes it.+ *+ * Field names match the wire exactly. That is the point: the server's report+ * service is the only thing that aggregates or prices, so a component here+ * reads a field and renders it rather than deriving it. Three surfaces used to+ * aggregate the ledger independently and published three different dollar+ * figures for one repository; a number computed in React would be a fourth.+ *+ * Declared here rather than imported from `@repowise-dev/api-client` because+ * this package stays free of the fetch layer -- the same reason+ * `settings/provider-settings.tsx` redeclares `ProviderInfo`. A host maps its+ * response onto this; it does not hand a component its HTTP client.+ */++/** One bucket of a breakdown. `group` is null for the bucket with no name --+ * savings whose events carry no pricing model, which is a real quantity+ * rather than a row to drop. */+export interface SavingsBreakdownRow {+ group: string | null;+ events: number;+ saved_input_tokens: number;+}++/** One agent's savings. `agent_display_name` is resolved from the server's+ * identity registry, so no client keeps a label map of its own. */+export interface SavingsAgentRow {+ agent: string;+ agent_display_name: string | null;+ events: number;+ saved_input_tokens: number;+}++/** One kind of recorded opportunity. Never part of achieved savings. */+export interface SavingsOpportunityRow {+ kind: string;+ observations: number;+ estimated_potential_input_tokens: number;+}++export interface SavingsView {+ /** `false` means nothing has been measured here, which is a different claim+ * from a measured zero. */+ available: boolean;+ /** Window the figures cover; null means all time. */+ window_days: number | null;+ as_of: string;+ first_event_at: string | null;+ last_event_at: string | null;++ unique_events: number;+ successful_or_usable_partial_events: number;+ saving_interactions: number;+ mcp_queries_answered: number;+ dead_ends: number;++ saved_input_tokens: number;+ measured_saved_input_tokens: number;+ inferred_saved_input_tokens: number;+ priced_saved_input_tokens: number;+ unpriced_saved_input_tokens: number;+ priced_input_savings_usd: number;+ /** Null when no event in the window carried output evidence at all, which is+ * distinct from a measured zero. */+ saved_output_tokens: number | null;+ priced_saved_output_tokens: number;+ unpriced_saved_output_tokens: number;+ priced_output_savings_usd: number;++ per_operation: SavingsBreakdownRow[];+ per_surface: SavingsBreakdownRow[];+ per_agent: SavingsAgentRow[];+ per_model: SavingsBreakdownRow[];+ per_day: SavingsBreakdownRow[];++ opportunity_count: number;+ opportunity_tokens_excluded: number;+ per_opportunity_kind: SavingsOpportunityRow[];+ /** Transcript-mined opportunities: what was *not* saved. */+ missed_events: number;+ missed_tokens_est: number;+ missed_window_days: number;+ reread_events: number;+ reread_tokens_est: number;+}++/** What Repowise's own model work cost. Metered spend, never netted against+ * savings: they are different accounts and the page keeps them apart. */+export interface SpendView {+ total_cost_usd: number;+ total_calls: number;+ total_input_tokens: number;+ total_output_tokens: number;+ since: string | null;+}++/**+ * Surface slugs read as identifiers; these are the words for them.+ *+ * Kept client-side rather than on the wire because a surface is a fixed part+ * of the accounting contract -- the set is closed and changing it is a schema+ * change -- unlike an agent, whose label comes from the identity registry in+ * the payload precisely because that set is open.+ */+const SURFACE_LABELS: Record<string, string> = {+ distill: "Distill",+ hook: "Hooks",+ mcp: "MCP",+ vscode_lm: "VS Code",+};++/** Name a surface slug. An unrecognised slug renders as itself rather than as+ * "Unknown": it is a real surface this build has no word for yet, and hiding+ * it behind a sentinel would lose which one it was. */+export function surfaceLabel(slug: string | null): string {+ if (!slug) return "Unknown";+ return SURFACE_LABELS[slug] ?? slug;+}++/** Name an agent from its row. The display name is the server's; the slug is+ * the fallback when this build's registry did not resolve one. */+export function agentLabel(row: SavingsAgentRow): string {+ return row.agent_display_name ?? row.agent;+}++/** Name a pricing-model bucket. Null is the unpriced bucket, which is a+ * quantity worth naming rather than a gap. */+export function modelLabel(slug: string | null): string {+ return slug ?? "No rate recorded";+}diff --git a/packages/ui/src/savings/usage-details.tsx b/packages/ui/src/savings/usage-details.tsxnew file mode 100644index 000000000..cdd99970b--- /dev/null+++ b/packages/ui/src/savings/usage-details.tsx@@ -0,0 +1,133 @@+"use client";++import * as React from "react";++import { ViewTabs, type ViewTab } from "../shared/view-tabs";+import { SavingsSourceTable, type SourceRow } from "./savings-source-table";+import { SavingsTimeline } from "./savings-timeline";+import { agentLabel, modelLabel, type SavingsView } from "./types";++export type UsageDetailTab = "day" | "operation" | "model" | "agent";++export interface UsageDetailsProps {+ data: SavingsView;+ /** Controlled selection. Omit both and the component keeps its own. */+ value?: UsageDetailTab | undefined;+ onValueChange?: ((tab: UsageDetailTab) => void) | undefined;+}++/**+ * The same savings, cut four ways.+ *+ * One tab row on one axis: each tab selects a *dimension of the same+ * dataset*, never a different scope or window. The page's window control is+ * separate and stays separate, which is the rule that keeps a reader from+ * having two controls that both look like they narrow the result.+ *+ * A dimension with no rows still gets a tab, and says what would populate it+ * once opened. Hiding it would make the vocabulary depend on the data and+ * leave a reader unsure whether "by model" exists at all.+ */+export function UsageDetails({ data, value, onValueChange }: UsageDetailsProps) {+ const [internal, setInternal] = React.useState<UsageDetailTab>("day");+ // Controlled by the presence of `value`, not of `onValueChange`. Keying on+ // the callback froze the tabs for a host that only wanted to observe the+ // selection: every click notified and nothing moved.+ const controlled = value !== undefined;+ const active = controlled ? value : internal;+ const select = React.useCallback(+ (id: string) => {+ const tab = id as UsageDetailTab;+ if (!controlled) setInternal(tab);+ // Fires in both modes: an uncontrolled caller may still want to know.+ onValueChange?.(tab);+ },+ [controlled, onValueChange],+ );++ const total = data.saved_input_tokens;++ const operations = toRows(data.per_operation, (g) => g ?? "Unknown");+ const models = toRows(data.per_model, modelLabel);+ const agents: SourceRow[] = data.per_agent.map((row) => ({+ label: agentLabel(row),+ events: row.events,+ savedInputTokens: row.saved_input_tokens,+ }));++ return (+ <ViewTabs+ tabs={[+ { id: "day", label: "By day" },+ tab("operation", "Operations", operations.length),+ tab("model", "Models", models.length),+ tab("agent", "Agents", agents.length),+ ]}+ value={active}+ onValueChange={select}+ >+ {active === "day" && <SavingsTimeline days={data.per_day} />}++ {active === "operation" && (+ <SavingsSourceTable+ rows={operations}+ total={total}+ nameHeader="Operation"+ caption="Savings by the operation that produced them"+ empty={<Empty subject="operation" />}+ />+ )}++ {active === "model" && (+ <SavingsSourceTable+ rows={models}+ total={total}+ nameHeader="Model"+ caption="Savings by the pricing model recorded on each event"+ empty={<Empty subject="model" />}+ />+ )}++ {active === "agent" && (+ <SavingsSourceTable+ rows={agents}+ total={total}+ nameHeader="Agent"+ caption="Savings by the agent that made the call"+ empty={<Empty subject="agent" />}+ />+ )}+ </ViewTabs>+ );+}++/**+ * One tab, carrying its row count only when it has rows.+ *+ * A zero badge is worse than no badge: it reads as a count the tab is+ * reporting rather than as an empty dimension, and the design language says a+ * count belongs on a tab only when it is meaningful before the click.+ */+function tab(id: UsageDetailTab, label: string, count: number): ViewTab {+ return count > 0 ? { id, label, badge: count } : { id, label };+}++function toRows(+ rows: SavingsView["per_operation"],+ label: (group: string | null) => string,+): SourceRow[] {+ return rows.map((row) => ({+ label: label(row.group),+ events: row.events,+ savedInputTokens: row.saved_input_tokens,+ }));+}++/** Says what would populate the view rather than rendering an empty table. */+function Empty({ subject }: { subject: string }) {+ return (+ <p className="py-2 text-sm text-[var(--color-text-secondary)]">+ No savings in this window carry a {subject}.+ </p>+ );+}diff --git a/packages/ui/src/shared/dismissible-notice.tsx b/packages/ui/src/shared/dismissible-notice.tsxnew file mode 100644index 000000000..9d9d85960--- /dev/null+++ b/packages/ui/src/shared/dismissible-notice.tsx@@ -0,0 +1,95 @@+import * as React from "react";+import { Info, X } from "lucide-react";++import { cn } from "../lib/cn";++export type NoticeTone = "neutral" | "info";++export interface DismissibleNoticeProps {+ /**+ * The notice itself, already rendered. A notice that formats its own+ * sentence ends up with a prop per clause; passing nodes keeps the copy+ * with the surface that knows what it is announcing.+ */+ children: React.ReactNode;+ /**+ * `"info"` tints the rule and icon with the accent; `"neutral"` leaves them+ * quiet. There is deliberately no warning or error tone: those are semantic+ * states an inline methodology notice does not have, and offering them is+ * how a calm disclosure becomes an alarm.+ */+ tone?: NoticeTone;+ /**+ * An optional link or button. Rendered after the copy, in the reading flow,+ * so a keyboard user reaches it before the dismiss control.+ */+ action?: React.ReactNode;+ /**+ * Called when the reader dismisses. Omit it and no dismiss control renders,+ * which is how a permanent inline note uses the same visual.+ *+ * The component holds no dismissed state of its own: whether this notice+ * has been seen is a question about a repository and a methodology version,+ * which only the host can answer and only the host can persist.+ */+ onDismiss?: (() => void) | undefined;+ /** Accessible name for the dismiss control. */+ dismissLabel?: string;+ className?: string;+}++/**+ * A calm inline notice, dismissed by whoever owns the answer to "again?".+ *+ * Deliberately not a modal, toast, or banner: this is for telling a reader+ * something about the numbers they are already looking at, so it sits beside+ * them and never takes focus. `role="status"` rather than `role="alert"` for+ * the same reason -- a methodology change is news, not an interruption.+ *+ * Built controlled because the three hand-rolled banners that preceded it each+ * embedded their own `localStorage` read, which put the persistence key, the+ * storage failure handling, and the visual in one file and made the visual+ * untestable without a DOM storage shim. Here the host decides visibility and+ * this decides only how it looks.+ */+export function DismissibleNotice({+ children,+ tone = "neutral",+ action,+ onDismiss,+ dismissLabel = "Dismiss",+ className,+}: DismissibleNoticeProps) {+ const ink =+ tone === "info" ? "var(--color-accent-primary)" : "var(--color-text-tertiary)";++ return (+ <div+ role="status"+ className={cn(+ "flex items-start gap-2.5 border-l-2 py-2 pl-3 text-[13px] leading-relaxed text-[var(--color-text-secondary)]",+ className,+ )}+ style={{ borderColor: ink }}+ >+ <Info className="mt-0.5 h-4 w-4 shrink-0" style={{ color: ink }} aria-hidden="true" />+ {/* min-w-0 so a long sentence wraps instead of widening the row past its+ container, which is what pushes the dismiss control off screen at+ 390px. */}+ <div className="min-w-0 flex-1 [text-wrap:pretty]">+ {children}+ {action && <div className="mt-2">{action}</div>}+ </div>+ {onDismiss && (+ <button+ type="button"+ onClick={onDismiss}+ aria-label={dismissLabel}+ className="-mr-1 shrink-0 rounded p-1 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <X className="h-3.5 w-3.5" aria-hidden="true" />+ </button>+ )}+ </div>+ );+}diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.tsindex 66952f3f4..d2b507682 100644--- a/packages/ui/src/shared/index.ts+++ b/packages/ui/src/shared/index.ts@@ -25,6 +25,11 @@ export {export { Toaster, toast, type ToasterProps } from "./toast";export * from "./breadcrumb";export * from "./empty-state";+export {+ DismissibleNotice,+ type DismissibleNoticeProps,+ type NoticeTone,+} from "./dismissible-notice";export { InfoTip, type InfoTipProps } from "./info-tip";export { OwlLoader, type OwlLoaderProps } from "./owl-loader";export {diff --git a/packages/ui/src/shared/loading-skeletons.tsx b/packages/ui/src/shared/loading-skeletons.tsxindex 6337e2e92..468ece45a 100644--- a/packages/ui/src/shared/loading-skeletons.tsx+++ b/packages/ui/src/shared/loading-skeletons.tsx@@ -92,10 +92,14 @@ export function PageSkeleton({<h1 className={PAGE_SHELL_TITLE}><Skeleton className="h-[1lh] w-52 max-w-full" /></h1>+ {/* A div, not a p: `Skeleton` renders a div and a p may not contain+ one. The browser closes the p early, so the server and client+ trees differ and React discards the hydrated subtree. It carries+ no text, so the p bought nothing. */}{description && (- <p className={PAGE_SHELL_DESCRIPTION}>+ <div className={PAGE_SHELL_DESCRIPTION}><Skeleton className="block h-[1lh] w-full" />- </p>+ </div>)}</div>{actions && <Skeleton className="h-8 w-24 shrink-0" />}diff --git a/packages/web/src/app/repos/[id]/costs/page.tsx b/packages/web/src/app/repos/[id]/costs/page.tsxindex 62866448f..bd2045df5 100644--- a/packages/web/src/app/repos/[id]/costs/page.tsx+++ b/packages/web/src/app/repos/[id]/costs/page.tsx@@ -1,331 +1,282 @@"use client";-import { useState } from "react";+import { useCallback, useEffect, useState } from "react";import useSWR from "swr";import { useParams } from "next/navigation";-import { DollarSign } from "lucide-react";-import { MetricCard } from "@repowise-dev/ui/shared/metric-card";+import Link from "next/link";+import { PageShell } from "@repowise-dev/ui/shared/page-shell";import { ApiError } from "@repowise-dev/ui/shared/api-error";-import { ChartSkeleton, StatGridSkeleton } from "@repowise-dev/ui/shared/loading-skeletons";-import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";-import { SkeletonRegion, Skeleton } from "@repowise-dev/ui/ui/skeleton";-import { Tabs, ScrollableTabsList, TabsTrigger, TabsContent } from "@repowise-dev/ui/ui/tabs";-import { CHART_HEIGHT, operationBreakdownHeight } from "@repowise-dev/ui/costs/chart-height";+import { EmptyState } from "@repowise-dev/ui/shared/empty-state";+import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";+import { OverviewSection } from "@repowise-dev/ui/overview/section";import {- CostHeatmap,- DailySpendChart,- SavingsCard,- ProviderComparison,- OperationBreakdown,- RoiCard,- SavingsTrendChart,-} from "@repowise-dev/ui/costs";-import { listCosts, getCostSummary, getSavings } from "@/lib/api/costs";-import type { CostGroup, CostSummary, Savings } from "@/lib/api/costs";-import { formatCost, formatNumber, formatTokens } from "@repowise-dev/ui/lib/format";--export default function CostsPage() {- const params = useParams<{ id: string }>();- const id = params.id;- const [tab, setTab] = useState("daily");+ ACCOUNTING_METHOD_VERSION,+ OpportunityList,+ SavingsLede,+ SavingsMethodology,+ SavingsResetNotice,+ SavingsSourceTable,+ SpendSummary,+ UsageDetails,+ buildOpportunities,+ surfaceLabel,+ type SavingsView,+ type SpendView,+} from "@repowise-dev/ui/savings";+import { getCostSummary, getSavings } from "@/lib/api/costs";+import type { CostSummary, Savings } from "@/lib/api/costs";- const {- data: summary,- error: summaryError,- isLoading: loadingSummary,- mutate: retrySummary,- } = useSWR<CostSummary>(- `costs-summary:${id}`,- () => getCostSummary(id),- { revalidateOnFocus: false },- );+/** Where the accounting is written down. One constant, used by the lede, the+ * reset notice and the methodology section, so the three cannot drift. */+const METHODOLOGY_HREF =+ "https://github.com/repowise-dev/repowise/blob/main/docs/architecture/savings-accounting.md";- const {- data: dayGroups,- error: dayError,- isLoading: loadingDay,- mutate: retryDay,- } = useSWR<CostGroup[]>(- `costs-groups:${id}:day`,- () => listCosts(id, { by: "day" }),- { revalidateOnFocus: false },- );+const DISTILL_DOCS_HREF =+ "https://github.com/repowise-dev/repowise/blob/main/docs/agent/DISTILL.md";- const {- data: modelGroups,- error: modelError,- mutate: retryModel,- } = useSWR<CostGroup[]>(- `costs-groups:${id}:model`,- () => listCosts(id, { by: "model" }),- { revalidateOnFocus: false },- );+/** Dismissal is scoped to a repository *and* an accounting-method version, so+ * a later methodology change announces itself once more to someone who+ * dismissed the previous one. */+function resetNoticeKey(repoId: string): string {+ return `repowise:savings-reset-dismissed:${repoId}:v${ACCOUNTING_METHOD_VERSION}`;+}- const {- data: opGroups,- error: opError,- mutate: retryOp,- } = useSWR<CostGroup[]>(- `costs-groups:${id}:operation`,- () => listCosts(id, { by: "operation" }),- { revalidateOnFocus: false },- );+/**+ * Usage and savings: what agents avoided, what Repowise cost, and how we know.+ *+ * A scan surface. Sections and hairlines carry the grouping; the only boxes+ * are the ones a reader can act on, which on this page is none. The subject is+ * the evidence-led lede, and everything below it qualifies or decomposes that+ * one figure.+ *+ * This page performs no accounting arithmetic. `load_report` on the server is+ * the only thing that aggregates or prices, and every figure here is a field+ * off the response. Three surfaces once aggregated the ledger independently+ * and published three different dollar figures for one repository; a number+ * computed in React would be a fourth.+ */+export default function CostsPage() {+ const params = useParams<{ id: string }>();+ const id = params.id;+ // Two fetches above the fold, in one wave. The previous page made five, three+ // of them the same endpoint with a different `by` for tabs that were not+ // open.const {- data: distillSavings,- error: distillError,- mutate: retryDistill,+ data: savings,+ error: savingsError,+ isLoading: loadingSavings,+ mutate: retrySavings,} = useSWR<Savings>(`savings:${id}`, () => getSavings(id), {revalidateOnFocus: false,});- // A discriminated union rather than a bare string, so the populated branch- // carries the data it is populated with and TypeScript can see that.- const savings = distillError- ? ({ kind: "error" } as const)- : distillSavings === undefined- ? ({ kind: "pending" } as const)- : distillSavings.available- ? ({ kind: "populated", data: distillSavings } as const)- : ({ kind: "unavailable" } as const);+ const {+ data: spend,+ error: spendError,+ mutate: retrySpend,+ } = useSWR<CostSummary>(`costs-summary:${id}`, () => getCostSummary(id), {+ revalidateOnFocus: false,+ });return (<PageShell- maxWidth="wide"- icon={<DollarSign className="h-5 w-5 text-[var(--color-success)]" />}- title="Cost Tracking"- description="What repowise saved your coding agent — and what generating the docs cost."+ title="Usage & savings"+ description="What agents avoided, what Repowise cost, and how we know.">- {/* Hero: the honest results surface — all tokens & dollars saved for the- coding agent, across distill (CLI + hook) and MCP tool responses. */}- {distillError ? (- <Card>- <CardContent className="py-6">- <ApiError- title="Couldn't load agent savings"- message="The savings endpoint did not respond. Everything below is unaffected."- onRetry={() => void retryDistill()}- />- </CardContent>- </Card>+ <ResetNotice repoId={id} />++ {savingsError ? (+ <ApiError+ title="Couldn't load agent savings"+ // Only claim spend is fine when it actually is. Asserted+ // unconditionally, this sat directly above a spend error.+ message={+ spendError+ ? "The savings endpoint did not respond."+ : "The savings endpoint did not respond. Model spend below is unaffected."+ }+ onRetry={() => void retrySavings()}+ />+ ) : savings === undefined ? (+ <SavingsSkeleton />) : (- <SavingsCard data={distillSavings} />+ // No cast: `Savings` and `SavingsView` are separate declarations of+ // the same wire shape, and an assignment is what makes the compiler+ // notice if they ever drift apart.+ <SavingsSections data={savings} />)}- {/* ROI and the savings trend are gated on `available`, which is a- SEMANTIC state, not a load state: a repo that has never run distill- legitimately has neither card. Three states, not a boolean, because- a plain `available &&` renders nothing while the request is still in- flight and then inserts ~400px above the tabs on arrival.+ <OverviewSection+ title="Repowise model spend"+ description="What Repowise's own model work cost, reported beside agent savings and never subtracted from them."+ >+ {spendError ? (+ <ApiError title="Couldn't load model spend" onRetry={() => void retrySpend()} />+ ) : spend === undefined ? (+ <p className="text-sm text-[var(--color-text-tertiary)]">Loading model spend…</p>+ ) : (+ <SpendSummary spend={spend} />+ )}+ </OverviewSection>- pending → reserve the populated height- unavailable → render nothing, reserve nothing- populated → the cards */}- {savings.kind === "pending" ? (- <>- <Skeleton className="h-[104px] w-full rounded-xl" />- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Agent tokens saved by day</CardTitle>- </CardHeader>- <CardContent className="pt-0">- <ChartSkeleton height={CHART_HEIGHT} label="Loading savings trend" />- </CardContent>- </Card>- </>- ) : savings.kind === "populated" ? (- <>- {summary ? (- <RoiCard- savedUsd={savings.data.priced_input_savings_usd}- spentUsd={summary.total_cost_usd}- savedTokens={savings.data.saved_input_tokens}- />- ) : null}- {(savings.data.per_day?.length ?? 0) > 0 ? (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Agent tokens saved by day</CardTitle>- </CardHeader>- <CardContent className="pt-0">- <SavingsTrendChart groups={savings.data.per_day} />- </CardContent>- </Card>- ) : null}- </>- ) : null}+ {/* No `OverviewSection` wrapper: `SavingsMethodology` is a collapsible+ that titles itself, and wrapping it printed "Method and limits"+ twice, once as a heading and once as the toggle under it. */}+ <SavingsMethodology href={METHODOLOGY_HREF} LinkComponent={Link} />+ </PageShell>+ );+}- <Tabs value={tab} onValueChange={setTab} className="w-full">- <ScrollableTabsList>- <TabsTrigger value="daily">Daily</TabsTrigger>- <TabsTrigger value="operations">Spend by operation</TabsTrigger>- <TabsTrigger value="providers">Providers</TabsTrigger>- <TabsTrigger value="hotspots">Hotspots</TabsTrigger>- <TabsTrigger value="efficiency">Efficiency</TabsTrigger>- </ScrollableTabsList>+/**+ * Reserves the lede and ribbon while the report is in flight.+ *+ * Shaped like what replaces it rather than a flat block: the populated lede+ * and ribbon stand ~260px, and a short placeholder made the whole page jump+ * on first paint. Deliberately not `PageSkeleton`, which draws a page header+ * that `PageShell` is already rendering for real just above this.+ */+function SavingsSkeleton() {+ return (+ <SkeletonRegion label="Loading agent savings" className="flex flex-col gap-6">+ <div className="flex flex-col gap-5 lg:flex-row lg:items-start lg:gap-12">+ <div className="flex flex-col gap-2.5 lg:w-[220px]">+ <Skeleton className="h-3 w-40" />+ <Skeleton className="h-11 w-32" />+ </div>+ <div className="flex max-w-[62ch] flex-1 flex-col gap-2">+ <Skeleton className="h-[1lh] w-full" />+ <Skeleton className="h-[1lh] w-full" />+ <Skeleton className="h-[1lh] w-2/3" />+ </div>+ </div>+ <div className="grid grid-cols-2 border-y border-[var(--color-border-default)] sm:grid-cols-3 lg:grid-cols-5">+ {[0, 1, 2, 3, 4].map((i) => (+ <div key={i} className="flex flex-col gap-1.5 px-4 py-3.5">+ <Skeleton className="h-2.5 w-20" />+ <Skeleton className="h-5 w-16" />+ </div>+ ))}+ </div>+ </SkeletonRegion>+ );+}- <TabsContent value="daily" className="mt-4">- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Daily Spend (USD)</CardTitle>- </CardHeader>- <CardContent className="pt-0">- {dayError ? (- <ApiError- title="Couldn't load daily spend"- onRetry={() => void retryDay()}- />- ) : loadingDay ? (- <ChartSkeleton height={CHART_HEIGHT} label="Loading daily spend" />- ) : (- <DailySpendChart groups={dayGroups ?? []} />- )}- </CardContent>- </Card>- </TabsContent>+/**+ * The savings half of the page, once there is a report to render.+ *+ * `available: false` is a semantic state, not a load state: a repository that+ * has never served an agent legitimately has no savings, and saying so is a+ * different claim from a measured zero.+ */+function SavingsSections({ data }: { data: SavingsView }) {+ if (!data.available) {+ return (+ <EmptyState+ title="No agent savings recorded yet"+ // Plain text: EmptyState renders its description as a string, so+ // backticks would print as backticks.+ description="Route noisy commands through repowise distill, or install the rewrite hook with repowise hook rewrite install. Savings appear here on their own once an agent starts using this repository."+ />+ );+ }- {/* Cache analytics aren't wired to real data yet; the tab shows the- real per-call efficiency numbers as a compact stat strip. */}- <TabsContent value="efficiency" className="mt-4">- {summary ? (- <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">- <MetricCard- label="Avg input / call"- value={- summary.total_calls > 0- ? Math.round(summary.total_input_tokens / summary.total_calls).toLocaleString()- : "—"- }- />- <MetricCard- label="Avg output / call"- value={- summary.total_calls > 0- ? Math.round(summary.total_output_tokens / summary.total_calls).toLocaleString()- : "—"- }- />- <MetricCard- label="Avg cost / call"- value={- summary.total_calls > 0- ? formatCost(summary.total_cost_usd / summary.total_calls)- : "—"- }- />- </div>- ) : summaryError ? (- <ApiError- title="Couldn't load efficiency"- onRetry={() => void retrySummary()}- />- ) : (- <StatGridSkeleton count={3} />- )}- </TabsContent>+ const opportunities = buildOpportunities(data, {+ distillDocsHref: DISTILL_DOCS_HREF,+ });- <TabsContent value="hotspots" className="mt-4">- {opError ? (- <ApiError title="Couldn't load hotspots" onRetry={() => void retryOp()} />- ) : opGroups ? (- <CostHeatmap- groups={opGroups.map((g) => ({ group: g.group, cost_usd: g.cost_usd, calls: g.calls }))}- title="Cost concentration by operation"- emptyHint="No operation-level data yet."- />- ) : (- // Heatmap cell heights are data-driven, so there is no height to- // match. Reserve the floor and let it grow rather than asserting- // a number that is wrong for every repo but one.- <SkeletonRegion label="Loading hotspots">- <Skeleton className="min-h-40 w-full" />- </SkeletonRegion>- )}- </TabsContent>+ const surfaces = data.per_surface.map((row) => ({+ label: surfaceLabel(row.group),+ events: row.events,+ savedInputTokens: row.saved_input_tokens,+ }));- <TabsContent value="providers" className="mt-4">- {modelError ? (- <ApiError title="Couldn't load providers" onRetry={() => void retryModel()} />- ) : modelGroups ? (- <ProviderComparison modelGroups={modelGroups} />- ) : (- <SkeletonRegion label="Loading providers">- <Skeleton className="min-h-40 w-full" />- </SkeletonRegion>- )}- </TabsContent>+ return (+ <>+ <SavingsLede data={data} methodologyHref={METHODOLOGY_HREF} LinkComponent={Link} />- <TabsContent value="operations" className="mt-4">- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Spend by operation</CardTitle>- </CardHeader>- <CardContent className="pt-0">- {opError ? (- <ApiError- title="Couldn't load spend by operation"- onRetry={() => void retryOp()}- />- ) : opGroups ? (- <OperationBreakdown groups={opGroups} />- ) : (- // The chart's own floor, from its own formula: the row count- // is unknown until the data lands, and the chart only grows- // from here.- <ChartSkeleton- height={operationBreakdownHeight(0)}- label="Loading spend by operation"- />- )}- </CardContent>- </Card>- </TabsContent>- </Tabs>+ <OverviewSection+ title="Savings by source"+ description="Which capture surface produced each part of the total."+ >+ <SavingsSourceTable+ rows={surfaces}+ total={data.saved_input_tokens}+ nameHeader="Surface"+ caption="Savings by the surface that produced them"+ empty={+ <p className="text-sm text-[var(--color-text-secondary)]">+ No savings in this window carry a surface.+ </p>+ }+ />+ </OverviewSection>- {/* Indexing / generation cost — deliberately secondary to the savings- hero above. */}- <div className="space-y-2">- <p className="text-xs font-medium uppercase tracking-wide text-[var(--color-text-tertiary)]">- Indexing & generation cost- </p>- {loadingSummary ? (- <StatGridSkeleton- count={4}- columns="grid-cols-2 sm:grid-cols-4"- description- />- ) : summaryError ? (- <ApiError- title="Couldn't load generation cost"- onRetry={() => void retrySummary()}- />- ) : summary ? (- <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">- <MetricCard- label="Indexing cost"- value={formatCost(summary.total_cost_usd)}- description="across all generation runs"- icon={<DollarSign className="h-4 w-4 text-[var(--color-success)]" />}- />- <MetricCard- label="Total Calls"- value={formatNumber(summary.total_calls)}- description="LLM API calls"- />- <MetricCard- label="Input Tokens"- value={formatTokens(summary.total_input_tokens)}- description="prompt tokens"- />- <MetricCard- label="Output Tokens"- value={formatTokens(summary.total_output_tokens)}- description="completion tokens"- />- </div>- ) : null}- </div>- </PageShell>+ {opportunities.length > 0 && (+ <OverviewSection+ title="Observed opportunities"+ description="Behaviour that could have been optimised and was not. Never part of the total above."+ >+ <OpportunityList items={opportunities} LinkComponent={Link} />+ </OverviewSection>+ )}++ <OverviewSection+ title="Details"+ description="The same savings, cut by day, operation, pricing model and agent."+ >+ <UsageDetails data={data} />+ </OverviewSection>+ </>+ );+}++/**+ * The savings-reset disclosure, shown once per repository and accounting+ * version.+ *+ * The host owns visibility and persistence; the shared component owns the+ * copy. Starts hidden and reveals after the storage read, so a reader who+ * dismissed this months ago never sees it flash back on every navigation.+ *+ * After dismissal the reset is still disclosed: the lede keeps a permanent+ * coverage date and a methodology link beside the figure they qualify.+ */+function ResetNotice({ repoId }: { repoId: string }) {+ const [visible, setVisible] = useState(false);++ // No `typeof window` guard: an effect never runs during SSR, so the guard+ // was dead code implying a hazard that is not there.+ useEffect(() => {+ try {+ setVisible(!window.localStorage.getItem(resetNoticeKey(repoId)));+ } catch {+ // Storage unavailable (private mode, blocked site data). Show it: an+ // explanation shown twice is better than a restarted total never+ // explained.+ setVisible(true);+ }+ }, [repoId]);++ const dismiss = useCallback(() => {+ try {+ window.localStorage.setItem(resetNoticeKey(repoId), "1");+ } catch {+ // Storage unavailable, so the dismissal cannot be remembered and the+ // notice returns on the next mount. Hiding it here is still right: the+ // reader asked for it to go away now.+ }+ setVisible(false);+ }, [repoId]);++ if (!visible) return null;++ return (+ <SavingsResetNotice+ onDismiss={dismiss}+ methodologyHref={METHODOLOGY_HREF}+ LinkComponent={Link}+ />);}