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): calm single-column chat with stage-aware progress (#3313)

Raghav Chamadiya8e309d593c51
diff --git a/packages/ui/__tests__/chat/artifacts.test.tsx b/packages/ui/__tests__/chat/artifacts.test.tsx
index 022e785b9..a2afbcf0d 100644
--- a/packages/ui/__tests__/chat/artifacts.test.tsx
+++ b/packages/ui/__tests__/chat/artifacts.test.tsx
@@ -70,7 +70,7 @@ describe("chat artifact renderers", () => {
/>,
);
expect(screen.getByText("src/hot.ts")).toBeInTheDocument();
- expect(screen.getByText("hotspot")).toBeInTheDocument();
+ expect(screen.getByText("Hotspot")).toBeInTheDocument();
expect(screen.getByText("src/other.ts")).toBeInTheDocument();
expect(screen.getByText(/99th pct/)).toBeInTheDocument();
expect(screen.getByText("88th")).toBeInTheDocument();
@@ -98,7 +98,7 @@ describe("chat artifact renderers", () => {
/>,
);
expect(screen.getByText("src/auth.py")).toBeInTheDocument();
- expect(screen.getByText("hotspot")).toBeInTheDocument();
+ expect(screen.getByText("Hotspot")).toBeInTheDocument();
expect(screen.getByText("src/db.py")).toBeInTheDocument();
expect(screen.getByText(/91th pct/)).toBeInTheDocument();
expect(screen.getByText("85th")).toBeInTheDocument();
diff --git a/packages/ui/__tests__/chat/chat-interface.test.tsx b/packages/ui/__tests__/chat/chat-interface.test.tsx
index 2388b7f57..b9b9778b8 100644
--- a/packages/ui/__tests__/chat/chat-interface.test.tsx
+++ b/packages/ui/__tests__/chat/chat-interface.test.tsx
@@ -239,7 +239,7 @@ describe("ChatInterface shell", () => {
expect(screen.getByTestId("model-slot")).toBeInTheDocument();
expect(screen.getByTestId("history-slot")).toBeInTheDocument();
const model = screen.getByTestId("model-slot");
- const shortcut = screen.getByText("Shift+Enter for newline");
+ const shortcut = screen.getByText("Enter to send · Shift+Enter for newline");
expect(model.compareDocumentPosition(shortcut) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(screen.getByRole("button", { name: "Send message" }).className).not.toContain("accent-fill");
});
@@ -259,4 +259,70 @@ describe("ChatInterface shell", () => {
expect(screen.getByRole("status")).toHaveTextContent("Answer complete.");
expect(screen.getByRole("status")).not.toHaveTextContent("First second");
});
+
+ it("keeps the empty state lean: no logo, no shortcut hint, at most four suggestions", () => {
+ const { container } = render(
+ <ChatInterface repoId="r1" messages={[]} isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />,
+ );
+ expect(container.querySelector("img")).toBeNull();
+ expect(screen.queryByText(/Press \? from any page/)).toBeNull();
+ const group = screen.getByRole("group", { name: "Suggested questions" });
+ expect(group.querySelectorAll("button")).toHaveLength(4);
+ // One hint, inside the composer.
+ expect(screen.getAllByText(/Shift\+Enter for newline/)).toHaveLength(1);
+ });
+
+ it("holds the header row in place before any artifact arrives", () => {
+ const view = render(
+ <ChatInterface repoId="r1" messages={[USER_MSG, ASSISTANT_MSG]} isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />,
+ );
+ const hidden = view.container.querySelector('button[aria-hidden="true"]');
+ expect(hidden?.className).toContain("invisible");
+ expect(screen.queryByRole("button", { name: /Artifacts/ })).toBeNull();
+ });
+
+ it("shows the disabled reason inside the composer instead of a warning box", () => {
+ const { container } = render(
+ <ChatInterface
+ repoId="r1"
+ messages={[]}
+ isStreaming={false}
+ onSend={vi.fn()}
+ onCancel={vi.fn()}
+ sendDisabled
+ sendDisabledReason={<span>No chat provider is configured.</span>}
+ />,
+ );
+ const composer = container.querySelector("[data-chat-composer]");
+ expect(composer).toHaveTextContent("No chat provider is configured.");
+ expect(container.innerHTML).not.toContain("color-warning");
+ expect(screen.getByRole("button", { name: "Send message" })).toBeDisabled();
+ });
+
+ it("puts a failed answer's error and Retry on the answer itself", () => {
+ const onRetry = vi.fn();
+ render(
+ <ChatInterface
+ repoId="r1"
+ messages={[USER_MSG, { ...ASSISTANT_MSG, text: "" }]}
+ isStreaming={false}
+ error="The provider timed out."
+ onRetry={onRetry}
+ onSend={vi.fn()}
+ onCancel={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("alert")).toHaveTextContent("The provider timed out.");
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ });
+
+ it("fills the send button only when there is text", () => {
+ render(<ChatInterface repoId="r1" messages={[]} isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />);
+ const send = screen.getByRole("button", { name: "Send message" });
+ expect(send.className).not.toContain("accent-fill");
+ fireEvent.change(screen.getByLabelText("Chat message"), { target: { value: "hi" } });
+ expect(send.className).toContain("accent-fill");
+ expect(send.className).toContain("rounded-full");
+ });
});
diff --git a/packages/ui/__tests__/chat/chat-message.test.tsx b/packages/ui/__tests__/chat/chat-message.test.tsx
index 2766d3404..5b96081c8 100644
--- a/packages/ui/__tests__/chat/chat-message.test.tsx
+++ b/packages/ui/__tests__/chat/chat-message.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { render, screen, fireEvent } from "@testing-library/react";
import { ChatMessage } from "../../src/chat/chat-message.js";
import type { ChatUIMessage } from "@repowise-dev/types/chat";
@@ -30,15 +30,78 @@ describe("ChatMessage", () => {
).toBeNull();
});
- it("renders the user on the opposite side with a neutral identity surface", () => {
- render(<ChatMessage message={USER} repoId="r1" />);
+ it("renders the user on the opposite side as a borderless bubble with no label or avatar", () => {
+ const { container } = render(<ChatMessage message={USER} repoId="r1" />);
const turn = screen.getByRole("article", { name: "You" });
- expect(turn.className).toContain("justify-end");
+ expect(turn.className).toContain("items-end");
expect(turn).toHaveAttribute("data-chat-role", "user");
- expect(screen.getByText("You")).toBeInTheDocument();
- expect(screen.getByText("Where is auth handled?").className).toContain(
- "bg-[var(--color-bg-surface)]",
+ expect(screen.queryByText("You")).toBeNull();
+ expect(container.querySelector("img, svg.lucide-user-round")).toBeNull();
+ const bubble = screen.getByText("Where is auth handled?");
+ expect(bubble.className).toContain("bg-[var(--color-bg-elevated)]");
+ expect(bubble.className).not.toContain("border");
+ });
+
+ it("renders the answer without a label or avatar", () => {
+ const { container } = render(<ChatMessage message={ASSISTANT} repoId="r1" />);
+ expect(screen.queryByText("Repowise")).toBeNull();
+ expect(container.querySelector("img")).toBeNull();
+ });
+
+ it("names the model only when it changed from the previous answer", () => {
+ const withModel = { ...ASSISTANT, provider: "anthropic", model: "claude" };
+ const view = render(<ChatMessage message={withModel} repoId="r1" />);
+ expect(screen.queryByText(/anthropic/)).toBeNull();
+ view.rerender(<ChatMessage message={withModel} repoId="r1" modelChanged />);
+ expect(screen.getByText(/Model changed to anthropic · claude/)).toBeInTheDocument();
+ });
+
+ it("offers copy and retry, with no canned follow up", () => {
+ render(<ChatMessage message={ASSISTANT} repoId="r1" isLatest onRetry={() => {}} />);
+ expect(screen.getByRole("button", { name: "Copy" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /follow up/i })).toBeNull();
+ // The newest answer never hides its actions behind hover.
+ const group = screen.getByRole("group", { name: "assistant message actions" });
+ expect(group.className).not.toContain("opacity-0");
+ });
+
+ it("reveals actions on hover or focus for older turns, never only on hover for touch", () => {
+ render(<ChatMessage message={ASSISTANT} repoId="r1" />);
+ const group = screen.getByRole("group", { name: "assistant message actions" });
+ expect(group.className).toContain("pointer-fine:opacity-0");
+ expect(group.className).toContain("group-focus-within/turn:opacity-100");
+ });
+
+ it("shows an inline error with Retry when the answer failed before any text", () => {
+ let retried = 0;
+ render(
+ <ChatMessage
+ message={{ ...ASSISTANT, text: "" }}
+ repoId="r1"
+ error="The provider rejected the request."
+ onRetry={() => {
+ retried += 1;
+ }}
+ />,
+ );
+ expect(screen.getByRole("alert")).toHaveTextContent("The provider rejected the request.");
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(retried).toBe(1);
+ });
+
+ it("resends an edit with the primary action, not the model colour", () => {
+ render(
+ <ChatMessage
+ message={{ ...USER, serverId: "s1" }}
+ repoId="r1"
+ onEditAndResend={() => {}}
+ />,
);
+ fireEvent.click(screen.getByRole("button", { name: "Edit and resend" }));
+ const submit = screen.getByRole("button", { name: "Fork and resend" });
+ expect(submit.className).toContain("accent-fill");
+ expect(submit.className).not.toContain("color-model");
});
it("renders assistant text as markdown", () => {
diff --git a/packages/ui/__tests__/chat/chat-stage.test.tsx b/packages/ui/__tests__/chat/chat-stage.test.tsx
new file mode 100644
index 000000000..4e167c6a9
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-stage.test.tsx
@@ -0,0 +1,67 @@
+import { describe, it, expect } from "vitest";
+import { render } from "@testing-library/react";
+import { ChatMessage } from "../../src/chat/chat-message.js";
+import { CHAT_STAGES, chatStage, chatToolKind } from "../../src/chat/chat-stage.js";
+import { ORB_STATE } from "../../src/shared/orb-loader.js";
+import type { ChatUIMessage, ChatUIToolCall } from "@repowise-dev/types/chat";
+
+const BASE: ChatUIMessage = {
+ id: "a1",
+ role: "assistant",
+ text: "",
+ toolCalls: [],
+ isStreaming: true,
+};
+
+function tool(name: string, status: ChatUIToolCall["status"]): ChatUIToolCall {
+ return { id: `${name}-${status}`, name, arguments: {}, status };
+}
+
+describe("chatToolKind", () => {
+ it("maps tools to the kind of wait they cause, unknown to working", () => {
+ expect(chatToolKind("search_codebase")).toBe("searching");
+ expect(chatToolKind("get_answer")).toBe("searching");
+ expect(chatToolKind("get_context")).toBe("tracing");
+ expect(chatToolKind("get_symbol")).toBe("tracing");
+ expect(chatToolKind("get_health")).toBe("working");
+ expect(chatToolKind("something_new")).toBe("working");
+ });
+});
+
+describe("chatStage", () => {
+ it("walks thinking, then the running tool's kind, then writing", () => {
+ expect(chatStage(BASE)).toBe("thinking");
+ expect(chatStage({ ...BASE, toolCalls: [tool("search_codebase", "running")] })).toBe("searching");
+ expect(chatStage({ ...BASE, toolCalls: [tool("get_context", "running")] })).toBe("tracing");
+ expect(chatStage({ ...BASE, toolCalls: [tool("get_risk", "running")] })).toBe("working");
+ expect(chatStage({ ...BASE, toolCalls: [tool("get_risk", "done")] })).toBe("thinking");
+ expect(chatStage({ ...BASE, text: "Partial" })).toBe("writing");
+ expect(chatStage({ ...BASE, isStreaming: false, text: "Done" })).toBeNull();
+ });
+
+ it("uses the shared orb vocabulary", () => {
+ expect(CHAT_STAGES.thinking.state).toBe(ORB_STATE.thinking);
+ expect(CHAT_STAGES.searching.state).toBe(ORB_STATE.searching);
+ expect(CHAT_STAGES.tracing.state).toBe(ORB_STATE.tracing);
+ expect(CHAT_STAGES.working.state).toBe(ORB_STATE.working);
+ expect(CHAT_STAGES.writing.state).toBe(ORB_STATE.writing);
+ });
+});
+
+describe("ChatMessage stage marker", () => {
+ it("names the stage beside one orb and drops it once the answer completes", () => {
+ const view = render(
+ <ChatMessage message={{ ...BASE, toolCalls: [tool("search_codebase", "running")] }} repoId="r1" />,
+ );
+ const marker = view.container.querySelector("[data-chat-stage]");
+ expect(marker).toHaveAttribute("data-chat-stage", "searching");
+ expect(marker).toHaveTextContent("Searching the index");
+ expect(view.container.querySelectorAll('[data-working-orb="true"]')).toHaveLength(1);
+
+ view.rerender(<ChatMessage message={{ ...BASE, text: "Partial" }} repoId="r1" />);
+ expect(view.container.querySelector("[data-chat-stage]")).toHaveTextContent("Writing");
+
+ view.rerender(<ChatMessage message={{ ...BASE, text: "Done", isStreaming: false }} repoId="r1" />);
+ expect(view.container.querySelector("[data-chat-stage]")).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/chat/tool-call-group.test.tsx b/packages/ui/__tests__/chat/tool-call-group.test.tsx
index a68846ae8..ef9f08863 100644
--- a/packages/ui/__tests__/chat/tool-call-group.test.tsx
+++ b/packages/ui/__tests__/chat/tool-call-group.test.tsx
@@ -1,6 +1,7 @@
import { describe, it, expect } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
-import { ToolCallGroup } from "../../src/chat/tool-call-group.js";
+import { ToolCallGroup, summarizeToolCalls } from "../../src/chat/tool-call-group.js";
+import { readableToolName } from "../../src/chat/tool-call-block.js";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
function call(id: string, status: ChatUIToolCall["status"]): ChatUIToolCall {
@@ -32,13 +33,13 @@ describe("ToolCallGroup", () => {
toolCalls={[call("a", "done"), call("b", "done"), call("c", "done")]}
/>,
);
- fireEvent.click(screen.getByRole("button", { name: /Activity/ }));
+ fireEvent.click(screen.getByRole("button", { name: /3 searches/ }));
expect(shells(container)).toHaveLength(1);
});
- it("uses one calm working orb rather than orange spinners", () => {
- // Rule 10: a badge every row carries says nothing. Success is the default,
- // so only work in flight gets a marker.
+ it("marks no step with a spinner or success badge", () => {
+ // Rule 10: a badge every row carries says nothing. The live marker is the
+ // turn's stage orb, not one per tool row.
const { container: done } = render(
<ToolCallGroup toolCalls={[call("a", "done")]} />,
);
@@ -49,19 +50,51 @@ describe("ToolCallGroup", () => {
<ToolCallGroup toolCalls={[call("b", "running")]} />,
);
expect(running.querySelector(".animate-spin")).toBeNull();
- expect(running.querySelector('[data-working-orb="true"]')).not.toBeNull();
- expect(running.innerHTML).not.toContain("color-accent-primary");
+ expect(running.querySelector('[data-working-orb="true"]')).toBeNull();
+ expect(running.innerHTML).not.toContain("text-[var(--color-accent-primary)]");
});
- it("auto-expands while a step is running and reports the step count", () => {
- render(
+ it("summarises several steps in one quiet line without borders", () => {
+ const { container } = render(
<ToolCallGroup toolCalls={[call("a", "done"), call("b", "running")]} />,
);
- expect(screen.getByText(/Working/)).toBeInTheDocument();
- expect(screen.getByText(/2 steps/)).toBeInTheDocument();
- // Expanded without a click: both step labels are on screen.
+ const line = screen.getByRole("button", { name: /2 searches/ });
+ expect(line).toHaveAttribute("aria-expanded", "false");
+ expect(container.innerHTML).not.toContain("border");
+ expect(container.innerHTML).not.toContain("uppercase");
+ fireEvent.click(line);
expect(screen.getAllByText("Searching codebase")).toHaveLength(2);
});
+
+ it("serialises input and result into the shared 12px code block only when opened", () => {
+ const { container } = render(<ToolCallGroup toolCalls={[call("a", "done")]} />);
+ expect(container.querySelector("pre")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: /Searching codebase/ }));
+ expect(screen.getByText("Input")).toBeInTheDocument();
+ expect(screen.getByText("Result")).toBeInTheDocument();
+ expect(container.querySelector("[data-chat-selection]")?.className).toContain("text-xs");
+ expect(container.querySelector("pre code")?.textContent).toContain('"query": "auth"');
+ });
+
+ it("names unknown tools readably", () => {
+ expect(readableToolName("get_blast_radius")).toBe("Blast radius");
+ render(<ToolCallGroup toolCalls={[{ ...call("a", "done"), name: "get_blast_radius" }]} />);
+ expect(screen.getByText("Blast radius")).toBeInTheDocument();
+ });
+});
+
+describe("summarizeToolCalls", () => {
+ it("counts pages read, searches and checks", () => {
+ expect(
+ summarizeToolCalls([
+ { id: "1", name: "get_context", arguments: { targets: ["a", "b", "c"] }, status: "done" },
+ { id: "2", name: "get_symbol", arguments: {}, status: "done" },
+ { id: "3", name: "search_codebase", arguments: {}, status: "done" },
+ { id: "4", name: "search_codebase", arguments: {}, status: "error" },
+ { id: "5", name: "get_health", arguments: {}, status: "done" },
+ ]),
+ ).toBe("Read 4 pages · 2 searches · 1 check · 1 failed");
+ });
});
describe("ToolCallGroup grounding row", () => {
@@ -82,7 +115,7 @@ describe("ToolCallGroup grounding row", () => {
},
};
- it("renders a read made for the page as one quiet hairline row naming what was read", () => {
+ it("renders a read made for the page as one quiet row naming what was read", () => {
const { container } = render(<ToolCallGroup toolCalls={[grounding]} />);
expect(shells(container)).toHaveLength(1);
expect(screen.getByText("Read for this page")).toBeInTheDocument();
@@ -94,7 +127,7 @@ describe("ToolCallGroup grounding row", () => {
it("keeps the model's own steps under their tool labels", () => {
render(<ToolCallGroup toolCalls={[grounding, call("b", "done")]} />);
- fireEvent.click(screen.getByRole("button", { name: /Activity/ }));
+ fireEvent.click(screen.getByRole("button", { name: /Read 1 page · 1 search/ }));
expect(screen.getByText("Read for this page")).toBeInTheDocument();
expect(screen.getByText("Searching codebase")).toBeInTheDocument();
});
diff --git a/packages/ui/__tests__/shared/markdown.test.tsx b/packages/ui/__tests__/shared/markdown.test.tsx
index bef057d2c..ec3129858 100644
--- a/packages/ui/__tests__/shared/markdown.test.tsx
+++ b/packages/ui/__tests__/shared/markdown.test.tsx
@@ -115,4 +115,32 @@ describe("Markdown", () => {
expect(container.querySelectorAll("ul").length).toBeGreaterThan(1);
expect(container.querySelector('input[type="checkbox"]')).toBeChecked();
});
+
+ it("steps down to 14px for the dock without forcing a 640px table", () => {
+ const { container } = render(
+ <Markdown content={"Dock text.\n\n| File | Score |\n|---|---|\n| a.py | 4 |"} density="narrow" />,
+ );
+ expect(screen.getByText("Dock text.").className).toContain("text-sm");
+ const table = container.querySelector("table");
+ expect(table?.className).not.toContain("min-w-[640px]");
+ expect(table?.parentElement?.className).toContain("overflow-x-auto");
+ });
+
+ it("fills the host column when asked instead of capping prose at 72ch", () => {
+ const view = render(<Markdown content="Capped." />);
+ expect(screen.getByText("Capped.").className).toContain("max-w-[72ch]");
+ view.rerender(<Markdown content="Capped." fill />);
+ expect(screen.getByText("Capped.").className).toContain("max-w-full");
+ });
+
+ it("keeps a streamed code block mounted in its final frame when the answer completes", async () => {
+ const content = "```ts\nconst kept = true\n```";
+ const view = render(<Markdown content={content} streaming />);
+ const frame = view.container.querySelector("[data-chat-selection]");
+ expect(frame).not.toBeNull();
+ view.rerender(<Markdown content={content} />);
+ expect(view.container.querySelector("[data-chat-selection]")).toBe(frame);
+ await waitFor(() => expect(view.container.querySelector(".shiki")).not.toBeNull());
+ expect(view.container.querySelector("[data-chat-selection]")).toBe(frame);
+ });
});
diff --git a/packages/ui/src/chat/artifact-panel.tsx b/packages/ui/src/chat/artifact-panel.tsx
index 2be5e180f..2ad5cdf12 100644
--- a/packages/ui/src/chat/artifact-panel.tsx
+++ b/packages/ui/src/chat/artifact-panel.tsx
@@ -96,8 +96,8 @@ function ArtifactHeader({ artifact, comparing, onCompare, onPin, onOpenSource, o
return (
<header className="border-b border-[var(--color-border-default)] pb-4">
<div className="flex items-start justify-between gap-3">
- <div className="min-w-0"><h2 className="truncate text-sm font-semibold text-[var(--color-text-primary)]">{artifact.title || artifact.type}</h2><p className="mt-1 font-mono text-[10px] text-[var(--color-text-tertiary)]">{artifact.tool_name} · {artifact.id}</p></div>
- {artifact.pinned && <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">Pinned</span>}
+ <h2 className="min-w-0 text-[15px] font-semibold text-[var(--color-text-primary)] [overflow-wrap:anywhere]">{artifact.title || artifact.type}</h2>
+ {artifact.pinned && <span className="shrink-0 text-xs text-[var(--color-text-tertiary)]">Pinned</span>}
</div>
<div className="mt-3 flex flex-wrap items-center gap-x-1">
{onPin && <button type="button" aria-label={artifact.pinned ? "Unpin artifact" : "Pin artifact"} className={actionClass} onClick={() => { const next = !artifact.pinned; void Promise.resolve(onPin(artifact, next)).catch(() => setStatus("Artifact pin update failed.")); }}>{artifact.pinned ? <PinOff className="h-3.5 w-3.5" /> : <Pin className="h-3.5 w-3.5" />}<span>{artifact.pinned ? "Unpin" : "Pin"}</span></button>}
diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsx
index a31dab4ff..7aecc8b83 100644
--- a/packages/ui/src/chat/artifacts.tsx
+++ b/packages/ui/src/chat/artifacts.tsx
@@ -62,7 +62,7 @@ function SectionTitle({
children: React.ReactNode;
}) {
return (
- <div className="flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mb-2">
+ <div className="flex items-center gap-1.5 font-mono text-[10px] font-medium uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] mb-2">
<Icon className="h-3 w-3" />
<span>{children}</span>
</div>
@@ -71,7 +71,7 @@ function SectionTitle({
function FilePathChip({ path }: { path: string }) {
return (
- <span className="inline-flex items-center gap-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[10px] font-mono text-[var(--color-text-secondary)]">
+ <span className="inline-flex items-center gap-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs font-mono text-[var(--color-text-secondary)]">
<FileCode className="h-2.5 w-2.5 opacity-60" />
<span className="truncate max-w-[200px]" title={path}>
{path}
@@ -119,7 +119,7 @@ export function OverviewRenderer({ data }: { data: OverviewArtifactData }) {
{data.modules.slice(0, 12).map((m) => (
<span
key={m}
- className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-[10px] font-mono text-[var(--color-text-secondary)]"
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-1.5 py-0.5 text-xs font-mono text-[var(--color-text-secondary)]"
>
{m}
</span>
@@ -295,21 +295,21 @@ function ChangeFindingCard({ finding }: { finding: ChangeFindingRow }) {
<li className="rounded-lg border border-[var(--color-border-default)] p-2.5">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<SeverityMark severity={finding.severity as Severity} />
- <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
{finding.change} · {finding.dimension}
</span>
</div>
<p className="mt-1 text-xs text-[var(--color-text-primary)]">
{finding.reason}
</p>
- <p className="mt-0.5 truncate font-mono text-[10px] text-[var(--color-text-secondary)]">
+ <p className="mt-0.5 truncate font-mono text-xs text-[var(--color-text-secondary)]">
{finding.symbol ? `${finding.symbol} — ` : ""}
<span title={finding.path}>
{finding.path}
{lines}
</span>
</p>
- <p className="mt-1 text-[10px] text-[var(--color-text-secondary)]">
+ <p className="mt-1 text-xs text-[var(--color-text-secondary)]">
<span className="text-[var(--color-text-tertiary)]">Why this change: </span>
{finding.attribution.why}{" "}
<span className="uppercase tracking-wider">
@@ -318,7 +318,7 @@ function ChangeFindingCard({ finding }: { finding: ChangeFindingRow }) {
</p>
{finding.inspect && (
<p
- className="mt-1 truncate font-mono text-[10px] text-[var(--color-text-secondary)]"
+ className="mt-1 truncate font-mono text-xs text-[var(--color-text-secondary)]"
title={finding.inspect}
>
{finding.inspect}
@@ -362,7 +362,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
{directive && (
<div>
<p
- className={`text-[10px] font-medium uppercase tracking-wider ${tone.className}`}
+ className={`font-mono text-[10px] font-medium uppercase tracking-[0.12em] ${tone.className}`}
>
{tone.label}
</p>
@@ -373,7 +373,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
)}
{partial && delta && (
- <p role="status" className="text-[10px] text-[var(--color-warning)]">
+ <p role="status" className="text-xs text-[var(--color-warning)]">
{delta.explanation}
</p>
)}
@@ -392,7 +392,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
)}
{/* One compact context row, not a second dashboard. */}
- <dl className="flex flex-wrap gap-x-4 gap-y-1 border-t border-[var(--color-border-default)] pt-2 text-[10px]">
+ <dl className="flex flex-wrap gap-x-4 gap-y-1 border-t border-[var(--color-border-default)] pt-2 text-xs">
{data.ref && <ContextItem label="Change" value={String(data.ref)} />}
{pct !== null && <ContextItem label="Diff shape" value={`p${pct}`} />}
{data.review_priority && (
@@ -423,14 +423,14 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
fragile.length > 0 ||
data.classification) && (
<details>
- <summary className="cursor-pointer text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]">
+ <summary className="cursor-pointer text-xs text-[var(--color-text-tertiary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]">
More detail
</summary>
<div className="mt-2 space-y-2">
{directive?.next_actions?.length ? (
<div>
<SectionTitle icon={ArrowRight}>Next actions</SectionTitle>
- <ul className="space-y-0.5 text-[10px] text-[var(--color-text-secondary)]">
+ <ul className="space-y-0.5 text-xs text-[var(--color-text-secondary)]">
{directive.next_actions.map((action) => (
<li key={action}>{action}</li>
))}
@@ -440,7 +440,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
{runAll !== null && (
<p
role="status"
- className="text-[10px] text-[var(--color-warning)]"
+ className="text-xs text-[var(--color-warning)]"
>
Run every test{runAll ? `: ${runAll}` : ""}
</p>
@@ -450,7 +450,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
<SectionTitle icon={CheckCircle2}>
{runAll !== null ? "Run these first" : "Tests to run"}
</SectionTitle>
- <ul className="space-y-0.5 font-mono text-[10px] text-[var(--color-text-secondary)]">
+ <ul className="space-y-0.5 font-mono text-xs text-[var(--color-text-secondary)]">
{tests.slice(0, 10).map((test) => (
<li key={test} className="truncate" title={test}>
{test}
@@ -464,7 +464,7 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
<SectionTitle icon={GitBranch}>
Historically fragile files
</SectionTitle>
- <ul className="space-y-0.5 text-[10px] text-[var(--color-text-secondary)]">
+ <ul className="space-y-0.5 text-xs text-[var(--color-text-secondary)]">
{fragile.slice(0, 5).map((file) => (
<li key={file.path} className="flex justify-between gap-2">
<span className="truncate font-mono" title={file.path}>
@@ -499,17 +499,17 @@ function ChangeRiskCard({ data }: { data: RiskReportArtifactData }) {
</div>
)}
{data.diff_shape && (
- <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
{String(data.diff_shape)}
</p>
)}
{data.classification && (
- <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
{String(data.classification)}
</p>
)}
{data.warning && (
- <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
{String(data.warning)}
</p>
)}
@@ -557,20 +557,20 @@ export function RiskReportRenderer({ data }: { data: RiskReportArtifactData }) {
{t.file_path}
</span>
{t.is_hotspot && (
- <span className="inline-flex items-center gap-1 rounded bg-[var(--color-warning)]/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wider text-[var(--color-warning)]">
- <AlertTriangle className="h-2.5 w-2.5" /> hotspot
+ <span className="inline-flex items-center gap-1 text-xs font-medium text-[var(--color-warning)]">
+ <AlertTriangle className="h-3 w-3" /> Hotspot
</span>
)}
</div>
{typeof t.score === "number" && (
- <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5 tabular-nums">
+ <div className="text-xs text-[var(--color-text-tertiary)] mt-0.5 tabular-nums">
Hotspot {formatHotspotPct(t.score)} pct
{t.risk_type ? ` · ${t.risk_type}` : ""}
{t.trend ? ` · ${t.trend}` : ""}
</div>
)}
{t.risk_summary && (
- <p className="text-[10px] text-[var(--color-text-secondary)] mt-1 line-clamp-2">
+ <p className="text-xs text-[var(--color-text-secondary)] mt-1 line-clamp-2">
{t.risk_summary}
</p>
)}
@@ -592,7 +592,7 @@ export function RiskReportRenderer({ data }: { data: RiskReportArtifactData }) {
<span className="font-mono text-[var(--color-text-secondary)] truncate">
{h.path}
</span>
- <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)]">
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
{formatHotspotPct(h.score)}
</span>
</div>
@@ -637,7 +637,7 @@ export function SearchResultsRenderer({
<div className="text-xs font-medium text-[var(--color-text-primary)]">
{r.title}
</div>
- <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5">
+ <div className="text-xs text-[var(--color-text-tertiary)] mt-0.5">
{getPageTypeLabel(r.page_type)}
{typeof r.relevance_score === "number" && (
<> · score {(r.relevance_score as number).toFixed(2)}</>
@@ -739,7 +739,7 @@ function DecisionCards({
<h3 className="text-xs font-medium text-[var(--color-text-primary)]">
{r.title}
{r.status && (
- <span className="ml-1.5 text-[10px] font-normal text-[var(--color-text-tertiary)]">
+ <span className="ml-1.5 text-xs font-normal text-[var(--color-text-tertiary)]">
({r.status})
</span>
)}
@@ -834,7 +834,7 @@ export function DecisionsRenderer({ data }: { data: DecisionsArtifactData }) {
<li key={i} className="text-xs text-[var(--color-text-secondary)]">
<span className="truncate">{d.title}</span>
{d.source && (
- <span className="ml-1.5 text-[10px] text-[var(--color-text-tertiary)]">
+ <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">
({d.source})
</span>
)}
@@ -851,7 +851,7 @@ export function DecisionsRenderer({ data }: { data: DecisionsArtifactData }) {
<li key={i} className="text-xs text-[var(--color-text-secondary)]">
<span className="truncate">{d.title}</span>
{d.status && (
- <span className="ml-1.5 text-[10px] text-[var(--color-text-tertiary)]">
+ <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">
({d.status})
</span>
)}
@@ -896,7 +896,7 @@ export function DecisionsRenderer({ data }: { data: DecisionsArtifactData }) {
)}
<DecisionCards rows={rows} />
{data.origin_story?.primary_author && (
- <p className="text-[10px] text-[var(--color-text-tertiary)]">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
Primary author: {String(data.origin_story.primary_author)}
</p>
)}
@@ -950,7 +950,7 @@ export function DeadCodeRenderer({ data }: { data: DeadCodeArtifactData }) {
))}
</div>
{tier.truncated && (
- <p className="mt-1.5 text-[10px] text-[var(--color-text-tertiary)]">
+ <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">
{tier.findings.length} of {tier.count.toLocaleString()} shown
</p>
)}
@@ -974,11 +974,11 @@ function DeadCodeRow({
<span className="font-mono text-[var(--color-text-primary)] truncate">
{finding.symbol_name ? `${finding.file_path}::${finding.symbol_name}` : finding.file_path}
</span>
- <span className="text-[10px] tabular-nums text-[var(--color-text-tertiary)] shrink-0">
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)] shrink-0">
{(finding.confidence * 100).toFixed(0)}%
</span>
</div>
- <div className="text-[10px] text-[var(--color-text-tertiary)] mt-0.5">
+ <div className="text-xs text-[var(--color-text-tertiary)] mt-0.5">
{finding.kind}
{showLines && typeof finding.lines === "number" && (
<> · {finding.lines} lines</>
@@ -1028,7 +1028,7 @@ export function SourceRenderer({ data }: { data: Record<string, unknown> }) {
return (
<div className="space-y-3">
<p className="truncate font-mono text-xs text-[var(--color-text-secondary)]" title={path}>{path}</p>
- <pre className="max-h-[60vh] overflow-auto border-l border-[var(--color-border-default)] pl-3 font-mono text-[11px] leading-relaxed text-[var(--color-text-secondary)] whitespace-pre-wrap break-words">{source || fallback.map((line) => typeof line === "string" ? line : JSON.stringify(line)).join("\n")}</pre>
+ <pre className="max-h-[60vh] overflow-auto border-l border-[var(--color-border-default)] pl-3 font-mono text-xs leading-relaxed text-[var(--color-text-secondary)] whitespace-pre-wrap break-words">{source || fallback.map((line) => typeof line === "string" ? line : JSON.stringify(line)).join("\n")}</pre>
</div>
);
}
@@ -1071,7 +1071,7 @@ function extractPath(data: Record<string, unknown>): Array<{ node: string; relat
export function DependencyPathRenderer({ data }: { data: Record<string, unknown> }) {
const path = extractPath(data);
if (path.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">No dependency path was found. This does not prove that no runtime relationship exists.</p>;
- return <div><SectionTitle icon={GitBranch}>Selected dependency path</SectionTitle><ol className="space-y-1">{path.slice(0, 100).map((item, index) => <li key={`${item.node}:${index}`} className="flex items-center gap-2 font-mono text-xs text-[var(--color-text-secondary)]"><span className="w-5 shrink-0 tabular-nums text-[var(--color-text-tertiary)]">{index + 1}</span><span className="break-all">{item.node}</span>{item.relationship && <span className="text-[10px] text-[var(--color-text-tertiary)]">{item.relationship}</span>}</li>)}</ol></div>;
+ return <div><SectionTitle icon={GitBranch}>Selected dependency path</SectionTitle><ol className="space-y-1">{path.slice(0, 100).map((item, index) => <li key={`${item.node}:${index}`} className="flex items-center gap-2 font-mono text-xs text-[var(--color-text-secondary)]"><span className="w-5 shrink-0 tabular-nums text-[var(--color-text-tertiary)]">{index + 1}</span><span className="break-all">{item.node}</span>{item.relationship && <span className="text-xs text-[var(--color-text-tertiary)]">{item.relationship}</span>}</li>)}</ol></div>;
}
export function CallPathRenderer({ data }: { data: Record<string, unknown> }) {
@@ -1079,7 +1079,7 @@ export function CallPathRenderer({ data }: { data: Record<string, unknown> }) {
const path = extractPath(data);
if (flows.length === 0 && path.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">No indexed call path was returned. Dynamic calls may be outside structural coverage.</p>;
if (path.length > 0) return <DependencyPathRenderer data={{ path }} />;
- return <div><SectionTitle icon={ArrowRight}>Selected execution flows</SectionTitle><ol className="border-t border-[var(--color-border-default)]">{flows.slice(0, 25).map((flow, index) => { const row = flow as Record<string, unknown>; const trace = Array.isArray(row.trace) ? row.trace.map(String) : []; return <li key={index} className="border-b border-[var(--color-border-default)] py-2 text-xs text-[var(--color-text-secondary)]"><span className="font-mono break-all">{String(row.entry_point_name ?? row.name ?? row.title ?? row.entry_point ?? `Flow ${index + 1}`)}</span>{trace.length > 0 && <ol className="mt-2 space-y-1 border-l border-[var(--color-border-default)] pl-3">{trace.slice(0, 50).map((node, traceIndex) => <li key={`${node}:${traceIndex}`} className="font-mono text-[11px] break-all">{node}</li>)}</ol>}{typeof row.termination === "string" && row.termination.length > 0 && <p className="mt-2 text-[10px] text-[var(--color-text-tertiary)]">Stopped: {row.termination}</p>}</li>; })}</ol></div>;
+ return <div><SectionTitle icon={ArrowRight}>Selected execution flows</SectionTitle><ol className="border-t border-[var(--color-border-default)]">{flows.slice(0, 25).map((flow, index) => { const row = flow as Record<string, unknown>; const trace = Array.isArray(row.trace) ? row.trace.map(String) : []; return <li key={index} className="border-b border-[var(--color-border-default)] py-2 text-xs text-[var(--color-text-secondary)]"><span className="font-mono break-all">{String(row.entry_point_name ?? row.name ?? row.title ?? row.entry_point ?? `Flow ${index + 1}`)}</span>{trace.length > 0 && <ol className="mt-2 space-y-1 border-l border-[var(--color-border-default)] pl-3">{trace.slice(0, 50).map((node, traceIndex) => <li key={`${node}:${traceIndex}`} className="font-mono text-xs break-all">{node}</li>)}</ol>}{typeof row.termination === "string" && row.termination.length > 0 && <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">Stopped: {row.termination}</p>}</li>; })}</ol></div>;
}
// ---------------------------------------------------------------------------
@@ -1092,7 +1092,7 @@ export function GenericJsonRenderer({
data: Record<string, unknown>;
}) {
return (
- <pre className="text-[10px] font-mono text-[var(--color-text-secondary)] overflow-auto max-h-[70vh] whitespace-pre-wrap break-words">
+ <pre className="text-xs font-mono text-[var(--color-text-secondary)] overflow-auto max-h-[70vh] whitespace-pre-wrap break-words">
{JSON.stringify(data, null, 2)}
</pre>
);
diff --git a/packages/ui/src/chat/chat-composer.tsx b/packages/ui/src/chat/chat-composer.tsx
index 26365013f..4225e44b8 100644
--- a/packages/ui/src/chat/chat-composer.tsx
+++ b/packages/ui/src/chat/chat-composer.tsx
@@ -2,7 +2,6 @@
import { useEffect, useRef, type ReactNode, type RefObject } from "react";
import { ArrowUp, Square } from "lucide-react";
-import { Button } from "../ui/button";
import { cn } from "../lib/cn";
export interface ChatComposerProps {
@@ -13,6 +12,9 @@ export interface ChatComposerProps {
isStreaming: boolean;
placeholder: string;
disabled?: boolean;
+ /** Why sending is unavailable (no provider, rate limit). Shown inside the
+ * composer in place of the input. */
+ disabledReason?: ReactNode;
autoFocus?: boolean;
compact?: boolean;
appearance?: "contained" | "bare";
@@ -22,6 +24,8 @@ export interface ChatComposerProps {
footer?: ReactNode;
}
+export const CHAT_COMPOSER_HINT = "Enter to send · Shift+Enter for newline";
+
/** Shared, controlled composer used by both the page chat and floating dock. */
export function ChatComposer({
value,
@@ -31,6 +35,7 @@ export function ChatComposer({
isStreaming,
placeholder,
disabled = false,
+ disabledReason,
autoFocus = false,
compact = false,
appearance = "contained",
@@ -40,6 +45,9 @@ export function ChatComposer({
}: ChatComposerProps) {
const localRef = useRef<HTMLTextAreaElement>(null);
const textareaRef = forwardedRef ?? localRef;
+ const hasText = value.trim().length > 0;
+ const showReason = disabled && Boolean(disabledReason);
+ const contained = appearance === "contained";
useEffect(() => {
const textarea = textareaRef.current;
@@ -57,58 +65,71 @@ export function ChatComposer({
return (
<div
+ data-chat-composer=""
className={cn(
- "min-w-0",
- appearance === "contained"
- ? "rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-1.5 focus-within:border-[var(--color-accent-primary)]"
+ "group/composer min-w-0",
+ contained
+ ? "rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2 transition-colors focus-within:border-[var(--color-border-hover)] motion-reduce:transition-none"
: "border-t border-[var(--color-border-subtle)] px-0 pb-0 pt-2",
- disabled && "opacity-60",
- compact && appearance === "contained" && "px-2 py-1.5",
className,
)}
>
<div className="flex items-end gap-2">
- <textarea
- ref={textareaRef}
- value={value}
- onChange={(event) => onValueChange(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === "Enter" && !event.shiftKey) {
- event.preventDefault();
- void submit();
- }
- }}
- placeholder={placeholder}
- aria-label="Chat message"
- disabled={disabled}
- autoFocus={autoFocus}
- rows={1}
- className={cn(
- "min-w-0 flex-1 resize-none bg-transparent px-1 py-0.5 text-[15px] leading-6 text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] overflow-y-auto",
- compact ? "max-h-24" : "max-h-36",
- )}
- style={{ scrollbarWidth: "none" }}
- />
- <Button
- variant="ghost"
- size="icon"
+ {showReason ? (
+ <p className="min-w-0 flex-1 py-1 text-sm leading-6 text-[var(--color-text-secondary)]">
+ {disabledReason}
+ </p>
+ ) : (
+ <textarea
+ ref={textareaRef}
+ value={value}
+ onChange={(event) => onValueChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
+ event.preventDefault();
+ void submit();
+ }
+ }}
+ placeholder={placeholder}
+ aria-label="Chat message"
+ disabled={disabled}
+ autoFocus={autoFocus}
+ rows={1}
+ className={cn(
+ // 16px: smaller text makes iOS zoom the page on focus.
+ "min-w-0 flex-1 resize-none overflow-y-auto bg-transparent px-1 py-1 text-base leading-6 text-[var(--color-text-primary)] !outline-none placeholder:text-[var(--color-text-tertiary)] disabled:opacity-60",
+ compact ? "max-h-24" : "max-h-36",
+ )}
+ style={{ scrollbarWidth: "none" }}
+ />
+ )}
+ <button
+ type="button"
className={cn(
- "h-9 w-9 shrink-0 rounded-md border border-[var(--color-border-default)]",
- "bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]",
- "hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-overlay)]",
+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-bg-surface)] disabled:cursor-not-allowed motion-reduce:transition-none",
+ isStreaming
+ ? "border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)] hover:border-[var(--color-border-hover)]"
+ : hasText && !disabled
+ ? "bg-[var(--color-accent-fill)] text-[var(--color-text-on-accent)] hover:bg-[var(--color-accent-fill-hover)]"
+ : "bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)]",
)}
onClick={isStreaming ? onCancel : () => void submit()}
- disabled={(!value.trim() && !isStreaming) || disabled}
+ disabled={(!hasText && !isStreaming) || disabled}
aria-label={isStreaming ? "Stop generation" : "Send message"}
title={isStreaming ? "Stop generation" : "Send message"}
>
- {isStreaming ? <Square className="h-3.5 w-3.5 fill-current" /> : <ArrowUp className="h-4 w-4" />}
- </Button>
+ {isStreaming ? <Square className="h-3 w-3 fill-current" /> : <ArrowUp className="h-4 w-4" />}
+ </button>
</div>
- {footer && (
- <div className="mt-0.5 flex min-h-6 items-center justify-between gap-2 px-0.5 text-xs text-[var(--color-text-tertiary)]">
+ {contained && (footer || !showReason) && (
+ <div className="mt-1 flex min-h-6 items-center justify-between gap-2 px-0.5 text-xs text-[var(--color-text-tertiary)]">
<div className="min-w-0">{footer}</div>
- <span className="ml-auto hidden sm:inline">Shift+Enter for newline</span>
+ {!showReason && (
+ // One hint, only while typing, and only where a keyboard is likely.
+ <span className="ml-auto hidden opacity-0 transition-opacity group-focus-within/composer:opacity-100 motion-reduce:transition-none pointer-fine:inline">
+ {CHAT_COMPOSER_HINT}
+ </span>
+ )}
</div>
)}
</div>
diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsx
index 0d5b44623..1d2b835ca 100644
--- a/packages/ui/src/chat/chat-dock.tsx
+++ b/packages/ui/src/chat/chat-dock.tsx
@@ -404,11 +404,11 @@ export function ChatDock({
alt=""
/>
</span>
- <span className="text-[13px] font-medium text-[var(--color-text-primary)]">
+ <span className="text-xs font-medium text-[var(--color-text-primary)]">
{statusText ?? "Ask Repowise"}
</span>
{hintVisible && !statusText && (
- <span className="hidden border-l border-[var(--color-border-default)] pl-2 text-[13px] text-[var(--color-text-tertiary)] sm:inline">
+ <span className="hidden border-l border-[var(--color-border-default)] pl-2 text-xs text-[var(--color-text-tertiary)] sm:inline">
{firstVisitHint}
</span>
)}
@@ -423,17 +423,15 @@ export function ChatDock({
)}
</button>
{onDismiss && (
- /* Quiet until wanted: the dismiss is the kind of control you look
- for only once you are already annoyed, and a permanent second
- button on the pill would make the thing louder to solve the
- complaint that it is too loud. Focusable while transparent, so
- the keyboard path is not gated on hover. */
+ /* Quiet until wanted on a mouse: revealed on hover or focus. Always
+ shown on touch screens, where there is no hover, with a hit area
+ padded out to 36px around the small visible disc. */
<button
type="button"
onClick={onDismiss}
aria-label="Hide Ask Repowise"
title="Hide Ask Repowise. Bring it back in Settings."
- className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] opacity-0 shadow-[var(--shadow-md)] transition-opacity hover:text-[var(--color-text-primary)] focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] group-hover/dock:opacity-100 motion-reduce:transition-none"
+ className="absolute -right-1.5 -top-1.5 flex h-6 w-6 items-center justify-center rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] shadow-[var(--shadow-md)] transition-opacity before:absolute before:-inset-1.5 before:content-[''] hover:text-[var(--color-text-primary)] focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] pointer-fine:opacity-0 pointer-fine:group-hover/dock:opacity-100 motion-reduce:transition-none"
>
<X className="h-3 w-3" />
</button>
@@ -509,6 +507,7 @@ export function ChatDock({
isStreaming={isStreaming}
placeholder={presentation.placeholder}
disabled={sendDisabled}
+ {...(sendDisabledReason ? { disabledReason: sendDisabledReason } : {})}
compact
appearance="bare"
autoFocus
@@ -525,11 +524,6 @@ export function ChatDock({
className="mt-2"
/>
)}
- {sendDisabled && sendDisabledReason && (
- <div className="mt-2 text-xs text-[var(--color-text-secondary)]">
- {sendDisabledReason}
- </div>
- )}
</aside>
);
}
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index 447de42bb..81304f70c 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -12,10 +12,10 @@
* The shell is stateless apart from the textarea input value and renders
* messages, the empty-state suggestions, the input area, and slots.
*
- * Chat is a reading surface: the transcript sits on `--color-bg-root` and the
- * one chrome row above it on `--color-bg-surface`. There is exactly one chrome
- * row — the page used to stack its own repo header on top of this one, under a
- * breadcrumb, so three hairlines ran before the first word of content.
+ * Chat is a reading surface: one 720px column on `--color-bg-root` holds the
+ * transcript, the empty state and the composer. History and artifacts sit in
+ * a borderless header row that is always mounted, so nothing shifts when the
+ * first artifact arrives.
*/
import {
@@ -32,7 +32,6 @@ import { Button } from "../ui/button";
import { ActivityDot } from "../ui/activity-dot";
import { ScrollArea } from "../ui/scroll-area";
import { cn } from "../lib/cn";
-import { BrandMark } from "../shared/brand-mark";
import { ChatMessage } from "./chat-message";
import { ArtifactPanel } from "./artifact-panel";
import { ChatContextIndicator } from "./chat-context-indicator";
@@ -48,7 +47,6 @@ import type {
import type { SourceReference } from "./source-citations";
import { ChatComposer } from "./chat-composer";
import { ChatSuggestions } from "./chat-suggestions";
-import { CHAT_SHORTCUT_HINT } from "./use-chat-shortcut";
import { useChatScroll } from "./use-chat-scroll";
const DEFAULT_SUGGESTIONS: readonly ChatSuggestion[] = [
@@ -60,8 +58,11 @@ const DEFAULT_SUGGESTIONS: readonly ChatSuggestion[] = [
"Search for authentication-related code",
].map((text) => ({ text, source: "static" as const }));
-const MICRO_LABEL =
- "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+// Radix wraps viewport content in an inline `display: table` div that grows
+// to its widest child, so one wide table or code line widened the whole
+// transcript past a phone screen. As a block it holds the column width and
+// wide content scrolls inside its own container.
+const VIEWPORT_BLOCK = "[&>div]:block!";
export interface ChatInterfaceProps {
/** Identifier forwarded to `ChatMessage` for source-citation hrefs. */
@@ -95,15 +96,15 @@ export interface ChatInterfaceProps {
*/
historySlot?: ReactNode;
- /** Avatar src forwarded to `ChatMessage`. */
+ /** @deprecated Turns no longer render avatars. Ignored. */
assistantAvatarSrc?: string;
- /** Optional host-supplied avatar for user turns. */
+ /** @deprecated Turns no longer render avatars. Ignored. */
userAvatarSrc?: string;
/** Forwarded to `SourceCitations` for href customisation. */
buildCitationHref?: (source: SourceReference) => string;
/** Forwarded to `SourceCitations` for route-agnostic link generation. */
linkPrefix?: string;
- /** Logo shown above the empty-state heading. */
+ /** @deprecated The empty state no longer shows a logo. Ignored. */
emptyStateLogoSrc?: string;
/** Override the static tier with suggestions derived from live page data. */
suggestions?: readonly ChatSuggestion[];
@@ -115,7 +116,7 @@ export interface ChatInterfaceProps {
statusSlot?: ReactNode;
/** Disables the composer (e.g. no chat provider configured). */
sendDisabled?: boolean;
- /** Banner shown above the composer when sending is disabled. */
+ /** Why sending is disabled, shown inside the composer. */
sendDisabledReason?: ReactNode;
/** Compact transcript treatment for a floating dock. */
variant?: "page" | "dock";
@@ -151,11 +152,8 @@ export function ChatInterface({
onCancel,
modelSelectorSlot,
historySlot,
- assistantAvatarSrc,
- userAvatarSrc,
buildCitationHref,
linkPrefix,
- emptyStateLogoSrc = "/repowise-logo.png",
suggestions,
placeholder,
statusSlot,
@@ -205,7 +203,11 @@ export function ChatInterface({
const contextPresentation = getChatContextPresentation(context);
const visibleSuggestions =
suggestions ?? (context ? contextPresentation.suggestions : DEFAULT_SUGGESTIONS);
- const composerPlaceholder = placeholder ?? contextPresentation.placeholder;
+ const composerPlaceholder =
+ placeholder ??
+ (isEmpty && context?.kind === "chat"
+ ? "Ask anything, or paste a file path"
+ : contextPresentation.placeholder);
const lastMessage = messages[messages.length - 1];
// An errored turn never carries follow-ups: the server sends them only on a
// turn that completed and called a tool.
@@ -213,6 +215,18 @@ export function ChatInterface({
!error && lastMessage?.role === "assistant" && !lastMessage.isStreaming
? lastMessage.followUps ?? []
: [];
+ // One pass rather than a backwards scan per turn on every streamed token.
+ const modelChangedIds = useMemo(() => {
+ const changed = new Set<string>();
+ let previous: string | null = null;
+ for (const m of messages) {
+ if (m.role !== "assistant") continue;
+ const identity = `${m.provider ?? ""}:${m.model ?? ""}`;
+ if (previous !== null && previous !== identity) changed.add(m.id);
+ previous = identity;
+ }
+ return changed;
+ }, [messages]);
const showContext =
context !== undefined &&
context.kind !== "repository" &&
@@ -318,68 +332,65 @@ export function ChatInterface({
textareaRef.current?.focus();
}
+ const dock = variant === "dock";
+ // One column for the transcript, the empty state and the composer.
+ 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}>
- {/* The one chrome row. */}
- {(historySlot || totalArtifactCount > 0) && (
- <div className="flex items-center justify-between gap-2 px-[var(--page-pad)] py-2.5 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]">
- <div className="flex min-w-0 items-center gap-2">{historySlot}</div>
- <div className="flex items-center gap-2 shrink-0">
- {totalArtifactCount > 0 && (
- <Button
- variant="ghost"
- size="sm"
- className={cn(
- "h-8 text-xs gap-1.5 tabular-nums",
- artifactPulse && "text-[var(--color-accent-secondary)]",
- )}
- onClick={() => setArtifactPanelOpen(true)}
- >
- {artifactPulse ? (
- <ActivityDot className="h-1.5 w-1.5 bg-[var(--color-accent-secondary)]" />
- ) : null}
- <PanelRight className="h-4 w-4" />
- <span className="sr-only sm:not-sr-only">Artifacts</span>
- {totalArtifactCount}
- </Button>
- )}
- </div>
- </div>
- )}
+ {/* 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="flex min-w-0 items-center gap-2">{historySlot}</div>
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-hidden={totalArtifactCount === 0 || undefined}
+ tabIndex={totalArtifactCount === 0 ? -1 : undefined}
+ className={cn(
+ "h-8 shrink-0 gap-1.5 text-xs tabular-nums",
+ totalArtifactCount === 0 && "invisible",
+ artifactPulse && "text-[var(--color-text-primary)]",
+ )}
+ onClick={() => setArtifactPanelOpen(true)}
+ >
+ {artifactPulse ? (
+ <ActivityDot className="h-1.5 w-1.5 bg-[var(--color-text-tertiary)]" />
+ ) : null}
+ <PanelRight className="h-4 w-4" />
+ <span className="sr-only sm:not-sr-only">Artifacts</span>
+ {totalArtifactCount}
+ </Button>
+ </div>
{/* Message list or empty state */}
<div className="flex-1 min-h-0 relative">
{isEmpty ? (
- // Scrolls: at 390x667 the mark, heading, status and six suggestions
- // exceed the viewport, and the old centred flex column clipped them.
- // Top-anchored rather than centred — vertical centring would need a
- // height Radix's `display:table` viewport wrapper does not pass down,
- // and the section style reads left-aligned everywhere else anyway.
- <ScrollArea className="h-full" viewportRef={viewportRef}>
- <div ref={contentRef} className={cn("mx-auto flex max-w-2xl flex-col", variant === "dock" ? "gap-5 px-4 py-7" : "gap-10 px-[var(--page-pad)] py-14")}>
- <div className="space-y-4">
- {variant !== "dock" && <BrandMark darkSrc={emptyStateLogoSrc} size={40} />}
- <h2 className={cn("font-semibold text-[var(--color-text-primary)]", variant === "dock" ? "text-lg" : "text-[22px]")}>
- {variant === "dock" ? "Ask from this view" : `Ask anything about ${repoName ?? "this codebase"}`}
+ // Top-anchored rather than centred: vertical centring would need a
+ // height Radix's `display:table` viewport wrapper does not pass down.
+ <ScrollArea className="h-full" viewportRef={viewportRef} viewportClassName={VIEWPORT_BLOCK}>
+ <div ref={contentRef} className={cn(column, "flex flex-col", dock ? "gap-5 py-6" : "gap-8 pb-8 pt-[12vh]")}>
+ <div className="space-y-2">
+ <h2 className={cn("font-semibold text-[var(--color-text-primary)]", dock ? "text-lg" : "text-[22px]")}>
+ {dock ? "Ask from this view" : `Ask anything about ${repoName ?? "this codebase"}`}
</h2>
- <p className={cn("text-[var(--color-text-secondary)] leading-relaxed", variant === "dock" ? "text-sm" : "text-base")}>
- {variant === "dock"
- ? "Keep investigating without leaving the page. Answers use the active repository context."
- : "Explore architecture, assess risk, search code, trace dependencies, and understand decisions. Every answer cites the pages it read."}
+ <p className={cn("text-[var(--color-text-secondary)] leading-relaxed", dock ? "text-sm" : "text-base")}>
+ {dock
+ ? "Answers use the active repository context."
+ : "Architecture, risk, code health, decisions. Every answer cites the pages it read."}
</p>
{statusSlot && (
<p className="font-mono text-xs text-[var(--color-text-tertiary)] tabular-nums">
{statusSlot}
</p>
)}
- <p className={cn(MICRO_LABEL)}>{CHAT_SHORTCUT_HINT}</p>
</div>
<ChatSuggestions
- suggestions={visibleSuggestions}
+ suggestions={visibleSuggestions.slice(0, 4)}
onSelect={handleSuggestion}
layout="rows"
- label="Start with"
+ ariaLabel="Suggested questions"
/>
</div>
</ScrollArea>
@@ -387,41 +398,26 @@ export function ChatInterface({
<ScrollArea
className="h-full"
viewportRef={viewportRef}
- viewportClassName="[overflow-anchor:auto]"
+ viewportClassName={cn(VIEWPORT_BLOCK, "[overflow-anchor:auto]")}
>
<div
ref={contentRef}
- className={cn(
- "mx-auto w-full",
- variant === "dock"
- ? "max-w-full space-y-6 px-4 py-5"
- : "max-w-[960px] space-y-10 px-[var(--page-pad)] py-10",
- )}
+ className={cn(column, dock ? "space-y-5 py-5" : "space-y-8 py-8")}
>
{messages.map((m, index) => {
- const previousAssistant = messages
- .slice(0, index)
- .reverse()
- .find((candidate) => candidate.role === "assistant");
- const modelChanged = Boolean(
- m.role === "assistant" &&
- previousAssistant &&
- `${previousAssistant.provider ?? ""}:${previousAssistant.model ?? ""}` !==
- `${m.provider ?? ""}:${m.model ?? ""}`,
- );
+ const isLast = index === messages.length - 1;
return (
<ChatMessage
key={m.id}
message={m}
repoId={repoId}
onViewArtifact={handleViewArtifact}
- {...(assistantAvatarSrc ? { assistantAvatarSrc } : {})}
- {...(userAvatarSrc ? { userAvatarSrc } : {})}
density={variant}
- modelChanged={modelChanged}
+ modelChanged={modelChangedIds.has(m.id)}
+ isLatest={isLast && m.role === "assistant"}
+ {...(isLast && m.role === "assistant" && error ? { error } : {})}
{...(onRetry ? { onRetry } : {})}
{...(onEditAndResend ? { onEditAndResend } : {})}
- onFollowUp={handleFollowUp}
{...(buildCitationHref ? { buildCitationHref } : {})}
{...(linkPrefix ? { linkPrefix } : {})}
/>
@@ -438,9 +434,21 @@ export function ChatInterface({
ariaLabel="Next steps"
/>
)}
- {error && (
- <div className="rounded-lg border border-[var(--color-error)]/30 bg-[var(--color-error)]/10 px-4 py-2.5 text-sm text-[var(--color-error)]">
- {error}
+ {error && lastMessage?.role !== "assistant" && (
+ // The newest answer carries its own error and Retry; this is
+ // only for a failure before any answer turn exists.
+ <div role="alert" className="flex flex-wrap items-center gap-2 text-sm text-[var(--color-text-secondary)]">
+ <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-error)]" />
+ <span className="min-w-0 [overflow-wrap:anywhere]">{error}</span>
+ {onRetry && lastMessage && (
+ <button
+ type="button"
+ onClick={() => void onRetry(lastMessage)}
+ className="inline-flex h-8 items-center rounded-md px-2 text-xs font-medium 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)]"
+ >
+ Retry
+ </button>
+ )}
</div>
)}
</div>
@@ -451,10 +459,11 @@ export function ChatInterface({
type="button"
onClick={jumpToLatest}
aria-pressed={isFollowingLive}
- className="absolute bottom-3 left-1/2 z-10 inline-flex min-h-9 -translate-x-1/2 items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-3 text-xs font-medium 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)]"
+ 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)]"
>
- <ArrowDown className="h-3.5 w-3.5" />
- Jump to latest
+ <ArrowDown className="h-4 w-4" />
</button>
)}
</div>
@@ -463,21 +472,13 @@ export function ChatInterface({
{announcement}
</span>
- {/* Input area. The composer keeps its elevation: it is a genuinely
- interactive surface, which is what rule 1 reserves elevation for. */}
<div
className={cn(
"shrink-0",
- variant === "dock" ? "px-3 pb-3 pt-3" : "px-[var(--page-pad)] pb-5 pt-4",
- !isEmpty && "border-t border-[var(--color-border-default)]",
+ dock ? "pb-3 pt-1" : "pb-[max(1.25rem,env(safe-area-inset-bottom))] pt-2",
)}
>
- <div className={cn("mx-auto w-full", variant === "dock" ? "max-w-full" : "max-w-[960px]")}>
- {sendDisabled && sendDisabledReason && (
- <div className="mb-2 rounded-lg border border-[var(--color-warning)]/40 bg-[var(--color-warning)]/10 px-3 py-2 text-xs text-[var(--color-text-secondary)]">
- {sendDisabledReason}
- </div>
- )}
+ <div className={cn(column, dock && "px-3")}>
{showContext && context && (
<ChatContextIndicator
context={context}
@@ -492,16 +493,12 @@ export function ChatInterface({
isStreaming={isStreaming}
placeholder={composerPlaceholder}
disabled={sendDisabled}
- compact={variant === "dock"}
+ {...(sendDisabledReason ? { disabledReason: sendDisabledReason } : {})}
+ compact={dock}
autoFocus={autoFocus}
textareaRef={textareaRef}
{...(modelSelectorSlot ? { footer: modelSelectorSlot } : {})}
/>
- {isEmpty && !modelSelectorSlot && (
- <p className={cn(MICRO_LABEL, "mt-2.5 text-center")}>
- Shift+Enter for newline · Enter to send
- </p>
- )}
</div>
</div>
diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsx
index 75709ca33..a6cefc0b7 100644
--- a/packages/ui/src/chat/chat-message.tsx
+++ b/packages/ui/src/chat/chat-message.tsx
@@ -1,12 +1,11 @@
"use client";
import { memo } from "react";
-import { UserRound } from "lucide-react";
import { cn } from "../lib/cn";
-import { BrandMark } from "../shared/brand-mark";
import { ToolCallGroup } from "./tool-call-group";
import { WorkingOrb } from "./working-orb";
import { MessageActions } from "./message-actions";
+import { CHAT_STAGES, chatStage } from "./chat-stage";
import { Markdown } from "../shared/markdown";
import { SourceCitations, type SourceReference } from "./source-citations";
import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
@@ -15,50 +14,44 @@ interface ChatMessageProps {
message: ChatUIMessage;
repoId: string;
onViewArtifact?: (artifact: ChatArtifact) => void;
- /** Optional avatar src for the assistant. Defaults to `/repowise-logo.png`. */
- assistantAvatarSrc?: string;
/** Forwarded to `SourceCitations` so consumers can customise the link path. */
buildCitationHref?: (source: SourceReference) => string;
/** Forwarded to `SourceCitations` for route-agnostic link generation. */
linkPrefix?: string;
density?: "page" | "dock";
- /** Optional host identity image for user turns. */
- userAvatarSrc?: string;
/** True when this response uses a different model from the prior answer. */
modelChanged?: boolean;
+ /** The newest answer keeps its actions visible without hover. */
+ isLatest?: boolean;
+ /** Why this turn failed, shown inline with Retry. */
+ error?: string | null;
onRetry?: (message: ChatUIMessage) => void | Promise<void>;
onEditAndResend?: (message: ChatUIMessage, text: string) => void | Promise<void>;
- onFollowUp?: (text: string) => void;
}
/**
- * One turn of the transcript.
- *
- * The user's turn used to be a solid accent bubble with an accent avatar disc —
- * the highest-contrast object on the page, spent on the one element that is
- * purely a record of what you already typed. The accent belongs to things that
- * respond. A question now reads as the heading it functionally is, and the
- * answer below it gets the page.
+ * One turn of the transcript, with no labels or avatars: the user's turn is a
+ * quiet right-aligned bubble and the answer is plain prose on the page.
*
* Memoised: without it every SSE token re-renders the whole list, which means
- * react-markdown re-parses every prior reply on every frame of a stream. The
- * cost is invisible in the JSX and scales with transcript length.
+ * react-markdown re-parses every prior reply on every frame of a stream.
*/
function ChatMessageImpl({
message,
repoId,
onViewArtifact,
- assistantAvatarSrc = "/repowise-logo.png",
buildCitationHref,
linkPrefix,
density = "page",
- userAvatarSrc,
modelChanged = false,
+ isLatest = false,
+ error,
onRetry,
onEditAndResend,
- onFollowUp,
}: ChatMessageProps) {
const isUser = message.role === "user";
+ const dock = density === "dock";
+ const stage = isUser ? null : chatStage(message);
if (isUser) {
return (
@@ -67,31 +60,21 @@ function ChatMessageImpl({
data-chat-message-id={message.id}
data-chat-role="user"
data-chat-density={density}
- className="flex min-w-0 justify-end gap-2.5"
+ className="group/turn flex min-w-0 flex-col items-end"
>
- <div className={cn("min-w-0", density === "dock" ? "max-w-[88%]" : "max-w-[78%]") }>
- <p className="mb-1 text-right font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- You
- </p>
- <p
- className={cn(
- "[overflow-wrap:anywhere] rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]",
- density === "dock"
- ? "px-3 py-2 text-[15px] leading-relaxed"
- : "px-3.5 py-2.5 text-base leading-relaxed",
- )}
- >
- {message.text}
- </p>
- <MessageActions message={message} {...(onEditAndResend ? { onEditAndResend: (text) => onEditAndResend(message, text) } : {})} />
- </div>
- <div className="mt-5 flex h-7 w-7 shrink-0 items-center justify-center overflow-hidden rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-secondary)]">
- {userAvatarSrc ? (
- <img src={userAvatarSrc} alt="" className="h-full w-full object-cover" />
- ) : (
- <UserRound aria-hidden className="h-3.5 w-3.5" />
+ <p
+ className={cn(
+ "max-w-[85%] whitespace-pre-wrap rounded-2xl bg-[var(--color-bg-elevated)] px-4 py-2.5 leading-relaxed text-[var(--color-text-primary)] [overflow-wrap:anywhere]",
+ dock ? "text-sm" : "text-base",
)}
- </div>
+ >
+ {message.text}
+ </p>
+ <MessageActions
+ message={message}
+ align="end"
+ {...(onEditAndResend ? { onEditAndResend: (text) => onEditAndResend(message, text) } : {})}
+ />
</article>
);
}
@@ -102,66 +85,60 @@ function ChatMessageImpl({
data-chat-message-id={message.id}
data-chat-role="assistant"
data-chat-density={density}
- className={cn("flex min-w-0", density === "dock" ? "gap-2.5" : "gap-3.5")}
+ className="group/turn min-w-0"
>
- <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center">
- <BrandMark darkSrc={assistantAvatarSrc} size={22} />
- </div>
-
- <div className="flex-1 min-w-0">
- <p className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Repowise
+ {modelChanged && (message.provider || message.model) && (
+ <p className="mb-2 text-xs text-[var(--color-text-tertiary)]">
+ Model changed to {[message.provider, message.model].filter(Boolean).join(" · ")}
</p>
- {(message.provider || message.model) && (
- <p className="mb-2 text-[11px] text-[var(--color-text-tertiary)]">
- {modelChanged ? "Model changed to " : ""}
- {[message.provider, message.model].filter(Boolean).join(" · ")}
- </p>
+ )}
+ <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={cn("max-w-full", density === "dock" ? "space-y-2.5" : "space-y-3")}>
- {message.toolCalls.length > 0 && (
- <ToolCallGroup
- toolCalls={message.toolCalls}
- {...(onViewArtifact ? { onViewArtifact } : {})}
- />
- )}
- {message.text && (
- <Markdown content={message.text} density={density === "dock" ? "compact" : "reading"} streaming={message.isStreaming} />
- )}
+ {message.text && (
+ <Markdown content={message.text} density={dock ? "narrow" : "reading"} streaming={message.isStreaming} fill />
+ )}
- {!message.isStreaming && message.toolCalls.length > 0 && (
- <SourceCitations
- toolCalls={message.toolCalls}
- repoId={repoId}
- {...(linkPrefix ? { linkPrefix } : {})}
- {...(buildCitationHref ? { buildHref: buildCitationHref } : {})}
- />
- )}
+ {!message.isStreaming && message.toolCalls.length > 0 && (
+ <SourceCitations
+ toolCalls={message.toolCalls}
+ repoId={repoId}
+ {...(linkPrefix ? { linkPrefix } : {})}
+ {...(buildCitationHref ? { buildHref: buildCitationHref } : {})}
+ />
+ )}
- {message.truncated && !message.isStreaming && (
- <p
- data-chat-truncated="true"
- className="border-y border-[var(--color-border-default)] px-3 py-2 text-xs text-[var(--color-text-tertiary)]"
- >
- Stopped at the step limit before a final answer. Ask again to continue.
- </p>
- )}
+ {message.truncated && !message.isStreaming && (
+ <p
+ data-chat-truncated="true"
+ className="text-xs text-[var(--color-text-tertiary)]"
+ >
+ Stopped at the step limit before a final answer. Ask again to continue.
+ </p>
+ )}
- {message.isStreaming &&
- !message.text &&
- !message.toolCalls.some((tc) => tc.status === "running") && (
- <div className="flex items-center gap-2 py-2 text-xs text-[var(--color-text-tertiary)]">
- <WorkingOrb />
- <span>Reading context</span>
- </div>
- )}
- <MessageActions
- message={message}
- {...(onRetry ? { onRetry: () => onRetry(message) } : {})}
- {...(onFollowUp ? { onFollowUp } : {})}
- />
- </div>
+ {stage && (
+ // The one live marker, always at the edge of the answer: it follows
+ // 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)]"
+ >
+ <WorkingOrb state={CHAT_STAGES[stage].state} />
+ <span>{CHAT_STAGES[stage].label}</span>
+ </div>
+ )}
+ <MessageActions
+ message={message}
+ pinned={isLatest}
+ {...(error ? { error } : {})}
+ {...(onRetry ? { onRetry: () => onRetry(message) } : {})}
+ />
</div>
</article>
);
diff --git a/packages/ui/src/chat/chat-stage.ts b/packages/ui/src/chat/chat-stage.ts
new file mode 100644
index 000000000..b23a480c1
--- /dev/null
+++ b/packages/ui/src/chat/chat-stage.ts
@@ -0,0 +1,45 @@
+import { ORB_STATE, type OrbState } from "../shared/orb-loader";
+import type { ChatUIMessage } from "@repowise-dev/types/chat";
+
+export type ChatToolKind = "searching" | "tracing" | "working";
+export type ChatStage = "thinking" | ChatToolKind | "writing";
+
+/** Tools by the kind of wait they cause. Anything not listed is `working`. */
+const TOOL_KINDS: Readonly<Record<string, ChatToolKind>> = {
+ search_codebase: "searching",
+ get_answer: "searching",
+ get_overview: "searching",
+ get_why: "searching",
+ get_context: "tracing",
+ get_symbol: "tracing",
+ get_callers: "tracing",
+ get_architecture: "tracing",
+ get_blast_radius: "tracing",
+ get_dependency_path: "tracing",
+};
+
+export function chatToolKind(name: string): ChatToolKind {
+ return TOOL_KINDS[name] ?? "working";
+}
+
+export const CHAT_STAGES: Readonly<Record<ChatStage, { state: OrbState; label: string }>> = {
+ thinking: { state: ORB_STATE.thinking, label: "Thinking" },
+ searching: { state: ORB_STATE.searching, label: "Searching the index" },
+ tracing: { state: ORB_STATE.tracing, label: "Tracing callers" },
+ working: { state: ORB_STATE.working, label: "Working" },
+ writing: { state: ORB_STATE.writing, label: "Writing" },
+};
+
+/**
+ * What a streaming answer is doing right now: thinking until the first step,
+ * the running tool's kind during a call, writing once text arrives. Null once
+ * the turn is complete.
+ */
+export function chatStage(message: ChatUIMessage): ChatStage | null {
+ if (!message.isStreaming) return null;
+ for (let i = message.toolCalls.length - 1; i >= 0; i -= 1) {
+ const call = message.toolCalls[i]!;
+ if (call.status === "running") return chatToolKind(call.name);
+ }
+ return message.text ? "writing" : "thinking";
+}
diff --git a/packages/ui/src/chat/conversation-history.tsx b/packages/ui/src/chat/conversation-history.tsx
index c3729ecd3..1509c3f76 100644
--- a/packages/ui/src/chat/conversation-history.tsx
+++ b/packages/ui/src/chat/conversation-history.tsx
@@ -89,7 +89,7 @@ export function ConversationHistory({
<button type="button" onClick={() => { onNew(); closePopover(); }} className="flex min-h-9 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-xs text-[var(--color-text-primary)] hover:bg-[var(--color-bg-elevated)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"><Plus className="h-3.5 w-3.5 shrink-0" /> <span className="truncate">New conversation</span></button>
{variant === "rail" && collapsible && <button type="button" onClick={() => updateRailCollapsed(true)} aria-label="Collapse conversation history" title="Collapse history" className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-[var(--color-text-tertiary)] 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)]"><PanelLeftClose className="h-4 w-4" /></button>}
</div>
- <label className="m-2 flex min-h-9 items-center gap-2 border-b border-[var(--color-border-default)] px-1"><Search className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><span className="sr-only">Search conversations</span><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search history" className="min-w-0 flex-1 bg-transparent text-xs text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)]" /></label>
+ <label className="m-2 flex min-h-9 items-center gap-2 border-b border-[var(--color-border-default)] px-1 focus-within:border-[var(--color-border-hover)]"><Search className="h-3.5 w-3.5 text-[var(--color-text-tertiary)]" /><span className="sr-only">Search conversations</span><input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search history" className="min-w-0 flex-1 bg-transparent text-xs text-[var(--color-text-primary)] !outline-none placeholder:text-[var(--color-text-tertiary)]" /></label>
<div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2">
{isLoading && !conversations && <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">Loading…</p>}
{conversations?.length === 0 && <p className="py-6 text-center text-xs text-[var(--color-text-tertiary)]">No conversations yet</p>}
diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.ts
index 5b09ac3fe..4086c250d 100644
--- a/packages/ui/src/chat/index.ts
+++ b/packages/ui/src/chat/index.ts
@@ -15,6 +15,7 @@ export * from "./use-chat-shortcut";
export * from "./chat-context-indicator";
export * from "../shared/markdown";
export * from "./chat-message";
+export * from "./chat-stage";
export * from "./conversation-history";
export * from "./model-selector";
export * from "./message-actions";
diff --git a/packages/ui/src/chat/message-actions.tsx b/packages/ui/src/chat/message-actions.tsx
index 253f41ec5..db9e23942 100644
--- a/packages/ui/src/chat/message-actions.tsx
+++ b/packages/ui/src/chat/message-actions.tsx
@@ -1,26 +1,146 @@
"use client";
import { useState } from "react";
-import { Check, Copy, Pencil, RotateCcw, Send } from "lucide-react";
+import { Check, Copy, Pencil, RotateCcw } from "lucide-react";
+import { cn } from "../lib/cn";
import type { ChatUIMessage } from "@repowise-dev/types/chat";
interface MessageActionsProps {
message: ChatUIMessage;
onRetry?: () => void | Promise<void>;
onEditAndResend?: (text: string) => void | Promise<void>;
- onFollowUp?: (text: string) => void;
+ /** Why this answer failed. Shown inline with Retry even when no text arrived. */
+ error?: string | null;
+ /** Keep the row visible without hover (the newest answer). */
+ pinned?: boolean;
+ align?: "start" | "end";
}
-export function MessageActions({ message, onRetry, onEditAndResend, onFollowUp }: MessageActionsProps) {
+const ICON_BUTTON =
+ "inline-flex h-8 w-8 items-center justify-center rounded-md 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)]";
+
+/**
+ * Copy, retry and edit under a turn. Revealed on hover or focus with a fine
+ * pointer; always shown on touch screens and on the newest answer, so nothing
+ * is reachable only by hovering.
+ */
+export function MessageActions({
+ message,
+ onRetry,
+ onEditAndResend,
+ error,
+ pinned = false,
+ align = "start",
+}: MessageActionsProps) {
const [copied, setCopied] = useState(false);
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(message.text);
- if (message.isStreaming || !message.text) return null;
+ if (message.isStreaming) return null;
+ if (!message.text && !error) return null;
if (editing) {
- return <form className="mt-2 flex gap-2" onSubmit={(event) => { event.preventDefault(); const text = draft.trim(); if (text) void onEditAndResend?.(text); setEditing(false); }}><textarea autoFocus value={draft} onChange={(event) => setDraft(event.target.value)} aria-label="Edit message" className="min-h-20 flex-1 resize-y rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-2 text-sm text-[var(--color-text-primary)] outline-none focus:border-[var(--color-accent-primary)]" /><button type="submit" className="flex h-10 w-10 items-center justify-center rounded-md bg-[var(--color-model)] text-[var(--color-text-on-model)]" aria-label="Fork and resend"><Send className="h-4 w-4" /></button></form>;
+ return (
+ <form
+ className="mt-2 w-full space-y-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const text = draft.trim();
+ if (text) void onEditAndResend?.(text);
+ setEditing(false);
+ }}
+ >
+ <textarea
+ autoFocus
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ aria-label="Edit message"
+ className="min-h-20 w-full resize-y rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-2.5 text-base leading-relaxed text-[var(--color-text-primary)] !outline-none focus:border-[var(--color-border-hover)] focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ />
+ <div className="flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={() => {
+ setDraft(message.text);
+ setEditing(false);
+ }}
+ className="inline-flex h-8 items-center rounded-full px-3 text-xs text-[var(--color-text-secondary)] 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)]"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ aria-label="Fork and resend"
+ className="inline-flex h-8 items-center rounded-full bg-[var(--color-accent-fill)] px-3 text-xs font-medium text-[var(--color-text-on-accent)] hover:bg-[var(--color-accent-fill-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--color-bg-root)]"
+ >
+ Send
+ </button>
+ </div>
+ </form>
+ );
}
- const actionClass = "inline-flex min-h-8 items-center gap-1 rounded-md px-1.5 text-[11px] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
- return <div className="mt-1.5 flex flex-wrap items-center gap-1" aria-label={`${message.role} message actions`}><button type="button" className={actionClass} onClick={() => { void navigator.clipboard.writeText(message.text); setCopied(true); window.setTimeout(() => setCopied(false), 1600); }}>{copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}{copied ? "Copied" : "Copy"}</button>{message.role === "assistant" && onRetry && <button type="button" className={actionClass} onClick={() => void onRetry()}><RotateCcw className="h-3 w-3" />Retry</button>}{message.role === "user" && message.serverId && onEditAndResend && <button type="button" className={actionClass} onClick={() => setEditing(true)}><Pencil className="h-3 w-3" />Edit and resend</button>}{message.role === "assistant" && onFollowUp && <button type="button" className={actionClass} onClick={() => onFollowUp("Can you go deeper on the most important part?")}>Follow up</button>}</div>;
+ const copy = () => {
+ void navigator.clipboard.writeText(message.text);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1600);
+ };
+
+ return (
+ <div className="mt-2 space-y-1.5">
+ {error && (
+ <div role="alert" className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
+ <span aria-hidden className="h-1.5 w-1.5 shrink-0 rounded-full bg-[var(--color-error)]" />
+ <span className="min-w-0 text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">{error}</span>
+ {onRetry && (
+ <button
+ type="button"
+ onClick={() => void onRetry()}
+ className="inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-xs font-medium text-[var(--color-text-secondary)] 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)]"
+ >
+ <RotateCcw aria-hidden className="h-3.5 w-3.5" />
+ Retry
+ </button>
+ )}
+ </div>
+ )}
+ {message.text && (
+ <div
+ role="group"
+ aria-label={`${message.role} message actions`}
+ className={cn(
+ "flex items-center gap-0.5 transition-opacity motion-reduce:transition-none",
+ align === "end" && "justify-end",
+ !pinned &&
+ "pointer-fine:opacity-0 pointer-fine:group-hover/turn:opacity-100 group-focus-within/turn:opacity-100",
+ )}
+ >
+ <button
+ type="button"
+ className={ICON_BUTTON}
+ onClick={copy}
+ aria-label={copied ? "Copied" : "Copy"}
+ title="Copy"
+ >
+ {copied ? <Check aria-hidden className="h-3.5 w-3.5" /> : <Copy aria-hidden className="h-3.5 w-3.5" />}
+ </button>
+ {message.role === "assistant" && onRetry && !error && (
+ <button type="button" className={ICON_BUTTON} onClick={() => void onRetry()} aria-label="Retry" title="Retry">
+ <RotateCcw aria-hidden className="h-3.5 w-3.5" />
+ </button>
+ )}
+ {message.role === "user" && message.serverId && onEditAndResend && (
+ <button
+ type="button"
+ className={ICON_BUTTON}
+ onClick={() => setEditing(true)}
+ aria-label="Edit and resend"
+ title="Edit and resend"
+ >
+ <Pencil aria-hidden className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ );
}
diff --git a/packages/ui/src/chat/source-citations.tsx b/packages/ui/src/chat/source-citations.tsx
index 79ea46b3a..fd73553e3 100644
--- a/packages/ui/src/chat/source-citations.tsx
+++ b/packages/ui/src/chat/source-citations.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMemo } from "react";
-import { ArrowUpRight } from "lucide-react";
+import { ChevronRight } from "lucide-react";
import { getPageTypeIcon } from "../lib/page-types";
import { filePageId } from "../shared/entity/routes";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
@@ -224,36 +224,35 @@ export function SourceCitations({
if (sources.length === 0) return null;
return (
- <details className="group/cites mt-5 border-t border-[var(--color-border-default)] pt-3">
- <summary className="flex min-h-8 cursor-pointer list-none items-center gap-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] marker:hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] [&::-webkit-details-marker]:hidden">
- <span>Sources · {sources.length}</span>
- <span aria-hidden className="transition-transform group-open/cites:rotate-90">›</span>
+ <details className="group/cites">
+ <summary className="inline-flex min-h-8 cursor-pointer list-none items-center gap-1.5 rounded-md text-xs text-[var(--color-text-tertiary)] marker:hidden hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] [&::-webkit-details-marker]:hidden">
+ <span className="tabular-nums">Sources · {sources.length}</span>
+ <ChevronRight aria-hidden className="h-3 w-3 transition-transform group-open/cites:rotate-90 motion-reduce:transition-none" />
</summary>
- {/* Links, not chips. Each one goes somewhere, so the accent is earned on
- hover; a border and a ground on every entry turned a list of eight
- into a wall of boxes that outweighed the answer above it. The counter
- badge went with them — numbering is only worth its weight when the
- prose cites [1], and a reply does not. */}
- <ul className="flex flex-col gap-1.5 pb-1 pt-2">
+ {/* Links, not chips: each goes somewhere, so the accent is earned on
+ hover. Titles wrap rather than truncate. */}
+ <ul className="flex flex-col gap-1 pb-1 pt-1">
{sources.map((source) => (
<li key={source.id}>
<a
href={buildHref ? buildHref(source) : defaultBuildHref(source, prefix)}
- className="group flex w-full min-w-0 items-baseline gap-2 text-[13px] text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"
+ className="group flex min-h-8 w-full min-w-0 flex-wrap items-baseline gap-x-2 rounded-md py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
>
<SourceIcon
pageType={source.pageType}
className="h-3.5 w-3.5 shrink-0 self-center text-[var(--color-text-tertiary)] group-hover:text-[var(--color-accent-primary)] transition-colors"
/>
- {/* No truncation: a cut title reports a layout decision to the
- reader as missing content. Long ones wrap. */}
- <span className="min-w-0 font-medium [overflow-wrap:anywhere]">{source.title}</span>
+ <span className="min-w-0 [overflow-wrap:anywhere]">{source.title}</span>
+ {source.targetPath && source.targetPath !== source.title && (
+ <span className="min-w-0 font-mono text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">
+ {source.targetPath}
+ </span>
+ )}
{source.confidence != null && (
- <span className="font-mono text-[11px] text-[var(--color-text-tertiary)] tabular-nums">
+ <span className="font-mono text-[var(--color-text-tertiary)] tabular-nums">
{(source.confidence * 100).toFixed(0)}%
</span>
)}
- <ArrowUpRight className="h-3 w-3 shrink-0 self-center opacity-0 group-hover:opacity-100 transition-opacity" />
</a>
</li>
))}
diff --git a/packages/ui/src/chat/tool-call-block.tsx b/packages/ui/src/chat/tool-call-block.tsx
index c4b06b09f..eb6f702ea 100644
--- a/packages/ui/src/chat/tool-call-block.tsx
+++ b/packages/ui/src/chat/tool-call-block.tsx
@@ -1,21 +1,15 @@
"use client";
/**
- * One step of the model's work, as a hairline row.
- *
- * It used to be a bordered `bg-elevated` box that `ToolCallGroup` then nested
- * inside another bordered `bg-elevated` box — the same plane twice, with two
- * borders around it. The group owns the container now; a step is a row.
- *
- * A finished step carries no success badge. A green check on every completed
- * row says nothing, because success is the default and the failure case is what
- * needs marking. Only a *running* step shows a marker, and only while it runs.
+ * One step of the model's work as a quiet text row. A finished step carries
+ * no success badge: success is the default, so only a failure is marked. The
+ * live progress marker belongs to the turn (see `chat-stage`), not the row.
*/
-import { useState } from "react";
-import { ChevronDown, ChevronRight, ArrowUpRight } from "lucide-react";
+import { useMemo, useState } from "react";
+import { ArrowUpRight, ChevronRight } from "lucide-react";
import { cn } from "../lib/cn";
-import { WorkingOrb } from "./working-orb";
+import { HighlightedCodeBlock } from "../shared/code-block";
import type { ChatUIToolCall } from "@repowise-dev/types/chat";
const TOOL_LABELS: Record<string, string> = {
@@ -28,104 +22,99 @@ const TOOL_LABELS: Record<string, string> = {
get_why: "Querying decisions",
search_codebase: "Searching codebase",
get_dead_code: "Checking dead code",
+ get_answer: "Asking the index",
};
/** A step the server took for the page, before the model's first turn. */
const GROUNDING_LABEL = "Read for this page";
-const MICRO_LABEL =
- "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+const RESULT_PREVIEW_CHARS = 2000;
+
+/** `get_blast_radius` reads as "Blast radius" for a tool with no label. */
+export function readableToolName(name: string): string {
+ const words = name.replace(/^get_/, "").replace(/[_-]+/g, " ").trim();
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : name;
+}
+
+export function toolCallLabel(toolCall: ChatUIToolCall): string {
+ if (toolCall.origin === "grounding") return GROUNDING_LABEL;
+ return TOOL_LABELS[toolCall.name] ?? readableToolName(toolCall.name);
+}
interface ToolCallBlockProps {
toolCall: ChatUIToolCall;
onViewArtifact?: () => void;
- /** Renders the top hairline. Omitted on the first row of a group. */
+ /** @deprecated Rows no longer draw dividers. Ignored. */
divided?: boolean;
}
-export function ToolCallBlock({
- toolCall,
- onViewArtifact,
- divided = false,
-}: ToolCallBlockProps) {
+export function ToolCallBlock({ toolCall, onViewArtifact }: ToolCallBlockProps) {
const [expanded, setExpanded] = useState(false);
- const label =
- toolCall.origin === "grounding"
- ? GROUNDING_LABEL
- : TOOL_LABELS[toolCall.name] ?? toolCall.name;
+ const label = toolCallLabel(toolCall);
const isRunning = toolCall.status === "running";
const isError = toolCall.status === "error";
+ // Serialised once per open, not on every render of a streaming turn.
+ const input = useMemo(
+ () => (expanded ? JSON.stringify(toolCall.arguments, null, 2) : ""),
+ [expanded, toolCall.arguments],
+ );
+ const result = useMemo(() => {
+ if (!expanded || !toolCall.result) return "";
+ const full = JSON.stringify(toolCall.result, null, 2);
+ return full.length > RESULT_PREVIEW_CHARS ? `${full.slice(0, RESULT_PREVIEW_CHARS)}\n...` : full;
+ }, [expanded, toolCall.result]);
+
return (
- <div
- data-tool-origin={toolCall.origin}
- className={cn(
- "text-xs",
- divided && "border-t border-[var(--color-border-default)]",
- )}
- >
- <div className="flex items-center gap-2 px-3 py-2">
+ <div data-tool-origin={toolCall.origin} className="text-xs">
+ <div className="flex min-h-8 items-center gap-2">
<button
type="button"
- className="flex flex-1 min-w-0 items-center gap-2 text-left"
+ className="flex min-h-8 min-w-0 flex-1 items-center gap-1.5 rounded-md text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
onClick={() => !isRunning && setExpanded((e) => !e)}
disabled={isRunning}
aria-expanded={expanded}
>
- {isRunning && <WorkingOrb />}
- <span className="font-medium text-[var(--color-text-secondary)]">
- {label}
- </span>
+ <span className="shrink-0 text-[var(--color-text-secondary)]">{label}</span>
{!isRunning && (toolCall.summary || isError) && (
// The server already composes a failed summary as "Error: ...", so
// a separate Failed badge beside it just says the same thing twice.
<span
+ title={toolCall.summary || "Failed"}
className={cn(
- "truncate ml-1",
- isError
- ? "text-[var(--color-error)]"
- : "text-[var(--color-text-tertiary)]",
+ "min-w-0 truncate",
+ isError ? "text-[var(--color-error)]" : "text-[var(--color-text-tertiary)]",
)}
>
- — {toolCall.summary || "Failed"}
+ · {toolCall.summary || "Failed"}
</span>
)}
- </button>
- <span className="ml-auto flex items-center gap-2 shrink-0">
- {toolCall.artifact && onViewArtifact && !isRunning && (
- <button
- type="button"
- onClick={onViewArtifact}
- className="text-[var(--color-accent-primary)] hover:underline flex items-center gap-0.5"
- >
- View <ArrowUpRight className="h-3 w-3" />
- </button>
+ {!isRunning && (
+ <ChevronRight
+ aria-hidden
+ className={cn(
+ "h-3 w-3 shrink-0 text-[var(--color-text-tertiary)] transition-transform motion-reduce:transition-none",
+ expanded && "rotate-90",
+ )}
+ />
)}
- {!isRunning &&
- (expanded ? (
- <ChevronDown className="h-3 w-3 text-[var(--color-text-tertiary)]" />
- ) : (
- <ChevronRight className="h-3 w-3 text-[var(--color-text-tertiary)]" />
- ))}
- </span>
+ </button>
+ {toolCall.artifact && onViewArtifact && !isRunning && (
+ <button
+ type="button"
+ onClick={onViewArtifact}
+ className="inline-flex min-h-8 shrink-0 items-center gap-0.5 rounded-md px-1 text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ View <ArrowUpRight aria-hidden className="h-3 w-3" />
+ </button>
+ )}
</div>
{expanded && (
- <div className="px-3 pb-2.5 space-y-2.5">
- <div>
- <span className={MICRO_LABEL}>Input</span>
- <pre className="mt-1 text-[10px] font-mono text-[var(--color-text-secondary)] overflow-x-auto max-h-32 overflow-y-auto">
- {JSON.stringify(toolCall.arguments, null, 2)}
- </pre>
- </div>
- {toolCall.result && (
- <div>
- <span className={MICRO_LABEL}>Result</span>
- <pre className="mt-1 text-[10px] font-mono text-[var(--color-text-secondary)] overflow-x-auto max-h-48 overflow-y-auto">
- {JSON.stringify(toolCall.result, null, 2).slice(0, 2000)}
- {JSON.stringify(toolCall.result).length > 2000 ? "\n..." : ""}
- </pre>
- </div>
+ <div className="pb-1">
+ <HighlightedCodeBlock code={input} language="json" label="Input" compact className="my-1.5" />
+ {result && (
+ <HighlightedCodeBlock code={result} language="json" label="Result" compact className="my-1.5" />
)}
</div>
)}
diff --git a/packages/ui/src/chat/tool-call-group.tsx b/packages/ui/src/chat/tool-call-group.tsx
index e40585ea5..e123bad17 100644
--- a/packages/ui/src/chat/tool-call-group.tsx
+++ b/packages/ui/src/chat/tool-call-group.tsx
@@ -1,9 +1,10 @@
"use client";
import { useState } from "react";
-import { ChevronDown, ChevronRight } from "lucide-react";
+import { ChevronRight } from "lucide-react";
+import { cn } from "../lib/cn";
import { ToolCallBlock } from "./tool-call-block";
-import { WorkingOrb } from "./working-orb";
+import { chatToolKind } from "./chat-stage";
import type { ChatArtifact, ChatUIToolCall } from "@repowise-dev/types/chat";
interface ToolCallGroupProps {
@@ -11,74 +12,91 @@ interface ToolCallGroupProps {
onViewArtifact?: (artifact: ChatArtifact) => void;
}
+function plural(count: number, one: string, many: string) {
+ return `${count} ${count === 1 ? one : many}`;
+}
+
+/** Pages a reading step covered: one per named target, else one. */
+function pagesRead(toolCall: ChatUIToolCall) {
+ const targets = toolCall.arguments.targets;
+ return Array.isArray(targets) && targets.length > 0 ? targets.length : 1;
+}
+
+/** "Read 4 pages · 2 searches", from what the steps did. */
+export function summarizeToolCalls(toolCalls: readonly ChatUIToolCall[]): string {
+ let pages = 0;
+ let searches = 0;
+ let checks = 0;
+ let failed = 0;
+ for (const call of toolCalls) {
+ if (call.status === "error") failed += 1;
+ const kind = chatToolKind(call.name);
+ if (call.origin === "grounding" || kind === "tracing") pages += pagesRead(call);
+ else if (kind === "searching") searches += 1;
+ else checks += 1;
+ }
+ return [
+ pages > 0 ? `Read ${plural(pages, "page", "pages")}` : null,
+ searches > 0 ? plural(searches, "search", "searches") : null,
+ checks > 0 ? plural(checks, "check", "checks") : null,
+ failed > 0 ? `${failed} failed` : null,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+}
+
/**
- * Collapses a run of tool calls into a single "thinking" group instead of N
- * stacked bordered boxes. Auto-expands while any step is running so progress
- * stays visible; collapses to a one-line summary once the work is done.
- *
- * The group owns the one border and the one ground. Steps inside it are
- * hairline rows — nesting a bordered box inside a bordered box of the same
- * plane was the "box soup" the section style exists to remove, and it happened
- * once per step.
+ * The model's work as one quiet line. A lone step reads as itself ("Read for
+ * this page · src/a.py"); several collapse into a count ("Read 4 pages ·
+ * 2 searches ›") that opens to the rows. No border, no ground.
*/
export function ToolCallGroup({ toolCalls, onViewArtifact }: ToolCallGroupProps) {
- const running = toolCalls.some((tc) => tc.status === "running");
const [expanded, setExpanded] = useState(false);
if (toolCalls.length === 0) return null;
- const shell =
- "border-y border-[var(--color-border-default)] text-xs overflow-hidden";
+ const viewHandler = (call: ChatUIToolCall) => {
+ const artifact = call.artifact;
+ return artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;
+ };
- // A lone tool call doesn't need a group wrapper, but it still needs the
- // container the row no longer carries itself.
if (toolCalls.length === 1) {
- const tc = toolCalls[0]!;
- const artifact = tc.artifact;
- const handler = artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;
+ const call = toolCalls[0]!;
+ const handler = viewHandler(call);
return (
- <div data-activity-trail="true" className={shell}>
- <ToolCallBlock toolCall={tc} {...(handler ? { onViewArtifact: handler } : {})} />
+ <div data-activity-trail="true">
+ <ToolCallBlock toolCall={call} {...(handler ? { onViewArtifact: handler } : {})} />
</div>
);
}
- const open = expanded || running;
+ const summary = summarizeToolCalls(toolCalls);
return (
- <div data-activity-trail="true" className={shell}>
+ <div data-activity-trail="true" className="text-xs">
<button
type="button"
- className="flex w-full items-center gap-2 px-3 py-2 text-left"
+ className="inline-flex min-h-8 max-w-full items-center gap-1.5 rounded-md text-left text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
onClick={() => setExpanded((e) => !e)}
- aria-expanded={open}
+ aria-expanded={expanded}
>
- {running && <WorkingOrb />}
- <span className="font-medium text-[var(--color-text-secondary)]">
- {running ? "Working" : "Activity"}
- </span>
- <span className="text-[var(--color-text-tertiary)] tabular-nums">
- · {toolCalls.length} steps
- </span>
- <span className="ml-auto shrink-0">
- {open ? (
- <ChevronDown className="h-3 w-3 text-[var(--color-text-tertiary)]" />
- ) : (
- <ChevronRight className="h-3 w-3 text-[var(--color-text-tertiary)]" />
+ <span className="min-w-0 truncate tabular-nums">{summary}</span>
+ <ChevronRight
+ aria-hidden
+ className={cn(
+ "h-3 w-3 shrink-0 transition-transform motion-reduce:transition-none",
+ expanded && "rotate-90",
)}
- </span>
+ />
</button>
- {open && (
- <div className="border-t border-[var(--color-border-default)]">
- {toolCalls.map((tc, idx) => {
- const artifact = tc.artifact;
- const handler =
- artifact && onViewArtifact ? () => onViewArtifact(artifact) : undefined;
+ {expanded && (
+ <div>
+ {toolCalls.map((call) => {
+ const handler = viewHandler(call);
return (
<ToolCallBlock
- key={tc.id}
- toolCall={tc}
- divided={idx > 0}
+ key={call.id}
+ toolCall={call}
{...(handler ? { onViewArtifact: handler } : {})}
/>
);
diff --git a/packages/ui/src/shared/code-block.tsx b/packages/ui/src/shared/code-block.tsx
index ea2eac8df..255fe66db 100644
--- a/packages/ui/src/shared/code-block.tsx
+++ b/packages/ui/src/shared/code-block.tsx
@@ -27,10 +27,14 @@ interface CodeFrameProps {
code: string;
language: string;
children: ReactNode;
+ /** 12px code for narrow columns (dock, tool output); 14px otherwise. */
compact?: boolean;
+ /** Header label. Defaults to the language. */
+ label?: string;
+ className?: string;
}
-export function CodeFrame({ code, language, children, compact = false }: CodeFrameProps) {
+export function CodeFrame({ code, language, children, compact = false, label, className }: CodeFrameProps) {
const [copied, setCopied] = useState(false);
async function copy() {
@@ -40,15 +44,16 @@ export function CodeFrame({ code, language, children, compact = false }: CodeFra
}
return (
- <div className="group my-4 min-w-0 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-inset)]">
- <div className="flex min-h-9 items-center justify-between border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-3">
+ <div className={cn("group/code my-4 min-w-0 overflow-hidden rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-inset)]", className)}>
+ <div className="flex min-h-7 items-center justify-between pl-3 pr-1 pointer-coarse:min-h-8">
<span className="font-mono text-[10px] uppercase tracking-[0.1em] text-[var(--color-text-tertiary)]">
- {language || "text"}
+ {label ?? (language || "text")}
</span>
+ {/* Revealed on hover or focus with a mouse; always shown on touch. */}
<button
type="button"
onClick={() => void copy()}
- className="inline-flex min-h-8 items-center gap-1.5 text-xs text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ className="inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs text-[var(--color-text-tertiary)] transition-opacity hover:text-[var(--color-text-primary)] focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] pointer-fine:opacity-0 pointer-fine:group-hover/code:opacity-100 pointer-coarse:h-8 motion-reduce:transition-none"
aria-label="Copy code"
>
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
@@ -57,10 +62,15 @@ export function CodeFrame({ code, language, children, compact = false }: CodeFra
</div>
{/* Selectable region for the chat selection control. No line numbers:
a fenced snippet's third line is not the third line of any file, and
- a wrong range is worse than none. */}
+ a wrong range is worse than none. The pre rules apply to both the
+ plain streaming pre and Shiki's, so completion swaps colour only and
+ never the block's height. */}
<div
data-chat-selection=""
- className={cn("min-w-0 overflow-x-auto", compact ? "text-[11px]" : "text-sm")}
+ className={cn(
+ "min-w-0 overflow-x-auto [&_code]:font-mono [&_pre]:m-0 [&_pre]:min-w-max [&_pre]:bg-transparent! [&_pre]:font-mono [&_pre]:leading-relaxed [&_pre]:text-[var(--color-text-primary)]",
+ compact ? "text-xs [&_pre]:px-3 [&_pre]:pb-3 [&_pre]:pt-1" : "text-sm [&_pre]:px-4 [&_pre]:pb-4 [&_pre]:pt-1",
+ )}
>
{children}
</div>
@@ -73,6 +83,8 @@ interface HighlightedCodeBlockProps {
language: string;
compact?: boolean;
streaming?: boolean;
+ label?: string;
+ className?: string;
}
export function HighlightedCodeBlock({
@@ -80,6 +92,8 @@ export function HighlightedCodeBlock({
language,
compact = false,
streaming = false,
+ label,
+ className,
}: HighlightedCodeBlockProps) {
const [html, setHtml] = useState<string | null>(null);
@@ -97,15 +111,18 @@ export function HighlightedCodeBlock({
}, [code, language, streaming]);
return (
- <CodeFrame code={code} language={language} compact={compact}>
+ <CodeFrame
+ code={code}
+ language={language}
+ compact={compact}
+ {...(label ? { label } : {})}
+ {...(className ? { className } : {})}
+ >
{!streaming && html ? (
- <div
- className="[&>pre]:m-0 [&>pre]:bg-transparent! [&>pre]:p-4"
- dangerouslySetInnerHTML={{ __html: html }}
- />
+ <div dangerouslySetInnerHTML={{ __html: html }} />
) : (
- <pre className="m-0 min-w-max p-4">
- <code className="font-mono text-[var(--color-text-primary)]">{code}</code>
+ <pre>
+ <code>{code}</code>
</pre>
)}
</CodeFrame>
diff --git a/packages/ui/src/shared/markdown.tsx b/packages/ui/src/shared/markdown.tsx
index 6daa6854a..4e21f78f8 100644
--- a/packages/ui/src/shared/markdown.tsx
+++ b/packages/ui/src/shared/markdown.tsx
@@ -20,9 +20,13 @@
* The face stays sans. Serif is bounded to the named wiki reading surfaces so
* the mark keeps meaning "this is a document"; a reply is prose, not a document.
*
- * `density="compact"` keeps the old chrome scale for consumers that render the
- * same markdown inside a narrow panel, where 16px body would not fit the column
- * it is given. One component, one prop — not a second renderer.
+ * `density="narrow"` steps the reading scale down to 14px for the chat dock;
+ * `density="compact"` keeps the chrome scale for side panels where 16px body
+ * would not fit the column. One component, one prop, not a second renderer.
+ *
+ * Streaming is read from context rather than baked into the component map, so
+ * the map keeps its identity when an answer completes: code blocks stay
+ * mounted in their final frame instead of remounting with a height jump.
*
* Inline code is deliberately *not* accent-coloured. Nothing here resolves to a
* page, so an accent path would be decoration on something that does not
@@ -30,7 +34,14 @@
* renderer already fixed.
*/
-import { lazy, Suspense, useMemo } from "react";
+import {
+ createContext,
+ lazy,
+ Suspense,
+ useContext,
+ useMemo,
+ type ComponentPropsWithoutRef,
+} from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Components } from "react-markdown";
@@ -46,7 +57,7 @@ const MermaidDiagram = lazy(() =>
const MICRO_LABEL =
"font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
-export type MarkdownDensity = "reading" | "compact";
+export type MarkdownDensity = "reading" | "narrow" | "compact";
interface Scale {
h1: string;
@@ -59,6 +70,8 @@ interface Scale {
gap: string;
listIndent: string;
rule: string;
+ /** Table width rule. Only the reading column can afford a 640px floor. */
+ table: string;
}
const SCALES: Record<MarkdownDensity, Scale> = {
@@ -73,6 +86,20 @@ const SCALES: Record<MarkdownDensity, Scale> = {
gap: "mb-4",
listIndent: "ml-5",
rule: "my-6",
+ table: "w-full min-w-[640px]",
+ },
+ narrow: {
+ h1: "text-lg mt-6 mb-2.5",
+ h2: "text-base mt-5 mb-2",
+ h3: "text-[15px] mt-4 mb-1.5",
+ body: "text-sm",
+ list: "text-sm space-y-1",
+ block: "my-3",
+ code: "text-xs",
+ gap: "mb-3",
+ listIndent: "ml-5",
+ rule: "my-5",
+ table: "w-full",
},
compact: {
h1: "text-base mt-4 mb-2",
@@ -81,15 +108,54 @@ const SCALES: Record<MarkdownDensity, Scale> = {
body: "text-xs",
list: "text-xs space-y-1",
block: "my-2",
- code: "text-[11px]",
+ code: "text-xs",
gap: "mb-2",
listIndent: "ml-4",
rule: "my-3",
+ table: "w-full",
},
};
-function buildComponents(s: Scale, streaming: boolean): Components {
- const measure = s.body === "text-base" ? "max-w-[72ch]" : "max-w-full";
+const StreamingContext = createContext(false);
+
+function MarkdownCode({
+ className,
+ children,
+ node: _node,
+ compact,
+ ...props
+}: ComponentPropsWithoutRef<"code"> & { node?: unknown; compact: boolean }) {
+ const streaming = useContext(StreamingContext);
+ const declaredLanguage = className?.match(/language-([^\s]+)/)?.[1];
+ const rawCode = String(children ?? "");
+ const isBlock = Boolean(declaredLanguage) || rawCode.includes("\n");
+ if (isBlock) {
+ const language = declaredLanguage ?? "text";
+ const code = rawCode.replace(/\n$/, "");
+ if (language === "mermaid") {
+ const source = <pre><code>{code}</code></pre>;
+ return (
+ <CodeFrame code={code} language={language} compact={compact}>
+ {streaming ? source : <Suspense fallback={source}><MermaidDiagram chart={code} /></Suspense>}
+ </CodeFrame>
+ );
+ }
+ return <HighlightedCodeBlock code={code} language={language} compact={compact} streaming={streaming} />;
+ }
+ // 0.85em, relative: Geist Mono runs wider and taller than Geist at the
+ // same nominal size, so 1em mono inside 16px sans reads oversized.
+ return (
+ <code
+ className="break-all whitespace-normal rounded px-1 py-0.5 bg-[var(--color-bg-inset)] text-[var(--color-text-primary)] text-[0.85em] font-mono [overflow-wrap:anywhere]"
+ {...props}
+ >
+ {children}
+ </code>
+ );
+}
+
+function buildComponents(s: Scale, measure: string): Components {
+ const compact = s.body !== "text-base";
return {
h1: ({ children }) => (
<h1
@@ -137,39 +203,7 @@ function buildComponents(s: Scale, streaming: boolean): Components {
input: ({ type, node: _node, ...props }) => type === "checkbox" ? (
<input type="checkbox" disabled className="mr-2 align-middle accent-[var(--color-accent-secondary)]" {...props} />
) : <input type={type} {...props} />,
- code: ({ className, children, node: _node, ...props }) => {
- const declaredLanguage = className?.match(/language-([^\s]+)/)?.[1];
- const rawCode = String(children ?? "");
- const isBlock = Boolean(declaredLanguage) || rawCode.includes("\n");
- if (isBlock) {
- const language = declaredLanguage ?? "text";
- const code = rawCode.replace(/\n$/, "");
- if (language === "mermaid") {
- return (
- <CodeFrame code={code} language={language} compact={s.body !== "text-base"}>
- {streaming ? (
- <pre className="m-0 min-w-max p-4"><code className="font-mono text-[var(--color-text-primary)]">{code}</code></pre>
- ) : (
- <Suspense fallback={<pre className="m-0 min-w-max p-4"><code className="font-mono text-[var(--color-text-primary)]">{code}</code></pre>}>
- <MermaidDiagram chart={code} />
- </Suspense>
- )}
- </CodeFrame>
- );
- }
- return <HighlightedCodeBlock code={code} language={language} compact={s.body !== "text-base"} streaming={streaming} />;
- }
- // 0.85em, relative: Geist Mono runs wider and taller than Geist at the
- // same nominal size, so 1em mono inside 16px sans reads oversized.
- return (
- <code
- className="break-all whitespace-normal rounded px-1 py-0.5 bg-[var(--color-bg-inset)] text-[var(--color-text-primary)] text-[0.85em] font-mono [overflow-wrap:anywhere]"
- {...props}
- >
- {children}
- </code>
- );
- },
+ code: (props) => <MarkdownCode {...props} compact={compact} />,
pre: ({ children }) => <>{children}</>,
blockquote: ({ children }) => (
<blockquote
@@ -190,7 +224,7 @@ function buildComponents(s: Scale, streaming: boolean): Components {
),
table: ({ children }) => (
<div className={`${s.block} max-w-full overflow-x-auto overscroll-x-contain border-y border-[var(--color-border-default)]`}>
- <table className={`${s.code} w-full min-w-[640px] border-collapse`}>{children}</table>
+ <table className={`${s.code} ${s.table} border-collapse`}>{children}</table>
</div>
),
thead: ({ children }) => (
@@ -226,21 +260,29 @@ function buildComponents(s: Scale, streaming: boolean): Components {
export interface MarkdownProps {
content: string;
- /** `compact` keeps chrome sizes for narrow panels. */
+ /** `narrow` for the chat dock, `compact` for chrome-sized side panels. */
density?: MarkdownDensity;
/** Defers expensive code/diagram rendering until the answer is complete. */
streaming?: boolean;
+ /** Fill the host column instead of capping prose at 72ch. For hosts that
+ * already set a reading width, such as the chat column. */
+ fill?: boolean;
}
-export function Markdown({ content, density = "reading", streaming = false }: MarkdownProps) {
+const REMARK_PLUGINS = [remarkGfm];
+
+export function Markdown({ content, density = "reading", streaming = false, fill = false }: MarkdownProps) {
+ const measure = density === "reading" && !fill ? "max-w-[72ch]" : "max-w-full";
const components = useMemo(
- () => buildComponents(SCALES[density], streaming),
- [density, streaming],
+ () => buildComponents(SCALES[density], measure),
+ [density, measure],
);
return (
- <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>
- {content}
- </ReactMarkdown>
+ <StreamingContext.Provider value={streaming}>
+ <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={components}>
+ {content}
+ </ReactMarkdown>
+ </StreamingContext.Provider>
);
}
diff --git a/packages/web/src/app/repos/[id]/chat/page.tsx b/packages/web/src/app/repos/[id]/chat/page.tsx
index dbb5ff9cf..406287dc5 100644
--- a/packages/web/src/app/repos/[id]/chat/page.tsx
+++ b/packages/web/src/app/repos/[id]/chat/page.tsx
@@ -18,14 +18,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
}
}
-/**
- * Thin shell. The page used to render its own header — repo name, local path,
- * branch and SHA — directly under the repo breadcrumb and directly above the
- * chat's own control row, so three hairlines ran before the first word of
- * content and the repo name appeared twice. The breadcrumb already names the
- * repo; branch and SHA are orientation, so they ride the empty state's status
- * line next to the file and doc counts, where the other figures already are.
- */
+/** Thin shell: the breadcrumb already names the repo, so the chat owns the page. */
export default async function RepoChatPage({ params, searchParams }: Props) {
const { id } = await params;
const { q } = await searchParams;
@@ -42,8 +35,6 @@ export default async function RepoChatPage({ params, searchParams }: Props) {
<ChatInterface
repoId={id}
repoName={repo.name}
- defaultBranch={repo.default_branch}
- {...(repo.head_commit ? { headCommit: repo.head_commit } : {})}
{...(q ? { initialQuestion: q } : {})}
/>
</div>
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index 114b355a6..a9060abeb 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -8,7 +8,6 @@ import { ChatInterface as ChatInterfaceShell } from "@repowise-dev/ui/chat/chat-
import { getArtifactSourceTarget, useChatDraft } from "@repowise-dev/ui/chat";
import { pageHref } from "@/lib/utils/page-href";
import { getProviders } from "@/lib/api/providers";
-import { getRepoStats } from "@/lib/api/repos";
import { forkConversation, setConversationArtifactPinned } from "@/lib/api/chat";
import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
import { ModelSelector } from "./model-selector";
@@ -19,10 +18,6 @@ import { useTranslations } from "next-intl";
interface ChatInterfaceProps {
repoId: string;
repoName?: string;
- /** Branch shown in the empty-state status line. */
- defaultBranch?: string;
- /** HEAD SHA shown in the empty-state status line, abbreviated to 7. */
- headCommit?: string;
/** Question to send immediately on mount (quick-ask deep links, `?q=`). */
initialQuestion?: string;
}
@@ -30,8 +25,6 @@ interface ChatInterfaceProps {
export function ChatInterface({
repoId,
repoName,
- defaultBranch,
- headCommit,
initialQuestion,
}: ChatInterfaceProps) {
const t = useTranslations("chat");
@@ -74,13 +67,6 @@ export function ChatInterface({
const anyConfigured =
providers === undefined || providers.providers.some((p) => p.configured);
- // Orientation status line for the empty state.
- const { data: stats } = useSWR(
- `repo-stats:${repoId}`,
- () => getRepoStats(repoId),
- { revalidateOnFocus: false },
- );
-
// A plain /chat URL is an explicit fresh workspace. Only an addressable
// conversation URL restores history, which keeps returning users from being
// dropped at the bottom of an old answer they did not choose to reopen.
@@ -129,11 +115,17 @@ export function ChatInterface({
...(selectedProvider ? { provider: selectedProvider } : {}),
...(selectedModel ? { model: selectedModel } : {}),
}), [pageContext, selectedModel, selectedProvider, sendMessage]);
+ // Read through a ref so the callback keeps its identity while tokens stream;
+ // otherwise every memoised turn re-renders on each token.
+ const messagesRef = useRef(messages);
+ messagesRef.current = messages;
const retryMessage = useCallback((message: ChatUIMessage) => {
- const index = messages.findIndex((candidate) => candidate.id === message.id);
- const previousUser = messages.slice(0, index).reverse().find((candidate) => candidate.role === "user");
+ if (message.role === "user") return sendWithConversationModel(message.text);
+ const all = messagesRef.current;
+ const index = all.findIndex((candidate) => candidate.id === message.id);
+ const previousUser = all.slice(0, index).reverse().find((candidate) => candidate.role === "user");
if (previousUser) return sendWithConversationModel(previousUser.text);
- }, [messages, sendWithConversationModel]);
+ }, [sendWithConversationModel]);
const editAndResend = useCallback(async (message: ChatUIMessage, text: string) => {
if (!conversationId || !message.serverId) return;
const fork = await forkConversation(repoId, conversationId, { beforeMessageId: message.serverId });
@@ -200,24 +192,6 @@ export function ChatInterface({
onArtifactPin={pinArtifact}
onOpenArtifactSource={openArtifactSource}
artifactOverrides={artifactOverrides}
- statusSlot={
- // Orientation, in one line: what was indexed, and which commit it was
- // indexed from. The branch and SHA used to sit in a second page header
- // that duplicated the breadcrumb; they belong with the other figures.
- <span>
- {[
- stats ? `${stats.file_count.toLocaleString()} files` : null,
- stats ? `${Math.round(stats.doc_coverage_pct)}% documented` : null,
- stats && stats.symbol_count > 0
- ? `${stats.symbol_count.toLocaleString()} symbols indexed`
- : null,
- defaultBranch,
- headCommit ? headCommit.slice(0, 7) : null,
- ]
- .filter(Boolean)
- .join(" · ")}
- </span>
- }
sendDisabled={!anyConfigured}
sendDisabledReason={
<span>