The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): keep Codex's resize clear off the viewer
tonyca1934819232
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsindex 620943ee1..93f6b1602 100644--- a/cli/src/lib/terminalStreamManager.spec.ts+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -203,6 +203,33 @@ describe('TerminalStreamManager', () => {expect(output()).toContain('\u001b[3J')})+ // The keyframe after a resize was taken before Codex's print began, and the clear came in the output held behind it.+ // Released while the keyframe was still marked as being taken, it went to the viewer unread (review of #1310).+ it('reads the output a keyframe held back for an engine\'s print, as it reads live output', async () => {+ const repaint = { clears: '\u001b[3J', ends: '\u001b[?2026l', withinMs: 250 }+ const output = () => binarySent.filter(({ frame }) => frame.kind === TerminalBinaryKind.output)+ .map(({ frame }) => Buffer.from(frame.bytes).toString('latin1')).join('')+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,+ })+ const streamId = sent[0].payload.streamId as string+ stream.onEndSnapshot = () => {+ stream.onEndSnapshot = null+ sink!.onData(Buffer.from('\u001b[?2026hworking\u001b[?2026l'))+ sink!.onData(Buffer.from('\u001b[H\u001b[2J\u001b[3J\u001b[H\u001b[?2026h'))+ }+ const taken = stream.snapshots+ await manager.handleFrame('web-1', 'terminal_resize', { streamId, resizeSeq: 0, cols: 120, rows: 30 })+ await vi.advanceTimersByTimeAsync(8)++ // The resize's keyframe, then the print's, which waits for its end.+ expect(stream.snapshots).toBe(taken + 2)+ expect(stream.snapshotOptions.at(-1)).toEqual({ conversationHistory: true, repaint: { ...repaint, cleared: true } })+ expect(stream.snapshotBegins).toBe(stream.snapshotEnds)+ expect(output()).not.toContain('\u001b[3J')+ expect(binarySent.at(-1)!.frame.kind).toBe(TerminalBinaryKind.keyframe)+ })+it('tells a Grok snapshot not to seed tmux history, an engine kept in the scrollback to seed all of it, and leaves other engines alone', async () => {await manager.handleFrame('web-1', 'terminal_open', {requestId: 'open-codex', protocolVersion: 3, agentId: 'agent-1', cols: 120, rows: 40,diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex bbe13c329..81027844b 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -1242,9 +1242,12 @@ export class TerminalStreamManager {compressedBytes: body.bytes.length,snapshotMs: Math.max(0, this.now() - startedAt),})- state.handle.endSnapshot()+ // The output held behind the keyframe is released as live output, read for an engine's print as it is+ // (`repaintBegan`): Codex's clear came in it, after a keyframe taken before its print began, and went straight to+ // the viewer while the keyframe was still marked as being taken. The print's keyframe can begin from it here.state.snapshotting = falsestate.resyncing = false+ state.handle.endSnapshot()this.flushOutput(state)if (state.pendingBytes > PAUSE_HIGH_WATERMARK_BYTES && !state.outputPaused) void this.pauseOutput(state)}diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex 7f5f1b117..f4cef7dd1 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -184,13 +184,16 @@ export interface TerminalStreamHandle<Ref extends TerminalRuntimeRef = TerminalR* (facets/launch.ts `ScreenContract.resizeRepaint`): a snapshot taken right* after the pane was resized waits for that print, so it holds what follows* the clear rather than what preceded it; `cleared`, when the clear has come- * already, as live output, so only the print's end is waited for. */+ * already, as live output, so only the print's end is waited for. A print+ * that began before the capture's cut and had not ended there, whenever it+ * began, has the snapshot taken again once it ends. */snapshot(options?: {tuiOwnsScrollback?: booleanconversationHistory?: booleanrepaint?: { clears: string; ends: string; withinMs: number; cleared?: boolean }}): Promise<TerminalReadResult<TerminalStreamSnapshot>>- /** Release output produced strictly after the snapshot cut. */+ /** Release output produced strictly after the snapshot cut. The sink may+ * begin the next snapshot from it: what is left is then held behind that one. */endSnapshot(): voidwriteRaw(bytes: Uint8Array): Promise<TerminalActionResult>/** A clipboard paste, delivered as one atomic unit rather than chunked like `writeRaw` — seediff --git a/cli/src/lib/tmuxStream.real.spec.ts b/cli/src/lib/tmuxStream.real.spec.tsindex 322d116f4..fb9ee4a8d 100644--- a/cli/src/lib/tmuxStream.real.spec.ts+++ b/cli/src/lib/tmuxStream.real.spec.ts@@ -215,6 +215,80 @@ run('TmuxControlStream real tmux', () => {}})+ // The print began before the capture's cut and had not ended at it, after the wait for it had given up: the keyframe+ // held a cleared, half-printed screen, and the rest of the print came as output with no clear in it (review of #1310).+ it('takes the keyframe again when an engine\'s print was under way at the capture\'s cut', async () => {+ const script = join(socketRoot, 'late-repaint.sh')+ await writeFile(script, [+ `trap 'printf "\\033[2J\\033[3J\\033[H\\033[?2026hHALF\\n"; sleep 0.5; printf "REPAINTED\\n\\033[?2026l"' WINCH`,+ `printf 'ready\\n'`,+ 'while :; do sleep 0.02; done',+ ].join('\n') + '\n')+ await tmux(['respawn-pane', '-k', '-t', paneId, 'bash', script])+ await eventually(async () => (await tmux(['capture-pane', '-p', '-t', paneId])).includes('ready'))+ const live: Buffer[] = []+ // The session's own size: opening does not resize it, and sets off no print of its own.+ const opened = await TmuxControlStream.open(paneId, { cols: 80, rows: 24 }, { onData: (bytes) => { live.push(Buffer.from(bytes)) }, onClose: () => {} })+ expect(opened.state).toBe('succeeded')+ try {+ if (opened.state !== 'succeeded') return+ await new Promise((resolve) => setTimeout(resolve, 100))+ opened.value.beginSnapshot()+ expect((await opened.value.resize({ cols: 80, rows: 12 })).state).toBe('succeeded')+ // Past the 250 ms the snapshot waits from a resize for the print to begin, which it did, and still under way.+ await new Promise((resolve) => setTimeout(resolve, 300))+ const screen = await tmux(['capture-pane', '-p', '-t', paneId])+ expect(screen).toContain('HALF')+ expect(screen).not.toContain('REPAINTED')+ live.length = 0+ const snapshot = await opened.value.snapshot({ repaint: { clears: '\u001b[3J', ends: '\u001b[?2026l', withinMs: 250 } })+ opened.value.endSnapshot()+ await new Promise((resolve) => setTimeout(resolve, 300))+ expect(snapshot.state).toBe('succeeded')+ expect(snapshot.state === 'succeeded' && Buffer.from(snapshot.value.bytes).toString('utf8')).toContain('REPAINTED')+ expect(Buffer.concat(live).toString('latin1')).not.toContain('REPAINTED')+ } finally {+ if (opened.state === 'succeeded') await opened.value.close()+ }+ })++ // The stream manager reads the output a keyframe held back as it reads live output, and begins the keyframe for+ // Codex's print from it: what follows the clear precedes that keyframe's cut, and must not reach the viewer after it.+ it('holds what is left of the output a snapshot releases behind the next one its sink begins', async () => {+ const delivered: string[] = []+ let regate: (() => void) | null = null+ const opened = await TmuxControlStream.open(paneId, { cols: 80, rows: 20 }, {+ onData: (bytes) => {+ delivered.push(Buffer.from(bytes).toString('utf8'))+ const begin = regate+ regate = null+ begin?.()+ },+ onClose: () => {},+ })+ expect(opened.state).toBe('succeeded')+ try {+ if (opened.state !== 'succeeded') return+ opened.value.beginSnapshot()+ expect((await opened.value.snapshot()).state).toBe('succeeded')+ const script = join(socketRoot, 'chunks.sh')+ await writeFile(script, "printf 'one,'; sleep 0.1; printf 'two,'; sleep 0.1; printf 'three'; sleep 30\n")+ await tmux(['respawn-pane', '-k', '-t', paneId, 'bash', script])+ await eventually(async () => (await tmux(['capture-pane', '-p', '-t', paneId])).includes('one,two,three'))+ await new Promise((resolve) => setTimeout(resolve, 100))+ delivered.length = 0+ regate = () => opened.value.beginSnapshot()+ opened.value.endSnapshot()+ // The first chunk began a snapshot: the rest are held behind it, and released with it, in order.+ expect(delivered).toHaveLength(1)+ opened.value.endSnapshot()+ expect(delivered.length).toBeGreaterThan(1)+ expect(delivered.join('')).toContain('one,two,three')+ } finally {+ if (opened.state === 'succeeded') await opened.value.close()+ }+ })+it('streams large styled Unicode and control-byte output without losing or changing bytes', async () => {const directory = await mkdtemp(join(tmpdir(), 'harness-stream-bytes-'))const path = join(directory, 'payload.bin')diff --git a/cli/src/lib/tmuxStream.spec.ts b/cli/src/lib/tmuxStream.spec.tsindex e8d73e4c7..ab3fd02fa 100644--- a/cli/src/lib/tmuxStream.spec.ts+++ b/cli/src/lib/tmuxStream.spec.ts@@ -7,6 +7,7 @@ import {normalizeTmuxHistoryLines,normalizeTmuxCaptureLines,parseTmuxControlOutput,+ printInProgress,quoteForOldTmux,synthesizeTmuxSnapshot,tuiScrollPageCount,@@ -369,4 +370,72 @@ describe('ControlCommandQueue', () => {expect((await queue.run('display-message -p one')).ok).toBe(false)expect(queue.idle).toBe(true)})++ // A conversation's three history captures must read one history: written one per line, the pane's output was read+ // between them in 28 of 500 tries (tmux 3.7c, 2026-10-14).+ it('writes commands run together in one write, and still pairs each with its own reply', async () => {+ const { queue, written } = harness()+ const ended: string[] = []+ const [plain, joined, seam] = queue.runTogether([+ { command: 'capture-pane -p -S -2000 -E -1', onEnd: () => ended.push('plain') },+ { command: 'capture-pane -p -J -S -2000 -E -1' },+ { command: 'capture-pane -p -J -S -1 -E 0', onEnd: () => ended.push('seam') },+ ])+ expect(written).toEqual(['capture-pane -p -S -2000 -E -1\ncapture-pane -p -J -S -2000 -E -1\ncapture-pane -p -J -S -1 -E 0\n'])++ queue.handleBegin('70')+ queue.appendResponseLine(Buffer.from('PLAIN'))+ queue.handleCompleted('end', '70')+ queue.handleBegin('71')+ queue.handleCompleted('error', '71')+ queue.handleBegin('72')+ queue.appendResponseLine(Buffer.from('SEAM'))+ queue.handleCompleted('end', '72')++ expect((await plain).stdout.toString()).toBe('PLAIN\n')+ expect((await joined).ok).toBe(false)+ expect((await seam).stdout.toString()).toBe('SEAM\n')+ expect(ended).toEqual(['plain', 'seam'])+ expect(queue.idle).toBe(true)+ })++ it('fails every command of a write the pipe refused', async () => {+ const { queue, reject } = harness()+ reject()+ const results = await Promise.all(queue.runTogether([{ command: 'display-message -p a' }, { command: 'display-message -p b' }]))+ expect(results.map((result) => result.ok)).toEqual([false, false])+ expect(queue.idle).toBe(true)+ })++ it('writes what waited for the attach in one write once it answers', async () => {+ const written: string[] = []+ const queue = new ControlCommandQueue({ write: (line) => { written.push(line); return true }, onFatal: () => {} })+ void queue.run('display-message -p one')+ void queue.run('send-keys -t %1 -H 61')+ expect(written).toEqual([])+ queue.markReady()+ expect(written).toEqual(['display-message -p one\nsend-keys -t %1 -H 61\n'])+ queue.failAll()+ })+})++// Codex in its scrollback answers a resize by clearing the screen and printing its transcript again in one+// synchronized update. A capture cut while that print was under way held a cleared or half-printed screen.+describe('printInProgress', () => {+ const print = { clears: '\u001b[3J', ends: '\u001b[?2026l' }+ const read = (...chunks: string[]) => printInProgress(chunks.map((chunk) => Buffer.from(chunk, 'latin1')), print)++ it('reads a print begun and not yet ended as under way', () => {+ expect(read('\u001b[?2026l\u001b[2J\u001b[3J\u001b[H\u001b[?2026htranscript')).toBe(true)+ // Its clear split between two notifications.+ expect(read('working\u001b[2J\u001b[', '3J\u001b[?2026hhalf')).toBe(true)+ // Ended, then begun again: the second is under way.+ expect(read('\u001b[3Jfirst\u001b[?2026l', 'more \u001b[3Jsecond')).toBe(true)+ })++ it('reads a print that ended, or none at all, as nothing under way', () => {+ expect(read()).toBe(false)+ expect(read('\u001b[?2026hworking 1\u001b[?2026l')).toBe(false)+ expect(read('\u001b[3J\u001b[?2026htranscript', '\u001b[?2026', 'l')).toBe(false)+ })})diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.tsindex ada33d6cb..5a3c7283f 100644--- a/cli/src/lib/tmuxStream.ts+++ b/cli/src/lib/tmuxStream.ts@@ -19,6 +19,8 @@ import {type TmuxRuntimeRef,} from './terminalTypes.js'+type SnapshotOptions = NonNullable<Parameters<TerminalStreamHandle<TmuxRuntimeRef>['snapshot']>[0]>+const MIN_COLS = 1const MAX_COLS = 300const MIN_ROWS = 1@@ -36,8 +38,8 @@ const CLOSE_EXIT_WAIT_MS = 500const SNAPSHOT_BUFFER_MAX_BYTES = 2 * 1024 * 1024const SNAPSHOT_QUIET_MS = 8const SNAPSHOT_QUIET_MAX_MS = 40-/** The longest a snapshot waits from a resize for an engine's print to end, once it has begun: Codex's ended by- * 186 ms. Past it the keyframe is taken as it is, and the rest of the print reaches the viewer as output. */+/** The longest a snapshot waits for an engine's print to end from the moment it saw the print begin: Codex's ended+ * by 186 ms after the resize. Past it the keyframe is taken as it is, and the rest reaches the viewer as output. */const REPAINT_MAX_MS = 400const SNAPSHOT_HISTORY_LINES = 500/**@@ -325,6 +327,18 @@ export function dropOldestHistoryRows(rows: Uint8Array, excess: number): Uint8Arreturn end < 0 ? Buffer.alloc(0) : buffer.subarray(end + 2)}+/**+ * Whether the output read before a capture's cut began an engine's print (facets/launch.ts+ * `ScreenContract.resizeRepaint`) and had not ended it there: the capture then holds a cleared or half-printed screen.+ */+export function printInProgress(chunks: readonly Uint8Array[], print: { clears: string; ends: string }): boolean {+ if (chunks.length === 0) return false+ const read = Buffer.concat(chunks)+ const clears = Buffer.from(print.clears, 'utf8')+ const at = read.lastIndexOf(clears)+ return at >= 0 && read.indexOf(Buffer.from(print.ends, 'utf8'), at + clears.length) < 0+}+export function synthesizeTmuxSnapshot(capture: Uint8Array,meta: PaneMeta,@@ -458,10 +472,22 @@ export class ControlCommandQueue {}run(command: string, onEnd?: () => void): Promise<ControlCommandResult> {- return new Promise((resolve) => {+ return this.runTogether([{ command, onEnd }])[0]+ }++ /**+ * Commands that must read the pane as one moment, written to tmux in one write. tmux runs every line it read at once+ * before it reads the pane again; one line per write, a pane printing all it could had output read between three+ * captures in 28 of 500 tries, and 0 of 500 written together (tmux 3.7c, 2026-10-14). Not one line joined with `;`:+ * tmux answers each command of a list in its own `%begin`/`%end`, and none after one that fails, which the queue+ * could no longer pair with what it sent.+ */+ runTogether(commands: ReadonlyArray<{ command: string; onEnd?: () => void }>): Array<Promise<ControlCommandResult>> {+ const results = commands.map(({ command, onEnd }) => new Promise<ControlCommandResult>((resolve) => {this.waiting.push({ command, lines: [], commandNumber: null, timer: null, onEnd, resolve })- this.pump()- })+ }))+ this.pump()+ return results}handleBegin(commandNumber: string): void {@@ -496,22 +522,21 @@ export class ControlCommandQueue {}}+ /** Everything waiting goes in one write: commands queued together (`runTogether`), or before the attach answered. */private pump(): void {- if (!this.ready) return- while (this.waiting.length) {- const next = this.waiting.shift()!- let written = false- try {- written = this.deps.write(`${next.command}\n`)- } catch {- written = false- }- if (!written) {- next.resolve(CONTROL_COMMAND_FAILED)- continue- }- this.outstanding.push(next)+ if (!this.ready || this.waiting.length === 0) return+ const batch = this.waiting.splice(0)+ let written = false+ try {+ written = this.deps.write(batch.map(({ command }) => `${command}\n`).join(''))+ } catch {+ written = false}+ if (!written) {+ for (const next of batch) next.resolve(CONTROL_COMMAND_FAILED)+ return+ }+ this.outstanding.push(...batch)this.armHead()}@@ -557,6 +582,9 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {private snapshotPostCut: Buffer[] = []private snapshotPostCutBytes = 0private snapshotLastOutputAt = 0+ /** How many of the pane's output notifications have been read: one that moved between two command replies was read+ * by tmux between the two commands. */+ private outputNotifications = 0/** When this stream last changed the pane's size (`resize`), which an engine may answer by printing again. */private resizedAt = Number.NEGATIVE_INFINITYprivate lastTuiScrollAt = 0@@ -695,6 +723,12 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {}private routeOutput(bytes: Uint8Array): void {+ this.outputNotifications+++ this.deliverOutput(bytes)+ }++ /** To the sink, or, while a snapshot is being taken, behind its gate. */+ private deliverOutput(bytes: Uint8Array): void {if (!this.snapshotGated) {this.sink.onData(bytes)return@@ -715,6 +749,11 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {return this.commands.run(command, onEnd)}+ private runControlCommands(commands: ReadonlyArray<{ command: string; onEnd?: () => void }>): Array<Promise<ControlCommandResult>> {+ if (this.closed || !this.child.stdin.writable) return commands.map(() => Promise.resolve(CONTROL_COMMAND_FAILED))+ return this.commands.runTogether(commands)+ }+private serializeOperation<T>(operation: () => Promise<T>): Promise<T> {const result = this.operationTail.then(operation, operation)this.operationTail = result.then(() => undefined, () => undefined)@@ -763,123 +802,159 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {let scanned = 0// The end of what was read that may begin a sequence the next chunk completes.let carry = Buffer.alloc(0)- // A clear that came as live output (the stream manager's guard) is behind this wait: only the end is read for.- let cleared = repaint.cleared === true- const from = cleared ? Date.now() : this.resizedAt+ // A clear already seen, as live output (the stream manager's guard) or before a capture's cut, is behind this+ // wait: only the end is read for.+ let clearedAt = repaint.cleared === true ? Date.now() : nullwhile (!this.closed && this.snapshotGated) {for (; scanned < this.snapshotPostCut.length; scanned++) {let chunk = Buffer.concat([carry, this.snapshotPostCut[scanned]])- if (!cleared) {+ if (clearedAt == null) {const at = chunk.indexOf(clears)if (at < 0) {carry = chunk.subarray(Math.max(0, chunk.length - clears.length + 1))continue}- cleared = true+ // The print gets all of REPAINT_MAX_MS, however late in `withinMs` it began.+ clearedAt = Date.now()chunk = chunk.subarray(at + clears.length)}if (chunk.includes(ends)) returncarry = chunk.subarray(Math.max(0, chunk.length - ends.length + 1))}- if (Date.now() - (cleared ? from : this.resizedAt) >= (cleared ? REPAINT_MAX_MS : repaint.withinMs)) return+ const now = Date.now()+ if (clearedAt == null ? now - this.resizedAt >= repaint.withinMs : now - clearedAt >= REPAINT_MAX_MS) returnawait new Promise((resolve) => setTimeout(resolve, 5))}}- async snapshot(options?: {- tuiOwnsScrollback?: boolean- conversationHistory?: boolean- repaint?: { clears: string; ends: string; withinMs: number; cleared?: boolean }- }): Promise<TerminalReadResult<TerminalStreamSnapshot>> {+ async snapshot(options?: SnapshotOptions): Promise<TerminalReadResult<TerminalStreamSnapshot>> {return this.serializeOperation(async () => {if (!this.snapshotGated) return { state: 'failed', reason: 'tmux snapshot gate is not active' }- // -N is required for TUI fidelity: styled blank cells (for example the- // Codex input box background) live in trailing spaces that tmux otherwise- // trims from each captured row. Deliberately do not use capture-pane -S:- // tmux scrollback contains old full-screen TUI repaint frames. Replaying- // those frames into a fresh emulator corrupts the visible screen.- // -N is tmux 3.1. Before it the flag failed the capture, and with it every- // snapshot: the terminal never showed. Without it the screen is all there,- // short only of the colour of a row's trailing blanks.- const keepTrailing = this.features.captureTrailingSpaces ? ' -N' : ''- const baseCapture = `capture-pane -p -e${keepTrailing} -t ${this.runtime.paneId}`- // Attaching a control client can trigger an immediate TUI repaint. Wait- // before reading both cursor metadata and the grid so the synthesized- // keyframe cannot combine a post-repaint grid with pre-repaint cursor- // coordinates.const repaint = options?.repaint- if (repaint && (repaint.cleared || Date.now() - this.resizedAt < repaint.withinMs)) await this.waitForRepaint(repaint)- await this.waitForSnapshotQuiet()- const metadata = await this.runControlCommand(- `display-message -p -t ${this.runtime.paneId} '${PANE_META_FORMAT}'`,- )- if (!metadata.ok) return { state: 'failed', reason: 'tmux snapshot metadata is unavailable' }- const meta = parsePaneMeta(metadata.stdout)- if (!meta || meta.windowPanes !== 1) return { state: 'failed', reason: 'tmux snapshot metadata is invalid' }- // History is a styled cell capture used only to seed the receiver's- // local scrollback. It preserves SGR attributes without replaying old- // TUI cursor movement. Read it before the authoritative visible-grid cut- // so concurrent output is included there or in a post-cut delta.- //- // Grok (and any TUI that paints in the normal buffer) is the other- // history trap: tmux reports alternate_on=0, so a naive capture would- // seed hundreds of prior full-screen repaint frames. The window then- // shows stacked empty chrome above the live header, and the wheel- // scrolls that junk locally instead of the program.- const tuiOwnsScrollback = options?.tuiOwnsScrollback === true- const seedsHistory = !meta.alternateOn && !tuiOwnsScrollback- const conversation = seedsHistory && options?.conversationHistory === true- const historyRange = `-t ${this.runtime.paneId} -S -${conversation ? CONVERSATION_HISTORY_LINES : SNAPSHOT_HISTORY_LINES} -E -1`- // A conversation's history is re-wrapped by word as well (historyRewrap.ts): tmux re-wraps it by the cell- // whenever a takeover narrows the pane. That reads the same rows joined back into the lines they were (-J),- // and whether the last of them runs on into the visible grid (one line from -1 to 0, not two). The three go- // to tmux together, so no output lands between them; the plain capture stays, for the keyframe whenever- // there is nothing to re-wrap or the re-wrap cannot be used.- const rewrap = conversation && meta.paneWidth >= REWRAP_MIN_WIDTH- const [plain, joined, seam] = seedsHistory- ? await Promise.all([- this.runControlCommand(`capture-pane -p -e${keepTrailing} ${historyRange}`),- rewrap ? this.runControlCommand(`capture-pane -p -e -J ${historyRange}`) : null,- rewrap ? this.runControlCommand(`capture-pane -p -J -t ${this.runtime.paneId} -S -1 -E 0`) : null,- ])- : [null, null, null]- const history = plain?.stdout ?? Buffer.alloc(0)- let historyRows: Buffer | null = null- if (joined?.ok && seam?.ok) {- try {- // One line, its newline the last byte: rows -1 and 0 are one line.- const lastContinues = seam.stdout.indexOf(0x0a) === seam.stdout.length - 1- historyRows = rewrapTmuxHistory(joined.stdout, meta.paneWidth, { lastContinues })- } catch {- // A history the re-wrap cannot read is sent as tmux has it, as it always was.- historyRows = null- }- }- const capture = await this.runControlCommand(baseCapture, () => {- // `%end` is the ordered cut. Notifications observed before it are- // represented by capture-pane; only later output may follow the keyframe.- this.snapshotPostCut = []- this.snapshotPostCutBytes = 0- })- if (!capture.ok) return { state: 'failed', reason: 'tmux snapshot failed' }- const screenMeta = tuiOwnsScrollback ? { ...meta, alternateOn: true } : meta- let rows: Uint8Array | undefined = historyRows ?? (conversation ? normalizeTmuxHistoryLines(history) : undefined)- let bytes = synthesizeTmuxSnapshot(capture.stdout, screenMeta, history, rows)- // A conversation is seeded as far back as fits: past the limit the stream would be closed, so its oldest- // rows go. Any other history is sent as it always was.- if (conversation && rows && bytes.length > KEYFRAME_MAX_BYTES) {- rows = dropOldestHistoryRows(rows, bytes.length - KEYFRAME_MAX_BYTES)- bytes = synthesizeTmuxSnapshot(capture.stdout, screenMeta, history, rows)- }- return {- state: 'succeeded',- value: {- bytes,- cols: meta.paneWidth,- rows: meta.paneHeight,- },- }+ if (!repaint) return this.capturePane(options)+ if (repaint.cleared || Date.now() - this.resizedAt < repaint.withinMs) await this.waitForRepaint(repaint)+ const taken = await this.capturePane(options, repaint)+ if (taken !== 'printing') return taken+ // The print began before the capture's cut and had not ended at it: after the wait above gave up, or where there+ // was none to make. The viewer would draw the cleared or half-printed screen that capture holds, and the live+ // output after it begins with no clear for the stream manager to see. It is taken again once the print ends.+ await this.waitForRepaint({ ...repaint, cleared: true })+ return this.capturePane(options)+ })+ }++ /**+ * The pane, read for a keyframe. With `print`, what the capture's cut discards is read for that print+ * (`printInProgress`), and a capture taken while it was under way comes back as `'printing'`.+ */+ private capturePane(options: SnapshotOptions | undefined): Promise<TerminalReadResult<TerminalStreamSnapshot>>+ private capturePane(+ options: SnapshotOptions | undefined, print: { clears: string; ends: string },+ ): Promise<TerminalReadResult<TerminalStreamSnapshot> | 'printing'>+ private async capturePane(+ options: SnapshotOptions | undefined, print?: { clears: string; ends: string },+ ): Promise<TerminalReadResult<TerminalStreamSnapshot> | 'printing'> {+ // -N is required for TUI fidelity: styled blank cells (for example the+ // Codex input box background) live in trailing spaces that tmux otherwise+ // trims from each captured row. Deliberately do not use capture-pane -S:+ // tmux scrollback contains old full-screen TUI repaint frames. Replaying+ // those frames into a fresh emulator corrupts the visible screen.+ // -N is tmux 3.1. Before it the flag failed the capture, and with it every+ // snapshot: the terminal never showed. Without it the screen is all there,+ // short only of the colour of a row's trailing blanks.+ const keepTrailing = this.features.captureTrailingSpaces ? ' -N' : ''+ const baseCapture = `capture-pane -p -e${keepTrailing} -t ${this.runtime.paneId}`+ // Attaching a control client can trigger an immediate TUI repaint. Wait+ // before reading both cursor metadata and the grid so the synthesized+ // keyframe cannot combine a post-repaint grid with pre-repaint cursor+ // coordinates.+ await this.waitForSnapshotQuiet()+ const metadata = await this.runControlCommand(+ `display-message -p -t ${this.runtime.paneId} '${PANE_META_FORMAT}'`,+ )+ if (!metadata.ok) return { state: 'failed', reason: 'tmux snapshot metadata is unavailable' }+ const meta = parsePaneMeta(metadata.stdout)+ if (!meta || meta.windowPanes !== 1) return { state: 'failed', reason: 'tmux snapshot metadata is invalid' }+ // History is a styled cell capture used only to seed the receiver's+ // local scrollback. It preserves SGR attributes without replaying old+ // TUI cursor movement. Read it before the authoritative visible-grid cut+ // so concurrent output is included there or in a post-cut delta.+ //+ // Grok (and any TUI that paints in the normal buffer) is the other+ // history trap: tmux reports alternate_on=0, so a naive capture would+ // seed hundreds of prior full-screen repaint frames. The window then+ // shows stacked empty chrome above the live header, and the wheel+ // scrolls that junk locally instead of the program.+ const tuiOwnsScrollback = options?.tuiOwnsScrollback === true+ const seedsHistory = !meta.alternateOn && !tuiOwnsScrollback+ const conversation = seedsHistory && options?.conversationHistory === true+ const historyRange = `-t ${this.runtime.paneId} -S -${conversation ? CONVERSATION_HISTORY_LINES : SNAPSHOT_HISTORY_LINES} -E -1`+ const plainHistory = `capture-pane -p -e${keepTrailing} ${historyRange}`+ const { history, rows: historyRows } = conversation && meta.paneWidth >= REWRAP_MIN_WIDTH+ ? await this.conversationHistory(plainHistory, historyRange, meta.paneWidth)+ : { history: seedsHistory ? (await this.runControlCommand(plainHistory)).stdout : Buffer.alloc(0), rows: null }+ let printing = false+ const capture = await this.runControlCommand(baseCapture, () => {+ // `%end` is the ordered cut. Notifications observed before it are+ // represented by capture-pane; only later output may follow the keyframe.+ if (print) printing = printInProgress(this.snapshotPostCut, print)+ this.snapshotPostCut = []+ this.snapshotPostCutBytes = 0})+ if (!capture.ok) return { state: 'failed', reason: 'tmux snapshot failed' }+ if (printing) return 'printing'+ const screenMeta = tuiOwnsScrollback ? { ...meta, alternateOn: true } : meta+ let rows: Uint8Array | undefined = historyRows ?? (conversation ? normalizeTmuxHistoryLines(history) : undefined)+ let bytes = synthesizeTmuxSnapshot(capture.stdout, screenMeta, history, rows)+ // A conversation is seeded as far back as fits: past the limit the stream would be closed, so its oldest+ // rows go. Any other history is sent as it always was.+ if (conversation && rows && bytes.length > KEYFRAME_MAX_BYTES) {+ rows = dropOldestHistoryRows(rows, bytes.length - KEYFRAME_MAX_BYTES)+ bytes = synthesizeTmuxSnapshot(capture.stdout, screenMeta, history, rows)+ }+ return {+ state: 'succeeded',+ value: {+ bytes,+ cols: meta.paneWidth,+ rows: meta.paneHeight,+ },+ }+ }++ /**+ * A conversation's history as tmux has it, and re-wrapped by word (historyRewrap.ts) where a line of it is wider than+ * the pane: tmux re-wraps it by the cell whenever a takeover narrows the pane. That reads the same rows joined back+ * into the lines they were (-J), and whether the last of them runs on into the visible grid (one line from -1 to 0,+ * not two). The three must read one history, so they are written to tmux together (`runTogether`); should the+ * pane's output be read between them all the same, they are read again, and a second time the history goes as tmux+ * has it. The plain capture is the keyframe's whenever there is nothing to re-wrap or the re-wrap cannot be used.+ */+ private async conversationHistory(+ plainHistory: string, range: string, width: number,+ ): Promise<{ history: Uint8Array; rows: Uint8Array | null }> {+ let history: Uint8Array = Buffer.alloc(0)+ for (let attempt = 0; attempt < 2; attempt++) {+ let readAtFirst = -1+ let readAtLast = -2+ const [plain, joined, seam] = await Promise.all(this.runControlCommands([+ { command: plainHistory, onEnd: () => { readAtFirst = this.outputNotifications } },+ { command: `capture-pane -p -e -J ${range}` },+ { command: `capture-pane -p -J -t ${this.runtime.paneId} -S -1 -E 0`, onEnd: () => { readAtLast = this.outputNotifications } },+ ]))+ history = plain.stdout+ if (!plain.ok || !joined.ok || !seam.ok) return { history, rows: null }+ if (readAtFirst !== readAtLast) continue+ try {+ // One line, its newline the last byte: rows -1 and 0 are one line.+ const lastContinues = seam.stdout.indexOf(0x0a) === seam.stdout.length - 1+ return { history, rows: rewrapTmuxHistory(joined.stdout, width, { lastContinues }) }+ } catch {+ // A history the re-wrap cannot read is sent as tmux has it, as it always was.+ return { history, rows: null }+ }+ }+ return { history, rows: null }}endSnapshot(): void {@@ -888,7 +963,10 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {const postCut = this.snapshotPostCutthis.snapshotPostCut = []this.snapshotPostCutBytes = 0- for (const chunk of postCut) this.sink.onData(chunk)+ // The sink can begin the next snapshot from what is released here: the stream manager reads it for an engine's+ // print as it reads live output (terminalStreamManager.ts `repaintBegan`), and Codex's clear could be in it. What+ // is left then comes before that snapshot's cut, and is held behind its gate like any output from then on.+ for (const chunk of postCut) this.deliverOutput(chunk)}/**diff --git a/docs/design/2026-10-14-codex-scrollback.md b/docs/design/2026-10-14-codex-scrollback.mdindex 92710c72e..110570046 100644--- a/docs/design/2026-10-14-codex-scrollback.md+++ b/docs/design/2026-10-14-codex-scrollback.md@@ -92,7 +92,19 @@ line breaks, which tmux cannot join.- once joined back into logical lines (`capture-pane -J`).It also probes the seam: `-J -S -1 -E 0` returns one line if the last history row runs on into the visible-grid. All three commands are sent together, so no output lands between them.+grid. The three must read the same history:++- **One write.** `ControlCommandQueue.runTogether` writes the three lines to tmux in one write. tmux runs+ every line it read at once before it reads the pane again. Against a pane printing as fast as it could,+ output was read between the three in 28 of 500 tries when written one line per write, and in 0 of 500+ when written together (tmux 3.7c).+- **Checked, not assumed.** tmux sends a pane's output and command replies in the order they happened. The+ stream counts the pane's output notifications at the first capture's `%end` and at the last one's. If they+ differ, the three are read again; if they differ a second time, the history goes as tmux has it.+- **Not one line joined with `;`.** tmux answers each command of a list with its own `%begin`/`%end`, and+ none after one that fails. The queue, which also carries keystrokes, could no longer pair replies with+ commands.+`lib/historyRewrap.ts` then writes the history again:- **Measure as the viewer does.** `cellAdvance.ts` ports xterm.dart's Unicode 11 wide table. xterm.dart@@ -149,13 +161,22 @@ between.- **The wait.** Codex declares `resizeRepaint`. `TmuxControlStream` records when it really changed thepane's size (`resizedAt`). A snapshot taken within `withinMs` (250 ms) of that waits for the clear, then- for the first `ESC[?2026l` after it, and gives up after 400 ms (`REPAINT_MAX_MS`). Output meanwhile is- held behind the snapshot gate, and what precedes the capture's cut is the capture's. The clear never- leaves the daemon, and the keyframe holds the reprinted screen.+ for the first `ESC[?2026l` after it, and gives up 400 ms after it saw the clear (`REPAINT_MAX_MS`).+ Output meanwhile is held behind the snapshot gate, and what precedes the capture's cut is the capture's.+ The clear never leaves the daemon, and the keyframe holds the reprinted screen.+- **A print under way at the cut.** The clear can come after the wait gave up, or where there was no wait+ to make, and still before the capture's cut. The cut then discards it, and the capture holds a cleared or+ half-printed screen. So the output the cut discards is read for the print (`printInProgress`). If the+ print began there and had not ended, the snapshot waits for its end and is taken again; only that+ keyframe is sent.- **The guard.** For 1.5 s after a keyframe for an open or a resize (`REPAINT_GUARD_MS`), the streammanager watches live output for the clear. If it arrives anyway (a Codex at work answered later than thewait), the chunk and anything unsent are dropped, and a keyframe waits for the reprint's end. If the endcame in the same chunk, the keyframe is taken at once.+- **The output a keyframe held back is live output too.** After a keyframe is sent, the output that followed+ its cut is released, and it is read for the clear like any live output. The manager marks the keyframe as+ done before releasing that output. If a keyframe for the print begins partway through the release, the+ stream holds the rest behind that keyframe's gate: it precedes the new cut, so the capture holds it.- **Reading the end, not a pause.** A first version waited for a 50 ms pause in the output. A Codex at workredraws its `Working (…)` line continuously and never pauses, so every resize keyframe ran to the 1.5 scap, holding the phone's echo of what was typed (`snapshotMs` 1536–1585 in the daemon's log).@@ -202,7 +223,9 @@ override the person's own choice for Claude Code.until they scroll into history and a later keyframe arrives (an open, a resize or a keyboard toggle).Codex's own reprint usually repairs them first.- **Resize keyframes for Codex arrive later:**- - 100–112 ms idle, about 185 ms in a long session at work, at most 400 ms;+ - 100–112 ms idle, about 185 ms in a long session at work, at most 400 ms after the clear;+ - a print caught under way at the capture's cut costs one more capture, after waiting up to another+ 400 ms for its end;- a Codex with no transcript to reprint costs the full 250 ms wait;- typed echo is held for that window, and only right after a resize.- **Heavier keyframes for Codex panes.** 2000 rows at 40 columns measured 103 KiB and about 32 ms to@@ -237,11 +260,17 @@ keyframe.long words, wide characters, clusters, the seam, and Codex diff joins;- `lib/cellAdvance.spec.ts`;- `engines/kit/launchScreen.spec.ts`.-- **Updated specs:** `lib/engineLaunch.spec.ts`, `shellLaunch.spec.ts`, `lib/terminalStreamManager.spec.ts`- (options, the repaint guard, `reason`) and `lib/tmuxStream.spec.ts` (`dropOldestHistoryRows`).+- **Updated specs:**+ - `lib/engineLaunch.spec.ts` and `shellLaunch.spec.ts`;+ - `lib/terminalStreamManager.spec.ts`: options, the repaint guard, `reason`, and a clear in the output a+ keyframe held back;+ - `lib/tmuxStream.spec.ts`: `dropOldestHistoryRows`, `printInProgress`, and `runTogether` (one write,+ replies still paired, failures).- **Real tmux** (`lib/tmuxStream.real.spec.ts`, `RUN_REAL_TMUX_STREAM=1`):- a conversation's history seeded whole and re-wrapped;- - a pane script that clears and reprints on SIGWINCH while animating a status line every 20 ms.+ - a pane script that clears and reprints on SIGWINCH while animating a status line every 20 ms;+ - a print still under way at the capture's cut, taken again once it ends;+ - the rest of a release held behind a snapshot its sink begins.On macOS run it with a short `TMPDIR`, or tmux's socket path is too long.- **Golden launch records re-recorded** (`RECORD_LAUNCH_GOLDEN`, `RECORD_LAUNCH_SHAPES_GOLDEN`,