From eae885fba47ca4900ad655f2e691d7eedbf4e5a1 Mon Sep 17 00:00:00 2001 From: luke Date: Sat, 28 Nov 2026 20:12:54 +0800 Subject: [PATCH] fix(app): hold back a closing code fence while it is still being typed (#7006) While a reply streams, the last line of an open code block can hold one or two backticks of the fence that will close it. Painted, they are a line of code that disappears a moment later. The reveal now withholds that line while the turn streams until it closes the block or turns out to be code. Finished turns paint everything. Co-authored-by: RoundRedDot --- .../agent-stream-closing-fence.spec.ts | 559 ++++++++++++++++++ .../app/src/agent-stream/text-reveal.test.ts | 125 ++++ packages/app/src/agent-stream/text-reveal.ts | 46 +- packages/app/src/hooks/use-revealed-text.ts | 9 +- .../providers/mock-load-test-agent.test.ts | 30 + .../agent/providers/mock-load-test-agent.ts | 49 ++ 6 files changed, 813 insertions(+), 5 deletions(-) create mode 100644 packages/app/e2e/browser/agent-stream-closing-fence.spec.ts diff --git a/packages/app/e2e/browser/agent-stream-closing-fence.spec.ts b/packages/app/e2e/browser/agent-stream-closing-fence.spec.ts new file mode 100644 index 0000000000..a28ba91bf2 --- /dev/null +++ b/packages/app/e2e/browser/agent-stream-closing-fence.spec.ts @@ -0,0 +1,559 @@ +import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; +import { connectDaemonClient } from "../support/helpers/daemon-client-loader"; +import { + beginTextReveal, + retargetTextReveal, + visibleRevealedText, +} from "../../src/agent-stream/text-reveal"; +import type { Page } from "@playwright/test"; +import { test, expect } from "../support/fixtures"; +import { expectComposerVisible } from "../support/helpers/composer"; +import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor"; +import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent"; + +test.use({ + e2eDaemonConfig: { + version: 1, + agents: { + providers: Object.fromEntries( + [ + "claude", + "codex", + "copilot", + "opencode", + "pi", + "omp", + "antigravity", + "hoplite", + "muse", + ].map((id) => [id, { enabled: false }]), + ), + }, + }, +}); + +interface ClosingFenceFrameSample { + text: string; + codeBlockHeights: number[]; + codeBlockTexts: string[]; + messageHeights: number[]; + partialFenceLines: string[]; +} + +interface ClosingFenceFrameReport { + finished: boolean; + samples: ClosingFenceFrameSample[]; +} + +async function sampleClosingFenceFrames(page: Page): Promise { + return await page.evaluate(async () => { + const samples: ClosingFenceFrameSample[] = []; + let finished = false; + + await new Promise((resolve) => { + const tick = () => { + const messages = Array.from( + document.querySelectorAll('[data-testid="assistant-message"]'), + ); + const text = messages.map((message) => message.textContent ?? "").join(""); + const sample: ClosingFenceFrameSample = { + text, + codeBlockHeights: [], + codeBlockTexts: [], + messageHeights: messages.map((message) => + Math.round(message.getBoundingClientRect().height), + ), + partialFenceLines: [], + }; + + for (const message of messages) { + for (const block of message.querySelectorAll( + 'pre, [data-paseo-markdown-tag="pre"]', + )) { + const code = block.querySelector('code, [data-paseo-markdown-tag="code"]'); + const codeText = code?.textContent ?? block.textContent ?? ""; + sample.codeBlockTexts.push(codeText.trimEnd()); + // Opening fence prefixes render as prose; closing artifacts live inside code blocks. + for (const line of codeText.split(/\r?\n/)) { + if (/^\s*`{1,2}\s*$/.test(line)) sample.partialFenceLines.push(line); + } + sample.codeBlockHeights.push(Math.round(block.getBoundingClientRect().height)); + } + } + + samples.push(sample); + + finished = text.includes("Both blocks are closed."); + if (finished) { + resolve(); + return; + } + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); + + return { finished, samples }; + }); +} + +const FIRST_PAUSE_TEXT = "Here is the first snippet:const answer = 42;\nconsole.log(answer);"; +const SECOND_PAUSE_TEXT = `${FIRST_PAUSE_TEXT}And a second one:echo done`; + +for (const { label, html } of [ + { label: "semantic", html: "
const answer = 42;\n`\n``
" }, + { + label: "annotated", + html: '
const answer = 42;\n`\n``
', + }, + { + label: "annotated semantic", + html: '
const answer = 42;\n`\n``
', + }, +]) { + test(`samples ${label} code block DOM without duplicate blocks or controls`, async ({ page }) => { + await page.setContent( + `
${html}

Both blocks are closed.

`, + ); + const report = await sampleClosingFenceFrames(page); + const sample = report.samples.at(-1)!; + expect(report.finished).toBe(true); + expect(sample.codeBlockTexts).toEqual(["const answer = 42;\n`\n``"]); + expect(sample.partialFenceLines).toEqual(["`", "``"]); + expect(sample.codeBlockHeights).toHaveLength(1); + expect(sample.codeBlockHeights[0]).toBeGreaterThan(0); + }); +} + +function closingFencePauseSamples( + samples: readonly ClosingFenceFrameSample[], + pauseText: string, +): ClosingFenceFrameSample[] { + return samples.filter((sample) => sample.text === pauseText); +} + +function expectStableGeometry( + samples: readonly ClosingFenceFrameSample[], + expectedCodeBlockTexts: readonly string[], +): void { + expect(samples.length, "the paused text state should be sampled").toBeGreaterThan(0); + expect( + samples.every( + (sample) => JSON.stringify(sample.codeBlockTexts) === JSON.stringify(expectedCodeBlockTexts), + ), + "the sampled code should contain only the authored lines", + ).toBe(true); + const geometries = new Set( + samples.map((sample) => JSON.stringify([sample.messageHeights, sample.codeBlockHeights])), + ); + expect( + geometries.size, + "message and code block geometry should stay fixed during the pause", + ).toBe(1); +} + +/** + * A closing fence that is still being typed must not be painted as code. + * + * The mock reply closes each code block in two arrivals: one backtick, a pause, + * then the other two. Painted, that first backtick is a line of code that + * vanishes when the fence completes, so the block grows and shrinks and every + * row below it moves twice. Each pause is sampled and its text geometry checked. + */ +test("does not paint a closing fence while it is still being typed", async ({ page }, testInfo) => { + test.setTimeout(90_000); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "closing-fence-", + title: "Closing fence", + model: "e2e-fast-stream", + }); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const reportPromise = sampleClosingFenceFrames(page); + await agent.client.sendAgentMessage( + agent.agentId, + "Stream a code block with a split closing fence.", + ); + const report = await reportPromise; + + await testInfo.attach("closing-fence-frames", { + body: JSON.stringify(report, null, 2), + contentType: "application/json", + }); + expect(report.finished, "the reply should finish streaming").toBe(true); + expect( + report.samples.flatMap((sample) => sample.partialFenceLines), + "no frame, including transitions outside the pause windows, may show a partial fence inside code", + ).toEqual([]); + const firstPauseSamples = closingFencePauseSamples(report.samples, FIRST_PAUSE_TEXT); + const secondPauseSamples = closingFencePauseSamples(report.samples, SECOND_PAUSE_TEXT); + expectStableGeometry(firstPauseSamples, ["const answer = 42;\nconsole.log(answer);"]); + expectStableGeometry(secondPauseSamples, [ + "const answer = 42;\nconsole.log(answer);", + "echo done", + ]); + expect(secondPauseSamples[0]?.codeBlockHeights[0]).toBe( + firstPauseSamples[0]?.codeBlockHeights[0], + ); + } finally { + await agent.cleanup(); + } +}); + +test("excludes each revealed character of the next paragraph from both pauses", () => { + for (const [pauseText, paragraph] of [ + [FIRST_PAUSE_TEXT, "And a second one:"], + [SECOND_PAUSE_TEXT, "Both blocks are closed."], + ]) { + const state = retargetTextReveal(beginTextReveal(pauseText), pauseText + paragraph); + const samples = Array.from({ length: paragraph.length + 1 }, (_, index) => ({ + text: visibleRevealedText({ ...state, revealed: pauseText.length + index }), + codeBlockHeights: [], + codeBlockTexts: [], + messageHeights: [index], + partialFenceLines: [], + })); + expect(closingFencePauseSamples(samples, pauseText)).toEqual([samples[0]]); + } +}); + +for (const { label, markdown, expectedCode, expectedPartialFenceLines } of [ + { + label: "opening prefixes in prose", + markdown: "And a second one:\n\n`\n\n``\n\nBoth blocks are closed.", + expectedCode: [], + expectedPartialFenceLines: [], + }, + { + label: "partial fences inside rendered code", + markdown: "```ts\nconst answer = 42;\n`\n``\n```\n\nBoth blocks are closed.", + expectedCode: ["const answer = 42;\n`\n``"], + expectedPartialFenceLines: ["`", "``"], + }, +]) { + test(`samples ${label} in the correct container`, async ({ page }, testInfo) => { + const agent = await seedMockAgentWorkspace({ + repoPrefix: "fence-sample-container-", + title: "Fence sample container", + featureValues: { mockAssistantResponse: markdown }, + }); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const reportPromise = sampleClosingFenceFrames(page); + await agent.client.sendAgentMessage(agent.agentId, "Show the fence sampling fixture."); + const report = await reportPromise; + await testInfo.attach("fence-container-frames", { + body: JSON.stringify(report, null, 2), + contentType: "application/json", + }); + expect(report.finished).toBe(true); + const messageText = await page.getByTestId("assistant-message").innerText(); + const messageLines = messageText.split(/\r?\n/); + const messageFenceLines = messageLines.filter((line) => /^\s*`{1,2}\s*$/.test(line)); + expect(messageFenceLines).toEqual(["`", "``"]); + const finalSample = report.samples.at(-1); + expect(finalSample?.codeBlockTexts).toEqual(expectedCode); + expect(finalSample?.partialFenceLines).toEqual(expectedPartialFenceLines); + } finally { + await agent.cleanup(); + } + }); +} + +test("shows the complete reasoning after a streamed turn finishes", async ({ page }, testInfo) => { + test.setTimeout(90_000); + await page.setViewportSize({ width: 1280, height: 900 }); + await page.addInitScript(() => { + localStorage.setItem( + "@paseo:app-settings", + JSON.stringify({ toolCallDetailLevel: "detailed", autoExpandReasoning: true }), + ); + }); + const reasoning = + "Need to find the scroll container, the layout effect that watches for new messages, and any gesture handler that might fight with programmatic scrolling. Probably a ref on the FlatList plus a near-bottom threshold."; + const agent = await seedMockAgentWorkspace({ + repoPrefix: "finished-reasoning-", + title: "Finished reasoning", + model: "ten-second-stream", + }); + const historyClient = await connectDaemonClient< + Pick + >({ clientIdPrefix: "finished-reasoning-history" }); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + await agent.client.sendAgentMessage( + agent.agentId, + "Stream briefly to check finished reasoning.", + ); + await agent.client.waitForFinish(agent.agentId, 30_000); + const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 }); + const thoughts = history.entries + .map((entry) => entry.item) + .filter((item) => item.type === "reasoning"); + await testInfo.attach("canonical-reasoning", { + body: JSON.stringify(thoughts, null, 2), + contentType: "application/json", + }); + expect(thoughts[0]?.text).toBe(reasoning); + const expectedCounts = new Map(); + for (const thought of thoughts) + expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1); + const rendered = page.getByText(reasoning, { exact: true }); + for (const [text, count] of expectedCounts) + await expect(page.getByText(text, { exact: true })).toHaveCount(count); + await expect(rendered.first()).toBeVisible(); + await testInfo.attach("finished-reasoning", { + body: await page.screenshot(), + contentType: "image/png", + }); + await page.reload(); + for (const [text, count] of expectedCounts) + await expect(page.getByText(text, { exact: true })).toHaveCount(count); + await expect(rendered.first()).toBeVisible(); + } catch (error) { + await testInfo.attach("reasoning-before-cleanup", { + body: await page.screenshot(), + contentType: "image/png", + }); + throw error; + } finally { + await historyClient.close(); + await agent.cleanup(); + } +}); + +test("records equal-input long-reply rendering metrics", async ({ page }, testInfo) => { + test.setTimeout(120_000); + await page.setViewportSize({ width: 1280, height: 900 }); + const markdown = + Array.from({ length: 15 }, (_, index) => + [ + "### Block " + index, + "", + "\x60\x60\x60ts", + ...Array.from( + { length: 12 }, + (_value, line) => "const value_" + index + "_" + line + " = " + (index * 12 + line) + ";", + ), + "\x60\x60\x60", + "", + ].join("\n"), + ).join("\n") + "\nEqual-input stream complete."; + const agent = await seedMockAgentWorkspace({ + repoPrefix: "equal-input-long-reply-", + title: "Equal-input long reply", + featureValues: { + mockStreamingAssistantResponse: markdown, + mockStreamingAssistantIntervalMs: 5, + }, + }); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + const session = await page.context().newCDPSession(page); + await session.send("Performance.enable"); + const before = await session.send("Performance.getMetrics"); + const sampler = await page.evaluateHandle(() => { + const state = { + frames: [] as number[], + longTasks: [] as number[], + running: true, + last: performance.now(), + }; + const observer = new PerformanceObserver((list) => { + state.longTasks.push(...list.getEntries().map((entry) => entry.duration)); + }); + observer.observe({ type: "longtask", buffered: false }); + const tick = (now: number) => { + state.frames.push(now - state.last); + state.last = now; + if (state.running) requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + return { state, observer }; + }); + await agent.client.sendAgentMessage(agent.agentId, "Render the fixed fifteen-block fixture."); + await agent.client.waitForFinish(agent.agentId, 60_000); + const message = page.getByTestId("assistant-message").last(); + await expect(message).toContainText("Equal-input stream complete.", { timeout: 30_000 }); + const blocks = message.locator('pre, [data-paseo-markdown-tag="pre"]'); + await expect(blocks).toHaveCount(15); + for (let index = 0; index < 15; index++) { + await expect(blocks.nth(index)).toContainText( + "const value_" + index + "_11 = " + (index * 12 + 11) + ";", + ); + } + const samples = await sampler.evaluate(({ state, observer }) => { + state.running = false; + state.longTasks.push(...observer.takeRecords().map((entry) => entry.duration)); + observer.disconnect(); + return state; + }); + const after = await session.send("Performance.getMetrics"); + const frames = [...samples.frames].sort((a, b) => a - b); + await testInfo.attach("equal-input-rendering", { + body: JSON.stringify( + { + markdown, + viewport: page.viewportSize(), + intervalMs: 5, + frameCount: frames.length, + frameP95Ms: frames[Math.floor(frames.length * 0.95)], + maxFrameMs: frames.at(-1), + longTasksMs: samples.longTasks, + before: before.metrics, + after: after.metrics, + }, + null, + 2, + ), + contentType: "application/json", + }); + await sampler.dispose(); + await session.detach(); + } finally { + await agent.cleanup(); + } +}); + +test("manually expands complete reasoning after leaving output following", async ({ + page, +}, testInfo) => { + test.setTimeout(90_000); + await page.setViewportSize({ width: 1280, height: 900 }); + await page.addInitScript(() => { + localStorage.setItem( + "@paseo:app-settings", + JSON.stringify({ chatDisplay: "full", autoExpandReasoning: false }), + ); + }); + const agent = await seedMockAgentWorkspace({ + repoPrefix: "manual-finished-reasoning-", + title: "Manual finished reasoning", + model: "ten-second-stream", + }); + const historyClient = await connectDaemonClient< + Pick + >({ clientIdPrefix: "manual-finished-reasoning-history" }); + try { + await openAgentRoute(page, agent); + await expectComposerVisible(page); + await agent.client.sendAgentMessage( + agent.agentId, + "Stream briefly to check finished reasoning.", + ); + const finished = await agent.client.waitForFinish(agent.agentId, 30_000); + expect(finished.status).toBe("idle"); + await testInfo.attach("manual-completed-turn", { + body: JSON.stringify(finished), + contentType: "application/json", + }); + const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 }); + const thoughts = history.entries + .map((entry) => entry.item) + .filter((item) => item.type === "reasoning"); + expect(thoughts.length).toBeGreaterThan(0); + expect(thoughts.every((thought) => thought.text.length > 0)).toBe(true); + const expectedCounts = new Map(); + for (const thought of thoughts) + expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1); + await testInfo.attach("manual-canonical-reasoning", { + body: JSON.stringify(thoughts, null, 2), + contentType: "application/json", + }); + const pointerCapture = await page.evaluateHandle(() => { + const events: { + type: string; + timestamp: number; + tag: string; + label: string; + scrollTop: number | null; + }[] = []; + const observe = (event: Event) => { + const target = event.target; + if (!(target instanceof HTMLElement)) return; + const scroll = document.querySelector('[data-testid="agent-chat-scroll"]'); + events.push({ + type: event.type, + timestamp: event.timeStamp, + tag: target.tagName, + label: target.textContent?.slice(0, 80) ?? "", + scrollTop: scroll?.scrollTop ?? null, + }); + }; + for (const type of ["pointerdown", "pointerup", "wheel"]) + document.addEventListener(type, observe, true); + return { + events, + stop: () => { + for (const type of ["pointerdown", "pointerup", "wheel"]) + document.removeEventListener(type, observe, true); + }, + }; + }); + const badges = page.getByTestId("tool-call-badge").filter({ hasText: "Thinking" }); + await expect(badges).toHaveCount(thoughts.length); + // Locator scrolling alone leaves output-following armed, so pointer-down can + // snap the feed to its tail before pointer-up reaches the Thinking control. + await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 }); + for (let index = 0; index < thoughts.length; index++) { + await badges + .nth(index) + .getByRole("button", { name: "Thinking", exact: true }) + .first() + .click(); + await expect( + badges.nth(index).getByText(thoughts[index].text, { exact: true }), + ).toBeVisible(); + } + for (const [text, count] of expectedCounts) + await expect(page.getByText(text, { exact: true })).toHaveCount(count); + const first = badges.first(); + await first.getByRole("button", { name: "Thinking", exact: true }).first().click(); + await expect(first.getByText(thoughts[0].text, { exact: true })).not.toBeVisible(); + await first.getByRole("button", { name: "Thinking", exact: true }).first().click(); + await expect(first.getByText(thoughts[0].text, { exact: true })).toBeVisible(); + for (const [text, count] of expectedCounts) + await expect(page.getByText(text, { exact: true })).toHaveCount(count); + await testInfo.attach("manual-expanded-reasoning", { + body: await page.screenshot(), + contentType: "image/png", + }); + const pointerEvents = await pointerCapture.evaluate(({ events, stop }) => { + stop(); + return events; + }); + await pointerCapture.dispose(); + await testInfo.attach("manual-pointer-events", { + body: JSON.stringify(pointerEvents, null, 2), + contentType: "application/json", + }); + await page.reload(); + await expect(badges).toHaveCount(thoughts.length); + await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 }); + for (let index = 0; index < thoughts.length; index++) { + await badges + .nth(index) + .getByRole("button", { name: "Thinking", exact: true }) + .first() + .click(); + await expect( + badges.nth(index).getByText(thoughts[index].text, { exact: true }), + ).toBeVisible(); + } + for (const [text, count] of expectedCounts) + await expect(page.getByText(text, { exact: true })).toHaveCount(count); + } catch (error) { + await testInfo.attach("manual-before-cleanup", { + body: await page.screenshot(), + contentType: "image/png", + }); + throw error; + } finally { + await historyClient.close(); + await agent.cleanup(); + } +}); diff --git a/packages/app/src/agent-stream/text-reveal.test.ts b/packages/app/src/agent-stream/text-reveal.test.ts index b6d88f1108..f8e847b694 100644 --- a/packages/app/src/agent-stream/text-reveal.test.ts +++ b/packages/app/src/agent-stream/text-reveal.test.ts @@ -12,6 +12,7 @@ import { TEXT_REVEAL_FRAME_INTERVAL_MS, TEXT_REVEAL_HORIZON_MS, visibleRevealedText, + withholdPartialClosingFence, } from "./text-reveal"; describe("computeRevealStep", () => { @@ -275,3 +276,127 @@ describe("trailing fragments from arrival boundaries", () => { expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose); }); }); + +describe("a closing fence still being typed", () => { + const code = "Intro\n\n```ts\nconst a = 1;\n"; + + it("holds back one or two backticks that can only become the closing fence", () => { + expect(withholdPartialClosingFence(`${code}\``)).toBe(code); + expect(withholdPartialClosingFence(`${code}\`\``)).toBe(code); + expect(withholdPartialClosingFence(`${code} \`\``)).toBe(code); + }); + + it.each([ + { char: "`", length: 3, whitespace: " " }, + { char: "`", length: 3, whitespace: "\t" }, + { char: "`", length: 4, whitespace: " " }, + { char: "`", length: 4, whitespace: "\t" }, + { char: "~", length: 3, whitespace: " " }, + { char: "~", length: 3, whitespace: "\t" }, + { char: "~", length: 5, whitespace: " " }, + { char: "~", length: 5, whitespace: "\t" }, + ])( + "paints real code after whitespace ends a $length $char run ($whitespace)", + ({ char, length, whitespace }) => { + const prefix = `${char.repeat(length)}\ncode\n`; + const run = char.repeat(length - 1); + expect(withholdPartialClosingFence(prefix + run)).toBe(prefix); + const text = prefix + run + whitespace; + expect(withholdPartialClosingFence(text)).toBe(text); + expect(visibleRevealedText(beginTextReveal(text), { streaming: true })).toBe(text); + }, + ); + + it("paints the fence once it closes the block", () => { + expect(withholdPartialClosingFence(`${code}\`\`\``)).toBe(`${code}\`\`\``); + expect(withholdPartialClosingFence(`${code}\`\`\`\n\nAfter`)).toBe(`${code}\`\`\`\n\nAfter`); + }); + + it("needs a run as long as the opener and of the same character", () => { + const long = "````md\nInside\n"; + expect(withholdPartialClosingFence(`${long}\`\`\``)).toBe(long); + expect(withholdPartialClosingFence(`${long}\`\`\`\``)).toBe(`${long}\`\`\`\``); + const tilde = "~~~\ncode\n"; + expect(withholdPartialClosingFence(`${tilde}~~`)).toBe(tilde); + expect(withholdPartialClosingFence(`${tilde}\``)).toBe(`${tilde}\``); + }); + + it.each([ + { lineEnding: "LF", newline: "\n", closer: "```" }, + { lineEnding: "CRLF", newline: "\r\n", closer: "```" }, + { lineEnding: "LF", newline: "\n", closer: "``` \t" }, + { lineEnding: "CRLF", newline: "\r\n", closer: "``` \t" }, + ])( + "recognizes completed closers before a tilde block with $lineEnding ($closer)", + ({ newline, closer }) => { + const backtickBlock = ["Intro", "```ts", "const a = 1;", closer, ""].join(newline); + const tildeBlock = backtickBlock + ["~~~md", "code", ""].join(newline); + + expect(withholdPartialClosingFence(tildeBlock + "~~")).toBe(tildeBlock); + expect(withholdPartialClosingFence(tildeBlock + "~~~")).toBe(tildeBlock + "~~~"); + expect(withholdPartialClosingFence(tildeBlock + "~~ not a closer")).toBe( + tildeBlock + "~~ not a closer", + ); + + const closedTildeBlock = tildeBlock + "~~~" + newline; + expect(withholdPartialClosingFence(closedTildeBlock + "`")).toBe(closedTildeBlock + "`"); + }, + ); + + it.each([ + { marker: "-", fence: "```", newline: "\n" }, + { marker: "1.", fence: "~~~", newline: "\n" }, + { marker: "-", fence: "~~~", newline: "\r\n" }, + { marker: "1.", fence: "```", newline: "\r\n" }, + ])( + "keeps prose after a closed $marker list fence ($fence, $newline)", + ({ marker, fence, newline }) => { + const indent = " ".repeat(marker.length + 1); + const closed = [`${marker} ${fence}`, `${indent}code`, `${indent}${fence}`, "", ""].join( + newline, + ); + const prose = closed + fence[0]; + expect(withholdPartialClosingFence(prose)).toBe(prose); + expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose); + const open = [`${marker} ${fence}`, `${indent}code`, ""].join(newline); + expect(withholdPartialClosingFence(open + indent + fence[0])).toBe(open); + }, + ); + + it("does not take an indented code block's fence for a top-level opener", () => { + const text = " code\n ```\n\n`"; + expect(withholdPartialClosingFence(text)).toBe(text); + }); + + it("leaves backticks alone outside a code block", () => { + expect(withholdPartialClosingFence("Prose\n`")).toBe("Prose\n`"); + const closed = "```\na\n```\n"; + expect(withholdPartialClosingFence(`${closed}\``)).toBe(`${closed}\``); + expect(withholdPartialClosingFence("`` inline ``\n`")).toBe("`` inline ``\n`"); + }); + + it("leaves a code line that only starts with backticks alone", () => { + expect(withholdPartialClosingFence(`${code}\`x`)).toBe(`${code}\`x`); + }); + + it("never paints a lone backtick line while a paced reveal crosses the closing fence", () => { + const full = `${code}\`\`\`\n\nAfter the block.`; + let state = retargetTextReveal(beginTextReveal(code), full); + const painted: string[] = []; + for (let frame = 0; frame < 120 && !isTextRevealSettled(state); frame += 1) { + state = advanceTextReveal(state, 16, 1_000); + painted.push(visibleRevealedText(state, { streaming: true })); + } + expect(painted.at(-1)).toBe(full); + for (const text of painted) { + expect(full.startsWith(text)).toBe(true); + expect(text.endsWith("\n`") || text.endsWith("\n``")).toBe(false); + } + }); + + it("holds the fence back when an arrival ends inside it, and paints it once the turn ends", () => { + const state = beginTextReveal(`${code}\``); + expect(visibleRevealedText(state, { streaming: true })).toBe(code); + expect(visibleRevealedText(state, { streaming: false })).toBe(`${code}\``); + }); +}); diff --git a/packages/app/src/agent-stream/text-reveal.ts b/packages/app/src/agent-stream/text-reveal.ts index 5c965f543b..b45eedd314 100644 --- a/packages/app/src/agent-stream/text-reveal.ts +++ b/packages/app/src/agent-stream/text-reveal.ts @@ -1,3 +1,5 @@ +import { createMarkdownParser } from "@/utils/markdown-parser"; + /** * Paced reveal for streaming assistant text. * @@ -207,6 +209,41 @@ function trimIncompleteTrailingCluster(text: string): string { return text; } +// Only parse block context when the current line can still become a closer. +const UNFINISHED_FENCE_RUN = /^ {0,3}(`+|~+)$/; +const fenceParser = createMarkdownParser({ linkify: false }).disable("inline"); + +/** + * Hold back the closing fence of a code block while it is still being typed. + * + * Inside an open fence, a last line holding one or two backticks is code until + * the third one arrives and closes the block. Painted, it adds a line of code + * that vanishes a frame later, so the block grows and shrinks and every row + * below it shifts twice. A paced reveal hands out these prefixes one character + * at a time, and an arrival boundary can end on one too. The line waits until it + * either closes the block or turns out to be code. + */ +export function withholdPartialClosingFence(text: string): string { + const lineStart = text.lastIndexOf("\n") + 1; + if (lineStart === 0) return text; + const run = UNFINISHED_FENCE_RUN.exec(text.slice(lineStart))?.[1]; + if (!run) return text; + // Source maps include container boundaries: a list closer must not become a + // new top-level opener, and a fence-looking line in indented code is not one. + const lastLine = text.split("\n").length - 1; + const open = fenceParser + .parse(text, {}) + .findLast( + (token) => + token.type === "fence" && + token.map !== null && + token.map[0] < lastLine && + token.map[1] === lastLine + 1, + ); + if (!open || open.markup[0] !== run[0] || run.length >= open.markup.length) return text; + return text.slice(0, lineStart); +} + /** Number of regional indicators at the end of `text`. A flag is a pair. */ function countTrailingRegionalIndicators(text: string): number { let count = 0; @@ -234,7 +271,12 @@ export function visibleRevealedText( options?: { streaming?: boolean }, ): string { if (state.revealed >= state.target.length) { - return options?.streaming ? trimIncompleteTrailingCluster(state.target) : state.target; + return options?.streaming + ? withholdPartialClosingFence(trimIncompleteTrailingCluster(state.target)) + : state.target; } - return state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed)); + // More text is already here, so a partial fence at the cut is certainly unfinished. + return withholdPartialClosingFence( + state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed)), + ); } diff --git a/packages/app/src/hooks/use-revealed-text.ts b/packages/app/src/hooks/use-revealed-text.ts index 6d7130927d..ac2d06bd21 100644 --- a/packages/app/src/hooks/use-revealed-text.ts +++ b/packages/app/src/hooks/use-revealed-text.ts @@ -10,6 +10,7 @@ import { retargetTextReveal, type TextRevealState, visibleRevealedText, + withholdPartialClosingFence, } from "@/agent-stream/text-reveal"; export type MarkdownPhase = "streaming" | "complete"; @@ -81,7 +82,9 @@ export function useRevealedText(text: string, phase: MarkdownPhase): string { }; }, [text, pacingSupported, phase]); - return pacingSupported - ? visibleRevealedText(stateRef.current, { streaming: phase === "streaming" }) - : text; + if (pacingSupported) { + return visibleRevealedText(stateRef.current, { streaming: phase === "streaming" }); + } + // Painted whole as it arrives, an arrival can still end inside a closing fence. + return phase === "streaming" ? withholdPartialClosingFence(text) : text; } diff --git a/packages/server/src/server/agent/providers/mock-load-test-agent.test.ts b/packages/server/src/server/agent/providers/mock-load-test-agent.test.ts index 21a2499cd8..1f83ddae28 100644 --- a/packages/server/src/server/agent/providers/mock-load-test-agent.test.ts +++ b/packages/server/src/server/agent/providers/mock-load-test-agent.test.ts @@ -507,6 +507,36 @@ describe("MockLoadTestAgentClient", () => { unsubscribe(); }); + test("closes each code block in two arrivals with a pause after the first backtick", async () => { + vi.useFakeTimers(); + const client = new MockLoadTestAgentClient(); + const session = await client.createSession({ + provider: "mock", + cwd: process.cwd(), + model: "e2e-fast-stream", + }); + const deltas: string[] = []; + const unsubscribe = session.subscribe((event) => { + if (event.type === "timeline" && event.item.type === "assistant_message") { + deltas.push(event.item.text); + } + }); + + const resultPromise = session.run("Stream a code block with a split closing fence."); + await vi.advanceTimersByTimeAsync(100); + expect(deltas).toEqual([expect.stringContaining("```ts\n"), "`"]); + // The lone backtick is all there is for most of the pause. + await vi.advanceTimersByTimeAsync(600); + expect(deltas.at(-1)).toBe("`"); + await vi.runAllTimersAsync(); + + const finalText = deltas.join(""); + await expect(resultPromise).resolves.toMatchObject({ finalText, canceled: false }); + expect(finalText.match(/^```$/gm)).toHaveLength(2); + expect(deltas.filter((delta) => delta === "`")).toHaveLength(2); + unsubscribe(); + }); + test("agent manager coalesces adjacent assistant tokens into fewer messages", async () => { vi.useFakeTimers(); const workdir = mkdtempSync(join(tmpdir(), "paseo-mock-load-test-")); diff --git a/packages/server/src/server/agent/providers/mock-load-test-agent.ts b/packages/server/src/server/agent/providers/mock-load-test-agent.ts index 368729529c..73ca6e1dd8 100644 --- a/packages/server/src/server/agent/providers/mock-load-test-agent.ts +++ b/packages/server/src/server/agent/providers/mock-load-test-agent.ts @@ -460,6 +460,25 @@ function parseLargeAgentStreamPayloadPrompt( }; } +/** + * A reply whose code blocks close in two arrivals: one backtick, a pause, then + * the other two. Providers and the daemon's coalescing window can end a delta + * anywhere, so this is the deterministic version of a closing fence that is + * still being typed when a frame paints. + */ +const SPLIT_CLOSING_FENCE_PAUSE_MS = 800; +const SPLIT_CLOSING_FENCE_CHUNKS: ReadonlyArray<{ text: string; pauseMs?: number }> = [ + { text: "Here is the first snippet:\n\n```ts\nconst answer = 42;\nconsole.log(answer);\n" }, + { text: "`", pauseMs: SPLIT_CLOSING_FENCE_PAUSE_MS }, + { text: "``\n\nAnd a second one:\n\n```sh\necho done\n" }, + { text: "`", pauseMs: SPLIT_CLOSING_FENCE_PAUSE_MS }, + { text: "``\n\nBoth blocks are closed." }, +]; + +function isSplitClosingFencePrompt(prompt: AgentPromptInput): boolean { + return /stream a code block with a split closing fence/i.test(promptToText(prompt)); +} + function parseAgentStreamStressPrompt(prompt: AgentPromptInput): AgentStreamStressRequest | null { const text = promptToText(prompt); const match = /emit\s+(\d+)\s+(coalesced\s+|tool\s+)?agent stream updates/i.exec(text); @@ -920,6 +939,7 @@ export class MockLoadTestAgentSession implements AgentSession { this.activeTurn = turn; const largePayload = parseLargeAgentStreamPayloadPrompt(prompt); const stress = parseAgentStreamStressPrompt(prompt); + const splitClosingFence = isSplitClosingFencePrompt(prompt); const questionPrompt = parseMockQuestionPrompt(prompt); const structuredBranchName = parseStructuredBranchNamePrompt(prompt); const settledAssistantImageMarkdown = parseSettledAssistantImageMarkdown(prompt); @@ -948,6 +968,8 @@ export class MockLoadTestAgentSession implements AgentSession { this.scheduleLargePayloadTurn(turn, largePayload); } else if (stress) { this.scheduleStressTurn(turn, stress); + } else if (splitClosingFence) { + this.scheduleSplitClosingFenceTurn(turn); } else { this.schedule(turn, 0); } @@ -1286,6 +1308,33 @@ export class MockLoadTestAgentSession implements AgentSession { turn.timer.unref?.(); } + private scheduleSplitClosingFenceTurn(turn: ActiveTurn): void { + const chunks = [...SPLIT_CLOSING_FENCE_CHUNKS]; + const finalText = chunks.map((chunk) => chunk.text).join(""); + const emitNext = () => { + if (this.activeTurn !== turn) { + return; + } + this.clearTurnTimer(turn); + this.emitTurnStarted(turn); + const chunk = chunks.shift(); + if (chunk === undefined) { + this.finishTurnWithText(turn, finalText); + return; + } + turn.emittedTokens += 1; + this.emitTimeline(turn.turnId, { + type: "assistant_message", + text: chunk.text, + messageId: turn.assistantMessageId, + }); + turn.timer = setTimeout(emitNext, chunk.pauseMs ?? this.streamingAssistantIntervalMs); + turn.timer.unref?.(); + }; + turn.timer = setTimeout(emitNext, 0); + turn.timer.unref?.(); + } + private scheduleStressTurn(turn: ActiveTurn, stress: AgentStreamStressRequest): void { turn.timer = setTimeout(() => { this.emitStressTurn(turn, stress);