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.

feat(ink): synchronized output — paint every frame atomically (DEC 2026)

Salman Qureshi3e2b932f9c51
diff --git a/docs/ink-patch.md b/docs/ink-patch.md
index 21f8f944..1c3f7611 100644
--- a/docs/ink-patch.md
+++ b/docs/ink-patch.md
@@ -87,6 +87,19 @@ The attribute lives on ink's DOM node instead of a ref for a reason. React attac
**Upstream.** Ink has no cursor API in 5.x. A proposal could be a public `useCursor()` hook or a `<Cursor />` marker component that resolves the same way, plus the park/unpark contract in log-update. The tests in `src/ui/hardware-cursor.test.tsx` show the expected byte sequences: wide characters, diff frames, cursor-only moves, trim, `<Static>` output, resize and unmount.
+
+## 8. Synchronized output (`ink.js`, `log-update.js`)
+
+**Problem.** A frame reaches the terminal as an erase followed by a redraw, and a new transcript line takes three writes: erase the live region, print the line, redraw. Terminals paint between those steps, so the user briefly sees the region blank or half-drawn. That is the flicker in iTerm2, kitty, WezTerm, Ghostty and Windows Terminal, and it is worst while a reply streams.
+
+**Fix.** Bracket each update in BSU/ESU (`ESC[?2026h` … `ESC[?2026l`, DEC private mode 2026), so the terminal swaps the finished frame in at once.
+- log-update brackets its own single writes. This also covers the throttled path, which writes after `onRender` returns.
+- `Ink.synchronized()` brackets multi-write sequences (clear + static + frame, and the console write-through paths) as one update. log-update skips its own brackets while one is open.
+- The gate matches upstream's `shouldSynchronize()`: a TTY, not CI, not debug.
+- Terminals without mode 2026 ignore both sequences.
+
+**Upstream.** Ink 6.7 shipped this (#866). This hunk is a backport, and it goes away with the move to Ink 8.
+
---
## Upgrading ink
diff --git a/patches/ink+5.2.1.patch b/patches/ink+5.2.1.patch
index 34b87ab4..3a925dd1 100644
--- a/patches/ink+5.2.1.patch
+++ b/patches/ink+5.2.1.patch
@@ -94,7 +94,7 @@ index 6bb7894..e22c94e 100644
const style = useMemo(() => ({
position: 'absolute',
diff --git a/node_modules/ink/build/ink.js b/node_modules/ink/build/ink.js
-index 68d3045..b6adc6d 100644
+index 68d3045..4fd2a7c 100644
--- a/node_modules/ink/build/ink.js
+++ b/node_modules/ink/build/ink.js
@@ -14,6 +14,53 @@ import logUpdate from './log-update.js';
@@ -124,7 +124,7 @@ index 68d3045..b6adc6d 100644
+// in-place node_modules edit.
+export const inkPatch = {
+ vendored: true,
-+ hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning'],
++ hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'],
+};
+globalThis.__mercuryInkPatch = inkPatch;
+const sameCursor = (a, b) => (!a && !b) || (!!a && !!b && a.row === b.row && a.col === b.col);
@@ -151,7 +151,17 @@ index 68d3045..b6adc6d 100644
export default class Ink {
options;
log;
-@@ -81,6 +128,11 @@ export default class Ink {
+@@ -41,7 +88,8 @@ export default class Ink {
+ trailing: true,
+ });
+ this.rootNode.onImmediateRender = this.onRender;
+- this.log = logUpdate.create(options.stdout);
++ // Synchronized output (Cosmic Stack patch): same gate as upstream shouldSynchronize().
++ this.log = logUpdate.create(options.stdout, { synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug });
+ this.throttledLog = options.debug
+ ? this.log
+ : throttle(this.log, undefined, {
+@@ -81,6 +129,11 @@ export default class Ink {
}
}
resized = () => {
@@ -163,7 +173,7 @@ index 68d3045..b6adc6d 100644
this.calculateLayout();
this.onRender();
};
-@@ -94,11 +146,53 @@ export default class Ink {
+@@ -94,11 +147,53 @@ export default class Ink {
this.rootNode.yogaNode.setWidth(terminalWidth);
this.rootNode.yogaNode.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
};
@@ -218,12 +228,18 @@ index 68d3045..b6adc6d 100644
// If <Static> output isn't empty, it means new children have been added to it
const hasStaticOutput = staticOutput && staticOutput !== '\n';
if (this.options.debug) {
-@@ -127,12 +221,13 @@ export default class Ink {
+@@ -125,19 +220,41 @@ export default class Ink {
+ }
+ // To ensure static output is cleanly rendered before main output, clear main output first
if (hasStaticOutput) {
- this.log.clear();
- this.options.stdout.write(staticOutput);
+- this.log.clear();
+- this.options.stdout.write(staticOutput);
- this.log(output);
-+ this.log(output, cursor);
++ this.synchronized(() => {
++ this.log.clear();
++ this.options.stdout.write(staticOutput);
++ this.log(output, cursor);
++ });
}
- if (!hasStaticOutput && output !== this.lastOutput) {
- this.throttledLog(output);
@@ -235,21 +251,57 @@ index 68d3045..b6adc6d 100644
};
render(node) {
const tree = (React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, exitOnCtrlC: this.options.exitOnCtrlC, onExit: this.unmount }, node));
-@@ -152,7 +247,7 @@ export default class Ink {
+ reconciler.updateContainer(tree, this.container, null, noop);
+ }
++ // Synchronized output (Cosmic Stack patch): run several writes as ONE terminal update (DEC
++ // mode 2026), so a new transcript line and the redrawn live region
++ // appear together instead of erase → static → redraw.
++ synchronized(write) {
++ const log = this.log;
++ if (!log.synchronize) {
++ write();
++ return;
++ }
++ this.options.stdout.write('\u001B[?2026h');
++ log.syncDepth++;
++ try {
++ write();
++ }
++ finally {
++ log.syncDepth--;
++ this.options.stdout.write('\u001B[?2026l');
++ }
++ }
+ writeToStdout(data) {
+ if (this.isUnmounted) {
+ return;
+@@ -150,9 +267,11 @@ export default class Ink {
+ this.options.stdout.write(data);
+ return;
}
- this.log.clear();
- this.options.stdout.write(data);
+- this.log.clear();
+- this.options.stdout.write(data);
- this.log(this.lastOutput);
-+ this.log(this.lastOutput, this.lastCursor);
++ this.synchronized(() => {
++ this.log.clear();
++ this.options.stdout.write(data);
++ this.log(this.lastOutput, this.lastCursor);
++ });
}
writeToStderr(data) {
if (this.isUnmounted) {
-@@ -169,7 +264,7 @@ export default class Ink {
+@@ -167,9 +286,11 @@ export default class Ink {
+ this.options.stderr.write(data);
+ return;
}
- this.log.clear();
- this.options.stderr.write(data);
+- this.log.clear();
+- this.options.stderr.write(data);
- this.log(this.lastOutput);
-+ this.log(this.lastOutput, this.lastCursor);
++ this.synchronized(() => {
++ this.log.clear();
++ this.options.stderr.write(data);
++ this.log(this.lastOutput, this.lastCursor);
++ });
}
// eslint-disable-next-line @typescript-eslint/ban-types
unmount(error) {
@@ -270,10 +322,19 @@ index 8068bd3..ff501a9 100644
declare const logUpdate: {
create: (stream: Writable, { showCursor }?: {
diff --git a/node_modules/ink/build/log-update.js b/node_modules/ink/build/log-update.js
-index 4c72645..501a658 100644
+index 4c72645..22efece 100644
--- a/node_modules/ink/build/log-update.js
+++ b/node_modules/ink/build/log-update.js
-@@ -4,25 +4,81 @@ const create = (stream, { showCursor = false } = {}) => {
+@@ -1,28 +1,91 @@
+ import ansiEscapes from 'ansi-escapes';
+ import cliCursor from 'cli-cursor';
+-const create = (stream, { showCursor = false } = {}) => {
++// Synchronized output (Cosmic Stack patch): see ink.js synchronized().
++const BSU = '\u001B[?2026h';
++const ESU = '\u001B[?2026l';
++const create = (stream, { showCursor = false, synchronize = false } = {}) => {
++ // One atomic update per write, unless ink.js already opened one.
++ const syncWrite = (data) => stream.write(synchronize && !(render.syncDepth > 0) ? BSU + data + ESU : data);
let previousLineCount = 0;
let previousOutput = '';
let hasHiddenCursor = false;
@@ -314,7 +375,7 @@ index 4c72645..501a658 100644
+ // may have moved or toggled — re-park without touching the frame.
+ const target = targetFor(cursor, previousLineCount);
+ const same = (!parked && !target) || (parked && target && parked.up === target.up && parked.col === target.col);
-+ if (!same) stream.write(unpark() + park(target));
++ if (!same) syncWrite(unpark() + park(target));
return;
}
+ // Diff-render (Cosmic Stack patch): erase and rewrite only the rows
@@ -337,7 +398,7 @@ index 4c72645..501a658 100644
previousOutput = output;
- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
previousLineCount = output.split('\n').length;
-+ stream.write(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n' + park(targetFor(cursor, previousLineCount)));
++ syncWrite(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n' + park(targetFor(cursor, previousLineCount)));
+ };
+ // Resize baseline reset (Cosmic Stack patch): forget what is on screen
+ // without touching the line count — the next render erases the old
@@ -346,9 +407,11 @@ index 4c72645..501a658 100644
+ render.invalidate = () => {
+ previousOutput = '';
};
++ render.synchronize = synchronize;
++ render.syncDepth = 0;
render.clear = () => {
- stream.write(ansiEscapes.eraseLines(previousLineCount));
-+ stream.write(unpark() + ansiEscapes.eraseLines(previousLineCount));
++ syncWrite(unpark() + ansiEscapes.eraseLines(previousLineCount));
previousOutput = '';
previousLineCount = 0;
};
diff --git a/scripts/apply-ink-patch.cjs b/scripts/apply-ink-patch.cjs
index 9b90bc82..5a1cdb2b 100644
--- a/scripts/apply-ink-patch.cjs
+++ b/scripts/apply-ink-patch.cjs
@@ -26,6 +26,8 @@
* 8. ink.js + log-update.js — hardware cursor positioning
* (`internal_cursor` host attribute), so IME preedit/candidate
* windows anchor on the input cell.
+ * 9. ink.js + log-update.js — synchronized output (DEC mode 2026): every
+ * frame is painted atomically; backport of ink 6.7 (#866).
*
* Loud on failure: a silent skip is never acceptable for a crash fix.
*/
@@ -87,7 +89,9 @@ function isPatched(p = paths) {
&& inkJs.includes('maxLiveRows')
&& inkJs.includes(RESIZE_RESET_MARKER)
&& inkJs.includes(FRAME_GATE_MARKER)
- && inkJs.includes(CURSOR_ANCHOR_MARKER);
+ && inkJs.includes(CURSOR_ANCHOR_MARKER)
+ && logUpdate.includes(SYNC_MARKER)
+ && inkJs.includes(SYNC_MARKER);
} catch {
return false;
}
@@ -98,6 +102,7 @@ const RESIZE_RESET_MARKER = 'Resize baseline reset (Cosmic Stack patch)';
const CURSOR_MARKER = 'Hardware cursor (Cosmic Stack patch)';
const CURSOR_ANCHOR_MARKER = '__mercuryCursorAnchor';
const YOGA_HYGIENE_MARKER = '__mercuryInkYogaHygiene';
+const SYNC_MARKER = 'Synchronized output (Cosmic Stack patch)';
/**
* Hardware cursor positioning (ADR-017, #41, #66). Stock ink hides the
@@ -217,7 +222,7 @@ globalThis.${CURSOR_ANCHOR_MARKER} = cursorAnchor;
// in-place node_modules edit.
export const inkPatch = {
vendored: false,
- hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning'],
+ hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'],
};
globalThis.__mercuryInkPatch = inkPatch;
const sameCursor = (a, b) => (!a && !b) || (!!a && !!b && a.row === b.row && a.col === b.col);
@@ -301,6 +306,84 @@ ${onRenderAnchor}`);
* 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). */
+/** Synchronized output: bracket every frame write in BSU/ESU (DEC private
+ * mode 2026) so the terminal swaps it in atomically — no visible gap between
+ * the erase and the redraw, which is the flicker modern terminals show.
+ * Terminals without 2026 ignore both sequences. log-update brackets its own
+ * single writes (that also covers the throttled path, which writes later);
+ * ink.js brackets multi-write sequences (clear + static + frame) as one
+ * update, and log-update skips its own brackets while one is open.
+ * Runs after the cursor hunk: it rewrites the unpark() writes that hunk adds. */
+function applySynchronizedOutput(p = paths) {
+ const { logUpdatePath, inkJsPath } = p;
+ let lu = fs.readFileSync(logUpdatePath, 'utf8');
+ let ink = fs.readFileSync(inkJsPath, 'utf8');
+ if (lu.includes(SYNC_MARKER) && ink.includes(SYNC_MARKER)) return true;
+ if (!lu.includes(SYNC_MARKER)) {
+ const createAnchor = 'const create = (stream, { showCursor = false } = {}) => {';
+ const clearAnchor = ' render.clear = () => {';
+ if (!lu.includes(createAnchor) || !lu.includes(clearAnchor)) return false;
+ const writes = lu.split('stream.write(unpark()').length - 1;
+ if (writes < 2) return false;
+ lu = lu.replace(createAnchor, `// ${SYNC_MARKER}: see ink.js synchronized().
+const BSU = '\\u001B[?2026h';
+const ESU = '\\u001B[?2026l';
+const create = (stream, { showCursor = false, synchronize = false } = {}) => {
+ // One atomic update per write, unless ink.js already opened one.
+ const syncWrite = (data) => stream.write(synchronize && !(render.syncDepth > 0) ? BSU + data + ESU : data);`);
+ lu = lu.split('stream.write(unpark()').join('syncWrite(unpark()');
+ lu = lu.replace(clearAnchor, ` render.synchronize = synchronize;
+ render.syncDepth = 0;
+${clearAnchor}`);
+ }
+ if (!ink.includes(SYNC_MARKER)) {
+ const createAnchor = 'this.log = logUpdate.create(options.stdout);';
+ const staticAnchor = ' this.log.clear();\n this.options.stdout.write(staticOutput);\n this.log(output, cursor);';
+ const writeToAnchor = ' writeToStdout(data) {';
+ if (!ink.includes(createAnchor) || !ink.includes(staticAnchor) || !ink.includes(writeToAnchor)) return false;
+ ink = ink.replace(createAnchor, `// ${SYNC_MARKER}: same gate as upstream shouldSynchronize().
+ this.log = logUpdate.create(options.stdout, { synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug });`);
+ ink = ink.replace(staticAnchor, ` this.synchronized(() => {
+ this.log.clear();
+ this.options.stdout.write(staticOutput);
+ this.log(output, cursor);
+ });`);
+ for (const stream of ['stdout', 'stderr']) {
+ const block = ` this.log.clear();\n this.options.${stream}.write(data);\n this.log(this.lastOutput, this.lastCursor);`;
+ if (ink.includes(block)) {
+ ink = ink.replace(block, ` this.synchronized(() => {
+ this.log.clear();
+ this.options.${stream}.write(data);
+ this.log(this.lastOutput, this.lastCursor);
+ });`);
+ }
+ }
+ ink = ink.replace(writeToAnchor, ` // ${SYNC_MARKER}: run several writes as ONE terminal update (DEC
+ // mode 2026), so a new transcript line and the redrawn live region
+ // appear together instead of erase → static → redraw.
+ synchronized(write) {
+ const log = this.log;
+ if (!log.synchronize) {
+ write();
+ return;
+ }
+ this.options.stdout.write('\\u001B[?2026h');
+ log.syncDepth++;
+ try {
+ write();
+ }
+ finally {
+ log.syncDepth--;
+ this.options.stdout.write('\\u001B[?2026l');
+ }
+ }
+${writeToAnchor}`);
+ }
+ fs.writeFileSync(logUpdatePath, lu);
+ fs.writeFileSync(inkJsPath, ink);
+ return true;
+}
+
function applyResizeBaselineReset(p = paths) {
const { inkJsPath, logUpdatePath } = p;
let lu = fs.readFileSync(logUpdatePath, 'utf8');
@@ -654,9 +737,13 @@ function apply(opts = {}) {
const diffRenderOk = applyLogUpdateDiffRender(p);
const resizeResetOk = applyResizeBaselineReset(p);
const cursorOk = applyCursorPositioning(p);
+ const syncOk = cursorOk && applySynchronizedOutput(p);
if (!cursorOk) {
return { ok: false, applied: true, error: 'hardware cursor positioning could not be inserted (ink.js onRender / log-update.js render anchors)' };
}
+ if (!syncOk) {
+ return { ok: false, applied: true, error: 'synchronized output could not be inserted (ink.js log/static/writeToStdout or log-update.js create/clear anchors)' };
+ }
if (!reconcilerOk) {
return { ok: false, applied: true, error: 'reconciler.js no longer matches the expected ink 5.2.1 shape — patch anchors not found' };
}
diff --git a/scripts/apply-ink-patch.test.ts b/scripts/apply-ink-patch.test.ts
index 3c02a575..b40c7e38 100644
--- a/scripts/apply-ink-patch.test.ts
+++ b/scripts/apply-ink-patch.test.ts
@@ -49,6 +49,9 @@ function writeStockInk(root: string): void {
'import logUpdate from \'./log-update.js\';',
'const noop = () => { };',
'export default class Ink {',
+ ' constructor(options) {',
+ ' this.log = logUpdate.create(options.stdout);',
+ ' }',
' resized = () => {',
' this.calculateLayout();',
' this.onRender();',
@@ -117,16 +120,22 @@ describe('ink patch applier (patch-package-free)', () => {
expect(resized).toContain("this.lastOutput = '';");
expect(resized).toContain('this.log.invalidate()');
expect(resized.indexOf('this.log.invalidate()')).toBeLessThan(resized.indexOf('this.calculateLayout()'));
- // Hardware cursor: every frame write unparks first and parks after,
+ // Hardware cursor: every frame write unparks first and parks after
+ // (through syncWrite, see the synchronized-output checks below),
// and both log() call sites pass the resolved cell through.
expect(logUpdate).toContain('const render = (str, cursor) => {');
- expect(logUpdate).toContain('stream.write(unpark() + ansiEscapes.eraseLines(eraseCount)');
- expect(logUpdate).toContain('stream.write(unpark() + ansiEscapes.eraseLines(previousLineCount))');
expect(inkJs).toContain('this.log(output, cursor);');
expect(inkJs).toContain('this.throttledLog(output, cursor);');
expect(inkJs).toContain('this.log(this.lastOutput, this.lastCursor);');
expect(inkJs).toContain('node.attributes?.internal_cursor');
expect(readFileSync(paths.reconcilerPath, 'utf8')).toContain('globalThis.__mercuryInkYogaHygiene = true;');
+ // Synchronized output: log-update brackets its own writes, ink.js
+ // brackets clear + static + frame as one update, gated on a TTY.
+ expect(logUpdate).toContain('syncWrite(unpark() + ansiEscapes.eraseLines(eraseCount)');
+ expect(logUpdate).toContain('syncWrite(unpark() + ansiEscapes.eraseLines(previousLineCount))');
+ expect(logUpdate).not.toContain('stream.write(unpark()');
+ expect(inkJs).toContain('synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug');
+ expect(inkJs).toMatch(/this\.synchronized\(\(\) => \{\n\s+this\.log\.clear\(\);\n\s+this\.options\.stdout\.write\(staticOutput\);/);
// 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/ui/hardware-cursor.test.tsx b/src/ui/hardware-cursor.test.tsx
index e51e529c..81fcfc74 100644
--- a/src/ui/hardware-cursor.test.tsx
+++ b/src/ui/hardware-cursor.test.tsx
@@ -34,13 +34,21 @@ const ESC = String.fromCharCode(27);
const PARK_RE = new RegExp(`${ESC}\\[(\\d+)A${ESC}\\[(\\d+)G${ESC}\\[\\?25h$`);
const stripAnsi = (s: string) => s.replace(new RegExp(`${ESC}\\[[0-9;?]*[A-Za-z]`, 'g'), '');
+// Synchronized output (DEC 2026) brackets every frame; it is framing, not
+// content, so the cursor assertions below see chunks without it.
+const BSU = '\x1b[?2026h';
+const ESU = '\x1b[?2026l';
+
class FakeStdout extends EventEmitter {
chunks: string[] = [];
+ raw: string[] = [];
columns = 80;
rows = 30;
isTTY = true;
write(chunk: string): boolean {
- this.chunks.push(chunk);
+ this.raw.push(chunk);
+ const content = chunk.split(BSU).join('').split(ESU).join('');
+ if (content) this.chunks.push(content);
return true;
}
get output(): string {
@@ -224,6 +232,81 @@ describe('hardware cursor positioning (vendored ink)', () => {
});
});
+/**
+ * Frame bytes written outside any BSU…ESU bracket (should be none while
+ * mounted). Cursor show/hide toggles (ink hides it once at startup) are
+ * mode switches, not frame content.
+ */
+function unbracketed(raw: string[]): string {
+ let depth = 0;
+ let outside = '';
+ let rest = raw.join('');
+ while (rest) {
+ const open = rest.indexOf(BSU);
+ const close = rest.indexOf(ESU);
+ const next = [open, close].filter((i) => i >= 0).sort((a, b) => a - b)[0] ?? rest.length;
+ if (depth === 0) outside += rest.slice(0, next);
+ if (next === rest.length) break;
+ depth += next === open ? 1 : -1;
+ rest = rest.slice(next + BSU.length);
+ }
+ return outside.split(HIDE).join('').split(SHOW).join('');
+}
+
+describe('synchronized output (vendored ink, DEC 2026)', () => {
+ function Transcript({ lines, live }: { lines: string[]; live: string }) {
+ return (
+ <>
+ <Static items={lines}>{(l) => <Text key={l}>{l}</Text>}</Static>
+ <Box><Text>{live}</Text></Box>
+ </>
+ );
+ }
+
+ it('brackets every frame write on a TTY, so the terminal paints it atomically', async () => {
+ const stdout = new FakeStdout();
+ const { rerender, unmount } = render(<Transcript lines={[]} live="tick 0" />, { stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });
+ for (let i = 1; i <= 5; i++) {
+ rerender(<Transcript lines={[]} live={`tick ${i}`} />);
+ await new Promise((r) => setTimeout(r, 40));
+ }
+ await waitFor(() => stdout.output.includes('tick 5'));
+ expect(stdout.raw.join('')).toContain(BSU);
+ expect(unbracketed(stdout.raw)).toBe('');
+ unmount();
+ });
+
+ it('writes a new transcript line and the redrawn live region as ONE update', async () => {
+ const stdout = new FakeStdout();
+ const { rerender, unmount } = render(<Transcript lines={['first line']} live="working" />, { stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });
+ await waitFor(() => stdout.output.includes('working'));
+ const mark = stdout.raw.length;
+ rerender(<Transcript lines={['first line', 'second line']} live="done" />);
+ await waitFor(() => stdout.output.includes('done'));
+ const update = stdout.raw.slice(mark).join('');
+ const open = update.indexOf(BSU);
+ const close = update.indexOf(ESU, open);
+ // Erase, the static line and the new frame all sit between one BSU/ESU.
+ expect(open).toBeGreaterThanOrEqual(0);
+ const inside = update.slice(open, close);
+ expect(inside).toContain('second line');
+ expect(inside).toContain('done');
+ expect(inside.indexOf('second line')).toBeLessThan(inside.indexOf('done'));
+ expect(unbracketed(stdout.raw)).toBe('');
+ unmount();
+ });
+
+ it('never emits mode 2026 when the output is not a TTY', async () => {
+ const stdout = new FakeStdout();
+ stdout.isTTY = false;
+ const { rerender, unmount } = render(<Transcript lines={['a']} live="x" />, { stdout: stdout as never, exitOnCtrlC: false, patchConsole: false });
+ rerender(<Transcript lines={['a', 'b']} live="y" />);
+ await waitFor(() => stdout.output.includes('y'));
+ unmount();
+ expect(stdout.raw.join('')).not.toContain('2026');
+ });
+});
+
function mercuryState(overrides: Partial<Record<string, unknown>> = {}): TuiState {
return {
mode: 'mercury-code',
diff --git a/src/ui/ink-patch-check.test.ts b/src/ui/ink-patch-check.test.ts
index b23b5151..51e5d01a 100644
--- a/src/ui/ink-patch-check.test.ts
+++ b/src/ui/ink-patch-check.test.ts
@@ -12,7 +12,7 @@ import {
INK_PATCH_MARKERS,
} from './ink-patch-check.js';
-const VENDORED_MANIFEST = { vendored: true, hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning'] };
+const VENDORED_MANIFEST = { vendored: true, hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'] };
const PATCHED_STATIC = 'export default function Static(props) { const { itemKey } = props; const [t, setCommitTick] = useState(0); }';
const STOCK_STATIC = 'export default function Static(props) { const { items, children: render } = props; }';
diff --git a/vendor/ink/build/ink.js b/vendor/ink/build/ink.js
index b6adc6d1..4fd2a7c1 100644
--- a/vendor/ink/build/ink.js
+++ b/vendor/ink/build/ink.js
@@ -37,7 +37,7 @@ globalThis.__mercuryCursorAnchor = cursorAnchor;
// in-place node_modules edit.
export const inkPatch = {
vendored: true,
- hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning'],
+ hunks: ['yoga-hygiene', 'static-item-key', 'freeze-gate', 'live-region-guard', 'diff-render', 'resize-invalidate', 'cursor-positioning', 'synchronized-output'],
};
globalThis.__mercuryInkPatch = inkPatch;
const sameCursor = (a, b) => (!a && !b) || (!!a && !!b && a.row === b.row && a.col === b.col);
@@ -88,7 +88,8 @@ export default class Ink {
trailing: true,
});
this.rootNode.onImmediateRender = this.onRender;
- this.log = logUpdate.create(options.stdout);
+ // Synchronized output (Cosmic Stack patch): same gate as upstream shouldSynchronize().
+ this.log = logUpdate.create(options.stdout, { synchronize: Boolean(options.stdout.isTTY) && !isInCi && !options.debug });
this.throttledLog = options.debug
? this.log
: throttle(this.log, undefined, {
@@ -219,9 +220,11 @@ export default class Ink {
}
// To ensure static output is cleanly rendered before main output, clear main output first
if (hasStaticOutput) {
- this.log.clear();
- this.options.stdout.write(staticOutput);
- this.log(output, cursor);
+ this.synchronized(() => {
+ this.log.clear();
+ this.options.stdout.write(staticOutput);
+ this.log(output, cursor);
+ });
}
if (!hasStaticOutput && (output !== this.lastOutput || !sameCursor(cursor, this.lastCursor))) {
this.throttledLog(output, cursor);
@@ -233,6 +236,25 @@ export default class Ink {
const tree = (React.createElement(App, { stdin: this.options.stdin, stdout: this.options.stdout, stderr: this.options.stderr, writeToStdout: this.writeToStdout, writeToStderr: this.writeToStderr, exitOnCtrlC: this.options.exitOnCtrlC, onExit: this.unmount }, node));
reconciler.updateContainer(tree, this.container, null, noop);
}
+ // Synchronized output (Cosmic Stack patch): run several writes as ONE terminal update (DEC
+ // mode 2026), so a new transcript line and the redrawn live region
+ // appear together instead of erase → static → redraw.
+ synchronized(write) {
+ const log = this.log;
+ if (!log.synchronize) {
+ write();
+ return;
+ }
+ this.options.stdout.write('\u001B[?2026h');
+ log.syncDepth++;
+ try {
+ write();
+ }
+ finally {
+ log.syncDepth--;
+ this.options.stdout.write('\u001B[?2026l');
+ }
+ }
writeToStdout(data) {
if (this.isUnmounted) {
return;
@@ -245,9 +267,11 @@ export default class Ink {
this.options.stdout.write(data);
return;
}
- this.log.clear();
- this.options.stdout.write(data);
- this.log(this.lastOutput, this.lastCursor);
+ this.synchronized(() => {
+ this.log.clear();
+ this.options.stdout.write(data);
+ this.log(this.lastOutput, this.lastCursor);
+ });
}
writeToStderr(data) {
if (this.isUnmounted) {
@@ -262,9 +286,11 @@ export default class Ink {
this.options.stderr.write(data);
return;
}
- this.log.clear();
- this.options.stderr.write(data);
- this.log(this.lastOutput, this.lastCursor);
+ this.synchronized(() => {
+ this.log.clear();
+ this.options.stderr.write(data);
+ this.log(this.lastOutput, this.lastCursor);
+ });
}
// eslint-disable-next-line @typescript-eslint/ban-types
unmount(error) {
diff --git a/vendor/ink/build/log-update.js b/vendor/ink/build/log-update.js
index 501a6587..22efeceb 100644
--- a/vendor/ink/build/log-update.js
+++ b/vendor/ink/build/log-update.js
@@ -1,6 +1,11 @@
import ansiEscapes from 'ansi-escapes';
import cliCursor from 'cli-cursor';
-const create = (stream, { showCursor = false } = {}) => {
+// Synchronized output (Cosmic Stack patch): see ink.js synchronized().
+const BSU = '\u001B[?2026h';
+const ESU = '\u001B[?2026l';
+const create = (stream, { showCursor = false, synchronize = false } = {}) => {
+ // One atomic update per write, unless ink.js already opened one.
+ const syncWrite = (data) => stream.write(synchronize && !(render.syncDepth > 0) ? BSU + data + ESU : data);
let previousLineCount = 0;
let previousOutput = '';
let hasHiddenCursor = false;
@@ -40,7 +45,7 @@ const create = (stream, { showCursor = false } = {}) => {
// may have moved or toggled — re-park without touching the frame.
const target = targetFor(cursor, previousLineCount);
const same = (!parked && !target) || (parked && target && parked.up === target.up && parked.col === target.col);
- if (!same) stream.write(unpark() + park(target));
+ if (!same) syncWrite(unpark() + park(target));
return;
}
// Diff-render (Cosmic Stack patch): erase and rewrite only the rows
@@ -62,7 +67,7 @@ const create = (stream, { showCursor = false } = {}) => {
const eraseCount = previousLineCount - firstChange;
previousOutput = output;
previousLineCount = output.split('\n').length;
- stream.write(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n' + park(targetFor(cursor, previousLineCount)));
+ syncWrite(unpark() + ansiEscapes.eraseLines(eraseCount) + nextRows.slice(firstChange).join('\n') + '\n' + park(targetFor(cursor, previousLineCount)));
};
// Resize baseline reset (Cosmic Stack patch): forget what is on screen
// without touching the line count — the next render erases the old
@@ -71,8 +76,10 @@ const create = (stream, { showCursor = false } = {}) => {
render.invalidate = () => {
previousOutput = '';
};
+ render.synchronize = synchronize;
+ render.syncDepth = 0;
render.clear = () => {
- stream.write(unpark() + ansiEscapes.eraseLines(previousLineCount));
+ syncWrite(unpark() + ansiEscapes.eraseLines(previousLineCount));
previousOutput = '';
previousLineCount = 0;
};