Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions components/MessageView.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
11 changes: 9 additions & 2 deletions components/MessageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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)" }}
/>
);
Expand Down
12 changes: 11 additions & 1 deletion components/SubagentTranscriptDialog.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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}`));
});
7 changes: 5 additions & 2 deletions components/SubagentTranscriptDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -56,7 +56,10 @@ function SubagentTranscriptRow({ message }: { message: AgentMessage }) {
? rawContent.map((block, i) => (
<div key={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) ?? ""
: ""}
Expand Down
22 changes: 22 additions & 0 deletions hooks/useAgentSession.rpc.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]);
Expand Down
6 changes: 4 additions & 2 deletions hooks/useAgentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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" });
Expand Down
39 changes: 39 additions & 0 deletions lib/assistant-response.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
});
17 changes: 17 additions & 0 deletions lib/assistant-response.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
Loading