Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Chat: stream long replies a block at a time (15a) (#651)

Oleksandr Ivanchenkof02416cad491
diff --git a/frontend/perf/stream/README.md b/frontend/perf/stream/README.md
index dc934ed5..186f2c53 100644
--- a/frontend/perf/stream/README.md
+++ b/frontend/perf/stream/README.md
@@ -5,6 +5,8 @@ part of the app build or the test suite.
`main.tsx` renders the real `SpaceApp` inside Shell's frame, with a faked `fetch` and `EventSource`: one chat of
`?n=` messages (default 300; prose, code blocks and lists, one comparison table and one line chart result).
+The streamed reply (~9,000 characters) cycles through prose with a list and a quote, a code block, a task
+list and a table. `window.__harness.finish()` lands it as the saved message.
`window.__harness.stream(count, perSecond)` then sends a turn of `count` text tokens at `perSecond`, the
way the server's events arrive.
@@ -16,6 +18,8 @@ way the server's events arrive.
| `scriptingMs`, `taskMs`, `layoutMs`, `styleMs` | CDP `Performance.getMetrics` deltas over the stream |
| `longestFrameMs`, `p95FrameMs`, `framesOver50`, `frames` | gaps between animation frames during the stream |
| `over50FirstHalf`, `over50SecondHalf` | where the slow frames fell |
+| `secondHalfFrames`, `secondHalfLongestMs`, `over50SecondHalfPct` | the stream's second half alone (15a) |
+| `load` | the machine's load average at the end of the run |
| `lastWordsShown` | the reply's last words are on screen at the end |
```sh
@@ -25,6 +29,7 @@ node perf/stream/run.mjs --n 300 --tokens 2000 --rate 50 --label after
node perf/stream/run.mjs --n 30 --tokens 2000 --rate 50
node perf/stream/run.mjs --n 300 --tokens 0 # 40 s idle: what the machine itself costs
node perf/stream/run.mjs --n 300 --width 390 --shot mid.png # screenshot at 60% of the stream
+node perf/stream/run.mjs --n 300 --end-shot end.png --final-shot final.png # last token in, then the reply landed
```
It needs `playwright-core` and a Chromium; point `PLAYWRIGHT_CORE` (path to its `index.mjs`) and `CHROMIUM`
diff --git a/frontend/perf/stream/main.tsx b/frontend/perf/stream/main.tsx
index e741053b..6d24d8ff 100644
--- a/frontend/perf/stream/main.tsx
+++ b/frontend/perf/stream/main.tsx
@@ -30,6 +30,9 @@ const prose = (i: number) =>
`**Step ${i}.** I read the notes and the two files you sent. Three things stand out:\n\n1. The *rates cache* is read before it is filled.\n2. The receipts list is sorted twice.\n3. The period ends one day early, see [the spec](https://example.com/spec).\n\n> Keep the old order for exports.\n\nI changed the first two and left the third for you to decide.`;
const list = (i: number) =>
`Checked ${i} items:\n\n- [x] invoices match\n- [x] totals add up\n- [ ] the March receipt is missing\n\nEverything else is in place.`;
+// Streamed only (15a): a table, so the live reply carries a list, a table and a code block.
+const table = (i: number) =>
+ `Totals for run ${i}:\n\n| Month | Invoices | Total |\n|---|---:|---:|\n| January | 14 | 2,310.00 |\n| February | 11 | 1,980.50 |\n| March | 9 | 1,402.75 |\n\nMarch is short one receipt.`;
const messages: unknown[] = [];
for (let i = 0; i < N; i++) {
if (i % 2 === 0) {
@@ -80,7 +83,7 @@ const emit = (ev: Record<string, unknown>) => streams.forEach((s) => s.readyStat
// ---- the reply that streams: ~2,000 tokens of mixed markdown, cut into 1-6 character tokens ----
const replyText = (() => {
let s = '';
- for (let i = 0; s.length < 9000; i++) s += `${[prose, code, list][i % 3](1000 + i)}\n\n`;
+ for (let i = 0; s.length < 9000; i++) s += `${[prose, code, list, table][i % 4](1000 + i)}\n\n`;
return s;
})();
const tokens: string[] = [];
@@ -92,7 +95,13 @@ for (let i = 0, k = 0; i < replyText.length; k++) {
declare global {
interface Window {
- __harness: { ready: () => boolean; stream: (count: number, perSecond: number) => Promise<{ sent: number; ms: number }>; tokens: number; streamed: () => string };
+ __harness: {
+ ready: () => boolean;
+ stream: (count: number, perSecond: number) => Promise<{ sent: number; ms: number }>;
+ tokens: number;
+ streamed: () => string;
+ finish: () => void;
+ };
}
}
let streamed = '';
@@ -100,6 +109,11 @@ window.__harness = {
tokens: tokens.length,
ready: () => document.querySelectorAll('[data-message-id]').length >= Math.min(N, 20),
streamed: () => streamed,
+ // The reply lands (15a shots): the saved message joins the history and the turn completes.
+ finish: () => {
+ messages.push({ id: 'm-final', sender_role: 'kwant', sender_id: 'Ada', text: streamed, results: null, channel_id: CTX, created_at: at(N), tokens_used: 400 });
+ emit({ type: 'TurnComplete', kwant_id: 'k1', context_id: CTX, turn_id: 't1', data: { tokens: 400 } });
+ },
// Sends `count` tokens at `perSecond`, on a timer, the way the server's events arrive.
stream: (count, perSecond) =>
new Promise((done) => {
diff --git a/frontend/perf/stream/run.mjs b/frontend/perf/stream/run.mjs
index 84cc12ac..af0822b9 100644
--- a/frontend/perf/stream/run.mjs
+++ b/frontend/perf/stream/run.mjs
@@ -7,6 +7,7 @@
// Needs playwright-core and a Chromium: PLAYWRIGHT_CORE=/path/to/playwright-core/index.mjs CHROMIUM=/path/to/chrome
import http from 'node:http';
import fs from 'node:fs';
+import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -20,6 +21,9 @@ const RATE = Number(arg('rate', 50));
const WIDTH = Number(arg('width', 1280));
const SHOT = arg('shot', '');
const LABEL = arg('label', '');
+// 15a: --end-shot after the last token (still streaming), --final-shot once the saved reply has landed.
+const END_SHOT = arg('end-shot', '');
+const FINAL_SHOT = arg('final-shot', '');
const { chromium } = await import(process.env.PLAYWRIGHT_CORE ?? '/home/maus/work/iris-ft-shots/node_modules/playwright-core/index.mjs');
const exe = process.env.CHROMIUM ?? '/home/maus/.cache/ms-playwright/chromium_headless_shell-1248/chrome-headless-shell-linux-arm64/chrome-headless-shell';
@@ -87,13 +91,15 @@ const out = await page.evaluate(() => {
const m = window.__m;
m.on = false;
const over50First = m.frames.slice(0, Math.floor(m.frames.length / 2)).filter((x) => x > 50).length;
+ // The reply's second half (by frame order): where a growing reply costs most (15a).
+ const second = m.frames.slice(Math.floor(m.frames.length / 2));
const f = m.frames.slice().sort((a, b) => a - b);
const pct = (p) => f[Math.min(f.length - 1, Math.floor((f.length * p) / 100))] ?? 0;
// The streamed text's last words are on screen once the stream ends (nothing late or lost).
const words = window.__harness.streamed().match(/[A-Za-z]{5,}/g) ?? [];
const tail = words.slice(-3).join(' ');
const shown = [...document.querySelectorAll('.markdown-content')].map((e) => e.textContent).join(' ').match(/[A-Za-z]{5,}/g) ?? [];
- return { over50First, commits: m.commits, frames: f.length, longest: f[f.length - 1] ?? 0, p95: pct(95), over50: f.filter((x) => x > 50).length, tail, tailShown: shown.join(' ').includes(tail) };
+ return { over50First, commits: m.commits, frames: f.length, longest: f[f.length - 1] ?? 0, p95: pct(95), over50: f.filter((x) => x > 50).length, tail, tailShown: shown.join(' ').includes(tail), secondFrames: second.length, secondLongest: Math.max(0, ...second) };
});
const secs = sent.ms / 1000;
const result = {
@@ -114,10 +120,22 @@ const result = {
framesOver50: out.over50,
over50FirstHalf: out.over50First,
over50SecondHalf: out.over50 - out.over50First,
+ secondHalfFrames: out.secondFrames,
+ secondHalfLongestMs: Math.round(out.secondLongest),
+ over50SecondHalfPct: out.secondFrames ? +((100 * (out.over50 - out.over50First)) / out.secondFrames).toFixed(2) : 0,
+ load: os.loadavg().map((x) => +x.toFixed(2)),
frames: out.frames,
lastWordsShown: out.tailShown,
errors,
};
console.log(JSON.stringify(result));
+if (END_SHOT) await page.screenshot({ path: END_SHOT });
+if (FINAL_SHOT) {
+ await page.evaluate(() => window.__harness.finish());
+ await page.waitForSelector('[data-message-id="m-final"]', { timeout: 30000 });
+ await page.waitForFunction(() => !document.querySelector('[data-live-bubble-body]'), null, { timeout: 30000 }).catch(() => {});
+ await page.waitForTimeout(800);
+ await page.screenshot({ path: FINAL_SHOT });
+}
await browser.close();
server.close();
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 57238e81..5bbcb82c 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -27,6 +27,7 @@ import { markNewSeen } from '../whatsNew';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
import { MarkdownRenderer } from './MarkdownRenderer';
+import { StreamMarkdown } from './StreamMarkdown';
import { ToolCallsList } from './ToolCallsList';
import { VirtualMachinePane, TerminalLogEntry } from './VirtualMachinePane';
import { playSfx } from '../audio/chiptune';
@@ -515,7 +516,8 @@ const useNarrow = () => {
/**
* The live reply's words or thinking line (14b): the one place that re-renders with the stream, at most
- * once a frame. The finished messages around it never do. `onGrow` keeps the bottom pinned.
+ * once a frame. The finished messages around it never do. `onGrow` keeps the bottom pinned. Its markdown
+ * renders a block at a time (15a, StreamMarkdown): only the open block at the end is parsed each frame.
*/
const StreamPart = React.memo(function StreamPart({ stream, part, onGrow }: { stream: StreamText; part: keyof StreamView; onGrow: () => void }) {
const streamingText = useStreamPart(stream, part);
@@ -523,7 +525,7 @@ const StreamPart = React.memo(function StreamPart({ stream, part, onGrow }: { st
if (part === 'thinking') return <>{streamingText}</>;
return (
<div className="kw-wa-in kw-wa-hold">
- <MarkdownRenderer content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} isStreaming={true} />
+ <StreamMarkdown content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} />
</div>
);
});
diff --git a/frontend/src/components/MarkdownRenderer.tsx b/frontend/src/components/MarkdownRenderer.tsx
index 0b4bb125..1948a36a 100644
--- a/frontend/src/components/MarkdownRenderer.tsx
+++ b/frontend/src/components/MarkdownRenderer.tsx
@@ -90,6 +90,8 @@ interface MarkdownRendererProps {
content: string;
className?: string;
isStreaming?: boolean;
+ /** The typing cursor after the text; while streaming by default. A finished streaming block has none (15a). */
+ cursor?: boolean;
/** The message's `results` (Smart Results). Only for a final bot reply. */
results?: unknown;
messageId?: string;
@@ -166,6 +168,7 @@ export const MarkdownRenderer = React.memo(function MarkdownRenderer({
content,
className = '',
isStreaming = false,
+ cursor = isStreaming,
results,
messageId,
}: MarkdownRendererProps) {
@@ -383,7 +386,7 @@ export const MarkdownRenderer = React.memo(function MarkdownRenderer({
/>
)}
- {isStreaming && (
+ {cursor && (
<span className="inline-block w-1.5 h-4 ml-0.5 align-middle bg-sky-400 animate-pulse rounded-sm" />
)}
</div>
diff --git a/frontend/src/components/StreamMarkdown.tsx b/frontend/src/components/StreamMarkdown.tsx
new file mode 100644
index 00000000..4eb36526
--- /dev/null
+++ b/frontend/src/components/StreamMarkdown.tsx
@@ -0,0 +1,24 @@
+import React from 'react';
+import { MarkdownRenderer } from './MarkdownRenderer';
+import { splitStreamBlocks } from '../streamBlocks';
+
+// A paragraph that ends a finished block keeps its usual gap below (MarkdownRenderer gives the last paragraph
+// `last:mb-0`), so the blocks read exactly as one text would. Other margins collapse across the blocks.
+const BLOCKS = '[&>.markdown-content:not(:last-child)>p:last-child]:mb-3';
+
+/**
+ * The live reply's markdown (15a). Finished blocks render once each, memoized: their content never changes
+ * again, so React skips them. Only the open block at the end is parsed again each frame, and only it carries
+ * the typing cursor. The final message
+ * renders whole through MarkdownRenderer, so any difference in how the text was cut is gone when it lands.
+ */
+export const StreamMarkdown = React.memo(function StreamMarkdown({ content }: { content: string }) {
+ const blocks = splitStreamBlocks(content);
+ return (
+ <div className={BLOCKS} data-stream-blocks={blocks.length}>
+ {blocks.map((block, i) => (
+ <MarkdownRenderer key={i} content={block} isStreaming={true} cursor={i === blocks.length - 1} />
+ ))}
+ </div>
+ );
+});
diff --git a/frontend/src/streamBlocks.ts b/frontend/src/streamBlocks.ts
new file mode 100644
index 00000000..6559f5c2
--- /dev/null
+++ b/frontend/src/streamBlocks.ts
@@ -0,0 +1,81 @@
+// Streaming markdown, a block at a time (15a).
+//
+// While a reply streams, its markdown is parsed again every frame. For a long reply that is the whole cost of
+// the frame, and it grows with the reply. `splitStreamBlocks` cuts the text into finished blocks plus one open
+// block at the end, so the finished ones can render once each (memoized) and only the open one is parsed per
+// frame. The final message never goes through here: it renders whole, as before.
+//
+// A block ends at a blank line outside a code fence, unless the next line carries on the same construct (a
+// list, an indented code block or continuation, a table, a block quote). When unsure it does not split: a
+// bigger open block is only slower, never wrong. Joining the blocks always gives back the text exactly.
+
+/** An opening code fence: ``` or ~~~, three or more, any indent (a fence inside a list item is indented). */
+const FENCE_OPEN = /^([ \t]*)(`{3,}|~{3,})(.*)$/;
+/** A closing fence: only the fence characters and trailing spaces. */
+const FENCE_CLOSE = /^([ \t]*)(`{3,}|~{3,})[ \t]*$/;
+/** A list item: a bullet or a number with . or ), then a space or the line's end. */
+const LIST_ITEM = /^ {0,3}(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$)/;
+/** A link reference or footnote definition: it can reach back to an earlier block, so such text is not split. */
+const DEFINITION = /^ {0,3}\[[^\]\n]+\]:/m;
+
+const indentOf = (s: string) => s.length - s.replace(/^[ \t]+/, '').length;
+
+/**
+ * True when the line still being typed already says what it starts: its first word is complete, or it is long.
+ * Before that, "2" could still become "2. item" and " " could become an indented code line.
+ */
+const decidable = (partial: string) => /^[ \t]*\S+[ \t]/.test(partial) || partial.length >= 16;
+
+/** Whether a blank line between `prev` (last non-blank line) and `next` may end a block. */
+function mayEnd(prev: string, next: string, inList: boolean): boolean {
+ // Indented: an indented code block, or a list item's continuation.
+ if (/^(?: {4}|\t)/.test(next)) return false;
+ // A list goes on (a loose list, a nested item, an item's later paragraph).
+ if (inList && (LIST_ITEM.test(next) || /^[ \t]/.test(next))) return false;
+ // A table row or a block quote right after one.
+ if (/^ {0,3}\|/.test(next) && prev.includes('|')) return false;
+ if (/^ {0,3}>/.test(next) && /^ {0,3}>/.test(prev)) return false;
+ return true;
+}
+
+/** Cuts a streaming reply into finished blocks and one open block (the last). Joined, they equal `text`. */
+export function splitStreamBlocks(text: string): string[] {
+ if (!text) return [];
+ if (DEFINITION.test(text)) return [text];
+ const blocks: string[] = [];
+ let start = 0; // where the open block starts
+ let fence: { ch: string; len: number; indent: number } | null = null;
+ let inList = false; // the open block holds a list item
+ let prev = ''; // the open block's last non-blank line
+ let blank = false; // a blank line came after `prev`
+ let pos = 0;
+ while (pos < text.length) {
+ const nl = text.indexOf('\n', pos);
+ const complete = nl >= 0;
+ const line = complete ? text.slice(pos, nl) : text.slice(pos);
+ if (fence) {
+ const c = complete ? FENCE_CLOSE.exec(line) : null;
+ if (c && c[2][0] === fence.ch && c[2].length >= fence.len && indentOf(line) <= fence.indent + 3) fence = null;
+ prev = line;
+ } else if (line.trim() === '') {
+ if (complete) blank = true;
+ } else {
+ // A blank line, then this line: the block before may be finished.
+ if (blank && prev && (complete || decidable(line)) && mayEnd(prev, line, inList)) {
+ blocks.push(text.slice(start, pos));
+ start = pos;
+ inList = false;
+ }
+ blank = false;
+ const f = FENCE_OPEN.exec(line);
+ // A backtick fence's info string has no backtick (``` `x` ``` is inline code, not a fence).
+ if (f && complete && !(f[2][0] === '`' && f[3].includes('`'))) fence = { ch: f[2][0], len: f[2].length, indent: f[1].length };
+ if (LIST_ITEM.test(line)) inList = true;
+ prev = line;
+ }
+ if (!complete) break;
+ pos = nl + 1;
+ }
+ blocks.push(text.slice(start));
+ return blocks;
+}
diff --git a/frontend/tests/smoothStreaming.test.mjs b/frontend/tests/smoothStreaming.test.mjs
index 78bd0cd6..f2d145fe 100644
--- a/frontend/tests/smoothStreaming.test.mjs
+++ b/frontend/tests/smoothStreaming.test.mjs
@@ -155,12 +155,18 @@ test('streaming 100 tokens re-renders no finished message and the live reply at
}
}
const finished = renders.filter((r) => isMarkdown(r) && !r.props.isStreaming);
- const live = renders.filter((r) => isMarkdown(r) && r.props.isStreaming);
+ // 15a: the live reply renders a block at a time. Its open block (the one with the cursor) renders at most
+ // once a frame; a block that finished renders once more without the cursor, and never again.
+ const live = renders.filter((r) => isMarkdown(r) && r.props.isStreaming && r.props.cursor !== false);
+ const closed = renders.filter((r) => isMarkdown(r) && r.props.isStreaming && r.props.cursor === false);
+ const blocks = Number(host.querySelector('[data-stream-blocks]').getAttribute('data-stream-blocks'));
const chat = renders.filter((r) => r.name === 'ChatView');
assert.equal(shown, 25);
assert.equal(finished.length, 0, 'finished messages stay as they are');
assert.ok(live.length <= shown, `live reply rendered ${live.length} times for ${shown} frames`);
assert.ok(live.length >= shown - 1, 'and it did render each frame');
+ assert.ok(blocks > 5, `${blocks} blocks`);
+ assert.ok(closed.length <= blocks - 1, `${closed.length} renders of ${blocks - 1} finished blocks`);
assert.ok(chat.length <= 1, `ChatView rendered ${chat.length} times: only when the reply first has text`);
assert.match(host.textContent, /w98/, 'the last token is on screen');
} finally {
diff --git a/frontend/tests/streamingMarkdown.test.mjs b/frontend/tests/streamingMarkdown.test.mjs
new file mode 100644
index 00000000..57f7492e
--- /dev/null
+++ b/frontend/tests/streamingMarkdown.test.mjs
@@ -0,0 +1,210 @@
+// 15a streaming-markdown: a streaming reply is cut into finished blocks plus one open block, so each frame
+// parses only the open block. The splitter's cases, "the blocks join back to the text", "the blocks render as
+// the whole text would", and a render count: each finished block renders once with its final text.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+// React DevTools' hook, reduced to counting which components rendered in each commit (as in smoothStreaming).
+const renders = [];
+g.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
+ supportsFiber: true,
+ isDisabled: false,
+ renderers: new Map(),
+ inject() {
+ return 1;
+ },
+ onCommitFiberRoot(_id, root) {
+ const walk = (next) => {
+ const prev = next.alternate;
+ if (typeof next.type === 'function' && (!prev || next.flags & 1)) renders.push({ name: next.type.name, props: next.memoizedProps });
+ if (prev && next.child === prev.child) return;
+ for (let c = next.child; c; c = c.sibling) walk(c);
+ };
+ walk(root.current);
+ },
+ onCommitFiberUnmount() {},
+ onPostCommitFiberRoot() {},
+ checkDCE() {},
+};
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { splitStreamBlocks } from './src/streamBlocks';
+ export { StreamMarkdown } from './src/components/StreamMarkdown';
+ export { MarkdownRenderer } from './src/components/MarkdownRenderer';
+`);
+const { React, createRoot, flushSync, renderToStaticMarkup, splitStreamBlocks, StreamMarkdown, MarkdownRenderer } = m;
+const h = React.createElement;
+
+/** Splits, checks the blocks join back to the text, and returns them. */
+const split = (text) => {
+ const blocks = splitStreamBlocks(text);
+ assert.equal(blocks.join(''), text, 'the joined blocks equal the text');
+ return blocks;
+};
+
+/** The markdown's HTML inside its wrapper(s), with the whitespace between tags dropped. */
+const inner = (html) => html.replace(/<div class="markdown-content[^"]*">/g, '').replace(/<\/div>$/g, '').replace(/>\s+</g, '><');
+const whole = (text) => inner(renderToStaticMarkup(h(MarkdownRenderer, { content: text, isStreaming: true })));
+const byBlocks = (text) =>
+ split(text)
+ .map((b, i, all) => inner(renderToStaticMarkup(h(MarkdownRenderer, { content: b, isStreaming: true, cursor: i === all.length - 1 }))))
+ .join('');
+/** The blocks, rendered one by one, give the same HTML as the whole text. */
+const sameAsWhole = (text) => assert.equal(byBlocks(text), whole(text), `renders as one text would:\n${text}`);
+
+test('paragraphs: each one is a block, the last one open', () => {
+ assert.deepEqual(split('One.\n\nTwo.\n\nThree is still'), ['One.\n\n', 'Two.\n\n', 'Three is still']);
+ assert.deepEqual(split(''), []);
+ assert.deepEqual(split('Only one line'), ['Only one line']);
+ sameAsWhole('One.\n\nTwo.\n\nThree.\n');
+});
+
+test('a code fence with blank lines inside stays one block (``` and ~~~, any length)', () => {
+ const text = 'Intro:\n\n```ts\nconst a = 1;\n\nconst b = 2;\n```\n\nAfter it.\n';
+ assert.deepEqual(split(text), ['Intro:\n\n', '```ts\nconst a = 1;\n\nconst b = 2;\n```\n\n', 'After it.\n']);
+ sameAsWhole(text);
+ // A shorter fence does not close a longer one, and a ~~~ fence is not closed by ```.
+ const tildes = 'Intro.\n\n~~~~\nx\n\n~~~\n\n```\n\ny\n~~~~\n\nEnd.\n';
+ assert.deepEqual(split(tildes), ['Intro.\n\n', '~~~~\nx\n\n~~~\n\n```\n\ny\n~~~~\n\n', 'End.\n']);
+ sameAsWhole(tildes);
+ // An indented fence inside a list item.
+ const nested = '- step:\n\n ```sh\n npm test\n\n npm run build\n ```\n\nDone.\n';
+ assert.deepEqual(split(nested), ['- step:\n\n ```sh\n npm test\n\n npm run build\n ```\n\n', 'Done.\n']);
+ sameAsWhole(nested);
+});
+
+test('a fence left open at the end is all in the open block', () => {
+ const text = 'Intro.\n\n```py\nx = 1\n\ny = 2\n\n';
+ assert.deepEqual(split(text), ['Intro.\n\n', '```py\nx = 1\n\ny = 2\n\n']);
+ sameAsWhole(text);
+});
+
+test('a loose list stays one block; a tight one ends at its blank line', () => {
+ const loose = '- one\n\n- two\n\n- three\n\nDone.\n';
+ assert.deepEqual(split(loose), ['- one\n\n- two\n\n- three\n\n', 'Done.\n']);
+ sameAsWhole(loose);
+ assert.match(whole(loose), /<li[^>]*><p/, 'loose: items hold paragraphs');
+ const tight = 'Plan:\n\n1. read\n2. fix\n3. test\n\nThen ship.\n';
+ assert.deepEqual(split(tight), ['Plan:\n\n', '1. read\n2. fix\n3. test\n\n', 'Then ship.\n']);
+ sameAsWhole(tight);
+});
+
+test('an ordered list with a start number keeps it, loose or tight', () => {
+ const text = 'From step 3:\n\n3. three\n\n4. four\n\n5) five\n\nEnd.\n';
+ const blocks = split(text);
+ // "5)" starts a new list (another delimiter); it stays in the same block, which is never wrong.
+ assert.equal(blocks[1], '3. three\n\n4. four\n\n5) five\n\n');
+ sameAsWhole(text);
+});
+
+test('a nested list and an item continued after a blank line stay with their list', () => {
+ const text = '- a\n - b\n\n - c\n- d\n\n more about d\n\nAfter.\n';
+ assert.deepEqual(split(text), ['- a\n - b\n\n - c\n- d\n\n more about d\n\n', 'After.\n']);
+ sameAsWhole(text);
+});
+
+test('a table is one block, and a row after a blank line does not split from it', () => {
+ const text = 'Totals:\n\n| Month | Total |\n|---|---:|\n| Jan | 2,310.00 |\n| Feb | 1,980.50 |\n\nMarch is short.\n';
+ assert.deepEqual(split(text), ['Totals:\n\n', '| Month | Total |\n|---|---:|\n| Jan | 2,310.00 |\n| Feb | 1,980.50 |\n\n', 'March is short.\n']);
+ sameAsWhole(text);
+ assert.equal(split('| a | b |\n|---|---|\n| 1 | 2 |\n\n| 3 | 4 |\n').length, 1);
+});
+
+test('a block quote goes on across a blank line; indented code is not cut', () => {
+ const quote = '> one\n\n> two\n\nAfter.\n';
+ assert.deepEqual(split(quote), ['> one\n\n> two\n\n', 'After.\n']);
+ sameAsWhole(quote);
+ const indented = 'Text.\n\n code\n\n more\n\nEnd.\n';
+ assert.deepEqual(split(indented), ['Text.\n\n code\n\n more\n\n', 'End.\n']);
+ sameAsWhole(indented);
+});
+
+test('when unsure it does not split: a line still undecided, and reference definitions', () => {
+ // "2" could still become "2. item" of the list above.
+ assert.deepEqual(split('- a\n\n2'), ['- a\n\n2']);
+ assert.deepEqual(split('- a\n\n2. b'), ['- a\n\n2. b']);
+ // A first word typed out says enough.
+ assert.deepEqual(split('Para.\n\nNext words'), ['Para.\n\n', 'Next words']);
+ // A link reference or footnote definition can reach back to an earlier block.
+ assert.deepEqual(split('See [the spec].\n\n[the spec]: https://example.com\n'), ['See [the spec].\n\n[the spec]: https://example.com\n']);
+ assert.equal(split('A note[^1].\n\nMore.\n\n[^1]: The note.\n').length, 1);
+});
+
+// A reply like the harness streams: prose with a list and a quote, a code block, a task list and a table.
+const REPLY = (() => {
+ const prose = (i) => `**Step ${i}.** I read the notes. Three things stand out:\n\n1. The *rates cache* is read early.\n2. The list is sorted twice.\n3. The period ends a day early, see [the spec](https://example.com/spec).\n\n> Keep the old order for exports.\n\nI changed the first two.`;
+ const code = (i) => `Here is the fix for step ${i}:\n\n\`\`\`ts\nexport function total(rows: Row[]): number {\n let sum = 0;\n\n for (const r of rows) sum += r.amount;\n return sum;\n}\n\`\`\`\n\nRun \`npm test\` after it.`;
+ const list = (i) => `Checked ${i} items:\n\n- [x] invoices match\n- [x] totals add up\n- [ ] the March receipt is missing\n\nEverything else is in place.`;
+ const table = (i) => `Totals for run ${i}:\n\n| Month | Invoices | Total |\n|---|---:|---:|\n| January | 14 | 2,310.00 |\n| March | 9 | 1,402.75 |\n\nMarch is short one receipt.`;
+ let s = '';
+ for (let i = 0; i < 12; i++) s += `${[prose, code, list, table][i % 4](i)}\n\n`;
+ return s;
+})();
+
+test('as a reply grows, finished blocks never change, and the whole reply renders as one text would', () => {
+ let finished = [];
+ for (let n = 1; n <= REPLY.length; n++) {
+ const blocks = split(REPLY.slice(0, n));
+ const done = blocks.slice(0, -1);
+ assert.deepEqual(done.slice(0, finished.length), finished, `at ${n} characters a finished block changed`);
+ finished = done;
+ }
+ assert.ok(finished.length >= 30, `${finished.length} finished blocks`);
+ sameAsWhole(REPLY);
+ // And at each line end on the way (a reply cut anywhere mid-stream).
+ for (let n = REPLY.indexOf('\n'); n > 0; n = REPLY.indexOf('\n', n + 1)) if (n % 5 === 0) sameAsWhole(REPLY.slice(0, n + 1));
+});
+
+test('StreamMarkdown renders each finished block once with its final text; only the open block each frame', () => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ const markdown = () => renders.filter((r) => /^MarkdownRenderer\d*$/.test(r.name));
+ try {
+ renders.length = 0;
+ let frames = 0;
+ for (let n = 40; n < REPLY.length; n += 40) {
+ flushSync(() => root.render(h(StreamMarkdown, { content: REPLY.slice(0, n) })));
+ frames++;
+ }
+ flushSync(() => root.render(h(StreamMarkdown, { content: REPLY })));
+ frames++;
+ const blocks = splitStreamBlocks(REPLY);
+ const all = markdown();
+ for (const [i, b] of blocks.slice(0, -1).entries()) {
+ // Once finished (no cursor) it never renders again; before that it was the open block.
+ // (The sample repeats some blocks word for word: each copy renders once.)
+ const copies = blocks.slice(0, -1).filter((x) => x === b).length;
+ const n = all.filter((r) => r.props.content === b && r.props.cursor === false).length;
+ assert.equal(n, copies, `finished block ${i} rendered ${n} times once finished (${copies} copies)`);
+ }
+ // Each frame: the open block, plus a block that just finished (re-cut once) and one just opened.
+ assert.ok(all.length <= frames + 2 * blocks.length, `${all.length} renders for ${frames} frames and ${blocks.length} blocks`);
+ assert.ok(all.every((r) => r.props.isStreaming === true), 'streaming blocks render as streaming (no smart results)');
+ assert.equal(host.querySelectorAll('.animate-pulse').length, 1, 'one typing cursor, after the open block');
+ assert.ok(host.querySelector('.markdown-content:last-child .animate-pulse'));
+ assert.equal(host.querySelectorAll('.markdown-content').length, blocks.length);
+ assert.equal(host.querySelector('[data-stream-blocks]').getAttribute('data-stream-blocks'), String(blocks.length));
+ assert.match(host.textContent, /March is short one receipt\./);
+ } finally {
+ flushSync(() => root.unmount());
+ }
+});
+
+test('a paragraph ending a finished block keeps its gap below (the class the blocks wrapper carries)', () => {
+ const html = renderToStaticMarkup(h(StreamMarkdown, { content: 'One.\n\nTwo words.' }));
+ assert.match(html, /^<div class="\[&amp;&gt;\.markdown-content:not\(:last-child\)&gt;p:last-child\]:mb-3" data-stream-blocks="2">/);
+});
diff --git a/frontend/tests/workingAvatar.test.mjs b/frontend/tests/workingAvatar.test.mjs
index 40a84509..7cd7d2df 100644
--- a/frontend/tests/workingAvatar.test.mjs
+++ b/frontend/tests/workingAvatar.test.mjs
@@ -47,7 +47,8 @@ test('a different speaker draws a different bot (team discussions follow the cur
test('the scene replaces the grey lines; the first words keep its height and fade in once', () => {
assert.doesNotMatch(chat, /kws-skel|Waiting for the first words/);
- assert.match(chat, /<div className="kw-wa-in kw-wa-hold">\s+<MarkdownRenderer content=\{hideStreamingDecisions\(stripDiscussionMarkers\(streamingText\)\)\} isStreaming=\{true\} \/>/);
+ // 15a: the live reply renders through StreamMarkdown (a block at a time), with the same cleaned text.
+ assert.match(chat, /<div className="kw-wa-in kw-wa-hold">\s+<StreamMarkdown content=\{hideStreamingDecisions\(stripDiscussionMarkers\(streamingText\)\)\} \/>/);
assert.match(css, /\.kw-wa-hold \{ min-height: 62px; \}/);
assert.match(css, /\.kw-wa \{[^}]*height: 62px;/);
assert.match(css, /\.kw-wa-scene \{[^}]*flex: none;[^}]*height: 54px;/);