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): reach a scoped composer in one gesture from any repository page (#2190)

Raghav Chamadiya9dac9a30a16d
diff --git a/packages/server/src/repowise/server/chat_grounding.py b/packages/server/src/repowise/server/chat_grounding.py
index f2651fe4e..8640f70e9 100644
--- a/packages/server/src/repowise/server/chat_grounding.py
+++ b/packages/server/src/repowise/server/chat_grounding.py
@@ -28,6 +28,11 @@ _PREFETCH_BY_KIND: dict[str, tuple[str, str, bool]] = {
"module": ("get_context", "targets", True),
"symbol": ("get_symbol", "symbol_id", False),
"risk": ("get_risk", "targets", True),
+ # Dead code and blast radius are separate page kinds so their seeded
+ # questions fit, but the evidence a reader needs on both is what depends on
+ # the selected files, which is what get_risk reports.
+ "dead-code": ("get_risk", "targets", True),
+ "blast-radius": ("get_risk", "targets", True),
"health": ("get_health", "targets", True),
"decision": ("get_why", "id", False),
"commit": ("get_change_risk", "revspec", False),
diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.py
index 3f90e8959..3144fd6f8 100644
--- a/packages/server/src/repowise/server/schemas/chat.py
+++ b/packages/server/src/repowise/server/schemas/chat.py
@@ -30,6 +30,8 @@ class ChatPageContext(BaseModel):
"contributor",
"decision",
"risk",
+ "dead-code",
+ "blast-radius",
"security",
"usage",
"settings",
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index a03611a37..bce4e5fcb 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -31,6 +31,8 @@ export type ChatContextKind =
| "contributor"
| "decision"
| "risk"
+ | "dead-code"
+ | "blast-radius"
| "security"
| "usage"
| "settings"
@@ -54,6 +56,33 @@ export interface ChatContext {
targetKind?: ChatContextTargetKind;
}
+/** A passage the reader highlighted on the page, carried into the composer. */
+export interface ChatSelection {
+ text: string;
+ path?: string;
+ startLine?: number;
+ endLine?: number;
+}
+
+/** What a page hands to chat when the reader asks about the thing in front of
+ * them. `autoSend` skips the composer and asks immediately. */
+export interface ChatHandoff {
+ context: ChatContext;
+ question?: string;
+ selection?: ChatSelection;
+ autoSend?: boolean;
+}
+
+/** Where a composer chip came from, so ranking and telemetry can tell the
+ * static fallback tier apart from one derived from live page data. */
+export type ChatSuggestionSource = "static" | "page" | "followup";
+
+export interface ChatSuggestion {
+ text: string;
+ source: ChatSuggestionSource;
+ toolHint?: string;
+}
+
// ---------------------------------------------------------------------------
// Conversations + messages
// ---------------------------------------------------------------------------
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 4acfe7745..a5386506d 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -318,7 +318,7 @@ export interface ChatMessageResponse {
/** Navigation metadata supplied by a product chat surface. */
export interface ChatPageContext {
- kind: "repository" | "overview" | "documentation" | "architecture" | "graph" | "health" | "refactoring" | "file" | "symbol" | "module" | "dependency" | "commit" | "contributor" | "decision" | "risk" | "security" | "usage" | "settings" | "chat";
+ kind: "repository" | "overview" | "documentation" | "architecture" | "graph" | "health" | "refactoring" | "file" | "symbol" | "module" | "dependency" | "commit" | "contributor" | "decision" | "risk" | "dead-code" | "blast-radius" | "security" | "usage" | "settings" | "chat";
label: string;
target?: string | null;
target_kind?: "path" | "symbol" | "module" | "dependency" | "commit" | "person" | "decision" | "documentation" | null;
diff --git a/packages/ui/__tests__/chat/chat-dock-command.test.tsx b/packages/ui/__tests__/chat/chat-dock-command.test.tsx
new file mode 100644
index 000000000..929172f16
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-dock-command.test.tsx
@@ -0,0 +1,146 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { ChatDock, type ChatDockProps } from "../../src/chat/chat-dock.js";
+
+function props(overrides: Partial<ChatDockProps> = {}): ChatDockProps {
+ return {
+ storageKey: "dock:r1",
+ repoId: "r1",
+ repoName: "acme",
+ context: { kind: "overview", label: "Overview" },
+ messages: [],
+ isStreaming: false,
+ onSend: vi.fn(),
+ onCancel: vi.fn(),
+ ...overrides,
+ };
+}
+
+const composer = () => screen.getByRole("textbox") as HTMLTextAreaElement;
+
+describe("ChatDock handoff receiver", () => {
+ beforeEach(() => window.localStorage.clear());
+
+ it("opens compact, seeds the question and focuses the composer", async () => {
+ render(
+ <ChatDock
+ {...props({
+ command: {
+ id: 1,
+ type: "handoff",
+ handoff: {
+ context: { kind: "file", label: "a.py", target: "a.py", targetKind: "path" },
+ question: "What is a.py for?",
+ },
+ },
+ })}
+ />,
+ );
+
+ expect(
+ await screen.findByRole("complementary", { name: "Repository chat" }),
+ ).toBeInTheDocument();
+ await waitFor(() => expect(composer().value).toBe("What is a.py for?"));
+ await waitFor(() => expect(document.activeElement).toBe(composer()));
+ });
+
+ it("sends the handoff's own context, not the route's, when autoSend is set", async () => {
+ const onSend = vi.fn();
+ const context = {
+ kind: "file" as const,
+ label: "a.py",
+ target: "a.py",
+ targetKind: "path" as const,
+ };
+ render(
+ <ChatDock
+ {...props({
+ onSend,
+ command: {
+ id: 1,
+ type: "handoff",
+ handoff: { context, question: "Explain a.py.", autoSend: true },
+ },
+ })}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(onSend).toHaveBeenCalledWith("Explain a.py.", context),
+ );
+ await waitFor(() => expect(composer().value).toBe(""));
+ });
+
+ it("reports the command back so a remount does not replay it", async () => {
+ const onCommandHandled = vi.fn();
+ render(
+ <ChatDock
+ {...props({
+ onCommandHandled,
+ command: { id: 1, type: "toggle" },
+ })}
+ />,
+ );
+ await waitFor(() => expect(onCommandHandled).toHaveBeenCalledTimes(1));
+ });
+
+ it("holds a command issued while suppressed and applies it on return", async () => {
+ const onCommandHandled = vi.fn();
+ const command = { id: 1, type: "toggle" as const };
+ const view = render(
+ <ChatDock {...props({ suppressed: true, command, onCommandHandled })} />,
+ );
+ // Nothing is rendered, so consuming the command here would lose it.
+ expect(onCommandHandled).not.toHaveBeenCalled();
+
+ view.rerender(<ChatDock {...props({ command, onCommandHandled })} />);
+
+ expect(
+ await screen.findByRole("complementary", { name: "Repository chat" }),
+ ).toBeInTheDocument();
+ expect(onCommandHandled).toHaveBeenCalledTimes(1);
+ });
+
+ it("toggles open from minimized and back again", async () => {
+ const view = render(<ChatDock {...props({ command: { id: 1, type: "toggle" } })} />);
+ expect(
+ await screen.findByRole("complementary", { name: "Repository chat" }),
+ ).toBeInTheDocument();
+
+ view.rerender(<ChatDock {...props({ command: { id: 2, type: "toggle" } })} />);
+ expect(
+ await screen.findByRole("button", { name: "Open repository chat" }),
+ ).toBeInTheDocument();
+ });
+
+ it("shows every suggestion for the page, not only the first", async () => {
+ render(<ChatDock {...props({ command: { id: 1, type: "toggle" } })} />);
+ await screen.findByRole("complementary", { name: "Repository chat" });
+
+ expect(
+ screen.getByRole("button", { name: "Explain the main architectural boundaries" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Where should a new contributor start?" }),
+ ).toBeInTheDocument();
+ });
+
+ it("introduces itself once and then returns to rest", async () => {
+ vi.useFakeTimers();
+ try {
+ const onFirstVisitHintShown = vi.fn();
+ render(
+ <ChatDock
+ {...props({ firstVisitHint: "Press ? to open chat", onFirstVisitHintShown })}
+ />,
+ );
+ expect(screen.getByText("Press ? to open chat")).toBeInTheDocument();
+ expect(onFirstVisitHintShown).toHaveBeenCalledTimes(1);
+
+ act(() => void vi.advanceTimersByTime(8000));
+ expect(screen.queryByText("Press ? to open chat")).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/ui/__tests__/chat/chat-dock.test.tsx b/packages/ui/__tests__/chat/chat-dock.test.tsx
index 42a7eae4a..79662c61a 100644
--- a/packages/ui/__tests__/chat/chat-dock.test.tsx
+++ b/packages/ui/__tests__/chat/chat-dock.test.tsx
@@ -48,11 +48,17 @@ describe("ChatDock", () => {
expect(screen.getByRole("button", { name: "Open repository chat" })).toBeInTheDocument();
});
- it("keeps compact discovery focused on one contextual suggestion", () => {
+ it("offers every suggestion the page has, not only the first", () => {
render(<ChatDock {...props()} />);
fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));
- expect(screen.getAllByRole("button", { name: /^Try / })).toHaveLength(1);
+ for (const suggestion of [
+ "Explain the main architectural boundaries",
+ "Which parts of this repository deserve attention first?",
+ "Where should a new contributor start?",
+ ]) {
+ expect(screen.getByRole("button", { name: suggestion })).toBeVisible();
+ }
});
it("updates context copy on navigation without losing the conversation", () => {
diff --git a/packages/ui/__tests__/chat/chat-handoff.test.tsx b/packages/ui/__tests__/chat/chat-handoff.test.tsx
new file mode 100644
index 000000000..e96c5d966
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-handoff.test.tsx
@@ -0,0 +1,114 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ChatContext, ChatHandoff } from "@repowise-dev/types/chat";
+import {
+ AskAboutThis,
+ ChatHandoffProvider,
+ buildHandoffDraft,
+} from "../../src/chat/index.js";
+
+const CONTEXT: ChatContext = {
+ kind: "file",
+ label: "packages/core/parser.py",
+ target: "packages/core/parser.py",
+ targetKind: "path",
+};
+
+function renderControl(
+ onHandoff: (handoff: ChatHandoff) => void,
+ askEnabled = true,
+) {
+ return render(
+ <ChatHandoffProvider onHandoff={onHandoff} askEnabled={askEnabled}>
+ <AskAboutThis context={CONTEXT} question="What is this for?" />
+ </ChatHandoffProvider>,
+ );
+}
+
+describe("AskAboutThis", () => {
+ it("hands the page's context and question to the host", () => {
+ const onHandoff = vi.fn();
+ renderControl(onHandoff);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Ask about packages/core/parser.py" }),
+ );
+
+ expect(onHandoff).toHaveBeenCalledWith({
+ context: CONTEXT,
+ question: "What is this for?",
+ });
+ });
+
+ it("renders nothing when the reader has switched the controls off", () => {
+ renderControl(vi.fn(), false);
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("renders nothing outside a chat host", () => {
+ render(<AskAboutThis context={CONTEXT} question="What is this for?" />);
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("names the control so a screen reader announces the subject", () => {
+ renderControl(vi.fn());
+ const button = screen.getByRole("button", {
+ name: "Ask about packages/core/parser.py",
+ });
+ expect(button.getAttribute("aria-label")).toBe(
+ "Ask about packages/core/parser.py",
+ );
+ });
+});
+
+describe("buildHandoffDraft", () => {
+ it("is the question alone when nothing was selected", () => {
+ expect(buildHandoffDraft({ context: CONTEXT, question: "Why?" })).toBe("Why?");
+ });
+
+ it("quotes a selection with its file and line range", () => {
+ const draft = buildHandoffDraft({
+ context: CONTEXT,
+ question: "Explain this.",
+ selection: {
+ text: "def parse():",
+ path: "packages/core/parser.py",
+ startLine: 10,
+ endLine: 12,
+ },
+ });
+
+ expect(draft).toContain("Explain this.");
+ expect(draft).toContain("From packages/core/parser.py:10-12:");
+ expect(draft).toContain("def parse():");
+ });
+
+ it("names one line rather than a range of one", () => {
+ const draft = buildHandoffDraft({
+ context: CONTEXT,
+ selection: { text: "x = 1", path: "a.py", startLine: 4, endLine: 4 },
+ });
+ expect(draft).toContain("From a.py:4:");
+ });
+
+ it("outruns a fence inside the selection so the quote cannot close early", () => {
+ const draft = buildHandoffDraft({
+ context: CONTEXT,
+ question: "What does this show?",
+ selection: { text: "```py\nx = 1\n```", path: "a.md" },
+ });
+
+ const fences = draft.match(/^`{4,}$/gm) ?? [];
+ expect(fences).toHaveLength(2);
+ expect(draft).toContain("```py");
+ });
+
+ it("says so when it truncates a long selection", () => {
+ const draft = buildHandoffDraft({
+ context: CONTEXT,
+ selection: { text: "x".repeat(5000), path: "a.py" },
+ });
+ expect(draft).toContain("first 2000 characters");
+ expect(draft.length).toBeLessThan(2300);
+ });
+});
diff --git a/packages/ui/__tests__/chat/chat-selection-affordance.test.tsx b/packages/ui/__tests__/chat/chat-selection-affordance.test.tsx
new file mode 100644
index 000000000..54b8330cd
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-selection-affordance.test.tsx
@@ -0,0 +1,144 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ChatContext, ChatHandoff } from "@repowise-dev/types/chat";
+import {
+ ChatHandoffProvider,
+ ChatSelectionAffordance,
+} from "../../src/chat/index.js";
+
+const PAGE: ChatContext = { kind: "overview", label: "Overview" };
+
+function resolveContext(path?: string): ChatContext {
+ return path
+ ? { kind: "file", label: path, target: path, targetKind: "path" }
+ : PAGE;
+}
+
+function setup(onHandoff: (handoff: ChatHandoff) => void, selectionEnabled = true) {
+ return render(
+ <ChatHandoffProvider
+ onHandoff={onHandoff}
+ selectionEnabled={selectionEnabled}
+ >
+ <div data-chat-selection="" data-chat-selection-path="a.py">
+ <span data-line="41">const value = 1;</span>
+ <span data-line="42">const other = 2;</span>
+ <span data-line="43">const third = 3;</span>
+ </div>
+ <p data-testid="outside">Plain page copy.</p>
+ <ChatSelectionAffordance resolveContext={resolveContext} />
+ </ChatHandoffProvider>,
+ );
+}
+
+/** jsdom computes no layout, so ranges report a zero rect. Give the control
+ * something to place itself against. */
+function selectWithin(node: Node, endNode?: Node) {
+ const range = document.createRange();
+ if (endNode) {
+ range.setStartBefore(node);
+ range.setEndAfter(endNode);
+ } else {
+ range.selectNodeContents(node);
+ }
+ range.getClientRects = () =>
+ [{ top: 100, left: 50, width: 120, height: 16 }] as unknown as DOMRectList;
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ fireEvent.mouseUp(document);
+}
+
+describe("ChatSelectionAffordance", () => {
+ beforeEach(() => window.getSelection()?.removeAllRanges());
+
+ it("renders nothing until something is selected", () => {
+ setup(vi.fn());
+ expect(screen.queryByRole("button", { name: "Ask about selection" })).toBeNull();
+ });
+
+ it("appears for a selection inside a marked region", () => {
+ const view = setup(vi.fn());
+ selectWithin(view.container.querySelector("[data-chat-selection]")!);
+ expect(
+ screen.getByRole("button", { name: "Ask about selection" }),
+ ).toBeInTheDocument();
+ });
+
+ it("stays away from text outside a marked region", () => {
+ const view = setup(vi.fn());
+ selectWithin(view.getByTestId("outside"));
+ expect(screen.queryByRole("button", { name: "Ask about selection" })).toBeNull();
+ });
+
+ it("carries the text, the path and the line range", () => {
+ const onHandoff = vi.fn();
+ const view = setup(onHandoff);
+ selectWithin(view.container.querySelector("[data-chat-selection]")!);
+
+ fireEvent.click(screen.getByRole("button", { name: "Ask about selection" }));
+
+ expect(onHandoff).toHaveBeenCalledTimes(1);
+ const handoff = onHandoff.mock.calls[0]![0] as ChatHandoff;
+ expect(handoff.selection?.path).toBe("a.py");
+ expect(handoff.selection?.startLine).toBe(41);
+ expect(handoff.selection?.endLine).toBe(43);
+ expect(handoff.context).toEqual({
+ kind: "file",
+ label: "a.py",
+ target: "a.py",
+ targetKind: "path",
+ });
+ });
+
+ it("names only the lines the selection actually covers", () => {
+ // The bug this guards: reading the boundary containers named the region's
+ // first and last line whatever the reader picked, because a boundary
+ // normalizes to a parent element on a triple-click.
+ const onHandoff = vi.fn();
+ const view = setup(onHandoff);
+ const lines = view.container.querySelectorAll("[data-line]");
+ selectWithin(lines[1]!, lines[1]!);
+
+ fireEvent.click(screen.getByRole("button", { name: "Ask about selection" }));
+
+ const handoff = onHandoff.mock.calls[0]![0] as ChatHandoff;
+ expect(handoff.selection?.startLine).toBe(42);
+ expect(handoff.selection?.endLine).toBe(42);
+ });
+
+ it("reports no range at all where the DOM carries no line numbers", () => {
+ const onHandoff = vi.fn();
+ const view = render(
+ <ChatHandoffProvider onHandoff={onHandoff}>
+ <div data-chat-selection="">
+ <pre>some fenced snippet</pre>
+ </div>
+ <ChatSelectionAffordance resolveContext={resolveContext} />
+ </ChatHandoffProvider>,
+ );
+ selectWithin(view.container.querySelector("pre")!);
+
+ fireEvent.click(screen.getByRole("button", { name: "Ask about selection" }));
+
+ const handoff = onHandoff.mock.calls[0]![0] as ChatHandoff;
+ expect(handoff.selection?.startLine).toBeUndefined();
+ expect(handoff.selection?.endLine).toBeUndefined();
+ });
+
+ it("renders nothing when the reader has switched it off", () => {
+ const view = setup(vi.fn(), false);
+ selectWithin(view.container.querySelector("[data-chat-selection]")!);
+ expect(screen.queryByRole("button", { name: "Ask about selection" })).toBeNull();
+ });
+
+ it("goes away when the selection collapses", () => {
+ const view = setup(vi.fn());
+ selectWithin(view.container.querySelector("[data-chat-selection]")!);
+ expect(screen.getByRole("button", { name: "Ask about selection" })).toBeInTheDocument();
+
+ window.getSelection()?.removeAllRanges();
+ fireEvent(document, new Event("selectionchange"));
+ expect(screen.queryByRole("button", { name: "Ask about selection" })).toBeNull();
+ });
+});
diff --git a/packages/ui/__tests__/chat/use-chat-shortcut.test.tsx b/packages/ui/__tests__/chat/use-chat-shortcut.test.tsx
new file mode 100644
index 000000000..912fc813e
--- /dev/null
+++ b/packages/ui/__tests__/chat/use-chat-shortcut.test.tsx
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render } from "@testing-library/react";
+import { useChatShortcut } from "../../src/chat/use-chat-shortcut.js";
+
+function Probe({ onTrigger, enabled }: { onTrigger: () => void; enabled?: boolean }) {
+ useChatShortcut(onTrigger, enabled);
+ return (
+ <div>
+ <input aria-label="filter" />
+ <textarea aria-label="composer" />
+ <div contentEditable aria-label="note" />
+ <div role="combobox" aria-label="picker" />
+ <div role="textbox" aria-label="rich" />
+ </div>
+ );
+}
+
+describe("useChatShortcut", () => {
+ it("fires on a bare ?", () => {
+ const onTrigger = vi.fn();
+ render(<Probe onTrigger={onTrigger} />);
+ fireEvent.keyDown(window, { key: "?" });
+ expect(onTrigger).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores ? with a platform modifier, which belongs to the browser", () => {
+ const onTrigger = vi.fn();
+ render(<Probe onTrigger={onTrigger} />);
+ fireEvent.keyDown(window, { key: "?", metaKey: true });
+ fireEvent.keyDown(window, { key: "?", ctrlKey: true });
+ fireEvent.keyDown(window, { key: "?", altKey: true });
+ expect(onTrigger).not.toHaveBeenCalled();
+ });
+
+ it("stays out of the way while the reader is typing", () => {
+ const onTrigger = vi.fn();
+ const view = render(<Probe onTrigger={onTrigger} />);
+ for (const label of ["filter", "composer", "note", "picker", "rich"]) {
+ fireEvent.keyDown(view.getByLabelText(label), { key: "?", bubbles: true });
+ }
+ expect(onTrigger).not.toHaveBeenCalled();
+ });
+
+ it("does not claim any other key", () => {
+ const onTrigger = vi.fn();
+ render(<Probe onTrigger={onTrigger} />);
+ for (const key of ["/", "k", "Escape", "Enter"]) {
+ fireEvent.keyDown(window, { key });
+ }
+ expect(onTrigger).not.toHaveBeenCalled();
+ });
+
+ it("registers nothing while disabled", () => {
+ const onTrigger = vi.fn();
+ render(<Probe onTrigger={onTrigger} enabled={false} />);
+ fireEvent.keyDown(window, { key: "?" });
+ expect(onTrigger).not.toHaveBeenCalled();
+ });
+
+ it("keeps one listener across renders when the caller is not memoized", () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const view = render(<Probe onTrigger={first} />);
+ view.rerender(<Probe onTrigger={second} />);
+
+ fireEvent.keyDown(window, { key: "?" });
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops listening once unmounted", () => {
+ const onTrigger = vi.fn();
+ const view = render(<Probe onTrigger={onTrigger} />);
+ view.unmount();
+ fireEvent.keyDown(window, { key: "?" });
+ expect(onTrigger).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/ui/src/blast-radius/direct-risks-table.tsx b/packages/ui/src/blast-radius/direct-risks-table.tsx
index e9b83e33b..8b76ca294 100644
--- a/packages/ui/src/blast-radius/direct-risks-table.tsx
+++ b/packages/ui/src/blast-radius/direct-risks-table.tsx
@@ -1,6 +1,7 @@
"use client";
import type { DirectRiskEntry } from "@repowise-dev/types/blast-radius";
+import { AskAboutThis } from "../chat/ask-about-this";
import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";
interface DirectRisksTableProps {
@@ -40,11 +41,24 @@ const COLUMNS: ResponsiveColumn<DisplayDirectRisk>[] = [
key: "path",
header: "File",
render: (r) => (
- <span
- className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-secondary)]"
- title={r.path}
- >
- {r.path}
+ <span className="flex min-w-0 items-center gap-1">
+ <span
+ className="block max-w-[280px] truncate font-mono text-xs text-[var(--color-text-secondary)]"
+ title={r.path}
+ >
+ {r.path}
+ </span>
+ <AskAboutThis
+ context={{
+ kind: "blast-radius",
+ label: r.path,
+ target: r.path,
+ targetKind: "path",
+ }}
+ question={`What breaks if I change ${r.path}, and which dependents deserve the closest review?`}
+ label={`Ask about ${r.path}`}
+ className="h-6 w-6"
+ />
</span>
),
},
diff --git a/packages/ui/src/chat/ask-about-this.tsx b/packages/ui/src/chat/ask-about-this.tsx
new file mode 100644
index 000000000..7d8c69ca6
--- /dev/null
+++ b/packages/ui/src/chat/ask-about-this.tsx
@@ -0,0 +1,61 @@
+"use client";
+
+import { MessageCircleQuestion } from "lucide-react";
+import type { ChatContext, ChatSelection } from "@repowise-dev/types/chat";
+import { cn } from "../lib/cn";
+import { useChatHandoff } from "./chat-handoff";
+
+export interface AskAboutThisProps {
+ /** The thing this control asks about, not the route the reader is on. */
+ context: ChatContext;
+ /** Seeded first question. Specific to the surface, not a generic prompt. */
+ question: string;
+ /** Accessible name. Defaults to the one primary verb plus the subject. */
+ label?: string;
+ selection?: ChatSelection;
+ /** Ask immediately instead of seeding the composer. */
+ autoSend?: boolean;
+ className?: string;
+}
+
+/**
+ * The one page-level entry point into chat.
+ *
+ * Neutral at rest so it does not compete with the surface's own actions, and
+ * absent entirely when the reader has switched these controls off.
+ */
+export function AskAboutThis({
+ context,
+ question,
+ label,
+ selection,
+ autoSend,
+ className,
+}: AskAboutThisProps) {
+ const { request, askEnabled } = useChatHandoff();
+ if (!askEnabled) return null;
+
+ const name = label ?? `Ask about ${context.label}`;
+ return (
+ <button
+ type="button"
+ title={name}
+ aria-label={name}
+ onClick={(event) => {
+ event.stopPropagation();
+ request({
+ context,
+ question,
+ ...(selection ? { selection } : {}),
+ ...(autoSend ? { autoSend } : {}),
+ });
+ }}
+ className={cn(
+ "inline-flex h-7 w-7 shrink-0 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)] motion-reduce:transition-none",
+ className,
+ )}
+ >
+ <MessageCircleQuestion className="h-4 w-4" aria-hidden />
+ </button>
+ );
+}
diff --git a/packages/ui/src/chat/chat-context.ts b/packages/ui/src/chat/chat-context.ts
index f2253187d..47e1b50e9 100644
--- a/packages/ui/src/chat/chat-context.ts
+++ b/packages/ui/src/chat/chat-context.ts
@@ -125,6 +125,22 @@ const PRESENTATIONS: Record<ChatContextKind, ChatContextPresentation> = {
"Propose the safest order for these changes",
],
},
+ "dead-code": {
+ placeholder: "Ask about this dead-code result",
+ suggestions: [
+ "Is this safe to remove, and what still reaches it?",
+ "Explain the evidence behind this result",
+ "What should I check before deleting it?",
+ ],
+ },
+ "blast-radius": {
+ placeholder: "Ask about the reach of this change",
+ suggestions: [
+ "What breaks if I change this?",
+ "Which dependents deserve the closest review?",
+ "Which tests cover this reach?",
+ ],
+ },
security: {
placeholder: "Ask about these security findings",
suggestions: [
diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsx
index 994a6c9e2..11dc30f2c 100644
--- a/packages/ui/src/chat/chat-dock.tsx
+++ b/packages/ui/src/chat/chat-dock.tsx
@@ -8,7 +8,7 @@ import {
X,
} from "lucide-react";
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
-import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
+import type { ChatArtifact, ChatHandoff, ChatUIMessage } from "@repowise-dev/types/chat";
import { BrandMark } from "../shared/brand-mark";
import { Button } from "../ui/button";
import { ActivityDot } from "../ui/activity-dot";
@@ -18,6 +18,8 @@ import { ChatComposer } from "./chat-composer";
import { ChatContextIndicator } from "./chat-context-indicator";
import { getChatContextPresentation, type ChatContext } from "./chat-context";
import { ChatInterface } from "./chat-interface";
+import { buildHandoffDraft } from "./chat-handoff";
+import { CHAT_SHORTCUT_HINT } from "./use-chat-shortcut";
export type ChatDockMode = "minimized" | "compact" | "expanded";
@@ -100,8 +102,11 @@ function usePersistentDockState(storageKey: string) {
};
}
+// Starts desktop, corrected on mount. It cannot read `matchMedia` during
+// render without making the server and the first client render disagree, and
+// defaulting to mobile flashed the full-width sheet on every desktop load.
function useMobileDock() {
- const [isMobile, setIsMobile] = useState(true);
+ const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
if (typeof window.matchMedia !== "function") return;
@@ -115,6 +120,14 @@ function useMobileDock() {
return isMobile;
}
+/** One imperative request from the host: a keyboard toggle, or a page handing
+ * the reader's question over. `id` lets the same request repeat. */
+export interface ChatDockCommand {
+ id: number;
+ type: "toggle" | "open" | "handoff";
+ handoff?: ChatHandoff;
+}
+
export interface ChatDockProps {
storageKey: string;
repoId: string;
@@ -125,6 +138,14 @@ export interface ChatDockProps {
error?: string | null;
onSend: (text: string, context?: ChatContext) => void | Promise<void>;
onCancel: () => void;
+ /** Applied once, then handed back through `onCommandHandled` so remounting
+ * the dock does not replay it. */
+ command?: ChatDockCommand | null;
+ onCommandHandled?: () => void;
+ /** Shown once beside the minimized label, then reported back so the host can
+ * remember it and never show it again. Never a modal, never persistent. */
+ firstVisitHint?: string;
+ onFirstVisitHintShown?: () => void;
suppressed?: boolean;
/** Hide the dock entirely. The host owns the preference and where it is
* stored: this component's own persisted state is keyed per conversation,
@@ -163,6 +184,10 @@ export function ChatDock({
error,
onSend,
onCancel,
+ command,
+ onCommandHandled,
+ firstVisitHint,
+ onFirstVisitHintShown,
suppressed = false,
onDismiss,
modelSelectorSlot,
@@ -183,6 +208,7 @@ export function ChatDock({
const { mode, draft, setMode, setDraft } = usePersistentDockState(storageKey);
const [dismissedContext, setDismissedContext] = useState<string | null>(null);
const [answerReady, setAnswerReady] = useState(false);
+ const [hintVisible, setHintVisible] = useState(false);
const previousStreaming = useRef(isStreaming);
const compactTextareaRef = useRef<HTMLTextAreaElement>(null);
const expandedTextareaRef = useRef<HTMLTextAreaElement>(null);
@@ -219,9 +245,70 @@ export function ChatDock({
if (mode !== "minimized") setAnswerReady(false);
}, [mode]);
+ useEffect(() => {
+ if (!firstVisitHint || mode !== "minimized") return undefined;
+ setHintVisible(true);
+ onFirstVisitHintShown?.();
+ const timeout = window.setTimeout(() => setHintVisible(false), 7000);
+ // Clears the flag as well as the timer: a host that stops passing the hint
+ // once it has been seen would otherwise leave an empty label behind.
+ return () => {
+ window.clearTimeout(timeout);
+ setHintVisible(false);
+ };
+ // One introduction per host decision, not one per mode change.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [firstVisitHint]);
+
+ useEffect(() => {
+ // Suppressed means nothing is rendered, so applying the command here would
+ // consume it against a dock nobody can see. Leave it pending instead.
+ if (!command || suppressed) return;
+ onCommandHandled?.();
+ const focusCompact = () =>
+ window.requestAnimationFrame(() => compactTextareaRef.current?.focus());
+
+ if (command.type === "toggle" || command.type === "open") {
+ // "open" rather than "toggle" when the host has just revealed a dock the
+ // reader had hidden: the stored mode is from before it was hidden, so
+ // toggling it could minimize the thing the keystroke asked to open.
+ if (command.type === "open" || mode === "minimized") {
+ setMode("compact");
+ focusCompact();
+ } else {
+ setMode("minimized");
+ window.requestAnimationFrame(() => minimizedButtonRef.current?.focus());
+ }
+ return;
+ }
+
+ const handoff = command.handoff;
+ if (!handoff) return;
+ const seeded = buildHandoffDraft(handoff);
+ setMode("compact");
+ if (handoff.autoSend && seeded) {
+ setDraft("");
+ void onSend(seeded, handoff.context);
+ focusCompact();
+ return;
+ }
+ setDraft(seeded);
+ window.requestAnimationFrame(() => {
+ const textarea = compactTextareaRef.current;
+ if (!textarea) return;
+ textarea.focus();
+ textarea.setSelectionRange(textarea.value.length, textarea.value.length);
+ });
+ // Applied once per command id; the host clears it immediately after, so a
+ // remount cannot replay it. `suppressed` is listed so a command that arrived
+ // while nothing was rendered is applied as soon as the dock comes back.
+ // `mode` is not: it is read from the render that produced the command, which
+ // is exactly the state a toggle must act on.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [command, suppressed]);
+
const activeContext = dismissedContext === identity ? undefined : context;
const presentation = getChatContextPresentation(activeContext);
- const suggestion = presentation.suggestions[0];
if (suppressed) return null;
@@ -242,6 +329,10 @@ export function ChatDock({
setMode("compact");
window.requestAnimationFrame(() => compactTextareaRef.current?.focus());
};
+ const expand = () => {
+ setMode("expanded");
+ window.requestAnimationFrame(() => expandedTextareaRef.current?.focus());
+ };
const statusText = isStreaming
? "Working"
: answerReady
@@ -280,6 +371,11 @@ export function ChatDock({
<span className="text-[13px] 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">
+ {firstVisitHint}
+ </span>
+ )}
{statusText && (
<span aria-hidden>
{isStreaming ? (
@@ -335,7 +431,7 @@ export function ChatDock({
variant="ghost"
size="icon"
className="h-8 w-8"
- onClick={() => setMode("expanded")}
+ onClick={expand}
aria-label="Expand repository chat"
>
<Expand className="h-4 w-4" />
@@ -382,18 +478,24 @@ export function ChatDock({
autoFocus
textareaRef={compactTextareaRef}
/>
- {messages.length === 0 && draft.length === 0 && suggestion && (
- <button
- type="button"
- onClick={() => {
- setDraft(suggestion);
- compactTextareaRef.current?.focus();
- }}
- className="mt-2 block max-w-full truncate rounded-md px-1 py-1 text-left text-xs 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)]"
- >
- <span className="mr-1.5 text-[var(--color-text-tertiary)]">Try</span>
- {suggestion}
- </button>
+ {messages.length === 0 && draft.length === 0 && presentation.suggestions.length > 0 && (
+ /* Chips wrap rather than truncate: at 390px a one-line suggestion
+ loses the half of the question that made it specific. */
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {presentation.suggestions.map((text) => (
+ <button
+ key={text}
+ type="button"
+ onClick={() => {
+ setDraft(text);
+ compactTextareaRef.current?.focus();
+ }}
+ className="rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-left text-xs text-[var(--color-text-tertiary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {text}
+ </button>
+ ))}
+ </div>
)}
{sendDisabled && sendDisabledReason && (
<div className="mt-2 text-xs text-[var(--color-text-secondary)]">
@@ -486,6 +588,7 @@ export function ChatDock({
onDraftChange={setDraft}
onContextRemove={removeExpandedContext}
composerRef={expandedTextareaRef}
+ autoFocus
modelSelectorSlot={modelSelectorSlot}
historySlot={historySlot}
sendDisabled={sendDisabled}
diff --git a/packages/ui/src/chat/chat-handoff.tsx b/packages/ui/src/chat/chat-handoff.tsx
new file mode 100644
index 000000000..78f35ad78
--- /dev/null
+++ b/packages/ui/src/chat/chat-handoff.tsx
@@ -0,0 +1,91 @@
+"use client";
+
+import { createContext, useContext, useMemo, type ReactNode } from "react";
+import type { ChatHandoff, ChatSelection } from "@repowise-dev/types/chat";
+
+export type { ChatHandoff, ChatSelection } from "@repowise-dev/types/chat";
+
+/** Longest selection carried into the composer. Past this the quote stops
+ * being a question and starts being a paste of the file. */
+const MAX_SELECTION_CHARS = 2000;
+
+export interface ChatHandoffValue {
+ /** Ask chat about one thing on the page. */
+ request: (handoff: ChatHandoff) => void;
+ /** Whether page-level "Ask about this" controls should render at all. */
+ askEnabled: boolean;
+ /** Whether the floating selection control should render at all. */
+ selectionEnabled: boolean;
+}
+
+const DISABLED: ChatHandoffValue = {
+ request: () => {},
+ askEnabled: false,
+ selectionEnabled: false,
+};
+
+/** Defaults to disabled so a surface rendered outside a chat host stays
+ * unchanged rather than growing a control that leads nowhere. */
+const ChatHandoffContext = createContext<ChatHandoffValue>(DISABLED);
+
+export function ChatHandoffProvider({
+ onHandoff,
+ askEnabled = true,
+ selectionEnabled = true,
+ children,
+}: {
+ onHandoff: (handoff: ChatHandoff) => void;
+ askEnabled?: boolean;
+ selectionEnabled?: boolean;
+ children: ReactNode;
+}) {
+ const value = useMemo<ChatHandoffValue>(
+ () => ({ request: onHandoff, askEnabled, selectionEnabled }),
+ [onHandoff, askEnabled, selectionEnabled],
+ );
+ return (
+ <ChatHandoffContext.Provider value={value}>
+ {children}
+ </ChatHandoffContext.Provider>
+ );
+}
+
+export function useChatHandoff(): ChatHandoffValue {
+ return useContext(ChatHandoffContext);
+}
+
+function formatSelectionRange(selection: ChatSelection): string {
+ const { path, startLine, endLine } = selection;
+ if (!path) return "";
+ if (startLine === undefined) return path;
+ if (endLine === undefined || endLine === startLine) return `${path}:${startLine}`;
+ return `${path}:${startLine}-${endLine}`;
+}
+
+/**
+ * The composer text one handoff seeds, shared so both hosts and every surface
+ * quote a selection the same way.
+ */
+export function buildHandoffDraft(handoff: ChatHandoff): string {
+ const question = handoff.question?.trim() ?? "";
+ const selection = handoff.selection;
+ const text = selection?.text.trim();
+ if (!text) return question;
+
+ const truncated = text.length > MAX_SELECTION_CHARS;
+ const body = truncated ? `${text.slice(0, MAX_SELECTION_CHARS)}\n...` : text;
+ // Longer than the longest run inside, so a selection that is itself fenced
+ // (a quoted code block, a copied transcript) cannot close the quote early.
+ const fence = "`".repeat(
+ Math.max(3, ...[...body.matchAll(/`+/g)].map((run) => run[0].length + 1)),
+ );
+ const range = formatSelectionRange(selection!);
+ const heading = [
+ range ? `From ${range}` : "Selected text",
+ truncated ? `(first ${MAX_SELECTION_CHARS} characters)` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+
+ return [question, `${heading}:`, fence, body, fence].filter(Boolean).join("\n\n");
+}
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index 16a1f8b55..391ab2c69 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -43,6 +43,7 @@ import {
import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
import type { SourceReference } from "./source-citations";
import { ChatComposer } from "./chat-composer";
+import { CHAT_SHORTCUT_HINT } from "./use-chat-shortcut";
import { useChatScroll } from "./use-chat-scroll";
const DEFAULT_SUGGESTIONS = [
@@ -118,6 +119,9 @@ export interface ChatInterfaceProps {
onDraftChange?: (draft: string) => void;
onContextRemove?: () => void;
composerRef?: RefObject<HTMLTextAreaElement | null>;
+ /** Focus the composer on mount. The dock and the full page both do; a host
+ * embedding chat below other content should not. */
+ autoFocus?: boolean;
onRetry?: (message: ChatUIMessage) => void | Promise<void>;
onEditAndResend?: (message: ChatUIMessage, text: string) => void | Promise<void>;
/** Controlled artifact deep links. Hosts own URL and persistence concerns. */
@@ -157,6 +161,7 @@ export function ChatInterface({
onDraftChange,
onContextRemove,
composerRef,
+ autoFocus = false,
onRetry,
onEditAndResend,
activeArtifactId,
@@ -355,6 +360,7 @@ export function ChatInterface({
{statusSlot}
</p>
)}
+ <p className={cn(MICRO_LABEL)}>{CHAT_SHORTCUT_HINT}</p>
</div>
{/* Hairline rows, not a grid of bordered boxes. A suggestion is
@@ -362,7 +368,7 @@ export function ChatInterface({
<div>
<p className={cn(MICRO_LABEL, "mb-1")}>Start with</p>
<ul className="border-t border-[var(--color-border-default)]">
- {visibleSuggestions.slice(0, variant === "dock" ? 3 : undefined).map((s) => (
+ {visibleSuggestions.map((s) => (
<li key={s}>
<button
className="group flex w-full items-center gap-3 border-b border-[var(--color-border-default)] py-3 text-left text-[15px] text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)]"
@@ -476,6 +482,7 @@ export function ChatInterface({
placeholder={composerPlaceholder}
disabled={sendDisabled}
compact={variant === "dock"}
+ autoFocus={autoFocus}
textareaRef={textareaRef}
{...(modelSelectorSlot ? { footer: modelSelectorSlot } : {})}
/>
diff --git a/packages/ui/src/chat/chat-selection-affordance.tsx b/packages/ui/src/chat/chat-selection-affordance.tsx
new file mode 100644
index 000000000..b3e3b149e
--- /dev/null
+++ b/packages/ui/src/chat/chat-selection-affordance.tsx
@@ -0,0 +1,214 @@
+"use client";
+
+import { MessageCircleQuestion } from "lucide-react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import type { ChatContext, ChatSelection } from "@repowise-dev/types/chat";
+import { useChatHandoff } from "./chat-handoff";
+
+/** A region whose text can be asked about. Optional companion attributes:
+ * `data-chat-selection-path` names the file, and `data-line` on any element
+ * inside gives the control a line range. */
+export const CHAT_SELECTION_ATTRIBUTE = "data-chat-selection";
+const PATH_ATTRIBUTE = "data-chat-selection-path";
+
+/** Cleared bottom-right so the control never lands on the compact chat dock.
+ * The expanded dock needs no zone: the control renders beneath its stacking
+ * level, so a selection made behind it cannot paint over it. */
+const DOCK_ZONE_WIDTH = 460;
+const DOCK_ZONE_HEIGHT = 200;
+const VIEWPORT_MARGIN = 8;
+const GAP_ABOVE_SELECTION = 8;
+
+interface Placement {
+ selection: ChatSelection;
+ top: number;
+ left: number;
+}
+
+function elementOf(node: Node | null): Element | null {
+ if (!node) return null;
+ return node.nodeType === Node.ELEMENT_NODE
+ ? (node as Element)
+ : node.parentElement;
+}
+
+/**
+ * The first and last numbered lines the selection actually covers.
+ *
+ * Asks the range which line elements it intersects rather than reading the
+ * boundary containers: a boundary normalizes to a parent element on a
+ * triple-click or a click at the start of a line, and reading that parent
+ * would name the region's first and last line whatever the reader picked.
+ * A wrong range is worse than no range.
+ */
+function lineRange(
+ range: Range,
+ region: HTMLElement,
+): { startLine?: number | undefined; endLine?: number | undefined } {
+ const covered: number[] = [];
+ for (const element of region.querySelectorAll("[data-line]")) {
+ if (!range.intersectsNode(element)) continue;
+ const line = Number(element.getAttribute("data-line"));
+ if (Number.isFinite(line)) covered.push(line);
+ }
+ if (covered.length === 0) return {};
+ return { startLine: covered[0], endLine: covered[covered.length - 1] };
+}
+
+/** The selectable region a range sits in, or null when it spans two of them. */
+function regionOf(range: Range): HTMLElement | null {
+ const start = elementOf(range.startContainer)?.closest<HTMLElement>(
+ `[${CHAT_SELECTION_ATTRIBUTE}]`,
+ );
+ if (!start) return null;
+ const end = elementOf(range.endContainer)?.closest<HTMLElement>(
+ `[${CHAT_SELECTION_ATTRIBUTE}]`,
+ );
+ return end === start ? start : null;
+}
+
+function readPlacement(): Placement | null {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) return null;
+ const text = selection.toString().trim();
+ if (!text) return null;
+
+ const range = selection.getRangeAt(0);
+ const region = regionOf(range);
+ if (!region) return null;
+
+ const rect = range.getClientRects()[0] ?? range.getBoundingClientRect();
+ if (!rect || (rect.width === 0 && rect.height === 0)) return null;
+
+ const path = region.getAttribute(PATH_ATTRIBUTE) ?? undefined;
+ const { startLine, endLine } = lineRange(range, region);
+
+ return {
+ selection: {
+ text,
+ ...(path ? { path } : {}),
+ ...(startLine === undefined ? {} : { startLine }),
+ ...(endLine === undefined ? {} : { endLine }),
+ },
+ top: rect.top,
+ left: rect.left,
+ };
+}
+
+export interface ChatSelectionAffordanceProps {
+ /** Host-owned mapping from the selected file to the chat context. */
+ resolveContext: (path?: string) => ChatContext;
+ question?: string;
+ label?: string;
+}
+
+/**
+ * A control that appears beside a text selection inside a region marked with
+ * `data-chat-selection`, and nowhere else.
+ *
+ * Mounted once per host. It renders nothing at rest, so it adds no permanent
+ * chrome to any page.
+ */
+export function ChatSelectionAffordance({
+ resolveContext,
+ question = "Explain this selection.",
+ label = "Ask about selection",
+}: ChatSelectionAffordanceProps) {
+ const { request, selectionEnabled } = useChatHandoff();
+ const [placement, setPlacement] = useState<Placement | null>(null);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+
+ const sync = useCallback(() => setPlacement(readPlacement()), []);
+
+ /** Follows the page without re-reading the selection. Scrolling moves the
+ * control but cannot change which lines are covered, and rescanning them
+ * would walk every numbered line in a long file on every scroll event. */
+ const reposition = useCallback(() => {
+ setPlacement((current) => {
+ if (!current) return current;
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
+ return null;
+ }
+ const range = selection.getRangeAt(0);
+ const rect = range.getClientRects()[0] ?? range.getBoundingClientRect();
+ if (!rect) return current;
+ return { ...current, top: rect.top, left: rect.left };
+ });
+ }, []);
+
+ useEffect(() => {
+ if (!selectionEnabled) {
+ setPlacement(null);
+ return undefined;
+ }
+ // `selectionchange` alone fires mid-drag on every character, which would
+ // make the control chase the pointer. Settle on pointer and key release.
+ const clear = () => {
+ const selection = window.getSelection();
+ if (!selection || selection.isCollapsed) setPlacement(null);
+ };
+ document.addEventListener("selectionchange", clear);
+ document.addEventListener("mouseup", sync);
+ document.addEventListener("keyup", sync);
+ window.addEventListener("scroll", reposition, true);
+ window.addEventListener("resize", reposition);
+ return () => {
+ document.removeEventListener("selectionchange", clear);
+ document.removeEventListener("mouseup", sync);
+ document.removeEventListener("keyup", sync);
+ window.removeEventListener("scroll", reposition, true);
+ window.removeEventListener("resize", reposition);
+ };
+ }, [reposition, selectionEnabled, sync]);
+
+ // Clamp after measuring: the control's width depends on its label, and the
+ // bottom-right clearance depends on that width. Runs before paint, so the
+ // first placement is never seen. It only ever moves the control, never hides
+ // it: a focusable control nobody can see is worse than one placed roughly.
+ useLayoutEffect(() => {
+ const button = buttonRef.current;
+ if (!button || !placement) return;
+ const { width, height } = button.getBoundingClientRect();
+
+ let top = placement.top - height - GAP_ABOVE_SELECTION;
+ if (top < VIEWPORT_MARGIN) top = placement.top + GAP_ABOVE_SELECTION;
+ let left = Math.max(
+ VIEWPORT_MARGIN,
+ Math.min(placement.left, window.innerWidth - width - VIEWPORT_MARGIN),
+ );
+ const inDockZone =
+ top + height > window.innerHeight - DOCK_ZONE_HEIGHT &&
+ left + width > window.innerWidth - DOCK_ZONE_WIDTH;
+ if (inDockZone) {
+ left = Math.max(VIEWPORT_MARGIN, window.innerWidth - DOCK_ZONE_WIDTH - width);
+ }
+ button.style.top = `${top}px`;
+ button.style.left = `${left}px`;
+ }, [placement]);
+
+ if (!selectionEnabled || !placement) return null;
+
+ return (
+ <button
+ ref={buttonRef}
+ type="button"
+ // Keep the selection alive: a plain mousedown on the control would
+ // collapse it before the click handler could read it.
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => {
+ request({
+ context: resolveContext(placement.selection.path),
+ question,
+ selection: placement.selection,
+ });
+ setPlacement(null);
+ }}
+ style={{ top: placement.top, left: placement.left }}
+ className="fixed z-[calc(var(--z-modal)-1)] inline-flex h-8 items-center gap-1.5 whitespace-nowrap rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-2.5 text-xs text-[var(--color-text-secondary)] shadow-[var(--shadow-md)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <MessageCircleQuestion className="h-3.5 w-3.5" aria-hidden />
+ {label}
+ </button>
+ );
+}
diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.ts
index 0702fbd14..df7973797 100644
--- a/packages/ui/src/chat/index.ts
+++ b/packages/ui/src/chat/index.ts
@@ -7,6 +7,10 @@ export * from "./use-chat-draft";
export * from "./chat-composer";
export * from "./chat-dock";
export * from "./chat-context";
+export * from "./chat-handoff";
+export * from "./ask-about-this";
+export * from "./chat-selection-affordance";
+export * from "./use-chat-shortcut";
export * from "./chat-context-indicator";
export * from "../shared/markdown";
export * from "./chat-message";
diff --git a/packages/ui/src/chat/use-chat-shortcut.ts b/packages/ui/src/chat/use-chat-shortcut.ts
new file mode 100644
index 000000000..30acd9799
--- /dev/null
+++ b/packages/ui/src/chat/use-chat-shortcut.ts
@@ -0,0 +1,57 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+
+/** The one place the shortcut is named, so the empty state and the handler
+ * cannot drift apart. */
+export const CHAT_SHORTCUT_KEY = "?";
+export const CHAT_SHORTCUT_HINT = "Press ? from any page to open chat";
+
+/** `closest`, not a tag check: a caret inside a nested span of a rich-text
+ * editor is still typing, and jsdom never sets `isContentEditable`. The ARIA
+ * roles are here because a combobox or textbox widget can accept typing
+ * without being any of the native elements. */
+const TYPING_SELECTOR = [
+ "input",
+ "textarea",
+ "select",
+ '[contenteditable=""]',
+ '[contenteditable="true"]',
+ '[role="textbox"]',
+ '[role="searchbox"]',
+ '[role="combobox"]',
+].join(", ");
+
+function isTypingTarget(event: KeyboardEvent): boolean {
+ // `composedPath` first: `target` is retargeted to the host for anything
+ // inside a shadow root, which would hide a real input behind it.
+ const origin = event.composedPath?.()[0] ?? event.target;
+ return origin instanceof Element && origin.closest(TYPING_SELECTOR) !== null;
+}
+
+/**
+ * Registers `Shift+/` once for the whole repository shell.
+ *
+ * Deliberately unmodified: a bare `?` is free everywhere in the product, and
+ * anything with a platform modifier belongs to the browser or the editor.
+ */
+export function useChatShortcut(onTrigger: () => void, enabled = true): void {
+ // Held in a ref so an unmemoized caller does not re-register the global
+ // listener on every render.
+ const latest = useRef(onTrigger);
+ latest.current = onTrigger;
+
+ useEffect(() => {
+ if (!enabled) return undefined;
+ const handle = (event: KeyboardEvent) => {
+ if (event.key !== CHAT_SHORTCUT_KEY) return;
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
+ if (event.defaultPrevented) return;
+ if (isTypingTarget(event)) return;
+ event.preventDefault();
+ latest.current();
+ };
+ window.addEventListener("keydown", handle);
+ return () => window.removeEventListener("keydown", handle);
+ }, [enabled]);
+}
diff --git a/packages/ui/src/commits/commit-detail-card.tsx b/packages/ui/src/commits/commit-detail-card.tsx
index c8e5467ba..47fe72d6d 100644
--- a/packages/ui/src/commits/commit-detail-card.tsx
+++ b/packages/ui/src/commits/commit-detail-card.tsx
@@ -1,4 +1,5 @@
import { Bug } from "lucide-react";
+import { AskAboutThis } from "../chat/ask-about-this";
import { AgentBadge, NewContributorBadge, isNewContributor } from "./agent-badge";
import { PriorityBadge } from "./priority-badge";
import { RiskDriverBreakdown, describeDriver } from "./risk-driver-breakdown";
@@ -51,6 +52,17 @@ export function CommitDetailCard({ commit, reviewCut, className }: CommitDetailC
{!c.agent_name && isNewContributor(c.author_commit_count) && (
<NewContributorBadge commitCount={c.author_commit_count as number} />
)}
+ <AskAboutThis
+ context={{
+ kind: "commit",
+ label: c.short_sha,
+ target: c.sha,
+ targetKind: "commit",
+ }}
+ question={`Summarize the intent and impact of commit ${c.short_sha}, and say which files deserve the closest review.`}
+ label={`Ask about commit ${c.short_sha}`}
+ className="h-6 w-6"
+ />
</div>
{/* The subject wraps. It is the one thing on this sheet a reader has to
be able to read in full, so it never gets an ellipsis. */}
diff --git a/packages/ui/src/decisions/decision-detail.tsx b/packages/ui/src/decisions/decision-detail.tsx
index cf6a7b006..a086f7849 100644
--- a/packages/ui/src/decisions/decision-detail.tsx
+++ b/packages/ui/src/decisions/decision-detail.tsx
@@ -39,6 +39,7 @@ import {
import { ModuleLinkEditor } from "./module-link-editor";
import { VerificationBadge } from "./verification-badge";
+import { AskAboutThis } from "../chat/ask-about-this";
import { DecisionStatusMark } from "./decision-status-mark";
import { DecisionEvidenceDrawer } from "./decision-evidence-drawer";
import { DecisionLineage } from "./decision-lineage";
@@ -288,6 +289,16 @@ export function DecisionDetail({ decision, adapter }: DecisionDetailProps) {
{decision.verification && (
<VerificationBadge verification={decision.verification} />
)}
+ <AskAboutThis
+ context={{
+ kind: "decision",
+ label: stripMarkdown(decision.title),
+ target: decision.id,
+ targetKind: "decision",
+ }}
+ question={`Why was this decision made, what evidence supports it, and has later work conflicted with it?`}
+ label="Ask about this decision"
+ />
</div>
</div>
diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsx
index 0a49a8c32..7a4e2547c 100644
--- a/packages/ui/src/docs/docs-reader.tsx
+++ b/packages/ui/src/docs/docs-reader.tsx
@@ -603,7 +603,10 @@ function DocsReaderBody({
two things — a hardcoded `prose-invert` that fed dark variables
to light mode, and `code::before/::after { content: "`" }`, which
printed literal backticks around every unresolved inline ref. */}
- <article className="max-w-none leading-relaxed overflow-hidden">
+ <article
+ data-chat-selection=""
+ className="max-w-none leading-relaxed overflow-hidden"
+ >
<WikiMarkdown
content={visibleContent}
wikiLinks={wikiLinks}
diff --git a/packages/ui/src/files/file-coverage-tab.tsx b/packages/ui/src/files/file-coverage-tab.tsx
index 3d596beab..9dfb3cfd8 100644
--- a/packages/ui/src/files/file-coverage-tab.tsx
+++ b/packages/ui/src/files/file-coverage-tab.tsx
@@ -13,6 +13,8 @@ interface FileCoverageTabProps {
* When absent we fall back to a summary-only view.
*/
coverageCodeHtml?: string | undefined;
+ /** Names the file a selection inside the source came from. */
+ filePath?: string;
/**
* The graph-inferred "which tests reach this file" block, supplied by the host
* already wrapped. A node rather than a fetcher because the tab bodies are
@@ -24,6 +26,7 @@ interface FileCoverageTabProps {
export function FileCoverageTab({
coverage,
coverageCodeHtml,
+ filePath,
testsPanel,
}: FileCoverageTabProps) {
// Rendered on both bases. Without a report it is the whole answer; with one it
@@ -136,7 +139,11 @@ export function FileCoverageTab({
}
>
{coverageCodeHtml ? (
- <div className="coverage-code overflow-x-auto border-y border-[var(--color-border-default)] text-xs leading-relaxed">
+ <div
+ data-chat-selection=""
+ {...(filePath ? { "data-chat-selection-path": filePath } : {})}
+ className="coverage-code overflow-x-auto border-y border-[var(--color-border-default)] text-xs leading-relaxed"
+ >
{/* Highlighted by the host through the shared shiki path; the
data-covered line attributes drive the gutter tint below. */}
<div dangerouslySetInnerHTML={{ __html: coverageCodeHtml }} />
diff --git a/packages/ui/src/files/file-doc-tab.tsx b/packages/ui/src/files/file-doc-tab.tsx
index 17a25dbc9..085071c92 100644
--- a/packages/ui/src/files/file-doc-tab.tsx
+++ b/packages/ui/src/files/file-doc-tab.tsx
@@ -59,7 +59,9 @@ export function FileDocTab({ wikiPage, docSlot }: FileDocTabProps) {
our tokens, `code::before/::after` prints literal backticks into the
page, and `prose-invert` is a static class that cannot follow the
theme. If the markdown needs a style, it gets styled in the renderer. */}
- <article className="max-w-none overflow-hidden">{docSlot}</article>
+ <article data-chat-selection="" className="max-w-none overflow-hidden">
+ {docSlot}
+ </article>
</div>
);
}
diff --git a/packages/ui/src/files/file-page-header.tsx b/packages/ui/src/files/file-page-header.tsx
index caddf83b1..778c3cfa4 100644
--- a/packages/ui/src/files/file-page-header.tsx
+++ b/packages/ui/src/files/file-page-header.tsx
@@ -1,6 +1,7 @@
import * as React from "react";
import { bandForScore, HEALTH_BAND_LABEL } from "@repowise-dev/types/health";
import type { FileDetailResponse } from "@repowise-dev/types/files";
+import { AskAboutThis } from "../chat/ask-about-this";
import { PageLede } from "../shared/page-lede";
import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
import { healthBandColor, coverageTextColor } from "../health/tokens";
@@ -64,14 +65,27 @@ export function FilePageHeader({
<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
File
</p>
- {wikiHref && (
- <A
- href={wikiHref}
- className="shrink-0 text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
- >
- Read in Docs <span aria-hidden>&rarr;</span>
- </A>
- )}
+ <div className="flex shrink-0 items-center gap-2">
+ {wikiHref && (
+ <A
+ href={wikiHref}
+ className="text-sm font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ Read in Docs <span aria-hidden>&rarr;</span>
+ </A>
+ )}
+ <AskAboutThis
+ context={{
+ kind: "file",
+ label: data.file_path,
+ target: data.file_path,
+ targetKind: "path",
+ }}
+ question={`What is ${data.file_path} responsible for, and what is risky about changing it?`}
+ label="Ask about this file"
+ className="self-center"
+ />
+ </div>
</div>
{/* `break-all`, never an ellipsis: a path is the identity of this page
and rule 6 puts no truncation in the primary column. The directory
diff --git a/packages/ui/src/files/file-page-panels.tsx b/packages/ui/src/files/file-page-panels.tsx
index 6597a1330..9e174e86e 100644
--- a/packages/ui/src/files/file-page-panels.tsx
+++ b/packages/ui/src/files/file-page-panels.tsx
@@ -112,6 +112,7 @@ export function buildFilePanels({
<FileCoverageTab
coverage={data.coverage}
coverageCodeHtml={coverageCodeHtml}
+ filePath={data.file_path}
testsPanel={testsPanel}
/>
),
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index ce38cd7d4..c76ffa11e 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -9,6 +9,7 @@ import { type Severity } from "./tokens";
import { ImpactFigure } from "./impact-figure";
import { FindingOpportunityLink } from "./file-opportunity";
import type { RefactoringOpportunity } from "@repowise-dev/types/refactoring";
+import { AskAboutThis } from "../chat/ask-about-this";
import { SeverityMark } from "./severity-mark";
export type EffortBucket = "S" | "M" | "L" | "XL";
@@ -174,6 +175,17 @@ export function HealthWorkItemCard({
<span className="ml-auto text-xs tabular-nums text-[var(--color-error)]" title="Total health impact across this file's findings">
−{target.total_impact.toFixed(2)}
</span>
+ <AskAboutThis
+ context={{
+ kind: "health",
+ label: target.file_path,
+ target: target.file_path,
+ targetKind: "path",
+ }}
+ question={`Explain the ${biomarkerLabel(target.primary_biomarker)} finding in ${target.file_path} and propose a safe way to address it.`}
+ label={`Ask about the finding in ${target.file_path}`}
+ className="-my-1 h-6 w-6"
+ />
</div>
<button
type="button"
diff --git a/packages/ui/src/shared/code-block.tsx b/packages/ui/src/shared/code-block.tsx
index 39679de00..ea2eac8df 100644
--- a/packages/ui/src/shared/code-block.tsx
+++ b/packages/ui/src/shared/code-block.tsx
@@ -55,7 +55,15 @@ export function CodeFrame({ code, language, children, compact = false }: CodeFra
{copied ? "Copied" : "Copy"}
</button>
</div>
- <div className={cn("min-w-0 overflow-x-auto", compact ? "text-[11px]" : "text-sm")}>{children}</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. */}
+ <div
+ data-chat-selection=""
+ className={cn("min-w-0 overflow-x-auto", compact ? "text-[11px]" : "text-sm")}
+ >
+ {children}
+ </div>
</div>
);
}
diff --git a/packages/ui/src/symbols/symbol-page.tsx b/packages/ui/src/symbols/symbol-page.tsx
index c2776e022..9824ecbdf 100644
--- a/packages/ui/src/symbols/symbol-page.tsx
+++ b/packages/ui/src/symbols/symbol-page.tsx
@@ -8,6 +8,7 @@ import type {
SymbolDetailResponse,
} from "@repowise-dev/types/symbols";
import { FixHistoryBadge, SYMBOL_FIX_TITLE } from "../git/fix-history-badge";
+import { AskAboutThis } from "../chat/ask-about-this";
import { SymbolDetailBody } from "./symbol-detail-body";
import { toSymbolBodyCall, toSymbolBodyRelations } from "./normalize-calls";
@@ -147,6 +148,17 @@ export function SymbolPage({
>
{s.file_path}:{s.start_line}
</a>
+ <AskAboutThis
+ context={{
+ kind: "symbol",
+ label: s.qualified_name || s.name,
+ target: s.symbol_id,
+ targetKind: "symbol",
+ }}
+ question={`What does ${s.qualified_name || s.name} do, who calls it, and what should tests protect?`}
+ label={`Ask about ${s.name}`}
+ className="h-6 w-6"
+ />
</>
}
{...(LinkComponent ? { LinkComponent } : {})}
diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
index 8306baa22..05dc5c4fc 100644
--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx
@@ -95,6 +95,8 @@ async function renderCoverageCode(
{
line(node, line) {
if (covered.has(line)) node.properties["data-covered"] = "y";
+ // Real file lines, so a selection here can name a real range.
+ node.properties["data-line"] = String(line);
},
},
],
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index dd5739c06..cbea039e1 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -182,6 +182,7 @@ export function ChatInterface({
error={error}
onSend={sendWithConversationModel}
onCancel={cancel}
+ autoFocus
draft={draft}
onDraftChange={setDraft}
buildCitationHref={buildCitationHref}
diff --git a/packages/web/src/components/chat/repository-chat-context.test.ts b/packages/web/src/components/chat/repository-chat-context.test.ts
index f97afe626..027d05118 100644
--- a/packages/web/src/components/chat/repository-chat-context.test.ts
+++ b/packages/web/src/components/chat/repository-chat-context.test.ts
@@ -21,11 +21,32 @@ describe("getRepositoryChatContext", () => {
label: "Architecture",
});
expect(getRepositoryChatContext("/repos/r1/dead-code")).toEqual({
- kind: "risk",
+ kind: "dead-code",
label: "Dead Code",
});
});
+ it("separates the three risk-shaped routes so each seeds its own question", () => {
+ // They used to share the `risk` kind, which gave a dead-code page the
+ // wrong first question and the wrong placeholder.
+ expect(getRepositoryChatContext("/repos/r1/blast-radius").kind).toBe(
+ "blast-radius",
+ );
+ expect(getRepositoryChatContext("/repos/r1/risk").kind).toBe("risk");
+ expect(getRepositoryChatContext("/repos/r1/hotspots").kind).toBe("risk");
+ });
+
+ it("keeps reading selected files on every risk-shaped route", () => {
+ for (const route of ["risk", "dead-code", "blast-radius"]) {
+ expect(
+ getRepositoryChatContext(
+ `/repos/r1/${route}`,
+ new URLSearchParams("file=a.py"),
+ ),
+ ).toMatchObject({ target: "a.py", targetKind: "path" });
+ }
+ });
+
it("preserves decoded dynamic file targets as machine context", () => {
expect(
getRepositoryChatContext(
diff --git a/packages/web/src/components/chat/repository-chat-context.ts b/packages/web/src/components/chat/repository-chat-context.ts
index 4c74e1cc5..21247b25a 100644
--- a/packages/web/src/components/chat/repository-chat-context.ts
+++ b/packages/web/src/components/chat/repository-chat-context.ts
@@ -51,8 +51,8 @@ const ROUTES: Readonly<Record<string, RouteDefinition>> = {
ownership: { kind: "contributor", targetKind: "person" },
decisions: { kind: "decision", targetKind: "decision" },
hotspots: { kind: "risk" },
- "dead-code": { kind: "risk" },
- "blast-radius": { kind: "risk" },
+ "dead-code": { kind: "dead-code" },
+ "blast-radius": { kind: "blast-radius" },
risk: { kind: "risk" },
security: { kind: "security" },
costs: { kind: "usage" },
@@ -61,6 +61,13 @@ const ROUTES: Readonly<Record<string, RouteDefinition>> = {
chat: { kind: "chat" },
};
+/** Page kinds whose route reads its selected files from `?file=`. */
+const RISK_FILE_TARGET_KINDS = new Set<ChatContextKind>([
+ "risk",
+ "dead-code",
+ "blast-radius",
+]);
+
function decodeSegment(segment: string): string {
try {
return decodeURIComponent(segment);
@@ -132,7 +139,9 @@ export function getRepositoryChatContext(
const docsTarget = route === "docs" ? joinedTargets(searchParams, "page") : "";
const commitTarget = route === "commits" ? joinedTargets(searchParams, "commit") : "";
const selectedFiles =
- route === "code-health" || route === "health" || definition.kind === "risk"
+ route === "code-health" ||
+ route === "health" ||
+ RISK_FILE_TARGET_KINDS.has(definition.kind)
? joinedTargets(searchParams, "file")
: "";
const isArchitecture =
diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsx
index a38f9e168..cb21fe1e0 100644
--- a/packages/web/src/components/chat/repository-chat-dock.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.tsx
@@ -3,7 +3,8 @@
import useSWR from "swr";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
-import { ChatDock, getArtifactSourceTarget } from "@repowise-dev/ui/chat";
+import { useEffect, useState } from "react";
+import { CHAT_SHORTCUT_HINT, ChatDock, getArtifactSourceTarget } from "@repowise-dev/ui/chat";
import { getProviders } from "@/lib/api/providers";
import { setConversationArtifactPinned } from "@/lib/api/chat";
import { pageHref } from "@/lib/utils/page-href";
@@ -11,7 +12,7 @@ import { ModelSelector } from "./model-selector";
import { ConversationHistory } from "./conversation-history";
import { useRepositoryChat } from "./repository-chat-provider";
import { useChatDockHidden } from "./use-chat-dock-hidden";
-import { setChatDockHidden } from "@/lib/config";
+import { config, setChatDockHidden } from "@/lib/config";
// Sigma's worst-case bottom-right stack is ~197px tall (layout status plus
// five controls and spacing). Keep a small measured clearance above it.
@@ -64,6 +65,9 @@ type RepositoryChatValue = ReturnType<typeof useRepositoryChat>;
function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
const router = useRouter();
const searchParams = useSearchParams();
+ // Read after mount so SSR and the first client render agree.
+ const [introduce, setIntroduce] = useState(false);
+ useEffect(() => setIntroduce(!config.getChatHintSeen()), []);
const { data: providers } = useSWR(
`providers:${chat.repoId}`,
() => getProviders(chat.repoId),
@@ -91,6 +95,10 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
...(chat.selectedModel ? { model: chat.selectedModel } : {}),
})}
onCancel={chat.cancel}
+ command={chat.dockCommand}
+ onCommandHandled={chat.clearDockCommand}
+ {...(introduce ? { firstVisitHint: CHAT_SHORTCUT_HINT } : {})}
+ onFirstVisitHintShown={() => config.setChatHintSeen()}
buildCitationHref={(source) => pageHref(chat.repoId, source.pageId)}
onArtifactPin={async (artifact, pinned) => {
if (!chat.conversationId) return;
diff --git a/packages/web/src/components/chat/repository-chat-handoff.test.tsx b/packages/web/src/components/chat/repository-chat-handoff.test.tsx
new file mode 100644
index 000000000..c1331876b
--- /dev/null
+++ b/packages/web/src/components/chat/repository-chat-handoff.test.tsx
@@ -0,0 +1,172 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { AskAboutThis } from "@repowise-dev/ui/chat";
+import { config } from "@/lib/config";
+import {
+ RepositoryChatProvider,
+ useRepositoryChat,
+} from "./repository-chat-provider";
+
+const sendMessage = vi.fn();
+let pathname = "/repos/r1/code-health";
+let search = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => pathname,
+ useSearchParams: () => search,
+}));
+
+vi.mock("@/lib/hooks/use-chat", () => ({
+ useChat: () => ({
+ messages: [],
+ conversationId: null,
+ isStreaming: false,
+ error: null,
+ sendMessage,
+ loadConversation: vi.fn(),
+ cancel: vi.fn(),
+ reset: vi.fn(),
+ artifactOverrides: {},
+ replaceArtifact: vi.fn(),
+ }),
+}));
+
+/** Stands in for the dock, which owns mode and draft inside packages/ui. */
+function CommandProbe() {
+ const { dockCommand, pageContext, clearDockCommand } = useRepositoryChat();
+ return (
+ <div>
+ <span data-testid="context">{`${pageContext.kind}:${pageContext.target ?? ""}`}</span>
+ <span data-testid="command">
+ {dockCommand ? `${dockCommand.type}:${dockCommand.handoff?.question ?? ""}` : "none"}
+ </span>
+ <button type="button" onClick={clearDockCommand}>
+ clear
+ </button>
+ </div>
+ );
+}
+
+function renderShell() {
+ return render(
+ <RepositoryChatProvider repoId="r1" repoName="acme">
+ <AskAboutThis
+ context={{ kind: "file", label: "a.py", target: "a.py", targetKind: "path" }}
+ question="What is a.py for?"
+ />
+ <CommandProbe />
+ </RepositoryChatProvider>,
+ );
+}
+
+describe("repository chat handoff receiver", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ pathname = "/repos/r1/code-health";
+ search = new URLSearchParams();
+ sendMessage.mockClear();
+ });
+ afterEach(cleanup);
+
+ it("starts on the route's own context with nothing pending", () => {
+ renderShell();
+ expect(screen.getByTestId("context").textContent).toBe("health:");
+ expect(screen.getByTestId("command").textContent).toBe("none");
+ });
+
+ it("takes the handoff's context and queues one command", () => {
+ renderShell();
+ fireEvent.click(screen.getByRole("button", { name: "Ask about a.py" }));
+
+ expect(screen.getByTestId("context").textContent).toBe("file:a.py");
+ expect(screen.getByTestId("command").textContent).toBe(
+ "handoff:What is a.py for?",
+ );
+ });
+
+ it("clears the command once the dock reports it applied", () => {
+ renderShell();
+ fireEvent.click(screen.getByRole("button", { name: "Ask about a.py" }));
+ fireEvent.click(screen.getByRole("button", { name: "clear" }));
+ expect(screen.getByTestId("command").textContent).toBe("none");
+ });
+
+ it("reveals the dock a reader had hidden, because the gesture was deliberate", async () => {
+ config.setChatDockHidden(true);
+ renderShell();
+ // Hidden means the control is gone, so drive the shortcut instead.
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Ask about a.py" })).toBeNull(),
+ );
+
+ act(() => {
+ fireEvent.keyDown(window, { key: "?" });
+ });
+
+ expect(config.getChatDockHidden()).toBe(false);
+ // "open", not "toggle": the stored mode predates the hide, so toggling it
+ // could minimize the thing the keystroke asked to open.
+ expect(screen.getByTestId("command").textContent).toBe("open:");
+ });
+
+ it("toggles rather than forces open when the dock is already available", () => {
+ renderShell();
+ act(() => {
+ fireEvent.keyDown(window, { key: "?" });
+ });
+ expect(screen.getByTestId("command").textContent).toBe("toggle:");
+ });
+
+ it("hides the ask control when the reader switched it off", async () => {
+ config.setChatAskControlsHidden(true);
+ renderShell();
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Ask about a.py" })).toBeNull(),
+ );
+ });
+
+ it("offers no page control on the full chat page, which mounts no dock", async () => {
+ pathname = "/repos/r1/chat";
+ renderShell();
+ await waitFor(() =>
+ expect(screen.queryByRole("button", { name: "Ask about a.py" })).toBeNull(),
+ );
+ });
+
+ it("drops the handoff when the query changes what the page is about", () => {
+ // Docs, dead code, blast radius and risk all change identity through the
+ // query alone, so keying the handoff on the pathname would leave the
+ // composer asking about a file the reader has already navigated past.
+ pathname = "/repos/r1/dead-code";
+ const view = renderShell();
+ fireEvent.click(screen.getByRole("button", { name: "Ask about a.py" }));
+ expect(screen.getByTestId("context").textContent).toBe("file:a.py");
+
+ search = new URLSearchParams("file=b.py");
+ view.rerender(
+ <RepositoryChatProvider repoId="r1" repoName="acme">
+ <CommandProbe />
+ </RepositoryChatProvider>,
+ );
+
+ expect(screen.getByTestId("context").textContent).toBe("dead-code:b.py");
+ });
+
+ it("returns to the route's context after navigating away", () => {
+ const view = renderShell();
+ fireEvent.click(screen.getByRole("button", { name: "Ask about a.py" }));
+ expect(screen.getByTestId("context").textContent).toBe("file:a.py");
+
+ pathname = "/repos/r1/decisions";
+ view.rerender(
+ <RepositoryChatProvider repoId="r1" repoName="acme">
+ <CommandProbe />
+ </RepositoryChatProvider>,
+ );
+
+ expect(screen.getByTestId("context").textContent).toBe("decision:");
+ });
+});
diff --git a/packages/web/src/components/chat/repository-chat-provider.tsx b/packages/web/src/components/chat/repository-chat-provider.tsx
index 39a18020c..d2d7bfdee 100644
--- a/packages/web/src/components/chat/repository-chat-provider.tsx
+++ b/packages/web/src/components/chat/repository-chat-provider.tsx
@@ -6,23 +6,37 @@ import {
useEffect,
useContext,
useMemo,
+ useRef,
useState,
type ReactNode,
} from "react";
import { usePathname, useSearchParams } from "next/navigation";
-import type { ChatContext as PageChatContext } from "@repowise-dev/ui/chat";
+import {
+ ChatHandoffProvider,
+ ChatSelectionAffordance,
+ useChatShortcut,
+ type ChatContext as PageChatContext,
+ type ChatDockCommand,
+ type ChatHandoff,
+} from "@repowise-dev/ui/chat";
import { useChat } from "@/lib/hooks/use-chat";
+import { setChatDockHidden } from "@/lib/config";
import { getRepositoryChatContext, getRepositoryChatContextQuery } from "./repository-chat-context";
+import { useChatAffordances } from "./use-chat-dock-hidden";
type ChatController = ReturnType<typeof useChat>;
export interface RepositoryChatValue extends ChatController {
repoId: string;
repoName: string;
+ /** The page context, or what a handoff replaced it with on this route. */
pageContext: PageChatContext;
selectedProvider: string | null;
selectedModel: string | null;
selectModel: (provider: string, model: string) => void;
+ /** One pending imperative request for the dock. */
+ dockCommand: ChatDockCommand | null;
+ clearDockCommand: () => void;
}
const RepositoryChatContext = createContext<RepositoryChatValue | null>(null);
@@ -69,6 +83,69 @@ export function RepositoryChatProvider({
() => getRepositoryChatContext(pathname, new URLSearchParams(contextQuery)),
[contextQuery, pathname],
);
+ const { dockHidden, askControlsEnabled, selectionAskEnabled } =
+ useChatAffordances();
+ const [dockCommand, setDockCommand] = useState<ChatDockCommand | null>(null);
+ const commandId = useRef(0);
+ // A handoff replaces the route's context until the reader navigates away.
+ // Keyed on the same identity `pageContext` is derived from, query included:
+ // picking a different `?page=` or `?file=` changes what the page is about
+ // without changing the pathname, and the handoff must not outlive that.
+ // Stored alongside that identity rather than cleared by an effect, so there
+ // is no render where the two disagree.
+ const routeIdentity = `${pathname}?${contextQuery}`;
+ const [handoffContext, setHandoffContext] = useState<
+ { routeIdentity: string; context: PageChatContext } | null
+ >(null);
+
+ const issue = useCallback((command: Omit<ChatDockCommand, "id">) => {
+ commandId.current += 1;
+ setDockCommand({ ...command, id: commandId.current });
+ }, []);
+
+ const clearDockCommand = useCallback(() => setDockCommand(null), []);
+
+ const requestHandoff = useCallback(
+ (handoff: ChatHandoff) => {
+ // A deliberate gesture outranks the stored preference: opening chat from
+ // a page must not silently do nothing because the pill was dismissed.
+ setChatDockHidden(false);
+ setHandoffContext({ routeIdentity, context: handoff.context });
+ issue({ type: "handoff", handoff });
+ },
+ [issue, routeIdentity],
+ );
+
+ useChatShortcut(
+ useCallback(() => {
+ // A deliberate keystroke outranks the stored preference.
+ if (dockHidden) {
+ setChatDockHidden(false);
+ issue({ type: "open" });
+ return;
+ }
+ issue({ type: "toggle" });
+ }, [dockHidden, issue]),
+ );
+
+ const activeContext =
+ handoffContext?.routeIdentity === routeIdentity
+ ? handoffContext.context
+ : pageContext;
+
+ // The full chat page mounts no dock, so a handoff made there would lead
+ // nowhere. Its transcript already carries its own follow-up affordance.
+ const onChatPage = pageContext.kind === "chat";
+
+ /** Selections name a file; everything else stays on the page's own context. */
+ const resolveSelectionContext = useCallback(
+ (path?: string): PageChatContext =>
+ path
+ ? { kind: "file", label: path, target: path, targetKind: "path" }
+ : activeContext,
+ [activeContext],
+ );
+
const {
messages,
conversationId,
@@ -85,7 +162,7 @@ export function RepositoryChatProvider({
() => ({
repoId,
repoName,
- pageContext,
+ pageContext: activeContext,
selectedProvider: modelSelection?.provider ?? null,
selectedModel: modelSelection?.model ?? null,
selectModel,
@@ -99,11 +176,13 @@ export function RepositoryChatProvider({
reset,
artifactOverrides,
replaceArtifact,
+ dockCommand,
+ clearDockCommand,
}),
[
repoId,
repoName,
- pageContext,
+ activeContext,
messages,
conversationId,
isStreaming,
@@ -116,12 +195,21 @@ export function RepositoryChatProvider({
replaceArtifact,
modelSelection,
selectModel,
+ dockCommand,
+ clearDockCommand,
],
);
return (
<RepositoryChatContext.Provider value={value}>
- {children}
+ <ChatHandoffProvider
+ onHandoff={requestHandoff}
+ askEnabled={askControlsEnabled && !onChatPage}
+ selectionEnabled={selectionAskEnabled && !onChatPage}
+ >
+ {children}
+ <ChatSelectionAffordance resolveContext={resolveSelectionContext} />
+ </ChatHandoffProvider>
</RepositoryChatContext.Provider>
);
}
diff --git a/packages/web/src/components/chat/use-chat-dock-hidden.test.tsx b/packages/web/src/components/chat/use-chat-dock-hidden.test.tsx
index 97a7c7ad0..5a86d4526 100644
--- a/packages/web/src/components/chat/use-chat-dock-hidden.test.tsx
+++ b/packages/web/src/components/chat/use-chat-dock-hidden.test.tsx
@@ -3,13 +3,32 @@
import React from "react";
import { render, screen, act, cleanup } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { config, setChatDockHidden } from "@/lib/config";
-import { useChatDockHidden } from "./use-chat-dock-hidden";
+import {
+ config,
+ setChatAskControlsHidden,
+ setChatDockHidden,
+ setChatSelectionAskHidden,
+} from "@/lib/config";
+import { useChatAffordances, useChatDockHidden } from "./use-chat-dock-hidden";
function Probe() {
return <span>{useChatDockHidden() ? "hidden" : "shown"}</span>;
}
+function AffordanceProbe() {
+ const { dockHidden, askControlsEnabled, selectionAskEnabled } =
+ useChatAffordances();
+ return (
+ <span>
+ {[
+ dockHidden ? "dock-hidden" : "dock-shown",
+ askControlsEnabled ? "ask-on" : "ask-off",
+ selectionAskEnabled ? "selection-on" : "selection-off",
+ ].join(" ")}
+ </span>
+ );
+}
+
describe("useChatDockHidden", () => {
beforeEach(() => {
localStorage.clear();
@@ -64,3 +83,57 @@ describe("useChatDockHidden", () => {
expect(config.getChatDockHidden()).toBe(false);
});
});
+
+describe("useChatAffordances", () => {
+ beforeEach(() => localStorage.clear());
+ afterEach(cleanup);
+
+ it("defaults both page controls on", () => {
+ render(<AffordanceProbe />);
+ expect(screen.getByText("dock-shown ask-on selection-on")).toBeTruthy();
+ });
+
+ it("switches each control off on its own", () => {
+ render(<AffordanceProbe />);
+
+ act(() => setChatAskControlsHidden(true));
+ expect(screen.getByText("dock-shown ask-off selection-on")).toBeTruthy();
+
+ act(() => setChatSelectionAskHidden(true));
+ expect(screen.getByText("dock-shown ask-off selection-off")).toBeTruthy();
+ });
+
+ it("hides both controls whenever the dock itself is hidden", () => {
+ render(<AffordanceProbe />);
+ act(() => setChatDockHidden(true));
+ expect(screen.getByText("dock-hidden ask-off selection-off")).toBeTruthy();
+ });
+
+ it("restores a control's own choice when the dock comes back", () => {
+ config.setChatAskControlsHidden(true);
+ render(<AffordanceProbe />);
+
+ act(() => setChatDockHidden(true));
+ expect(screen.getByText("dock-hidden ask-off selection-off")).toBeTruthy();
+
+ act(() => setChatDockHidden(false));
+ expect(screen.getByText("dock-shown ask-off selection-on")).toBeTruthy();
+ });
+
+ it("stays off across reloads and across tabs", () => {
+ // A reload is a fresh mount reading the same storage.
+ config.setChatSelectionAskHidden(true);
+ render(<AffordanceProbe />);
+ expect(screen.getByText("dock-shown ask-on selection-off")).toBeTruthy();
+ cleanup();
+
+ render(<AffordanceProbe />);
+ expect(screen.getByText("dock-shown ask-on selection-off")).toBeTruthy();
+
+ act(() => {
+ config.setChatAskControlsHidden(true);
+ window.dispatchEvent(new StorageEvent("storage"));
+ });
+ expect(screen.getByText("dock-shown ask-off selection-off")).toBeTruthy();
+ });
+});
diff --git a/packages/web/src/components/chat/use-chat-dock-hidden.ts b/packages/web/src/components/chat/use-chat-dock-hidden.ts
index a0384746d..8a0d3f33a 100644
--- a/packages/web/src/components/chat/use-chat-dock-hidden.ts
+++ b/packages/web/src/components/chat/use-chat-dock-hidden.ts
@@ -4,10 +4,10 @@ import { useEffect, useState } from "react";
import { CHAT_DOCK_VISIBILITY_EVENT, config } from "@/lib/config";
/**
- * Whether the "Ask Repowise" dock is hidden, kept in step with the settings
- * toggle without a reload.
+ * Which chat affordances this browser shows, kept in step with the settings
+ * toggles without a reload.
*
- * Starts `false` and reads the stored value after mount rather than during
+ * Starts at the defaults and reads stored values after mount rather than during
* render: `localStorage` does not exist on the server, so seeding from it
* directly would make the server and the first client render disagree and
* flash the dock away on hydration.
@@ -16,11 +16,45 @@ import { CHAT_DOCK_VISIBILITY_EVENT, config } from "@/lib/config";
* OTHER tabs, so it keeps a second window honest; the custom event covers the
* tab that made the change, where `storage` stays silent.
*/
-export function useChatDockHidden(): boolean {
- const [hidden, setHidden] = useState(false);
+export interface ChatAffordances {
+ dockHidden: boolean;
+ /** Per-object "Ask about this" controls. */
+ askControlsEnabled: boolean;
+ /** The control that appears beside a text selection. */
+ selectionAskEnabled: boolean;
+}
+
+const DEFAULTS: ChatAffordances = {
+ dockHidden: false,
+ askControlsEnabled: true,
+ selectionAskEnabled: true,
+};
+
+function readAffordances(): ChatAffordances {
+ // Hiding the dock hides the page controls with it: they all lead to the same
+ // place, and a control that opens something the reader has switched off is a
+ // dead path.
+ const dockHidden = config.getChatDockHidden();
+ return {
+ dockHidden,
+ askControlsEnabled: !dockHidden && !config.getChatAskControlsHidden(),
+ selectionAskEnabled: !dockHidden && !config.getChatSelectionAskHidden(),
+ };
+}
+
+export function useChatAffordances(): ChatAffordances {
+ const [state, setState] = useState<ChatAffordances>(DEFAULTS);
useEffect(() => {
- const sync = () => setHidden(config.getChatDockHidden());
+ const sync = () =>
+ setState((current) => {
+ const next = readAffordances();
+ return current.dockHidden === next.dockHidden &&
+ current.askControlsEnabled === next.askControlsEnabled &&
+ current.selectionAskEnabled === next.selectionAskEnabled
+ ? current
+ : next;
+ });
sync();
window.addEventListener(CHAT_DOCK_VISIBILITY_EVENT, sync);
window.addEventListener("storage", sync);
@@ -30,5 +64,9 @@ export function useChatDockHidden(): boolean {
};
}, []);
- return hidden;
+ return state;
+}
+
+export function useChatDockHidden(): boolean {
+ return useChatAffordances().dockHidden;
}
diff --git a/packages/web/src/components/docs/docs-explorer.tsx b/packages/web/src/components/docs/docs-explorer.tsx
index ec192ee34..0e7906926 100644
--- a/packages/web/src/components/docs/docs-explorer.tsx
+++ b/packages/web/src/components/docs/docs-explorer.tsx
@@ -24,6 +24,7 @@ import {
} from "@repowise-dev/ui/docs/reader-persona";
import { DocsHeader } from "./docs-header";
import { DocsViewer } from "./docs-viewer";
+import { AskAboutThis } from "@repowise-dev/ui/chat";
import {
DocsPageActions,
ExportMenu,
@@ -357,6 +358,19 @@ export function DocsExplorer({ repoId }: DocsExplorerProps) {
personaHasEffect={personaHasEffect}
/>
)}
+ {selectedPage && (
+ <AskAboutThis
+ context={{
+ kind: "documentation",
+ label: selectedPage.title,
+ target: selectedPage.id,
+ targetKind: "documentation",
+ }}
+ question={`Explain "${selectedPage.title}" using the source code, and name the files it rests on.`}
+ label={`Ask about ${selectedPage.title}`}
+ className="shrink-0"
+ />
+ )}
{selectedPage && isModelWrittenType(selectedPage.page_type) && (
<PageGenerateButton
page={selectedPage}
diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.ts
index c8e02b08e..b21b25ca8 100644
--- a/packages/web/src/components/layout/nav-items.ts
+++ b/packages/web/src/components/layout/nav-items.ts
@@ -2,9 +2,11 @@
* Single source of truth for app navigation. Both the desktop sidebar and
* the mobile nav consume these — the two surfaces must never diverge again.
*
- * Repo IA (6 groups + Settings pinned last):
- * Overview · Docs · Architecture · Knowledge Graph · Code Health ·
- * People & History · Chat
+ * Repo IA (3 groups + Settings pinned last):
+ * Overview · Chat · Docs · Architecture · Knowledge Graph · Code Health ·
+ * Refactoring · Files, then People & History, then Settings.
+ * Chat sits second because it is the fastest route to an answer about
+ * anything below it, not because it is the second most visited page.
*/
import {
@@ -62,6 +64,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {
{
items: [
{ label: "Overview", href: `${base}/overview`, icon: Activity },
+ { label: "Chat", href: `${base}/chat`, icon: MessageSquare },
{ label: "Docs", href: `${base}/docs`, icon: BookOpen },
{ label: "Architecture", href: `${base}/architecture`, icon: Boxes },
{ label: "Knowledge Graph", href: `${base}/knowledge-graph`, icon: ScanSearch },
@@ -78,9 +81,6 @@ export function repoNavGroups(repoId: string): NavGroup[] {
{ label: "Decisions", href: `${base}/decisions`, icon: Lightbulb },
],
},
- {
- items: [{ label: "Chat", href: `${base}/chat`, icon: MessageSquare }],
- },
{
label: "Settings",
items: [
diff --git a/packages/web/src/components/layout/repo-breadcrumb.tsx b/packages/web/src/components/layout/repo-breadcrumb.tsx
index b146182ae..7c29cdfdf 100644
--- a/packages/web/src/components/layout/repo-breadcrumb.tsx
+++ b/packages/web/src/components/layout/repo-breadcrumb.tsx
@@ -2,6 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
+import { MessageSquare } from "lucide-react";
import { Breadcrumb } from "@repowise-dev/ui/shared/breadcrumb";
import type { BreadcrumbSegment } from "@repowise-dev/ui/shared/breadcrumb";
import { DocsModeBadge, type DocsMode } from "@repowise-dev/ui/docs/docs-mode-badge";
@@ -46,12 +47,26 @@ export function RepoBreadcrumb({
const showCrumbs = segments.length > 2 && showsRouteBreadcrumb(pathname);
const showBadge = docsMode !== "none";
// Nothing to show at the repo root with no docs — stay out of the way.
+ // The Ask entry rides this row rather than earning one of its own: a bar
+ // that exists only to hold a chat link is new permanent chrome.
if (!showCrumbs && !showBadge) return null;
+ const onChatPage = rest[0] === "chat";
return (
<div className="flex items-center justify-between gap-3 px-4 sm:px-6 py-2 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">
{showCrumbs ? <Breadcrumb segments={segments} LinkComponent={Link} /> : <span />}
- {showBadge && <DocsModeBadge mode={docsMode} />}
+ <div className="flex shrink-0 items-center gap-3">
+ {showBadge && <DocsModeBadge mode={docsMode} />}
+ {!onChatPage && (
+ <Link
+ href={`/repos/${repoId}/chat`}
+ className="inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-xs 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)]"
+ >
+ <MessageSquare className="h-3.5 w-3.5" aria-hidden />
+ Ask
+ </Link>
+ )}
+ </div>
</div>
);
}
diff --git a/packages/web/src/components/settings/display-section.tsx b/packages/web/src/components/settings/display-section.tsx
index 548398e1e..fa2a03823 100644
--- a/packages/web/src/components/settings/display-section.tsx
+++ b/packages/web/src/components/settings/display-section.tsx
@@ -17,19 +17,78 @@ import {
} from "@repowise-dev/ui/settings";
import { Switch } from "@repowise-dev/ui/ui/switch";
import { DEFAULT_WEEKEND_PRESET, WEEKEND_PRESETS } from "@repowise-dev/ui/stats";
-import { config, setChatDockHidden } from "@/lib/config";
+import {
+ CHAT_DOCK_VISIBILITY_EVENT,
+ config,
+ setChatAskControlsHidden,
+ setChatDockHidden,
+ setChatSelectionAskHidden,
+} from "@/lib/config";
+
+/** The three chat switches, in the order a reader meets them: the dock first,
+ * then the two controls it gates. Each hint names what switching off removes. */
+const CHAT_SWITCHES = [
+ {
+ key: "dock",
+ label: "Ask Repowise",
+ hint: "The chat pill in the bottom-right of every repository page. Hiding it also hides the two controls below, and does not affect the full chat page.",
+ ariaLabel: "Show the Ask Repowise chat pill",
+ read: () => !config.getChatDockHidden(),
+ write: (shown: boolean) => setChatDockHidden(!shown),
+ },
+ {
+ key: "ask",
+ label: "Ask about this",
+ hint: "The small chat button beside a file, symbol, finding, decision or commit. Hiding it removes those buttons; the pill and the full chat page still work.",
+ ariaLabel: "Show the Ask about this buttons",
+ read: () => !config.getChatAskControlsHidden(),
+ write: (shown: boolean) => setChatAskControlsHidden(!shown),
+ },
+ {
+ key: "selection",
+ label: "Ask about a selection",
+ hint: "The control that appears when you select text in code or documentation. Hiding it removes that control; selecting text behaves normally.",
+ ariaLabel: "Show the Ask about selection control",
+ read: () => !config.getChatSelectionAskHidden(),
+ write: (shown: boolean) => setChatSelectionAskHidden(!shown),
+ },
+] as const;
+
+type ChatSwitchKey = (typeof CHAT_SWITCHES)[number]["key"];
/** Reader-local display preferences for the stats surfaces. */
export function DisplaySection() {
const [weekend, setWeekend] = useState(DEFAULT_WEEKEND_PRESET.id);
- const [dockShown, setDockShown] = useState(true);
+ const [chatShown, setChatShown] = useState<Record<ChatSwitchKey, boolean>>({
+ dock: true,
+ ask: true,
+ selection: true,
+ });
const [saveState, setSaveState] = useState<SaveState>("idle");
const savedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Read after mount so SSR and the first client render agree.
useEffect(() => {
setWeekend(config.getWeekend() || DEFAULT_WEEKEND_PRESET.id);
- setDockShown(!config.getChatDockHidden());
+ }, []);
+
+ // The same two listeners the affordances themselves use: `storage` covers
+ // another tab, the custom event covers this one. Without them these switches
+ // would keep showing a choice another surface has already changed.
+ useEffect(() => {
+ const sync = () =>
+ setChatShown({
+ dock: CHAT_SWITCHES[0].read(),
+ ask: CHAT_SWITCHES[1].read(),
+ selection: CHAT_SWITCHES[2].read(),
+ });
+ sync();
+ window.addEventListener(CHAT_DOCK_VISIBILITY_EVENT, sync);
+ window.addEventListener("storage", sync);
+ return () => {
+ window.removeEventListener(CHAT_DOCK_VISIBILITY_EVENT, sync);
+ window.removeEventListener("storage", sync);
+ };
}, []);
useEffect(
@@ -51,11 +110,15 @@ export function DisplaySection() {
markSaved();
}
- function handleDockChange(shown: boolean) {
- setDockShown(shown);
- // Goes through the helper, not `config` directly: the dock is mounted on a
- // different route and needs the event to notice.
- setChatDockHidden(!shown);
+ function handleChatChange(
+ entry: (typeof CHAT_SWITCHES)[number],
+ shown: boolean,
+ ) {
+ // Goes through the helper, not `config` directly: the affordances are
+ // mounted on a different route and need the event to notice. The event
+ // also drives this component's own sync, so there is no optimistic state
+ // that could drift from storage.
+ entry.write(shown);
markSaved();
}
@@ -83,16 +146,29 @@ export function DisplaySection() {
</SelectContent>
</Select>
</SettingsRow>
- <SettingsRow
- label="Ask Repowise"
- hint="The chat pill in the bottom-right of every repository page. Hiding it does not affect the full chat page."
- >
- <Switch
- checked={dockShown}
- onCheckedChange={handleDockChange}
- aria-label="Show the Ask Repowise chat pill"
- />
- </SettingsRow>
+ {CHAT_SWITCHES.map((entry) => {
+ // The dock gates the other two, so their switches cannot act while it
+ // is hidden. Say why rather than leaving a live-looking control.
+ const gated = entry.key !== "dock" && !chatShown.dock;
+ return (
+ <SettingsRow
+ key={entry.key}
+ label={entry.label}
+ hint={
+ gated
+ ? `${entry.hint} Unavailable while Ask Repowise is hidden.`
+ : entry.hint
+ }
+ >
+ <Switch
+ checked={chatShown[entry.key] && !gated}
+ disabled={gated}
+ onCheckedChange={(shown) => handleChatChange(entry, shown)}
+ aria-label={entry.ariaLabel}
+ />
+ </SettingsRow>
+ );
+ })}
</SettingsRows>
</OverviewSection>
);
diff --git a/packages/web/src/lib/config.ts b/packages/web/src/lib/config.ts
index dc18496cb..ba7ec1a95 100644
--- a/packages/web/src/lib/config.ts
+++ b/packages/web/src/lib/config.ts
@@ -12,6 +12,9 @@ const KEYS = {
embedder: "repowise_embedder",
weekend: "repowise_weekend",
chatDockHidden: "repowise_chat_dock_hidden",
+ chatAskControlsHidden: "repowise_chat_ask_controls_hidden",
+ chatSelectionAskHidden: "repowise_chat_selection_ask_hidden",
+ chatHintSeen: "repowise_chat_hint_seen",
} as const;
function read(key: string): string {
@@ -54,16 +57,47 @@ export const config = {
* shown, so an unset value reads as false. */
getChatDockHidden: () => read(KEYS.chatDockHidden) === "1",
setChatDockHidden: (v: boolean) => write(KEYS.chatDockHidden, v ? "1" : ""),
+
+ /** Whether the per-object "Ask about this" controls are hidden. Same
+ * default-shown encoding as the dock. */
+ getChatAskControlsHidden: () => read(KEYS.chatAskControlsHidden) === "1",
+ setChatAskControlsHidden: (v: boolean) =>
+ write(KEYS.chatAskControlsHidden, v ? "1" : ""),
+
+ /** Whether the control that appears beside a text selection is hidden. */
+ getChatSelectionAskHidden: () => read(KEYS.chatSelectionAskHidden) === "1",
+ setChatSelectionAskHidden: (v: boolean) =>
+ write(KEYS.chatSelectionAskHidden, v ? "1" : ""),
+
+ /** Whether the pill has already introduced itself once in this browser. */
+ getChatHintSeen: () => read(KEYS.chatHintSeen) === "1",
+ setChatHintSeen: () => write(KEYS.chatHintSeen, "1"),
};
-/** Fires when the dock's visibility changes in this tab. `localStorage` only
- * notifies OTHER tabs via `storage`, so without this the dock and the settings
- * toggle would not agree until a reload. */
+/** Fires when any chat affordance's visibility changes in this tab.
+ * `localStorage` only notifies OTHER tabs via `storage`, so without this the
+ * affordance and the settings toggle would not agree until a reload. One
+ * event for all three: every reader of one reads the others too, because
+ * hiding the dock hides the page controls with it. */
export const CHAT_DOCK_VISIBILITY_EVENT = "repowise:chat-dock-visibility";
-export function setChatDockHidden(hidden: boolean): void {
- config.setChatDockHidden(hidden);
+function announce(): void {
if (typeof window !== "undefined") {
window.dispatchEvent(new Event(CHAT_DOCK_VISIBILITY_EVENT));
}
}
+
+export function setChatDockHidden(hidden: boolean): void {
+ config.setChatDockHidden(hidden);
+ announce();
+}
+
+export function setChatAskControlsHidden(hidden: boolean): void {
+ config.setChatAskControlsHidden(hidden);
+ announce();
+}
+
+export function setChatSelectionAskHidden(hidden: boolean): void {
+ config.setChatSelectionAskHidden(hidden);
+ announce();
+}
diff --git a/packages/web/vitest.config.ts b/packages/web/vitest.config.ts
index 8d0405a66..693d22a67 100644
--- a/packages/web/vitest.config.ts
+++ b/packages/web/vitest.config.ts
@@ -2,6 +2,10 @@ import { defineConfig } from "vitest/config";
import path from "node:path";
export default defineConfig({
+ // `jsx: "preserve"` in tsconfig leaves esbuild on the classic transform, so
+ // any component that does not import React itself fails to render under
+ // test. Next compiles the app with the automatic runtime; match it here.
+ esbuild: { jsx: "automatic", jsxImportSource: "react" },
test: {
include: ["src/**/*.{test,spec}.{ts,tsx}"],
},
diff --git a/tests/unit/server/test_chat_grounding.py b/tests/unit/server/test_chat_grounding.py
index 2980dc439..3b2076912 100644
--- a/tests/unit/server/test_chat_grounding.py
+++ b/tests/unit/server/test_chat_grounding.py
@@ -45,6 +45,8 @@ def _context(kind: str, target: str | None = None, target_kind: str | None = Non
("module", "src/pkg", "get_context", {"targets": ["src/pkg"]}),
("symbol", "src/a.py::run", "get_symbol", {"symbol_id": "src/a.py::run"}),
("risk", "src/a.py", "get_risk", {"targets": ["src/a.py"]}),
+ ("dead-code", "src/a.py", "get_risk", {"targets": ["src/a.py"]}),
+ ("blast-radius", "src/a.py", "get_risk", {"targets": ["src/a.py"]}),
("health", "src/a.py", "get_health", {"targets": ["src/a.py"]}),
("decision", "d13e820c", "get_why", {"id": "d13e820c"}),
("commit", "abc1234", "get_change_risk", {"revspec": "abc1234"}),