Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

perf(tui): fence-aligned stream tail in chat, one shared tick, async git header, resize repaint

Salman Qureshi26d1f76aed5c
diff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patch
index b5c6447a..5afd70a9 100644
--- a/patches/ink+5.2.1.patch
+++ b/patches/ink+5.2.1.patch
@@ -94,10 +94,9 @@ index 9c54f14..6274f9a 100644
const style = useMemo(() => ({
position: 'absolute',
diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
-index a9c444f..f3457f7 100644
--- a/node_modules/ink/build/ink.js
+++ b/node_modules/ink/build/ink.js
-@@ -14,6 +14,14 @@ import logUpdate from './log-update.js';
+@@ -14,6 +14,14 @@
import instances from './instances.js';
import App from './components/App.js';
const noop = () => { };
@@ -112,7 +111,19 @@ index a9c444f..f3457f7 100644
export default class Ink {
options;
log;
-@@ -98,7 +106,33 @@ export default class Ink {
+@@ -81,6 +89,11 @@
+ }
+ }
+ resized = () => {
++ // Resize baseline reset (Cosmic Stack patch): rows that re-wrapped on
++ // resize must be repainted even when their bytes did not change, so
++ // the diff-render baseline (ours and log-update's) is dropped first.
++ this.lastOutput = '';
++ if (typeof this.log.invalidate === 'function') this.log.invalidate();
+ this.calculateLayout();
+ this.onRender();
+ };
+@@ -98,7 +111,33 @@
if (this.isUnmounted) {
return;
}
@@ -148,10 +159,9 @@ index a9c444f..f3457f7 100644
const hasStaticOutput = staticOutput && staticOutput !== '\n';
if (this.options.debug) {
diff --git a/node_modules/ink/build/log-update.js b/node_modules/ink/build/log-update.js
-index 547421e..73cb297 100644
--- a/node_modules/ink/build/log-update.js
+++ b/node_modules/ink/build/log-update.js
-@@ -13,9 +13,26 @@ const create = (stream, { showCursor = false } = {}) => {
+@@ -13,10 +13,34 @@
if (output === previousOutput) {
return;
}
@@ -177,8 +187,16 @@ index 547421e..73cb297 100644
previousLineCount = output.split('\n').length;
+ stream.write(ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n');
};
++ // Resize baseline reset (Cosmic Stack patch): forget what is on screen
++ // without touching the line count — the next render erases the old
++ // frame's rows and rewrites every row instead of diffing against rows
++ // the terminal has already re-wrapped.
++ render.invalidate = () => {
++ previousOutput = '';
++ };
render.clear = () => {
stream.write(ansiEscapes.eraseLines(previousLineCount));
+ previousOutput = '';
diff --git a/node_modules/ink/build/reconciler.js b/node_modules/ink/build/reconciler.js
index 55acec7..f440fa9 100644
--- a/node_modules/ink/build/reconciler.js
diff --git a/scripts/apply-ink-patch.cjs b/scripts/apply-ink-patch.cjs
index fe933b64..243603b9 100644
--- a/scripts/apply-ink-patch.cjs
+++ b/scripts/apply-ink-patch.cjs
@@ -61,7 +61,9 @@ function isPatched(p = paths) {
&& staticComponent.includes('itemKey')
&& staticComponent.includes('setCommitTick')
&& logUpdate.includes('Diff-render (Cosmic Stack patch)')
+ && logUpdate.includes(RESIZE_RESET_MARKER)
&& inkJs.includes('maxLiveRows')
+ && inkJs.includes(RESIZE_RESET_MARKER)
&& inkJs.includes(FRAME_GATE_MARKER);
} catch {
return false;
@@ -69,6 +71,51 @@ function isPatched(p = paths) {
}
const FRAME_GATE_MARKER = '__mercuryFrameGate';
+const RESIZE_RESET_MARKER = 'Resize baseline reset (Cosmic Stack patch)';
+
+/** Resize baseline reset: after a terminal resize the rows already on
+ * screen have re-wrapped, so the diff-render's "unchanged rows above stay"
+ * assumption is false — identical row BYTES no longer sit at the same
+ * terminal rows. Ink's `resized` handler now drops `lastOutput` and
+ * log-update's `previousOutput` baseline (keeping the line count, so the
+ * erase still covers the old frame) and the next frame repaints whole.
+ * Applies to both ink.js and log-update.js (after the diff-render edit). */
+function applyResizeBaselineReset(p = paths) {
+ const { inkJsPath, logUpdatePath } = p;
+ let lu = fs.readFileSync(logUpdatePath, 'utf8');
+ if (!lu.includes(RESIZE_RESET_MARKER)) {
+ const anchor = ' render.clear = () => {';
+ if (!lu.includes(anchor)) return false;
+ lu = lu.replace(anchor, ` // ${RESIZE_RESET_MARKER}: forget what is on screen
+ // without touching the line count — the next render erases the old
+ // frame's rows and rewrites every row instead of diffing against rows
+ // the terminal has already re-wrapped.
+ render.invalidate = () => {
+ previousOutput = '';
+ };
+${anchor}`);
+ fs.writeFileSync(logUpdatePath, lu);
+ }
+ let ink = fs.readFileSync(inkJsPath, 'utf8');
+ if (!ink.includes(RESIZE_RESET_MARKER)) {
+ const anchor = ` resized = () => {
+ this.calculateLayout();
+ this.onRender();
+ };`;
+ if (!ink.includes(anchor)) return false;
+ ink = ink.replace(anchor, ` resized = () => {
+ // ${RESIZE_RESET_MARKER}: rows that re-wrapped on
+ // resize must be repainted even when their bytes did not change, so
+ // the diff-render baseline (ours and log-update's) is dropped first.
+ this.lastOutput = '';
+ if (typeof this.log.invalidate === 'function') this.log.invalidate();
+ this.calculateLayout();
+ this.onRender();
+ };`);
+ fs.writeFileSync(inkJsPath, ink);
+ }
+ return lu.includes(RESIZE_RESET_MARKER) && ink.includes(RESIZE_RESET_MARKER);
+}
/** Diff-render log-update + freeze gate. Both live in already-patched
* files, so this is an idempotent string-insert on the applied state. */
@@ -363,6 +410,7 @@ function apply(opts = {}) {
const frameGateOk = applyInkFrameGate(p);
const liveRegionOk = applyInkLiveRegionGuard(p);
const diffRenderOk = applyLogUpdateDiffRender(p);
+ const resizeResetOk = applyResizeBaselineReset(p);
if (!reconcilerOk) {
return { ok: false, applied: true, error: 'reconciler.js no longer matches the expected ink 5.2.1 shape — patch anchors not found' };
}
@@ -378,6 +426,9 @@ function apply(opts = {}) {
if (!diffRenderOk) {
return { ok: false, applied: true, error: 'log-update.js diff-render could not be inserted' };
}
+ if (!resizeResetOk) {
+ return { ok: false, applied: true, error: 'resize baseline reset could not be inserted (ink.js resized / log-update.js clear anchors)' };
+ }
} catch (err) {
return { ok: false, applied: true, error: err.message };
}
diff --git a/scripts/apply-ink-patch.test.ts b/scripts/apply-ink-patch.test.ts
index c1e4361a..0e6f42d9 100644
--- a/scripts/apply-ink-patch.test.ts
+++ b/scripts/apply-ink-patch.test.ts
@@ -45,6 +45,10 @@ function writeStockInk(root: string): void {
'import logUpdate from \'./log-update.js\';',
'const noop = () => { };',
'export default class Ink {',
+ ' resized = () => {',
+ ' this.calculateLayout();',
+ ' this.onRender();',
+ ' };',
' onRender() {',
' const { output, outputHeight, staticOutput } = render(this.rootNode);',
' const hasStaticOutput = staticOutput && staticOutput !== \'\\n\';',
@@ -64,6 +68,9 @@ function writeStockInk(root: string): void {
' stream.write(ansiEscapes.eraseLines(previousLineCount) + output);',
" previousLineCount = output.split('\\n').length;",
' };',
+ ' render.clear = () => {',
+ ' stream.write(ansiEscapes.eraseLines(previousLineCount));',
+ ' };',
' return render;',
'};',
].join('\n'));
@@ -79,6 +86,16 @@ describe('ink patch applier (patch-package-free)', () => {
expect(result.applied).toBe(true);
expect(result.error).toBeUndefined();
expect(isPatched(pathsFor(root))).toBe(true);
+ const paths = pathsFor(root);
+ const inkJs = readFileSync(paths.inkJsPath, 'utf8');
+ const logUpdate = readFileSync(paths.logUpdatePath, 'utf8');
+ // Resize baseline reset: resized() drops both diff baselines BEFORE
+ // the re-layout + render, and log-update exposes the invalidate hook.
+ expect(logUpdate).toContain('render.invalidate = () => {');
+ const resized = inkJs.slice(inkJs.indexOf('resized = () => {'), inkJs.indexOf('onRender() {'));
+ expect(resized).toContain("this.lastOutput = '';");
+ expect(resized).toContain('this.log.invalidate()');
+ expect(resized.indexOf('this.log.invalidate()')).toBeLessThan(resized.indexOf('this.calculateLayout()'));
// Idempotent: a second run must recognize the applied state and no-op.
const again = apply({ root });
expect(again.ok).toBe(true);
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index c0e3f91b..8190433b 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -1082,7 +1082,7 @@ export class CLIChannel extends BaseChannel {
this.exitMercuryCode();
return;
}
- if (sub === 'git-refresh') { this.refreshMercuryCodeGit(); return; }
+ if (sub === 'git-refresh') { void this.refreshMercuryCodeGit(); return; }
return;
}
if (trimmed === '/mc') {
@@ -2312,7 +2312,11 @@ export class CLIChannel extends BaseChannel {
mercuryCode: {
cwd: target,
dirName,
- git: this.readGitStateQuick(target),
+ // Filled in asynchronously below: a blocking git read here stalled
+ // the first frame. An EMPTY branch means "not read yet" (the status
+ // bar hides the segment); 'no-git' is the settled "not a repo"
+ // answer, which also disables completion-time change stats.
+ git: { branch: '', ahead: 0, behind: 0, dirty: 0 },
mouse: false,
scrollOffset: 0,
exitConfirm: false,
@@ -2332,6 +2336,8 @@ export class CLIChannel extends BaseChannel {
// throttled background update check. Entirely async and unref'd — a slow
// npm look-up must never stall the TUI.
void this.announceVersionNotices(version);
+ // Branch / ahead / behind / dirty for the status bar — off the hot path.
+ void this.refreshMercuryCodeGit();
return { ok: true, message: `Mercury Code active in ${dirName}` };
}
@@ -2415,34 +2421,44 @@ export class CLIChannel extends BaseChannel {
this.update({ mercuryCode: { ...mc, scrollOffset: 0 } });
}
- /** Refresh cached git header state from disk. */
- refreshMercuryCodeGit(): void {
+ /** A git header refresh in flight (coalesces overlapping requests). */
+ private gitRefreshInFlight: Promise<void> | null = null;
+
+ /**
+ * Refresh the cached git header state from disk — asynchronously. The
+ * old `execSync` pair blocked the event loop for the whole `git status`
+ * (hundreds of ms on a large tree), freezing streaming and input every
+ * time Mercury Code entered or `/mc git-refresh` ran.
+ */
+ refreshMercuryCodeGit(): Promise<void> {
+ if (this.gitRefreshInFlight) return this.gitRefreshInFlight;
const mc = this.state.mercuryCode;
- if (!mc) return;
- const git = this.readGitStateQuick(mc.cwd);
- if (
- git.branch !== mc.git.branch ||
- git.ahead !== mc.git.ahead ||
- git.behind !== mc.git.behind ||
- git.dirty !== mc.git.dirty
- ) {
- this.update({ mercuryCode: { ...mc, git } });
- }
+ if (!mc) return Promise.resolve();
+ const cwd = mc.cwd;
+ this.gitRefreshInFlight = this.readGitStateQuick(cwd)
+ .then((git) => {
+ const current = this.state.mercuryCode;
+ // The session may have left Mercury Code (or moved) meanwhile.
+ if (!current || current.cwd !== cwd) return;
+ if (
+ git.branch !== current.git.branch ||
+ git.ahead !== current.git.ahead ||
+ git.behind !== current.git.behind ||
+ git.dirty !== current.git.dirty
+ ) {
+ this.update({ mercuryCode: { ...current, git } });
+ }
+ })
+ .catch((err) => logger.debug({ err }, 'git header refresh failed'))
+ .finally(() => { this.gitRefreshInFlight = null; });
+ return this.gitRefreshInFlight;
}
- private readGitStateQuick(rootPath: string): MercuryCodeGitState {
- try {
- const branch = execSync('git -C ' + JSON.stringify(rootPath) + ' branch --show-current', { stdio: 'pipe' }).toString().trim() || 'detached';
- const out = execSync('git -C ' + JSON.stringify(rootPath) + ' status --porcelain=v1 --branch', { stdio: 'pipe' }).toString();
- const lines = out.split('\n');
- const header = lines[0] || '';
- const ahead = parseInt(header.match(/ahead (\d+)/)?.[1] ?? '0', 10);
- const behind = parseInt(header.match(/behind (\d+)/)?.[1] ?? '0', 10);
- const dirty = lines.slice(1).filter((l) => l.trim().length > 0).length;
- return { branch, ahead, behind, dirty };
- } catch {
- return { branch: 'no-git', ahead: 0, behind: 0, dirty: 0 };
- }
+ /** Header-sized git state (branch / ahead / behind / dirty count) via async execFile. */
+ private async readGitStateQuick(rootPath: string): Promise<MercuryCodeGitState> {
+ const state = await this.readGitStateAsync(rootPath);
+ if (state.branch === 'not-a-git-repo') return { branch: 'no-git', ahead: 0, behind: 0, dirty: 0 };
+ return { branch: state.branch, ahead: state.ahead, behind: state.behind, dirty: state.files.length };
}
setProgrammingStatus(mode: import('../core/programming-mode.js').ProgrammingModeState, projectContext: string | null): void {
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 908eb7a7..09e73a5c 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -11,6 +11,7 @@ import { isDevBuild } from '../utils/dev-build.js';
import { highlightCodeBlock } from '../utils/highlight.js';
import { normalizeTerminalText, getViewportWindow } from './terminal-viewport.js';
import { useTerminalSize as useSharedTerminalSize } from './use-terminal-size.js';
+import { useTick, spinnerFrame, elapsedSeconds, SPINNER_FRAMES } from './tick-store.js';
import { buildMercuryMessageLines, buildMercuryBrandLines, buildStreamTailLines, parseChunkIndex, splitFinalMessage, splitStreamingMessage, type MercuryTranscriptLine } from './mercury-transcript.js';
import { GENERIC_PHASES, PLANNING_VERBS, lastUserText, pickStatusWord } from './status-word.js';
import { nextTip, rotateTip } from './tips.js';
@@ -833,7 +834,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
) : null}
{state.mode === 'spotify' ? <SpotifyBody activeIdx={spotifyIdx} nowPlaying={spotifyNow} status={spotifyStatus} volume={spotifyVolume} albumArtAnsi={spotifyArtAnsi} /> : null}
{state.mode === 'menu' ? <MenuBody menuIdx={menuIdx} /> : null}
- {state.mode === 'coding' ? <CodingBody state={state} maxDynamicLines={Math.min(12, Math.max(3, terminalSize.rows - 14))} /> : null}
+ {state.mode === 'coding' ? <CodingBody state={state} maxDynamicLines={Math.min(12, Math.max(3, terminalSize.rows - 14))} cols={terminalSize.cols} /> : null}
{state.mode === 'workspace' ? (
<WorkspaceBody state={state} gitCursor={gitCursor} height={Math.max(8, terminalSize.rows - 6)} cols={terminalSize.cols} onInput={onInput} />
) : null}
@@ -842,7 +843,7 @@ export function TuiApp({ channel, onInput, onPermissionResolve, onExit, onInterr
// repaint per frame — finalized content is already in <Static>. A
// near-full-screen live region was rewritten every 60ms frame, which
// read as a visible "on-off" flicker on long chats.
- <ChatBody state={state} maxDynamicLines={Math.min(12, Math.max(3, terminalSize.rows - 14))} />
+ <ChatBody state={state} maxDynamicLines={Math.min(12, Math.max(3, terminalSize.rows - 14))} cols={terminalSize.cols} />
) : null}
{state.permissionPrompt && state.mode !== 'mercury-code' && (
<PermPromptView prompt={state.permissionPrompt} activeIdx={permIdx} />
@@ -1043,7 +1044,7 @@ function formatCompact(n: number): string {
return String(n);
}
-function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines: number }) {
+function ChatBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDynamicLines: number; cols: number }) {
// Static-output bound: Ink's <Static> accumulates every rendered item in a
// monotonically growing output string that is re-written on each frame.
// Retaining the entire transcript there is O(N²) work and permanent heap;
@@ -1064,7 +1065,7 @@ function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines
? <HeaderBanner key={item} />
: <ChatMessagesView key={item.id} messages={[item]} agentName={state.agentName} />}
</Static>
- <ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />
+ <StreamingMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} width={cols - (state.sidebarSections.length > 0 ? 30 : 0)} />
{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}
{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}
{state.botChat && !state.isThinking && (
@@ -1082,7 +1083,7 @@ function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines
);
}
-function CodingBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines: number }) {
+function CodingBody({ state, maxDynamicLines, cols }: { state: TuiState; maxDynamicLines: number; cols: number }) {
const modeLabels: Record<ProgrammingModeState, { label: string; color: string }> = {
off: { label: 'OFF', color: 'gray' },
auto: { label: 'AUTO', color: 'cyan' },
@@ -1123,7 +1124,7 @@ function CodingBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLin
? <HeaderBanner key={item} />
: <ChatMessagesView key={item.id} messages={[item]} agentName={state.agentName} />}
</Static>
- <ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />
+ <StreamingMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} width={cols - (state.sidebarSections.length > 0 ? 30 : 0)} />
{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}
{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} liveActivity={state.liveActivity} thinkingPreview={state.thinkingPreview} />}
{state.botChat && !state.isThinking && (
@@ -1631,6 +1632,82 @@ function SpotifyBody({ activeIdx, nowPlaying, status, volume, albumArtAnsi }: {
);
}
+/**
+ * Throttled live tail of the streaming message (shared by chat, coding and
+ * Mercury Code). Recomputes at most every 120 ms while content grows, with
+ * a TRAILING flush: the frame after the last delta always repaints with
+ * the complete text (the old memo returned the stale cache and left the
+ * final chunk unrendered until something else re-rendered).
+ */
+function useThrottledStreamTail<T>(
+ message: ChatMessage | null | undefined,
+ compute: (message: ChatMessage) => T,
+ empty: T,
+ deps: readonly unknown[],
+): T {
+ const cacheRef = React.useRef<null | { id: string; at: number; contentLength: number; value: T; deps: readonly unknown[] }>(null);
+ const [, bump] = React.useReducer((n: number) => n + 1, 0);
+ const trailingRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
+ React.useEffect(() => () => { if (trailingRef.current) clearTimeout(trailingRef.current); }, []);
+ if (!message) {
+ cacheRef.current = null;
+ return empty;
+ }
+ const now = Date.now();
+ const cache = cacheRef.current;
+ const sameDeps = cache !== null && cache.deps.length === deps.length && cache.deps.every((d, i) => d === deps[i]);
+ if (cache && sameDeps && cache.id === message.id && cache.contentLength === message.content.length) return cache.value;
+ if (cache && sameDeps && cache.id === message.id && now - cache.at < STREAM_TAIL_THROTTLE_MS && cache.contentLength <= message.content.length) {
+ // Stale but inside the window: schedule the trailing repaint once.
+ if (!trailingRef.current) {
+ trailingRef.current = setTimeout(() => { trailingRef.current = null; bump(); }, STREAM_TAIL_THROTTLE_MS - (now - cache.at) + 1);
+ }
+ return cache.value;
+ }
+ const value = compute(message);
+ cacheRef.current = { id: message.id, at: now, contentLength: message.content.length, value, deps };
+ return value;
+}
+
+const STREAM_TAIL_THROTTLE_MS = 120;
+
+/**
+ * The streaming agent message in chat / coding mode. Renders only the
+ * fence-aligned tail of the buffer (buildStreamTailLines — the same
+ * renderer Mercury Code uses) instead of running renderMarkdown over the
+ * ENTIRE buffer on every delta, which was O(message) work per frame and
+ * the main reason long replies made the TUI crawl.
+ */
+function StreamingMessageTail({ message, agentName, maxLines, width }: { message: ChatMessage; agentName: string; maxLines: number; width: number }) {
+ const lines = useThrottledStreamTail(
+ message,
+ (m) => buildStreamTailLines(m, width, STREAM_TAIL_CHARS, maxLines, { showHeader: false }),
+ [] as MercuryTranscriptLine[],
+ [width, maxLines],
+ );
+ return (
+ <Box flexDirection="column" marginBottom={1} flexShrink={0}>
+ <Box flexShrink={0}>
+ <Text bold color="cyan">{agentName}:</Text>
+ </Box>
+ <Box flexDirection="column" flexShrink={0}>
+ {lines.map((line) => <MercuryTranscriptRow key={line.key} line={line} />)}
+ </Box>
+ </Box>
+ );
+}
+
+function StreamingMessagesView({ messages, agentName, maxLines, width }: { messages: ChatMessage[]; agentName: string; maxLines: number; width: number }) {
+ if (messages.length === 0) return null;
+ return (
+ <Box flexDirection="column" flexGrow={1} flexShrink={0} paddingX={1}>
+ {messages.slice(-3).map((msg) => (
+ <StreamingMessageTail key={msg.id} message={msg} agentName={agentName} maxLines={maxLines} width={width} />
+ ))}
+ </Box>
+ );
+}
+
function ChatMessagesView({ messages, agentName, maxLines }: { messages: ChatMessage[]; agentName: string; maxLines?: number }) {
if (messages.length === 0) return null;
@@ -1725,8 +1802,6 @@ const MessageRow = React.memo(function MessageRow({
);
});
-const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
-
/**
* Animated row for a currently-running tool step.
*
@@ -1740,19 +1815,12 @@ const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧',
* > 90s : red — long-op warning (mentions Ctrl+C)
*/
function RunningStepRow({ step }: { step: ToolStep }) {
- const [frame, setFrame] = React.useState(0);
- const [elapsed, setElapsed] = React.useState(() =>
- step.startedAt ? Math.floor((Date.now() - step.startedAt) / 1000) : 0,
- );
-
- React.useEffect(() => {
- const startedAt = step.startedAt ?? Date.now();
- const timer = setInterval(() => {
- setFrame((v) => (v + 1) % SPINNER_FRAMES.length);
- setElapsed(Math.floor((Date.now() - startedAt) / 1000));
- }, 80);
- return () => clearInterval(timer);
- }, [step.startedAt]);
+ // Shared 100 ms tick (tick-store.ts): one timer for every animated row.
+ const tick = useTick();
+ const frame = tick % SPINNER_FRAMES.length;
+ const startedAtRef = React.useRef(step.startedAt ?? Date.now());
+ if (step.startedAt) startedAtRef.current = step.startedAt;
+ const elapsed = elapsedSeconds(startedAtRef.current);
const tone = elapsed >= 90 ? 'red' : elapsed >= 30 ? 'yellow' : 'cyan';
const mins = Math.floor(elapsed / 60);
@@ -1823,23 +1891,14 @@ function ToolStepsView({ steps, viewMode, idle }: { steps: ToolStep[]; viewMode:
}
function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPreview, frozen, title, longOpHint }: { agentName: string; steps: ToolStep[]; mode: AppMode; liveActivity?: LiveActivityState | null; thinkingPreview?: string | null; frozen?: boolean; title?: string; longOpHint?: boolean }) {
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
- const [frame, setFrame] = React.useState(0);
- const [elapsed, setElapsed] = React.useState(0);
+ const frames = SPINNER_FRAMES;
const startRef = React.useRef(Date.now());
+ // Shared 100 ms tick. Scroll lock: an unsubscribed (frozen) indicator
+ // commits no frames at all.
+ const frame = useTick(!frozen) % frames.length;
+ const elapsed = elapsedSeconds(startRef.current);
- React.useEffect(() => {
- startRef.current = Date.now();
- // Scroll lock: the self-ticker must not repaint while frames are frozen.
- if (frozen) return;
- const timer = setInterval(() => {
- setFrame((v) => (v + 1) % frames.length);
- setElapsed(Math.floor((Date.now() - startRef.current) / 1000));
- }, 80);
- return () => clearInterval(timer);
- }, [frozen]);
-
- const spinner = frames[frame % frames.length];
+ const spinner = frames[frame];
const runningStep = [...steps].reverse().find((s) => s.status === 'running');
const doneSteps = steps.filter((s) => s.status === 'done');
const totalSteps = steps.length;
@@ -1855,7 +1914,7 @@ function ThinkingIndicator({ agentName, steps, mode, liveActivity, thinkingPrevi
: (mode === 'coding' || mode === 'workspace') ? 'Analyzing code' : 'Composing response';
const displayElapsed = runningStep?.startedAt
- ? Math.floor((Date.now() - runningStep.startedAt) / 1000) + (frame * 0)
+ ? elapsedSeconds(runningStep.startedAt)
: elapsed;
const actionTone = displayElapsed >= 90 ? 'red' : displayElapsed >= 30 ? 'yellow' : 'white';
@@ -1918,14 +1977,12 @@ function BotFleetLiveRegion({ botId, botName, botLiveActivity, botStreamTails, b
const crew = botRoster.filter(b => b.parent === botId);
const crewLive = crew.filter(c => botLiveActivity[c.id]);
const ownTail = botStreamTails[botId];
- if (!own && crewLive.length === 0 && !ownTail) return null;
+ const visible = Boolean(own || crewLive.length > 0 || ownTail);
+ // Shared 100 ms tick; subscribed only while there is something to animate.
+ const tick = useTick(visible);
+ if (!visible) return null;
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
- const [tick, setTick] = React.useState(0);
- React.useEffect(() => {
- const timer = setInterval(() => setTick(v => v + 1), 250);
- return () => clearInterval(timer);
- }, []);
+ const frames = SPINNER_FRAMES;
const row = (id: string, name: string, label: string, indent: string): React.ReactNode => {
return (
@@ -2288,28 +2345,17 @@ function MercuryCodeHints({ cols }: { cols: number }): React.ReactNode {
/** Single active live-feedback block: phase + elapsed + running tool + done ticks + swarm. */
function MercuryLiveFeedback({ state }: { state: TuiState }): React.ReactNode {
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
- const [frame, setFrame] = React.useState(0);
- const [, forceTick] = React.useState(0);
+ const frames = SPINNER_FRAMES;
// Finished steps are not repeated here: each one is already a block in
// the transcript above (tool-block.ts). Only live work shows.
const running = [...state.toolSteps].reverse().find((s) => s.status === 'running');
const activeAgents = state.subAgents.filter((a) => a.status === 'running' || a.status === 'paused');
const activity = state.liveActivity;
const active = Boolean(running || state.isThinking || activeAgents.length > 0 || activity);
- React.useEffect(() => {
- if (!active || state.mode !== 'mercury-code') return;
- // Scroll lock: the self-ticker must not repaint while the TUI is frozen
- // (each tick commits a frame — frame writes are what freezing stops).
- if (state.tuiFrozen) return;
- // 100ms tick: smooth spinner AND a live seconds counter. The old 250ms
- // tick with no elapsed read as frozen during long tool calls.
- const t = setInterval(() => {
- setFrame((v) => (v + 1) % frames.length);
- forceTick((v) => v + 1);
- }, 100);
- return () => clearInterval(t);
- }, [active, state.mode, state.tuiFrozen]);
+ // Shared 100 ms tick: smooth spinner AND a live seconds counter. Scroll
+ // lock: a frozen screen is not subscribed, so no frame is committed.
+ const forceTick = useTick(active && state.mode === 'mercury-code' && !state.tuiFrozen);
+ const frame = forceTick % frames.length;
// "Did you know?" tip row: after a minute of a running task, ONE dim tip
// appears and its content rotates a couple of times — the row's height is
@@ -2653,28 +2699,22 @@ export function MercuryCodeView({
// 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(() => {
- if (!streamingMessage) {
- tailRef.current = null;
- return [] as MercuryTranscriptLine[];
- }
- const now = Date.now();
- const cache = tailRef.current;
- if (cache && cache.id === streamingMessage.id && now - cache.at < 120 && cache.contentLength <= streamingMessage.content.length) {
- return cache.lines;
- }
- // 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) };
- // Role marker only while the remainder is still the message's first block.
- const lines = buildStreamTailLines(remainderMessage, contentWidth, STREAM_TAIL_CHARS, tailCap, { showHeader: streamingChunks.remainderStart === 0 });
- 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, streamingChunks, contentWidth, tailCap]);
+ // 120 ms throttle with a trailing flush (useThrottledStreamTail): the
+ // last delta of a stream is always painted.
+ const streamTail = useThrottledStreamTail(
+ streamingMessage,
+ (message) => {
+ // 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 = { ...message, content: message.content.slice(streamingChunks.remainderStart) };
+ // Role marker only while the remainder is still the message's first block.
+ return buildStreamTailLines(remainderMessage, contentWidth, STREAM_TAIL_CHARS, tailCap, { showHeader: streamingChunks.remainderStart === 0 });
+ },
+ [] as MercuryTranscriptLine[],
+ [contentWidth, tailCap, streamingChunks.remainderStart],
+ );
const paddedStreamTail = React.useMemo(() => {
if (streamTail.length === 0) return streamTail;
const pad = tailCap - streamTail.length;
@@ -2715,7 +2755,8 @@ export function MercuryCodeView({
const mode = state.programmingMode;
const modeLabel = mode === 'execute' ? 'EXECUTE' : mode === 'plan' ? 'PLAN' : mode === 'auto' ? 'AUTO' : 'CHAT';
const git = mc.git;
- const hasGit = git.branch !== 'no-git' && git.branch !== 'not-a-git-repo';
+ // '' = not read yet (async refresh pending); hide the segment until then.
+ const hasGit = git.branch !== '' && git.branch !== 'no-git' && git.branch !== 'not-a-git-repo';
const rightSegs: Array<{ text: string; color: string }> = [{ text: mc.dirName, color: THEME_ACCENT }];
if (hasGit) {
const gitBits = [`⎇ ${git.branch}`];
diff --git a/src/ui/tick-store.test.ts b/src/ui/tick-store.test.ts
new file mode 100644
index 00000000..d33877ed
--- /dev/null
+++ b/src/ui/tick-store.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { subscribe, getSnapshot, subscriberCount, isRunning, spinnerFrame, elapsedSeconds, TICK_MS, SPINNER_FRAMES } from './tick-store.js';
+
+/**
+ * One shared interval for every animated row: it runs only while someone
+ * is subscribed, every subscriber sees the same tick, and elapsed time is
+ * derived from Date.now() rather than counted per tick.
+ */
+describe('tick store', () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it('starts with the first subscriber and stops with the last', () => {
+ expect(isRunning()).toBe(false);
+ const a = vi.fn();
+ const b = vi.fn();
+ const offA = subscribe(a);
+ expect(isRunning()).toBe(true);
+ const offB = subscribe(b);
+ expect(subscriberCount()).toBe(2);
+
+ const before = getSnapshot();
+ vi.advanceTimersByTime(TICK_MS * 3);
+ expect(getSnapshot()).toBe(before + 3);
+ expect(a).toHaveBeenCalledTimes(3);
+ expect(b).toHaveBeenCalledTimes(3);
+
+ offA();
+ expect(isRunning()).toBe(true);
+ offB();
+ expect(isRunning()).toBe(false);
+ expect(subscriberCount()).toBe(0);
+
+ // No subscribers → the clock is stopped, not ticking in the background.
+ const idle = getSnapshot();
+ vi.advanceTimersByTime(TICK_MS * 5);
+ expect(getSnapshot()).toBe(idle);
+ });
+
+ it('a throwing listener does not stop the clock for the others', () => {
+ const bad = vi.fn(() => { throw new Error('boom'); });
+ const good = vi.fn();
+ const offBad = subscribe(bad);
+ const offGood = subscribe(good);
+ vi.advanceTimersByTime(TICK_MS * 2);
+ expect(good).toHaveBeenCalledTimes(2);
+ offBad();
+ offGood();
+ });
+
+ it('spinner frames cycle on the tick and elapsed seconds derive from Date.now()', () => {
+ expect(spinnerFrame(0)).toBe(SPINNER_FRAMES[0]);
+ expect(spinnerFrame(SPINNER_FRAMES.length + 1)).toBe(SPINNER_FRAMES[1]);
+ expect(spinnerFrame(1, 3)).toBe(SPINNER_FRAMES[4]);
+ expect(elapsedSeconds(undefined)).toBe(0);
+ expect(elapsedSeconds(10_000, 13_400)).toBe(3);
+ expect(elapsedSeconds(20_000, 13_400)).toBe(0); // never negative
+ });
+});
diff --git a/src/ui/tick-store.ts b/src/ui/tick-store.ts
new file mode 100644
index 00000000..5b78fd3d
--- /dev/null
+++ b/src/ui/tick-store.ts
@@ -0,0 +1,92 @@
+import { useSyncExternalStore } from 'react';
+
+/**
+ * One shared 100 ms tick for every animated row in the TUI.
+ *
+ * Before this module each spinner / elapsed counter / size poll owned its
+ * own `setInterval` (80 ms, 80 ms per running step, 250 ms, 100 ms, 500 ms):
+ * five unsynchronised timers each committing a React frame, so a busy
+ * screen repainted far more often than any one of them intended. Now there
+ * is a single interval that runs ONLY while someone is subscribed, and
+ * every consumer re-renders on the same edge. Elapsed times are derived
+ * from `Date.now()` at render, never accumulated per tick.
+ *
+ * `subscribe` / `getSnapshot` are the `useSyncExternalStore` pair; the
+ * `useTick(active)` hook is the convenience wrapper (an inactive consumer
+ * is not subscribed at all, so a frozen screen keeps no timer alive).
+ */
+export const TICK_MS = 100;
+
+const listeners = new Set<() => void>();
+let tick = 0;
+let timer: ReturnType<typeof setInterval> | null = null;
+
+function start(): void {
+ if (timer) return;
+ timer = setInterval(() => {
+ tick += 1;
+ for (const listener of listeners) {
+ try { listener(); } catch { /* a listener must never stop the clock */ }
+ }
+ }, TICK_MS);
+ (timer as { unref?: () => void }).unref?.();
+}
+
+function stop(): void {
+ if (!timer) return;
+ clearInterval(timer);
+ timer = null;
+}
+
+/** Subscribe to the shared tick; the interval starts with the first subscriber and stops with the last. */
+export function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ start();
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) stop();
+ };
+}
+
+/** Current tick count (monotonic while anyone is subscribed). */
+export function getSnapshot(): number {
+ return tick;
+}
+
+/** Number of live subscribers (tests / diagnostics). */
+export function subscriberCount(): number {
+ return listeners.size;
+}
+
+/** True while the shared interval is running. */
+export function isRunning(): boolean {
+ return timer !== null;
+}
+
+const noopSubscribe = (): (() => void) => () => {};
+const zeroSnapshot = (): number => 0;
+
+/**
+ * Re-render on every shared tick while `active`; when inactive the
+ * component is not subscribed and sees a constant 0.
+ */
+export function useTick(active = true): number {
+ return useSyncExternalStore(
+ active ? subscribe : noopSubscribe,
+ active ? getSnapshot : zeroSnapshot,
+ active ? getSnapshot : zeroSnapshot,
+ );
+}
+
+export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;
+
+/** Spinner glyph for a tick (optionally offset so parallel rows differ). */
+export function spinnerFrame(tickValue: number, offset = 0): string {
+ return SPINNER_FRAMES[Math.abs(tickValue + offset) % SPINNER_FRAMES.length];
+}
+
+/** Whole seconds elapsed since `startedAt` (0 when unknown). */
+export function elapsedSeconds(startedAt: number | undefined | null, now = Date.now()): number {
+ if (!startedAt) return 0;
+ return Math.max(0, Math.floor((now - startedAt) / 1000));
+}
diff --git a/src/ui/use-terminal-size.ts b/src/ui/use-terminal-size.ts
index 18659c2a..60681505 100644
--- a/src/ui/use-terminal-size.ts
+++ b/src/ui/use-terminal-size.ts
@@ -1,28 +1,32 @@
import React from 'react';
import { useStdout } from 'ink';
+import { subscribe as subscribeTick } from './tick-store.js';
/**
- * Live terminal size. Listens to stdout resize and polls as a fallback — some
- * terminal/pty setups (remote-desktop sessions, multiplexers) don't deliver
- * the resize event when the window changes, and a stale size breaks any
- * explicit-width layout.
+ * Live terminal size. Listens to stdout resize and re-checks on the shared
+ * 100 ms tick as a fallback — some terminal/pty setups (remote-desktop
+ * sessions, multiplexers) don't deliver the resize event when the window
+ * changes, and a stale size breaks any explicit-width layout. The check
+ * is a property read; the component re-renders only when the size
+ * actually changed (the snapshot object is reused while it is equal).
*/
export function useTerminalSize(): { rows: number; cols: number } {
const { stdout } = useStdout();
- const [size, setSize] = React.useState({ rows: stdout.rows || 24, cols: stdout.columns || 80 });
- React.useEffect(() => {
- const onResize = () => {
- const rows = stdout.rows || 24;
- const cols = stdout.columns || 80;
- setSize((current) => current.rows === rows && current.cols === cols ? current : { rows, cols });
- };
- stdout.on('resize', onResize);
- const fallback = setInterval(onResize, 500);
- fallback.unref?.();
+ const cacheRef = React.useRef<{ rows: number; cols: number }>({ rows: stdout.rows || 24, cols: stdout.columns || 80 });
+ const getSnapshot = React.useCallback(() => {
+ const rows = stdout.rows || 24;
+ const cols = stdout.columns || 80;
+ const current = cacheRef.current;
+ if (current.rows !== rows || current.cols !== cols) cacheRef.current = { rows, cols };
+ return cacheRef.current;
+ }, [stdout]);
+ const subscribe = React.useCallback((listener: () => void) => {
+ stdout.on('resize', listener);
+ const unsubscribeTick = subscribeTick(listener);
return () => {
- stdout.off('resize', onResize);
- clearInterval(fallback);
+ stdout.off('resize', listener);
+ unsubscribeTick();
};
}, [stdout]);
- return size;
-}
\ No newline at end of file
+ return React.useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}