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
Agents work on tmux older than 3.0 again; terminals on older than 3.2; Harness paints only its own panes (#822)
Dee458666be56c2
diff --git a/cli/e2e/tmuxmoves.e2e.ts b/cli/e2e/tmuxmoves.e2e.tsindex ea43de433..c535b3c95 100644--- a/cli/e2e/tmuxmoves.e2e.ts+++ b/cli/e2e/tmuxmoves.e2e.ts@@ -38,25 +38,46 @@ async function turn(client: LocalClient, agentId: string, content: string): Prom}const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))const paneOf = (agent: Row): string => String(agent.terminal?.runtimes?.[0]?.paneId ?? agent.tmuxPane)+/** How tmux paints [pane]: its window's `window-style`, and the pane's style as `select-pane -g` reports+ * it (the pane's own before tmux 3.0; from 3.0 its pane option, or its window's when it has none). */+const styleOf = async (d: IsolatedDaemon, pane: string) => ({+ window: await d.tmux.run('show-options', '-w', '-v', '-t', pane, 'window-style'),+ pane: await d.tmux.run('select-pane', '-g', '-t', pane),+})+type Style = Awaited<ReturnType<typeof styleOf>>describe('the person reaching into the agents\' tmux', () => {let daemon: IsolatedDaemon | undefinedafterEach(async () => { await daemon?.close(); daemon = undefined })+ // A move returns the person's own pane it put the agent's beside, if any, and how it was painted.it.each([['renames its session', async (d: IsolatedDaemon, pane: string, engine: Engine) => {const session = await d.tmux.run('display-message', '-p', '-t', pane, '#{session_name}')await d.tmux.run('rename-session', '-t', session, `my-${engine}-work`)+ return null as { pane: string; style: Style } | null}],['renames its window', async (d: IsolatedDaemon, pane: string, _engine: Engine) => {await d.tmux.run('rename-window', '-t', pane, 'review')+ return null}],['moves its pane into a window of their own', async (d: IsolatedDaemon, pane: string, engine: Engine) => {- await d.tmux.run('new-session', '-d', '-s', `mine-${engine}`, '-x', '120', '-y', '40')+ const theirs = await d.tmux.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', `mine-${engine}`, '-x', '120', '-y', '40')+ // The person's own colours for the window they made.+ await d.tmux.run('set-option', '-w', '-t', theirs, 'window-style', 'bg=#102030')+ const style = await styleOf(d, theirs)await d.tmux.run('join-pane', '-d', '-s', pane, '-t', `mine-${engine}:`)+ return { pane: theirs, style }}],['breaks its pane out into a window of its own', async (d: IsolatedDaemon, pane: string, _engine: Engine) => {- await d.tmux.run('break-pane', '-d', '-s', pane)+ await d.tmux.run('break-pane', '-d', '-s', pane).catch(async (error: unknown) => {+ // tmux before 3.1 will not break out a window's only pane ("can't break with only one pane"):+ // there the person has opened a shell beside the agent first, and it stays behind.+ if (!/only one pane/.test(String(error))) throw error+ await d.tmux.run('split-window', '-d', '-t', pane, '/bin/sh')+ await d.tmux.run('break-pane', '-d', '-s', pane)+ })+ return null}],] as const)('the person %s: the agent stays active, works, and comes back after a restart', async (_what, move) => {const d = await IsolatedDaemon.create()@@ -65,7 +86,22 @@ describe('the person reaching into the agents\' tmux', () => {await d.start()let client = await LocalClient.connect(d)const agents = [await create(d, client, 'claude', 'moved-claude'), await create(d, client, 'codex', 'moved-codex')]- for (const agent of agents) await move(d, paneOf(agent), agent.engine)+ const theirs: Array<{ pane: string; style: Style }> = []+ for (const agent of agents) {+ const beside = await move(d, paneOf(agent), agent.engine)+ if (beside) theirs.push(beside)+ }+ // The person's panes beside a moved agent keep their own colours, and the agent's keeps Harness's:+ // Harness paints only its panes, each on its own, never the window. When it painted windows, the+ // moved agent took the colours of the person's window, and the first scan after a daemon restart,+ // or a palette change, painted the person's shells there in Harness's.+ const untouched = async (when: string) => {+ for (const { pane, style } of theirs) expect(await styleOf(d, pane), `the person's ${pane} ${when}`).toEqual(style)+ for (const agent of agents) {+ await until(`${agent.engine}'s own pane in Harness's colours ${when}`, async () =>+ (await styleOf(d, paneOf(agent))).pane.includes('bg=#181818') ? true : null, 10_000, 250)+ }+ }// Several reconcile passes (5 s each here).await sleep(15_000)for (const agent of agents) {@@ -74,6 +110,7 @@ describe('the person reaching into the agents\' tmux', () => {expect(now?.sessionId).toBe(agent.sessionId)await turn(client, agent.id, `after the move (${agent.engine})`)}+ await untouched('after the move')client.close()await d.restart()client = await LocalClient.connect(d)@@ -84,6 +121,7 @@ describe('the person reaching into the agents\' tmux', () => {}, 60_000, 500)await turn(client, agent.id, `after the restart (${agent.engine})`)}+ await untouched('after the restart')expect(d.coresStarted()).toBe(2)client.close()}, 300_000)diff --git a/cli/src/lib/codexUpdateRestart.real.spec.ts b/cli/src/lib/codexUpdateRestart.real.spec.tsindex 06e3418ce..ccea35614 100644--- a/cli/src/lib/codexUpdateRestart.real.spec.ts+++ b/cli/src/lib/codexUpdateRestart.real.spec.ts@@ -71,7 +71,9 @@ if (output !== undefined) {const pane = await server.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-x', '40', '-y', '12', '-s', 'update', ...command)const screen = () => server!.run('capture-pane', '-p', '-J', '-t', pane)const attempts = async () => JSON.parse(await readFile(state, 'utf8')) as Attempt[]- const exited = () => server!.run('show-option', '-p', '-v', '-t', pane, '@harness_engine_exit').catch(() => '')+ // Read as the daemon reads it (`tmuxPaneState`): through a format, which finds the pane's own option+ // and, on a tmux before 3.0 with no pane options, the window's the mark went on there.+ const exited = () => server!.run('display-message', '-p', '-t', pane, '#{@harness_engine_exit}').catch(() => '')const waitFor = async (check: () => Promise<boolean>) => {const deadline = Date.now() + 10_000while (Date.now() < deadline) {diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex 63c27bed5..e352b7f6f 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -140,9 +140,31 @@ describe('buildEngineLaunchArgv', () => {const argv = buildEngineLaunchArgv('claude', {}, '/bin/sh', undefined, undefined, NO_TMUX)expect(run([argv[0], argv[1], argv[2], 'harness-engine', '/nowhere/claude-that-is-not-here']).status).toBe(127)})+ it.each([+ ['with pane options (3.0 and later)', '', 'set-option -p -t %5 @harness_engine_exit 3'],+ // tmux 2.x answers `-p` with its usage text: the mark goes on the pane's window instead.+ ['before pane options (tmux 2.x)', 'if [ "$2" = -p ]; then echo "set-option: illegal option -- p" >&2; exit 1; fi\n',+ 'set-option -w -t %5 @harness_engine_exit 3'],+ ])('marks the pane with the engine\'s exit status on a tmux %s', (_tmux, refuse, mark) => {+ const folder = mkdtempSync(join(tmpdir(), 'harness-exit-mark-'))+ try {+ const tmux = join(folder, 'tmux')+ const calls = join(folder, 'calls')+ writeFileSync(tmux, `#!/bin/sh\n${refuse}printf '%s\\n' "$*" >> '${calls}'\n`, { mode: 0o755 })+ const prelude = engineFallbackPrelude('claude', '/bin/sh', tmux)+ execFileSync('/bin/sh', ['-c', `${prelude}harness_engine "$@"`, 'harness-engine', '/bin/sh', '-c', 'exit 3'], {+ stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TMUX_PANE: '%5' },+ }).toString()+ } catch (error) {+ expect((error as { status: number }).status).toBe(3)+ } finally {+ expect(readFileSync(join(folder, 'calls'), 'utf8').trim()).toBe(mark)+ rmSync(folder, { recursive: true, force: true })+ }+ })it('marks the pane with the exit status through the daemon\'s own tmux, and only then hands over a shell', () => {const prelude = engineFallbackPrelude('codex', '/bin/bash', '/opt/homebrew/bin/tmux')- expect(prelude).toContain(`[ -n "\${TMUX_PANE:-}" ] && '/opt/homebrew/bin/tmux' set-option -p -t "$TMUX_PANE" @harness_engine_exit "$harness_status"`)+ expect(prelude).toContain(`[ -n "\${TMUX_PANE:-}" ] && { '/opt/homebrew/bin/tmux' set-option -p -t "$TMUX_PANE" @harness_engine_exit "$harness_status"`)expect(prelude.indexOf('set-option')).toBeLessThan(prelude.indexOf("exec '/bin/bash'"))expect(prelude).toContain('if [ "$harness_status" -eq 127 ]; then exit 127; fi')// zsh is a login shell; bash keeps its interactive rc (same rule as a terminal).diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex e5f09011d..90d5e3577 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -547,8 +547,13 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tmconst loginArgs = basename(shellPath).toLowerCase() === 'zsh' ? ' -l' : ''// Named by the command a person would type (`cursor-agent`, `cmd`), not the engine id.const command = basename(engineBin(engine)) || engine- const mark = tmuxBinary && isAbsolute(tmuxBinary)- ? ` [ -n "\${TMUX_PANE:-}" ] && ${shellSingleQuote(tmuxBinary)} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1 || true\n`+ // The pane's own option; a tmux before 3.0 has no pane options and refuses `-p`, so there the mark+ // goes on the pane's window, where `tmuxPaneState` reads it just the same. Without the second try+ // the mark was never made on such a tmux, and an engine that left read as still starting.+ const tmux = tmuxBinary && isAbsolute(tmuxBinary) ? shellSingleQuote(tmuxBinary) : null+ const mark = tmux+ ? ` [ -n "\${TMUX_PANE:-}" ] && { ${tmux} set-option -p -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1`+ + ` || ${tmux} set-option -w -t "$TMUX_PANE" ${ENGINE_EXIT_PANE_OPTION} "$harness_status" >/dev/null 2>&1; } || true\n`: ''// A function has its own positional parameters. Reprobe each replacement// binary without adding --no-daemon to the saved launch arguments repeatedly.diff --git a/cli/src/lib/harnessSessionLabel.spec.ts b/cli/src/lib/harnessSessionLabel.spec.tsindex 0573b8c37..1fc0b0e78 100644--- a/cli/src/lib/harnessSessionLabel.spec.ts+++ b/cli/src/lib/harnessSessionLabel.spec.ts@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'-import { harnessPaneOwner, ownedHere } from './harnessSessionLabel.js'+import { harnessPaneOwner, ownedHere, ownerCommand, paneOwnerFormat, paneOwnerOf } from './harnessSessionLabel.js'const dirs: string[] = []afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })@@ -49,3 +49,27 @@ describe('which daemon a pane belongs to', () => {expect(ownedHere('bbbb', 'my-claude-work', 'aaaa')).toBe(false)})})++// tmux before 3.0 (Debian 10's 2.8, RHEL 8's 2.7) has no pane options, and a window option stays behind+// with its window when the person moves the pane. The pane's start command goes with it.+describe('the tag on a tmux before 3.0', () => {+ it('rides the start command through env, which execs the real command at once', () => {+ expect(ownerCommand('0123456789abcdef', ['/bin/zsh', '-lic', 'exec "$@"', 'claude']))+ .toEqual(['/usr/bin/env', 'HARNESS_DAEMON=0123456789abcdef', '/bin/zsh', '-lic', 'exec "$@"', 'claude'])+ })++ it('is read from the pane option where there is one, and from the start command then the window before', () => {+ expect(paneOwnerFormat(true)).toBe('#{@harness_daemon}')+ // tmux 2.x cannot cut a substring out of a format: the start command comes back cut to the prefix+ // and a tag's length, never whole (it can hold the `|` and newlines a listing is split on).+ expect(paneOwnerFormat(false))+ .toBe('#{?#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}},#{=44:pane_start_command},#{@harness_daemon}}')+ })++ it('takes the tag out of a start command, and any other field as the tag itself', () => {+ expect(paneOwnerOf('/usr/bin/env HARNESS_DAEMON=0123456789abcdef')).toBe('0123456789abcdef')+ // The window's tag, a pane option, or nobody's.+ expect(paneOwnerOf('0123456789abcdef')).toBe('0123456789abcdef')+ expect(paneOwnerOf('')).toBe('')+ })+})diff --git a/cli/src/lib/harnessSessionLabel.ts b/cli/src/lib/harnessSessionLabel.tsindex cb2ba9ff6..df07671bd 100644--- a/cli/src/lib/harnessSessionLabel.ts+++ b/cli/src/lib/harnessSessionLabel.ts@@ -28,9 +28,50 @@ export const HARNESS_SESSION_PREFIX = 'harness-'* live in tmux), and a session name stops saying whose it is; a pane option goes with the pane, where a* window option stays behind with the window (e2e/tmuxmoves.e2e.ts). Read through the window too, which* is how a format resolves a pane option nobody set: a tag a build set on the window still counts.+ *+ * tmux before 3.0 has no pane options, and a `set-option -p` chained into `new-session` failed the whole+ * command list there, so every agent create failed (PR #789's review). There the tag is a window option,+ * and the pane's start command carries it too (`ownerCommand`).*/export const HARNESS_OWNER_OPTION = '@harness_daemon'+/**+ * Before tmux 3.0 there are no pane options: the tag can only be a window option, and a window option+ * stays behind with its window when the person moves the pane. What does go with a pane there is the+ * command it was started with, `#{pane_start_command}`. So on such a tmux a daemon starts each pane+ * through `/usr/bin/env HARNESS_DAEMON=<tag>` (`ownerCommand`), which execs the real command at once —+ * the pane's process is the shell, as before — and leaves the tag where tmux keeps it for the pane's+ * life, through any join, break or rename (e2e/tmuxmoves.e2e.ts, run on tmux 2.8).+ */+export const OWNER_COMMAND_ENV = 'HARNESS_DAEMON'+const OWNER_COMMAND_PREFIX = `/usr/bin/env ${OWNER_COMMAND_ENV}=`+/** How long a tag is (`harnessPaneOwner`). */+const OWNER_TAG_LENGTH = 16++/** [command], started so that tmux keeps [owner]'s tag in the pane's start command (see above). */+export function ownerCommand(owner: string, command: readonly string[]): string[] {+ return ['/usr/bin/env', `${OWNER_COMMAND_ENV}=${owner}`, ...command]+}++/**+ * The tmux format for a pane's owner tag, for a pane listing. With pane options (3.0), the option: a+ * format resolves it through the window too. Before 3.0, the tag the pane's start command carries,+ * then the window's. tmux 2.x cannot cut a substring out of a format, so the start command comes back+ * cut to the prefix and a tag's length, and `paneOwnerOf` takes the tag out — never the whole command,+ * which can be long and hold the `|` and newlines a listing is split on.+ */+export function paneOwnerFormat(paneOptions: boolean): string {+ if (paneOptions) return `#{${HARNESS_OWNER_OPTION}}`+ const width = OWNER_COMMAND_PREFIX.length + OWNER_TAG_LENGTH+ return `#{?#{m:${OWNER_COMMAND_PREFIX}*,#{pane_start_command}},#{=${width}:pane_start_command},#{${HARNESS_OWNER_OPTION}}}`+}++/** The tag out of a `paneOwnerFormat` field: the field itself, unless it is a start command's prefix. */+export function paneOwnerOf(field: string): string {+ if (!field.startsWith(OWNER_COMMAND_PREFIX)) return field+ return field.slice(OWNER_COMMAND_PREFIX.length).split(' ')[0]+}+/** A path with its symlinks resolved, including one whose last parts do not exist yet: the same answer* before a data folder is created as after (macOS's `/var` is `/private/var`). */function canonicalPath(path: string): string {@@ -46,7 +87,7 @@ function canonicalPath(path: string): string {/** This daemon's tag: its data folder, which no two daemons share, hashed (a path can hold the `|` the* pane listing splits on, and the tag is all a pane needs to carry). */export function harnessPaneOwner(dataDir: string): string {- return createHash('sha256').update(canonicalPath(dataDir)).digest('hex').slice(0, 16)+ return createHash('sha256').update(canonicalPath(dataDir)).digest('hex').slice(0, OWNER_TAG_LENGTH)}/**diff --git a/cli/src/lib/sessionSearch/externals/support.spec.ts b/cli/src/lib/sessionSearch/externals/support.spec.tsindex 9cb2509ad..4b7257080 100644--- a/cli/src/lib/sessionSearch/externals/support.spec.ts+++ b/cli/src/lib/sessionSearch/externals/support.spec.ts@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'nodeimport { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { UNSETTLED } from './types.js'import {@@ -244,9 +244,21 @@ describe('processes', () => {expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: 'no server running on /tmp/tmux-501/default' }))).toEqual(new Set())expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: 'error connecting to /tmp/x (No such file or directory)' }))).toEqual(new Set())expect(await harnessTtys(async () => ({ stdout: '', failed: true, stderr: '' }))).toBeNull()- // The real tmux answers one way or the other.- const real = await harnessTtys()- expect(real === null || real instanceof Set).toBe(true)+ // Before tmux 3.0 the tag rides the pane's start command (`paneOwnerFormat`), asked for as such.+ let asked: readonly string[] = []+ const old = '/dev/ttys006\tmy-claude-work\t/usr/bin/env HARNESS_DAEMON=0123456789abcdef\n/dev/ttys007\tmy-own\t\n'+ expect(await harnessTtys(async (_command, args) => { asked = args; return { stdout: old, failed: false, stderr: '' } }, false))+ .toEqual(new Set(['/dev/ttys006']))+ expect(asked.at(-1)).toContain('#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}}')+ // A real tmux answers one way or the other: a private one with no server, never the developer's own.+ vi.stubEnv('TMUX', undefined)+ vi.stubEnv('TMUX_PANE', undefined)+ vi.stubEnv('TMUX_TMPDIR', home())+ try {+ expect(await harnessTtys()).toEqual(new Set())+ } finally {+ vi.unstubAllEnvs()+ }})it('reads entries through a symlinked folder too', async () => {diff --git a/cli/src/lib/sessionSearch/externals/support.ts b/cli/src/lib/sessionSearch/externals/support.tsindex 4df4ef983..b02bc531e 100644--- a/cli/src/lib/sessionSearch/externals/support.ts+++ b/cli/src/lib/sessionSearch/externals/support.ts@@ -8,8 +8,9 @@ import type { Dirent } from 'node:fs'import { open, readdir, readFile, stat } from 'node:fs/promises'import { isAbsolute, relative, resolve } from 'node:path'-import { HARNESS_OWNER_OPTION, isHarnessSession } from '../../harnessSessionLabel.js'+import { isHarnessSession, paneOwnerFormat } from '../../harnessSessionLabel.js'import { processRows } from '../../tmux.js'+import { tmuxFeatures } from '../../tmuxVersion.js'import { type ProcessView, type RunningProcess, type ScanContext, UNSETTLED } from './types.js'/** A folder's entries, or none when it is missing or unreadable. */@@ -254,8 +255,13 @@ const ask: Ask = (command, args, timeout) => new Promise((resolve) => {* binding it, and a take-over never stops it. None when no tmux server is running; null when tmux could* not be asked (a timeout): then nobody can say.*/-export async function harnessTtys(exec: Ask = ask): Promise<Set<string> | null> {- const { stdout, failed, stderr } = await exec('tmux', ['list-panes', '-a', '-F', `#{pane_tty}\t#{session_name}\t#{${HARNESS_OWNER_OPTION}}`], 3_000)+export async function harnessTtys(+ exec: Ask = ask,+ // Before tmux 3.0 the tag is not a pane option (`paneOwnerFormat`).+ paneOptions?: boolean,+): Promise<Set<string> | null> {+ const format = `#{pane_tty}\t#{session_name}\t${paneOwnerFormat(paneOptions ?? (await tmuxFeatures()).paneOptions)}`+ const { stdout, failed, stderr } = await exec('tmux', ['list-panes', '-a', '-F', format], 3_000)if (failed && !/no server running|error connecting to/i.test(stderr)) return nullconst ttys = new Set<string>()for (const line of stdout.split('\n')) {diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex abf7b7b1b..7a44ca794 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -19,6 +19,7 @@ import { psEnv } from './childLocale.js'import { nativeProcessImages } from './nativeProcessImages.js'import { neutralizePasteControls } from './pasteText.js'import { patientExec } from './patientExec.js'+import { tmuxFeatures, type TmuxFeatures } from './tmuxVersion.js'export { captureTmuxPane, tmuxCaptureArgs } from './tmuxCapture.js'// Every tmux and `ps` call here: a held event loop must not turn a timeout into an empty answer@@ -1143,15 +1144,42 @@ export function setPaneMouseOn(pane: string): Promise<void> {})}+/**+ * Where an option Harness keeps for one of its panes lives: on the pane, where tmux has pane options+ * (3.0), so it goes with the pane into any window the person moves it to and touches nothing else+ * there; on the window before that, which is the agent's own for as long as the person leaves it be.+ * A window option on a pane the person had joined into a window of their own changed their panes too,+ * and a `-p` on tmux 2.x is a usage error that, chained into `new-session`, failed every agent create+ * (PR #789's review). Never `-g`: the daemon shares the person's tmux server.+ */+export function paneOptionScope(features: Pick<TmuxFeatures, 'paneOptions'>): '-p' | '-w' {+ return features.paneOptions ? '-p' : '-w'+}++/**+ * The tmux command that gives one pane [style] (see `hostTheme.ts`), aimed at [pane] or, without one,+ * at the pane a command list just made. The pane's own `window-style` from tmux 3.0; before that+ * `select-pane -P`, the style tmux 2.x kept for each pane. Never the window's: an agent pane the+ * person had moved into a window of their own repainted their shells there in Harness's colours on+ * every scan (PR #789's review, e2e/tmuxmoves.e2e.ts).+ */+export function paneStyleArgs(features: Pick<TmuxFeatures, 'paneOptions'>, style: string, pane?: string): string[] {+ const target = pane ? ['-t', pane] : []+ return features.paneOptions+ ? ['set-option', '-p', ...target, 'window-style', style]+ : ['select-pane', ...target, '-P', style]+}+/*** The colours tmux reports to a program in the pane that asks (`OSC 10;?`/`OSC 11;?`) — see- * `hostTheme.ts` for why a TUI's palette depends on it. Window-scoped, never `-g`: the daemon- * shares the user's default tmux server and must not restyle sessions it did not create.- * Best-effort and idempotent, like [setPaneMouseOn].+ * `hostTheme.ts` for why a TUI's palette depends on it. Pane-scoped (`paneStyleArgs`), never the+ * window's and never `-g`: the daemon shares the user's default tmux server and must not restyle+ * panes it did not create. Best-effort and idempotent, like [setPaneMouseOn].*/-export function setPaneWindowStyle(pane: string, style: string): Promise<boolean> {+export async function setPaneStyle(pane: string, style: string): Promise<boolean> {+ const features = await tmuxFeatures()return new Promise((resolve) => {- run('tmux', ['set-option', '-w', '-t', pane, 'window-style', style], { timeout: 2_000 }, (error) => resolve(!error))+ run('tmux', paneStyleArgs(features, style, pane), { timeout: 2_000 }, (error) => resolve(!error))})}@@ -1259,9 +1287,12 @@ export function tmuxPaneInfo(pane: string, socket?: string): Promise<TmuxPaneInf* Called as soon as a created pane becomes a real agent: from then on it must vanish when its engine* exits, exactly like a pane the user started themselves, rather than lingering as a dead pane.*/-export function clearPaneRemainOnExit(pane: string): Promise<void> {+export async function clearPaneRemainOnExit(pane: string): Promise<void> {+ // The pane's own option where tmux has one (`paneOptionScope`): restarting an agent the person had+ // moved into a window of their own must not switch remain-on-exit off for their panes there.+ const scope = paneOptionScope(await tmuxFeatures())return new Promise((resolve) => {- run('tmux', ['set-option', '-w', '-t', pane, 'remain-on-exit', 'off'], { timeout: 2_000 }, () => resolve())+ run('tmux', ['set-option', scope, '-t', pane, 'remain-on-exit', 'off'], { timeout: 2_000 }, () => resolve())})}diff --git a/cli/src/lib/tmuxAgentDiscovery.ts b/cli/src/lib/tmuxAgentDiscovery.tsindex c3c2c83ff..c7a79c15b 100644--- a/cli/src/lib/tmuxAgentDiscovery.ts+++ b/cli/src/lib/tmuxAgentDiscovery.ts@@ -20,8 +20,9 @@ import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'import { probeCodexHome } from './codexHomeProbe.js'import { env } from '../config/env.js'import {- buildHarnessSessionLabel, HARNESS_OWNER_OPTION, harnessPaneOwner, isLegacyHarnessSession, ownedHere,+ buildHarnessSessionLabel, harnessPaneOwner, isLegacyHarnessSession, ownedHere, paneOwnerFormat, paneOwnerOf,} from './harnessSessionLabel.js'+import { tmuxFeatures } from './tmuxVersion.js'import { psEnv } from './childLocale.js'import type { ProcessIdentity, RegisteredSession } from './registry.js'import {@@ -107,8 +108,14 @@ function execText(}/** What every pane listing asks tmux for. The owner tag goes last: a folder's path can hold `|`, the tag- * never does, so the last `|` is always the one before it. */-export const PANE_FORMAT = `#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}|#{${HARNESS_OWNER_OPTION}}`+ * never does, so the last `|` is always the one before it. How the tag is read depends on the tmux+ * (`paneOwnerFormat`): before 3.0 it is not a pane option. */+export function paneFormat(paneOptions: boolean): string {+ return `#{pane_id}|#{pane_pid}|#{session_name}|#{pane_current_path}|${paneOwnerFormat(paneOptions)}`+}++/** The listing on a tmux with pane options. */+export const PANE_FORMAT = paneFormat(true)export function parsePanes(stdout: string): TmuxPaneSnapshot[] {const panes: TmuxPaneSnapshot[] = []@@ -129,7 +136,7 @@ export function parsePanes(stdout: string): TmuxPaneSnapshot[] {rootPid,tmuxSessionName: line.slice(second + 1, third),cwd: tag < 0 ? rest : rest.slice(0, tag),- owner: tag < 0 ? '' : rest.slice(tag + 1),+ owner: tag < 0 ? '' : paneOwnerOf(rest.slice(tag + 1)),})}return panes@@ -151,7 +158,8 @@ export type TmuxPaneInventory =*/export async function listTmuxPanes(owner: string = harnessPaneOwner(env.ADAPTER_DATA_DIR)): Promise<TmuxPaneInventory> {// Printable delimiters survive tmux's POSIX-locale output sanitiser (see PANE_FORMAT).- const read = () => execText('tmux', ['list-panes', '-a', '-F', PANE_FORMAT], 2_000)+ const format = paneFormat((await tmuxFeatures()).paneOptions)+ const read = () => execText('tmux', ['list-panes', '-a', '-F', format], 2_000)let result = await read()// A server whose socket was removed still runs its panes: asked back, it is read again, once.if (!result.ok && isNoTmuxServerError(result.error) && await reviveRemovedTmuxSocket()) result = await read()diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.tsindex e88f5eb43..04960dd8a 100644--- a/cli/src/lib/tmuxBackend.spec.ts+++ b/cli/src/lib/tmuxBackend.spec.ts@@ -1,13 +1,19 @@import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { delimiter, join } from 'node:path'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { TmuxBackend, clearEnvArgs } from './tmuxBackend.js'+import { clearPaneRemainOnExit } from './tmux.js'+import { assumeTmuxVersion, resetTmuxVersionCache } from './tmuxVersion.js'const originalPath = process.env.PATHconst dirs: string[] = []+// A tmux that answers `-V` with no number reads as the newest; the specs that need an older one say so.+beforeEach(() => assumeTmuxVersion(null))+afterEach(() => {+ resetTmuxVersionCache()process.env.PATH = originalPathdelete process.env.TMUX_BACKEND_CALLSfor (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })@@ -55,7 +61,9 @@ esac// `window-style` rides the same invocation for the same reason: the engine asks its// terminal for its colours (OSC 10/11) once, at startup, and never again. And so does the// daemon's tag: another daemon on this tmux server must never see the pane untagged.- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',+ // All three on the pane itself, where tmux has pane options: they go with it wherever the person+ // moves it, and never touch the rest of a window of theirs.+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -p remain-on-exit on ; set-option destroy-unattached off ; set-option -p window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a','set-option -t %42 mouse on','kill-pane -t %42',])@@ -157,12 +165,13 @@ esacawait backend.inventory()const styleCalls = () => readFileSync(calls, 'utf8').trim().split('\n').filter((line) => line.includes('window-style'))await vi.waitFor(() => expect(styleCalls()).toEqual([- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -w remain-on-exit on ; set-option destroy-unattached off ; set-option -w window-style bg=#171b29,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',- // The pane this daemon did not create is styled on the first scan; %7 already was.- 'set-option -w -t %9 window-style bg=#171b29,fg=#f5f5f5',+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -p remain-on-exit on ; set-option destroy-unattached off ; set-option -p window-style bg=#171b29,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',+ // The pane this daemon did not create is styled on the first scan; %7 already was. Each pane on+ // its own, never its window: the person may have moved it into one of theirs.+ 'set-option -p -t %9 window-style bg=#171b29,fg=#f5f5f5',// The app changed its palette: every live pane, once.- 'set-option -w -t %7 window-style bg=#300a24,fg=#ffffff',- 'set-option -w -t %9 window-style bg=#300a24,fg=#ffffff',+ 'set-option -p -t %7 window-style bg=#300a24,fg=#ffffff',+ 'set-option -p -t %9 window-style bg=#300a24,fg=#ffffff',]))await backend.inventory()await new Promise((resolve) => setTimeout(resolve, 80))@@ -216,7 +225,7 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"await expect(new TmuxBackend().holdOpen({ backend: 'tmux', paneId: '%9' })).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })- expect(readFileSync(calls, 'utf8').trim()).toBe('set-option -w -t %9 remain-on-exit on')+ expect(readFileSync(calls, 'utf8').trim()).toBe('set-option -p -t %9 remain-on-exit on')})it('inventory only exposes panes whose session was named by agent_create (autonomous-harness-desktop#6)', async () => {@@ -311,8 +320,8 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS".resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([// The `;` inside an argv element is never shell-interpreted — it lands as one literal token.- 'set-option -w -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -c /tmp/work -t %9 claude --resume abc; rm -rf /',- 'set-option -w -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -t %9 claude',+ 'set-option -p -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -c /tmp/work -t %9 claude --resume abc; rm -rf /',+ 'set-option -p -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -t %9 claude',])})@@ -365,8 +374,8 @@ printf '%%42\\n'expect(readFileSync(calls, 'utf8').trim().split('\n')[0]).toBe('new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'+ ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_AUTH_TOKEN=gridkey-abc123'- + ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on'- + ' ; set-option destroy-unattached off ; set-option -w window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',+ + ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -p remain-on-exit on'+ + ' ; set-option destroy-unattached off ; set-option -p window-style bg=#181818,fg=#f5f5f5 ; set-option -p @harness_daemon daemon-a',)})it('respawns a pane in place with a new environment, keeping the pane id', async () => {@@ -391,7 +400,7 @@ printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"// `remain-on-exit` is chained BEFORE the respawn, not after: an engine handed a rejected key can// exit before a follow-up call lands, taking its own error message down with it.expect(readFileSync(calls, 'utf8').trim()).toBe(- 'set-option -w -t %42 remain-on-exit on ; set-option -p -t %42 @harness_engine_exit ; respawn-pane -k -c /tmp/work'+ 'set-option -p -t %42 remain-on-exit on ; set-option -p -t %42 @harness_engine_exit ; respawn-pane -k -c /tmp/work'+ ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_MODEL=GLM-4.7-Flash'+ ' -t %42 /bin/zsh -lic exec "$@" harness-engine claude --resume sess-1',)@@ -415,6 +424,132 @@ exit 1})})+/** A fake tmux on PATH that records every call, prints [listing] for `list-panes` and `%42` otherwise. */+function recordingTmux(listing = ''): () => string[] {+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-old-'))+ dirs.push(dir)+ const calls = join(dir, 'calls')+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"+case "$1" in+ list-panes) printf '${listing.replace(/%/g, '%%')}' ;;+ *) printf '%%42\\n' ;;+esac+`, { mode: 0o700 })+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ process.env.TMUX_BACKEND_CALLS = calls+ return () => { try { return readFileSync(calls, 'utf8').trim().split('\n') } catch { return [] } }+}++// Debian 10 ships tmux 2.8 and RHEL 8 ships 2.7: no pane options, and tmux checks a whole `;` list before+// it runs any of it. One `set-option -p` chained into `new-session` failed every agent create there.+describe('TmuxBackend on a tmux before 3.0', () => {+ beforeEach(() => assumeTmuxVersion({ major: 2, minor: 8 }))+ const command = ['/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', 'claude']++ it('creates the session with nothing in the list that tmux cannot run, the tag on the window and in the start command', async () => {+ const calls = recordingTmux()+ const created = await new TmuxBackend(undefined, () => 'daemon-a').create({ cwd: '/tmp/work', label: 'harness-test', command })+ expect(created).toEqual({ state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId: '%42' } })+ expect(calls()[0]).toBe(+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'+ // The start command goes with the pane wherever the person moves it, where a window option stays.+ + ' /usr/bin/env HARNESS_DAEMON=daemon-a /bin/zsh -lic exec "$@" harness-engine claude'+ + ' ; set-option -w remain-on-exit on ; set-option destroy-unattached off'+ // tmux 2.x keeps a style for each pane: `select-pane -P`, aimed at the pane just made.+ + ' ; select-pane -P bg=#181818,fg=#f5f5f5 ; set-option -w @harness_daemon daemon-a',+ )+ expect(calls()[0]).not.toContain(' -p ')+ })++ it('starts tmux\'s default shell as it is: env with nothing to run would print and exit', async () => {+ const calls = recordingTmux()+ await new TmuxBackend(undefined, () => 'daemon-a').create({ label: 'harness-test' })+ expect(calls()[0]).toMatch(/^new-session -d -P -F #\{pane_id\} -s harness-test ; set-option -w remain-on-exit on/)+ })++ it('respawns with the tag kept in the new start command and the exit mark on the window', async () => {+ const calls = recordingTmux()+ await expect(new TmuxBackend(undefined, () => 'daemon-a').respawn({ backend: 'tmux', paneId: '%9' }, { command: ['claude'] }))+ .resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })+ expect(calls()).toEqual([+ 'set-option -w -t %9 remain-on-exit on ; set-option -w -t %9 @harness_engine_exit ; respawn-pane -k -t %9 /usr/bin/env HARNESS_DAEMON=daemon-a claude',+ ])+ })++ it('re-arms remain-on-exit on the window, the only place it can go', async () => {+ const calls = recordingTmux()+ await new TmuxBackend().holdOpen({ backend: 'tmux', paneId: '%9' })+ expect(calls()).toEqual(['set-option -w -t %9 remain-on-exit on'])+ })++ it('styles each pane with select-pane -P, never its window', async () => {+ const calls = recordingTmux('%9|100|harness-claude-1|/work|daemon-a\\n')+ await new TmuxBackend(undefined, () => 'daemon-a').inventory()+ await vi.waitFor(() => expect(calls()).toContain('select-pane -t %9 -P bg=#181818,fg=#f5f5f5'))+ expect(calls().join('\n')).not.toContain('window-style')+ })++ it('finds its panes by the start command wherever they moved, by the window\'s tag otherwise, never another daemon\'s', async () => {+ const calls = recordingTmux(+ '%1|100|mine-claude|/work/moved|/usr/bin/env HARNESS_DAEMON=daemon-a\\n'+ + '%2|101|harness-codex-2|/work/theirs|/usr/bin/env HARNESS_DAEMON=daemon-b\\n'+ + '%3|102|harness-claude-3|/work/respawned|daemon-a\\n'+ + '%4|103|my-shell|/work/shell|\\n',+ )+ const inventory = await new TmuxBackend(undefined, () => 'daemon-a').inventory()+ expect(inventory.state === 'available' && inventory.roots.map((root) => root.runtime.paneId)).toEqual(['%1', '%3'])+ expect(calls()[0]).toContain('#{?#{m:/usr/bin/env HARNESS_DAEMON=*,#{pane_start_command}},#{=44:pane_start_command},#{@harness_daemon}}')+ })+})++describe('handing a pane back to tmux\'s disposal', () => {+ // A window option on an agent the person had moved into a window of their own switched+ // remain-on-exit off for their panes there too.+ it('switches remain-on-exit off on the pane alone where tmux has pane options', async () => {+ assumeTmuxVersion({ major: 3, minor: 0 })+ const calls = recordingTmux()+ await clearPaneRemainOnExit('%9')+ expect(calls()).toEqual(['set-option -p -t %9 remain-on-exit off'])+ })++ it('switches it off on the window before tmux 3.0, the only place it can go', async () => {+ assumeTmuxVersion({ major: 2, minor: 8 })+ const calls = recordingTmux()+ await clearPaneRemainOnExit('%9')+ expect(calls()).toEqual(['set-option -w -t %9 remain-on-exit off'])+ })+})++describe('TmuxBackend with variables on a tmux that cannot take them', () => {+ const env = { CODEX_HOME: '/work/profile' }++ it('refuses a create below 3.2, saying why, and asks tmux nothing', async () => {+ assumeTmuxVersion({ major: 3, minor: 1 })+ const calls = recordingTmux()+ const created = await new TmuxBackend().create({ label: 'harness-test', env, command: ['codex'] })+ expect(created).toMatchObject({ state: 'failed', dispatch: 'not_started' })+ expect(created.state !== 'succeeded' && created.reason).toContain('older than 3.2')+ expect(calls()).toEqual([])+ })++ it('refuses a respawn below 3.0, saying why, and asks tmux nothing', async () => {+ assumeTmuxVersion({ major: 2, minor: 9 })+ const calls = recordingTmux()+ const moved = await new TmuxBackend().respawn({ backend: 'tmux', paneId: '%9' }, { env, command: ['codex'] })+ expect(moved).toMatchObject({ state: 'failed', dispatch: 'not_started' })+ expect(moved.state !== 'succeeded' && moved.reason).toContain('older than 3.0')+ expect(calls()).toEqual([])+ })++ it('respawns with them from 3.0, where respawn-pane takes -e', async () => {+ assumeTmuxVersion({ major: 3, minor: 0 })+ const calls = recordingTmux()+ await new TmuxBackend(undefined, () => 'daemon-a').respawn({ backend: 'tmux', paneId: '%9' }, { env, command: ['codex'] })+ expect(calls()).toEqual(['set-option -p -t %9 remain-on-exit on ; set-option -p -t %9 @harness_engine_exit ; respawn-pane -k -e CODEX_HOME=/work/profile -t %9 codex'])+ })+})+// The command line is the whole contract here: `set-environment -u` REMOVES a variable, while the// `-e VAR=` form a respawn takes would set it to an empty string. An engine handed// ANTHROPIC_BASE_URL="" does not fall back to its own login; it tries to dial the empty string.diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex 669ac5efa..4bb7496d1 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -29,12 +29,15 @@ import {lookupPaneEngineProcess,sendKeyToTmux,sendLiteralToTmux,+ paneOptionScope,+ paneStyleArgs,sendToTmux,setPaneMouseOn,- setPaneWindowStyle,+ setPaneStyle,} from './tmux.js'import { env } from '../config/env.js'-import { HARNESS_OWNER_OPTION, harnessPaneOwner } from './harnessSessionLabel.js'+import { HARNESS_OWNER_OPTION, harnessPaneOwner, ownerCommand } from './harnessSessionLabel.js'+import { tmuxFeatures, type TmuxFeatures } from './tmuxVersion.js'import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'import { machineNames } from './machineNames.js'import { isNoTmuxServerError, listTmuxPanes } from './tmuxAgentDiscovery.js'@@ -76,6 +79,11 @@ const TMUX_KEYS: Record<TerminalLogicalKey, string> = {'9': '9',}+/** Why a launch with its own environment was refused on this tmux, in words a person can act on. */+function tmuxTooOldForEnv(version: string, what: string): string {+ return `this machine's tmux is older than ${version}, the first version that can give ${what} its own environment. Upgrade tmux.`+}+function legacyActionResult(ok: boolean, operation: string): TerminalActionResult {// The legacy helper has spawned tmux before it reports false, so execution cannot safely be ruled out.return ok ? TERMINAL_ACTION_SUCCEEDED : terminalActionPossiblyExecuted(`${operation} did not complete`)@@ -117,6 +125,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {private readonly hostTheme: () => HostTheme = () => DEFAULT_HOST_THEME,private readonly owner: () => string = () => harnessPaneOwner(env.ADAPTER_DATA_DIR),private readonly observeMachineName: () => void = () => machineNames.observe(),+ /** What this machine's tmux can do (`tmuxVersion.ts`): a command an older tmux does not know fails+ * the whole command list it is chained into, and every agent create with it. */+ private readonly features: () => Promise<TmuxFeatures> = tmuxFeatures,) {}async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<TmuxRuntimeRef>> {@@ -124,23 +135,32 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// that sets no title keeps it. Read here, that name is refused even if the machine has another// by the next title sweep: a name it had only between two sweeps would otherwise never be seen.this.observeMachineName()+ const features = await this.features()+ const variables = Object.entries(request.env ?? {})+ // `-e` (tmux 3.2+) puts these in the SESSION environment rather than the launch argv, so a grid+ // relay key never lands in `ps` output for the life of the agent. Callers refuse a grid or a+ // harness on an older tmux by name (`tmuxSupportsSessionEnv()`); whatever else reaches here with+ // variables on one is refused here, saying why, rather than handed to tmux to answer with its+ // usage text — and never moved into the argv, where a secret would show.+ if (variables.length && !features.sessionEnv) return terminalActionNotStarted(tmuxTooOldForEnv('3.2', 'a new session'))+ const owner = this.owner()const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']if (request.cwd) args.push('-c', request.cwd)if (request.label) args.push('-s', request.label)- // `-e` (tmux 3.2+) puts these in the SESSION environment rather than the launch argv, so a grid- // relay key never lands in `ps` output for the life of the agent. Callers gate on- // `tmuxSupportsSessionEnv()`; an older tmux answers the flag with its usage text.- for (const [key, value] of Object.entries(request.env ?? {})) args.push('-e', `${key}=${value}`)+ for (const [key, value] of variables) args.push('-e', `${key}=${value}`)// Trailing args after this point become the session's shell-command. tmux execs them directly// (no shell interposed) when given as separate argv elements, so no quoting/escaping is needed.- if (request.command?.length) args.push(...request.command)+ if (request.command?.length) args.push(...this.ownedCommand(features, owner, request.command))+ // Pane options where tmux has them, so these go with the pane wherever the person moves it and never+ // change the rest of a window of theirs; the agent's own new window before tmux 3.0.+ const scope = paneOptionScope(features)// Keep the pane when its process dies, so an engine that exits immediately (not logged in, bad// config) still has its error text readable afterwards instead of taking the whole session down// with it. Chained into THIS tmux invocation on purpose: an engine can exit in under a// millisecond, and a second `set-option` call loses that race — measured, the session was// already gone before the follow-up command could reach the server.// Whoever created the pane owns turning this back off; see `clearPaneRemainOnExit`.- args.push(';', 'set-option', '-w', 'remain-on-exit', 'on')+ args.push(';', 'set-option', scope, 'remain-on-exit', 'on')// An agent's session never has a client attached, so a person's `set -g destroy-unattached on`// (in their ~/.tmux.conf, which this server loads) ended every agent the moment it was made, and// Harness could not run at all on their machine (found end to end, e2e/tmuxconf.e2e.ts). Turned@@ -149,11 +169,11 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {// Same invocation, same reason: an engine asks its terminal for its colours (OSC 10/11) in its// first milliseconds and never again, so the style has to be there before the engine is.const style = windowStyleOf(this.hostTheme())- args.push(';', 'set-option', '-w', 'window-style', style)+ args.push(';', ...paneStyleArgs(features, style))// Whose pane it is, from its first instant: another daemon on this tmux server scanning a moment// later must already see it is not its own. On the pane, which keeps it wherever the person moves- // it (see HARNESS_OWNER_OPTION).- args.push(';', 'set-option', '-p', HARNESS_OWNER_OPTION, this.owner())+ // it (see HARNESS_OWNER_OPTION); before tmux 3.0, on the window, and in the start command.+ args.push(';', 'set-option', scope, HARNESS_OWNER_OPTION, owner)// `killed`/`signal` come from execFile's own error shape, which ErrnoException alone does not declare.type ExecError = NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null }const result = await new Promise<{ error: ExecError | null; stdout: string; stderr: string }>((resolve) => {@@ -184,6 +204,16 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } }}+ /**+ * [command] as this daemon starts it. Before tmux 3.0, through `ownerCommand`, so the pane's start+ * command carries the tag that a window option cannot keep once the person moves the pane. An empty+ * command is tmux's default shell, and stays that: `/usr/bin/env` with nothing to run would print the+ * environment and exit.+ */+ private ownedCommand(features: TmuxFeatures, owner: string, command: readonly string[] = []): string[] {+ return features.paneOptions || !command.length ? [...command] : ownerCommand(owner, command)+ }+/*** Replace the process running in an existing pane, with a different environment.*@@ -193,16 +223,23 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {* instead of taking the pane down with it. Whoever calls this owns turning it back off.*/async respawn(runtime: TmuxRuntimeRef, request: TerminalRespawnRequest): Promise<TerminalActionResult> {+ const features = await this.features()+ const variables = Object.entries(request.env ?? {})+ // `respawn-pane -e` is tmux 3.0; refused before, for the reason `create` gives.+ if (variables.length && !features.respawnEnv) return terminalActionNotStarted(tmuxTooOldForEnv('3.0', 'a respawned pane'))+ const scope = paneOptionScope(features)// The engine-exit marker is the pane's, and a respawned pane is a new launch: cleared here, in- // the same invocation, or the new engine would read as exited the moment it started.+ // the same invocation, or the new engine would read as exited the moment it started. A `-p` here+ // before tmux 3.0 failed the whole list, the respawn with it, so no agent could restart there.const args = [- 'set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on', ';',- 'set-option', '-p', '-t', runtime.paneId, ENGINE_EXIT_PANE_OPTION, '', ';',+ 'set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on', ';',+ 'set-option', scope, '-t', runtime.paneId, ENGINE_EXIT_PANE_OPTION, '', ';','respawn-pane', '-k',]if (request.cwd) args.push('-c', request.cwd)- for (const [key, value] of Object.entries(request.env ?? {})) args.push('-e', `${key}=${value}`)- args.push('-t', runtime.paneId, ...request.command)+ for (const [key, value] of variables) args.push('-e', `${key}=${value}`)+ // A respawn replaces the pane's start command, which carries its tag before tmux 3.0 (`create`).+ args.push('-t', runtime.paneId, ...this.ownedCommand(features, this.owner(), request.command))const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {run('tmux', args, { timeout: 5_000 }, (error, _stdout, stderr) => resolve({error: error as NodeJS.ErrnoException | null,@@ -277,8 +314,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {* instant the old process exits.*/async holdOpen(runtime: TmuxRuntimeRef): Promise<TerminalActionResult> {+ const scope = paneOptionScope(await this.features())const ok = await new Promise<boolean>((resolve) => {- run('tmux', ['set-option', '-w', '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {+ run('tmux', ['set-option', scope, '-t', runtime.paneId, 'remain-on-exit', 'on'], { timeout: 2_000 }, (error) => {resolve(!error)})})@@ -311,7 +349,8 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {* Retroactive, on every scan: a pane from before this build, one that outlived a daemon restart,* or every pane after the app changed its palette. Fire-and-forget — a scan that misses one* because tmux was briefly slow catches it on the next pass. Panes that are gone are forgotten- * so a reused pane id is styled afresh.+ * so a reused pane id is styled afresh. Each pane on its own (`setPaneStyle`), never its window:+ * the person may have moved it into a window of theirs.*/private restyle(panes: readonly string[]): void {const style = windowStyleOf(this.hostTheme())@@ -333,7 +372,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {if (style === undefined || this.stylingPanes.has(pane) || this.styledPanes.get(pane) === style) return// Serialize writes per pane: scans can overlap a slow tmux command or a theme change.this.stylingPanes.add(pane)- void setPaneWindowStyle(pane, style).then((applied) => {+ void setPaneStyle(pane, style).then((applied) => {if (applied && this.desiredStyles.has(pane)) this.styledPanes.set(pane, style)}).finally(() => {this.stylingPanes.delete(pane)diff --git a/cli/src/lib/tmuxStream.oldTmux.spec.ts b/cli/src/lib/tmuxStream.oldTmux.spec.tsnew file mode 100644index 000000000..b0e98b56e--- /dev/null+++ b/cli/src/lib/tmuxStream.oldTmux.spec.ts@@ -0,0 +1,134 @@+/**+ * The terminal on the tmux a distribution ships. Debian 10 ships 2.8, Ubuntu 20.04 3.0a, Debian 11 3.1c:+ * before 3.2 the control client's `-f ignore-size` was a usage error and no terminal opened at all;+ * before 3.1 `capture-pane -N` failed every snapshot; before 3.0 `send-keys -H` failed every keystroke;+ * before 2.9 there was no `resize-window`. Each is asked of the tmux by name (`tmuxVersion.ts`), and+ * the same stream is proven against real tmux 2.8 and 3.0a in tmuxStream.real.spec.ts.+ */+import { EventEmitter } from 'node:events'+import { PassThrough, Writable } from 'node:stream'+import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { TmuxControlStream } from './tmuxStream.js'+import { assumeTmuxVersion, resetTmuxVersionCache, type TmuxVersion } from './tmuxVersion.js'++vi.mock('node:child_process', async (importOriginal) => ({+ ...await importOriginal<typeof import('node:child_process')>(),+ execFile: vi.fn(),+ spawn: vi.fn(),+}))++afterEach(() => {+ vi.resetAllMocks()+ resetTmuxVersionCache()+})++/** A control client that answers every command, `display-message` with [meta], and records what it was sent. */+function controlClient(version: TmuxVersion, meta = '$1|@1|1|80|24|80|24|0|0|0|1|0|0|0|0|0') {+ assumeTmuxVersion(version)+ const sent: string[] = []+ const child = new EventEmitter() as {+ -readonly [K in keyof ChildProcessWithoutNullStreams]: ChildProcessWithoutNullStreams[K]+ }+ child.stdout = new PassThrough()+ child.stderr = new PassThrough()+ child.exitCode = null+ child.signalCode = null+ let command = 1+ child.kill = () => { child.exitCode = 0; child.emit('close', 0); return true }+ child.stdin = new Writable({+ write(chunk, _encoding, callback) {+ const line = chunk.toString().replace(/\n$/, '')+ sent.push(line)+ const number = command+++ setImmediate(() => {+ callback()+ if (line.startsWith('detach-client')) { child.kill(); return }+ const body = line.startsWith('display-message') ? `${meta}\n` : ''+ child.stdout.emit('data', Buffer.from(`%begin 1 ${number} 0\n${body}%end 1 ${number} 0\n`))+ })+ },+ })+ vi.mocked(execFile).mockImplementation(((...args: unknown[]) => {+ (args.at(-1) as (error: null, stdout: Buffer) => void)(null, Buffer.from(`${meta}\n`))+ return child+ }) as typeof execFile)+ vi.mocked(spawn).mockImplementation(() => {+ setImmediate(() => {+ child.emit('spawn')+ setImmediate(() => child.stdout.emit('data', Buffer.from('%begin 1 0 0\n%end 1 0 0\n')))+ })+ return child+ })+ return { sent }+}++async function open(size = { cols: 80, rows: 24 }) {+ const opened = await TmuxControlStream.open('%1', size, { onData: () => {}, onClose: () => {} })+ expect(opened.state).toBe('succeeded')+ if (opened.state !== 'succeeded') throw new Error('stream did not open')+ return opened.value+}++describe('the terminal on an older tmux', () => {+ it.each([+ [{ major: 3, minor: 2 }, ['-C', 'attach-session', '-f', 'ignore-size', '-t', '%1']],+ // Before client flags the control client never sets a size of its own, and counts for none.+ [{ major: 3, minor: 1 }, ['-C', 'attach-session', '-t', '%1']],+ [{ major: 2, minor: 8 }, ['-C', 'attach-session', '-t', '%1']],+ ])('attaches its control client as tmux %o takes it', async (version, argv) => {+ controlClient(version)+ const stream = await open()+ expect(vi.mocked(spawn).mock.calls[0]?.[1]).toEqual(argv)+ await stream.close()+ })++ it('types through send-keys -H from 3.0, and as literal text and keys before it', async () => {+ const modern = controlClient({ major: 3, minor: 0 })+ let stream = await open()+ expect((await stream.writeRaw(Buffer.from("ls;\n"))).state).toBe('succeeded')+ expect(modern.sent.slice(-1)).toEqual(['send-keys -t %1 -H 6c 73 3b 0a'])+ await stream.close()++ vi.resetAllMocks()+ const old = controlClient({ major: 2, minor: 8 })+ stream = await open()+ expect((await stream.writeRaw(Buffer.from("echo 'hi';\n-x"))).state).toBe('succeeded')+ expect(old.sent.slice(-3)).toEqual([+ `send-keys -t %1 -l -- 'echo '"'"'hi'"'"'\\;'`,+ 'send-keys -t %1 C-j',+ `send-keys -t %1 -l -- '-x'`,+ ])+ await stream.close()+ })++ it('sizes its window with resize-window from 2.9, and as a control client before it, never under 2x2', async () => {+ const modern = controlClient({ major: 2, minor: 9 })+ let stream = await open({ cols: 100, rows: 30 })+ expect(modern.sent).toContain('resize-window -t @1 -x 100 -y 30')+ await stream.close()++ vi.resetAllMocks()+ const old = controlClient({ major: 2, minor: 8 })+ stream = await open({ cols: 100, rows: 30 })+ expect((await stream.resize({ cols: 1, rows: 1 })).state).toBe('succeeded')+ expect(old.sent.filter((line) => /resize|refresh/.test(line))).toEqual(['refresh-client -C 100,30', 'refresh-client -C 2,2'])+ await stream.close()+ })++ it('keeps a row\'s trailing blanks from 3.1, and captures without asking for them before it', async () => {+ for (const [version, flag] of [[{ major: 3, minor: 1 }, ' -N'], [{ major: 3, minor: 0 }, '']] as const) {+ vi.resetAllMocks()+ const client = controlClient(version)+ const stream = await open()+ stream.beginSnapshot()+ expect((await stream.snapshot()).state).toBe('succeeded')+ stream.endSnapshot()+ expect(client.sent.filter((line) => line.startsWith('capture-pane'))).toEqual([+ `capture-pane -p -e${flag} -t %1 -S -500 -E -1`,+ `capture-pane -p -e${flag} -t %1`,+ ])+ await stream.close()+ }+ })+})diff --git a/cli/src/lib/tmuxStream.real.spec.ts b/cli/src/lib/tmuxStream.real.spec.tsindex c7002d9c9..a6d338bd1 100644--- a/cli/src/lib/tmuxStream.real.spec.ts+++ b/cli/src/lib/tmuxStream.real.spec.ts@@ -9,6 +9,7 @@ import type { RegisteredSession } from './registry.js'import { TerminalStreamManager } from './terminalStreamManager.js'import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'import { TmuxControlStream } from './tmuxStream.js'+import { tmuxFeatures } from './tmuxVersion.js'import { TerminalBinaryKind, type TerminalBinaryClear } from './terminalBinary.js'const run = process.env.RUN_REAL_TMUX_STREAM === '1' ? describe : describe.skip@@ -20,8 +21,11 @@ function tmux(args: string[]): Promise<string> {}async function eventually(predicate: () => boolean | Promise<boolean>, timeoutMs = 3_000): Promise<void> {+ // A predicate that throws has not come true yet: a file the pane's process is about to create reads+ // ENOENT for the ~200 ms an older tmux takes to start it.+ const settled = async () => { try { return await predicate() } catch { return false } }const deadline = Date.now() + timeoutMs- while (!await predicate() && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20))+ while (!await settled() && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20))expect(await predicate()).toBe(true)}@@ -115,8 +119,11 @@ run('TmuxControlStream real tmux', () => {try {if (opened.state !== 'succeeded') returnexpect(await tmux(['display-message', '-p', '-t', paneId, '#{pane_width}x#{pane_height}'])).toBe('30x8')- for (const size of [{ cols: 1, rows: 1 }, { cols: 39, rows: 11 }, { cols: 120, rows: 40 }]) {- expect((await opened.value.resize(size)).state).toBe('succeeded')+ // Before tmux 2.9 a control client sizes the window, and tmux takes no client under 2x2.+ const least = (await tmuxFeatures()).resizeWindow ? 1 : 2+ for (const asked of [{ cols: 1, rows: 1 }, { cols: 39, rows: 11 }, { cols: 120, rows: 40 }]) {+ const size = { cols: Math.max(least, asked.cols), rows: Math.max(least, asked.rows) }+ expect((await opened.value.resize(asked)).state).toBe('succeeded')expect(await tmux(['display-message', '-p', '-t', paneId, '#{pane_width}x#{pane_height}'])).toBe(`${size.cols}x${size.rows}`)opened.value.beginSnapshot()const snapshot = await opened.value.snapshot()@@ -153,6 +160,37 @@ run('TmuxControlStream real tmux', () => {}})+ it('types every byte exactly as given: quotes, a trailing semicolon, a leading dash, control bytes, UTF-8', async () => {+ // tmux before 3.0 has no `send-keys -H`: there the bytes go as quoted literal text and keys, and this+ // is the case that would show a byte its command parser took for syntax (`literalKeyCommands`).+ const directory = await mkdtemp(join(tmpdir(), 'harness-typed-'))+ const sink = join(directory, 'typed.bin')+ const typed = Buffer.concat([+ Buffer.from("-l 'single' \"double\" $HOME #not-a-comment ~ a;b \\; \t\r\u001b[A\u007f 世界🚀 "),+ Buffer.from([0x0a, 0x00, 0x01, 0x1f]),+ Buffer.from('x'.repeat(5_000) + "';"),+ ])+ const typedSession = `harness-typed-${randomUUID().slice(0, 8)}`+ // A raw tty: every byte reaches `head` as it was written, none taken for a signal or a line edit.+ const typedPane = await tmux([+ 'new-session', '-d', '-P', '-F', '#{pane_id}', '-s', typedSession,+ 'bash', '--noprofile', '--norc', '-c', `stty raw -echo; head -c ${typed.length} > ${sink}`,+ ])+ try {+ const opened = await TmuxControlStream.open(typedPane, { cols: 120, rows: 30 }, { onData: () => {}, onClose: () => {} })+ expect(opened.state).toBe('succeeded')+ if (opened.state !== 'succeeded') return+ // The pane's `stty raw` must land before the first byte, or the tty would still edit lines.+ await new Promise((resolve) => setTimeout(resolve, 500))+ expect((await opened.value.writeRaw(typed)).state).toBe('succeeded')+ await eventually(async () => (await readFile(sink)).length === typed.length, 5_000)+ expect((await readFile(sink)).equals(typed)).toBe(true)+ await opened.value.close()+ } finally {+ await tmux(['kill-session', '-t', typedSession]).catch(() => { /* best effort */ })+ }+ })+it('delivers a multi-chunk paste to the pane whole and in order', async () => {// 8 KiB in one writeRaw spans several `send-keys -H` commands (INPUT_CHUNK_BYTES is 2 KiB).// They are pipelined into the control client, so this is the case that would expose either adiff --git a/cli/src/lib/tmuxStream.spec.ts b/cli/src/lib/tmuxStream.spec.tsindex 7a26b02c8..782b4a42b 100644--- a/cli/src/lib/tmuxStream.spec.ts+++ b/cli/src/lib/tmuxStream.spec.ts@@ -2,9 +2,11 @@ import { describe, expect, it, vi } from 'vitest'import {ControlCommandQueue,decodeTmuxControlData,+ literalKeyCommands,normalizeTmuxHistoryLines,normalizeTmuxCaptureLines,parseTmuxControlOutput,+ quoteForOldTmux,synthesizeTmuxSnapshot,tuiScrollPageCount,} from './tmuxStream.js'@@ -19,6 +21,51 @@ describe('tuiScrollPageCount', () => {})})+// 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')diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.tsindex c8e738119..ba4257f24 100644--- a/cli/src/lib/tmuxStream.ts+++ b/cli/src/lib/tmuxStream.ts@@ -1,6 +1,7 @@import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'import { patientDeadline } from './patientExec.js'import { pasteRawIntoTmux } from './tmux.js'+import { tmuxFeatures, tmuxFeaturesOf, type TmuxFeatures } from './tmuxVersion.js'import {TERMINAL_ACTION_SUCCEEDED,terminalActionNotStarted,@@ -37,6 +38,57 @@ export function tuiScrollPageCount(lines: number): number {if (!Number.isFinite(lines) || lines <= 0) return 0return 1}++/** Keystrokes as hex bytes (`send-keys -H`, tmux 3.0), [chunk] bytes to a command. */+function hexKeyCommands(paneId: string, bytes: Uint8Array, chunk = INPUT_CHUNK_BYTES): string[] {+ const commands: string[] = []+ for (let offset = 0; offset < bytes.length; offset += chunk) {+ const hex = [...bytes.subarray(offset, offset + chunk)].map((byte) => byte.toString(16).padStart(2, '0')).join(' ')+ commands.push(`send-keys -t ${paneId} -H ${hex}`)+ }+ return commands+}++/**+ * One argument for the command parser of tmux before 3.0 (`cmd-string.c`), holding [text] exactly.+ * Single quotes take every byte as it is but their own; a `'` goes in double quotes, which hold it+ * as it is too. An argument that ends in `;` would end the command there instead, unless it ends in+ * `\;`, which the parser gives back as `;` (`cmd_list_parse`).+ */+export function quoteForOldTmux(text: string): string {+ const quoted = text.split("'").map((part) => `'${part}'`).join(`"'"`)+ return text.endsWith(';') ? `${quoted.slice(0, -2)}\\;'` : quoted+}++/**+ * Keystrokes for a tmux before 3.0, which has no `send-keys -H`: the bytes as literal text,+ * `send-keys -l`, which tmux writes to the pane byte for byte. Two bytes cannot ride a control-mode+ * command line, and go as the keys that write them: LF ends the line (`C-j`), NUL ends the string+ * (`C-@`). Runs are cut at [chunk] bytes and never inside a UTF-8 sequence: tmux reads each argument as+ * UTF-8, and half a character would be written as two wrong ones. `--` before the text, or text that+ * starts with `-` would be read as a flag. One command per line: tmux answers each with its own+ * `%begin`/`%end`, which is what `ControlCommandQueue` counts.+ */+export function literalKeyCommands(paneId: string, bytes: Uint8Array, chunk = INPUT_CHUNK_BYTES): string[] {+ const commands: string[] = []+ const literal = (from: number, to: number): void => {+ for (let at = from; at < to;) {+ let cut = Math.min(to, at + chunk)+ while (cut < to && cut > at + 1 && (bytes[cut] & 0xc0) === 0x80) cut--+ commands.push(`send-keys -t ${paneId} -l -- ${quoteForOldTmux(Buffer.from(bytes.subarray(at, cut)).toString('utf8'))}`)+ at = cut+ }+ }+ let start = 0+ for (let index = 0; index < bytes.length; index++) {+ if (bytes[index] !== 0x0a && bytes[index] !== 0x00) continue+ literal(start, index)+ commands.push(`send-keys -t ${paneId} ${bytes[index] === 0x0a ? 'C-j' : 'C-@'}`)+ start = index + 1+ }+ literal(start, bytes.length)+ return commands+}const PANE_META_FORMAT = ['#{session_id}', '#{window_id}', '#{window_panes}', '#{window_width}', '#{window_height}','#{pane_width}', '#{pane_height}', '#{alternate_on}', '#{cursor_x}', '#{cursor_y}',@@ -63,10 +115,14 @@ interface PaneMeta {mouseSgr: boolean}-function boundedSize(size: TerminalStreamSize): TerminalStreamSize {+/** The smallest size `refresh-client -C` takes before tmux 2.9 (its PANE_MINIMUM): asked for less, it+ * refused, and the resize failed instead of drawing two columns. */+const OLD_TMUX_MIN_CLIENT_SIZE = 2++function boundedSize(size: TerminalStreamSize, min = { cols: MIN_COLS, rows: MIN_ROWS }): TerminalStreamSize {return {- cols: Math.max(MIN_COLS, Math.min(MAX_COLS, Math.floor(size.cols))),- rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, Math.floor(size.rows))),+ cols: Math.max(min.cols, Math.min(MAX_COLS, Math.floor(size.cols))),+ rows: Math.max(min.rows, Math.min(MAX_ROWS, Math.floor(size.rows))),}}@@ -460,6 +516,8 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {child: ChildProcessWithoutNullStreams,private readonly sink: TerminalStreamSink,private readonly readOnly = false,+ /** What this tmux can do: read once, at open, so a keystroke never waits on it (see `writeRaw`). */+ private readonly features: TmuxFeatures = tmuxFeaturesOf(null),) {this.runtime = { backend: 'tmux', paneId }this.child = child@@ -491,7 +549,12 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {const original = await paneMeta(paneId)if (!original) return { state: 'failed', reason: 'tmux pane metadata is unavailable' }if (original.windowPanes !== 1) return { state: 'failed', reason: 'TERMINAL_MULTI_PANE_UNSUPPORTED' }- const child = spawn('tmux', ['-C', 'attach-session', '-f', 'ignore-size', '-t', paneId], {+ const features = await tmuxFeatures()+ // `ignore-size` keeps this client's size out of the window's. Client flags are tmux 3.2; before it+ // the flag was a usage error, the client exited at once, and no terminal opened on 3.1 or older.+ // Nothing is lost there: a control client that never sets its own size counts for none (`resize`).+ const flags = features.clientFlags ? ['-f', 'ignore-size'] : []+ const child = spawn('tmux', ['-C', 'attach-session', ...flags, '-t', paneId], {stdio: ['pipe', 'pipe', 'pipe'],})const spawned = await new Promise<boolean>((resolve) => {@@ -500,7 +563,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {child.once('error', () => { if (!settled) { settled = true; resolve(false) } })})if (!spawned) return { state: 'failed', reason: 'tmux control client could not start' }- const stream = new TmuxControlStream(paneId, child, sink, readOnly)+ const stream = new TmuxControlStream(paneId, child, sink, readOnly, features)const resized = readOnly ? TERMINAL_ACTION_SUCCEEDED : await stream.resize(size)if (resized.state !== 'succeeded') {await stream.close()@@ -625,7 +688,11 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {// 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.- const baseCapture = `capture-pane -p -e -N -t ${this.runtime.paneId}`+ // -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@@ -651,7 +718,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {const history = (meta.alternateOn || tuiOwnsScrollback)? Buffer.alloc(0): (await this.runControlCommand(- `capture-pane -p -e -N -t ${this.runtime.paneId} -S -${SNAPSHOT_HISTORY_LINES} -E -1`,+ `capture-pane -p -e${keepTrailing} -t ${this.runtime.paneId} -S -${SNAPSHOT_HISTORY_LINES} -E -1`,)).stdoutconst capture = await this.runControlCommand(baseCapture, () => {// `%end` is the ordered cut. Notifications observed before it are@@ -702,11 +769,12 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {const sends: Array<Promise<ControlCommandResult>> = []// Every chunk is handed to the queue before any reply is awaited, so a paste costs one// round-trip rather than one per chunk. tmux applies them in the order they were written.- for (let offset = 0; offset < bytes.length; offset += INPUT_CHUNK_BYTES) {- const chunk = bytes.subarray(offset, offset + INPUT_CHUNK_BYTES)- const hex = [...chunk].map((byte) => byte.toString(16).padStart(2, '0')).join(' ')- sends.push(this.runControlCommand(`send-keys -t ${this.runtime.paneId} -H ${hex}`))- }+ // `send-keys -H` is tmux 3.0: before it, every keystroke was a usage error and nothing typed in+ // a terminal reached the engine. There the same bytes go as literal text (`literalKeyCommands`).+ const commands = this.features.sendKeysHex+ ? hexKeyCommands(this.runtime.paneId, bytes)+ : literalKeyCommands(this.runtime.paneId, bytes)+ for (const command of commands) sends.push(this.runControlCommand(command))const results = await Promise.all(sends)const failedAt = results.findIndex((result) => !result.ok)if (failedAt < 0) return TERMINAL_ACTION_SUCCEEDED@@ -772,16 +840,20 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {const meta = parsePaneMeta(metadata.stdout)if (!meta) return terminalActionNotStarted('tmux pane disappeared')if (meta.windowPanes !== 1) return terminalActionNotStarted('TERMINAL_MULTI_PANE_UNSUPPORTED')- const size = boundedSize(requested)+ const size = this.features.resizeWindow+ ? boundedSize(requested)+ : boundedSize(requested, { cols: OLD_TMUX_MIN_CLIENT_SIZE, rows: OLD_TMUX_MIN_CLIENT_SIZE })// A repeated open/focus can legitimately ask for the grid already in// use. Avoid a redundant resize-window because full-screen TUIs may// repaint on SIGWINCH even when the dimensions did not change.if (meta.windowWidth === size.cols && meta.windowHeight === size.rows) {return TERMINAL_ACTION_SUCCEEDED}- const result = await this.runControlCommand(- `resize-window -t ${meta.windowId} -x ${size.cols} -y ${size.rows}`,- )+ // `resize-window` is tmux 2.9. Before it a control client gives its own size, and the window takes+ // the smallest of its session's clients: alone with the agent, this one.+ const result = await this.runControlCommand(this.features.resizeWindow+ ? `resize-window -t ${meta.windowId} -x ${size.cols} -y ${size.rows}`+ : `refresh-client -C ${size.cols},${size.rows}`)if (!result.ok) return terminalActionPossiblyExecuted('tmux resize did not complete')return TERMINAL_ACTION_SUCCEEDED})diff --git a/cli/src/lib/tmuxVersion.spec.ts b/cli/src/lib/tmuxVersion.spec.tsindex 4993c2560..139dc2a12 100644--- a/cli/src/lib/tmuxVersion.spec.ts+++ b/cli/src/lib/tmuxVersion.spec.ts@@ -1,5 +1,10 @@-import { describe, expect, it } from 'vitest'-import { TMUX_SESSION_ENV_MIN, parseTmuxVersion, supportsSessionEnv } from './tmuxVersion.js'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { delimiter, join } from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import {+ TMUX_SESSION_ENV_MIN, parseTmuxVersion, resetTmuxVersionCache, supportsSessionEnv, tmuxFeaturesOf, tmuxVersion,+} from './tmuxVersion.js'describe('parseTmuxVersion', () => {it('reads the shapes tmux -V actually prints', () => {@@ -29,3 +34,64 @@ describe('supportsSessionEnv', () => {expect(supportsSessionEnv(null)).toBe(true)})})++describe('tmuxFeaturesOf', () => {+ it('answers each feature by the release that brought it', () => {+ const none = {+ resizeWindow: false, paneOptions: false, sendKeysHex: false, respawnEnv: false,+ captureTrailingSpaces: false, clientFlags: false, sessionEnv: false,+ }+ // RHEL and Rocky 8 ship 2.7, Debian 10 ships 2.8.+ expect(tmuxFeaturesOf({ major: 2, minor: 7 })).toEqual(none)+ expect(tmuxFeaturesOf({ major: 2, minor: 8 })).toEqual(none)+ expect(tmuxFeaturesOf({ major: 2, minor: 9 })).toEqual({ ...none, resizeWindow: true })+ // Ubuntu 20.04 ships 3.0a: pane options, but no client flags or session environment yet.+ const three = { ...none, resizeWindow: true, paneOptions: true, sendKeysHex: true, respawnEnv: true }+ expect(tmuxFeaturesOf({ major: 3, minor: 0 })).toEqual(three)+ expect(tmuxFeaturesOf({ major: 3, minor: 1 })).toEqual({ ...three, captureTrailingSpaces: true })+ const all = { ...three, captureTrailingSpaces: true, clientFlags: true, sessionEnv: true }+ expect(tmuxFeaturesOf({ major: 3, minor: 2 })).toEqual(all)+ expect(tmuxFeaturesOf({ major: 4, minor: 0 })).toEqual(all)+ // A build that prints no number is newer than every release.+ expect(tmuxFeaturesOf(null)).toEqual(all)+ })+})++describe('tmuxVersion', () => {+ const originalPath = process.env.PATH+ let dir = ''+ afterEach(() => {+ resetTmuxVersionCache()+ process.env.PATH = originalPath+ if (dir) rmSync(dir, { recursive: true, force: true })+ dir = ''+ })+ /** A tmux on PATH that counts its calls and answers `tmux 2.8`, or fails while [refuse] exists. */+ function fakeTmux() {+ dir = mkdtempSync(join(tmpdir(), 'tmux-version-'))+ const calls = join(dir, 'calls')+ const refuse = join(dir, 'refuse')+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh\necho -V >> '${calls}'\n[ -f '${refuse}' ] && exit 1\necho 'tmux 2.8'\n`, { mode: 0o755 })+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`+ return { calls: () => readFileSync(calls, 'utf8').trim().split('\n').length, refuse }+ }++ it('asks tmux once, and keeps its answer', async () => {+ const tmux = fakeTmux()+ resetTmuxVersionCache()+ expect(await tmuxVersion()).toEqual({ major: 2, minor: 8 })+ expect(await tmuxVersion()).toEqual({ major: 2, minor: 8 })+ expect(tmux.calls()).toBe(1)+ })++ it('asks again after a tmux that could not be asked, rather than taking it for the newest for good', async () => {+ const tmux = fakeTmux()+ writeFileSync(tmux.refuse, '')+ resetTmuxVersionCache()+ expect(await tmuxVersion()).toBeNull()+ rmSync(tmux.refuse)+ expect(await tmuxVersion()).toEqual({ major: 2, minor: 8 })+ expect(await tmuxVersion()).toEqual({ major: 2, minor: 8 })+ expect(tmux.calls()).toBe(2)+ })+})diff --git a/cli/src/lib/tmuxVersion.ts b/cli/src/lib/tmuxVersion.tsindex f3a9b7f11..4a535ce67 100644--- a/cli/src/lib/tmuxVersion.ts+++ b/cli/src/lib/tmuxVersion.ts@@ -1,22 +1,51 @@/**- * What this machine's tmux can do, for the one feature that is not universally available.+ * What this machine's tmux can do, for every feature newer than the oldest tmux Harness runs on.*- * `new-session -e VAR=value` arrived in tmux 3.2. Without a check, an older tmux answers a grid- * launch with its own usage text — which the create path faithfully reports as `SPAWN_FAILED:- * usage: new-session [-AdDEHPX] ...`, a dead end for anyone who did not already know the flag was- * new. The version is worth one `tmux -V` so the refusal can name the actual cause.+ * Harness runs on the tmux a distribution ships, and those are old: RHEL and Rocky 8 ship 2.7, Debian+ * 10 ships 2.8, Ubuntu 20.04 ships 3.0a, Debian 11 ships 3.1c. tmux checks a whole `;` command list+ * before it runs any of it, so one flag an older tmux does not know fails every command in the list:+ * the pane-owner tag (`set-option -p`, 3.0) chained into `new-session` made every agent create fail on+ * tmux 2.x (PR #789's review). And a flag it does not know in a one-off command is its usage text where+ * a result was expected — `new-session -e` once came back as `SPAWN_FAILED: usage: new-session ...`, a+ * dead end for anyone who did not already know the flag was new. So each feature is named here, with+ * the release that brought it, and every caller asks by name.*/import { execFile } from 'node:child_process'+import { patientExec } from './patientExec.js'-/** The first tmux that accepts `-e` on `new-session`. */-export const TMUX_SESSION_ENV_MIN = { major: 3, minor: 2 } as const+// A held event loop must not turn a timeout into a tmux that could not be asked (patientExec.ts).+const run = patientExec(execFile)export interface TmuxVersion {major: numberminor: number}+/** The first release with each feature, from tmux's CHANGES; each measured against tmux 2.8 and 3.0a. */+export const TMUX_FEATURE_MIN = {+ /** `resize-window` (2.9). Before it a control client sizes its session with `refresh-client -C w,h`. */+ resizeWindow: { major: 2, minor: 9 },+ /** Pane options (3.0): `set-option -p`, and `window-style` and `remain-on-exit` kept per pane. */+ paneOptions: { major: 3, minor: 0 },+ /** `send-keys -H`, keys given as hex bytes (3.0). */+ sendKeysHex: { major: 3, minor: 0 },+ /** `respawn-pane -e` (3.0). */+ respawnEnv: { major: 3, minor: 0 },+ /** `capture-pane -N`, a row's trailing spaces kept (3.1). */+ captureTrailingSpaces: { major: 3, minor: 1 },+ /** Client flags (3.2): `attach-session -f ignore-size`. */+ clientFlags: { major: 3, minor: 2 },+ /** `new-session -e`, a session's own environment (3.2). */+ sessionEnv: { major: 3, minor: 2 },+} as const satisfies Record<string, TmuxVersion>++export type TmuxFeature = keyof typeof TMUX_FEATURE_MIN+export type TmuxFeatures = Readonly<Record<TmuxFeature, boolean>>++/** The first tmux that accepts `-e` on `new-session`. */+export const TMUX_SESSION_ENV_MIN = TMUX_FEATURE_MIN.sessionEnv+/*** `tmux 3.5a` / `tmux next-3.6` / `tmux openbsd-7.4` → the numeric part; `null` when there is none.*@@ -29,22 +58,58 @@ export function parseTmuxVersion(output: string): TmuxVersion | null {return { major: Number(match[1]), minor: Number(match[2]) }}+/** Whether [version] is [min] or newer. Unknown is not old: see parseTmuxVersion. */+export function atLeast(version: TmuxVersion | null, min: TmuxVersion): boolean {+ if (!version) return true+ if (version.major !== min.major) return version.major > min.major+ return version.minor >= min.minor+}+export function supportsSessionEnv(version: TmuxVersion | null): boolean {- if (!version) return true // see parseTmuxVersion — unknown is not old- if (version.major !== TMUX_SESSION_ENV_MIN.major) return version.major > TMUX_SESSION_ENV_MIN.major- return version.minor >= TMUX_SESSION_ENV_MIN.minor+ return atLeast(version, TMUX_SESSION_ENV_MIN)+}++/** Every feature, answered for one version. */+export function tmuxFeaturesOf(version: TmuxVersion | null): TmuxFeatures {+ const features = {} as Record<TmuxFeature, boolean>+ for (const feature of Object.keys(TMUX_FEATURE_MIN) as TmuxFeature[]) {+ features[feature] = atLeast(version, TMUX_FEATURE_MIN[feature])+ }+ return features}let cached: Promise<TmuxVersion | null> | undefined-async function probe(): Promise<TmuxVersion | null> {- return await new Promise((resolve) => {- execFile('tmux', ['-V'], { timeout: 2_000 }, (error, stdout) => {+/**+ * This machine's tmux, probed once per process — tmux does not change under a running daemon (a new+ * tmux cannot even talk to the old server: it says "protocol version mismatch"), and this sits in front+ * of an interactive "create agent" click.+ *+ * Kept only once tmux has answered. A tmux that could not be asked (not on the daemon's PATH yet, a+ * timeout) reads as the newest for that one call, like a build that prints no number, and is asked+ * again at the next. Kept, one missed answer would stand for the life of the daemon, and on tmux 2.x+ * every agent create after it would chain a pane option and fail.+ */+export function tmuxVersion(): Promise<TmuxVersion | null> {+ if (cached) return cached+ const asked = new Promise<{ answered: boolean; version: TmuxVersion | null }>((resolve) => {+ run('tmux', ['-V'], { timeout: 2_000 }, (error, stdout) => {// A tmux that cannot be run at all is not this check's problem: the create path already// reports `TMUX_UNAVAILABLE` for it, and answering "too old" here would name the wrong cause.- resolve(error ? null : parseTmuxVersion(stdout))+ resolve({ answered: !error, version: error ? null : parseTmuxVersion(stdout) })})})+ const answer = asked.then(({ answered, version }) => {+ if (!answered && cached === answer) cached = undefined+ return version+ })+ cached = answer+ return answer+}++/** What this machine's tmux can do (see `TMUX_FEATURE_MIN`). */+export async function tmuxFeatures(): Promise<TmuxFeatures> {+ return tmuxFeaturesOf(await tmuxVersion())}/**@@ -52,11 +117,15 @@ async function probe(): Promise<TmuxVersion | null> {* a running daemon, and this sits in front of an interactive "create agent" click.*/export async function tmuxSupportsSessionEnv(): Promise<boolean> {- cached ??= probe()- return supportsSessionEnv(await cached)+ return supportsSessionEnv(await tmuxVersion())}/** Test seam: forget the cached probe so a spec can install its own tmux. */export function resetTmuxVersionCache(): void {cached = undefined}++/** Test seam: answer as [version] without asking tmux (null: a tmux that prints no number). */+export function assumeTmuxVersion(version: TmuxVersion | null): void {+ cached = Promise.resolve(version)+}diff --git a/cli/src/testing/isolatedTmux.ts b/cli/src/testing/isolatedTmux.tsindex 358cd1c6e..21f91c6cd 100644--- a/cli/src/testing/isolatedTmux.ts+++ b/cli/src/testing/isolatedTmux.ts@@ -29,7 +29,10 @@ export async function isolatedTmux(inherited: NodeJS.ProcessEnv = process.env) {run,async close() {await run('kill-server').catch(() => { /* this disposable server may already have exited */ })- await rm(root, { recursive: true, force: true })+ // kill-server returns before its panes have exited, and a zsh among them writes its history as+ // it goes (macOS's /etc/zshrc sets HISTFILE): the folder filled up under the removal, and a+ // passing tmuxmoves.e2e.ts test failed in its teardown with ENOTEMPTY. Asked again, it is empty.+ await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 })},}}