Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(chat): render tables and charts from view parts in the web chat (#3780)

Raghav Chamadiya7694591e35b0
diff --git a/package-lock.json b/package-lock.json
index 737631556..0f73047ad 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -494,6 +494,7 @@
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -8861,16 +8862,6 @@
"license": "MIT",
"peer": true
},
- "node_modules/dom-helpers": {
- "version": "5.2.1",
- "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
- "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
- "license": "MIT",
- "dependencies": {
- "@babel/runtime": "^7.8.7",
- "csstype": "^3.0.2"
- }
- },
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
@@ -10063,15 +10054,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/fast-equals": {
- "version": "5.4.1",
- "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.4.1.tgz",
- "integrity": "sha512-DjlFSM5Pk9cGcL0q5QXl66eGzx0N6szNgaswwc5ZphlBohjTVJSnGgI+rJVOgOi65qUoQnDZN4nDqi33udtydQ==",
- "license": "MIT",
- "engines": {
- "node": ">=6.0.0"
- }
- },
"node_modules/fast-glob": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz",
@@ -12629,6 +12611,7 @@
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
+ "dev": true,
"license": "MIT"
},
"node_modules/lodash-es": {
@@ -12731,6 +12714,7 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
@@ -14663,6 +14647,7 @@
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -15478,6 +15463,7 @@
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"loose-envify": "^1.4.0",
@@ -15489,6 +15475,7 @@
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "dev": true,
"license": "MIT"
},
"node_modules/property-information": {
@@ -15747,21 +15734,6 @@
}
}
},
- "node_modules/react-smooth": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
- "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",
- "license": "MIT",
- "dependencies": {
- "fast-equals": "^5.0.1",
- "prop-types": "^15.8.1",
- "react-transition-group": "^4.4.5"
- },
- "peerDependencies": {
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
- }
- },
"node_modules/react-style-singleton": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",
@@ -15784,22 +15756,6 @@
}
}
},
- "node_modules/react-transition-group": {
- "version": "4.4.5",
- "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
- "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",
- "license": "BSD-3-Clause",
- "dependencies": {
- "@babel/runtime": "^7.5.5",
- "dom-helpers": "^5.0.1",
- "loose-envify": "^1.4.0",
- "prop-types": "^15.6.2"
- },
- "peerDependencies": {
- "react": ">=16.6.0",
- "react-dom": ">=16.6.0"
- }
- },
"node_modules/read": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz",
@@ -15912,15 +15868,6 @@
"react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
- "node_modules/recharts-scale": {
- "version": "0.4.5",
- "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz",
- "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==",
- "license": "MIT",
- "dependencies": {
- "decimal.js-light": "^2.4.1"
- }
- },
"node_modules/recma-build-jsx": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/recma-build-jsx/-/recma-build-jsx-1.0.0.tgz",
@@ -19568,7 +19515,6 @@
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
- "recharts": "^2.13.0",
"remark-gfm": "^4.0.1",
"shiki": "^1.22.0",
"sonner": "^2.0.7",
@@ -19665,12 +19611,6 @@
"undici-types": "~6.21.0"
}
},
- "packages/web/node_modules/eventemitter3": {
- "version": "4.0.7",
- "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
- "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
- "license": "MIT"
- },
"packages/web/node_modules/lucide-react": {
"version": "0.460.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.460.0.tgz",
@@ -19691,36 +19631,6 @@
"regex-recursion": "^5.1.1"
}
},
- "packages/web/node_modules/react-is": {
- "version": "18.3.1",
- "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
- "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
- "license": "MIT"
- },
- "packages/web/node_modules/recharts": {
- "version": "2.15.4",
- "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz",
- "integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==",
- "deprecated": "1.x and 2.x branches are no longer active. Bump to Recharts v3 to receive latest features and bugfixes. See https://github.com/recharts/recharts/wiki/3.0-migration-guide",
- "license": "MIT",
- "dependencies": {
- "clsx": "^2.0.0",
- "eventemitter3": "^4.0.1",
- "lodash": "^4.17.21",
- "react-is": "^18.3.1",
- "react-smooth": "^4.0.4",
- "recharts-scale": "^0.4.4",
- "tiny-invariant": "^1.3.1",
- "victory-vendor": "^36.6.8"
- },
- "engines": {
- "node": ">=14"
- },
- "peerDependencies": {
- "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
- }
- },
"packages/web/node_modules/regex": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/regex/-/regex-5.1.1.tgz",
@@ -19772,28 +19682,6 @@
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
- },
- "packages/web/node_modules/victory-vendor": {
- "version": "36.9.2",
- "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",
- "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==",
- "license": "MIT AND ISC",
- "dependencies": {
- "@types/d3-array": "^3.0.3",
- "@types/d3-ease": "^3.0.0",
- "@types/d3-interpolate": "^3.0.1",
- "@types/d3-scale": "^4.0.2",
- "@types/d3-shape": "^3.1.0",
- "@types/d3-time": "^3.0.0",
- "@types/d3-timer": "^3.0.0",
- "d3-array": "^3.1.6",
- "d3-ease": "^3.0.1",
- "d3-interpolate": "^3.0.1",
- "d3-scale": "^4.0.2",
- "d3-shape": "^3.1.0",
- "d3-time": "^3.0.0",
- "d3-timer": "^3.0.1"
- }
}
}
}
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index 23a998c09..da5fb72e6 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -176,6 +176,8 @@ export interface ChatUIMessage {
followUps?: ChatSuggestion[];
/** Validated evidence cards for this turn. */
cards?: EvidenceCard[];
+ /** Validated view parts for this turn, in the order they were built. */
+ views?: ViewPart[];
}
// ---------------------------------------------------------------------------
diff --git a/packages/ui/__tests__/chat/view-part.test.tsx b/packages/ui/__tests__/chat/view-part.test.tsx
new file mode 100644
index 000000000..3d628fe38
--- /dev/null
+++ b/packages/ui/__tests__/chat/view-part.test.tsx
@@ -0,0 +1,223 @@
+import { cloneElement, type ReactElement } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import type { ChatUIMessage } from "@repowise-dev/types/chat";
+import type { ChartView, SectionView, TableView, ViewPart } from "@repowise-dev/types/views";
+import fixture from "../../../types/fixtures/views.conformance.json";
+import { ViewPartList } from "../../src/chat/view-part.js";
+import { ChatMessage } from "../../src/chat/chat-message.js";
+
+// jsdom has no layout, so a ResponsiveContainer never measures. Give the plot
+// a fixed box so the chart draws its SVG.
+vi.mock("recharts", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("recharts")>();
+ return {
+ ...actual,
+ ResponsiveContainer: ({ children }: { children: ReactElement<{ width?: number; height?: number }> }) =>
+ cloneElement(children, { width: 480, height: 220 }),
+ };
+});
+
+const valid = fixture.valid as unknown as Record<string, ViewPart>;
+const TABLE = valid.t1 as TableView;
+const BAR = valid.c1 as ChartView;
+const STACKED = valid.c2 as ChartView;
+const LINE = valid.c3 as ChartView;
+const DONUT = valid.c4 as ChartView;
+const SECTION = valid.s1 as SectionView;
+
+const href = (ref: { type: string; id: string }) => `/repos/r1/${ref.type}/${ref.id}`;
+
+function part(id: string) {
+ return document.querySelector(`[data-view-id="${id}"]`) as HTMLElement;
+}
+
+describe("ViewPartList", () => {
+ it("draws a chart as SVG with its title and summary, its table closed", () => {
+ render(<ViewPartList views={[BAR]} buildRefHref={href} />);
+
+ const figure = part("c1");
+ expect(figure).toHaveAttribute("data-chart-type", "bar");
+ expect(figure.querySelector("figcaption")).toHaveTextContent("Changes by component");
+ expect(figure.querySelector("figcaption")).toHaveTextContent(BAR.summary);
+ expect(figure.querySelector("svg.recharts-surface")).not.toBeNull();
+
+ const toggle = within(figure).getByRole("button", { name: "Data" });
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ const data = figure.querySelector("[data-view-data]") as HTMLElement;
+ expect(toggle).toHaveAttribute("aria-controls", data.id);
+ expect(data).toHaveClass("hidden");
+ });
+
+ it("opens the plotted table from the data toggle, refs as links", () => {
+ render(<ViewPartList views={[BAR]} buildRefHref={href} />);
+ const figure = part("c1");
+
+ const toggle = within(figure).getByRole("button", { name: "Data" });
+ fireEvent.click(toggle);
+
+ // The label stays put; aria-expanded carries the state.
+ expect(toggle).toHaveTextContent(/^Data$/);
+ expect(toggle).toHaveAttribute("aria-expanded", "true");
+ const data = figure.querySelector("[data-view-data]") as HTMLElement;
+ expect(data).not.toHaveClass("hidden");
+ const table = within(data).getByRole("table");
+ expect(within(table).getAllByRole("row")).toHaveLength(4);
+ expect(within(table).getByRole("link", { name: "payments" })).toHaveAttribute(
+ "href",
+ "/repos/r1/component/payments",
+ );
+ expect(within(table).getByText("12")).toHaveClass("tabular-nums");
+ });
+
+ it("keeps the toggle off paper and prints every chart with its table", () => {
+ render(<ViewPartList views={[BAR]} />);
+ const figure = part("c1");
+
+ expect(within(figure).getByRole("button", { name: "Data" })).toHaveClass("print:hidden");
+ expect(figure.querySelector("[data-view-data]")).toHaveClass("print:block");
+ expect(figure).toHaveClass("print:break-inside-avoid");
+ });
+
+ it("shows basis, coverage, truncation and the index commit under a table", () => {
+ render(<ViewPartList views={[TABLE]} buildRefHref={href} />);
+ const figure = part("t1");
+ const line = figure.querySelector("[data-view-provenance]") as HTMLElement;
+
+ expect(line).toHaveTextContent("Measured · git history");
+ expect(line).toHaveTextContent("get_health");
+ expect(line).toHaveTextContent("Test reach coverage 75%");
+ expect(line).toHaveTextContent("Showing 2 of 3 rows");
+ expect(line).toHaveTextContent("as of 4c1e31f");
+ expect(line.querySelector("[data-view-stale]")).toBeNull();
+ // A table part is its own data: no toggle.
+ expect(within(figure).queryByRole("button")).toBeNull();
+ expect(within(figure).getByRole("columnheader", { name: "Health (score)" })).toBeInTheDocument();
+ expect(within(figure).getByRole("columnheader", { name: "Commits, 90 days" })).toBeInTheDocument();
+ expect(within(figure).getByText("none")).toHaveClass("sr-only");
+ });
+
+ it("names every series in a legend and flags a stale index", () => {
+ render(<ViewPartList views={[STACKED, LINE]} />);
+
+ expect(within(part("c2")).getByRole("list")).toHaveTextContent("Measured");
+ expect(within(part("c2")).getByRole("list")).toHaveTextContent("Inferred");
+ expect(part("c3").querySelector("[data-view-stale]")).toHaveTextContent(
+ "Index behind the code it read",
+ );
+ });
+
+ it("plots five series and points to the data table for the rest", () => {
+ const keys = ["s1", "s2", "s3", "s4", "s5", "s6", "s7"];
+ const { sort: _sort, ...unsorted } = BAR;
+ const wide: ChartView = {
+ ...unsorted,
+ id: "w1",
+ data: {
+ columns: [
+ { key: "component", label: "Component" },
+ ...keys.map((key) => ({ key, label: key.toUpperCase(), unit: "changes" })),
+ ],
+ rows: [
+ { component: "auth", ...Object.fromEntries(keys.map((k, i) => [k, i + 1])) },
+ { component: "search", ...Object.fromEntries(keys.map((k, i) => [k, i + 2])) },
+ ],
+ total_rows: 2,
+ truncated: false,
+ },
+ series: keys,
+ };
+ render(<ViewPartList views={[wide]} />);
+ const figure = part("w1");
+ const legend = within(figure).getByRole("list");
+
+ expect(within(legend).getAllByRole("listitem")).toHaveLength(6);
+ expect(legend).toHaveTextContent("S5");
+ expect(legend).not.toHaveTextContent("S6");
+ expect(legend.querySelector("[data-view-undrawn]")).toHaveTextContent("2 more series in the data table");
+ expect(figure.querySelectorAll(".recharts-bar")).toHaveLength(5);
+ // The table keeps every series.
+ expect(within(figure).getAllByRole("columnheader")).toHaveLength(8);
+ });
+
+ it("separates stacked segments with a seam and lines with dashes", () => {
+ const lines: ChartView = { ...STACKED, id: "l2", chart_type: "line" };
+ render(<ViewPartList views={[STACKED, lines]} />);
+
+ const segment = part("c2").querySelector(".recharts-bar-rectangle path");
+ expect(segment).toHaveAttribute("stroke", "var(--color-bg-surface)");
+ const dashes = [...part("l2").querySelectorAll(".recharts-line-curve")].map((el) =>
+ el.getAttribute("stroke-dasharray"),
+ );
+ expect(dashes).toHaveLength(2);
+ expect(new Set(dashes).size).toBe(2);
+ });
+
+ it("draws nothing for a donut with no series instead of failing", () => {
+ render(<ViewPartList views={[{ ...DONUT, id: "d0", series: [] }]} />);
+
+ expect(part("d0").querySelector("svg.recharts-surface")).toBeNull();
+ expect(within(part("d0")).queryByRole("list")).toBeNull();
+ });
+
+ it("labels each donut part with its value", () => {
+ render(<ViewPartList views={[DONUT]} />);
+ const items = within(part("c4")).getAllByRole("listitem");
+
+ expect(items).toHaveLength(DONUT.data.rows.length);
+ const [first] = DONUT.data.rows;
+ expect(items[0]).toHaveTextContent(String(first![DONUT.series[0]!]));
+ });
+
+ it("renders a section's parts inside it only, with narrative citing them", () => {
+ render(<ViewPartList views={[TABLE, BAR, SECTION]} />);
+
+ const section = part("s1");
+ expect(section.tagName).toBe("SECTION");
+ expect(within(section).getByRole("heading", { name: SECTION.title })).toBeInTheDocument();
+ expect(document.querySelectorAll('[data-view-id="t1"]')).toHaveLength(1);
+ expect(document.querySelectorAll('[data-view-id="c1"]')).toHaveLength(1);
+ expect(section.contains(part("c1"))).toBe(true);
+ const cite = within(section).getByRole("link", { name: `See ${BAR.title}` });
+ expect(cite.getAttribute("href")).toBe(`#${part("c1").id}`);
+ });
+
+ it("gives repeated view ids page-unique anchors across turns", () => {
+ render(
+ <>
+ <ViewPartList views={[BAR]} />
+ <ViewPartList views={[BAR]} />
+ </>,
+ );
+ const ids = [...document.querySelectorAll('[data-view-id="c1"]')].map((el) => el.id);
+ expect(new Set(ids).size).toBe(2);
+ });
+});
+
+describe("ChatMessage views", () => {
+ const message: ChatUIMessage = {
+ id: "a1",
+ role: "assistant",
+ text: "Payments changed most.",
+ toolCalls: [],
+ isStreaming: true,
+ views: [BAR],
+ };
+
+ it("renders a view while the answer is still streaming", () => {
+ render(<ChatMessage message={message} repoId="r1" />);
+
+ expect(part("c1")).toBeInTheDocument();
+ expect(screen.getByText("Payments changed most.")).toBeInTheDocument();
+ });
+
+ it("links ref cells to the dashboard", () => {
+ render(<ChatMessage message={{ ...message, isStreaming: false }} repoId="r1" />);
+ fireEvent.click(screen.getByRole("button", { name: "Data" }));
+
+ // Components have no dashboard page, so the ref stays text.
+ const table = within(part("c1")).getByRole("table");
+ expect(within(table).queryByRole("link")).toBeNull();
+ expect(within(table).getByText("payments")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/cards/evidence-card.tsx b/packages/ui/src/cards/evidence-card.tsx
index 3260c5199..d57389853 100644
--- a/packages/ui/src/cards/evidence-card.tsx
+++ b/packages/ui/src/cards/evidence-card.tsx
@@ -44,7 +44,7 @@ export function cardRefHref(ref: CardRef, prefix: string): string | undefined {
}
}
-function refLabel(ref: CardRef): string {
+export function refLabel(ref: CardRef): string {
const name =
ref.type === "file"
? (ref.id.split("/").pop() ?? ref.id)
@@ -74,9 +74,9 @@ function subject(card: EvidenceCard): string | CardRef {
}
}
-type RefHref = (ref: CardRef) => string | undefined;
+export type RefHref = (ref: CardRef) => string | undefined;
-function RefView({ cardRef, buildRefHref }: { cardRef: CardRef; buildRefHref?: RefHref | undefined }) {
+export function RefView({ cardRef, buildRefHref }: { cardRef: CardRef; buildRefHref?: RefHref | undefined }) {
const href = buildRefHref?.(cardRef);
const label = refLabel(cardRef);
const className = "font-mono text-xs [overflow-wrap:anywhere]";
@@ -96,7 +96,7 @@ function RefView({ cardRef, buildRefHref }: { cardRef: CardRef; buildRefHref?: R
}
/** Basis is spelled out, never colour-coded, so it reads the same in every theme. */
-function BasisNote({ basis }: { basis: CardBasis }) {
+export function BasisNote({ basis }: { basis: CardBasis }) {
return (
<span data-card-basis={basis.kind} className="text-xs text-[var(--color-text-tertiary)]">
<span className="sr-only">Basis: </span>
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index 81304f70c..2756bb310 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -337,10 +337,12 @@ export function ChatInterface({
const column = cn("mx-auto w-full", dock ? "max-w-full px-4" : "max-w-[720px] px-[var(--page-pad)]");
return (
- <div className="flex h-full min-h-0 flex-col" data-chat-variant={variant}>
+ // Printed, the transcript is the document: chrome and composer drop out
+ // and the scroll region unclips so the answer flows across pages.
+ <div className="flex h-full min-h-0 flex-col print:block print:h-auto" data-chat-variant={variant}>
{/* Header controls. Always mounted at a fixed height so the transcript
never shifts when the first artifact arrives. */}
- <div className={cn("flex h-11 shrink-0 items-center justify-between gap-2", dock ? "px-3" : "px-[var(--page-pad)]")}>
+ <div className={cn("flex h-11 shrink-0 items-center justify-between gap-2 print:hidden", dock ? "px-3" : "px-[var(--page-pad)]")}>
<div className="flex min-w-0 items-center gap-2">{historySlot}</div>
<Button
variant="ghost"
@@ -396,9 +398,9 @@ export function ChatInterface({
</ScrollArea>
) : (
<ScrollArea
- className="h-full"
+ className="h-full print:h-auto print:overflow-visible"
viewportRef={viewportRef}
- viewportClassName={cn(VIEWPORT_BLOCK, "[overflow-anchor:auto]")}
+ viewportClassName={cn(VIEWPORT_BLOCK, "[overflow-anchor:auto] print:h-auto print:overflow-visible!")}
>
<div
ref={contentRef}
@@ -461,7 +463,7 @@ export function ChatInterface({
aria-pressed={isFollowingLive}
aria-label="Jump to latest"
title="Jump to latest"
- className="absolute bottom-3 left-1/2 z-10 flex h-8 w-8 -translate-x-1/2 items-center justify-center rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] text-[var(--color-text-secondary)] shadow-[var(--shadow-sm)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ className="absolute bottom-3 left-1/2 z-10 flex h-8 w-8 print:hidden -translate-x-1/2 items-center justify-center rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] text-[var(--color-text-secondary)] shadow-[var(--shadow-sm)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
<ArrowDown className="h-4 w-4" />
</button>
@@ -474,7 +476,7 @@ export function ChatInterface({
<div
className={cn(
- "shrink-0",
+ "shrink-0 print:hidden",
dock ? "pb-3 pt-1" : "pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-2",
)}
>
diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsx
index 58d839db8..289c85bbf 100644
--- a/packages/ui/src/chat/chat-message.tsx
+++ b/packages/ui/src/chat/chat-message.tsx
@@ -9,6 +9,7 @@ import { CHAT_STAGES, chatStage } from "./chat-stage";
import { Markdown } from "../shared/markdown";
import { SourceCitations, type SourceReference } from "./source-citations";
import { EvidenceCardList, cardRefHref } from "../cards/evidence-card";
+import { ViewPartList } from "./view-part";
import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
interface ChatMessageProps {
@@ -95,16 +96,26 @@ function ChatMessageImpl({
)}
<div className={cn("max-w-full", dock ? "space-y-2.5" : "space-y-3")}>
{message.toolCalls.length > 0 && (
- <ToolCallGroup
- toolCalls={message.toolCalls}
- {...(onViewArtifact ? { onViewArtifact } : {})}
- />
+ <div className="print:hidden">
+ <ToolCallGroup
+ toolCalls={message.toolCalls}
+ {...(onViewArtifact ? { onViewArtifact } : {})}
+ />
+ </div>
)}
{message.text && (
<Markdown content={message.text} density={dock ? "narrow" : "reading"} streaming={message.isStreaming} fill />
)}
+ {/* Views arrive live, each right after the call that built it. */}
+ {message.views && message.views.length > 0 && (
+ <ViewPartList
+ views={message.views}
+ buildRefHref={(ref) => cardRefHref(ref, linkPrefix ?? `/repos/${repoId}`)}
+ />
+ )}
+
{/* Only stored messages carry cards for now; the stream sends none. */}
{!message.isStreaming && message.cards && (
<EvidenceCardList
@@ -136,7 +147,7 @@ function ChatMessageImpl({
// the turn from thinking through each tool to writing.
<div
data-chat-stage={stage}
- className="flex min-h-8 items-center gap-2 text-xs text-[var(--color-text-tertiary)]"
+ className="flex min-h-8 print:hidden items-center gap-2 text-xs text-[var(--color-text-tertiary)]"
>
<WorkingOrb state={CHAT_STAGES[stage].state} />
<span>{CHAT_STAGES[stage].label}</span>
diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.ts
index 4086c250d..4245ab109 100644
--- a/packages/ui/src/chat/index.ts
+++ b/packages/ui/src/chat/index.ts
@@ -23,3 +23,4 @@ export * from "./source-citation";
export * from "./source-citations";
export * from "./tool-call-block";
export * from "./tool-call-group";
+export * from "./view-part";
diff --git a/packages/ui/src/chat/message-actions.tsx b/packages/ui/src/chat/message-actions.tsx
index efaad9c57..30331c100 100644
--- a/packages/ui/src/chat/message-actions.tsx
+++ b/packages/ui/src/chat/message-actions.tsx
@@ -60,7 +60,7 @@ export function MessageActions({
};
return (
- <div className="mt-2 space-y-1.5">
+ <div className="mt-2 space-y-1.5 print:hidden">
{error && <ErrorNotice error={error} onRetry={onRetry} />}
{message.text && (
<div
@@ -110,7 +110,7 @@ function MessageEditForm({
}) {
return (
<form
- className="mt-2 w-full space-y-2"
+ className="mt-2 w-full space-y-2 print:hidden"
onSubmit={(event) => {
event.preventDefault();
const text = draft.trim();
diff --git a/packages/ui/src/chat/tool-call-block.tsx b/packages/ui/src/chat/tool-call-block.tsx
index eb6f702ea..9795a2d9f 100644
--- a/packages/ui/src/chat/tool-call-block.tsx
+++ b/packages/ui/src/chat/tool-call-block.tsx
@@ -11,6 +11,7 @@ import { ArrowUpRight, ChevronRight } from "lucide-react";
import { cn } from "../lib/cn";
import { HighlightedCodeBlock } from "../shared/code-block";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
+import { SHOW_VIEW_TOOL } from "@repowise-dev/types/views";
const TOOL_LABELS: Record<string, string> = {
get_overview: "Getting codebase overview",
@@ -23,6 +24,7 @@ const TOOL_LABELS: Record<string, string> = {
search_codebase: "Searching codebase",
get_dead_code: "Checking dead code",
get_answer: "Asking the index",
+ [SHOW_VIEW_TOOL]: "Building a view",
};
/** A step the server took for the page, before the model's first turn. */
diff --git a/packages/ui/src/chat/view-part.tsx b/packages/ui/src/chat/view-part.tsx
new file mode 100644
index 000000000..d94c8e893
--- /dev/null
+++ b/packages/ui/src/chat/view-part.tsx
@@ -0,0 +1,474 @@
+"use client";
+
+/**
+ * Chat view parts: the tables, charts and report sections a server-side
+ * builder made from a tool result of the turn. The renderer draws exactly the
+ * rows it is given: every chart keeps a text summary, a "Data" toggle opens
+ * the table it plots, and the line under each part names where the values
+ * came from. On paper the toggle goes and every chart prints with its table.
+ */
+
+import { useId, useState, type ReactNode } from "react";
+import {
+ Bar,
+ BarChart,
+ CartesianGrid,
+ Cell,
+ Line,
+ LineChart,
+ Pie,
+ PieChart,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from "recharts";
+import type { CardRef } from "@repowise-dev/types/cards";
+import type {
+ ChartView,
+ SectionView,
+ TableView,
+ ViewCell,
+ ViewColumn,
+ ViewPart,
+ ViewTableData,
+} from "@repowise-dev/types/views";
+import { BasisNote, RefView, refLabel, type RefHref } from "../cards/evidence-card";
+import { cn } from "../lib/cn";
+
+/**
+ * Series fills in fixed order, never cycled: the share steps, ink stepped
+ * toward the well, each clearing 3:1 on the page and a card. No hue, so a
+ * series never reads as navigation, model work or a health verdict. Only
+ * five clear the floor, so a chart plots its first five series and the
+ * legend points to the data table for the rest.
+ */
+const SERIES_FILLS = [
+ "var(--color-share-1)",
+ "var(--color-share-2)",
+ "var(--color-share-3)",
+ "var(--color-share-4)",
+ "var(--color-share-5)",
+] as const;
+/** Lines differ by dash as well as lightness, one pattern per fill. */
+const LINE_DASHES = ["", "6 3", "2 3", "8 3 2 3", "1 2"] as const;
+
+const seriesFill = (i: number): string => SERIES_FILLS[Math.min(i, SERIES_FILLS.length - 1)]!;
+const lineDash = (i: number): string => LINE_DASHES[Math.min(i, LINE_DASHES.length - 1)]!;
+/** The series a chart draws; the rest stay in its data table. */
+const drawnSeries = (view: ChartView): string[] => view.series.slice(0, SERIES_FILLS.length);
+
+const COVERAGE_LABEL: Record<string, string> = {
+ attribution: "Attribution coverage",
+ test_reach: "Test reach coverage",
+};
+
+const AXIS_TICK = { fill: "var(--color-text-tertiary)", fontSize: 10 };
+const TOOLTIP_STYLE = {
+ background: "var(--color-bg-overlay)",
+ border: "1px solid var(--color-border-default)",
+ borderRadius: 6,
+ fontSize: 12,
+ color: "var(--color-text-primary)",
+};
+const X_KEY = "__label";
+const BAR_ROW_PX = 24;
+const PLOT_PX = 220;
+
+const isRef = (cell: ViewCell): cell is CardRef => typeof cell === "object" && cell !== null;
+
+function cellText(cell: ViewCell): string {
+ if (cell === null) return "";
+ return isRef(cell) ? refLabel(cell) : String(cell);
+}
+
+/** "Changes (commits)", unless the label already names its unit. */
+function columnHeading(column: ViewColumn): string {
+ const unit = column.unit;
+ return unit && !column.label.toLowerCase().includes(unit.toLowerCase())
+ ? `${column.label} (${unit})`
+ : column.label;
+}
+
+function short(text: string, max = 22): string {
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
+}
+
+interface PartProps {
+ buildRefHref?: RefHref | undefined;
+ /** Page-unique DOM id for a part id; view ids repeat across turns. */
+ domId: (partId: string) => string;
+}
+
+function CellText({ cell, buildRefHref }: { cell: ViewCell; buildRefHref?: RefHref | undefined }) {
+ if (cell === null) {
+ return (
+ <span className="text-[var(--color-text-tertiary)]">
+ <span aria-hidden>–</span>
+ <span className="sr-only">none</span>
+ </span>
+ );
+ }
+ if (isRef(cell)) return <RefView cardRef={cell} buildRefHref={buildRefHref} />;
+ return <>{String(cell)}</>;
+}
+
+export function ViewTable({
+ data,
+ caption,
+ buildRefHref,
+}: {
+ data: ViewTableData;
+ /** Accessible name; the visible title sits on the part. */
+ caption: string;
+ buildRefHref?: RefHref | undefined;
+}) {
+ return (
+ <div className="max-w-full overflow-x-auto print:overflow-visible">
+ <table className="w-full border-collapse text-xs">
+ <caption className="sr-only">{caption}</caption>
+ <thead>
+ <tr className="border-b border-[var(--color-border-default)]">
+ {data.columns.map((column) => (
+ <th
+ key={column.key}
+ scope="col"
+ title={column.basis ? `${column.basis.kind} · ${column.basis.source}` : undefined}
+ className="px-2 py-1.5 text-left font-medium text-[var(--color-text-secondary)] first:pl-0"
+ >
+ {columnHeading(column)}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {data.rows.map((row, i) => (
+ <tr key={i} className="border-b border-[var(--color-border-default)] last:border-0 print:break-inside-avoid">
+ {data.columns.map((column) => {
+ const cell = row[column.key] ?? null;
+ return (
+ <td
+ key={column.key}
+ className={cn(
+ "px-2 py-1.5 align-top text-[var(--color-text-primary)] first:pl-0",
+ typeof cell === "number" && "text-right tabular-nums",
+ )}
+ >
+ <CellText cell={cell} buildRefHref={buildRefHref} />
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
+
+/** Where the values came from, in one quiet line. */
+function ProvenanceLine({ part }: { part: TableView | ChartView }) {
+ const table: ViewTableData = part.kind === "chart" ? part.data : part;
+ const coverage = part.coverage;
+ return (
+ <p data-view-provenance="" className="flex flex-wrap gap-x-2 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">
+ <BasisNote basis={part.basis} />
+ <span>· {part.source.tool_name}</span>
+ {coverage && (
+ <span data-view-coverage={coverage.metric}>
+ · {COVERAGE_LABEL[coverage.metric] ?? coverage.metric} {Math.round(coverage.ratio * 100)}%
+ </span>
+ )}
+ {table.truncated && (
+ <span data-view-truncated="">
+ · Showing {table.rows.length} of {table.total_rows} rows
+ </span>
+ )}
+ {part.as_of && (
+ <span title={part.as_of} className="font-mono">
+ · as of {part.as_of.slice(0, 7)}
+ </span>
+ )}
+ {part.stale && <span data-view-stale="">· Index behind the code it read</span>}
+ </p>
+ );
+}
+
+function legendItems(view: ChartView): Array<{ label: string; fill: string; value?: ViewCell }> {
+ if (view.chart_type === "donut") {
+ const key = view.series[0];
+ if (key === undefined) return [];
+ return view.data.rows.map((row, i) => ({
+ label: cellText(row[view.x] ?? null),
+ fill: seriesFill(i),
+ value: row[key] ?? null,
+ }));
+ }
+ if (view.series.length < 2) return [];
+ const labels = new Map(view.data.columns.map((c) => [c.key, c.label]));
+ return drawnSeries(view).map((key, i) => ({ label: labels.get(key) ?? key, fill: seriesFill(i) }));
+}
+
+function ChartLegend({ view }: { view: ChartView }) {
+ const items = legendItems(view);
+ const undrawn = view.chart_type === "donut" ? 0 : view.series.length - drawnSeries(view).length;
+ if (items.length === 0) return null;
+ return (
+ <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-[var(--color-text-secondary)]">
+ {items.map((item, i) => (
+ <li key={i} className="inline-flex items-center gap-1.5">
+ {view.chart_type === "line" ? (
+ <svg aria-hidden width="16" height="6" className="shrink-0">
+ <line x1="0" y1="3" x2="16" y2="3" stroke={item.fill} strokeWidth="2" strokeDasharray={lineDash(i)} />
+ </svg>
+ ) : (
+ <span aria-hidden className="h-2.5 w-2.5 shrink-0 rounded-sm" style={{ background: item.fill }} />
+ )}
+ <span>{item.label}</span>
+ {item.value !== undefined && (
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">{cellText(item.value)}</span>
+ )}
+ </li>
+ ))}
+ {undrawn > 0 && (
+ <li data-view-undrawn={undrawn} className="text-[var(--color-text-tertiary)]">
+ {undrawn} more series in the data table
+ </li>
+ )}
+ </ul>
+ );
+}
+
+function ChartPlot({ view }: { view: ChartView }) {
+ const series = drawnSeries(view);
+ const labels = new Map(view.data.columns.map((c) => [c.key, c.label]));
+ const rows = view.data.rows.map((row) => {
+ const point: Record<string, string | number | null> = { [X_KEY]: cellText(row[view.x] ?? null) };
+ for (const key of series) {
+ const value = row[key];
+ point[key] = typeof value === "number" ? value : null;
+ }
+ return point;
+ });
+ const tooltip = (
+ <Tooltip
+ cursor={{ fill: "var(--color-bg-elevated)" }}
+ contentStyle={TOOLTIP_STYLE}
+ formatter={(value, name) => [String(value), labels.get(String(name)) ?? String(name)]}
+ />
+ );
+
+ if (view.chart_type === "donut") {
+ const key = series[0];
+ if (key === undefined) return null;
+ return (
+ <div style={{ height: 180 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <PieChart>
+ <Pie
+ data={rows}
+ dataKey={key}
+ nameKey={X_KEY}
+ innerRadius="55%"
+ outerRadius="85%"
+ stroke="var(--color-bg-root)"
+ isAnimationActive={false}
+ >
+ {rows.map((_, i) => (
+ <Cell key={i} fill={seriesFill(i)} />
+ ))}
+ </Pie>
+ {tooltip}
+ </PieChart>
+ </ResponsiveContainer>
+ </div>
+ );
+ }
+
+ if (view.chart_type === "line") {
+ return (
+ <div style={{ height: PLOT_PX }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <LineChart data={rows} margin={{ top: 8, right: 12, bottom: 0, left: -12 }}>
+ <CartesianGrid stroke="var(--color-border-default)" vertical={false} />
+ <XAxis dataKey={X_KEY} tick={AXIS_TICK} axisLine={false} tickLine={false} tickFormatter={(v: string) => short(v, 14)} />
+ <YAxis tick={AXIS_TICK} axisLine={false} tickLine={false} />
+ {tooltip}
+ {series.map((key, i) => (
+ <Line
+ key={key}
+ type="monotone"
+ dataKey={key}
+ stroke={seriesFill(i)}
+ strokeDasharray={lineDash(i)}
+ strokeWidth={2}
+ dot={rows.length <= 24}
+ connectNulls={false}
+ isAnimationActive={false}
+ />
+ ))}
+ </LineChart>
+ </ResponsiveContainer>
+ </div>
+ );
+ }
+
+ // Bars run horizontally: their categories are components and paths, which
+ // read along a row and not under a column.
+ const stacked = view.chart_type === "stacked_bar";
+ return (
+ <div style={{ height: Math.max(96, rows.length * BAR_ROW_PX + 32) }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <BarChart data={rows} layout="vertical" margin={{ top: 4, right: 16, bottom: 0, left: 0 }}>
+ <CartesianGrid stroke="var(--color-border-default)" horizontal={false} />
+ <XAxis type="number" tick={AXIS_TICK} axisLine={false} tickLine={false} />
+ <YAxis
+ type="category"
+ dataKey={X_KEY}
+ tick={{ ...AXIS_TICK, fill: "var(--color-text-secondary)", fontSize: 11 }}
+ axisLine={false}
+ tickLine={false}
+ width={140}
+ interval={0}
+ tickFormatter={(v: string) => short(v)}
+ />
+ {tooltip}
+ {series.map((key, i) => (
+ <Bar
+ key={key}
+ dataKey={key}
+ fill={seriesFill(i)}
+ // A surface-coloured seam keeps stacked segments apart beyond their lightness.
+ {...(stacked ? { stackId: "parts", stroke: "var(--color-bg-surface)", strokeWidth: 1 } : {})}
+ maxBarSize={18}
+ isAnimationActive={false}
+ />
+ ))}
+ </BarChart>
+ </ResponsiveContainer>
+ </div>
+ );
+}
+
+function PartFrame({
+ part,
+ domId,
+ children,
+}: {
+ part: TableView | ChartView;
+ domId: (partId: string) => string;
+ children: ReactNode;
+}) {
+ return (
+ <figure
+ id={domId(part.id)}
+ data-view-kind={part.kind}
+ data-view-id={part.id}
+ {...(part.kind === "chart" ? { "data-chart-type": part.chart_type } : {})}
+ className="m-0 space-y-2 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 print:break-inside-avoid print:border-0 print:p-0"
+ >
+ <figcaption className="space-y-0.5">
+ <span className="block text-sm font-medium text-[var(--color-text-primary)]">{part.title}</span>
+ {part.summary && <span className="block text-sm text-[var(--color-text-secondary)]">{part.summary}</span>}
+ </figcaption>
+ {children}
+ <ProvenanceLine part={part} />
+ </figure>
+ );
+}
+
+function ChartPart({ view, buildRefHref, domId }: PartProps & { view: ChartView }) {
+ const [showData, setShowData] = useState(false);
+ const tableId = `${domId(view.id)}-data`;
+ return (
+ <PartFrame part={view} domId={domId}>
+ <ChartLegend view={view} />
+ {/* The chart is a picture of the table below; the summary is its text. */}
+ <div aria-hidden>
+ <ChartPlot view={view} />
+ </div>
+ <button
+ type="button"
+ aria-expanded={showData}
+ aria-controls={tableId}
+ onClick={() => setShowData((open) => !open)}
+ className="inline-flex min-h-8 items-center rounded-md text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] print:hidden"
+ >
+ Data
+ </button>
+ {/* Always mounted so print shows it; hidden on screen until asked for. */}
+ <div id={tableId} data-view-data="" className={cn(!showData && "hidden print:block")}>
+ <ViewTable data={view.data} caption={view.title} buildRefHref={buildRefHref} />
+ </div>
+ </PartFrame>
+ );
+}
+
+function TablePart({ view, buildRefHref, domId }: PartProps & { view: TableView }) {
+ return (
+ <PartFrame part={view} domId={domId}>
+ <ViewTable data={view} caption={view.title} buildRefHref={buildRefHref} />
+ </PartFrame>
+ );
+}
+
+function DataPart({ view, ...props }: PartProps & { view: TableView | ChartView }) {
+ return view.kind === "chart" ? <ChartPart view={view} {...props} /> : <TablePart view={view} {...props} />;
+}
+
+function SectionPart({
+ section,
+ parts,
+ ...props
+}: PartProps & { section: SectionView; parts: Map<string, TableView | ChartView> }) {
+ return (
+ <section data-view-kind="section" data-view-id={section.id} className="space-y-3">
+ <h3 className="text-base font-semibold text-[var(--color-text-primary)] print:break-after-avoid">{section.title}</h3>
+ {section.summary && <p className="text-sm text-[var(--color-text-secondary)]">{section.summary}</p>}
+ {section.narrative.map((block, i) => (
+ <p key={i} className="text-sm leading-relaxed text-[var(--color-text-primary)]">
+ {block.text}
+ {block.cites.map((id) => (
+ <a
+ key={id}
+ href={`#${props.domId(id)}`}
+ aria-label={`See ${parts.get(id)?.title ?? id}`}
+ className="ml-1 align-super text-[10px] text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {id}
+ </a>
+ ))}
+ </p>
+ ))}
+ {section.view_ids.map((id) => {
+ const part = parts.get(id);
+ return part ? <DataPart key={id} view={part} {...props} /> : null;
+ })}
+ </section>
+ );
+}
+
+/**
+ * A turn's parts in order. A data part a section shows renders inside that
+ * section only; the others render where they stand.
+ */
+export function ViewPartList({ views, buildRefHref }: { views: ViewPart[]; buildRefHref?: RefHref }) {
+ const scope = useId();
+ if (views.length === 0) return null;
+ const domId = (partId: string) => `view-${scope.replace(/:/g, "")}-${partId}`;
+ const data = new Map<string, TableView | ChartView>();
+ const inSection = new Set<string>();
+ for (const part of views) {
+ if (part.kind === "section") part.view_ids.forEach((id) => inSection.add(id));
+ else data.set(part.id, part);
+ }
+ const props = { buildRefHref, domId };
+ return (
+ <div data-view-list="" className="space-y-3">
+ {views.map((part) => {
+ if (part.kind === "section") return <SectionPart key={part.id} section={part} parts={data} {...props} />;
+ return inSection.has(part.id) ? null : <DataPart key={part.id} view={part} {...props} />;
+ })}
+ </div>
+ );
+}
diff --git a/packages/web/package.json b/packages/web/package.json
index 5fee17cb8..dd70c14b5 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -32,7 +32,6 @@
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
- "recharts": "^2.13.0",
"remark-gfm": "^4.0.1",
"shiki": "^1.22.0",
"sonner": "^2.0.7",
diff --git a/packages/web/src/app/layout.tsx b/packages/web/src/app/layout.tsx
index 4f00b3423..fbae21849 100644
--- a/packages/web/src/app/layout.tsx
+++ b/packages/web/src/app/layout.tsx
@@ -96,15 +96,17 @@ export default async function RootLayout({
<TooltipProvider delayDuration={300}>
<Suspense fallback={<AppShellSkeleton />}>
<ContextDrawerShell>
- <div className="flex h-screen flex-col overflow-hidden">
+ {/* Printed, the shell unclips so a long page (a chat
+ transcript) flows across sheets instead of one viewport. */}
+ <div className="flex h-screen flex-col overflow-hidden print:block print:h-auto print:overflow-visible">
<UpgradeBanner />
- <div className="flex flex-1 overflow-hidden">
+ <div className="flex flex-1 overflow-hidden print:block print:overflow-visible">
<Sidebar
repos={repos}
workspace={workspace}
reposUnavailable={reposUnavailable}
/>
- <div className="flex flex-1 flex-col min-w-0 overflow-hidden">
+ <div className="flex flex-1 flex-col min-w-0 overflow-hidden print:block print:overflow-visible">
<MobileNav repos={repos} workspace={workspace} />
{/* A flex column, so anything a route layout stacks above
the page (repo breadcrumb, reindex hint, active-job
@@ -118,7 +120,7 @@ export default async function RootLayout({
it could not be clicked. */}
<main
id="main-content"
- className="relative flex flex-1 flex-col overflow-auto min-w-0"
+ className="relative flex flex-1 flex-col overflow-auto min-w-0 print:block print:overflow-visible"
>
{children}
</main>
diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsx
index c3c7430b1..ed3e87509 100644
--- a/packages/web/src/components/layout/mobile-nav.tsx
+++ b/packages/web/src/components/layout/mobile-nav.tsx
@@ -74,7 +74,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
}, [pathname]);
return (
- <div className="flex md:hidden min-h-14 items-center gap-3 px-4 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0">
+ <div className="flex md:hidden print:hidden min-h-14 items-center gap-3 px-4 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0">
<Button
variant="ghost"
size="icon"
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index cbd84a409..2b794557f 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -116,7 +116,7 @@ export function Sidebar({
return (
<aside
className={cn(
- "hidden md:flex h-full flex-col border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0 motion-safe:transition-all motion-safe:duration-200",
+ "hidden md:flex print:hidden h-full flex-col border-r border-[var(--color-border-default)] bg-[var(--color-bg-surface)] shrink-0 motion-safe:transition-all motion-safe:duration-200",
isIconOnly ? "w-[56px]" : "w-[280px]",
)}
>
diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.test.ts b/packages/web/src/lib/chat/to-chat-ui-messages.test.ts
index b8ba33a50..a335f3b0d 100644
--- a/packages/web/src/lib/chat/to-chat-ui-messages.test.ts
+++ b/packages/web/src/lib/chat/to-chat-ui-messages.test.ts
@@ -1,9 +1,10 @@
import { describe, expect, it } from "vitest";
import type { ChatMessageResponse } from "@/lib/api/types";
import { toChatUiMessages } from "./to-chat-ui-messages";
+import fixture from "../../../../types/fixtures/views.conformance.json";
describe("toChatUiMessages", () => {
- it("hides a stored show_view call and tolerates stored views", () => {
+ it("keeps a stored show_view call as a step with no artifact, and restores valid views", () => {
const stored: ChatMessageResponse[] = [
{
id: "m1",
@@ -14,15 +15,31 @@ describe("toChatUiMessages", () => {
{ id: "t1", name: "get_risk", result: { score: 1 } },
{ id: "t2", name: "show_view", result: { view_id: "v1" } },
],
- views: [{ id: "v1", kind: "table" }],
+ views: [fixture.valid.c1, { id: "v1", kind: "table" }],
},
created_at: "2026-10-14T00:00:00Z",
},
];
- expect(toChatUiMessages(stored)[0]?.toolCalls.map((call) => call.name)).toEqual([
- "get_risk",
- ]);
+ const [message] = toChatUiMessages(stored);
+ expect(message?.toolCalls.map((call) => call.name)).toEqual(["get_risk", "show_view"]);
+ expect(message?.toolCalls[1]).not.toHaveProperty("artifact");
+ expect(message?.toolCalls[0]?.artifact).toBeDefined();
+ expect(message?.views?.map((view) => view.id)).toEqual(["c1"]);
+ });
+
+ it("leaves a turn with no valid views without the field", () => {
+ const stored: ChatMessageResponse[] = [
+ {
+ id: "m1",
+ conversation_id: "c1",
+ role: "assistant",
+ content: { text: "x", views: [{ id: "v1", kind: "table" }] },
+ created_at: "2026-10-14T00:00:00Z",
+ },
+ ];
+
+ expect(toChatUiMessages(stored)[0]).not.toHaveProperty("views");
});
it.each([
diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.ts
index e730704df..026386ee2 100644
--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts
+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts
@@ -2,7 +2,7 @@ import type { ChatMessageResponse } from "@/lib/api/types";
import type { ChatUIMessage } from "@repowise-dev/types/chat";
import { getLegacyChatArtifactType } from "@repowise-dev/ui/chat";
import { parseEvidenceCards } from "@repowise-dev/api-client/cards";
-import { SHOW_VIEW_TOOL } from "@repowise-dev/types/views";
+import { SHOW_VIEW_TOOL, parseViewParts } from "@repowise-dev/api-client/views";
/** Stored cards are untrusted wire data; only the ones that validate render. */
function storedCards(message: ChatMessageResponse): Pick<ChatUIMessage, "cards"> {
@@ -10,6 +10,12 @@ function storedCards(message: ChatMessageResponse): Pick<ChatUIMessage, "cards">
return cards.length ? { cards } : {};
}
+/** Stored views are untrusted wire data too; same rule as the live stream. */
+function storedViews(message: ChatMessageResponse): Pick<ChatUIMessage, "views"> {
+ const views = parseViewParts(message.content.views);
+ return views.length ? { views } : {};
+}
+
/** Normalize stored API messages into the same shape produced while streaming. */
export function toChatUiMessages(
messages: ChatMessageResponse[],
@@ -19,16 +25,17 @@ export function toChatUiMessages(
serverId: message.id,
role: message.role,
text: message.content.text ?? "",
- // A show_view call is plumbing for a view, not a read; it is not shown.
toolCalls: (message.content.tool_calls ?? [])
- .filter((toolCall) => toolCall.name !== SHOW_VIEW_TOOL)
.map((toolCall) => ({
id: toolCall.id,
name: toolCall.name,
arguments: toolCall.arguments ?? {},
result: toolCall.result,
summary: toolCall.summary,
- ...(toolCall.artifact
+ // A show_view receipt is not evidence; the view itself renders inline.
+ ...(toolCall.name === SHOW_VIEW_TOOL
+ ? {}
+ : toolCall.artifact
? { artifact: toolCall.artifact }
: toolCall.result
? {
@@ -68,5 +75,6 @@ export function toChatUiMessages(
? { followUps: message.content.follow_ups }
: {}),
...storedCards(message),
+ ...storedViews(message),
}));
}
diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsx
index 27b150657..e3f10ecea 100644
--- a/packages/web/src/lib/hooks/use-chat.test.tsx
+++ b/packages/web/src/lib/hooks/use-chat.test.tsx
@@ -3,6 +3,7 @@
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useChat } from "./use-chat";
+import fixture from "../../../../types/fixtures/views.conformance.json";
const mocks = vi.hoisted(() => ({
signal: undefined as AbortSignal | undefined,
@@ -394,17 +395,22 @@ describe("useChat grounding and truncation events", () => {
expect(result.current.error).toBeNull();
});
- it("shows no step for a show_view call and ignores its view event", async () => {
+ it("shows a show_view call as a step and puts its view on the answer", async () => {
+ const view = fixture.valid.c1;
+ const receipt = { view_id: "c1", kind: "chart", title: view.title };
const push = streamed([
- { type: "tool_start", tool_id: "t2", tool_name: "show_view", input: {} },
+ { type: "tool_start", tool_id: "t2", tool_name: "show_view", input: { view: "table" } },
{
type: "tool_result",
tool_id: "t2",
tool_name: "show_view",
- summary: "show_view",
- artifact: { ...artifact, id: "art-2", tool_name: "show_view", data: { view_id: "v1" } },
+ summary: "Built a chart",
+ artifact: { ...artifact, id: "art-2", tool_name: "show_view", data: receipt },
},
- { type: "view", tool_id: "t2", view: { id: "v1", kind: "table" } },
+ { type: "view", tool_id: "t2", view },
+ // A repeat id and a part that does not validate are both dropped.
+ { type: "view", tool_id: "t2", view },
+ { type: "view", tool_id: "t3", view: { id: "v9", kind: "table" } },
{ type: "done", conversation_id: "c1", message_id: "m1" },
]);
const { result } = renderHook(() => useChat("r1"));
@@ -415,8 +421,49 @@ describe("useChat grounding and truncation events", () => {
await sending;
});
- expect(result.current.messages.at(-1)?.toolCalls).toEqual([]);
- expect(result.current.messages.at(-1)?.isStreaming).toBe(false);
+ const answer = result.current.messages.at(-1);
+ expect(answer?.toolCalls).toEqual([
+ {
+ id: "t2",
+ name: "show_view",
+ arguments: { view: "table" },
+ result: receipt,
+ summary: "Built a chart",
+ status: "done",
+ },
+ ]);
+ expect(answer?.views?.map((part) => part.id)).toEqual(["c1"]);
+ expect(answer?.isStreaming).toBe(false);
expect(result.current.error).toBeNull();
});
+
+ it("marks a refused show_view step as failed and adds no view", async () => {
+ const push = streamed([
+ { type: "tool_start", tool_id: "t2", tool_name: "show_view", input: {} },
+ {
+ type: "tool_result",
+ tool_id: "t2",
+ tool_name: "show_view",
+ summary: "Error: insufficient coverage",
+ artifact: {
+ ...artifact,
+ id: "art-2",
+ tool_name: "show_view",
+ data: { error: "insufficient coverage", error_code: "insufficient_coverage" },
+ },
+ },
+ { type: "done", conversation_id: "c1", message_id: "m1" },
+ ]);
+ const { result } = renderHook(() => useChat("r1"));
+
+ await act(async () => {
+ const sending = result.current.sendMessage("chart it");
+ await push();
+ await sending;
+ });
+
+ const answer = result.current.messages.at(-1);
+ expect(answer?.toolCalls[0]?.status).toBe("error");
+ expect(answer).not.toHaveProperty("views");
+ });
});
diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.ts
index a9b8c03fb..9383a4856 100644
--- a/packages/web/src/lib/hooks/use-chat.ts
+++ b/packages/web/src/lib/hooks/use-chat.ts
@@ -9,7 +9,7 @@ import type {
ChatUIToolCall as ChatToolCall,
ChatUIMessage as ChatMessage,
} from "@repowise-dev/types/chat";
-import { SHOW_VIEW_TOOL } from "@repowise-dev/types/views";
+import { SHOW_VIEW_TOOL, parseViewParts } from "@repowise-dev/api-client/views";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
import { toChatUiMessages } from "@/lib/chat/to-chat-ui-messages";
@@ -245,9 +245,6 @@ export function useChat(repoId: string) {
};
case "tool_start":
- // Views have no renderer yet; without a row here the
- // matching tool_result and view events are no-ops too.
- if (ev.tool_name === SHOW_VIEW_TOOL) return m;
return {
...m,
toolCalls: [
@@ -277,7 +274,8 @@ export function useChat(repoId: string) {
...tc,
result: data,
summary: ev.summary,
- artifact: ev.artifact,
+ // A show_view receipt is not evidence; the view itself renders inline.
+ ...(ev.tool_name === SHOW_VIEW_TOOL ? {} : { artifact: ev.artifact }),
status: failed ? ("error" as const) : ("done" as const),
}
: tc,
@@ -285,6 +283,12 @@ export function useChat(repoId: string) {
};
}
+ case "view": {
+ // Wire data: only a part that validates, once per id, renders.
+ const views = parseViewParts([...(m.views ?? []), ev.view]);
+ return views.length > (m.views?.length ?? 0) ? { ...m, views } : m;
+ }
+
case "truncated":
return { ...m, truncated: true };