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
75 changes: 75 additions & 0 deletions components/ChatInput.image-skip-notice.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import "../tests/setup-dom.mjs";
import assert from "node:assert/strict";
import test, { afterEach, beforeEach } from "node:test";
import React, { act } from "react";
import { cleanup, render, screen, waitFor } from "@testing-library/react/pure.js";
import { createJiti } from "jiti";

const jiti = createJiti(import.meta.url, { jsx: { runtime: "automatic" }, tsconfigPaths: true });
const { ChatInput } = await jiti.import("./ChatInput.tsx");
const { clearDraft, getDraft } = await jiti.import("@/lib/draft-store");

const KEY = "hunt-silent-drop";
const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";

const previousFileReader = globalThis.FileReader;
class TestFileReader {
result = null;
onload = null;
onerror = null;
readAsDataURL(blob) {
blob.arrayBuffer().then(
(buffer) => {
this.result = `data:${blob.type};base64,${Buffer.from(buffer).toString("base64")}`;
this.onload?.();
},
(error) => this.onerror?.(error),
);
}
}

beforeEach(() => {
window.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
globalThis.FileReader = TestFileReader;
URL.createObjectURL ??= () => "blob:test";
URL.revokeObjectURL ??= () => {};
});
afterEach(() => {
try { cleanup(); } finally {
clearDraft(KEY);
localStorage.clear();
delete window.matchMedia;
globalThis.FileReader = previousFileReader;
}
});

test("reports an oversized image dropped while another image is accepted", async () => {
const ref = React.createRef();
render(React.createElement(ChatInput, {
ref, draftKey: KEY, isStreaming: false,
onSend: async () => ({ status: "accepted" }),
onAbort: async () => {},
}));
const small = new File([Buffer.from(PNG, "base64")], "small.png", { type: "image/png" });
const big = new File([Buffer.alloc(5 * 1024 * 1024 + 1, 0)], "big.png", { type: "image/png" });
await act(async () => { ref.current.addFiles([small, big]); });
await waitFor(() => assert.equal(getDraft(KEY)?.images.length, 1));
const alerts = screen.queryAllByRole("alert");
// A dropped file must be reported, not vanish.
assert.equal(alerts.length, 1, `expected a skip notice for the oversized file, got ${alerts.length}`);
});

test("reports images dropped past the 10-image cap while some are accepted", async () => {
const ref = React.createRef();
render(React.createElement(ChatInput, {
ref, draftKey: KEY, isStreaming: false,
onSend: async () => ({ status: "accepted" }),
onAbort: async () => {},
}));
const files = Array.from({ length: 11 }, (_, i) => new File([Buffer.from(PNG, "base64")], `img${i}.png`, { type: "image/png" }));
await act(async () => { ref.current.addFiles(files); });
await waitFor(() => assert.equal(getDraft(KEY)?.images.length, 10));
const alerts = screen.queryAllByRole("alert");
// A dropped file must be reported, not vanish.
assert.equal(alerts.length, 1, `expected a skip notice for the over-cap image, got ${alerts.length}`);
});
13 changes: 12 additions & 1 deletion components/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,10 @@
const imageFiles = files
.filter((file) => file.type.startsWith("image/") && file.size <= MAX_ATTACHED_IMAGE_BYTES)
.slice(0, remaining);
// Dropped images must be reported even when siblings are accepted:
// silently losing one makes the user send believing all attached.
// (processFiles only passes image files here, so every gap is a drop.)
const skipped = files.length - imageFiles.length;
if (!imageFiles.length) {
if (files.length > 0) {
setAttachError(
Expand Down Expand Up @@ -619,7 +623,14 @@
newImages.slice(accepted.length).forEach(revokeImagePreview);
return [...prev, ...accepted];
});
setAttachError(null);
// Keep the skip notice when some files were dropped, mirroring the
// text-file path, which reports every dropped candidate. The zero-
// acceptance branch above keeps its own at-limit/skip wording.
if (skipped > 0) {
setAttachError(t("chatInput.attachmentImagesSkipped", { count: skipped, size: formatAttachmentBytes(MAX_ATTACHED_IMAGE_BYTES) }));
} else {
setAttachError(null);
}
} catch {
// A failed read in the batch must not leak the siblings' blob URLs.
created.forEach(revokeImagePreview);
Expand All @@ -627,7 +638,7 @@
} finally {
pendingImageCountRef.current -= imageFiles.length;
}
}, []);

Check warning on line 641 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

Check warning on line 641 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

const processTextFiles = useCallback(async (files: File[]) => {
const remaining = Math.max(
Expand Down Expand Up @@ -688,7 +699,7 @@
pendingTextFileCountRef.current -= textFiles.length;
pendingTextFileBytesRef.current -= textFiles.reduce((total, file) => total + file.size, 0);
}
}, []);

Check warning on line 702 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (ubuntu-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

Check warning on line 702 in components/ChatInput.tsx

View workflow job for this annotation

GitHub Actions / Verify (windows-latest)

React Hook useCallback has a missing dependency: 't'. Either include it or remove the dependency array

const processFiles = useCallback((files: File[]) => {
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
Expand Down
39 changes: 39 additions & 0 deletions components/MessageView.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -950,3 +950,42 @@ test("user messages fork at their own entry and edit the prompt", async (t) => {
assert.deepEqual(forked, [["user-7", true]]);
view.unmount();
});

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 @@ -349,11 +349,17 @@ function UserMessageView({ message, cwd, onOpenFile, entryId, onFork, forking, f
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 @@ -362,7 +368,7 @@ function UserMessageView({ message, cwd, onOpenFile, entryId, onFork, forking, f
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 @@ -408,6 +414,7 @@ function UserMessageView({ message, cwd, onOpenFile, entryId, onFork, forking, f
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 @@ -8,7 +8,7 @@ const jiti = createJiti(import.meta.url, {
jsx: { runtime: "automatic" },
tsconfigPaths: true,
});
const { TaskBlock, CompletionBlock, SubagentModel } = await jiti.import("./SubagentTranscriptDialog.tsx");
const { TaskBlock, CompletionBlock, SubagentModel, SubagentTranscriptRow } = await jiti.import("./SubagentTranscriptDialog.tsx");

test("shows the provider-qualified model and reasoning effort split from the resolved model", () => {
const html = renderToStaticMarkup(React.createElement(SubagentModel, {
Expand Down Expand Up @@ -90,3 +90,13 @@ test("shows an empty state when no completion exists yet", () => {
}));
assert.match(html, /No output yet/);
});

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 @@ -22,7 +22,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 @@ -55,7 +55,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 @@ -1158,6 +1158,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 @@ -13,7 +13,7 @@ import type {
ToolResultMessage,
} 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 { sendAgentCommand, setSessionAdvisorSpawn } from "@/lib/agent-client";
import { parseSkillDiagnosticsSnapshot, type SkillDiagnosticsSnapshot } from "@/lib/skill-diagnostics";
Expand Down Expand Up @@ -2333,9 +2333,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