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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Chat: stream the reply once per frame, finished messages stay still (14b smooth-streaming) (#642)
Oleksandr Ivanchenko0a984c4fb095
diff --git a/frontend/perf/stream/README.md b/frontend/perf/stream/README.mdnew file mode 100644index 00000000..dc934ed5--- /dev/null+++ b/frontend/perf/stream/README.md@@ -0,0 +1,31 @@+# Streaming harness (dev only)++Measures what a streaming reply costs the browser in a long chat (roadmap 14b smooth-streaming). It is not+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).+`window.__harness.stream(count, perSecond)` then sends a turn of `count` text tokens at `perSecond`, the+way the server's events arrive.++`run.mjs` serves the build, opens it in headless Chromium, runs the stream and prints one JSON line:++| field | what |+|---|---|+| `commitsPerSecond`, `commits` | React commits during the stream (a devtools hook counts them) |+| `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 |+| `lastWordsShown` | the reply's last words are on screen at the end |++```sh+cd frontend+npx vite build --config perf/stream/vite.config.mts # on the team server: through bin/heavy+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+```++It needs `playwright-core` and a Chromium; point `PLAYWRIGHT_CORE` (path to its `index.mjs`) and `CHROMIUM`+at them. Numbers depend on the machine and its load: compare runs from the same machine and the same hour.diff --git a/frontend/perf/stream/index.html b/frontend/perf/stream/index.htmlnew file mode 100644index 00000000..69373cfa--- /dev/null+++ b/frontend/perf/stream/index.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title>kwant stream harness</title>+ </head>+ <body class="bg-zinc-950 text-zinc-100 antialiased overflow-hidden font-sans">+ <div id="root"></div>+ <script type="module" src="./main.tsx"></script>+ </body>+</html>diff --git a/frontend/perf/stream/main.tsx b/frontend/perf/stream/main.tsxnew file mode 100644index 00000000..e741053b--- /dev/null+++ b/frontend/perf/stream/main.tsx@@ -0,0 +1,148 @@+// Streaming harness (dev only, never shipped; perf/stream/README.md). The real SpaceApp, with the server+// faked in the page: one channel holding ?n= messages (default 300: markdown, code blocks, a table and a+// chart result), and an event stream the runner drives through window.__stream.+import { FIXTURES } from '../../src/components/results/fixtures';+// The app's own stylesheets, as main.tsx loads them.+import '../../src/styles/fonts.css';+import '../../src/styles/modern.css';+import '../../src/styles/stream.css';+import '../../src/styles/needsYou.css';+import '../../src/styles/ideas.css';+import '../../src/styles/ideaShell.css';+import '../../src/styles/devStatus.css';+import '../../src/styles/tickets.css';+import '../../src/styles/telegram.css';+import '../../src/styles/showOnce.css';+import '../../src/styles/gettingStarted.css';+import '../../src/styles/dropLayer.css';+import { trackAppHeight } from '../../src/pwa';++const q = new URLSearchParams(location.search);+const N = Number(q.get('n') ?? 300);+const CTX = 'ch1';+const T0 = Date.parse('2026-11-14T09:00:00Z');+const at = (i: number) => new Date(T0 + i * 60_000).toISOString();++// ---- 300 messages: alternating person / bot, the bot's replies cycling through shapes ----+const code = (i: number) =>+ `Here is the fix for step ${i}:\n\n\`\`\`ts\nexport function total(rows: Row[]): number {\n let sum = 0;\n for (const r of rows) sum += r.amount * (1 + r.tax);\n return Math.round(sum * 100) / 100;\n}\n\`\`\`\n\nRun \`npm test\` after it.`;+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.`;+const messages: unknown[] = [];+for (let i = 0; i < N; i++) {+ if (i % 2 === 0) {+ messages.push({ id: `m${i}`, sender_role: 'user', sender_id: 'user', text: `Question ${i}: can you check the next part?`, channel_id: CTX, created_at: at(i) });+ continue;+ }+ let text: string;+ let results: unknown = null;+ if (i === 41) ({ reply: text, results } = FIXTURES.comparison as { reply: string; results: unknown });+ else if (i === 83) ({ reply: text, results } = FIXTURES.chartLine as { reply: string; results: unknown });+ else text = [prose, code, list][Math.floor(i / 2) % 3](i);+ messages.push({ id: `m${i}`, sender_role: 'kwant', sender_id: 'Ada', text, results, channel_id: CTX, created_at: at(i), tokens_used: 400 });+}++// ---- the server ----+const bot = (id: string, name: string, title: string) => ({ id, name, title, persona_prompt: '', avatar_sprite: 'mouse', driver_type: 'claude', preferred_model: '' });+const routes: Record<string, unknown> = {+ '/api/kwants': [bot('k1', 'Ada', 'Tech lead'), bot('k2', 'Lin', 'Backend')],+ '/api/channels': [{ id: CTX, name: 'general', kwant_ids: ['k1', 'k2'], created_at: '' }],+ '/api/teams': [],+ '/api/engines': [{ id: 'claude', kind: 'cli', enabled: true, status: 'ready', ready: true }],+ '/api/automation-discovery': { setting: 'off', daily_cap: 3, blocked_by: [], last_scan_at: null, suggestions: [], stats: {} },+ [`/api/channels/${CTX}/messages`]: messages,+};+const json = (b: unknown) => new Response(JSON.stringify(b), { status: 200, headers: { 'Content-Type': 'application/json' } });+window.fetch = async (url: RequestInfo | URL, init?: RequestInit) => {+ const path = String(url instanceof Request ? url.url : url).replace(location.origin, '').split('?')[0];+ return json(path in routes ? routes[path] : init?.method === 'PUT' || init?.method === 'POST' ? {} : []);+};+const streams: FakeEvents[] = [];+class FakeEvents {+ onmessage: ((e: { data: string }) => void) | null = null;+ onerror: (() => void) | null = null;+ onopen: (() => void) | null = null;+ readyState = 1;+ constructor() {+ streams.push(this);+ }+ addEventListener() {}+ removeEventListener() {}+ close() {+ this.readyState = 2;+ }+}+(window as unknown as { EventSource: unknown }).EventSource = FakeEvents;+const emit = (ev: Record<string, unknown>) => streams.forEach((s) => s.readyState === 1 && s.onmessage?.({ data: JSON.stringify(ev) }));++// ---- 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`;+ return s;+})();+const tokens: string[] = [];+for (let i = 0, k = 0; i < replyText.length; k++) {+ const len = 1 + ((k * 7) % 6);+ tokens.push(replyText.slice(i, i + len));+ i += len;+}++declare global {+ interface Window {+ __harness: { ready: () => boolean; stream: (count: number, perSecond: number) => Promise<{ sent: number; ms: number }>; tokens: number; streamed: () => string };+ }+}+let streamed = '';+window.__harness = {+ tokens: tokens.length,+ ready: () => document.querySelectorAll('[data-message-id]').length >= Math.min(N, 20),+ streamed: () => streamed,+ // Sends `count` tokens at `perSecond`, on a timer, the way the server's events arrive.+ stream: (count, perSecond) =>+ new Promise((done) => {+ emit({ type: 'turn_started', kwant_id: 'k1', context_id: CTX, data: { turn_id: 't1', kwant_id: 'k1', context_id: CTX } });+ const t0 = performance.now();+ let sent = 0;+ const tick = () => {+ // Catch up when a long frame held the timer back, as the event stream would.+ const due = Math.min(count, Math.floor(((performance.now() - t0) / 1000) * perSecond) + 1);+ while (sent < due) {+ const tok = tokens[sent % tokens.length];+ streamed += tok;+ emit({ type: 'TextDelta', kwant_id: 'k1', context_id: CTX, turn_id: 't1', data: tok });+ sent++;+ }+ if (sent >= count) return done({ sent, ms: performance.now() - t0 });+ setTimeout(tick, 1000 / perSecond);+ };+ tick();+ }),+};++const [{ default: React }, { createRoot }, { SpaceApp }] = await Promise.all([import('react'), import('react-dom/client'), import('../../src/App')]);+const space = { id: 'spc_default', name: 'Default', icon: '', color: '#f59e0b', sort: 0, is_default: true, archived_at: null, created_at: '', general_channel_id: CTX, counts: { bots: 2, ready_accounts: 1, unread: 0 } };+const noop = () => {};+trackAppHeight();+// Shell's frame (Shell.tsx), so the chat scrolls inside the window the way it does in the app.+const frame = (child: React.ReactNode) =>+ React.createElement(+ 'div',+ { className: 'h-[var(--kwnt-app-height,100dvh)] w-screen flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden font-sans' },+ React.createElement('div', { className: 'flex-1 min-h-0 flex' }, child),+ );+createRoot(document.getElementById('root')!).render(+ frame(React.createElement(SpaceApp as React.FC<Record<string, unknown>>, {+ space,+ spaces: [space],+ initialTarget: { channelId: CTX },+ onSwitchSpace: noop,+ onCreateSpace: noop,+ onOpenArchived: noop,+ onSpacesChanged: noop,+ onSpaceArchived: noop,+ onChatChange: noop,+ })),+);diff --git a/frontend/perf/stream/run.mjs b/frontend/perf/stream/run.mjsnew file mode 100644index 00000000..84cc12ac--- /dev/null+++ b/frontend/perf/stream/run.mjs@@ -0,0 +1,123 @@+// Streaming harness runner (dev only; perf/stream/README.md). Serves perf/stream/dist, opens it in headless+// Chromium, streams tokens into a chat of --n messages and prints what the stream cost:+// commits/s React commits per second during the stream (a devtools hook counts them)+// scripting CDP ScriptDuration over the stream, in ms+// longest frame the longest gap between animation frames during the stream, in ms (plus how many went over 50 ms)+// Usage: node perf/stream/run.mjs --n 300 --tokens 2000 --rate 50 [--width 1280] [--shot file.png] [--label after]+// 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 path from 'node:path';+import { fileURLToPath } from 'node:url';++const arg = (k, d) => {+ const i = process.argv.indexOf(`--${k}`);+ return i > 0 ? process.argv[i + 1] : d;+};+const N = Number(arg('n', 300));+const TOKENS = Number(arg('tokens', 2000));+const RATE = Number(arg('rate', 50));+const WIDTH = Number(arg('width', 1280));+const SHOT = arg('shot', '');+const LABEL = arg('label', '');+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';++const dist = path.join(path.dirname(fileURLToPath(import.meta.url)), 'dist');+const types = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png' };+const server = http.createServer((req, res) => {+ const p = decodeURIComponent(new URL(req.url, 'http://x').pathname);+ const file = path.join(dist, p === '/' ? 'index.html' : p);+ if (!file.startsWith(dist) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) return res.writeHead(404).end();+ res.writeHead(200, { 'Content-Type': types[path.extname(file)] ?? 'application/octet-stream' }).end(fs.readFileSync(file));+});+await new Promise((r) => server.listen(0, '127.0.0.1', r));+const base = `http://127.0.0.1:${server.address().port}`;++const browser = await chromium.launch({ executablePath: exe });+const phone = WIDTH < 500;+const ctx = await browser.newContext({ viewport: { width: WIDTH, height: phone ? 844 : 800 }, deviceScaleFactor: phone ? 2 : 1, isMobile: phone, hasTouch: phone, colorScheme: 'dark', reducedMotion: 'reduce' });+const page = await ctx.newPage();+const errors = [];+page.on('pageerror', (e) => errors.push(String(e)));+await page.addInitScript(() => {+ // React DOM reports each commit to a devtools hook when one is there (production builds too).+ const m = { commits: 0, on: false, frames: [], last: 0 };+ window.__m = m;+ window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {+ supportsFiber: true,+ renderers: new Map(),+ inject: () => 1,+ onCommitFiberRoot: () => m.on && m.commits++,+ onCommitFiberUnmount: () => {},+ onPostCommitFiberRoot: () => {},+ checkDCE: () => {},+ };+ const loop = (t) => {+ if (m.on && m.last) m.frames.push(t - m.last);+ m.last = t;+ requestAnimationFrame(loop);+ };+ requestAnimationFrame(loop);+});+await page.goto(`${base}/?n=${N}`);+await page.waitForFunction(() => window.__harness?.ready(), null, { timeout: 120000 });+await page.waitForTimeout(1500);+const rows = await page.evaluate(() => document.querySelectorAll('[data-message-id]').length);+const cdp = await ctx.newCDPSession(page);+await cdp.send('Performance.enable');+const metric = async () => Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map((x) => [x.name, x.value]));+const m0 = await metric();+await page.evaluate(() => Object.assign(window.__m, { on: true, commits: 0, frames: [], last: 0 }));+const shotAt = SHOT ? Math.floor(TOKENS * 0.6) : 0;+let sent;+if (shotAt) {+ await page.evaluate(([c, r]) => window.__harness.stream(c, r), [shotAt, RATE]);+ await page.screenshot({ path: SHOT });+ sent = await page.evaluate(([c, r]) => window.__harness.stream(c, r), [TOKENS - shotAt, RATE]);+ sent.sent += shotAt;+} else if (TOKENS === 0) {+ // --tokens 0: the same 40 s with nothing streaming, to see what the machine itself costs.+ await page.waitForTimeout(40000);+ sent = { sent: 0, ms: 40000 };+} else sent = await page.evaluate(([c, r]) => window.__harness.stream(c, r), [TOKENS, RATE]);+await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));+const m1 = await metric();+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;+ 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) };+});+const secs = sent.ms / 1000;+const result = {+ label: LABEL,+ messages: N,+ rows,+ width: WIDTH,+ tokens: sent.sent,+ streamSeconds: +secs.toFixed(2),+ commitsPerSecond: +(out.commits / secs).toFixed(1),+ commits: out.commits,+ scriptingMs: Math.round((m1.ScriptDuration - m0.ScriptDuration) * 1000),+ taskMs: Math.round((m1.TaskDuration - m0.TaskDuration) * 1000),+ layoutMs: Math.round((m1.LayoutDuration - m0.LayoutDuration) * 1000),+ styleMs: Math.round((m1.RecalcStyleDuration - m0.RecalcStyleDuration) * 1000),+ longestFrameMs: Math.round(out.longest),+ p95FrameMs: Math.round(out.p95),+ framesOver50: out.over50,+ over50FirstHalf: out.over50First,+ over50SecondHalf: out.over50 - out.over50First,+ frames: out.frames,+ lastWordsShown: out.tailShown,+ errors,+};+console.log(JSON.stringify(result));+await browser.close();+server.close();diff --git a/frontend/perf/stream/vite.config.mts b/frontend/perf/stream/vite.config.mtsnew file mode 100644index 00000000..7f92dfce--- /dev/null+++ b/frontend/perf/stream/vite.config.mts@@ -0,0 +1,21 @@+// Dev-only build of the streaming harness (perf/stream/README.md). Run from frontend/:+// npx vite build --config perf/stream/vite.config.mts+// Same React plugin and Tailwind setup as the app; "What's new" is stubbed (the harness never opens it).+import { defineConfig, Plugin } from 'vite';+import react from '@vitejs/plugin-react';+import { fileURLToPath } from 'node:url';++const here = fileURLToPath(new URL('.', import.meta.url));+const whatsNewStub = (): Plugin => ({+ name: 'stream-harness-whats-new',+ resolveId: (id) => (id === 'virtual:kwant-whatsnew' ? '\0whatsnew-stub' : null),+ load: (id) => (id === '\0whatsnew-stub' ? 'export const entries = [];\nexport const changelog = {};\n' : null),+});++export default defineConfig({+ root: here,+ base: './',+ publicDir: false,+ plugins: [react(), whatsNewStub()],+ build: { outDir: 'dist', emptyOutDir: true, target: 'es2022' },+});diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 32edfb3f..589a3e6a 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -122,6 +122,7 @@ import {turnsIn,upsertThread,} from './threads';+import { createStreamText, NO_STREAM } from './streamText';import { Profile, profilesApi } from './profiles';import { FailoverEvent, createOutageLog, failoverNotice, outageKey } from './failover';import type { SwitchNote } from './failoverNotes';@@ -287,8 +288,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const openCtxRef = useRef(openCtx);openCtxRef.current = openCtx;// What the open chat is streaming; other chats' streams are kept in streamsRef until opened.- const [streamingText, setStreamingText] = useState('');- const [streamingThinking, setStreamingThinking] = useState('');+ // The open chat's streaming reply (14b): a store only the live reply subscribes to, not App state, so a+ // token never re-renders the app or the finished messages. Updates land once per frame, with one blip.+ const streamStore = useMemo(+ () => createStreamText({}, { onFrame: (prev, next) => next.text !== prev.text && playSfx('blip') }),+ [],+ );const streamsRef = useRef<Record<string, { text: string; thinking: string }>>({});// Running turns' live steps by turn id (with the chat they belong to), until the saved reply shows.const [activity, setActivity] = useState<Record<string, LiveActivity & { ctx: string }>>({});@@ -872,8 +877,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({delete liveKwantRef.current[ctx];}if (ctx === openCtxRef.current) {- setStreamingText('');- setStreamingThinking('');+ streamStore.show({ text: '', thinking: '' });}if (!ctx || !(ctx in liveRef.current)) return;const next = { ...liveRef.current };@@ -1152,8 +1156,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setHistoryWindow((w) => (w && w.ctx !== openCtx ? null : w));if (!openCtx) return;const b = streamsRef.current[openCtx];- setStreamingText(b?.text ?? '');- setStreamingThinking(b?.thinking ?? '');+ streamStore.show({ text: b?.text ?? '', thinking: b?.thinking ?? '' });setMessages(messagesCacheRef.current[openCtx] || []);setMessagesError(null);refreshContext(openCtx).then(() => {@@ -1230,8 +1233,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (turnsIn(turnsRef.current, ctx).length > 0) {streamsRef.current[ctx] = { text: '', thinking: '' };if (ctx === openCtxRef.current) {- setStreamingText('');- setStreamingThinking('');+ streamStore.show({ text: '', thinking: '' });}return;}@@ -1374,8 +1376,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (d.state === 'deciding') {if (streamsRef.current[ctx]) streamsRef.current[ctx] = { text: '', thinking: '' };if (ctx === openCtxRef.current) {- setStreamingText('');- setStreamingThinking('');+ streamStore.show({ text: '', thinking: '' });}} else {refreshContext(ctx);@@ -1552,12 +1553,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (event.type === 'TextDelta') buf.text += event.data;else buf.thinking = event.data;if (!(ctx in liveRef.current)) markLiveKwant(ctx, event.kwant_id);- if (shouldRenderDelta(event, openCtxRef.current, streamingContextIdRef.current)) {- if (event.type === 'TextDelta') {- setStreamingText(buf.text);- playSfx('blip');- } else setStreamingThinking(buf.thinking);- }+ // At most one update per frame (14b); the blip goes with it (streamStore's onFrame).+ if (shouldRenderDelta(event, openCtxRef.current, streamingContextIdRef.current)) streamStore.schedule(() => ({ ...buf }));break;}case 'activity':@@ -1693,8 +1690,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({refreshContext(targetId).then(() => {streamsRef.current[targetId] = { text: '', thinking: '' };if (openCtxRef.current === targetId) {- setStreamingText('');- setStreamingThinking('');+ streamStore.show({ text: '', thinking: '' });}});markLive(targetId, spkName);@@ -1715,6 +1711,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}case 'TurnComplete': {const ctx = streamTarget(event, streamingContextIdRef.current);+ // The last tokens show now, not a frame later (14b): the stream stays up until the saved reply lands.+ if (ctx === openCtxRef.current) streamStore.flush();if (ctx === openCtxRef.current) {playSfx('coin');// Live events only (the stream has no replay; history loads via refreshContext).@@ -1817,6 +1815,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}case 'Error': {const ctx = streamTarget(event, streamingContextIdRef.current);+ if (ctx === openCtxRef.current) streamStore.flush();if (ctx && ctx === streamingContextIdRef.current) {discussionInProgressRef.current = false;setDiscussionState({ inProgress: false });@@ -1841,6 +1840,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({/** Stop in the composer: the open thread's turn, the direct chat's, or the channel's. */const handleCancelDiscussion = async () => {const ctx = openCtxRef.current;+ // What already streamed shows at once (14b), so Stop never leaves the last words a frame behind.+ streamStore.flush();const threadId = openThreadId;try {if (threadId) {@@ -1931,8 +1932,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({streamingContextIdRef.current = targetId;if (!(targetId in liveRef.current)) {streamsRef.current[targetId] = { text: '', thinking: '' };- setStreamingText('');- setStreamingThinking('');+ streamStore.show({ text: '', thinking: '' });}markLive(targetId, speakerName);}@@ -2257,8 +2257,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({if (!(ctx in liveRef.current)) {streamsRef.current[ctx] = { text: '', thinking: '' };if (ctx === openCtxRef.current) {- setStreamingText('');- setStreamingThinking('');+ streamStore.show({ text: '', thinking: '' });}}markLive(ctx, senderLabel(msg.sender_role, msg.sender_id, liveRef.current[ctx] || 'Bot'));@@ -4282,8 +4281,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({messages={viewingHistory ? historyWindow.messages : messages}viewingHistory={viewingHistory}onJumpToLatest={() => setHistoryWindow(null)}- streamingText={isCurrentContextStreaming ? streamingText : ''}- streamingThinking={isCurrentContextStreaming ? streamingThinking : ''}+ stream={isCurrentContextStreaming ? streamStore : NO_STREAM}pendingApprovals={approvalsHere}prepush={devOn && currentKwant && !viewingHistory ? (diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 47363720..57238e81 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -1,6 +1,7 @@import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from 'react';import { parseWatchMeta, type WatchMeta } from '../missionWatch';import { flushSync } from 'react-dom';+import { createStreamText, useStreamPart, useStreamThinking, useStreamWriting, type StreamText, type StreamView } from '../streamText';import { queuedText } from '../claudeVm';import { QueuedBeside } from './QueuedBeside';import { WaitingBanner } from './WaitingBanner';@@ -218,8 +219,14 @@ export interface ChatViewProps {/** Phones: back to the list. */onBack?: () => void;messages: ChatMessage[];- streamingText: string;- streamingThinking: string;+ /**+ * The open chat's streaming reply (14b): only the live reply's body subscribes to it, so a token never+ * re-renders this view or its finished messages. App passes this.+ */+ stream?: StreamText;+ /** Without `stream`: the streaming reply as plain props (tests, previews). */+ streamingText?: string;+ streamingThinking?: string;/** Tool approvals waiting in this chat, oldest first. */pendingApprovals: PendingApproval[];/** 0.8.0 B3: this bot's pre-push cards (Dev mode), shown above its approvals. */@@ -506,6 +513,21 @@ const useNarrow = () => {return narrow;};+/**+ * 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.+ */+const StreamPart = React.memo(function StreamPart({ stream, part, onGrow }: { stream: StreamText; part: keyof StreamView; onGrow: () => void }) {+ const streamingText = useStreamPart(stream, part);+ useEffect(onGrow, [streamingText, onGrow]);+ if (part === 'thinking') return <>{streamingText}</>;+ return (+ <div className="kw-wa-in kw-wa-hold">+ <MarkdownRenderer content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} isStreaming={true} />+ </div>+ );+});+export const ChatView: React.FC<ChatViewProps> = ({heldNotes,dropOff = false,@@ -514,8 +536,9 @@ export const ChatView: React.FC<ChatViewProps> = ({spaceName,onBack,messages,- streamingText,- streamingThinking,+ stream: streamProp,+ streamingText: streamingTextProp = '',+ streamingThinking: streamingThinkingProp = '',pendingApprovals,prepush,settledApprovals = [],@@ -862,6 +885,16 @@ export const ChatView: React.FC<ChatViewProps> = ({// Follow new tokens only while the reader is at the bottom; scrolling up to read stays put.const stickRef = useRef(true);+ // The streaming reply (14b). Given as props instead of a store, those props feed a store of this view's own.+ const [propStream] = useState(() => createStreamText({ text: streamingTextProp, thinking: streamingThinkingProp }));+ const stream = streamProp ?? propStream;+ useLayoutEffect(() => {+ if (!streamProp) propStream.show({ text: streamingTextProp, thinking: streamingThinkingProp });+ }, [streamProp, propStream, streamingTextProp, streamingThinkingProp]);+ // From here on these only say whether the reply has words (a thinking line) yet; they flip once per reply.+ // The words themselves reach StreamPart alone.+ const streamingText = useStreamWriting(stream) || (!streamProp && !!streamingTextProp);+ const streamingThinking = useStreamThinking(stream) || (!streamProp && !!streamingThinkingProp);const lastScrollTopRef = useRef(0);// The empty chat's home opens at its top: on a phone a team home is taller than the screen, and its faces come first (13d).const homeShowingRef = useRef(false);@@ -896,7 +929,7 @@ export const ChatView: React.FC<ChatViewProps> = ({// (`phone` is the A1 PHONE_QUERY flag above).const stripWaitsOn = isStreaming ? waitingOn({ live: liveActivity, queued: !!queued, awaitingAnswer: !!awaitingAnswer, awaitingBrowser: !!awaitingBrowser }) : null;// What the live bubble holds before its first words: a pending approval reads as "waiting for your OK", not loading.- const bubble = liveBubble({ live: liveActivity, queued: !!queued, awaitingAnswer: !!awaitingAnswer, awaitingBrowser: !!awaitingBrowser, writing: !!streamingText });+ const bubble = liveBubble({ live: liveActivity, queued: !!queued, awaitingAnswer: !!awaitingAnswer, awaitingBrowser: !!awaitingBrowser, writing: streamingText });// The strip's "Answer ↑": the open question card, else the approval card, fully in view.const showWaitingCard = (on: 'question' | 'approval') => {if (on === 'approval') return showApproval();@@ -916,7 +949,7 @@ export const ChatView: React.FC<ChatViewProps> = ({awaitingBrowser: !!awaitingBrowser,approvalOpen: pendingApprovals.length > 0,queued: !!queued,- writing: !!streamingText,+ writing: streamingText,});// Team words ("Stop team", the rail) only for a team turn; a single bot asking in a channel gets "Stop".const teamChat = isTeamTurn(home?.kind, !!discussionState?.inProgress);@@ -943,7 +976,7 @@ export const ChatView: React.FC<ChatViewProps> = ({queued={!!queued}awaitingAnswer={!!awaitingAnswer}awaitingBrowser={!!awaitingBrowser}- writing={!!streamingText}+ writing={streamingText}onAnswer={showWaitingCard}onWatch={onWatchBrowser && !vmOpen ? onWatchBrowser : undefined}phone={phone}@@ -994,6 +1027,13 @@ export const ChatView: React.FC<ChatViewProps> = ({if (scrollRef.current && stickRef.current) pinToBottom(scrollRef.current);checkApprovalVisible();}, [messages, streamingText, streamingThinking, approvalKey, routingState, queued, contextKey]);+ // Each streamed update (at most one a frame) keeps the bottom pinned while the person follows the chat.+ const onStreamGrowRef = useRef(() => {});+ onStreamGrowRef.current = () => {+ if (scrollRef.current && stickRef.current) pinToBottom(scrollRef.current);+ checkApprovalVisible();+ };+ const [onStreamGrow] = useState(() => () => onStreamGrowRef.current());// Jump to a search hit: open its folded discussion if needed, then centre and flash it.// Runs after the auto-scroll above, so it wins.@@ -2477,7 +2517,7 @@ export const ChatView: React.FC<ChatViewProps> = ({{streamingThinking && (<div className="mb-2 p-2.5 rounded-xl bg-violet-950/20 border border-violet-500/20 text-xs text-violet-300/90 flex items-center gap-2 animate-pulse motion-reduce:animate-none max-w-full"><Sparkles size={13} className="text-violet-400 flex-shrink-0" />- <span className="truncate">{streamingThinking}</span>+ <span className="truncate"><StreamPart stream={stream} part="thinking" onGrow={onStreamGrow} /></span></div>)}@@ -2490,10 +2530,8 @@ export const ChatView: React.FC<ChatViewProps> = ({{queuedText(queued.reason, queued.slots)}</p>) : streamingText ? (- /* The scene's 62 px holds under the first words (kw-wa-hold), so the bubble does not jump; they fade in once. */- <div className="kw-wa-in kw-wa-hold">- <MarkdownRenderer content={hideStreamingDecisions(stripDiscussionMarkers(streamingText))} isStreaming={true} />- </div>+ /* The scene's 62 px holds under the first words (kw-wa-hold, in StreamPart), so the bubble does not jump; they fade in once. */+ <StreamPart stream={stream} part="text" onGrow={onStreamGrow} />) : awaitingAnswer ? (<p className="text-zinc-400" role="status">{awaitingBrowserdiff --git a/frontend/src/components/MarkdownRenderer.tsx b/frontend/src/components/MarkdownRenderer.tsxindex 43fa32f2..0b4bb125 100644--- a/frontend/src/components/MarkdownRenderer.tsx+++ b/frontend/src/components/MarkdownRenderer.tsx@@ -160,13 +160,15 @@ function listSource(node: HastNode, children: React.ReactNode): ReplySource {};}-export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({+// Memoized (14b): a finished message parses its markdown again only when its own props change, never+// because the reply streaming below it moved on.+export const MarkdownRenderer = React.memo(function MarkdownRenderer({content,className = '',isStreaming = false,results,messageId,-}) => {+}: MarkdownRendererProps) {// Never while streaming: the block appears when the final message arrives.const smart = !isStreaming && !!messageId && resultBlocks(results).length > 0;const slot = smart ? blockAt(results, { kind: 'slot' }) : null;@@ -387,4 +389,4 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({</div></ReplyText.Provider>);-};+});diff --git a/frontend/src/streamText.ts b/frontend/src/streamText.tsnew file mode 100644index 00000000..f120b8ba--- /dev/null+++ b/frontend/src/streamText.ts@@ -0,0 +1,124 @@+// The open chat's streaming reply, outside React state (14b smooth-streaming).+//+// Tokens arrive one event at a time, up to dozens a second. Holding the text in App state re-rendered the+// whole app and every finished message on each token. Here the text lives in a small store: only the live+// reply's body (and the thinking line) subscribe to it, and token updates reach them at most once per+// animation frame. Everything else reads `writing` (any text yet?), which changes twice per reply.++import { useSyncExternalStore } from 'react';++export interface StreamView {+ /** The reply so far, as streamed. */+ text: string;+ /** The latest thinking line. */+ thinking: string;+}++export interface StreamText {+ get(): StreamView;+ subscribe(listener: () => void): () => void;+ /** Shows `next` now, dropping any update still waiting for its frame (a reset, a chat switch). */+ show(next: Partial<StreamView>): void;+ /**+ * Shows what `read` returns at the next animation frame, or after `FALLBACK_MS` when frames don't come+ * (a hidden tab). Calls before the frame only move the reader: one update per frame.+ */+ schedule(read: () => Partial<StreamView>): void;+ /** Applies a waiting update now (the stream ended). */+ flush(): void;+}++/** A hidden tab gets no animation frames; the stream still moves on this timer. */+export const FALLBACK_MS = 50;++const EMPTY: StreamView = Object.freeze({ text: '', thinking: '' });++export interface StreamTextOptions {+ /** Runs after each scheduled (not `show`) update with the old and new view, e.g. the typing blip. */+ onFrame?: (prev: StreamView, next: StreamView) => void;+ /** Frame and timer functions; the window's by default (tests pass their own). */+ frame?: (cb: () => void) => number;+ cancelFrame?: (id: number) => void;+}++export function createStreamText(initial: Partial<StreamView> = {}, opts: StreamTextOptions = {}): StreamText {+ let view: StreamView = initial.text || initial.thinking ? { ...EMPTY, ...initial } : EMPTY;+ const listeners = new Set<() => void>();+ let reader: (() => Partial<StreamView>) | null = null;+ let frameId: number | null = null;+ let timerId: ReturnType<typeof setTimeout> | null = null;+ const raf =+ opts.frame ?? (typeof requestAnimationFrame === 'function' ? (cb: () => void) => requestAnimationFrame(() => cb()) : null);+ const caf = opts.cancelFrame ?? (typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : null);++ const cancel = () => {+ if (frameId !== null && caf) caf(frameId);+ if (timerId !== null) clearTimeout(timerId);+ frameId = timerId = null;+ reader = null;+ };+ /** Sets the view; true when it changed. */+ const apply = (next: Partial<StreamView>): boolean => {+ const text = next.text ?? view.text;+ const thinking = next.thinking ?? view.thinking;+ if (text === view.text && thinking === view.thinking) return false;+ view = text || thinking ? { text, thinking } : EMPTY;+ listeners.forEach((l) => l());+ return true;+ };+ const flush = () => {+ const read = reader;+ cancel();+ if (!read) return;+ const prev = view;+ if (apply(read())) opts.onFrame?.(prev, view);+ };++ return {+ get: () => view,+ subscribe(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ show(next) {+ cancel();+ apply(next);+ },+ schedule(read) {+ reader = read;+ if (frameId !== null || timerId !== null) return;+ if (raf) frameId = raf(flush);+ timerId = setTimeout(flush, FALLBACK_MS);+ },+ flush,+ };+}++/** A chat with nothing streaming: always empty, never changes. */+export const NO_STREAM: StreamText = {+ get: () => EMPTY,+ subscribe: () => () => {},+ show: () => {},+ schedule: () => {},+ flush: () => {},+};++/** One part of the stream, re-rendering when that part changes. Only the live reply's body and thinking line use this. */+export const useStreamPart = (s: StreamText, part: keyof StreamView): string => {+ const get = () => s.get()[part];+ return useSyncExternalStore(s.subscribe, get, get);+};++/** Whether any reply text has arrived yet; re-renders only when that flips. */+export const useStreamWriting = (s: StreamText): boolean => {+ const get = () => !!s.get().text;+ return useSyncExternalStore(s.subscribe, get, get);+};++/** Whether a thinking line is showing; re-renders only when that flips. */+export const useStreamThinking = (s: StreamText): boolean => {+ const get = () => !!s.get().thinking;+ return useSyncExternalStore(s.subscribe, get, get);+};diff --git a/frontend/tests/smoothStreaming.test.mjs b/frontend/tests/smoothStreaming.test.mjsnew file mode 100644index 00000000..78bd0cd6--- /dev/null+++ b/frontend/tests/smoothStreaming.test.mjs@@ -0,0 +1,181 @@+// 14b smooth-streaming: the reply streams into React at most once per frame, and finished messages don't+// re-render while it does. The store's batching and flushes, then a ChatView render count in JSDOM.+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', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'CSS']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+if (!g.CSS) g.CSS = { escape: (s) => s };+g.window.matchMedia = g.window.matchMedia || ((q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }));+g.ResizeObserver = g.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };+g.IntersectionObserver = g.window.IntersectionObserver = class { observe() {} unobserve() {} disconnect() {} };+g.window.HTMLElement.prototype.scrollIntoView = function () {};+g.fetch = g.window.fetch = async () => new Response('[]', { status: 200, headers: { 'Content-Type': 'application/json' } });++// React DevTools' hook, reduced to counting which components rendered in each commit. A fiber rendered when+// it is new or carries PerformedWork; a subtree whose child list is unchanged bailed out and is skipped.+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 * from './src/streamText';+ export { ChatView } from './src/components/ChatView';+`);+const { React, createRoot, flushSync, createStreamText } = m;+const h = React.createElement;++/** A frame clock the test advances by hand. */+function frames() {+ let cb = null;+ let id = 0;+ return {+ frame: (f) => ((cb = f), ++id),+ cancelFrame: () => (cb = null),+ tick() {+ const f = cb;+ cb = null;+ f?.();+ },+ get waiting() {+ return cb !== null;+ },+ };+}++test('tokens before a frame land together, once, with one blip', () => {+ const clock = frames();+ const blips = [];+ const s = createStreamText({}, { ...clock, onFrame: (prev, next) => blips.push([prev.text, next.text]) });+ let seen = 0;+ s.subscribe(() => seen++);+ let buf = '';+ for (const t of ['Hel', 'lo', ' wor', 'ld']) {+ buf += t;+ s.schedule(() => ({ text: buf }));+ }+ assert.equal(s.get().text, '', 'nothing shows before the frame');+ assert.equal(seen, 0);+ clock.tick();+ assert.equal(s.get().text, 'Hello world', 'the frame shows the latest text, not the first');+ assert.equal(seen, 1, 'one update for four tokens');+ assert.deepEqual(blips, [['', 'Hello world']], 'one blip per frame');+ clock.tick();+ assert.equal(seen, 1, 'an idle frame changes nothing');+});++test('the end of the stream and Stop flush at once; a reset or chat switch drops what was waiting', () => {+ const clock = frames();+ const s = createStreamText({}, clock);+ s.schedule(() => ({ text: 'Final words' }));+ s.flush();+ assert.equal(s.get().text, 'Final words', 'flush applies without waiting for the frame');+ assert.equal(clock.waiting, false, 'and cancels the frame');+ s.schedule(() => ({ text: 'Final words and more' }));+ s.show({ text: '', thinking: '' });+ clock.tick();+ assert.deepEqual(s.get(), { text: '', thinking: '' }, 'show cancels the waiting update');+ s.show({ text: 'Other chat', thinking: 'Reading' });+ assert.deepEqual(s.get(), { text: 'Other chat', thinking: 'Reading' }, 'a chat switch shows its buffer now');+});++test('without animation frames (a hidden tab) the timer still moves the stream', async () => {+ const s = createStreamText({}, { frame: () => 1, cancelFrame: () => {} });+ s.schedule(() => ({ thinking: 'Checking the logs' }));+ assert.equal(s.get().thinking, '');+ await new Promise((r) => setTimeout(r, m.FALLBACK_MS + 30));+ assert.equal(s.get().thinking, 'Checking the logs');+});++const conversation = Array.from({ length: 12 }, (_, i) =>+ i % 2+ ? { id: `k${i}`, sender_role: 'kwant', sender_id: 'Ada', text: `## Step ${i}\n\nDone with **part ${i}**.\n\n\`\`\`ts\nconst x = ${i};\n\`\`\`\n\n- one\n- two` }+ : { id: `u${i}`, sender_role: 'user', sender_id: 'PlayerHero', text: `Next, please (${i})` },+);+const isMarkdown = (r) => /^MarkdownRenderer\d*$/.test(r.name);++test('streaming 100 tokens re-renders no finished message and the live reply at most once per frame', () => {+ const clock = frames();+ const stream = createStreamText({}, clock);+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ const props = {+ title: 'Ada',+ messages: conversation,+ stream,+ pendingApprovals: [],+ isStreaming: true,+ onSendMessage: () => true,+ onResolveApproval: () => {},+ contextKey: 'k1',+ };+ flushSync(() => root.render(h(m.ChatView, props)));+ assert.ok(renders.filter(isMarkdown).length >= 6, 'the finished replies render through MarkdownRenderer');++ try {+ renders.length = 0;+ let buf = '';+ let shown = 0;+ for (let i = 0; i < 100; i++) {+ buf += i % 7 === 6 ? '\n\n' : `w${i} `;+ stream.schedule(() => ({ text: buf }));+ // 50 tokens a second against 60 frames a second is about one token a frame; four per frame is the+ // harder case for batching and still has to come out as one render per frame.+ if (i % 4 === 3) {+ flushSync(() => clock.tick());+ shown++;+ }+ }+ const finished = renders.filter((r) => isMarkdown(r) && !r.props.isStreaming);+ const live = renders.filter((r) => isMarkdown(r) && r.props.isStreaming);+ 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(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 {+ flushSync(() => root.unmount());+ }+});++test('without a stream store, the streamingText prop still shows the reply (older callers and tests)', () => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ const props = { title: 'Ada', messages: conversation.slice(0, 2), streamingText: 'Working on **it**', streamingThinking: '', pendingApprovals: [], isStreaming: true, onSendMessage: () => true, onResolveApproval: () => {} };+ flushSync(() => root.render(h(m.ChatView, props)));+ assert.match(host.textContent, /Working on it/);+ flushSync(() => root.render(h(m.ChatView, { ...props, streamingText: 'Working on it, done' })));+ assert.match(host.textContent, /Working on it, done/);+ flushSync(() => root.unmount());+});