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
import { describe, expect, it, vi } from 'vitest'
import {
ControlCommandQueue,
decodeTmuxControlData,
dropOldestHistoryRows,
literalKeyCommands,
normalizeTmuxHistoryLines,
normalizeTmuxCaptureLines,
parseTmuxControlOutput,
printInProgress,
quoteForOldTmux,
synthesizeTmuxSnapshot,
tuiScrollPageCount,
} from './tmuxStream.js'
describe('tuiScrollPageCount', () => {
it('is one page per gesture, never a stack', () => {
expect(tuiScrollPageCount(0)).toBe(0)
expect(tuiScrollPageCount(-1)).toBe(0)
expect(tuiScrollPageCount(1)).toBe(1)
expect(tuiScrollPageCount(12)).toBe(1)
expect(tuiScrollPageCount(400)).toBe(1)
})
})
// tmux before 3.0 has no `send-keys -H`: keystrokes go as text through its command parser (cmd-string.c),
// so every byte that parser treats as syntax has to come back out exactly. Proven against real tmux 2.8
// byte for byte in tmuxStream.real.spec.ts; these pin the encoding.
describe('keystrokes for a tmux without send-keys -H', () => {
it('quotes text so the old parser hands it back as it was', () => {
expect(quoteForOldTmux('plain text')).toBe("'plain text'")
// Single quotes hold everything but themselves; a `'` goes in double quotes.
expect(quoteForOldTmux("it's")).toBe(`'it'"'"'s'`)
expect(quoteForOldTmux('$HOME #not ~ "x" \\')).toBe(`'$HOME #not ~ "x" \\'`)
// An argument ending in `;` ends the command, unless it ends in `\;`, which comes back as `;`.
expect(quoteForOldTmux('a;')).toBe(`'a\\;'`)
expect(quoteForOldTmux(';')).toBe(`'\\;'`)
expect(quoteForOldTmux("';")).toBe(`''"'"'\\;'`)
expect(quoteForOldTmux('a\\;')).toBe(`'a\\\\;'`)
expect(quoteForOldTmux('a;b')).toBe("'a;b'")
})
it('sends LF and NUL as the keys that write them, and text after `--`', () => {
expect(literalKeyCommands('%3', Buffer.from('-a\nb\0'))).toEqual([
"send-keys -t %3 -l -- '-a'",
'send-keys -t %3 C-j',
"send-keys -t %3 -l -- 'b'",
'send-keys -t %3 C-@',
])
expect(literalKeyCommands('%3', Buffer.from('\n\n'))).toEqual(['send-keys -t %3 C-j', 'send-keys -t %3 C-j'])
expect(literalKeyCommands('%3', Buffer.alloc(0))).toEqual([])
})
it('cuts long text into commands, never inside a UTF-8 character', () => {
// 世 is three bytes: a cut after three would land inside the first one, so it moves back before it.
expect(literalKeyCommands('%3', Buffer.from('a世世b'), 3)).toEqual([
"send-keys -t %3 -l -- 'a'",
"send-keys -t %3 -l -- '世'",
"send-keys -t %3 -l -- '世'",
"send-keys -t %3 -l -- 'b'",
])
expect(literalKeyCommands('%3', Buffer.from('a世世b'), 4)).toEqual([
"send-keys -t %3 -l -- 'a世'",
"send-keys -t %3 -l -- '世b'",
])
// A run of bytes that are not UTF-8 at all is still cut, rather than never.
expect(literalKeyCommands('%3', Buffer.from([0x61, 0x80, 0x80, 0x80, 0x80]), 2)).toHaveLength(4)
})
})
describe('tmux control-mode output decoding', () => {
it('decodes octal bytes without corrupting adjacent UTF-8', () => {
const decoded = decodeTmuxControlData('hello\\040世界\\015\\012\\033[31m')
expect(Buffer.from(decoded)).toEqual(Buffer.from('hello 世界\r\n\u001b[31m'))
})
it('preserves ordinary backslashes that are not octal escapes', () => {
expect(Buffer.from(decodeTmuxControlData('C:\\Users\\name')).toString()).toBe('C:\\Users\\name')
})
it('preserves a UTF-8 scalar split across separate output records', () => {
const first = parseTmuxControlOutput(Buffer.concat([
Buffer.from('%output %7 '),
Buffer.from([0xe2, 0x94]),
]))
const second = parseTmuxControlOutput(Buffer.concat([
Buffer.from('%output %7 '),
Buffer.from([0x80]),
]))
expect(first?.paneId).toBe('%7')
expect(second?.paneId).toBe('%7')
expect(Buffer.concat([
Buffer.from(first!.data),
Buffer.from(second!.data),
])).toEqual(Buffer.from('─'))
})
})
describe('tmux snapshot row normalization', () => {
it('turns capture-pane LF rows into VT CRLF and drops its final output delimiter', () => {
const capture = Buffer.from('first\n\u001b[31m世界\nlast\r\n')
expect(Buffer.from(normalizeTmuxCaptureLines(capture))).toEqual(
Buffer.from('first\u001b[0m\r\n\u001b[31m世界\u001b[0m\r\nlast\u001b[0m'),
)
})
it('stops a styled trailing background from bleeding into the next blank row', () => {
const capture = Buffer.from('\u001b[48;5;237mprompt \n\n\u001b[49mreply\n')
expect(Buffer.from(normalizeTmuxCaptureLines(capture)).toString()).toBe(
'\u001b[48;5;237mprompt \u001b[0m\r\n\u001b[0m\r\n\u001b[49mreply\u001b[0m',
)
})
it('places every captured row absolutely while autowrap is disabled', () => {
const snapshot = Buffer.from(synthesizeTmuxSnapshot(
Buffer.from('wide 世界 row\nsecond row\n'),
{
sessionId: '$1', windowId: '@1', windowPanes: 1,
windowWidth: 80, windowHeight: 2, paneWidth: 80, paneHeight: 2,
alternateOn: false, cursorX: 4, cursorY: 1,
cursorVisible: true,
mouseStandard: false, mouseButton: false, mouseAll: false,
mouseUtf8: false, mouseSgr: false,
},
)).toString()
expect(snapshot).toContain('\u001b[?7l')
expect(snapshot).toContain('\u001b[1;1Hwide 世界 row\u001b[0m')
expect(snapshot).toContain('\u001b[2;1Hsecond row\u001b[0m')
expect(snapshot).toContain('\u001b[2;5H\u001b[?7h\u001b[?25h')
})
it('says which screen it captured, so the receiver can scroll it', () => {
// A pane running a full-screen TUI is on the ALTERNATE screen, and that one fact closes both ways
// of scrolling when it goes unsaid: the alternate screen has no scrollback to move through (tmux
// reports history_size=0), and the emulator only converts the wheel into escapes for the remote
// application while it believes it is on that buffer. `ESC c` resets to the normal one, so a
// keyframe that stayed silent actively asserted the wrong screen.
const meta = {
sessionId: '$1', windowId: '@1', windowPanes: 1,
windowWidth: 80, windowHeight: 2, paneWidth: 80, paneHeight: 2,
cursorX: 0, cursorY: 0, cursorVisible: true,
mouseStandard: false, mouseButton: false, mouseAll: false,
mouseUtf8: false, mouseSgr: false,
}
const onAlt = Buffer.from(synthesizeTmuxSnapshot(
Buffer.from('row\n'), { ...meta, alternateOn: true },
)).toString()
expect(onAlt).toContain('\u001b[?1049h')
expect(onAlt).not.toContain('\u001b[?1049l')
// And said in BOTH directions: a pane that has just come out of a TUI must not be left in it, and
// whether RIS alone leaves the alternate buffer is emulator-dependent.
const onNormal = Buffer.from(synthesizeTmuxSnapshot(
Buffer.from('row\n'), { ...meta, alternateOn: false },
)).toString()
expect(onNormal).toContain('\u001b[?1049l')
expect(onNormal).not.toContain('\u001b[?1049h')
})
it('preserves a tmux-hidden hardware cursor while restoring its position', () => {
const snapshot = Buffer.from(synthesizeTmuxSnapshot(
Buffer.from('painted input\n'),
{
sessionId: '$1', windowId: '@1', windowPanes: 1,
windowWidth: 80, windowHeight: 2, paneWidth: 80, paneHeight: 2,
alternateOn: false, cursorX: 0, cursorY: 1,
cursorVisible: false,
mouseStandard: false, mouseButton: false, mouseAll: false,
mouseUtf8: false, mouseSgr: false,
},
)).toString()
expect(snapshot.endsWith('\u001b[2;1H\u001b[?7h\u001b[?25l')).toBe(true)
})
it('seeds styled cell history before rebuilding the visible grid', () => {
const history = Buffer.from('\u001b[31mold-frame-1\u001b[39m\nold-frame-2\n')
expect(Buffer.from(normalizeTmuxHistoryLines(history)).toString()).toBe(
'\u001b[31mold-frame-1\u001b[39m\u001b[0m\r\nold-frame-2\u001b[0m\r\n',
)
const snapshot = Buffer.from(synthesizeTmuxSnapshot(
Buffer.from('current-screen\n'),
{
sessionId: '$1', windowId: '@1', windowPanes: 1,
windowWidth: 80, windowHeight: 2, paneWidth: 80, paneHeight: 2,
alternateOn: false, cursorX: 0, cursorY: 0,
cursorVisible: true,
mouseStandard: false, mouseButton: false, mouseAll: false,
mouseUtf8: false, mouseSgr: false,
},
history,
)).toString()
expect(snapshot.indexOf('old-frame-1')).toBeLessThan(snapshot.indexOf('current-screen'))
expect(snapshot).toContain('old-frame-2\u001b[0m\r\n\r\n\r\n\u001b[H\u001b[2J')
})
it('restores tmux mouse modes even when no scrollback exists', () => {
const snapshot = Buffer.from(synthesizeTmuxSnapshot(
Buffer.from('alternate-screen\n'),
{
sessionId: '$1', windowId: '@1', windowPanes: 1,
windowWidth: 80, windowHeight: 2, paneWidth: 80, paneHeight: 2,
alternateOn: true, cursorX: 0, cursorY: 0,
cursorVisible: true,
mouseStandard: false, mouseButton: false, mouseAll: true,
mouseUtf8: false, mouseSgr: true,
},
)).toString()
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',
)
})
it('sheds the oldest whole history rows, each still restoring the style carried into it', () => {
const rows = normalizeTmuxHistoryLines(Buffer.from('\u001b[2mone \ntwo\u001b[0m\nthree\n'))
const first = '\u001b[2mone \u001b[0m\r\n'
expect(dropOldestHistoryRows(rows, 0)).toBe(rows)
expect(Buffer.from(dropOldestHistoryRows(rows, 1)).toString()).toBe('\u001b[2mtwo\u001b[0m\u001b[0m\r\nthree\u001b[0m\r\n')
expect(Buffer.from(dropOldestHistoryRows(rows, Buffer.byteLength(first))).toString()).toBe('\u001b[2mtwo\u001b[0m\u001b[0m\r\nthree\u001b[0m\r\n')
expect(Buffer.from(dropOldestHistoryRows(rows, Buffer.byteLength(first) + 1)).toString()).toBe('three\u001b[0m\r\n')
expect(dropOldestHistoryRows(rows, rows.length).length).toBe(0)
})
})
describe('ControlCommandQueue', () => {
function harness(timeoutMs = 3_000) {
const written: string[] = []
const fatal: string[] = []
let accept = true
const queue = new ControlCommandQueue({
write: (line) => { if (!accept) return false; written.push(line); return true },
onFatal: (reason) => fatal.push(reason),
timeoutMs,
})
queue.markReady()
return { queue, written, fatal, reject: () => { accept = false } }
}
it('pipelines commands and completes them in order', async () => {
const { queue, written } = harness()
const first = queue.run('display-message -p one')
const second = queue.run('display-message -p two')
// Both reached tmux before either replied — that is what stops input queueing behind a snapshot.
expect(written).toEqual(['display-message -p one\n', 'display-message -p two\n'])
expect(queue.idle).toBe(false)
queue.handleBegin('10')
queue.appendResponseLine(Buffer.from('ONE'))
queue.handleCompleted('end', '10')
queue.handleBegin('11')
queue.appendResponseLine(Buffer.from('TWO'))
queue.handleCompleted('end', '11')
expect((await first).stdout.toString()).toBe('ONE\n')
expect((await second).stdout.toString()).toBe('TWO\n')
expect(queue.idle).toBe(true)
})
it('keeps an untracked send-keys from stealing a real command number', async () => {
const { queue } = harness()
const keys = queue.run('send-keys -t %1 -H 61')
const query = queue.run('display-message -p meta')
queue.handleBegin('20')
queue.handleCompleted('end', '20')
queue.handleBegin('21')
queue.appendResponseLine(Buffer.from('META'))
queue.handleCompleted('end', '21')
expect((await keys).ok).toBe(true)
// The reply landed on the query, not on the keystroke that preceded it.
expect((await query).stdout.toString()).toBe('META\n')
})
it('fails one command on %error without disturbing the next', async () => {
const { queue } = harness()
const bad = queue.run('send-keys -t %1 -H zz')
const good = queue.run('display-message -p ok')
queue.handleBegin('30')
queue.handleCompleted('error', '30')
queue.handleBegin('31')
queue.appendResponseLine(Buffer.from('OK'))
queue.handleCompleted('end', '31')
expect((await bad).ok).toBe(false)
expect((await good).ok).toBe(true)
expect((await good).stdout.toString()).toBe('OK\n')
})
it('ignores a completion that does not match the head', async () => {
const { queue } = harness()
const pending = queue.run('display-message -p one')
queue.handleBegin('40')
expect(queue.handleCompleted('end', '41')).toBe(false)
expect(queue.idle).toBe(false)
expect(queue.handleCompleted('end', '40')).toBe(true)
expect((await pending).ok).toBe(true)
})
it('times out from the moment a command reaches the head, not when it was written', async () => {
vi.useFakeTimers()
try {
const { queue, fatal } = harness(100)
const slow = queue.run('capture-pane -p')
const queued = queue.run('send-keys -t %1 -H 61')
queue.handleBegin('50')
// The second command has been on the wire the whole time but is not being timed yet.
await vi.advanceTimersByTimeAsync(90)
queue.handleCompleted('end', '50')
await vi.advanceTimersByTimeAsync(90)
expect(fatal).toEqual([])
await vi.advanceTimersByTimeAsync(20)
expect(fatal).toEqual(['tmux control command timed out'])
await slow
queue.failAll()
await queued
} finally {
vi.useRealTimers()
}
})
it('resolves everything as failed when the channel dies', async () => {
const { queue } = harness()
const inFlight = queue.run('display-message -p one')
queue.handleBegin('60')
queue.failAll()
expect((await inFlight).ok).toBe(false)
expect(queue.idle).toBe(true)
})
it('reports a write that the pipe refused', async () => {
const { queue, reject } = harness()
reject()
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)
})
})