Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Fix lost CLI turn after tmux buffer load timeout (#1629)

0xken1566fd847b1d1b
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index 63399f380..78ea3fcc8 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -633,10 +633,11 @@ if [ "$1" = "paste-buffer" ] && [ "$TMUX_SUBMIT_FAIL" = "1" ]; then exit 2; fi
// A revoked engine operation must not paste after waiting for a tmux room or buffer load.
writeFileSync(argsFile, '')
- expect(await sendToTmux('%7', '/model next', undefined, () => false)).toBe(false)
+ expect(await sendToTmux('%7', '/model next', undefined, () => false)).toEqual({ notPasted: 'tmux buffer was not pasted' })
expect(readFileSync(argsFile, 'utf8')).toBe('')
writeFileSync(argsFile, '')
- expect(await sendToTmux('%7', '/model next', undefined, () => readFileSync(argsFile, 'utf8') === '')).toBe(false)
+ expect(await sendToTmux('%7', '/model next', undefined, () => readFileSync(argsFile, 'utf8') === ''))
+ .toEqual({ notPasted: 'tmux buffer was not pasted' })
expect(commands()).toEqual(['load-buffer -b buffer -', 'delete-buffer -b buffer'])
// Revocation while the caller awaits a final admission check must withhold Enter.
@@ -655,7 +656,7 @@ if [ "$1" = "paste-buffer" ] && [ "$TMUX_SUBMIT_FAIL" = "1" ]; then exit 2; fi
await new Promise(resolve => setTimeout(resolve, 10))
allowed = false
leave()
- expect(await queued).toBe(false)
+ expect(await queued).toEqual({ notPasted: 'tmux buffer was not pasted' })
expect(readFileSync(argsFile, 'utf8')).toBe('')
assumeTmuxVersion(null)
@@ -815,6 +816,58 @@ if [ "$1" = "load-buffer" ]; then exec sleep 30; fi
rmSync(dir, { recursive: true, force: true })
}
}, 20_000)
+
+ it('recovers a timed-out buffer load without pasting a late first buffer twice', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'harness-tmux-late-buffer-'))
+ const calls = join(dir, 'calls')
+ const loaded = join(dir, 'loaded')
+ const first = join(dir, 'first')
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh
+printf '%s\\n' "$*" >> "$TMUX_LATE_CALLS"
+if [ "$1" = "load-buffer" ]; then
+ cat > /dev/null
+ if [ ! -e "$TMUX_LATE_FIRST" ]; then
+ touch "$TMUX_LATE_FIRST"
+ (sleep 6; printf '%s\\n' "$3" >> "$TMUX_LATE_LOADED") < /dev/null > /dev/null 2>&1 &
+ exec sleep 30
+ fi
+ printf '%s\\n' "$3" >> "$TMUX_LATE_LOADED"
+fi
+`, { mode: 0o700 })
+ const previous = {
+ path: process.env.PATH,
+ calls: process.env.TMUX_LATE_CALLS,
+ loaded: process.env.TMUX_LATE_LOADED,
+ first: process.env.TMUX_LATE_FIRST,
+ }
+ try {
+ process.env.PATH = `${dir}:${previous.path ?? ''}`
+ process.env.TMUX_LATE_CALLS = calls
+ process.env.TMUX_LATE_LOADED = loaded
+ process.env.TMUX_LATE_FIRST = first
+ assumeTmuxVersion({ major: 3, minor: 4 })
+ expect(await sendToTmux('%7', 'one message')).toBe(true)
+ await vi.waitFor(() => expect(readFileSync(loaded, 'utf8').trim().split('\n')).toHaveLength(2), { timeout: 3_000 })
+ const commands = readFileSync(calls, 'utf8').trim().split('\n')
+ const loads = commands.filter((line) => line.startsWith('load-buffer '))
+ const pastes = commands.filter((line) => line.startsWith('paste-buffer '))
+ expect(loads).toHaveLength(2)
+ expect(pastes).toHaveLength(1)
+ expect(pastes[0]).toContain(loads[1].split(' ')[2])
+ expect(pastes[0]).not.toContain(loads[0].split(' ')[2])
+ expect(commands.filter((line) => line === 'send-keys -t %7 Enter')).toHaveLength(1)
+ } finally {
+ resetTmuxVersionCache()
+ for (const [key, value] of Object.entries({
+ PATH: previous.path, TMUX_LATE_CALLS: previous.calls,
+ TMUX_LATE_LOADED: previous.loaded, TMUX_LATE_FIRST: previous.first,
+ })) {
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ rmSync(dir, { recursive: true, force: true })
+ }
+ }, 15_000)
})
describe('cleanPaneTitle', () => {
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 336e8433c..80c495bee 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -244,25 +244,27 @@ function tmuxEnter(pane: string): Promise<boolean> {
export const LOAD_BUFFER_TIMEOUT_MS = 5_000
/** Stage text in a NAMED tmux buffer via stdin (avoids arg-length limits + the user's default buffer). */
-function tmuxLoadBuffer(name: string, content: string): Promise<boolean> {
+type BufferLoad = 'loaded' | 'timed_out' | 'failed'
+
+function tmuxLoadBuffer(name: string, content: string): Promise<BufferLoad> {
return new Promise((resolve) => {
let settled = false
let cancel = (): void => {}
- const settle = (loaded: boolean): void => {
+ const settle = (result: BufferLoad): void => {
if (settled) return
settled = true
cancel()
- resolve(loaded)
+ resolve(result)
}
const c = spawn('tmux', ['load-buffer', '-b', name, '-'])
// Answered without waiting for its pipes to close: a client killed here may leave one open behind it.
cancel = patientDeadline(LOAD_BUFFER_TIMEOUT_MS, () => {
c.kill('SIGKILL')
- settle(false)
+ settle('timed_out')
})
- c.on('error', () => settle(false))
- c.on('close', (code) => settle(code === 0))
- c.stdin.on('error', () => { /* EPIPE if tmux died first — 'close' still resolves false */ })
+ c.on('error', () => settle('failed'))
+ c.on('close', (code) => settle(code === 0 ? 'loaded' : 'failed'))
+ c.stdin.on('error', () => { /* EPIPE if tmux died first — 'close' still reports failure */ })
c.stdin.end(content)
})
}
@@ -433,19 +435,28 @@ function tmuxDeleteBuffer(name: string): Promise<void> {
*
* A buffer set and deleted is a notification to every control client, which on a tmux before 3.7
* crashed the server while one was attaching: the paste waits for none to be (tmuxControlGate.ts). */
-function tmuxPasteText(pane: string, content: string, bracketed: boolean, allowed?: () => boolean): Promise<boolean> {
+type PasteResult = 'pasted' | 'not_pasted' | 'uncertain'
+
+function tmuxPasteText(pane: string, content: string, bracketed: boolean, allowed?: () => boolean): Promise<PasteResult> {
return inTmuxRoom('notify', () => pasteThroughBuffer(pane, content, bracketed, allowed))
}
-async function pasteThroughBuffer(pane: string, content: string, bracketed: boolean, allowed?: () => boolean): Promise<boolean> {
- if (allowed && !allowed()) return false
- const bufferName = `machinemsg-${process.pid}-${++injectBufferSequence}`
- if (!(await tmuxLoadBuffer(bufferName, bracketed ? neutralizePasteControls(content) : content))) {
+async function pasteThroughBuffer(pane: string, content: string, bracketed: boolean, allowed?: () => boolean): Promise<PasteResult> {
+ let bufferName = ''
+ for (let attempt = 0; attempt < 2; attempt++) {
+ if (allowed && !allowed()) return 'not_pasted'
+ bufferName = `machinemsg-${process.pid}-${++injectBufferSequence}`
+ const loaded = await tmuxLoadBuffer(bufferName, bracketed ? neutralizePasteControls(content) : content)
+ if (loaded === 'loaded') break
await tmuxDeleteBuffer(bufferName)
- console.error(`[tmux] load-buffer for ${pane} failed`)
- return false
+ // No paste command has run. A timed-out client may still finish loading its unique buffer,
+ // but only the next, separately named buffer can be pasted into the pane.
+ if (loaded !== 'timed_out' || attempt === 1) {
+ console.error(`[tmux] load-buffer for ${pane} failed`)
+ return 'not_pasted'
+ }
}
- if (allowed && !allowed()) { await tmuxDeleteBuffer(bufferName); return false }
+ if (allowed && !allowed()) { await tmuxDeleteBuffer(bufferName); return 'not_pasted' }
const args = ['paste-buffer', '-t', pane, '-b', bufferName]
if (bracketed) args.push('-p')
args.push('-d')
@@ -456,7 +467,7 @@ async function pasteThroughBuffer(pane: string, content: string, bracketed: bool
})
})
if (!pasted) await tmuxDeleteBuffer(bufferName)
- return pasted
+ return pasted ? 'pasted' : 'uncertain'
}
/**
@@ -473,11 +484,13 @@ async function pasteThroughBuffer(pane: string, content: string, bracketed: bool
* from being pressed, and comes back as `{ withheld }`, the text left typed. An engine can open a dialog
* in that gap, mid-turn, and the Enter would answer it.
*/
-export function sendToTmux(pane: string, text: string, beforeEnter?: () => Promise<string | null>, allowed?: () => boolean): Promise<boolean | { withheld: string }> {
+export function sendToTmux(pane: string, text: string, beforeEnter?: () => Promise<string | null>, allowed?: () => boolean): Promise<boolean | { withheld: string } | { notPasted: string }> {
const content = submitContent(text)
return (async () => {
const settle = submitSettleMs(content)
- if (!(await tmuxPasteText(pane, content, true, allowed))) return false
+ const pasted = await tmuxPasteText(pane, content, true, allowed)
+ if (pasted === 'not_pasted') return { notPasted: 'tmux buffer was not pasted' }
+ if (pasted === 'uncertain') return false
if (settle) await sleep(settle)
const withheld = beforeEnter ? await beforeEnter() : null
if (withheld) return { withheld }
@@ -493,7 +506,7 @@ export function sendToTmux(pane: string, text: string, beforeEnter?: () => Promi
* land on the row that just opened and pick whatever was already highlighted.
*/
export function sendLiteralToTmux(pane: string, text: string): Promise<boolean> {
- return tmuxPasteText(pane, text, false)
+ return tmuxPasteText(pane, text, false).then((result) => result === 'pasted')
}
/**
@@ -509,7 +522,7 @@ export function sendLiteralToTmux(pane: string, text: string): Promise<boolean>
* paste into a live terminal must not auto-submit.
*/
export function pasteRawIntoTmux(pane: string, text: string, allowed?: () => boolean): Promise<boolean> {
- return tmuxPasteText(pane, text, true, allowed)
+ return tmuxPasteText(pane, text, true, allowed).then((result) => result === 'pasted')
}
export function sendKeyToTmux(pane: string, key: string): Promise<boolean> {
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 65e87b01f..a20103a57 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -151,6 +151,21 @@ describe('TmuxBackend lifecycle', () => {
expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual(['load-buffer', 'paste-buffer', 'send-keys', 'load-buffer', 'paste-buffer'])
})
+ it('reports a failed buffer load as not pasted, rather than a possible submission', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-load-fail-'))
+ dirs.push(dir)
+ const calls = join(dir, 'calls')
+ writeFileSync(join(dir, 'tmux'), `#!/bin/sh
+printf '%s\\n' "$1" >> "$TMUX_BACKEND_CALLS"
+if [ "$1" = "load-buffer" ]; then cat > /dev/null; exit 2; fi
+`, { mode: 0o700 })
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ process.env.TMUX_BACKEND_CALLS = calls
+ const result = await new TmuxBackend().submitText({ backend: 'tmux', paneId: '%42' }, 'one message')
+ expect(result).toMatchObject({ state: 'failed', dispatch: 'not_started' })
+ expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual(['load-buffer', 'delete-buffer'])
+ })
+
it('creates a detached session and closes only its exact pane', async () => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-lifecycle-'))
dirs.push(dir)
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 9d85f51b4..42054ea99 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -568,7 +568,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
async submitText(runtime: TmuxRuntimeRef, text: string, options?: SubmitOptions): Promise<TerminalActionResult> {
const sent = await sendToTmux(runtime.paneId, text, options?.beforeEnter, options?.allowed)
- return typeof sent === 'boolean' ? legacyActionResult(sent, 'tmux submission') : terminalEnterWithheld(sent.withheld)
+ if (typeof sent === 'boolean') return legacyActionResult(sent, 'tmux submission')
+ if ('notPasted' in sent) return terminalActionNotStarted(sent.notPasted)
+ return terminalEnterWithheld(sent.withheld)
}
async sendKey(runtime: TmuxRuntimeRef, key: TerminalLogicalKey): Promise<TerminalActionResult> {