Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { PromptContentPart, PromptImage } from "../model";
import { FindReveal } from "./chatFind";
import { attachmentPath, FileAttachment } from "../FileAttachment";
import { PasteChip, PromptText, PromptTyped } from "./PromptText";
import { HUGE_PROMPT_HEAD_CHARS, headParts } from "./promptCollapse";

/** Sent prompt content in ACP order. Text and attachment runs stay in one bubble, like Messages.
* A pasted block is the same chip a legacy prompt draws (PromptText.tsx), opening to its text. */
Expand All @@ -27,9 +28,10 @@ export const InlinePromptContent = memo(function InlinePromptContent({
text={parts.flatMap((part) => blockText(part) ?? []).join("\n")}
show={show}
>
{(open) => (
{(open, head) => (
<span className="cv-user__inline-content" data-inline-content="true">
{parts.map((part, index) => {
{/* A huge prompt collapsed draws only its head (PromptText.tsx): the clamp hides the rest. */}
{(head ? headParts(parts, HUGE_PROMPT_HEAD_CHARS, typedText) : parts).map((part, index) => {
// Two text blocks side by side read as the recorded text does, with its newline between
// them; the strip view's bubble, its attachments moved to the band, is that text. An
// attachment drawn between two blocks stands in the newline's place.
Expand All @@ -48,7 +50,10 @@ export const InlinePromptContent = memo(function InlinePromptContent({
);

function renderPart(part: PromptContentPart, index: number, open: () => void): ReactNode {
if (part.kind === "text") return <PromptTyped key={`text-${index}`} text={part.text} show={show} />;
if (part.kind === "text")
return (
<PromptTyped key={`text-${index}`} text={part.text} show={show} plain={"huge" in part && part.huge === true} />
);
if (part.kind === "image")
return (
<span key={`image-${part.id}-${index}`} className="cv-user__inline-image">
Expand Down Expand Up @@ -93,6 +98,9 @@ function blockText(part: PromptContentPart): string | undefined {
return undefined;
}

/** A typed text block's text: what a collapsed huge prompt's head counts (pastes are chips). */
const typedText = (part: PromptContentPart) => (part.kind === "text" ? part.text : undefined);

/** The parts the strip setting moves to the band above the bubble: attachments, not what reads as
* the prompt's text (typed text, pasted blocks and a text file's body stay in the bubble, as a
* legacy prompt's do), so the bubble keeps the recorded text whole. */
Expand Down
45 changes: 38 additions & 7 deletions webviews/src/agent-session/acpmux/conversation/PromptText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ import { useT, usePaneLanguage } from "../i18n";
import { FindReveal } from "./chatFind";
import {
COLLAPSED_PROMPT_LINES,
HUGE_PROMPT_HEAD_CHARS,
type PasteRange,
isHugePrompt,
looksLongPrompt,
pasteLines,
pasteName,
headParts,
promptParts,
} from "./promptCollapse";
import { useTranscriptDisclosure } from "./transcriptDisclosure";
Expand All @@ -39,7 +42,9 @@ export function PromptText({
/// How a typed part reads in the bubble (a `data:` image as its name, UserBubble.tsx).
show: (text: string) => string;
/// Ordered attachments share this fold; opening a pasted block also opens the prompt.
children?: (open: () => void) => ReactNode;
/// `head`: the prompt is huge and collapsed, so only its first `HUGE_PROMPT_HEAD_CHARS` of text
/// need drawing (`headParts`).
children?: (open: () => void, head: boolean) => ReactNode;
}) {
const t = useT();
const id = useId();
Expand All @@ -48,9 +53,17 @@ export function PromptText({
// Whether the prompt is taller than the collapsed lines: guessed from its text until laid out,
// then measured against its line height (open or closed), again when its width changes. A
// measure is of one text: a bubble drawn again with another prompt guesses again.
const guess = looksLongPrompt(pasted?.length ? "" : text) || parts.length > 3;
// A huge typed part beside pastes is long too, so it never draws whole before it is measured.
const guess =
looksLongPrompt(pasted?.length ? "" : text) ||
parts.length > 3 ||
parts.some((part) => part.kind === "text" && isHugePrompt(part.text));
const [measured, setMeasured] = useState<{ parts: typeof parts; long: boolean }>();
const long = measured?.parts === parts ? measured.long : guess;
// A huge prompt is always long: collapsed it draws only its head, and a measure of that head
// (which `show` may shrink to a label) must never unclamp it, or it would flip between head and
// whole text without end. Its Show more stays; the cost is at most a needless one.
const huge = isHugePrompt(text);
const long = huge || (measured?.parts === parts ? measured.long : guess);
const body = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const node = body.current;
Expand Down Expand Up @@ -80,6 +93,14 @@ export function PromptText({
return () => observer.disconnect();
}, [parts, long, open, children]);
const collapsed = long && !open;
// A huge prompt draws literally, and collapsed only its head: the clamp hides the rest anyway,
// and laying out megabytes of hidden text froze the chat (promptCollapse.ts HUGE_PROMPT_CHARS).
const head = huge && collapsed;
const shownParts = useMemo(
() =>
head ? headParts(parts, HUGE_PROMPT_HEAD_CHARS, (part) => (part.kind === "text" ? part.text : undefined)) : parts,
[head, parts],
);
// Show more and Show less (Leo 2026-10-21: "these all need animations for expand and collpase"),
// over the fold's token, without moving what the reader looks at ("just expand the area at the
// bottom and you're in the same place"):
Expand Down Expand Up @@ -164,10 +185,10 @@ export function PromptText({
<>
<div ref={body} id={id} className={`cv-user__text${collapsed ? " is-clamped is-faded" : ""}`}>
{children
? children(() => setOpen(true))
: parts.map((part, index) =>
? children(() => setOpen(true), head)
: shownParts.map((part, index) =>
part.kind === "text" ? (
<PromptTyped key={index} text={part.text} show={show} />
<PromptTyped key={index} text={part.text} show={show} plain={"huge" in part && part.huge === true} />
) : (
<PasteChip
key={index}
Expand Down Expand Up @@ -201,8 +222,18 @@ export function PromptText({
/// else its literal text, its line breaks kept (the bubble's `pre-wrap`), a bare web address as a
/// link, and break points in long tokens. A sent prompt's inline parts draw theirs with it too
/// (InlinePromptContent.tsx), so a placed prompt reads as a legacy one does.
export function PromptTyped({ text, show }: { text: string; show: (text: string) => string }) {
export function PromptTyped({
text,
show,
plain,
}: {
text: string;
show: (text: string) => string;
/// Draw it as one literal text node (a huge prompt's part; promptCollapse.ts HUGE_PROMPT_CHARS).
plain?: boolean;
}) {
const shown = show(text);
if (plain || isHugePrompt(text)) return <span className="cv-user__typed">{shown}</span>;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: PromptTyped selects literal mode using only this part’s length. A prompt with more than 200,000 typed characters split across smaller parts still parses each part as Markdown or scans it for links and break points when expanded; compute the threshold from aggregate typed text and pass the result to each part.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At webviews/src/agent-session/acpmux/conversation/PromptText.tsx, line 236:

<comment>`PromptTyped` selects literal mode using only this part’s length. A prompt with more than 200,000 typed characters split across smaller parts still parses each part as Markdown or scans it for links and break points when expanded; compute the threshold from aggregate typed text and pass the result to each part.</comment>

<file context>
@@ -201,8 +222,18 @@ export function PromptText({
+  plain?: boolean;
+}) {
   const shown = show(text);
+  if (plain || isHugePrompt(text)) return <span className="cv-user__typed">{shown}</span>;
   return isPromptMarkdown(text) ? (
     <Markdown className="cv-user__markdown" thumbnails={false}>
</file context>

return isPromptMarkdown(text) ? (
<Markdown className="cv-user__markdown" thumbnails={false}>
{shown}
Expand Down
162 changes: 162 additions & 0 deletions webviews/src/agent-session/acpmux/conversation/hugePrompt.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// l10n-allow-file: fixture prompts, not shipped UI.
// A prompt of megabytes (a pasted log, a base64 blob) never freezes the chat that holds it (Leo,
// 2026-10-31: "this is completely hardlocked bc of message size"). Past HUGE_PROMPT_CHARS it draws as
// one literal text node (no Markdown, no link scan, no <wbr> per separator), collapsed it draws only
// its head, and the row estimate is its collapsed lines without lexing or measuring the text.
import { expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { PromptText, PromptTyped } from "./PromptText";
import { InlinePromptContent } from "./InlinePromptContent";
import {
COLLAPSED_PROMPT_LINES,
HUGE_PROMPT_CHARS,
HUGE_PROMPT_HEAD_CHARS,
PROMPT_MORE_HEIGHT,
isHugePrompt,
promptHead,
} from "./promptCollapse";
import { layoutConversation } from "../model";
import { currentChatMetrics } from "../chatDisplay";

const same = (text: string) => text;
// Base64-like: no spaces, a `/` every 64 characters, so softBreaks would put a <wbr> after each.
const blob = (chars: number) =>
"QUJD/"
.concat("A".repeat(59))
.repeat(Math.ceil(chars / 64))
.slice(0, chars);
// Markdown-shaped, so a small one would go through the Markdown renderer.
const markdown = (chars: number) => `# Log\n- item **bold** \`code\`\n${"x".repeat(chars)}`;

test("a huge typed part draws as one literal text node, with no break points or Markdown", () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The test title says 'one literal text node', but the assertions only check for absent tags and the outer span. Either assert a single text node or rename the test to match what it checks.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At webviews/src/agent-session/acpmux/conversation/hugePrompt.test.tsx, line 31:

<comment>The test title says 'one literal text node', but the assertions only check for absent tags and the outer span. Either assert a single text node or rename the test to match what it checks.</comment>

<file context>
@@ -0,0 +1,162 @@
+// Markdown-shaped, so a small one would go through the Markdown renderer.
+const markdown = (chars: number) => `# Log\n- item **bold** \`code\`\n${"x".repeat(chars)}`;
+
+test("a huge typed part draws as one literal text node, with no break points or Markdown", () => {
+  const text = markdown(HUGE_PROMPT_CHARS);
+  const html = renderToStaticMarkup(<PromptTyped text={text} show={same} />);
</file context>

const text = markdown(HUGE_PROMPT_CHARS);
const html = renderToStaticMarkup(<PromptTyped text={text} show={same} />);
expect(html.startsWith('<span class="cv-user__typed">')).toBe(true);
expect(html).not.toContain("<h");
expect(html).not.toContain("<li");
expect(html).not.toContain("<wbr");
// A small one still renders its Markdown.
expect(renderToStaticMarkup(<PromptTyped text={markdown(10)} show={same} />)).toContain("<li");
});

test("a huge sent prompt opens collapsed on its head only", () => {
const text = blob(5 * 1024 * 1024);
const html = renderToStaticMarkup(<PromptText rowId="huge" text={text} show={same} />);
expect(html).toContain("is-clamped");
expect(html).not.toContain("<wbr");
expect(html.length).toBeLessThan(HUGE_PROMPT_HEAD_CHARS + 1_000);
// A prompt under the threshold keeps its whole text in the clamp, as before.
const small = blob(HUGE_PROMPT_CHARS - 1);
expect(renderToStaticMarkup(<PromptText rowId="small" text={small} show={same} />).length).toBeGreaterThan(
HUGE_PROMPT_CHARS - 1,
);
});

test("a huge prompt's head never ends inside a surrogate pair", () => {
const text = "a".repeat(9) + "😀" + "b".repeat(10);
expect(promptHead(text, 10)).toBe("a".repeat(9));
expect(promptHead(text, 11)).toBe("a".repeat(9) + "😀");
expect(promptHead("short", 10)).toBe("short");
expect(isHugePrompt("x".repeat(HUGE_PROMPT_CHARS))).toBe(false);
expect(isHugePrompt("x".repeat(HUGE_PROMPT_CHARS + 1))).toBe(true);
});

test("a huge prompt's row is estimated as its collapsed lines, quickly", () => {
const { lineHeight } = currentChatMetrics();
const row = (id: string, text: string) => ({ id, version: 1, at: 0, kind: "user", text });
const started = performance.now();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The wall-clock elapsed < 2_000 assertion can flake on a loaded CI runner, and it includes building the 20 MiB fixture. Assert on the equality of heights, which already proves the path, and drop or start the timer after the fixture is built.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At webviews/src/agent-session/acpmux/conversation/hugePrompt.test.tsx, line 67:

<comment>The wall-clock `elapsed < 2_000` assertion can flake on a loaded CI runner, and it includes building the 20 MiB fixture. Assert on the equality of heights, which already proves the path, and drop or start the timer after the fixture is built.</comment>

<file context>
@@ -0,0 +1,162 @@
+test("a huge prompt's row is estimated as its collapsed lines, quickly", () => {
+  const { lineHeight } = currentChatMetrics();
+  const row = (id: string, text: string) => ({ id, version: 1, at: 0, kind: "user", text });
+  const started = performance.now();
+  const [huge] = [...layoutConversation([row("h", markdown(20 * 1024 * 1024))] as never, 720).heights];
+  const elapsed = performance.now() - started;
</file context>

const [huge] = [...layoutConversation([row("h", markdown(20 * 1024 * 1024))] as never, 720).heights];
const elapsed = performance.now() - started;
const [long] = [...layoutConversation([row("l", "A line that wraps.\n".repeat(200))] as never, 720).heights];
// The same collapsed height as any long prompt: ten lines and Show more.
expect(huge).toBe(long);
expect(huge!).toBeGreaterThanOrEqual(COLLAPSED_PROMPT_LINES * lineHeight + PROMPT_MORE_HEIGHT);
expect(elapsed).toBeLessThan(2_000);
});

test("a huge prompt with placed attachments opens collapsed on its head only", () => {
const parts = [
{ kind: "text" as const, text: blob(3 * 1024 * 1024) },
{ kind: "image" as const, id: "img", mimeType: "image/png", data: "", placed: true as const },
{ kind: "text" as const, text: "after the image" },
];
const html = renderToStaticMarkup(
<InlinePromptContent rowId="inline-huge" parts={parts as never} show={same} renderImage={() => <i />} />,
);
expect(html).toContain("is-clamped");
expect(html).not.toContain("<wbr");
expect(html.length).toBeLessThan(HUGE_PROMPT_HEAD_CHARS + 1_000);
});

test("a short Markdown note beside a huge paste keeps its Markdown", () => {
const note = "- one\n- two";
const text = `${note}\n${"y".repeat(HUGE_PROMPT_CHARS + 10)}`;
const html = renderToStaticMarkup(
<PromptText rowId="note" text={text} pasted={[{ start: note.length + 1, end: text.length }]} show={same} />,
);
expect(html).toContain("<li");
});

test("a huge typed part beside a paste opens collapsed on its head", () => {
const typed = blob(HUGE_PROMPT_CHARS + 10);
const text = `${typed}\n${"pasted line\n".repeat(5)}`;
const html = renderToStaticMarkup(
<PromptText rowId="typed-huge" text={text} pasted={[{ start: typed.length + 1, end: text.length }]} show={same} />,
);
expect(html).toContain("is-clamped");
expect(html.length).toBeLessThan(HUGE_PROMPT_HEAD_CHARS + 2_000);
});

test("a huge prompt whose drawn head measures short stays collapsed, never flipping", async () => {
const { JSDOM } = await import("jsdom");
const { act } = await import("react");
const { createRoot } = await import("react-dom/client");
const dom = new JSDOM("<!doctype html><html><body><main id=root></main></body></html>");
const scope = globalThis as Record<string, unknown>;
const keys = ["window", "document", "navigator", "Node", "HTMLElement", "Element", "IS_REACT_ACT_ENVIRONMENT"];
const saved = keys.map((key) => [key, scope[key]] as const);
Object.assign(scope, {
window: dom.window,
document: dom.window.document,
navigator: dom.window.navigator,
Node: dom.window.Node,
HTMLElement: dom.window.HTMLElement,
Element: dom.window.Element,
IS_REACT_ACT_ENVIRONMENT: true,
});
// Layout as a browser does it here: 20px lines, each 100 characters one line, so the head that
// `show` shrinks to a label fits one line and the whole text is thousands.
const height = (node: Node) => Math.ceil((node.textContent?.length ?? 0) / 100) * 20;
dom.window.getComputedStyle = (() => ({ lineHeight: "20px" })) as never;
Object.defineProperty(dom.window.HTMLElement.prototype, "scrollHeight", {
get(this: HTMLElement) {
return height(this);
},
});
const createRange = dom.window.document.createRange.bind(dom.window.document);
dom.window.document.createRange = () => {
const range = createRange();
let of: Node | undefined;
range.selectNodeContents = (node: Node) => void (of = node);
range.getBoundingClientRect = () => ({ height: of ? height(of) : 0 }) as DOMRect;
return range;
};
let renders = 0;
const show = (text: string) => {
renders++;
return text.startsWith("data:") ? "[Image]" : text;
};
const uri = `data:text/plain;base64,${"A".repeat(HUGE_PROMPT_HEAD_CHARS + 1_000)}`;
const text = `${uri}${"\nline".repeat(HUGE_PROMPT_CHARS / 4)}`;
const host = dom.window.document.getElementById("root")!;
const root = createRoot(host);
try {
act(() => root.render(<PromptText rowId="flip" text={text} show={show} />));
expect(host.querySelector(".cv-user__text")!.classList.contains("is-clamped")).toBe(true);
expect(host.textContent!.length).toBeLessThan(HUGE_PROMPT_HEAD_CHARS);
expect(renders).toBeLessThan(10);
} finally {
act(() => root.unmount());
for (const [key, value] of saved) scope[key] = value;
}
});
43 changes: 43 additions & 0 deletions webviews/src/agent-session/acpmux/conversation/promptCollapse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,49 @@ export function collapsedPromptHeight(height: number, lineHeight: number): numbe
return height > limit + 1 ? limit + PROMPT_MORE_HEIGHT : height;
}

/// A prompt longer than this many characters (a pasted log, a base64 blob) draws as literal text in
/// one text node: no Markdown, no link scan and no break points, each of which costs the main thread
/// per character or per token, and a prompt of megabytes froze the chat that held it (Leo,
/// 2026-10-31: "this is completely hardlocked bc of message size"). Collapsed, it draws only its
/// head (`HUGE_PROMPT_HEAD_CHARS`), far more than ten lines at any width; Show more draws it whole.
export const HUGE_PROMPT_CHARS = 200_000;
export const HUGE_PROMPT_HEAD_CHARS = 4_000;

export const isHugePrompt = (text: string) => text.length > HUGE_PROMPT_CHARS;

/// A huge prompt's typed parts as its collapsed bubble draws them: the parts within its first `chars`
/// characters of typed text, the last one cut short, and nothing after. A paste or an attachment is
/// a chip whatever its length, so it counts nothing. `huge` marks a part cut from a huge one, which
/// draws literally as its whole text does once open; a short part beside a big paste keeps its
/// Markdown.
export function headParts<T extends { kind: string }>(
parts: readonly T[],
chars: number,
typed: (part: T) => string | undefined,
): (T & { huge?: boolean })[] {
const out: (T & { huge?: boolean })[] = [];
let left = chars;
for (const part of parts) {
if (left <= 0) break;
const text = typed(part);
if (text === undefined) {
out.push(part);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: headParts retains paste parts regardless of size, so a collapsed huge paste still reaches PasteChip, which splits the full text to derive its name and line count. Bound those calculations for huge paste chips so collapsing the prompt does not allocate arrays proportional to the paste’s line count.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At webviews/src/agent-session/acpmux/conversation/promptCollapse.ts, line 50:

<comment>`headParts` retains paste parts regardless of size, so a collapsed huge paste still reaches `PasteChip`, which splits the full text to derive its name and line count. Bound those calculations for huge paste chips so collapsing the prompt does not allocate arrays proportional to the paste’s line count.</comment>

<file context>
@@ -21,6 +21,49 @@ export function collapsedPromptHeight(height: number, lineHeight: number): numbe
+    if (left <= 0) break;
+    const text = typed(part);
+    if (text === undefined) {
+      out.push(part);
+      continue;
+    }
</file context>

continue;
}
const head = promptHead(text, left);
out.push(head === text ? part : { ...part, text: head, huge: isHugePrompt(text) });
left -= head.length;
}
return out;
}

/// The first `chars` UTF-16 units of `text`, never ending inside a surrogate pair.
export function promptHead(text: string, chars: number): string {
if (text.length <= chars) return text;
const code = text.charCodeAt(chars - 1);
return text.slice(0, code >= 0xd800 && code <= 0xdbff ? chars - 1 : chars);
}

/// Whether a prompt is likely taller than the collapsed lines, before it is laid out.
export const looksLongPrompt = (text: string) =>
text.length > LONG_PROMPT_CHARS || text.split("\n", COLLAPSED_PROMPT_LINES + 1).length > COLLAPSED_PROMPT_LINES;
Expand Down
Loading