Skip to content

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.

fix(cli): a snapshot keeps the colour tmux carries from one row into the next

Dev jacob506073c0dc11
diff --git a/cli/src/lib/sgrCarry.spec.ts b/cli/src/lib/sgrCarry.spec.ts
new file mode 100644
index 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.ts
new file mode 100644
index 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.ts
index ff4a769bb..329b994d2 100644
--- a/cli/src/lib/tmuxStream.spec.ts
+++ b/cli/src/lib/tmuxStream.spec.ts
@@ -152,6 +152,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.ts
index 9abb037c4..68b20170c 100644
--- a/cli/src/lib/tmuxStream.ts
+++ b/cli/src/lib/tmuxStream.ts
@@ -1,4 +1,5 @@
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
+import { SgrCarry } from './sgrCarry.js'
import { pasteRawIntoTmux } from './tmux.js'
import {
TERMINAL_ACTION_SUCCEEDED,
@@ -205,7 +206,15 @@ export function normalizeTmuxHistoryLines(capture: Uint8Array): Uint8Array {
const end = raw.at(-1) === 0x0a ? raw.length - 1 : raw.length
if (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(
@@ -244,6 +253,7 @@ export function synthesizeTmuxSnapshot(
)
const raw = Buffer.from(capture)
const rows: Buffer[] = []
+ const carry = new SgrCarry()
let start = 0
let rowIndex = 0
for (let index = 0; index <= raw.length && rowIndex < meta.paneHeight; index++) {
@@ -254,9 +264,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++
diff --git a/desktop/third_party/xterm/lib/src/core/escape/parser.dart b/desktop/third_party/xterm/lib/src/core/escape/parser.dart
index 7571a9e18..12dbd8c36 100644
--- a/desktop/third_party/xterm/lib/src/core/escape/parser.dart
+++ b/desktop/third_party/xterm/lib/src/core/escape/parser.dart
@@ -437,6 +437,36 @@ class EscapeParser {
}
}
+ /// The colour after SGR 38/48 at [at] — `2;r;g;b` or `5;n` — handed to [rgb]
+ /// or [indexed]. Returns how many parameters after [at] it used.
+ ///
+ /// ⚠️ **A sequence cut short is dropped, never read past.** `CSI 38;2;1 m`
+ /// used to index beyond [params]; the RangeError failed the renderer, which
+ /// forced a resync — and a fresh keyframe — for one malformed colour. The
+ /// rest of the parameters are consumed, as they belong to that colour.
+ int _sgrExtendedColor(
+ List<int> params,
+ int at,
+ void Function(int r, int g, int b) rgb,
+ void Function(int index) indexed,
+ ) {
+ final remaining = params.length - at - 1;
+ final mode = remaining > 0 ? params[at + 1] : null;
+ final needed = switch (mode) {
+ 2 => 4,
+ 5 => 2,
+ _ => 0,
+ };
+ if (needed == 0) return 0;
+ if (needed > remaining) return remaining;
+ if (mode == 2) {
+ rgb(params[at + 2], params[at + 3], params[at + 4]);
+ } else {
+ indexed(params[at + 2]);
+ }
+ return needed;
+ }
+
/// `ESC [ [ Ps ] m` Select Graphic Rendition (SGR)
///
/// https://terminalguide.namepad.de/seq/csi_sm/
@@ -542,21 +572,12 @@ class EscapeParser {
handler.setForegroundColor16(NamedColor.white);
continue;
case 38:
- final mode = params[i + 1];
- switch (mode) {
- case 2:
- final r = params[i + 2];
- final g = params[i + 3];
- final b = params[i + 4];
- handler.setForegroundColorRgb(r, g, b);
- i += 4;
- break;
- case 5:
- final index = params[i + 2];
- handler.setForegroundColor256(index);
- i += 2;
- break;
- }
+ i += _sgrExtendedColor(
+ params,
+ i,
+ handler.setForegroundColorRgb,
+ handler.setForegroundColor256,
+ );
continue;
case 39:
handler.resetForeground();
@@ -587,21 +608,12 @@ class EscapeParser {
handler.setBackgroundColor16(NamedColor.white);
continue;
case 48:
- final mode = params[i + 1];
- switch (mode) {
- case 2:
- final r = params[i + 2];
- final g = params[i + 3];
- final b = params[i + 4];
- handler.setBackgroundColorRgb(r, g, b);
- i += 4;
- break;
- case 5:
- final index = params[i + 2];
- handler.setBackgroundColor256(index);
- i += 2;
- break;
- }
+ i += _sgrExtendedColor(
+ params,
+ i,
+ handler.setBackgroundColorRgb,
+ handler.setBackgroundColor256,
+ );
continue;
case 49:
handler.resetBackground();
diff --git a/desktop/third_party/xterm/lib/src/ui/palette_builder.dart b/desktop/third_party/xterm/lib/src/ui/palette_builder.dart
index 0dedff03b..4e0986590 100644
--- a/desktop/third_party/xterm/lib/src/ui/palette_builder.dart
+++ b/desktop/third_party/xterm/lib/src/ui/palette_builder.dart
@@ -49,7 +49,7 @@ class PaletteBuilder {
case 14:
return theme.brightCyan;
case 15:
- return theme.white;
+ return theme.brightWhite;
}
if (colNum < 232) {
diff --git a/mobile/test/xterm_sgr_colour_test.dart b/mobile/test/xterm_sgr_colour_test.dart
new file mode 100644
index 000000000..cb31ad658
--- /dev/null
+++ b/mobile/test/xterm_sgr_colour_test.dart
@@ -0,0 +1,53 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/terminal_theme.dart';
+import 'package:xterm/src/ui/palette_builder.dart';
+import 'package:xterm/xterm.dart';
+
+/// The colours a terminal paints: what SGR 38/48 set, and what palette slot 15
+/// holds.
+void main() {
+ int foreground(Terminal terminal) =>
+ terminal.buffer.lines[0].getForeground(0) & ~CellColor.typeMask;
+ int foregroundType(Terminal terminal) =>
+ terminal.buffer.lines[0].getForeground(0) & CellColor.typeMask;
+
+ test('a 256-colour and a truecolour foreground land on the cell', () {
+ final indexed = Terminal()..write('\u001b[38;5;244mX');
+ expect(foregroundType(indexed), CellColor.palette);
+ expect(foreground(indexed), 244);
+
+ final rgb = Terminal()..write('\u001b[38;2;1;2;3mX');
+ expect(foregroundType(rgb), CellColor.rgb);
+ expect(foreground(rgb), 0x010203);
+ });
+
+ // A malformed colour used to index past the parameters and throw, which
+ // failed the renderer and forced a resync for one bad sequence.
+ test(
+ 'a colour cut short is dropped without throwing, and so is the rest of it',
+ () {
+ for (final cut in [
+ '\u001b[38;2;1m',
+ '\u001b[48;2;1;2m',
+ '\u001b[38;5m',
+ '\u001b[38m',
+ ]) {
+ final terminal = Terminal();
+ expect(() => terminal.write('${cut}X'), returnsNormally, reason: cut);
+ expect(foregroundType(terminal), CellColor.normal, reason: cut);
+ }
+ // What came before the cut colour still applies.
+ final faint = Terminal()..write('\u001b[2;38;2;1mX');
+ expect(
+ faint.buffer.lines[0].getAttributes(0) & CellAttr.faint,
+ CellAttr.faint,
+ );
+ },
+ );
+
+ test('palette slot 15 is bright white, not white', () {
+ final palette = PaletteBuilder(darkTerminalTheme).build();
+ expect(palette[15], darkTerminalTheme.brightWhite);
+ expect(palette[7], darkTerminalTheme.white);
+ });
+}
diff --git a/mobile/third_party/xterm/lib/src/core/escape/parser.dart b/mobile/third_party/xterm/lib/src/core/escape/parser.dart
index 7571a9e18..12dbd8c36 100644
--- a/mobile/third_party/xterm/lib/src/core/escape/parser.dart
+++ b/mobile/third_party/xterm/lib/src/core/escape/parser.dart
@@ -437,6 +437,36 @@ class EscapeParser {
}
}
+ /// The colour after SGR 38/48 at [at] — `2;r;g;b` or `5;n` — handed to [rgb]
+ /// or [indexed]. Returns how many parameters after [at] it used.
+ ///
+ /// ⚠️ **A sequence cut short is dropped, never read past.** `CSI 38;2;1 m`
+ /// used to index beyond [params]; the RangeError failed the renderer, which
+ /// forced a resync — and a fresh keyframe — for one malformed colour. The
+ /// rest of the parameters are consumed, as they belong to that colour.
+ int _sgrExtendedColor(
+ List<int> params,
+ int at,
+ void Function(int r, int g, int b) rgb,
+ void Function(int index) indexed,
+ ) {
+ final remaining = params.length - at - 1;
+ final mode = remaining > 0 ? params[at + 1] : null;
+ final needed = switch (mode) {
+ 2 => 4,
+ 5 => 2,
+ _ => 0,
+ };
+ if (needed == 0) return 0;
+ if (needed > remaining) return remaining;
+ if (mode == 2) {
+ rgb(params[at + 2], params[at + 3], params[at + 4]);
+ } else {
+ indexed(params[at + 2]);
+ }
+ return needed;
+ }
+
/// `ESC [ [ Ps ] m` Select Graphic Rendition (SGR)
///
/// https://terminalguide.namepad.de/seq/csi_sm/
@@ -542,21 +572,12 @@ class EscapeParser {
handler.setForegroundColor16(NamedColor.white);
continue;
case 38:
- final mode = params[i + 1];
- switch (mode) {
- case 2:
- final r = params[i + 2];
- final g = params[i + 3];
- final b = params[i + 4];
- handler.setForegroundColorRgb(r, g, b);
- i += 4;
- break;
- case 5:
- final index = params[i + 2];
- handler.setForegroundColor256(index);
- i += 2;
- break;
- }
+ i += _sgrExtendedColor(
+ params,
+ i,
+ handler.setForegroundColorRgb,
+ handler.setForegroundColor256,
+ );
continue;
case 39:
handler.resetForeground();
@@ -587,21 +608,12 @@ class EscapeParser {
handler.setBackgroundColor16(NamedColor.white);
continue;
case 48:
- final mode = params[i + 1];
- switch (mode) {
- case 2:
- final r = params[i + 2];
- final g = params[i + 3];
- final b = params[i + 4];
- handler.setBackgroundColorRgb(r, g, b);
- i += 4;
- break;
- case 5:
- final index = params[i + 2];
- handler.setBackgroundColor256(index);
- i += 2;
- break;
- }
+ i += _sgrExtendedColor(
+ params,
+ i,
+ handler.setBackgroundColorRgb,
+ handler.setBackgroundColor256,
+ );
continue;
case 49:
handler.resetBackground();
diff --git a/mobile/third_party/xterm/lib/src/ui/palette_builder.dart b/mobile/third_party/xterm/lib/src/ui/palette_builder.dart
index 0dedff03b..4e0986590 100644
--- a/mobile/third_party/xterm/lib/src/ui/palette_builder.dart
+++ b/mobile/third_party/xterm/lib/src/ui/palette_builder.dart
@@ -49,7 +49,7 @@ class PaletteBuilder {
case 14:
return theme.brightCyan;
case 15:
- return theme.white;
+ return theme.brightWhite;
}
if (colNum < 232) {