Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(chat): add persistent contextual dock (#1951)
Raghav Chamadiya2f64022b8138
diff --git a/packages/ui/__tests__/chat/chat-dock.test.tsx b/packages/ui/__tests__/chat/chat-dock.test.tsxnew file mode 100644index 000000000..42a7eae4a--- /dev/null+++ b/packages/ui/__tests__/chat/chat-dock.test.tsx@@ -0,0 +1,300 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { renderToString } from "react-dom/server";+import { hydrateRoot, type Root } from "react-dom/client";+import { ChatDock, type ChatDockProps } from "../../src/chat/chat-dock.js";+import type { ChatUIMessage } from "@repowise-dev/types/chat";++const MESSAGE: ChatUIMessage = {+ id: "assistant-1",+ role: "assistant",+ text: "The parser lives in packages/core.",+ toolCalls: [],+ isStreaming: false,+};++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,+ };+}++describe("ChatDock", () => {+ beforeEach(() => window.localStorage.clear());+ afterEach(() => vi.unstubAllGlobals());++ it("moves between minimized, compact, and expanded states", async () => {+ render(<ChatDock {...props()} />);++ expect(screen.getByText("Ask Repowise")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));+ expect(screen.getByRole("complementary", { name: "Repository chat" })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Expand repository chat" }));+ expect(await screen.findByRole("dialog", { name: "Repository chat" })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Collapse repository chat" }));+ expect(screen.getByRole("complementary", { name: "Repository chat" })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Minimize repository chat" }));+ expect(screen.getByRole("button", { name: "Open repository chat" })).toBeInTheDocument();+ });++ it("keeps compact discovery focused on one contextual suggestion", () => {+ render(<ChatDock {...props()} />);+ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));++ expect(screen.getAllByRole("button", { name: /^Try / })).toHaveLength(1);+ });++ it("updates context copy on navigation without losing the conversation", () => {+ const view = render(<ChatDock {...props({ messages: [MESSAGE] })} />);+ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));+ expect(screen.getByLabelText("Chat message")).toHaveAttribute(+ "placeholder",+ "Ask about this repository overview",+ );++ view.rerender(+ <ChatDock+ {...props({+ messages: [MESSAGE],+ context: {+ kind: "file",+ label: "Files",+ target: "src/parser.ts",+ targetKind: "path",+ },+ })}+ />,+ );+ expect(screen.getByLabelText("Chat message")).toHaveAttribute(+ "placeholder",+ "Ask about this file",+ );++ fireEvent.click(screen.getByRole("button", { name: "Expand repository chat" }));+ expect(screen.getByText("The parser lives in packages/core.")).toBeInTheDocument();+ expect(screen.getByText("src/parser.ts")).toBeInTheDocument();+ });++ it("opens the full chat through the host navigation callback", async () => {+ const onOpenFullChat = vi.fn();+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "expanded", draft: "" }),+ );+ render(<ChatDock {...props({ messages: [MESSAGE], onOpenFullChat })} />);+ fireEvent.click(await screen.findByRole("button", { name: "Full chat" }));+ expect(onOpenFullChat).toHaveBeenCalledOnce();+ });++ it("removes context, restores composer focus, and resets for a new page", async () => {+ const view = render(+ <ChatDock+ {...props({+ context: { kind: "health", label: "Code Health" },+ })}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));+ const remove = screen.getByRole("button", {+ name: "Remove current view from this message",+ });+ remove.focus();+ fireEvent.click(remove);+ expect(screen.queryByText("Current view")).not.toBeInTheDocument();+ await waitFor(() => expect(screen.getByLabelText("Chat message")).toHaveFocus());++ view.rerender(+ <ChatDock+ {...props({ context: { kind: "architecture", label: "Architecture" } })}+ />,+ );+ expect(screen.getByText("Current view")).toBeInTheDocument();+ });++ it("restores focus across compact and expanded dismiss transitions", async () => {+ render(<ChatDock {...props()} />);+ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));+ fireEvent.click(screen.getByRole("button", { name: "Minimize repository chat" }));+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Open repository chat" })).toHaveFocus(),+ );++ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));+ fireEvent.click(screen.getByRole("button", { name: "Expand repository chat" }));+ fireEvent.keyDown(document, { key: "Escape" });+ await waitFor(() => expect(screen.getByLabelText("Chat message")).toHaveFocus());++ fireEvent.click(screen.getByRole("button", { name: "Expand repository chat" }));+ fireEvent.click(screen.getByRole("button", { name: "Minimize repository chat" }));+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Open repository chat" })).toHaveFocus(),+ );+ });++ it("restores the expanded composer focus after removing page context", async () => {+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "expanded", draft: "" }),+ );+ render(+ <ChatDock+ {...props({+ context: {+ kind: "file",+ label: "Files",+ target: "src/parser.ts",+ targetKind: "path",+ },+ })}+ />,+ );+ fireEvent.click(+ await screen.findByRole("button", {+ name: "Remove current view from this message",+ }),+ );+ await waitFor(() => expect(screen.getByLabelText("Chat message")).toHaveFocus());+ });++ it("keeps the expanded desktop dock non-modal while the page remains interactive", async () => {+ vi.stubGlobal(+ "matchMedia",+ vi.fn().mockReturnValue({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }),+ );+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "expanded", draft: "" }),+ );+ const onPageAction = vi.fn();+ render(+ <>+ <button type="button" onClick={onPageAction}>Select page entity</button>+ <ChatDock {...props()} />+ </>,+ );+ expect(await screen.findByRole("dialog", { name: "Repository chat" })).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Select page entity" }));+ expect(onPageAction).toHaveBeenCalledOnce();+ expect(screen.getByRole("dialog", { name: "Repository chat" })).toBeInTheDocument();+ });++ it("exposes a host collision inset for bottom-anchored page controls", async () => {+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "compact", draft: "" }),+ );+ render(<ChatDock {...props({ collisionInset: "5rem" })} />);+ expect(await screen.findByRole("complementary", { name: "Repository chat" })).toHaveStyle({+ "--chat-dock-bottom-offset": "5rem",+ });+ });++ it("subtracts a desktop collision inset from expanded height", async () => {+ vi.stubGlobal(+ "matchMedia",+ vi.fn().mockReturnValue({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }),+ );+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "expanded", draft: "" }),+ );+ render(<ChatDock {...props({ collisionInset: "11rem" })} />);+ expect(await screen.findByRole("dialog", { name: "Repository chat" })).toHaveStyle({+ "--chat-dock-bottom-offset": "11rem",+ height: "min(760px, calc(100dvh - var(--chat-dock-bottom-offset) - 1rem))",+ });+ });++ it("server-renders a stable minimized shell before hydrating persisted state", async () => {+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "expanded", draft: "saved question" }),+ );+ const html = renderToString(<ChatDock {...props()} />);+ expect(html).toContain("Open repository chat");+ expect(html).not.toContain("Repository chat</h2>");++ const container = document.createElement("div");+ container.innerHTML = html;+ document.body.appendChild(container);+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);+ let root: Root | undefined;+ await act(async () => {+ root = hydrateRoot(container, <ChatDock {...props()} />);+ });+ await waitFor(() =>+ expect(screen.getByRole("dialog", { name: "Repository chat" })).toBeInTheDocument(),+ );+ expect(+ consoleError.mock.calls.some((call) => String(call[0]).includes("hydration")),+ ).toBe(false);+ await act(async () => root?.unmount());+ container.remove();+ consoleError.mockRestore();+ });++ it("continues to report streaming and announces quiet completion while minimized", () => {+ const view = render(<ChatDock {...props({ isStreaming: true })} />);+ expect(+ screen.getByRole("button", { name: "Open repository chat, response in progress" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("status")).toHaveTextContent("Working");++ view.rerender(<ChatDock {...props({ isStreaming: false, messages: [MESSAGE] })} />);+ expect(+ screen.getByRole("button", { name: "Open repository chat, answer ready" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("status")).toHaveTextContent("Answer ready");+ });++ it("suppresses every dock state when the host is the full chat page", () => {+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "expanded", draft: "still here" }),+ );+ const { container } = render(<ChatDock {...props({ suppressed: true })} />);+ expect(container).toBeEmptyDOMElement();+ });++ it("persists drafts by repository and never leaks them across repositories", async () => {+ window.localStorage.setItem(+ "dock:r1",+ JSON.stringify({ mode: "compact", draft: "question for one" }),+ );+ window.localStorage.setItem(+ "dock:r2",+ JSON.stringify({ mode: "compact", draft: "question for two" }),+ );+ const view = render(<ChatDock {...props()} />);+ expect(screen.getByLabelText("Chat message")).toHaveValue("question for one");++ view.rerender(+ <ChatDock {...props({ storageKey: "dock:r2", repoId: "r2", repoName: "beta" })} />,+ );+ await waitFor(() =>+ expect(screen.getByLabelText("Chat message")).toHaveValue("question for two"),+ );+ expect(JSON.parse(window.localStorage.getItem("dock:r1") ?? "{}").draft).toBe(+ "question for one",+ );+ });+});diff --git a/packages/ui/src/chat/chat-composer.tsx b/packages/ui/src/chat/chat-composer.tsxnew file mode 100644index 000000000..b316d31e9--- /dev/null+++ b/packages/ui/src/chat/chat-composer.tsx@@ -0,0 +1,104 @@+"use client";++import { useEffect, useRef, type RefObject } from "react";+import { Send, StopCircle } from "lucide-react";+import { Button } from "../ui/button";+import { cn } from "../lib/cn";++export interface ChatComposerProps {+ value: string;+ onValueChange: (value: string) => void;+ onSend: (text: string) => void | Promise<void>;+ onCancel: () => void;+ isStreaming: boolean;+ placeholder: string;+ disabled?: boolean;+ autoFocus?: boolean;+ compact?: boolean;+ appearance?: "contained" | "bare";+ textareaRef?: RefObject<HTMLTextAreaElement | null>;+ className?: string;+}++/** Shared, controlled composer used by both the page chat and floating dock. */+export function ChatComposer({+ value,+ onValueChange,+ onSend,+ onCancel,+ isStreaming,+ placeholder,+ disabled = false,+ autoFocus = false,+ compact = false,+ appearance = "contained",+ textareaRef: forwardedRef,+ className,+}: ChatComposerProps) {+ const localRef = useRef<HTMLTextAreaElement>(null);+ const textareaRef = forwardedRef ?? localRef;++ useEffect(() => {+ const textarea = textareaRef.current;+ if (!textarea) return;+ textarea.style.height = "auto";+ textarea.style.height = `${Math.min(textarea.scrollHeight, compact ? 96 : 144)}px`;+ }, [compact, textareaRef, value]);++ async function submit() {+ const text = value.trim();+ if (!text || isStreaming || disabled) return;+ onValueChange("");+ await onSend(text);+ }++ return (+ <div+ className={cn(+ "flex items-end gap-2",+ appearance === "contained"+ ? "rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3 focus-within:border-[var(--color-accent-primary)]"+ : "border-t border-[var(--color-border-subtle)] px-0 pb-0 pt-3",+ disabled && "opacity-60",+ compact && appearance === "contained" && "rounded-xl px-3 py-2.5",+ className,+ )}+ >+ <textarea+ ref={textareaRef}+ value={value}+ onChange={(event) => onValueChange(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault();+ void submit();+ }+ }}+ placeholder={placeholder}+ aria-label="Chat message"+ disabled={disabled}+ autoFocus={autoFocus}+ rows={1}+ className={cn(+ "min-w-0 flex-1 resize-none bg-transparent text-[15px] leading-6 text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-tertiary)] overflow-y-auto",+ compact ? "max-h-24" : "max-h-36",+ )}+ style={{ scrollbarWidth: "none" }}+ />+ <Button+ size="icon"+ className="h-8 w-8 shrink-0 rounded-xl"+ onClick={isStreaming ? onCancel : () => void submit()}+ disabled={(!value.trim() && !isStreaming) || disabled}+ aria-label={isStreaming ? "Stop generation" : "Send message"}+ title={isStreaming ? "Stop generation" : "Send message"}+ >+ {isStreaming ? (+ <StopCircle className="h-4 w-4" />+ ) : (+ <Send className="h-4 w-4" />+ )}+ </Button>+ </div>+ );+}diff --git a/packages/ui/src/chat/chat-context-indicator.tsx b/packages/ui/src/chat/chat-context-indicator.tsxindex 54d58fb31..b15fa0e7d 100644--- a/packages/ui/src/chat/chat-context-indicator.tsx+++ b/packages/ui/src/chat/chat-context-indicator.tsx@@ -1,14 +1,17 @@import { cn } from "../lib/cn";+import { X } from "lucide-react";import type { ChatContext } from "./chat-context";export interface ChatContextIndicatorProps {context: ChatContext;className?: string;+ onRemove?: () => void;}export function ChatContextIndicator({context,className,+ onRemove,}: ChatContextIndicatorProps) {return (<div@@ -29,6 +32,17 @@ export function ChatContextIndicator({{context.target}</span>)}+ {onRemove && (+ <button+ type="button"+ onClick={onRemove}+ aria-label="Remove current view from this message"+ title="Remove current view"+ className="ml-auto inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <X className="h-3.5 w-3.5" />+ </button>+ )}</div>);}diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsxnew file mode 100644index 000000000..2027bb66a--- /dev/null+++ b/packages/ui/src/chat/chat-dock.tsx@@ -0,0 +1,464 @@+"use client";++import * as DialogPrimitive from "@radix-ui/react-dialog";+import {+ Expand,+ MessageCircle,+ Minus,+ X,+} from "lucide-react";+import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";+import type { ChatUIMessage } from "@repowise-dev/types/chat";+import { BrandMark } from "../shared/brand-mark";+import { Button } from "../ui/button";+import { cn } from "../lib/cn";+import type { SourceReference } from "./source-citations";+import { ChatComposer } from "./chat-composer";+import { ChatContextIndicator } from "./chat-context-indicator";+import { getChatContextPresentation, type ChatContext } from "./chat-context";+import { ChatInterface } from "./chat-interface";++export type ChatDockMode = "minimized" | "compact" | "expanded";++interface PersistedDockState {+ mode: ChatDockMode;+ draft: string;+}++const DEFAULT_STATE: PersistedDockState = { mode: "minimized", draft: "" };++function readDockState(storageKey: string): PersistedDockState {+ if (typeof window === "undefined") return DEFAULT_STATE;+ try {+ const value = JSON.parse(window.localStorage.getItem(storageKey) ?? "null") as+ | Partial<PersistedDockState>+ | null;+ const mode =+ value?.mode === "compact" || value?.mode === "expanded" || value?.mode === "minimized"+ ? value.mode+ : DEFAULT_STATE.mode;+ return { mode, draft: typeof value?.draft === "string" ? value.draft : "" };+ } catch {+ return DEFAULT_STATE;+ }+}++function usePersistentDockState(storageKey: string) {+ const [state, setState] = useState(() => ({+ storageKey,+ ...DEFAULT_STATE,+ hydrated: false,+ }));++ useEffect(() => {+ setState({ storageKey, ...readDockState(storageKey), hydrated: true });+ }, [storageKey]);++ useEffect(() => {+ if (+ !state.hydrated ||+ state.storageKey !== storageKey ||+ typeof window === "undefined"+ ) return;+ const timeout = window.setTimeout(() => {+ try {+ window.localStorage.setItem(+ storageKey,+ JSON.stringify({ mode: state.mode, draft: state.draft }),+ );+ } catch {+ // Storage can be unavailable in private or embedded contexts. The dock+ // remains fully usable for the current repository session.+ }+ }, 150);+ return () => window.clearTimeout(timeout);+ }, [state, storageKey]);++ const visible = state.storageKey === storageKey ? state : {+ storageKey,+ ...DEFAULT_STATE,+ hydrated: false,+ };+ return {+ mode: visible.mode,+ draft: visible.draft,+ setMode: (mode: ChatDockMode) =>+ setState((current) => ({+ ...(current.storageKey === storageKey ? current : readDockState(storageKey)),+ storageKey,+ mode,+ hydrated: true,+ })),+ setDraft: (draft: string) =>+ setState((current) => ({+ ...(current.storageKey === storageKey ? current : readDockState(storageKey)),+ storageKey,+ draft,+ hydrated: true,+ })),+ };+}++function useMobileDock() {+ const [isMobile, setIsMobile] = useState(true);++ useEffect(() => {+ if (typeof window.matchMedia !== "function") return;+ const query = window.matchMedia("(max-width: 767px)");+ const update = () => setIsMobile(query.matches);+ update();+ query.addEventListener?.("change", update);+ return () => query.removeEventListener?.("change", update);+ }, []);++ return isMobile;+}++export interface ChatDockProps {+ storageKey: string;+ repoId: string;+ repoName?: string;+ context: ChatContext;+ messages: ChatUIMessage[];+ isStreaming: boolean;+ error?: string | null;+ onSend: (text: string, context?: ChatContext) => void | Promise<void>;+ onCancel: () => void;+ suppressed?: boolean;+ modelSelectorSlot?: ReactNode;+ historySlot?: ReactNode;+ sendDisabled?: boolean;+ sendDisabledReason?: ReactNode;+ assistantAvatarSrc?: string;+ buildCitationHref?: (source: SourceReference) => string;+ linkPrefix?: string;+ onOpenFullChat?: () => void;+ owlDarkSrc?: string;+ owlLightSrc?: string;+ /** Clears host page controls anchored near the viewport bottom. */+ collisionInset?: string;+}++function contextIdentity(context: ChatContext) {+ return `${context.kind}:${context.label}:${context.target ?? ""}`;+}++/** Portable persistent dock. Hosts provide one existing chat controller. */+export function ChatDock({+ storageKey,+ repoId,+ repoName,+ context,+ messages,+ isStreaming,+ error,+ onSend,+ onCancel,+ suppressed = false,+ modelSelectorSlot,+ historySlot,+ sendDisabled = false,+ sendDisabledReason,+ assistantAvatarSrc,+ buildCitationHref,+ linkPrefix,+ onOpenFullChat,+ owlDarkSrc = "/repowise-logo.png",+ owlLightSrc = "/repowise-logo-light.png",+ collisionInset = "1rem",+}: ChatDockProps) {+ const { mode, draft, setMode, setDraft } = usePersistentDockState(storageKey);+ const [dismissedContext, setDismissedContext] = useState<string | null>(null);+ const [answerReady, setAnswerReady] = useState(false);+ const previousStreaming = useRef(isStreaming);+ const compactTextareaRef = useRef<HTMLTextAreaElement>(null);+ const expandedTextareaRef = useRef<HTMLTextAreaElement>(null);+ const minimizedButtonRef = useRef<HTMLButtonElement>(null);+ const isMobile = useMobileDock();+ const identity = contextIdentity(context);+ const dockOffsetStyle = {+ "--chat-dock-bottom-offset": collisionInset,+ } as CSSProperties;+ const expandedDockStyle = {+ ...dockOffsetStyle,+ ...(isMobile+ ? {}+ : {+ height:+ "min(760px, calc(100dvh - var(--chat-dock-bottom-offset) - 1rem))",+ }),+ } as CSSProperties;++ useEffect(() => setDismissedContext(null), [identity]);++ useEffect(() => {+ if (previousStreaming.current && !isStreaming && mode === "minimized") {+ setAnswerReady(true);+ const timeout = window.setTimeout(() => setAnswerReady(false), 6000);+ previousStreaming.current = isStreaming;+ return () => window.clearTimeout(timeout);+ }+ previousStreaming.current = isStreaming;+ return undefined;+ }, [isStreaming, mode]);++ useEffect(() => {+ if (mode !== "minimized") setAnswerReady(false);+ }, [mode]);++ const activeContext = dismissedContext === identity ? undefined : context;+ const presentation = getChatContextPresentation(activeContext);+ const suggestion = presentation.suggestions[0];++ if (suppressed) return null;++ const send = (text: string) => onSend(text, activeContext);+ const removeCompactContext = () => {+ setDismissedContext(identity);+ window.requestAnimationFrame(() => compactTextareaRef.current?.focus());+ };+ const removeExpandedContext = () => {+ setDismissedContext(identity);+ window.requestAnimationFrame(() => expandedTextareaRef.current?.focus());+ };+ const minimize = () => {+ setMode("minimized");+ window.requestAnimationFrame(() => minimizedButtonRef.current?.focus());+ };+ const collapse = () => {+ setMode("compact");+ window.requestAnimationFrame(() => compactTextareaRef.current?.focus());+ };+ const statusText = isStreaming+ ? "Working"+ : answerReady+ ? error+ ? "Chat needs attention"+ : "Answer ready"+ : null;++ if (mode === "minimized") {+ return (+ <div+ style={dockOffsetStyle}+ className="fixed bottom-[max(var(--chat-dock-bottom-offset),env(safe-area-inset-bottom))] right-[max(1rem,env(safe-area-inset-right))] z-[calc(var(--z-toast)-1)]"+ >+ <button+ ref={minimizedButtonRef}+ type="button"+ onClick={() => setMode("compact")}+ aria-label={+ isStreaming+ ? "Open repository chat, response in progress"+ : answerReady+ ? `Open repository chat, ${error ? "chat needs attention" : "answer ready"}`+ : "Open repository chat"+ }+ className="group flex min-h-11 items-center gap-2 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1.5 pl-1.5 pr-3 shadow-[var(--shadow-md)] outline-none transition-[border-color,box-shadow,transform] hover:border-[var(--color-border-hover)] hover:shadow-[var(--shadow-lg)] focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] motion-safe:hover:-translate-y-px motion-reduce:transition-none"+ >+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent-muted)]">+ <BrandMark+ darkSrc={owlDarkSrc}+ lightSrc={owlLightSrc}+ size={25}+ alt=""+ />+ </span>+ <span className="text-[13px] font-medium text-[var(--color-text-primary)]">+ {statusText ?? "Ask Repowise"}+ </span>+ {statusText && (+ <span aria-hidden>+ <span+ className={cn(+ "block h-1.5 w-1.5 rounded-full",+ isStreaming+ ? "bg-[var(--color-text-tertiary)] motion-safe:animate-pulse"+ : "bg-[var(--color-accent-primary)]",+ )}+ />+ </span>+ )}+ </button>+ <span className="sr-only" role="status" aria-live="polite">+ {statusText ?? ""}+ </span>+ </div>+ );+ }++ if (mode === "compact") {+ return (+ <aside+ style={dockOffsetStyle}+ aria-label="Repository chat"+ className="fixed inset-x-3 bottom-[max(var(--chat-dock-bottom-offset),env(safe-area-inset-bottom))] z-[calc(var(--z-toast)-1)] mx-auto w-auto max-w-[640px] rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] px-3 pb-3 pt-2 shadow-[var(--shadow-lg)] sm:inset-x-auto sm:right-[max(1rem,env(safe-area-inset-right))] sm:w-[min(420px,calc(100vw-2rem))]"+ >+ <div className="flex min-w-0 items-center gap-1">+ <p className="min-w-0 flex-1 truncate pl-1 text-xs text-[var(--color-text-tertiary)]">+ {activeContext && activeContext.kind !== "repository"+ ? activeContext.label+ : repoName ?? "Repository"}+ </p>+ {isStreaming && (+ <span role="status" className="text-xs text-[var(--color-text-tertiary)]">+ Working+ </span>+ )}+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8"+ onClick={() => setMode("expanded")}+ aria-label="Expand repository chat"+ >+ <Expand className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8"+ onClick={minimize}+ aria-label="Minimize repository chat"+ >+ <Minus className="h-4 w-4" />+ </Button>+ </div>+ {activeContext && activeContext.kind !== "repository" && (+ <ChatContextIndicator+ context={activeContext}+ onRemove={removeCompactContext}+ className="pb-1 pt-0.5"+ />+ )}+ <ChatComposer+ value={draft}+ onValueChange={setDraft}+ onSend={send}+ onCancel={onCancel}+ isStreaming={isStreaming}+ placeholder={presentation.placeholder}+ disabled={sendDisabled}+ compact+ appearance="bare"+ 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-accent-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>+ )}+ {sendDisabled && sendDisabledReason && (+ <div className="mt-2 text-xs text-[var(--color-text-secondary)]">+ {sendDisabledReason}+ </div>+ )}+ </aside>+ );+ }++ return (+ <DialogPrimitive.Root+ open+ modal={isMobile}+ onOpenChange={(open) => {+ if (!open) collapse();+ }}+ >+ <DialogPrimitive.Portal>+ {isMobile && (+ <DialogPrimitive.Overlay className="fixed inset-0 z-[var(--z-modal)] bg-black/40" />+ )}+ <DialogPrimitive.Content+ style={expandedDockStyle}+ aria-describedby={undefined}+ onInteractOutside={(event) => {+ if (!isMobile) event.preventDefault();+ }}+ className="fixed inset-x-0 bottom-0 z-[var(--z-modal)] flex h-[min(88dvh,760px)] flex-col overflow-hidden rounded-t-2xl border-t border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] pb-[env(safe-area-inset-bottom)] shadow-[var(--shadow-xl)] outline-none md:inset-x-auto md:bottom-[max(var(--chat-dock-bottom-offset),env(safe-area-inset-bottom))] md:right-[max(1rem,env(safe-area-inset-right))] md:w-[min(480px,calc(100vw-2rem))] md:rounded-2xl md:border"+ >+ <DialogPrimitive.Title className="sr-only">+ Repository chat+ </DialogPrimitive.Title>+ <div className="flex justify-center py-2 md:hidden" aria-hidden>+ <div className="h-1 w-10 rounded-full bg-[var(--color-border-hover)]" />+ </div>+ <header className="flex min-w-0 items-center gap-2 border-b border-[var(--color-border-default)] px-3 py-2">+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[var(--color-accent-muted)]">+ <BrandMark darkSrc={owlDarkSrc} lightSrc={owlLightSrc} size={25} alt="" />+ </span>+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium text-[var(--color-text-primary)]">+ Ask Repowise+ </p>+ <p className="truncate text-xs text-[var(--color-text-tertiary)]">+ {repoName ?? repoId}+ </p>+ </div>+ {onOpenFullChat && (+ <button+ type="button"+ onClick={onOpenFullChat}+ className="inline-flex h-8 items-center gap-1.5 rounded-md px-2 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <MessageCircle className="h-3.5 w-3.5" />+ Full chat+ </button>+ )}+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8"+ onClick={collapse}+ aria-label="Collapse repository chat"+ >+ <Minus className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8"+ onClick={minimize}+ aria-label="Minimize repository chat"+ >+ <X className="h-4 w-4" />+ </Button>+ </header>+ <div className="min-h-0 flex-1">+ <ChatInterface+ variant="dock"+ repoId={repoId}+ {...(repoName ? { repoName } : {})}+ {...(activeContext ? { context: activeContext } : {})}+ messages={messages}+ isStreaming={isStreaming}+ {...(error !== undefined ? { error } : {})}+ onSend={send}+ onCancel={onCancel}+ draft={draft}+ onDraftChange={setDraft}+ onContextRemove={removeExpandedContext}+ composerRef={expandedTextareaRef}+ modelSelectorSlot={modelSelectorSlot}+ historySlot={historySlot}+ sendDisabled={sendDisabled}+ sendDisabledReason={sendDisabledReason}+ {...(assistantAvatarSrc ? { assistantAvatarSrc } : {})}+ {...(buildCitationHref ? { buildCitationHref } : {})}+ {...(linkPrefix ? { linkPrefix } : {})}+ />+ </div>+ </DialogPrimitive.Content>+ </DialogPrimitive.Portal>+ </DialogPrimitive.Root>+ );+}diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsxindex 0dd9e8960..c98fe5cc1 100644--- a/packages/ui/src/chat/chat-interface.tsx+++ b/packages/ui/src/chat/chat-interface.tsx@@ -23,9 +23,10 @@ import {useEffect,useRef,useState,+ type RefObject,type ReactNode,} from "react";-import { Send, StopCircle, PanelRight } from "lucide-react";+import { Send, PanelRight } from "lucide-react";import { Button } from "../ui/button";import { ScrollArea } from "../ui/scroll-area";import { cn } from "../lib/cn";@@ -39,6 +40,7 @@ import {} from "./chat-context";import type { ChatUIMessage } from "@repowise-dev/types/chat";import type { SourceReference } from "./source-citations";+import { ChatComposer } from "./chat-composer";const DEFAULT_SUGGESTIONS = ["Give me an overview of this codebase",@@ -105,6 +107,13 @@ export interface ChatInterfaceProps {sendDisabled?: boolean;/** Banner shown above the composer when sending is disabled. */sendDisabledReason?: ReactNode;+ /** Compact transcript treatment for a floating dock. */+ variant?: "page" | "dock";+ /** Optional controlled draft shared with another chat surface. */+ draft?: string;+ onDraftChange?: (draft: string) => void;+ onContextRemove?: () => void;+ composerRef?: RefObject<HTMLTextAreaElement | null>;}export function ChatInterface({@@ -127,12 +136,20 @@ export function ChatInterface({statusSlot,sendDisabled = false,sendDisabledReason,+ variant = "page",+ draft,+ onDraftChange,+ onContextRemove,+ composerRef,}: ChatInterfaceProps) {- const [input, setInput] = useState("");+ const [internalInput, setInternalInput] = useState("");+ const input = draft ?? internalInput;+ const setInput = onDraftChange ?? setInternalInput;const [artifactPanelOpen, setArtifactPanelOpen] = useState(false);const [artifacts, setArtifacts] = useState<Artifact[]>([]);const bottomRef = useRef<HTMLDivElement>(null);- const textareaRef = useRef<HTMLTextAreaElement>(null);+ const internalTextareaRef = useRef<HTMLTextAreaElement>(null);+ const textareaRef = composerRef ?? internalTextareaRef;const isEmpty = messages.length === 0;const contextPresentation = getChatContextPresentation(context);@@ -148,14 +165,6 @@ export function ChatInterface({bottomRef.current?.scrollIntoView?.({ behavior: "smooth" });}, [messages]);- useEffect(() => {- const ta = textareaRef.current;- if (ta) {- ta.style.height = "auto";- ta.style.height = `${Math.min(ta.scrollHeight, 144)}px`;- }- }, [input]);-const handleViewArtifact = useCallback((artifact: { type: string; data: Record<string, unknown> }) => {const title = (artifact.data.title as string) ?? artifact.type;@@ -191,23 +200,13 @@ export function ChatInterface({return undefined;}, [totalArtifactCount, artifactPanelOpen]);- async function handleSubmit() {- const text = input.trim();- if (!text || isStreaming || sendDisabled) return;- setInput("");- if (textareaRef.current) {- textareaRef.current.style.height = "auto";- }- await onSend(text);- }-function handleSuggestion(text: string) {setInput(text);textareaRef.current?.focus();}return (- <div className="flex h-full flex-col min-h-0">+ <div className="flex h-full min-h-0 flex-col" data-chat-variant={variant}>{/* The one chrome row. */}{(historySlot || modelSelectorSlot) && (<div className="flex items-center justify-between gap-2 px-[var(--page-pad)] py-2.5 border-b border-[var(--color-border-default)] shrink-0 bg-[var(--color-bg-surface)]">@@ -243,16 +242,16 @@ export function ChatInterface({// height Radix's `display:table` viewport wrapper does not pass down,// and the section style reads left-aligned everywhere else anyway.<ScrollArea className="h-full">- <div className="mx-auto flex max-w-2xl flex-col gap-10 px-[var(--page-pad)] py-14">+ <div className={cn("mx-auto flex max-w-2xl flex-col", variant === "dock" ? "gap-5 px-4 py-7" : "gap-10 px-[var(--page-pad)] py-14")}><div className="space-y-4">- <BrandMark darkSrc={emptyStateLogoSrc} size={40} />- <h2 className="text-[22px] font-semibold text-[var(--color-text-primary)]">- Ask anything about {repoName ?? "this codebase"}+ {variant !== "dock" && <BrandMark darkSrc={emptyStateLogoSrc} size={40} />}+ <h2 className={cn("font-semibold text-[var(--color-text-primary)]", variant === "dock" ? "text-lg" : "text-[22px]")}>+ {variant === "dock" ? "Ask from this view" : `Ask anything about ${repoName ?? "this codebase"}`}</h2>- <p className="text-base text-[var(--color-text-secondary)] leading-relaxed">- Explore architecture, assess risk, search code, trace- dependencies, and understand decisions. Every answer cites the- pages it read.+ <p className={cn("text-[var(--color-text-secondary)] leading-relaxed", variant === "dock" ? "text-sm" : "text-base")}>+ {variant === "dock"+ ? "Keep investigating without leaving the page. Answers use the active repository context."+ : "Explore architecture, assess risk, search code, trace dependencies, and understand decisions. Every answer cites the pages it read."}</p>{statusSlot && (<p className="font-mono text-xs text-[var(--color-text-tertiary)] tabular-nums">@@ -266,7 +265,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.map((s) => (+ {visibleSuggestions.slice(0, variant === "dock" ? 3 : undefined).map((s) => (<li key={s}><buttonclassName="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-accent-primary)]"@@ -283,7 +282,7 @@ export function ChatInterface({</ScrollArea>) : (<ScrollArea className="h-full">- <div className="px-[var(--page-pad)] py-10 space-y-10 max-w-3xl mx-auto">+ <div className={cn("mx-auto max-w-3xl", variant === "dock" ? "space-y-7 px-4 py-6" : "space-y-10 px-[var(--page-pad)] py-10")}>{messages.map((m) => (<ChatMessagekey={m.id}@@ -310,7 +309,8 @@ export function ChatInterface({interactive surface, which is what rule 1 reserves elevation for. */}<divclassName={cn(- "shrink-0 px-[var(--page-pad)] pb-5 pt-4",+ "shrink-0",+ variant === "dock" ? "px-3 pb-3 pt-3" : "px-[var(--page-pad)] pb-5 pt-4",!isEmpty && "border-t border-[var(--color-border-default)]",)}>@@ -320,45 +320,23 @@ export function ChatInterface({{sendDisabledReason}</div>)}- {showContext && context && <ChatContextIndicator context={context} />}- <div- className={cn(- "flex items-end gap-2 rounded-2xl border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-4 py-3",- sendDisabled && "opacity-60",- )}- >- <textarea- ref={textareaRef}- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- void handleSubmit();- }- }}- placeholder={composerPlaceholder}- aria-label="Chat message"- disabled={sendDisabled}- rows={1}- className="flex-1 resize-none bg-transparent text-[15px] text-[var(--color-text-primary)] placeholder:text-[var(--color-text-tertiary)] outline-none leading-6 max-h-36 overflow-y-auto"- style={{ scrollbarWidth: "none" }}+ {showContext && context && (+ <ChatContextIndicator+ context={context}+ {...(onContextRemove ? { onRemove: onContextRemove } : {})}/>- <Button- size="icon"- className="h-8 w-8 shrink-0 rounded-xl"- onClick={isStreaming ? onCancel : () => void handleSubmit()}- disabled={(!input.trim() && !isStreaming) || sendDisabled}- aria-label={isStreaming ? "Stop generation" : "Send message"}- title={isStreaming ? "Stop generation" : "Send message"}- >- {isStreaming ? (- <StopCircle className="h-4 w-4" />- ) : (- <Send className="h-4 w-4" />- )}- </Button>- </div>+ )}+ <ChatComposer+ value={input}+ onValueChange={setInput}+ onSend={onSend}+ onCancel={onCancel}+ isStreaming={isStreaming}+ placeholder={composerPlaceholder}+ disabled={sendDisabled}+ compact={variant === "dock"}+ textareaRef={textareaRef}+ />{isEmpty && (<p className={cn(MICRO_LABEL, "mt-2.5 text-center")}>Shift+Enter for newline · Enter to senddiff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.tsindex 0f16aaea3..362755407 100644--- a/packages/ui/src/chat/index.ts+++ b/packages/ui/src/chat/index.ts@@ -1,6 +1,8 @@export * from "./artifact-panel";export * from "./artifacts";export * from "./chat-interface";+export * from "./chat-composer";+export * from "./chat-dock";export * from "./chat-context";export * from "./chat-context-indicator";export * from "../shared/markdown";diff --git a/packages/web/src/app/repos/[id]/layout.tsx b/packages/web/src/app/repos/[id]/layout.tsxindex cb25200b9..c74ee6fb5 100644--- a/packages/web/src/app/repos/[id]/layout.tsx+++ b/packages/web/src/app/repos/[id]/layout.tsx@@ -5,6 +5,7 @@ import { PageTransition } from "@/components/layout/page-transition";import { ReindexHintBanner } from "@/components/layout/reindex-hint-banner";import { RepoBreadcrumb } from "@/components/layout/repo-breadcrumb";import { RepositoryChatProvider } from "@/components/chat/repository-chat-provider";+import { RepositoryChatDock } from "@/components/chat/repository-chat-dock";interface RepoLayoutProps {children: React.ReactNode;@@ -28,6 +29,7 @@ export default async function RepoLayout({ children, params }: RepoLayoutProps)<ActiveJobBanner repoId={id} /><RepoBreadcrumb repoName={repoName} docsMode={docsMode ?? "none"} /><PageTransition>{children}</PageTransition>+ <RepositoryChatDock /></RepositoryChatProvider>);}diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsxindex 37d65ba00..dc7135fb5 100644--- a/packages/web/src/components/chat/chat-interface.tsx+++ b/packages/web/src/components/chat/chat-interface.tsx@@ -37,6 +37,7 @@ export function ChatInterface({error,sendMessage,loadConversation,+ cancel,reset,pageContext,} = useRepositoryChat();@@ -97,7 +98,7 @@ export function ChatInterface({isStreaming={isStreaming}error={error}onSend={(text) => sendMessage(text, { context: pageContext })}- onCancel={reset}+ onCancel={cancel}buildCitationHref={(s) => pageHref(repoId, s.pageId)}modelSelectorSlot={<ModelSelector repoId={repoId} />}statusSlot={diff --git a/packages/web/src/components/chat/repository-chat-dock.test.tsx b/packages/web/src/components/chat/repository-chat-dock.test.tsxnew file mode 100644index 000000000..43e90e5fa--- /dev/null+++ b/packages/web/src/components/chat/repository-chat-dock.test.tsx@@ -0,0 +1,40 @@+// @vitest-environment jsdom++import React from "react";+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import {+ getRepositoryDockCollisionInset,+ REPOSITORY_GRAPH_DOCK_INSET,+ RepositoryChatDock,+} from "./repository-chat-dock";++vi.mock("./repository-chat-provider", () => ({+ useRepositoryChat: () => ({+ repoId: "r1",+ repoName: "acme",+ pageContext: { kind: "chat", label: "Chat" },+ messages: [],+ conversationId: null,+ isStreaming: false,+ error: null,+ sendMessage: vi.fn(),+ loadConversation: vi.fn(),+ reset: vi.fn(),+ }),+}));++describe("RepositoryChatDock", () => {+ it("clears the full graph control stack", () => {+ expect(REPOSITORY_GRAPH_DOCK_INSET).toBe("12.5rem");+ expect(getRepositoryDockCollisionInset("architecture")).toBe("12.5rem");+ expect(getRepositoryDockCollisionInset("graph")).toBe("12.5rem");+ expect(getRepositoryDockCollisionInset("health")).toBeUndefined();+ });++ it("does not mount duplicate chat UI on the full chat route", () => {+ const { container } = render(<RepositoryChatDock />);+ expect(container.innerHTML).toBe("");+ expect(screen.queryByLabelText("Repository chat")).toBeNull();+ });+});diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsxnew file mode 100644index 000000000..382e6b38d--- /dev/null+++ b/packages/web/src/components/chat/repository-chat-dock.tsx@@ -0,0 +1,84 @@+"use client";++import useSWR from "swr";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { ChatDock } from "@repowise-dev/ui/chat";+import { getProviders } from "@/lib/api/providers";+import { pageHref } from "@/lib/utils/page-href";+import { ModelSelector } from "./model-selector";+import { ConversationHistory } from "./conversation-history";+import { useRepositoryChat } from "./repository-chat-provider";++// Sigma's worst-case bottom-right stack is ~197px tall (layout status plus+// five controls and spacing). Keep a small measured clearance above it.+export const REPOSITORY_GRAPH_DOCK_INSET = "12.5rem";++export function getRepositoryDockCollisionInset(kind: string) {+ return kind === "architecture" || kind === "graph"+ ? REPOSITORY_GRAPH_DOCK_INSET+ : undefined;+}++export function RepositoryChatDock() {+ const chat = useRepositoryChat();++ // The full chat page already renders this controller's complete transcript.+ // Keep the dock out of both the visual and accessibility trees there.+ if (chat.pageContext.kind === "chat") return null;++ return <ConnectedRepositoryChatDock chat={chat} />;+}++type RepositoryChatValue = ReturnType<typeof useRepositoryChat>;++function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {+ const router = useRouter();+ const { data: providers } = useSWR(+ `providers:${chat.repoId}`,+ () => getProviders(chat.repoId),+ { revalidateOnFocus: false },+ );+ const anyConfigured =+ providers === undefined || providers.providers.some((provider) => provider.configured);+ const collisionInset = getRepositoryDockCollisionInset(chat.pageContext.kind);++ return (+ <ChatDock+ storageKey={`repowise:chat-dock:${chat.repoId}`}+ repoId={chat.repoId}+ repoName={chat.repoName}+ context={chat.pageContext}+ messages={chat.messages}+ isStreaming={chat.isStreaming}+ error={chat.error}+ onSend={(text, context) => chat.sendMessage(text, { context })}+ onCancel={chat.cancel}+ buildCitationHref={(source) => pageHref(chat.repoId, source.pageId)}+ onOpenFullChat={() => router.push(`/repos/${chat.repoId}/chat`)}+ {...(collisionInset ? { collisionInset } : {})}+ sendDisabled={!anyConfigured}+ sendDisabledReason={+ <span>+ No chat provider is configured. Add an API key in{" "}+ <Link+ href="/settings"+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ settings+ </Link>+ .+ </span>+ }+ modelSelectorSlot={<ModelSelector repoId={chat.repoId} />}+ historySlot={+ <ConversationHistory+ repoId={chat.repoId}+ activeConversationId={chat.conversationId}+ onSelect={chat.loadConversation}+ onNew={chat.reset}+ />+ }+ />+ );+}diff --git a/packages/web/src/components/chat/repository-chat-provider.tsx b/packages/web/src/components/chat/repository-chat-provider.tsxindex f56b4a68f..aac994ad6 100644--- a/packages/web/src/components/chat/repository-chat-provider.tsx+++ b/packages/web/src/components/chat/repository-chat-provider.tsx@@ -37,19 +37,42 @@ export function RepositoryChatProvider({() => getRepositoryChatContext(pathname, searchParams),[pathname, searchParams],);+ const {+ messages,+ conversationId,+ isStreaming,+ error,+ sendMessage,+ loadConversation,+ cancel,+ reset,+ } = chat;const value = useMemo<RepositoryChatValue>(- () => ({ repoId, repoName, pageContext, ...chat }),+ () => ({+ repoId,+ repoName,+ pageContext,+ messages,+ conversationId,+ isStreaming,+ error,+ sendMessage,+ loadConversation,+ cancel,+ reset,+ }),[repoId,repoName,pageContext,- chat.messages,- chat.conversationId,- chat.isStreaming,- chat.error,- chat.sendMessage,- chat.loadConversation,- chat.reset,+ messages,+ conversationId,+ isStreaming,+ error,+ sendMessage,+ loadConversation,+ cancel,+ reset,],);diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsxindex 29863b4e8..23c1593ec 100644--- a/packages/web/src/lib/hooks/use-chat.test.tsx+++ b/packages/web/src/lib/hooks/use-chat.test.tsx@@ -51,6 +51,23 @@ describe("useChat lifecycle", () => {expect(result.current.conversationId).toBeNull();});+ it("cancels streaming without erasing the conversation", () => {+ const { result } = renderHook(() => useChat("r1"));++ act(() => {+ void result.current.sendMessage("Explain this page");+ });+ expect(result.current.messages).toHaveLength(2);+ expect(result.current.isStreaming).toBe(true);++ act(() => result.current.cancel());++ expect(mocks.signal?.aborted).toBe(true);+ expect(result.current.messages).toHaveLength(2);+ expect(result.current.messages.at(-1)?.isStreaming).toBe(false);+ expect(result.current.isStreaming).toBe(false);+ });+it.each(["resolve", "reject"] as const)("ignores a late conversation %s from the previous repository",async (outcome) => {diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.tsindex 6e077158e..978bbe860 100644--- a/packages/web/src/lib/hooks/use-chat.ts+++ b/packages/web/src/lib/hooks/use-chat.ts@@ -249,11 +249,24 @@ export function useChat(repoId: string) {[repoId],);+ const cancel = useCallback(() => {+ abortRef.current?.abort();+ abortRef.current = null;+ setState((prev) => ({+ ...prev,+ isStreaming: false,+ messages: prev.messages.map((message) =>+ message.isStreaming ? { ...message, isStreaming: false } : message,+ ),+ }));+ }, []);+const reset = useCallback(() => {abortRef.current?.abort();+ abortRef.current = null;setState(EMPTY_CHAT_STATE);}, []);const visibleState = activeRepoRef.current === repoId ? state : EMPTY_CHAT_STATE;- return { ...visibleState, sendMessage, loadConversation, reset };+ return { ...visibleState, sendMessage, loadConversation, cancel, reset };}