From 98a3105ddfd6ac39b1e04973ce58a82190ad85c1 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:43:01 +0200 Subject: [PATCH] fix(chat): round-1 bug-hunt fixes, minus the superseded skip-notice hunk (rework of #299) --- components/MessageView.test.mjs | 39 ++++++++++++++++++++ components/MessageView.tsx | 11 +++++- components/SubagentTranscriptDialog.test.mjs | 12 +++++- components/SubagentTranscriptDialog.tsx | 7 +++- hooks/useAgentSession.rpc.test.mjs | 22 +++++++++++ hooks/useAgentSession.ts | 6 ++- lib/assistant-response.test.mjs | 39 ++++++++++++++++++++ lib/assistant-response.ts | 17 +++++++++ 8 files changed, 146 insertions(+), 7 deletions(-) create mode 100644 lib/assistant-response.test.mjs diff --git a/components/MessageView.test.mjs b/components/MessageView.test.mjs index 8e07bb444..11e7fd738 100644 --- a/components/MessageView.test.mjs +++ b/components/MessageView.test.mjs @@ -1431,3 +1431,42 @@ test("a successful shell card exposes its outcome in its accessible name", () => })); assert.ok(view.getByRole("button", { name: /true.*succeeded/i })); }); + +test("user-bubble overflow toggle appears when a late-loading image pushes past the cap", (t) => { + // Layout stub: the bubble fits its text at first; a loaded image grows + // its scroll height past the 300px cap without resizing the capped box, + // so the ResizeObserver never fires and only an image-load re-measure + // can reveal the overflow. + const originalResizeObserver = globalThis.ResizeObserver; + globalThis.ResizeObserver = class { + constructor(callback) { this.callback = callback; } + observe() {} + disconnect() {} + }; + const proto = window.HTMLElement.prototype; + const scrollHeight = Object.getOwnPropertyDescriptor(proto, "scrollHeight"); + const clientHeight = Object.getOwnPropertyDescriptor(proto, "clientHeight"); + let grown = false; + Object.defineProperty(proto, "scrollHeight", { configurable: true, get() { return grown ? 900 : 300; } }); + Object.defineProperty(proto, "clientHeight", { configurable: true, get() { return 300; } }); + t.after(() => { + globalThis.ResizeObserver = originalResizeObserver; + for (const [name, descriptor] of [["scrollHeight", scrollHeight], ["clientHeight", clientHeight]]) { + if (descriptor) Object.defineProperty(proto, name, descriptor); + else delete proto[name]; + } + }); + + const view = render(React.createElement(MessageView, { + message: { + role: "user", + content: [{ type: "image", data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", mimeType: "image/png" }], + }, + })); + assert.equal(view.queryByRole("button", { name: "Show full input" }), null); + const img = view.container.querySelector("img"); + assert.ok(img, "user-bubble image must render"); + grown = true; + fireEvent.load(img); + assert.ok(view.getByRole("button", { name: "Show full input" }), "image load must re-measure overflow and reveal the toggle"); +}); diff --git a/components/MessageView.tsx b/components/MessageView.tsx index 2ac5e7d89..d889b49b3 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -384,11 +384,17 @@ function UserMessageView({ message, cwd, onOpenFile, sessionId, entryId, onFork, typeof message.content === "string" ? [] : message.content.filter((b): b is ImageContent => b.type === "image"); + // Hoisted so bubble images can re-trigger it on load: image loading grows + // the bubble's scrollHeight without resizing the capped box, so the + // ResizeObserver below never fires for late-loading images. + const updateOverflow = useCallback(() => { + const element = bodyRef.current; + if (element) setHasOverflow(isMessageOverflowing(element)); + }, []); useLayoutEffect(() => { const element = bodyRef.current; if (!element) return; const observedElement = element; - const updateOverflow = () => setHasOverflow(isMessageOverflowing(observedElement)); updateOverflow(); observedElement.addEventListener("scroll", updateOverflow, { passive: true }); const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(updateOverflow) : null; @@ -397,7 +403,7 @@ function UserMessageView({ message, cwd, onOpenFile, sessionId, entryId, onFork, observedElement.removeEventListener("scroll", updateOverflow); observer?.disconnect(); }; - }, [content, imageBlocks.length]); + }, [content, imageBlocks.length, updateOverflow]); const time = formatTime(message.timestamp, locale); const canFork = !!entryId && !!onFork; @@ -445,6 +451,7 @@ function UserMessageView({ message, cwd, onOpenFile, sessionId, entryId, onFork, key={i} src={src} alt="" + onLoad={updateOverflow} style={{ maxWidth: 240, maxHeight: 240, borderRadius: 6, objectFit: "contain", display: "block", border: "1px solid color-mix(in srgb, var(--accent) 18%, transparent)" }} /> ); diff --git a/components/SubagentTranscriptDialog.test.mjs b/components/SubagentTranscriptDialog.test.mjs index 63891ab66..3c1ace16a 100644 --- a/components/SubagentTranscriptDialog.test.mjs +++ b/components/SubagentTranscriptDialog.test.mjs @@ -13,7 +13,7 @@ mock.module("@/lib/agent-client", () => ({ }, })); const { cleanup, fireEvent, render, waitFor } = await import("@testing-library/react/pure.js"); -const { TaskBlock, CompletionBlock, SubagentDetails, SubagentTranscriptDialog } = await import("./SubagentTranscriptDialog.tsx"); +const { TaskBlock, CompletionBlock, SubagentDetails, SubagentTranscriptDialog, SubagentTranscriptRow } = await import("./SubagentTranscriptDialog.tsx"); const originalFetch = globalThis.fetch; afterEach(() => { @@ -215,3 +215,13 @@ test("refreshes an open transcript while completion metadata is stalled", async view.rerender(React.createElement(SubagentTranscriptDialog, props(1))); await waitFor(() => assert.equal(pageRequests, 2), { timeout: 2_000 }); }); + +test("transcript rows cap tool-call input at the same 400-char budget as text", () => { + const big = "x".repeat(5000); + const html = renderToStaticMarkup(React.createElement(SubagentTranscriptRow, { + message: { role: "assistant", content: [{ type: "toolCall", toolName: "edit", input: { patch: big } }] }, + })); + assert.match(html, /edit/); + assert.ok(html.length < 1000, `tool-call row must not render unbounded input JSON (got ${html.length} chars)`); + assert.doesNotMatch(html, new RegExp(`x{1000}`)); +}); diff --git a/components/SubagentTranscriptDialog.tsx b/components/SubagentTranscriptDialog.tsx index c3fd291db..b1a708613 100644 --- a/components/SubagentTranscriptDialog.tsx +++ b/components/SubagentTranscriptDialog.tsx @@ -23,7 +23,7 @@ interface SubagentMessagesPage { /** Compact, defensive row for one raw transcript message (content may be a * string, a block array, or absent — legacy pi / omp RPC shapes). */ -function SubagentTranscriptRow({ message }: { message: AgentMessage }) { +export function SubagentTranscriptRow({ message }: { message: AgentMessage }) { const label = message.role === "user" ? "U" : message.role === "assistant" ? "A" : "R"; const labelColor = message.role === "user" ? "var(--accent)" : message.role === "assistant" ? "var(--text-muted)" : "var(--text-dim)"; const rawContent = (message as ToolResultMessage).content; @@ -56,7 +56,10 @@ function SubagentTranscriptRow({ message }: { message: AgentMessage }) { ? rawContent.map((block, i) => (
{block && typeof block === "object" && (block as { type?: unknown }).type === "toolCall" - ? `→ ${(block as { toolName?: unknown }).toolName ?? "tool"} ${JSON.stringify((block as { input?: unknown }).input ?? {})}` + // Cap the input JSON at the same 400-char budget as plain + // text rows: a big file write/edit must not freeze the + // dialog with one unbounded row. + ? `→ ${(block as { toolName?: unknown }).toolName ?? "tool"} ${JSON.stringify((block as { input?: unknown }).input ?? {}).slice(0, 400)}` : block && typeof block === "object" && (block as { type?: unknown }).type === "text" ? ((block as { text?: unknown }).text as string) ?? "" : ""} diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index efce900b5..8e23c8055 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -1557,6 +1557,28 @@ test("a finished reply stays on screen until its saved copy replaces it", async assert.equal(w.latest.streamState.streamingMessage, null, "the held reply gives way to its saved copy"); }); +test("a thinking-only finished reply stays on screen until its saved copy replaces it", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "loaded question")]); + const { w, es } = await startRun("s1", "hello agent"); + world.agents.set("s1", { running: true, state: { isStreaming: true } }); + const reply = { ...assistantMsg("a1", ""), content: [{ type: "thinking", thinking: "Let me think through the options." }], timestamp: 43 }; + await act(async () => { es.emit({ type: "agent_start" }); await Promise.resolve(); }); + await act(async () => { es.emit({ type: "message_update", message: reply }); await Promise.resolve(); }); + await settle(90); + // Hold the catch-up read the way the text-reply hold test does, so the + // saved copy cannot land before the hold itself is observed. + saveSession("s1", [userMsg("u0", "loaded question"), userMsg("u1", "hello agent")]); + const releaseSync = holdNextSync("s1", syncSnapshot("s1", liveSnapshot("s1", 99, null))); + await act(async () => { es.emit({ type: "message_end", message: reply }); await Promise.resolve(); }); + // Like a text reply, a thinking row the user was watching must be held, + // not unmounted before the catch-up reload delivers the saved copy. + assert.equal(w.latest.streamState.streamingMessage?.content?.[0]?.thinking, "Let me think through the options."); + await act(async () => { releaseSync(); }); + await settle(); + assert.equal(w.latest.streamState.streamingMessage?.content?.[0]?.thinking, "Let me think through the options.", "a read without the saved reply keeps it on screen"); +}); + test("provider error on the assistant message is shown instead of ending silently", async () => { resetWorld(); primeSession("s1", [userMsg("u0", "q")]); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index 0d3a9ed84..77955e97a 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -21,7 +21,7 @@ import type { UserMessage, } from "@/lib/types"; import { normalizeToolCalls } from "@/lib/normalize"; -import { hasVisibleAssistantContent } from "@/lib/assistant-response"; +import { hasHoldableAssistantContent, hasVisibleAssistantContent } from "@/lib/assistant-response"; import type { ThinkingModelMeta } from "@/lib/thinking-levels"; import { HostOfflineError, TransportLostError, getOutboxScope, rememberOutboxScope, sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client"; import type { HostStatus } from "@/lib/hosts/host"; @@ -2911,9 +2911,11 @@ export function useAgentSession(opts: UseAgentSessionOptions) { // copy (history callback). Tool-call turns still clear at once: their // rows and status line come from the live tool state instead. A // past-branch view never receives the saved copy, so it never holds. + // Thinking-only replies hold too: their thinking row was on screen + // while streaming, so dropping it flickers just like a text reply. const finishedReply = completed?.role === "assistant" && !catchUp.view().leafId - && hasVisibleAssistantContent(completed) + && hasHoldableAssistantContent(completed) && !(Array.isArray(completed.content) && completed.content.some((block) => block?.type === "toolCall")); dispatch(finishedReply ? { type: "hold", message: normalizeToolCalls(completed) } : { type: "idle", streaming: false }); setAgentPhase({ kind: "waiting_model" }); diff --git a/lib/assistant-response.test.mjs b/lib/assistant-response.test.mjs new file mode 100644 index 000000000..ec189507a --- /dev/null +++ b/lib/assistant-response.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url, { tsconfigPaths: true }); +const { hasVisibleAssistantContent, hasHoldableAssistantContent } = await jiti.import("./assistant-response.ts"); + +const thinkingOnly = { + role: "assistant", + content: [{ type: "thinking", thinking: "Let me think through the options carefully." }], +}; +const textReply = { role: "assistant", content: [{ type: "text", text: "hi" }] }; +const toolCallOnly = { + role: "assistant", + content: [{ type: "toolCall", toolCallId: "c1", toolName: "read", input: {} }], +}; + +test("hasVisibleAssistantContent is unchanged: thinking alone is not visible content", () => { + assert.equal(hasVisibleAssistantContent(thinkingOnly), false); + assert.equal(hasVisibleAssistantContent(textReply), true); + assert.equal(hasVisibleAssistantContent(toolCallOnly), false); +}); + +test("hasHoldableAssistantContent holds a thinking-only finished reply", () => { + assert.equal(hasHoldableAssistantContent(thinkingOnly), true); +}); + +test("hasHoldableAssistantContent holds ordinary visible replies", () => { + assert.equal(hasHoldableAssistantContent(textReply), true); + assert.equal(hasHoldableAssistantContent({ role: "assistant", content: [{ type: "image", source: { type: "base64", data: "x", media_type: "image/png" } }] }), true); +}); + +test("hasHoldableAssistantContent rejects empty and tool-call-only replies", () => { + assert.equal(hasHoldableAssistantContent({ role: "assistant", content: [{ type: "thinking", thinking: " " }] }), false); + assert.equal(hasHoldableAssistantContent({ role: "assistant", content: [{ type: "thinking", thinking: "" }] }), false); + assert.equal(hasHoldableAssistantContent(toolCallOnly), false); + assert.equal(hasHoldableAssistantContent({ role: "assistant", content: [] }), false); + assert.equal(hasHoldableAssistantContent({ role: "user", content: [{ type: "text", text: "hi" }] }), false); +}); diff --git a/lib/assistant-response.ts b/lib/assistant-response.ts index 7d4d4a212..9b26862f9 100644 --- a/lib/assistant-response.ts +++ b/lib/assistant-response.ts @@ -1,5 +1,22 @@ import { isRecord } from "./type-guards"; +/** + * Whether a finished reply must be held on screen until its saved copy + * lands (see the message_end handler in hooks/useAgentSession.ts). This is + * hasVisibleAssistantContent plus non-empty thinking: a thinking row was + * visible while streaming, so dropping it would flicker exactly like + * dropping a text reply. Other call sites keep the stricter predicate — + * a thinking-only run is not "content" for run-had-content purposes. + */ +export function hasHoldableAssistantContent(value: unknown): boolean { + if (hasVisibleAssistantContent(value)) return true; + if (!isRecord(value) || value.role !== "assistant" || !Array.isArray(value.content)) return false; + return value.content.some((block) => isRecord(block) + && block.type === "thinking" + && typeof block.thinking === "string" + && block.thinking.trim().length > 0); +} + /** Tool calls and empty assistant envelopes are not a response. */ export function hasVisibleAssistantContent(value: unknown): boolean { if (!isRecord(value) || value.role !== "assistant") return false;