Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(code): progressive streaming flush — the document builds in scrollback while it streams
Salman Qureshi9cb0d46f45af
diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 26aa6648..cb0778f2 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -8,7 +8,7 @@ import type { ProgrammingModeState } from '../core/programming-mode.js';import { renderMarkdown } from '../utils/markdown.js';import { highlightCodeBlock } from '../utils/highlight.js';import { normalizeTerminalText, getViewportWindow } from './terminal-viewport.js';-import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, type MercuryTranscriptLine } from './mercury-transcript.js';+import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, parseChunkIndex, splitFinalMessage, splitStreamingMessage, type MercuryTranscriptLine } from './mercury-transcript.js';import { PLAYER_CONTROLS, formatNowPlaying } from '../spotify/ui.js';import type { SpotifyClient } from '../spotify/client.js';import type { SubAgentStatus } from '../types/agent.js';@@ -2561,7 +2561,10 @@ function MercuryBrandBlock({ brandLines }: { brandLines: MercuryTranscriptLine[]}function MercuryMessageBlock({ message, width }: { message: ChatMessage; width: number }): React.ReactNode {- const lines = buildMercuryMessageLines(message, width);+ // Progressive-chunk items carry ids like `${msgId}#c<i>`; only chunk 0+ // renders the MERCURY/YOU role header — continuation chunks flow on.+ const chunkIndex = parseChunkIndex(message.id);+ const lines = buildMercuryMessageLines(message, width, { showHeader: chunkIndex == null || chunkIndex === 0 });return (<Box flexDirection="column" flexShrink={0}>{lines.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}@@ -2619,6 +2622,25 @@ export function MercuryCodeView({// arithmetic (log-update) never changes the region's line count, which is// what made the user's scroll position churn ("takes me back") while a// response streamed. Released when the message finalizes into <Static>.+ // Progressive flush bookkeeping: ids that streamed through settled-chunk+ // <Static> items this session. When such a message finalizes it must KEEP+ // its chunk representation (identical item keys) — rendering it as one+ // whole-message item would re-print blocks <Static> already emitted.+ const streamedIdsRef = React.useRef<Set<string>>(new Set());++ // Settled markdown blocks of the streaming message, flushed into <Static>+ // as they complete (blank-line-terminated paragraph, closed code fence).+ // <Static> prints each new item exactly once, so the document builds+ // top-to-bottom in scrollback during the stream; only the unsettled+ // remainder renders in the live tail below. Bookkeeping is ref-based like+ // the tail throttle below (React state would loop).+ const streamingChunks = React.useMemo(() => {+ if (!streamingMessage) return { chunks: [] as ChatMessage[], remainderStart: 0 };+ streamedIdsRef.current.add(streamingMessage.id);+ return splitStreamingMessage(streamingMessage);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- ref bookkeeping, not state+ }, [streamingMessage]);+const tailRef = React.useRef<null | { id: string; at: number; contentLength: number; lines: MercuryTranscriptLine[] }>(null);const tailCap = streamTailRowCap(rows);const streamTail = React.useMemo(() => {@@ -2631,11 +2653,15 @@ export function MercuryCodeView({if (cache && cache.id === streamingMessage.id && now - cache.at < 120 && cache.contentLength <= streamingMessage.content.length) {return cache.lines;}- const lines = buildStreamTailLines(streamingMessage, contentWidth, STREAM_TAIL_CHARS, tailCap);+ // The live tail renders only the unsettled remainder (settled blocks+ // have already joined <Static> above); the 32KB fence-aligned slice+ // stays as the safety net for a huge in-progress block.+ const remainderMessage = { ...streamingMessage, content: streamingMessage.content.slice(streamingChunks.remainderStart) };+ const lines = buildStreamTailLines(remainderMessage, contentWidth, STREAM_TAIL_CHARS, tailCap);tailRef.current = { id: streamingMessage.id, at: now, contentLength: streamingMessage.content.length, lines };return lines;// eslint-disable-next-line react-hooks/exhaustive-deps -- tailCap derives from rows; cache ref holds state- }, [streamingMessage, contentWidth, tailCap]);+ }, [streamingMessage, streamingChunks, contentWidth, tailCap]);const paddedStreamTail = React.useMemo(() => {if (streamTail.length === 0) return streamTail;const pad = tailCap - streamTail.length;@@ -2655,9 +2681,16 @@ export function MercuryCodeView({);}+ // <Static> items: brand block, then per-message content. Messages that+ // streamed through settled chunks keep their chunk items (identical keys —+ // finalization appends exactly one tail-chunk item); every other message+ // renders whole, as before.+ const streamedIds = streamedIdsRef.current;const staticItems: Array<string | ChatMessage> = [MERCURY_BRAND_ITEM_KEY,- ...finalizedMessages.slice(-MAX_STATIC_MESSAGES),+ ...finalizedMessages.slice(-MAX_STATIC_MESSAGES).flatMap((message) =>+ streamedIds.has(message.id) ? splitFinalMessage(message) : [message]),+ ...streamingChunks.chunks,];// Status bar (single row): a short contextual hint on the left, sessiondiff --git a/src/ui/mercury-transcript.test.ts b/src/ui/mercury-transcript.test.tsindex 3c8eab4a..2d9b85e3 100644--- a/src/ui/mercury-transcript.test.ts+++ b/src/ui/mercury-transcript.test.ts@@ -1,6 +1,13 @@import { describe, expect, it } from 'vitest';import type { ChatMessage } from './types.js';-import { buildMercuryMessageLines, wrapMercuryText } from './mercury-transcript.js';+import {+ buildMercuryMessageLines,+ parseChunkIndex,+ settledChunkEnds,+ splitFinalMessage,+ splitStreamingMessage,+ wrapMercuryText,+} from './mercury-transcript.js';function message(partial: Partial<ChatMessage> = {}): ChatMessage {return {@@ -57,3 +64,111 @@ describe('Mercury Code transcript formatting', () => {]);});});++const FULL = [+ '# Refactor Plan',+ '',+ '## Overview',+ 'We will split the auth module into three layers.',+ '',+ '- **Step one:** extract token verification',+ '- **Step two:** move session storage to redis',+ '',+ '## Details',+ '',+ '```ts',+ "import { verifyToken } from './auth';",+ 'export function guard(req) {',+ ' return verifyToken(req.headers.authorization);',+ '}',+ '```',+ '',+ '## Rollout',+ 'Ship behind a flag.',+].join('\n');++const chunkMessage = (content: string, streaming = false): ChatMessage => ({+ id: 'm1',+ role: 'agent',+ content,+ timestamp: 1,+ streaming,+});++/**+ * Progressive-flush splitter guards. <Static> prints each item exactly once,+ * so the chunk keys produced while a message streams must be a strict prefix+ * of the keys produced by the finalized content — otherwise finalization+ * re-prints blocks the user already saw (or drops them).+ */+describe('settled-chunk splitter (progressive streaming flush)', () => {+ it('reassembles into the original content exactly', () => {+ const chunks = splitFinalMessage(chunkMessage(FULL));+ expect(chunks.map((c) => c.content).join('')).toBe(FULL);+ });++ it('settled boundaries of every partial stream are a subset of the final boundaries', () => {+ const fullEnds = settledChunkEnds(FULL);+ for (let cut = 1; cut < FULL.length; cut++) {+ for (const end of settledChunkEnds(FULL.slice(0, cut))) {+ expect(fullEnds).toContain(end);+ }+ }+ });++ it('never settles a boundary inside an open code fence', () => {+ const unclosed = '```ts\nconst x = 1;\nstill inside the fence';+ expect(settledChunkEnds(unclosed)).toEqual([]);+ // A closed fence settles at the closer even without a trailing blank line.+ expect(settledChunkEnds('```ts\nconst x = 1;\n```\nnext')).toEqual([+ '```ts\nconst x = 1;\n```\n'.length,+ ]);+ });++ it('settles blank-line-terminated blocks only when content resumes after the blank', () => {+ // Trailing blank line(s) at the stream's current end are NOT a boundary —+ // more content could still continue the block.+ expect(settledChunkEnds('para one\n\n')).toEqual([]);+ expect(settledChunkEnds('para one\n\npara two')).toEqual(['para one\n\n'.length]);+ });++ it('streaming chunks exclude the unsettled remainder; finalize adds exactly one tail chunk', () => {+ let streamedIds: string[] = [];+ for (const cut of [20, 60, 120, FULL.length]) {+ const content = FULL.slice(0, cut);+ const { chunks, remainderStart } = splitStreamingMessage(chunkMessage(content, true));+ streamedIds = chunks.map((c) => c.id); // the last cut's chunk list is the streamed state+ // Settled chunks + remainder reassemble the streamed content.+ expect(chunks.map((c) => c.content).join('') + content.slice(remainderStart)).toBe(content);+ }+ const finalIds = splitFinalMessage(chunkMessage(FULL)).map((c) => c.id);+ // Every streamed chunk key must survive into the final list, in order.+ expect(finalIds.join(',').startsWith(streamedIds.join(','))).toBe(true);+ // Finalization adds exactly one NEW item (the tail chunk).+ expect(finalIds.length).toBe(streamedIds.length + 1);+ });++ it('carries fileChanges only on the last chunk', () => {+ const fileChanges = [{ path: 'src/a.ts', added: 3, removed: 1 }];+ const chunks = splitFinalMessage({ ...chunkMessage(FULL), fileChanges });+ expect(chunks.slice(0, -1).every((c) => c.fileChanges === undefined)).toBe(true);+ expect(chunks[chunks.length - 1].fileChanges).toEqual(fileChanges);+ });++ it('renders the role header only on chunk 0', () => {+ const chunks = splitFinalMessage(chunkMessage(FULL));+ expect(chunks.length).toBeGreaterThan(1);+ expect(buildMercuryMessageLines(chunks[0], 76).some((l) => l.kind === 'header')).toBe(true);+ for (const chunk of chunks.slice(1)) {+ expect(buildMercuryMessageLines(chunk, 76, { showHeader: false }).some((l) => l.kind === 'header')).toBe(false);+ }+ // Whole messages (no #c id) keep the header.+ expect(parseChunkIndex('m1')).toBeNull();+ expect(buildMercuryMessageLines(chunkMessage('hello'), 76).some((l) => l.kind === 'header')).toBe(true);+ });++ it('degenerate inputs: short and empty messages produce exactly one chunk', () => {+ expect(splitFinalMessage(chunkMessage('short answer')).map((c) => c.id)).toEqual(['m1#c0']);+ expect(splitFinalMessage(chunkMessage('')).map((c) => c.id)).toEqual(['m1#c0']);+ });+});diff --git a/src/ui/mercury-transcript.ts b/src/ui/mercury-transcript.tsindex f31b4190..bd06b356 100644--- a/src/ui/mercury-transcript.ts+++ b/src/ui/mercury-transcript.ts@@ -126,7 +126,138 @@ export function buildStreamTailLines(return lines;}-export function buildMercuryMessageLines(message: ChatMessage, width: number): MercuryTranscriptLine[] {+export interface MessageLinesOptions {+ /** Render the MERCURY/YOU role header row. False for continuation chunks. */+ showHeader?: boolean;+}++/**+ * Progressive streaming flush.+ *+ * While a message streams, only complete markdown blocks are safe to print+ * into <Static> (which never repaints a printed item): a block is SETTLED+ * when its structure can no longer change as more content arrives —+ *+ * - immediately after a closing code-fence line (fence parity even), or+ * - after a blank line (fence parity even) that is followed, further down,+ * by more content — i.e. the blank line terminated the block.+ *+ * The rule is PREFIX-STABLE: a boundary that qualifies on partial content+ * keeps qualifying as the stream grows (it only depends on already-fixed+ * context), so chunk indices — and therefore <Static> item keys — are the+ * same during streaming and after finalization. That is what lets the live+ * tail hand blocks to scrollback mid-stream without anything being printed+ * twice when the message finalizes.+ */+const FENCE_RE = /^```\s*([^\s`]*)/;++export function settledChunkEnds(content: string): number[] {+ if (content.length === 0) return [];+ const lines = content.split('\n');+ // Index of the last non-blank line: a blank-line boundary after line i+ // settles only if content resumes after the blank (i.e. the blank+ // TERMINATED a block rather than trailing the stream's current end).+ let lastNonBlank = -1;+ for (let i = 0; i < lines.length; i++) if (lines[i].trim() !== '') lastNonBlank = i;+ const ends: number[] = [];+ let inFence = false;+ let prevClosed = false; // previous line closed a fence and already settled a boundary+ let offset = 0;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const lineEnd = offset + line.length + 1; // + newline (virtual on the last line)+ offset = lineEnd;+ if (FENCE_RE.test(line)) inFence = !inFence;+ if (inFence) {+ prevClosed = false;+ continue;+ }+ const blank = line.trim() === '';+ const prevBlank = i > 0 && lines[i - 1].trim() === '';+ if (blank) {+ // Settle after the FIRST blank of a run (later blanks ride along in the+ // next chunk), and not right after a fence close (that line already+ // settled its own boundary).+ if (i > 0 && !prevBlank && !prevClosed && lastNonBlank > i) ends.push(lineEnd);+ prevClosed = false;+ continue;+ }+ if (FENCE_RE.test(line)) {+ // Non-blank line that just closed a fence: the block is complete now.+ ends.push(lineEnd);+ prevClosed = true;+ continue;+ }+ prevClosed = false;+ }+ return ends;+}++/** Module cache: settled-chunk scans are O(content) per call, and static+ * items are rebuilt every frame — finalized messages must be scanned once,+ * not per frame. Keyed by id + content length (content is append-only while+ * streaming, so length+prefix identifies the scan). */+const chunkCache = new Map<string, ChatMessage[]>();++function cachedChunks(key: string, content: string, compute: () => ChatMessage[]): ChatMessage[] {+ const hit = chunkCache.get(key);+ // Cheap staleness guard: content is append-only while streaming, so the+ // first chunk's head must always be a prefix of the current content.+ if (hit && hit.length > 0 && content.startsWith(hit[0].content.slice(0, 32))) return hit;+ const chunks = compute();+ if (chunkCache.size > 200) chunkCache.clear();+ chunkCache.set(key, chunks);+ return chunks;+}++function sliceChunks(message: ChatMessage, ends: number[], finalEnd: number): ChatMessage[] {+ const bounds = [...ends, finalEnd];+ return bounds.map((end, i) => ({+ ...message,+ id: `${message.id}#c${i}`,+ content: message.content.slice(i === 0 ? 0 : bounds[i - 1], end),+ fileChanges: i === bounds.length - 1 ? message.fileChanges : undefined,+ streaming: false,+ }));+}++/**+ * Chunks of a FINALIZED message: settled boundaries plus the tail as the+ * last chunk. Keys are identical to the chunks printed while the message+ * streamed, so finalization adds exactly one new <Static> item.+ */+export function splitFinalMessage(message: ChatMessage): ChatMessage[] {+ return cachedChunks(+ `${message.id}:${message.content.length}:final:${message.fileChanges?.length ?? -1}`,+ message.content,+ () => sliceChunks(message, settledChunkEnds(message.content), message.content.length),+ );+}++/** Settled chunks of a still-streaming message (tail excluded — it is still+ * growing) plus the offset where the unsettled remainder begins. */+export function splitStreamingMessage(message: ChatMessage): { chunks: ChatMessage[]; remainderStart: number } {+ const chunks = cachedChunks(+ `${message.id}:${message.content.length}:live:${message.fileChanges?.length ?? -1}`,+ message.content,+ () => sliceChunks(message, settledChunkEnds(message.content), message.content.length).slice(0, -1),+ );+ // Chunks are contiguous from offset 0, so the remainder starts where they end.+ const remainderStart = chunks.reduce((sum, c) => sum + c.content.length, 0);+ return { chunks, remainderStart };+}++/** True for synthetic progressive-chunk items (id `${msgId}#c<i>`). */+export function parseChunkIndex(id: string): number | null {+ const match = /#c(\d+)$/.exec(id);+ return match ? parseInt(match[1], 10) : null;+}++export function buildMercuryMessageLines(+ message: ChatMessage,+ width: number,+ options?: MessageLinesOptions,+): MercuryTranscriptLine[] {if (message.id.startsWith('heartbeat-')) return [];const contentWidth = Math.max(12, width - 4);const lines: MercuryTranscriptLine[] = [];@@ -173,7 +304,7 @@ export function buildMercuryMessageLines(message: ChatMessage, width: number): M}flushProse();} else {- push('header', message.role === 'user' ? 'YOU' : 'MERCURY');+ if (options?.showHeader !== false) push('header', message.role === 'user' ? 'YOU' : 'MERCURY');const source = normalizeTerminalText(message.content).split('\n');let prose: string[] = [];let inCode = false;diff --git a/src/ui/progressive-flush.test.tsx b/src/ui/progressive-flush.test.tsxnew file mode 100644index 00000000..dd162236--- /dev/null+++ b/src/ui/progressive-flush.test.tsx@@ -0,0 +1,154 @@+import { describe, expect, it, vi } from 'vitest';++// Ink skips ALL frame writes when it detects CI (`is-in-ci` → process.env.CI).+// Setting CI to '0' (the one value is-in-ci treats as false) BEFORE the ink+// module loads restores normal rendering.+vi.hoisted(() => {+ process.env.CI = '0';+});++import React from 'react';+import { render, Box, Text } from 'ink';+import { EventEmitter } from 'node:events';+import { MercuryCodeView } from './App.js';+import type { TuiState } from '../channels/cli.js';+import type { ChatMessage } from './types.js';++class FakeStdout extends EventEmitter {+ chunks: string[] = [];+ columns = 80;+ rows = 24;+ isTTY = true;+ write(chunk: string): boolean {+ this.chunks.push(chunk);+ return true;+ }+ get output(): string {+ return this.chunks.join('');+ }+}++class FakeStdin extends EventEmitter {+ setEncoding(): void {}+ setRawMode(): void {}+ resume(): void {}+ pause(): void {}+ ref(): void {}+ unref(): void {}+ isTTY = true;+}++const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));++const count = (haystack: string, needle: string) => haystack.split(needle).length - 1;++/**+ * Progressive streaming flush, against the REAL patched ink.+ *+ * Settled markdown blocks (blank-line-terminated paragraphs, closed code+ * fences) must join <Static> DURING the stream so the document builds+ * top-to-bottom in native scrollback — instead of appearing only when the+ * message finalizes. <Static> prints each item exactly once, so every block+ * must appear in the byte stream EXACTLY ONCE across growth and finalization:+ * the item keys produced while streaming are the same keys the finalized+ * message re-derives, and only the tail chunk is new.+ */+describe('Mercury Code progressive streaming flush', () => {+ const BLOCK1 = '# Design Notes\n\nThe gateway now owns token refresh.\n\n';+ const BLOCK2 = '## Rollout\n\nShip behind a feature flag this week.\n\n';+ const TAIL = 'The dashboard reads the flag on boot.';++ const stateFor = (content: string, streaming: boolean): TuiState => ({+ mode: 'mercury-code',+ version: '1.2.5',+ agentName: 'Mercury',+ programmingMode: 'execute',+ projectContext: '/tmp/proj',+ permissionMode: 'allow-all',+ chatMessages: [+ { id: 'u1', role: 'user', content: 'write the design notes', timestamp: 1 },+ { id: 'a1', role: 'agent', content, timestamp: 2, streaming },+ ] as ChatMessage[],+ toolSteps: [],+ subAgents: [],+ planProgress: [],+ backgroundTasks: [],+ skills: [],+ sidebarSections: [],+ mercuryCode: {+ cwd: '/tmp/proj', dirName: 'proj', git: { branch: 'main', ahead: 0, behind: 0, dirty: 0 },+ scrollOffset: 0, exitConfirm: false,+ },+ tuiFrozen: false,+ isThinking: !streaming,+ } as unknown as TuiState);++ it('prints settled blocks once during streaming and exactly once more item at finalization', async () => {+ const stdout = new FakeStdout() as any;+ const { rerender, unmount } = render(+ React.createElement(+ Box,+ { flexDirection: 'column' },+ React.createElement(MercuryCodeView, { state: stateFor(BLOCK1 + 'Ship behind', true), cols: 100, rows: 24 }),+ ),+ { stdout, exitOnCtrlC: false, patchConsole: false },+ );+ await sleep(400);++ // Block 1 is settled (blank-line-terminated, content continues after) —+ // it has joined <Static>, exactly once.+ expect(count(stdout.output, 'owns token refresh')).toBe(1);+ // The in-progress remainder is in the live tail.+ expect(count(stdout.output, 'Ship behind')).toBe(1);++ // Growth: block 2 settles and prints; block 1 must NOT re-print.+ rerender(+ React.createElement(+ Box,+ { flexDirection: 'column' },+ React.createElement(MercuryCodeView, { state: stateFor(BLOCK1 + BLOCK2 + 'The dashboard reads', true), cols: 100, rows: 24 }),+ ),+ );+ await sleep(400);+ expect(count(stdout.output, 'owns token refresh')).toBe(1);+ expect(count(stdout.output, 'feature flag this week')).toBe(1);+ // The old in-progress text was part of block 2's <Static> print now; the+ // new remainder is the tail sentence.+ expect(stdout.output).not.toContain('\x1b[3J');++ // Finalization: the tail chunk prints exactly once; nothing re-prints.+ rerender(+ React.createElement(+ Box,+ { flexDirection: 'column' },+ React.createElement(MercuryCodeView, { state: stateFor(BLOCK1 + BLOCK2 + TAIL, false), cols: 100, rows: 24 }),+ ),+ );+ await sleep(400);+ expect(count(stdout.output, 'owns token refresh')).toBe(1);+ expect(count(stdout.output, 'feature flag this week')).toBe(1);+ expect(count(stdout.output, 'dashboard reads the flag on boot')).toBe(1);+ expect(stdout.output).not.toContain('\x1b[3J');++ unmount();+ }, 15_000);++ it('a message with no settled blocks streams entirely in the live region (unchanged behavior)', async () => {+ const stdout = new FakeStdout() as any;+ const content = Array.from({ length: 40 }, (_, i) => `unbroken line ${i}`).join('\n'); // no blank lines, no fences+ const { rerender, unmount } = render(+ React.createElement(+ Box,+ { flexDirection: 'column' },+ React.createElement(MercuryCodeView, { state: stateFor(content, true), cols: 100, rows: 24 }),+ ),+ { stdout, exitOnCtrlC: false, patchConsole: false },+ );+ await sleep(400);+ // Everything stays in the live tail (capped): newest rows visible.+ expect(stdout.output).toContain('unbroken line 39');+ expect(stdout.output).not.toContain('\x1b[3J');+ void rerender;+ unmount();+ }, 15_000);+});\ No newline at end of filediff --git a/src/ui/stream-tail.test.ts b/src/ui/stream-tail.test.tsindex 281f1883..7bdb4171 100644--- a/src/ui/stream-tail.test.ts+++ b/src/ui/stream-tail.test.ts@@ -145,8 +145,9 @@ describe('streaming tail live-region integration', () => {expect(app).toContain('export function streamTailRowCap(terminalRows: number)');expect(app).toContain('const tailCap = streamTailRowCap(rows)');expect(app).toContain("kind: 'spacer' as const, role: 'system' as const, text: ''");- // Live tail renders through the markdown pipeline, on the bounded slice.- expect(app).toContain('buildStreamTailLines(streamingMessage, contentWidth');+ // Live tail renders through the markdown pipeline, on the bounded slice —+ // now the UNSETTLED REMAINDER (settled blocks flush into <Static> mid-stream).+ expect(app).toContain('buildStreamTailLines(remainderMessage, contentWidth');// Forbidden patterns: the removed in-app viewport machinery.expect(app).not.toContain('getViewportWindow(totalWithTail');expect(app).not.toContain('wordmarkOnScreen');