Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(chat): side chat upgrades: dictation, live thinking, code blocks (#682)

Ruben Lütkee3b310f9b462
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index 07366df5c9..9c7d9b330d 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -409,6 +409,16 @@ async def _live_cli_models() -> dict[str, list[dict[str, Any]]]:
return await live_models()
+def _folder_for(surface: str, raw: str | None) -> str | None:
+ """The folder a ``surface`` session may be given; ``None`` = its default.
+
+ A plain chat touches no folder, so whatever a client still remembers (a
+ workspace that has since been deleted, say) is ignored rather than allowed
+ to refuse the chat.
+ """
+ return None if kit_for(surface).plain else _validate_cwd(raw)
+
+
def _validate_cwd(raw: str | None) -> str | None:
if raw is None:
return None
@@ -460,7 +470,7 @@ async def get_catalog(
if agent_accounts.resolve(account_id) is None:
raise HTTPException(status_code=400, detail="Unknown subscription account")
- folder = _validate_cwd(cwd)
+ folder = _folder_for(surface, cwd)
with cli_catalog_scope(
account_id=account_id,
cwd=Path(folder) if folder else None,
@@ -999,7 +1009,7 @@ def create_session(body: CreateSessionBody, request: Request) -> dict[str, Any]:
+ ", ".join(m.id for m in permission_modes(ladder))
),
)
- cwd = _validate_cwd(body.cwd)
+ cwd = _folder_for(body.surface, body.cwd)
try:
session = svc.create_session(
provider=body.provider,
@@ -1109,7 +1119,7 @@ async def patch_session(
fields["effort"] = normalize_effort(provider, body.effort)
current = svc.store.get_session(session_id)
assert current is not None
- if body.cwd is not None:
+ if body.cwd is not None and not kit_for(current.surface).plain:
fields["cwd"] = _validate_cwd(body.cwd) or svc.default_cwd(current.surface)
runner = resolve_runner(
fields.get("provider") or current.provider,
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
index cc60d903d5..4b9bc97559 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChatMarkdown, mediaKind, normalizeMediaMarkup, safeMediaUrl } from "./ChatMarkdown";
@@ -27,6 +27,18 @@ describe("chat visual fences", () => {
expect(screen.getByTestId("inline-html-frame").getAttribute("srcdoc")).toContain(code);
});
+ it("gives fenced code its language and a copy button", async () => {
+ const writeText = vi.fn(async () => undefined);
+ Object.assign(navigator, { clipboard: { writeText } });
+ render(<ChatMarkdown text={["Here:", "", "```python", "print('hi')", "```"].join("\n")} />);
+
+ expect(screen.getByText("python")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Copy code" }));
+
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith("print('hi')"));
+ expect(await screen.findByRole("button", { name: "Code copied" })).toBeTruthy();
+ });
+
it("keeps JSON results and explicit text as code", () => {
const { container } = render(<ChatMarkdown text={'```json\n{"ok":true,"artifacts":[]}\n```\n\n```text\n<svg><rect/></svg>\n```'} />);
expect(container.querySelectorAll("pre")).toHaveLength(2);
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
index 9dea2b76e0..7405518f85 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
@@ -9,6 +9,7 @@ import { openLocalPath } from "@/lib/openLocalPath";
import { readFence, visualFenceLanguage } from "@/lib/visualFence";
import { chatLinkAction, chatUrlTransform, localPathFromChatHref } from "./chatLinks";
import { parseToolResult, ToolResultCard } from "./ToolResultCard";
+import { CodeBlock } from "@/components/docs/CodeBlock";
import * as Dialog from "@radix-ui/react-dialog";
const RenderedFence = lazy(() => import("@/components/outputs/RenderedFence").then(module => ({ default: module.RenderedFence })));
@@ -181,6 +182,8 @@ const MARKDOWN_COMPONENTS: Components = {
}
const language = visualFenceLanguage(fence.language, fence.code);
if (language) return <Suspense fallback={<pre>{children}</pre>}><RenderedFence language={language} code={fence.code} /></Suspense>;
+ // Any other fenced code: its language on top, a copy button, highlighting.
+ return <CodeBlock language={fence.language} code={fence.code} dense />;
}
return <pre {...props}>{children}</pre>;
},
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx
index 863a586d3a..d43e95a455 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx
@@ -1,6 +1,7 @@
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { TimelineItem, TurnBlock, TurnItem, TurnStatus } from "@/components/agentchat/reduce";
+import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
import { SideChatTab } from "./SideChatTab";
import { useSideChatStore } from "./sideChatStore";
@@ -48,6 +49,7 @@ function seed(items: TimelineItem[], extra: Record<string, unknown> = {}) {
beforeEach(() => {
localStorage.clear();
+ useEventStore.setState({ dictating: false });
useIdeChatStore.setState({ workspace: null });
});
@@ -88,6 +90,19 @@ describe("SideChatTab", () => {
expect(input.value).toBe("");
});
+ it("stops an answer that is still coming on Escape", () => {
+ const { cancel } = seed([USER, turn([], "running")]);
+ render(<SideChatTab />);
+ fireEvent.keyDown(screen.getByTestId("side-chat-input"), { key: "Escape" });
+ expect(cancel).toHaveBeenCalledWith("side-chat-escape");
+ });
+
+ it("puts the cursor in the box when the chat opens", () => {
+ seed([]);
+ render(<SideChatTab />);
+ expect(document.activeElement).toBe(screen.getByTestId("side-chat-input"));
+ });
+
it("puts a message that never left back into the box", async () => {
seed([], { send: vi.fn(async () => "failed" as const) });
render(<SideChatTab />);
@@ -106,7 +121,7 @@ describe("SideChatTab", () => {
expect(screen.getByText("Make the login form accessible.")).toBeTruthy();
// An answer offers Copy and nothing that reaches into the IDE.
expect(screen.queryByTestId("side-chat-send-to-terminal")).toBeNull();
- const fold = screen.getByTestId("thread-worked-for");
+ const fold = screen.getByTestId("chat-thought-toggle");
expect(fold.textContent).toContain("Thought for 3.0s");
// The thought itself is one click away, not in the way.
expect(screen.queryByText("The person wants a goal, not steps.")).toBeNull();
@@ -118,7 +133,7 @@ describe("SideChatTab", () => {
const { cancel } = seed([USER, turn([], "running")]);
render(<SideChatTab />);
- expect(screen.getByTestId("thread-working").textContent).toContain("Thinking for");
+ expect(screen.getByRole("status").textContent).toContain("Thinking");
fireEvent.click(screen.getByTestId("side-chat-stop"));
expect(cancel).toHaveBeenCalled();
});
@@ -135,4 +150,31 @@ describe("SideChatTab", () => {
fireEvent.change(screen.getByTestId("side-chat-input"), { target: { value: "next question" } });
expect(screen.getByTestId("side-chat-stop")).toBeTruthy();
});
+
+ it("offers the dictation mic beside Send", () => {
+ seed([]);
+ render(<SideChatTab />);
+ expect(screen.getByRole("button", { name: "Dictate" })).toBeTruthy();
+ });
+
+ it("puts dictated words into the box, after what was typed", () => {
+ seed([]);
+ render(<SideChatTab />);
+ const input = screen.getByTestId("side-chat-input") as HTMLTextAreaElement;
+ fireEvent.change(input, { target: { value: "Question:" } });
+
+ act(() => {
+ const seq = useEventStore.getState().dictationCommitSeq + 1;
+ useEventStore.setState({ dictationCommitText: "why is the sky blue", dictationCommitSeq: seq });
+ });
+
+ expect(input.value).toBe("Question: why is the sky blue");
+ });
+
+ it("can send while dictating, before anything is in the box", () => {
+ seed([]);
+ useEventStore.setState({ dictating: true });
+ render(<SideChatTab />);
+ expect((screen.getByTestId("side-chat-send") as HTMLButtonElement).disabled).toBe(false);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx
index 9039dfa0eb..5a55588860 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx
@@ -3,6 +3,8 @@ import { ArrowUp, History, Square, SquarePen, Trash2 } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { joinProviderOptions } from "@/store/agentChat";
+import { DictationButton } from "@/components/agentchat/DictationButton";
+import { useComposerDictation } from "@/components/agentchat/useComposerDictation";
import { AgentModelPicker, EffortPicker } from "@/components/agentic/threads/ThreadPickers";
import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
import { ThreadTimeline } from "@/components/agentic/threads/ThreadTimeline";
@@ -38,10 +40,10 @@ const ICON_BTN =
/**
* The side panel's Chat surface: a plain AI chat with the model you pick.
*
- * Ask anything, read the answer. It is not a coding agent and knows nothing
- * about the workspace: no seat on its surface has tools, and the model is told
- * only how to answer. Answers stream, and a model's thinking folds behind one
- * line once it is done.
+ * Ask anything, typed or dictated, and read the answer. It is not a coding
+ * agent and knows nothing about the workspace: no seat on its surface has
+ * tools, and the model is told only how to answer. Answers stream, and a
+ * model's thinking folds behind one line once it is done.
*/
export function SideChatTab() {
const t = useT();
@@ -66,6 +68,15 @@ export function SideChatTab() {
setMessageState(value);
persistMessage(value);
}, []);
+ // Dictation appends to the box as it is when the words land, not as it was.
+ const messageRef = useRef(message);
+ messageRef.current = message;
+ const setDictated = useCallback((next: string | ((current: string) => string)) => {
+ setMessage(typeof next === "function" ? next(messageRef.current) : next);
+ }, [setMessage]);
+ // Send during a dictation sends once the transcript is in the box.
+ const sendRef = useRef<() => void>(() => undefined);
+ const dictation = useComposerDictation(setDictated, () => sendRef.current());
useEffect(() => {
const store = useSideChatStore.getState();
@@ -89,19 +100,30 @@ export function SideChatTab() {
);
const provider = providers.find((option) => option.id === draft.provider) ?? null;
const running = busy || timeline.items.some((item) => item.type === "turn" && item.status === "running");
- const canSend = message.trim().length > 0 && !running && Boolean(provider?.connected);
+ const canSend = (message.trim().length > 0 || dictation.dictating) && !running && Boolean(provider?.connected);
const started = timeline.items.length > 0;
const send = useCallback(async () => {
+ if (dictation.dictating) {
+ dictation.stopAndSend();
+ return;
+ }
const text = message.trim();
if (!text || running) return;
setMessage("");
const outcome = await useSideChatStore.getState().send(text);
// A message that never left comes back into the box.
if (outcome === "failed") setMessage(text);
- }, [message, running, setMessage]);
+ }, [dictation, message, running, setMessage]);
+ sendRef.current = () => void send();
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ // Escape stops an answer that is still coming.
+ if (event.key === "Escape" && running) {
+ event.preventDefault();
+ void useSideChatStore.getState().cancel("side-chat-escape");
+ return;
+ }
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
event.preventDefault();
void send();
@@ -160,7 +182,7 @@ export function SideChatTab() {
<div className="shrink-0 px-3 pb-3 pt-1">
{error && <p role="alert" data-testid="side-chat-error" className="mb-2 px-1 text-xs text-destructive">{error}</p>}
<div className="overflow-hidden rounded-3xl border border-border bg-card shadow-[0_8px_24px_-12px_rgb(var(--scrim-rgb)/0.5)] transition-colors focus-within:border-border-strong">
- <textarea ref={input} value={message} rows={2}
+ <textarea ref={input} value={message} rows={2} autoFocus
onChange={(event) => setMessage(event.target.value)} onKeyDown={onKeyDown}
aria-label={t("ide_side_panel.chat.input_aria")} placeholder={t("ide_side_panel.chat.placeholder")}
data-testid="side-chat-input"
@@ -173,6 +195,9 @@ export function SideChatTab() {
<EffortPicker provider={provider} draft={draft} liveModels={liveModels} separated
onPick={(effort) => void useSideChatStore.getState().setDraft({ effort })} />
</div>
+ <div className="flex shrink-0 items-center gap-1.5">
+ <DictationButton dictating={dictation.dictating} onToggle={dictation.toggle}
+ startLabel={t("chats_view.dictation_start")} stopLabel={t("chats_view.dictation_stop")} shape="round" />
{running
? <button type="button" aria-label={t("ide_side_panel.chat.stop")} title={t("ide_side_panel.chat.stop")} data-testid="side-chat-stop"
onClick={() => void useSideChatStore.getState().cancel("side-chat-stop-button")}
@@ -188,6 +213,7 @@ export function SideChatTab() {
)}>
<ArrowUp className="h-4 w-4" />
</button>}
+ </div>
</div>
</div>
</div>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ChatThought.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ChatThought.test.tsx
new file mode 100644
index 0000000000..f278bdddd5
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ChatThought.test.tsx
@@ -0,0 +1,77 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ReasoningBlock, TurnBlock, TurnItem, TurnStatus } from "@/components/agentchat/reduce";
+import { ThreadTimeline } from "./ThreadTimeline";
+
+function turn(blocks: TurnBlock[], status: TurnStatus = "done"): TurnItem {
+ return {
+ type: "turn", id: "t1", provider: "fake", model: "", effort: "", runner: "api", status, blocks,
+ startedMs: Date.now(), durationMs: status === "running" ? null : 9000, usage: null, liveUsage: null, costUsd: null, error: null,
+ };
+}
+
+function thought(id: string, text: string, over: Partial<ReasoningBlock> = {}): ReasoningBlock {
+ return { kind: "reasoning", id, text, durationMs: 2000, live: false, startedMs: Date.now(), ...over };
+}
+
+const answer: TurnBlock = { kind: "text", id: "a1", text: "Rayleigh scattering." };
+const show = (item: TurnItem) => render(<ThreadTimeline items={[item]} sessionId="s1" bottomInset={0} tone="chat" />);
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("a chat's thinking", () => {
+ it("streams the thought under a live Thinking line until the answer begins", () => {
+ show(turn([thought("r1", "Short wavelengths scatter more.", { live: true, durationMs: null })], "running"));
+
+ expect(screen.getByRole("status").textContent).toContain("Thinking");
+ expect(screen.getByTestId("chat-thought").getAttribute("data-live")).toBe("true");
+ expect(screen.getByTestId("chat-thought-stream").textContent).toContain("Short wavelengths scatter more.");
+ // One live indicator, not the coding thread's "Working for" line beside it.
+ expect(screen.queryByTestId("thread-working")).toBeNull();
+ });
+
+ it("says it is thinking before any thought arrives", () => {
+ show(turn([], "running"));
+ expect(screen.getByRole("status").textContent).toContain("Thinking");
+ expect(screen.queryByTestId("chat-thought-stream")).toBeNull();
+ });
+
+ it("counts the time while it thinks", () => {
+ vi.useFakeTimers();
+ const started = Date.now();
+ show(turn([thought("r1", "", { live: true, durationMs: null, startedMs: started })], "running"));
+ act(() => { vi.advanceTimersByTime(3000); });
+ expect(screen.getByRole("status").textContent).toContain("3.0s");
+ });
+
+ it("folds into one line once the answer streams, and opens on a click", () => {
+ show(turn([thought("r1", "First idea."), thought("r2", "Second idea.", { durationMs: 1500 }), answer]));
+
+ const toggle = screen.getByTestId("chat-thought-toggle");
+ // Two blocks read as one thought, timed by the thinking alone.
+ expect(toggle.textContent).toBe("Thought for 3.5s");
+ expect(screen.queryByText("First idea.")).toBeNull();
+ expect(screen.getByText("Rayleigh scattering.")).toBeTruthy();
+
+ fireEvent.click(toggle);
+ const body = screen.getByTestId("chat-thought-body").textContent ?? "";
+ expect(body).toContain("First idea.");
+ expect(body).toContain("Second idea.");
+ });
+
+ it("shows nothing for a finished answer that had no thinking", () => {
+ show(turn([answer]));
+ expect(screen.queryByTestId("chat-thought")).toBeNull();
+ expect(screen.queryByTestId("thread-turn-closing")?.textContent).not.toContain("Worked");
+ });
+
+ it("keeps a redacted thought as a plain line that does not open", () => {
+ show(turn([thought("r1", ""), answer]));
+ const toggle = screen.getByTestId("chat-thought-toggle") as HTMLButtonElement;
+ expect(toggle.textContent).toBe("Thought for 2.0s");
+ expect(toggle.disabled).toBe(true);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ChatThought.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ChatThought.tsx
new file mode 100644
index 0000000000..daef9208cf
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ChatThought.tsx
@@ -0,0 +1,89 @@
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { ChevronRight } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";
+import type { ReasoningBlock, TurnItem } from "@/components/agentchat/reduce";
+import { traceDuration } from "@/components/agentchat/traceEntries";
+
+/** The thinking as it reads: a quiet column under a hairline, a step below the answer. */
+const BODY = cn(
+ "prose prose-sm max-w-none border-l-2 border-border pl-3 text-sm leading-6 text-muted-foreground dark:prose-invert [overflow-wrap:anywhere]",
+ "prose-p:my-1.5 prose-p:text-muted-foreground prose-li:text-muted-foreground prose-strong:text-foreground-secondary",
+ "prose-headings:my-1.5 prose-headings:text-sm prose-headings:font-medium prose-headings:text-foreground-secondary prose-pre:text-xs",
+);
+
+/** Time since `since`, counted in place: the turn never re-renders to tick. */
+function Ticker({ since }: { since: number }) {
+ const ref = useRef<HTMLSpanElement | null>(null);
+ useEffect(() => {
+ const tick = () => {
+ if (ref.current) ref.current.textContent = traceDuration(Math.max(0, Date.now() - since));
+ };
+ tick();
+ const timer = window.setInterval(tick, 1000);
+ return () => window.clearInterval(timer);
+ }, [since]);
+ return <span ref={ref} className="text-xs tabular-nums text-faint-foreground" />;
+}
+
+/**
+ * A chat answer's thinking, as one piece.
+ *
+ * While the model thinks, a shimmering "Thinking" with its clock, and under
+ * it the thought itself as it streams: the newest lines in view, the older
+ * ones fading out at the top. Once the answer starts, all of it folds into
+ * one line, "Thought for 4s", that opens the whole text on a click. Several
+ * reasoning blocks of one turn read as a single thought, never as a stack of
+ * "Thinking" lines.
+ */
+export function ChatThought({ turn, answering }: { turn: TurnItem; answering: boolean }) {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const [clipped, setClipped] = useState(false);
+ const stream = useRef<HTMLDivElement | null>(null);
+ const blocks = useMemo(
+ () => turn.blocks.filter((block): block is ReasoningBlock => block.kind === "reasoning"),
+ [turn.blocks],
+ );
+ const text = useMemo(() => blocks.map((block) => block.text.trim()).filter(Boolean).join("\n\n"), [blocks]);
+ // Thinking lasts until the answer begins; a model that never says what it
+ // thinks still shows that it is at work.
+ const live = turn.status === "running" && (!answering || blocks.some((block) => block.live));
+ const thoughtMs = blocks.reduce((sum, block) => sum + (block.durationMs ?? 0), 0);
+
+ // The newest words stay in view while they arrive.
+ useLayoutEffect(() => {
+ const box = stream.current;
+ if (!box || !live) return;
+ box.scrollTop = box.scrollHeight;
+ setClipped(box.scrollHeight > box.clientHeight + 1);
+ }, [text, live]);
+
+ if (!live && blocks.length === 0) return null;
+
+ if (live) {
+ return <div data-testid="chat-thought" data-live="true" className="min-w-0 space-y-1.5">
+ <div role="status" className="flex h-7 items-center gap-2 text-sm">
+ <span className="thinking-shimmer font-medium">{t("thread_turn.thinking")}</span>
+ <Ticker since={blocks[0]?.startedMs ?? turn.startedMs} />
+ </div>
+ {text && <div ref={stream} data-testid="chat-thought-stream"
+ className={cn("max-h-32 overflow-hidden", clipped && "[mask-image:linear-gradient(to_bottom,transparent,black_3rem)]")}>
+ <div className={BODY}><ChatMarkdown text={text} /></div>
+ </div>}
+ </div>;
+ }
+
+ const label = thoughtMs > 0 ? fill(t("work_trace.thought_for"), { duration: traceDuration(thoughtMs) }) : t("work_trace.thought");
+ return <div data-testid="chat-thought" className="min-w-0">
+ <button type="button" aria-expanded={open} disabled={!text} onClick={() => setOpen((value) => !value)} data-testid="chat-thought-toggle"
+ className="inline-flex h-7 items-center gap-1 rounded-md text-sm text-muted-foreground transition-colors hover:text-foreground disabled:cursor-default disabled:hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <span className="tabular-nums">{label}</span>
+ {text && <ChevronRight aria-hidden className={cn("h-3.5 w-3.5 transition-transform duration-150", open && "rotate-90")} />}
+ </button>
+ {open && text && <div data-testid="chat-thought-body" className={cn(BODY, "mb-1 mt-1 max-h-96 overflow-y-auto scrollbar-jarvis")}>
+ <ChatMarkdown text={text} />
+ </div>}
+ </div>;
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
index a131743fae..6a52be7830 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
@@ -12,6 +12,7 @@ import { localeForUiLanguage } from "@/components/runs/format";
import type { ApprovalDecision } from "@/lib/agentChatApi";
import { robustCopy } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
+import { ChatThought } from "./ChatThought";
import { buildThreadRows, isFailed, thoughtGist, type ThreadRow, type WorkGroup, type WorkItem } from "./threadWork";
import { SubagentCard } from "./ThreadSubagents";
import { listSubagents } from "./subagents";
@@ -609,9 +610,9 @@ export function foldFinished(rows: ThreadRow[]): { work: ThreadRow[]; answer: Th
}
/** "Working for 12s" with the ticking clock in place of the duration. */
-function WorkingFor({ since, labelKey = "thread_turn.working_for" }: { since: number; labelKey?: string }) {
+function WorkingFor({ since }: { since: number }) {
const t = useT();
- const [before, after = ""] = t(labelKey).split("{duration}");
+ const [before, after = ""] = t("thread_turn.working_for").split("{duration}");
return <>{before}<Elapsed since={since} />{after}</>;
}
@@ -633,10 +634,11 @@ export interface ThreadTurnProps {
/** A quiet note on a finished turn's closing line: tokens, cost. */
receipt?: ReactNode;
/**
- * How the turn's status lines read. A coding thread counts work ("Working
- * for 12s", "Worked for 40s"); a plain chat has thoughts and an answer, so
- * it says "Thinking for 3s" until its first line shows and "Thought for
- * 3s" on the fold, and puts no duration under an answer.
+ * How the turn reads. A coding thread counts its work ("Working for 12s",
+ * "Worked for 40s"). A plain chat has a thought and an answer: the thought
+ * streams under a shimmering "Thinking" and folds into "Thought for 3s"
+ * once the answer begins (`ChatThought`), and no duration sits under the
+ * answer.
*/
tone?: "work" | "chat";
}
@@ -674,18 +676,12 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
const duration = turn.durationMs != null ? traceDuration(turn.durationMs) : "";
const timed = (key: string) => duration ? fill(t(`thread_turn.${key}_after`), { duration }) : t(`thread_turn.${key}`);
const workedFor = duration ? fill(t("thread_turn.worked_for"), { duration }) : "";
- const chat = tone === "chat";
- // A chat's fold holds thoughts alone, so it is timed by the thinking, not the whole turn.
- const thoughtMs = chat ? turn.blocks.reduce((sum, block) => sum + (block.kind === "reasoning" ? block.durationMs ?? 0 : 0), 0) : 0;
- const thoughtFor = thoughtMs > 0 ? fill(t("work_trace.thought_for"), { duration: traceDuration(thoughtMs) }) : t("work_trace.thought");
- // A chat's rows are its sign of life; the ticking line only covers the wait before the first one.
- const quiet = chat && rows.length > 0;
const foldLabel = turn.status === "cancelled" ? timed("stopped")
: turn.status === "error" ? timed("failed")
- : chat ? thoughtFor : workedFor || t("thread_turn.worked");
+ : workedFor || t("thread_turn.worked");
const closing = turn.status === "cancelled" ? timed("stopped")
: turn.status === "error" ? timed("failed")
- : answer ? (chat ? "" : workedFor) : timed("no_answer");
+ : answer ? workedFor : timed("no_answer");
const renderRow = (row: ThreadRow) => {
if (row.kind === "work") return <WorkGroupView key={row.id} group={row} running={running} />;
if (row.kind === "thought") return <ThoughtView key={row.id} text={row.text} />;
@@ -701,6 +697,24 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
const pending = pendingLabel(row.block, t);
return pending ? <WorkRow key={row.id} icon={pending.icon} label={pending.text} live /> : null;
};
+ if (tone === "chat") {
+ // A plain chat: its thought, its answer, and a quiet closing line.
+ const textRows = rows.filter((row) => row.kind === "text");
+ const ending = turn.status === "cancelled" ? timed("stopped")
+ : turn.status === "error" ? timed("failed")
+ : !answer ? timed("no_answer") : "";
+ return <CallMedia.Provider value={pictures.byCall}><div className="min-w-0 space-y-1.5" data-testid="thread-turn" data-status={turn.status}>
+ <ChatThought turn={turn} answering={textRows.length > 0} />
+ {textRows.map(renderRow)}
+ {!running && <>
+ {turn.status === "error" && turn.error && <p role="alert" className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">{turn.error}</p>}
+ <div className="flex items-center gap-1.5 pt-1 text-xs text-muted-foreground" data-testid="thread-turn-closing">
+ {ending && <span>{ending}</span>}
+ {answer && <CopyButton text={answer} label={t("thread_turn.copy_answer")} />}
+ </div>
+ </>}
+ </div></CallMedia.Provider>;
+ }
const extraNodes = extraRows.map((extra) => <div key={`extra:${extra.key}`} className="min-w-0">{extra.node}</div>);
// A running turn's streaming answer is its tail; extra steps go above it.
const shown = folded ? tail : rows;
@@ -726,8 +740,8 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
{!folded && extraNodes}
{shown.slice(extraAt).map(renderRow)}
{running
- ? !quiet && <div className="flex h-6 min-w-0 items-center px-1 text-sm leading-relaxed text-muted-foreground" data-testid="thread-working">
- <span className="whitespace-nowrap"><WorkingFor since={turn.startedMs} labelKey={chat ? "work_trace.thinking_for" : undefined} />
+ ? <div className="flex h-6 min-w-0 items-center px-1 text-sm leading-relaxed text-muted-foreground" data-testid="thread-working">
+ <span className="whitespace-nowrap"><WorkingFor since={turn.startedMs} />
{agentsWorking > 0 && <> · {fill(t(`thread_turn.subagents_working_${plural(lang, agentsWorking)}`), { count: agentsWorking })}</>}</span>
</div>
: <>
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx
index ac0c945e60..a3e035a531 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/team/TeamThreadView.test.tsx
@@ -155,7 +155,8 @@ it("unfolds a contribution of the story in place", async () => {
fireEvent.click(within(first).getByRole("button"));
const body = within(first).getByTestId("team-entry-body");
expect(within(body).getByText("backoff").tagName).toBe("STRONG");
- fireEvent.click(within(first).getByRole("button"));
+ // The open entry's code block brings its own Copy button; fold by the entry's toggle.
+ fireEvent.click(within(first).getByRole("button", { expanded: true }));
expect(within(first).queryByTestId("team-entry-body")).toBeNull();
});
diff --git a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx
index 7d4bb4ad97..d7bbaf4d2a 100644
--- a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx
+++ b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx
@@ -84,9 +84,11 @@ interface CodeBlockProps {
* header bars never stack.
*/
chrome?: boolean;
+ /** Less air around the frame: a chat answer, not a long guide. */
+ dense?: boolean;
}
-export function CodeBlock({ language, code, chrome = true }: CodeBlockProps) {
+export function CodeBlock({ language, code, chrome = true, dense = false }: CodeBlockProps) {
const t = useT();
const [html, setHtml] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
@@ -145,7 +147,8 @@ export function CodeBlock({ language, code, chrome = true }: CodeBlockProps) {
<div
className={cn(
"not-prose group relative overflow-hidden",
- chrome && "my-6 rounded-lg border border-border bg-card",
+ chrome && "rounded-lg border border-border bg-card",
+ chrome && (dense ? "my-3" : "my-6"),
)}
>
{chrome && (
diff --git a/tests/unit/agent_chat/test_side_chat.py b/tests/unit/agent_chat/test_side_chat.py
index f2146c5848..584d02840f 100644
--- a/tests/unit/agent_chat/test_side_chat.py
+++ b/tests/unit/agent_chat/test_side_chat.py
@@ -220,3 +220,45 @@ async def test_the_chat_is_told_how_to_answer_and_nothing_about_a_workspace(
assert "no tools in this chat" in prompt
assert str(tmp_path) not in prompt and "src" not in prompt
assert prompt == await side_chat.system_prompt(SimpleNamespace(cwd=""), "other", "Testo")
+
+
+def test_a_plain_chat_ignores_a_folder_that_no_longer_exists(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A client that still remembers a deleted folder must not lose the chat."""
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from jarvis.ui.web.agent_chat_routes import router
+
+ store = AgentChatStore(":memory:")
+ try:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.agent_chat = AgentChatService(store, default_cwd=lambda: str(tmp_path))
+ client = TestClient(app)
+ gone = str(tmp_path / "deleted-worktree")
+
+ created = client.post(
+ "/api/agent-chat/sessions",
+ json={"provider": "openai", "surface": "side", "cwd": gone},
+ )
+ assert created.status_code == 201, created.text
+ session_id = created.json()["session_id"]
+ assert created.json()["cwd"] != gone
+
+ patched = client.patch(f"/api/agent-chat/sessions/{session_id}", json={"cwd": gone})
+ assert patched.status_code == 200, patched.text
+ assert patched.json()["cwd"] != gone
+
+ catalog = client.get("/api/agent-chat/catalog", params={"surface": "side", "cwd": gone})
+ assert catalog.status_code == 200, catalog.text
+
+ # Every other surface still refuses a folder that is not there.
+ refused = client.post(
+ "/api/agent-chat/sessions",
+ json={"provider": "openai", "surface": "agent", "cwd": gone},
+ )
+ assert refused.status_code == 400
+ finally:
+ store.close()