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 the colour tmux carries across snapshot rows
Dev jacobfa3357032662
diff --git a/cli/src/lib/sgrCarry.spec.ts b/cli/src/lib/sgrCarry.spec.tsnew file mode 100644index 000000000..727787158--- /dev/null+++ b/cli/src/lib/sgrCarry.spec.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest'+import { SgrCarry } from './sgrCarry.js'++function carriedAfter(...rows: string[]): string {+ const carry = new SgrCarry()+ for (const row of rows) carry.feed(row)+ return carry.restore+}++describe('SgrCarry', () => {+ it('carries nothing out of a row that set nothing, or reset what it set', () => {+ expect(carriedAfter('plain text')).toBe('')+ expect(carriedAfter('\u001b[2mdim\u001b[0m')).toBe('')+ expect(carriedAfter('\u001b[2mdim\u001b[m')).toBe('')+ })++ it('carries what is still open at the end of a row, into rows that restate nothing', () => {+ expect(carriedAfter('\u001b[2mdim text that wraps ')).toBe('\u001b[2m')+ expect(carriedAfter('\u001b[2mdim ', '', 'still dim')).toBe('\u001b[2m')+ })++ it('serializes in one order, whatever order the row set them in', () => {+ expect(carriedAfter('\u001b[31m\u001b[1mbold red')).toBe('\u001b[1;31m')+ expect(carriedAfter('\u001b[1;31m')).toBe('\u001b[1;31m')+ })++ it('clears only what each reset code names', () => {+ expect(carriedAfter('\u001b[1;2;3;31;42m', '\u001b[22m')).toBe('\u001b[3;31;42m')+ expect(carriedAfter('\u001b[31;42m', '\u001b[39m')).toBe('\u001b[42m')+ expect(carriedAfter('\u001b[4;7;9m', '\u001b[24;27;29m')).toBe('')+ })++ it('keeps 256-colour and truecolour whole, and lets a later colour replace an earlier one', () => {+ expect(carriedAfter('\u001b[38;5;244m')).toBe('\u001b[38;5;244m')+ expect(carriedAfter('\u001b[38;2;166;227;161;48;5;236m')).toBe('\u001b[38;2;166;227;161;48;5;236m')+ expect(carriedAfter('\u001b[38;5;244m', '\u001b[91m')).toBe('\u001b[91m')+ })++ it('reads colon sub-parameters as one parameter', () => {+ expect(carriedAfter('\u001b[4:3m')).toBe('\u001b[4:3m')+ expect(carriedAfter('\u001b[4:3m', '\u001b[4:0m')).toBe('')+ expect(carriedAfter('\u001b[38:2::1:2:3m')).toBe('\u001b[38:2::1:2:3m')+ })++ it('drops a truncated extended colour rather than carrying half of it', () => {+ expect(carriedAfter('\u001b[2;38;2;1m')).toBe('\u001b[2m')+ })++ it('ignores CSI that is not SGR', () => {+ expect(carriedAfter('\u001b[>4;2m\u001b[2K\u001b[5;1H')).toBe('')+ })+})diff --git a/cli/src/lib/sgrCarry.ts b/cli/src/lib/sgrCarry.tsnew file mode 100644index 000000000..d78be221c--- /dev/null+++ b/cli/src/lib/sgrCarry.ts@@ -0,0 +1,103 @@+/**+ * The SGR state a tmux capture leaves open at the end of one row, re-stated at the start of the next.+ *+ * ⚠️ **`capture-pane -e` is a diff, not a set of self-contained rows.** tmux writes only the SGR that+ * changes from one cell to the next, and that includes the step from the last cell of row N to the+ * first cell of row N+1. A dim command line that wraps (Codex's `Ran …` output) arrives as+ * `ESC[2mdim text that wraps ` and then `past twenty cols` with no SGR at all, because tmux considers+ * dim still in force. Its empty rows carry the state across without writing a byte.+ *+ * The snapshot builders reset SGR at every row end, and they must keep doing so: a background left+ * active at EOL would otherwise fill the next row when it scrolls in. The reset alone, though, turned+ * every carried cell back into plain default text, so the same Codex output read dim live and bright+ * after the next keyframe (open, resize, resync, reconnect). This tracker is the other half: whatever+ * tmux assumed was still active is written again after the reset.+ */++type SgrSlot =+ | 'bold' | 'faint' | 'italic' | 'underline' | 'blink' | 'inverse' | 'hidden' | 'strike' | 'overline'+ | 'fg' | 'bg' | 'underlineColor'++/** Emission order, so the same state always serializes to the same bytes. */+const SLOTS: readonly SgrSlot[] = [+ 'bold', 'faint', 'italic', 'underline', 'blink', 'inverse', 'hidden', 'strike', 'overline',+ 'fg', 'bg', 'underlineColor',+]++/** Plain SGR codes that set one slot, or clear the listed ones. */+const SETS: Readonly<Record<number, SgrSlot>> = {+ 1: 'bold', 2: 'faint', 3: 'italic', 4: 'underline', 5: 'blink', 6: 'blink', 7: 'inverse', 8: 'hidden',+ 9: 'strike', 21: 'underline', 53: 'overline',+}+const CLEARS: Readonly<Record<number, readonly SgrSlot[]>> = {+ 22: ['bold', 'faint'], 23: ['italic'], 24: ['underline'], 25: ['blink'], 27: ['inverse'], 28: ['hidden'],+ 29: ['strike'], 39: ['fg'], 49: ['bg'], 55: ['overline'], 59: ['underlineColor'],+}+const EXTENDED_COLOR: Readonly<Record<number, SgrSlot>> = { 38: 'fg', 48: 'bg', 58: 'underlineColor' }++/** Private-marker CSI (`CSI > 4 ; 2 m`) is not SGR, so it never matches. */+const SGR_PATTERN = /\u001b\[([0-9;:]*)m/g++function colorSlot(code: number): SgrSlot | undefined {+ if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) return 'fg'+ if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107)) return 'bg'+ return undefined+}++export class SgrCarry {+ private readonly state = new Map<SgrSlot, string>()++ /** The SGR that re-establishes the carried state, or '' when nothing is carried. */+ get restore(): string {+ if (this.state.size === 0) return ''+ return `\u001b[${SLOTS.flatMap((slot) => this.state.get(slot) ?? []).join(';')}m`+ }++ /** Read one captured row and move the state to where tmux leaves it at that row's end. */+ feed(row: string): void {+ for (const match of row.matchAll(SGR_PATTERN)) this.apply(match[1].split(';'))+ }++ private apply(params: readonly string[]): void {+ for (let index = 0; index < params.length; index++) {+ const param = params[index]+ if (param.includes(':')) {+ this.applySubParams(param)+ continue+ }+ const code = param === '' ? 0 : Number(param)+ if (code === 0) {+ this.state.clear()+ continue+ }+ const extended = EXTENDED_COLOR[code]+ if (extended) {+ // `38;5;n` or `38;2;r;g;b`: the colour is the code plus the parameters that belong to it.+ const take = params[index + 1] === '5' ? 2 : params[index + 1] === '2' ? 4 : 0+ if (take === 0 || index + take >= params.length) return+ this.state.set(extended, params.slice(index, index + take + 1).join(';'))+ index += take+ continue+ }+ const set = SETS[code] ?? colorSlot(code)+ if (set) {+ this.state.set(set, param)+ continue+ }+ for (const slot of CLEARS[code] ?? []) this.state.delete(slot)+ }+ }++ /** Colon forms carry their own sub-parameters: `4:3` (curly underline), `38:2::r:g:b`. */+ private applySubParams(param: string): void {+ const [head, first] = param.split(':')+ const code = Number(head)+ if (code === 4) {+ if (first === '0') this.state.delete('underline')+ else this.state.set('underline', param)+ return+ }+ const extended = EXTENDED_COLOR[code]+ if (extended) this.state.set(extended, param)+ }+}diff --git a/cli/src/lib/tmuxStream.spec.ts b/cli/src/lib/tmuxStream.spec.tsindex 782b4a42b..2aa5fb87e 100644--- a/cli/src/lib/tmuxStream.spec.ts+++ b/cli/src/lib/tmuxStream.spec.ts@@ -210,6 +210,36 @@ describe('tmux snapshot row normalization', () => {expect(snapshot).toContain('\u001b[H\u001b[2J\u001b[?1003h\u001b[?1006h')})++ // What `capture-pane -p -e -N` printed for a dim line wrapped at 20 columns, then a red line, a blank+ // row, and more red (tmux 3.7c): the second row of the wrap, and the row after the blank one, carry+ // their SGR over from the row above without restating it.+ const carriedCapture = Buffer.from(+ '\u001b[2mdim text that wraps \npast twenty cols\u001b[0m \n'+ + '\u001b[31mred\u001b[39m \n\n\u001b[31mafter blank\u001b[39m\n',+ )++ it('keeps a wrapped dim line dim on its second row, across the per-row reset', () => {+ const snapshot = Buffer.from(synthesizeTmuxSnapshot(carriedCapture, {+ sessionId: '$1', windowId: '@1', windowPanes: 1,+ windowWidth: 20, windowHeight: 5, paneWidth: 20, paneHeight: 5,+ alternateOn: false, cursorX: 0, cursorY: 0,+ cursorVisible: true,+ mouseStandard: false, mouseButton: false, mouseAll: false,+ mouseUtf8: false, mouseSgr: false,+ })).toString()++ expect(snapshot).toContain('\u001b[1;1H\u001b[2mdim text that wraps \u001b[0m')+ expect(snapshot).toContain('\u001b[2;1H\u001b[2mpast twenty cols\u001b[0m \u001b[0m')+ // A row that closed its own colour carries nothing into the next.+ expect(snapshot).toContain('\u001b[4;1H\u001b[0m\u001b[5;1H\u001b[31mafter blank')+ })++ it('carries SGR across history rows the same way', () => {+ expect(Buffer.from(normalizeTmuxHistoryLines(Buffer.from('\u001b[2mone \ntwo\u001b[0m\nthree\n'))).toString()).toBe(+ '\u001b[2mone \u001b[0m\r\n\u001b[2mtwo\u001b[0m\u001b[0m\r\nthree\u001b[0m\r\n',+ )+ })})describe('ControlCommandQueue', () => {diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.tsindex 1dbf98bf9..c652a92e6 100644--- a/cli/src/lib/tmuxStream.ts+++ b/cli/src/lib/tmuxStream.ts@@ -1,5 +1,6 @@import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'import { patientDeadline } from './patientExec.js'+import { SgrCarry } from './sgrCarry.js'import { pasteRawIntoTmux } from './tmux.js'import { enterTmuxRoom, inTmuxRoom, needsControlGate } from './tmuxControlGate.js'import { tmuxFeatures, tmuxFeaturesOf, type TmuxFeatures } from './tmuxVersion.js'@@ -290,7 +291,15 @@ export function normalizeTmuxHistoryLines(capture: Uint8Array): Uint8Array {const end = raw.at(-1) === 0x0a ? raw.length - 1 : raw.lengthif (end <= 0) return Buffer.alloc(0)const rows = raw.subarray(0, end).toString('utf8').split('\n')- return Buffer.from(rows.map((row) => `${row.replace(/\r$/, '')}\u001b[0m\r\n`).join(''), 'utf8')+ // The reset keeps a row's trailing background out of the one that scrolls in after it; the carry+ // puts back what tmux left open across that boundary — see SgrCarry.+ const carry = new SgrCarry()+ return Buffer.from(rows.map((line) => {+ const row = line.replace(/\r$/, '')+ const restore = carry.restore+ carry.feed(row)+ return `${restore}${row}\u001b[0m\r\n`+ }).join(''), 'utf8')}export function synthesizeTmuxSnapshot(@@ -329,6 +338,7 @@ export function synthesizeTmuxSnapshot()const raw = Buffer.from(capture)const rows: Buffer[] = []+ const carry = new SgrCarry()let start = 0let rowIndex = 0for (let index = 0; index <= raw.length && rowIndex < meta.paneHeight; index++) {@@ -339,9 +349,15 @@ export function synthesizeTmuxSnapshot(// can disagree on the display width of Unicode scalars; replaying rows via// CRLF lets that disagreement wrap one row into another. Absolute row// placement with autowrap disabled makes the captured grid authoritative.+ //+ // Each row ends reset and begins with whatever SGR tmux carried into it (see SgrCarry): a wrapped+ // dim line's second row has no SGR of its own in the capture.+ const row = raw.subarray(start, end)+ const restore = carry.restore+ carry.feed(row.toString('latin1'))rows.push(- Buffer.from(`\u001b[${rowIndex + 1};1H`, 'utf8'),- raw.subarray(start, end),+ Buffer.from(`\u001b[${rowIndex + 1};1H${restore}`, 'utf8'),+ row,Buffer.from('\u001b[0m', 'utf8'),)rowIndex++