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.

Resume Codex startup after an update without losing attached tasks (#732)

Dee0e23bf713e3b
diff --git a/cli/package.json b/cli/package.json
index 550a734ca..efa20a28c 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -23,7 +23,7 @@
"test:sharing-e2e": "tsx scripts/share-harness-e2e.ts",
"test:remote-viewers": "vitest run --config vitest.viewer.config.ts",
"test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",
- "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts src/lib/restartDiscovery.real.spec.ts src/lib/terminalClose.real.spec.ts --reporter=verbose",
+ "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts src/lib/codexUpdateRestart.real.spec.ts src/lib/restartDiscovery.real.spec.ts src/lib/terminalClose.real.spec.ts --reporter=verbose",
"test:resume": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume",
"test:resume-native": "tsx scripts/resume-native-e2e.ts",
"test:portability": "vitest run --config vitest.portability.config.ts"
diff --git a/cli/src/lib/codexStartupRetry.spec.ts b/cli/src/lib/codexStartupRetry.spec.ts
index f1a0d056f..b52db927f 100644
--- a/cli/src/lib/codexStartupRetry.spec.ts
+++ b/cli/src/lib/codexStartupRetry.spec.ts
@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it } from 'vitest'
import { CODEX_STARTUP_RETRY_PROBE } from './codexStartupRetry.js'
const timeout = 'Error: account/read failed during TUI bootstrap: account/read failed: workspace routing discovery timed out (code -32603)'
+const updated = '🎉 Update ran successfully! Please restart Codex.'
const dirs: string[] = []
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
@@ -63,3 +64,41 @@ describe('Codex startup timeout evidence', () => {
expect(f.probe('after', JSON.stringify(before)).status).toBe(1)
})
})
+
+describe('Codex startup update evidence', () => {
+ it.each([updated, updated.replace('🎉 ', '')])('accepts a fresh successful update after waiting at the prompt: %s', output => {
+ const f = fixture()
+ const before = JSON.parse(f.probe('before').out)
+ writeFileSync(f.screen, `Updating Codex via installer\n${output}\n\n`)
+ expect(f.probe('after-update', JSON.stringify({ ...before, at: Date.now() - 600_000 })).status).toBe(0)
+ expect(f.probe('after', JSON.stringify(before)).status).toBe(1)
+ expect(f.probe('after-update', f.probe('before').out).status).toBe(1)
+ })
+
+ it.each([
+ 'Update failed: network error',
+ 'Update available! Run npm install -g @openai/codex',
+ `quoted output: ${updated}`,
+ `${updated}\n› Ask Codex to do anything`,
+ timeout,
+ '',
+ ])('rejects output that does not end with a successful update: %s', output => {
+ const f = fixture()
+ const before = f.probe('before').out
+ writeFileSync(f.screen, output)
+ expect(f.probe('after-update', before).status).toBe(1)
+ })
+
+ it('rejects missing, malformed, future and unavailable evidence', () => {
+ const f = fixture()
+ const before = JSON.parse(f.probe('before').out)
+ writeFileSync(f.screen, updated)
+ for (const baseline of ['', '{}', '{broken', JSON.stringify({ ...before, at: Date.now() + 10_000 }), JSON.stringify({ ...before, hash: '' })]) {
+ expect(f.probe('after-update', baseline).status).toBe(1)
+ }
+ expect(f.probe('unknown', JSON.stringify(before)).status).toBe(1)
+ expect(f.probe('after-update', JSON.stringify(before), 'other-session').status).toBe(1)
+ rmSync(f.tmux)
+ expect(f.probe('after-update', JSON.stringify(before)).status).toBe(1)
+ })
+})
diff --git a/cli/src/lib/codexStartupRetry.ts b/cli/src/lib/codexStartupRetry.ts
index b43a9f275..7d7b8d169 100644
--- a/cli/src/lib/codexStartupRetry.ts
+++ b/cli/src/lib/codexStartupRetry.ts
@@ -6,10 +6,12 @@
* safe; retrying an arbitrary exit could replay work. Inspect tmux AFTER exit so
* stdin, stdout and stderr stay real terminals (no tee, pipe or second PTY).
*
- * The baseline rejects an old error left in the pane. Only a new, final error line
- * within 30 seconds qualifies; normal exits, cancellation, auth/config errors,
- * session failures and unavailable terminal evidence all fail closed. The baseline
- * contains a hash, never terminal contents or the user's prompt.
+ * The baseline rejects old output left in the pane. A bootstrap timeout must be
+ * the new, final line within 30 seconds. A successful startup update instead ends
+ * with Codex's explicit restart request (observed in codex-cli 0.160.0). That path
+ * has no time limit: the person may leave the update prompt open before accepting.
+ * Normal exits, cancellation, auth/config errors, session failures and unavailable
+ * terminal evidence fail closed. The baseline stores no terminal text or prompt.
*/
export const CODEX_STARTUP_RETRY_PROBE = String.raw`
const { execFileSync } = require('node:child_process');
@@ -28,7 +30,11 @@ try {
const before = JSON.parse(baseline);
const elapsed = Date.now() - before.at;
const error = 'Error: account/read failed during TUI bootstrap: account/read failed: workspace routing discovery timed out (code -32603)';
- process.exit(elapsed >= 0 && elapsed <= 30000 && before.hash !== hash && last === error ? 0 : 1);
+ const fresh = Number.isFinite(elapsed) && elapsed >= 0 && /^[a-f0-9]{64}$/.test(before.hash) && before.hash !== hash;
+ const matches = mode === 'after-update'
+ ? /^(?:🎉\s*)?Update ran successfully! Please restart Codex\.$/.test(last)
+ : mode === 'after' && elapsed <= 30000 && last === error;
+ process.exit(fresh && matches ? 0 : 1);
}
} catch { process.exit(1); }
`.trim()
diff --git a/cli/src/lib/codexUpdateRestart.real.spec.ts b/cli/src/lib/codexUpdateRestart.real.spec.ts
new file mode 100644
index 000000000..06e3418ce
--- /dev/null
+++ b/cli/src/lib/codexUpdateRestart.real.spec.ts
@@ -0,0 +1,153 @@
+import { existsSync } from 'node:fs'
+import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'
+import { resolveBinaryOnPath } from './binaryOnPath.js'
+import { buildEngineCommandArgv, buildEngineLaunchArgv, type LaunchCommandOptions } from './engineLaunch.js'
+
+const real = process.env.RUN_REAL_TMUX_DISCOVERY === '1' ? describe : describe.skip
+const updated = '🎉 Update ran successfully! Please restart Codex.'
+const timeout = 'Error: account/read failed during TUI bootstrap: account/read failed: workspace routing discovery timed out (code -32603)'
+const prompt = 'Fix this image: "quotes", $(false), `false`, ; & !\nand a second line'
+type Attempt = { args: string[]; tty: boolean[]; cwd: string; codexHome: string }
+
+real('Codex update restart in an isolated real tmux pane', () => {
+ let server: IsolatedTmux | undefined
+ const dirs: string[] = []
+ afterEach(async () => {
+ await server?.close()
+ server = undefined
+ for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true })
+ })
+
+ async function launch({
+ shell = '/bin/sh', outputs = [updated], status = 0, options = {}, older = false,
+ }: {
+ shell?: string; outputs?: string[]; status?: number; options?: LaunchCommandOptions; older?: boolean
+ } = {}) {
+ const dir = await realpath(await mkdtemp(join(tmpdir(), "codex update 'fixture-")))
+ dirs.push(dir)
+ const state = join(dir, 'attempts.json')
+ const image = join(dir, "image with 'quotes.png")
+ const imageBytes = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aG9kAAAAASUVORK5CYII=', 'base64')
+ await writeFile(state, '[]')
+ await writeFile(image, imageBytes)
+ const binary = join(dir, 'codex')
+ // This models the observed updater boundary without installing software or
+ // contacting an account: a real update prompt, real TTYs, and Codex's final
+ // success line. Successful starts remain interactive in the same pane.
+ await writeFile(binary, `#!${process.execPath}
+const fs = require('node:fs');
+const state = ${JSON.stringify(state)};
+const attempts = JSON.parse(fs.readFileSync(state, 'utf8'));
+if (process.argv.includes('--help')) {
+ console.log(${older} && attempts.length === 0 ? '--model' : '--no-daemon');
+ process.exit(0);
+}
+attempts.push({ args: process.argv.slice(2), tty: [process.stdin.isTTY, process.stdout.isTTY, process.stderr.isTTY], cwd: process.cwd(), codexHome: process.env.CODEX_HOME });
+fs.writeFileSync(state, JSON.stringify(attempts));
+const output = ${JSON.stringify(outputs)}[attempts.length - 1];
+process.stdin.setRawMode(true);
+if (output === ${JSON.stringify(timeout)}) { console.error(output); process.exit(1); }
+if (output !== undefined) {
+ console.log('UPDATE_PROMPT');
+ process.stdin.once('data', () => {
+ process.stdin.setRawMode(false);
+ console.log(output);
+ process.exit(${status});
+ });
+} else {
+ console.log('CODEX_READY');
+ process.stdin.on('data', data => console.log('INPUT:' + data.toString()));
+}
+`, { mode: 0o755 })
+ server = await isolatedTmux({ ...process.env, ZDOTDIR: dir, CODEX_HOME: dir })
+ const launchOptions = { cwd: dir, permissionMode: 'auto', firstPrompt: prompt, extraArgs: ['--image', image, '--model', 'chosen-model'], ...options }
+ const command = buildEngineLaunchArgv('codex', launchOptions, shell, undefined, 'grid', resolveBinaryOnPath('tmux'))
+ command[command.indexOf('harness-engine') + 2] = binary
+ if (shell.endsWith('/bash')) command.splice(1, 0, '--norc')
+ 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(() => '')
+ const waitFor = async (check: () => Promise<boolean>) => {
+ const deadline = Date.now() + 10_000
+ while (Date.now() < deadline) {
+ if (await check()) return
+ await new Promise(resolve => setTimeout(resolve, 30))
+ }
+ throw new Error(`condition not met: ${await screen()}`)
+ }
+ const accept = () => server!.run('send-keys', '-t', pane, 'Enter')
+ await waitFor(async () => (await screen()).includes('UPDATE_PROMPT'))
+ return { pane, screen, attempts, exited, waitFor, accept, dir, image, imageBytes, launchOptions }
+ }
+
+ it.each(['/bin/sh', '/bin/bash', '/bin/zsh'].filter(existsSync))('continues the original task and image in %s without handing off to a shell', async shell => {
+ const f = await launch({ shell, older: true })
+ expect(await f.exited()).toBe('')
+ await f.accept()
+ await f.waitFor(async () => (await f.screen()).includes('CODEX_READY'))
+ const attempts = await f.attempts()
+ expect(attempts).toHaveLength(2)
+ const original = buildEngineCommandArgv('codex', f.launchOptions).slice(1)
+ // The replacement is probed again: an update may introduce --no-daemon.
+ expect(attempts[0].args).toEqual(original)
+ expect(attempts[1].args).toEqual(['--no-daemon', ...original])
+ for (const attempt of attempts) {
+ expect(attempt.tty).toEqual([true, true, true])
+ expect(attempt.cwd).toBe(f.dir)
+ expect(attempt.codexHome).toBe(f.dir)
+ }
+ expect(await readFile(f.image)).toEqual(f.imageBytes)
+ expect(await f.exited()).toBe('')
+ expect(await f.screen()).not.toContain('This pane is a shell now')
+ await server!.run('send-keys', '-t', f.pane, '-l', 'follow-up')
+ await f.waitFor(async () => (await f.screen()).includes('INPUT:follow-up'))
+ }, 15_000)
+
+ it.each(['resumeSessionId', 'forkSessionId'] as const)('preserves an explicit %s through the startup update', async key => {
+ const f = await launch({ options: { [key]: 'specific-conversation' } })
+ await f.accept()
+ await f.waitFor(async () => (await f.screen()).includes('CODEX_READY'))
+ const attempts = await f.attempts()
+ expect(attempts).toHaveLength(2)
+ expect(attempts[1].args).toEqual(attempts[0].args)
+ expect(attempts[1].args.slice(0, 3)).toEqual(['--no-daemon', key === 'resumeSessionId' ? 'resume' : 'fork', 'specific-conversation'])
+ expect(await f.exited()).toBe('')
+ })
+
+ it.each([
+ { output: 'Goodbye!', status: 0 },
+ { output: 'Update failed', status: 1 },
+ { output: updated, status: 130 },
+ { output: updated, status: 1 },
+ ])('leaves normal exits, failures and cancellation alone: $status $output', async ({ output, status }) => {
+ const f = await launch({ outputs: [output], status })
+ await f.accept()
+ await f.waitFor(async () => await f.exited() === String(status))
+ expect(await f.attempts()).toHaveLength(1)
+ expect(await f.screen()).toContain('This pane is a shell now')
+ })
+
+ it('bounds update restarts even when the replacement requests another restart', async () => {
+ const f = await launch({ outputs: [updated, updated] })
+ await f.accept()
+ await f.waitFor(async () => (await f.attempts()).length === 2)
+ await f.accept()
+ await f.waitFor(async () => await f.exited() === '0')
+ expect(await f.attempts()).toHaveLength(2)
+ })
+
+ it('still recovers a bootstrap timeout after the update', async () => {
+ const f = await launch({ outputs: [updated, timeout] })
+ await f.accept()
+ await f.waitFor(async () => (await f.screen()).includes('CODEX_READY'))
+ const attempts = await f.attempts()
+ expect(attempts).toHaveLength(3)
+ expect(attempts[2].args).toEqual(attempts[0].args)
+ expect(await f.exited()).toBe('')
+ }, 15_000)
+})
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index b56a554b3..00e3bb3fe 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -509,11 +509,15 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm
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`
: ''
- return 'harness_engine() {\n'
- + (engine === 'codex' ? codexOwnedLaunchPrelude() : '')
+ // A function has its own positional parameters. Reprobe each replacement
+ // binary without adding --no-daemon to the saved launch arguments repeatedly.
+ return (engine === 'codex'
+ ? 'harness_codex_launch() {\n' + codexOwnedLaunchPrelude() + ' "$@"\n}\n'
+ : '')
+ + 'harness_engine() {\n'
+ (engine === 'codex' && tmuxBinary && isAbsolute(tmuxBinary)
? codexStartupRetryScript(tmuxBinary)
- : ' harness_status=0\n "$@" || harness_status=$?\n')
+ : ` harness_status=0\n ${engine === 'codex' ? 'harness_codex_launch ' : ''}"$@" || harness_status=$?\n`)
+ ' if [ "$harness_status" -eq 127 ]; then exit 127; fi\n'
+ mark
// Only a pane — something with a terminal on stdin — gets a shell to type into. Run without one
@@ -524,18 +528,27 @@ export function engineFallbackPrelude(engine: AgentEngine, shellPath: string, tm
+ '}\n'
}
-/** Keep a transient pre-session account lookup failure inside the original launch.
+/** Keep a successful startup update or transient account lookup failure in the original launch.
* Only the final exit gets the pane's engine-exit marker. The short backoff also
* keeps discovery from archiving the row between attempts. Never reparse "$@": it
- * includes the original prompt, model, permissions and resume/fork arguments. */
+ * includes the original prompt, images, model, permissions and resume/fork arguments.
+ * Codex's updater runs before the conversation opens, so replay that exact launch
+ * once, without choosing an unrelated conversation via `resume --last`. */
function codexStartupRetryScript(tmuxBinary: string): string {
const probe = `${shellSingleQuote(process.execPath)} -e ${shellSingleQuote(CODEX_STARTUP_RETRY_PROBE)}`
return ' harness_codex_attempt=1\n'
+ + ' harness_codex_updated=0\n'
+ ' while :; do\n'
+ ' harness_codex_before=\n'
+ ` if [ -n "\${TMUX_PANE:-}" ]; then harness_codex_before=$(${probe} before ${shellSingleQuote(tmuxBinary)} "$TMUX_PANE") || harness_codex_before=; fi\n`
+ ' harness_status=0\n'
- + ' "$@" || harness_status=$?\n'
+ + ' harness_codex_launch "$@" || harness_status=$?\n'
+ + ' if [ "$harness_status" -eq 0 ] && [ "$harness_codex_updated" -eq 0 ] && [ -n "$harness_codex_before" ] &&\n'
+ + ` ${probe} after-update ${shellSingleQuote(tmuxBinary)} "$TMUX_PANE" "$harness_codex_before"; then\n`
+ + ' harness_codex_updated=1\n'
+ + ` printf '\\n%s\\n' 'harness: Codex updated. Continuing startup…'\n`
+ + ' continue\n'
+ + ' fi\n'
+ ' [ "$harness_status" -eq 1 ] && [ "$harness_codex_attempt" -lt 3 ] && [ -n "$harness_codex_before" ] || break\n'
+ ` ${probe} after ${shellSingleQuote(tmuxBinary)} "$TMUX_PANE" "$harness_codex_before" || break\n`
+ ' harness_codex_delay=$((harness_codex_attempt * 2))\n'
diff --git a/desktop/lib/state/attached_task_delivery.dart b/desktop/lib/state/attached_task_delivery.dart
index de5eaf374..2181ac76d 100644
--- a/desktop/lib/state/attached_task_delivery.dart
+++ b/desktop/lib/state/attached_task_delivery.dart
@@ -1,16 +1,52 @@
import 'dart:async';
+import 'package:xterm/xterm.dart';
+
import '../logging/app_log.dart';
import '../terminal/terminal_session.dart';
import 'app_state.dart';
import 'harness_attachments.dart';
/// How long a new harness has to open its terminal and start its engine.
+/// An observed Codex update waits for completion or pane closure instead: the
+/// person may leave its confirmation open for longer than this deadline.
const kAttachedTaskOpenTimeout = Duration(minutes: 2);
/// A beat after the engine reports ready, for its input to be drawn.
const kAttachedTaskSettle = Duration(milliseconds: 800);
+/// Codex can be alive in its updater before it opens a conversation. An empty
+/// chat may not have a session ID yet either. Read only the visible terminal,
+/// looking for its composer and footer together, not a menu's selected row or
+/// an old prompt in scrollback.
+enum _CodexStartup { waiting, updating, ready }
+
+_CodexStartup _codexStartup(Terminal terminal) {
+ final buffer = terminal.buffer;
+ final lines = [
+ for (var row = buffer.scrollBack; row < buffer.height; row++)
+ buffer.lines[row].getText(),
+ ];
+ final prompt = lines.lastIndexWhere(
+ (line) => RegExp(r'^\s*›').hasMatch(line),
+ );
+ if (prompt >= 0 &&
+ lines
+ .skip(prompt + 1)
+ .any(
+ (line) =>
+ RegExp(r'\? for shortcuts|\d+% context left').hasMatch(line),
+ )) {
+ return _CodexStartup.ready;
+ }
+ if (RegExp(
+ r'Update available!|Updating Codex via|Update ran successfully! Please restart Codex\.',
+ ).hasMatch(lines.join('\n'))) {
+ return _CodexStartup.updating;
+ }
+ return _CodexStartup.waiting;
+}
+
/// Can [machineId] take files into a harness's prompt? Both halves are the
/// daemon's: a file written there and its path pasted, then a space pasted.
bool canAttachFiles(AppNotifier app, String machineId) {
@@ -62,6 +98,10 @@ Future<TerminalSession?> _readySession(
String agentId,
) async {
var claimed = false;
+ TerminalSession? watchedSession;
+ Terminal? watchedTerminal;
+ Timer? timeout;
+ late void Function() check;
TerminalSession? ready() {
final agent = app
.stateOf(machineId)
@@ -76,7 +116,24 @@ Future<TerminalSession?> _readySession(
.nonNulls
.firstOrNull;
if (session == null) return null;
- if (session.acceptsInput) return session;
+ // Output and replacement keyframes need not change the agent inventory.
+ // Watch both so the queued task wakes up when the new composer is drawn.
+ if (!identical(watchedSession, session)) {
+ watchedSession?.removeListener(check);
+ watchedSession = session..addListener(check);
+ }
+ if (!identical(watchedTerminal, session.terminal)) {
+ watchedTerminal?.removeListener(check);
+ watchedTerminal = session.terminal..addListener(check);
+ }
+ if (session.acceptsInput) {
+ if (agent?.engine == 'codex') {
+ final startup = _codexStartup(session.terminal);
+ if (startup == _CodexStartup.updating) timeout?.cancel();
+ if (startup != _CodexStartup.ready) return null;
+ }
+ return session;
+ }
// A pane that arrives over the desk opens as a watcher, and another window
// on the account (the Mac's own app) may hold the terminal. Pressing New
// Harness with files is this person asking to type here: take it, once,
@@ -87,29 +144,51 @@ Future<TerminalSession?> _readySession(
session.status == TerminalSessionStatus.takenOver)) {
claimed = true;
appLog.info('attach', 'taking control of $agentId to hand it its files');
- unawaited(session.reopen(force: true));
+ // A local takeover can notify synchronously. Check again after reopen
+ // returns so that notification cannot be cancelled by this call's null.
+ unawaited(session.reopen(force: true).then((_) => check()));
}
return null;
}
final found = Completer<TerminalSession?>();
- void check() {
+ TerminalSession? candidate;
+ Timer? settle;
+ check = () {
if (found.isCompleted) return;
- if (ready() case final session?) found.complete(session);
- }
+ if (watchedSession != null &&
+ !app.panesFor(machineId).any((pane) => pane.agentId == agentId)) {
+ found.complete(null);
+ return;
+ }
+ final session = ready();
+ if (identical(candidate, session)) return;
+ settle?.cancel();
+ candidate = session;
+ if (session == null) return;
+ settle = Timer(kAttachedTaskSettle, () {
+ if (found.isCompleted) return;
+ if (identical(ready(), session)) {
+ found.complete(session);
+ } else {
+ candidate = null;
+ check();
+ }
+ });
+ };
- final timeout = Timer(kAttachedTaskOpenTimeout, () {
+ timeout = Timer(kAttachedTaskOpenTimeout, () {
if (!found.isCompleted) found.complete(null);
});
app.addListener(check);
check();
try {
- final session = await found.future;
- if (session == null) return null;
- await Future<void>.delayed(kAttachedTaskSettle);
- return session.acceptsInput ? session : null;
+ return await found.future;
} finally {
timeout.cancel();
+ settle?.cancel();
+ watchedSession?.removeListener(check);
+ watchedTerminal?.removeListener(check);
app.removeListener(check);
}
}
diff --git a/desktop/test/harness_attachments_test.dart b/desktop/test/harness_attachments_test.dart
index adf5c1835..d7d947504 100644
--- a/desktop/test/harness_attachments_test.dart
+++ b/desktop/test/harness_attachments_test.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/xterm.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
@@ -13,6 +14,10 @@ import 'package:harness/terminal/terminal_session.dart';
HarnessAttachment _file(String name, [int size = 4]) =>
HarnessAttachment(name, Uint8List(size));
+const _codexComposer =
+ '\u001b[1m›\u001b[0m \u001b[2mAsk Codex to do anything\u001b[0m\r\n'
+ '\r\n GPT-6-Astra · /tmp/work\r\n ? for shortcuts';
+
/// Records what a harness's terminal was handed, in order.
class _RecordingSession extends TerminalSession {
_RecordingSession()
@@ -57,7 +62,11 @@ class _RecordingSession extends TerminalSession {
}
}
-AppNotifier _app({String launch = 'ready', bool canPasteFiles = true}) {
+AppNotifier _app({
+ String launch = 'ready',
+ bool canPasteFiles = true,
+ String? engine,
+}) {
final app = AppNotifier(config: AppConfig.dev, authSession: AuthSession());
app.machineStates['box'] =
MachineState(
@@ -69,7 +78,9 @@ AppNotifier _app({String launch = 'ready', bool canPasteFiles = true}) {
)
..terminalPasteFileAvailable = canPasteFiles
..terminalPasteRawAvailable = true
- ..agents = [Agent(id: 'a1', name: 'Weather', launchState: launch)];
+ ..agents = [
+ Agent(id: 'a1', name: 'Weather', launchState: launch, engine: engine),
+ ];
return app;
}
@@ -92,6 +103,127 @@ void main() {
});
group('deliverAttachedTask', () {
+ testWidgets('rechecks Codex readiness and follows a replacement keyframe', (
+ tester,
+ ) async {
+ final app = _app(engine: 'codex');
+ addTearDown(app.dispose);
+ final session = _RecordingSession();
+ session.terminal.write(_codexComposer);
+ app.adoptSessionForTest(session);
+ String? problem = 'pending';
+ unawaited(
+ deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png')],
+ task: 'Look',
+ ).then((value) => problem = value),
+ );
+ await tester.pump(const Duration(milliseconds: 400));
+ // The old composer has scrolled away. It cannot make installer output
+ // ready, including during the interval originally reserved for settling.
+ session.terminal.write('${'\r\n' * 40}Updating Codex via installer…');
+ await tester.pump(kAttachedTaskSettle);
+ expect(session.calls, isEmpty);
+ expect(problem, 'pending');
+ final oldTerminal = session.terminal;
+ session.terminal = Terminal();
+ session.notifyListeners();
+ oldTerminal.write('\u001b[2J\u001b[H$_codexComposer');
+ await tester.pump(kAttachedTaskSettle);
+ expect(session.calls, isEmpty);
+ session.terminal.write(_codexComposer);
+ await tester.pump(kAttachedTaskSettle + const Duration(milliseconds: 10));
+ await tester.pump();
+ expect(problem, isNull);
+ expect(session.calls, ['file:shot.png', 'paste: ', 'send:Look']);
+ });
+
+ testWidgets('stops waiting if the updating Codex pane is closed', (
+ tester,
+ ) async {
+ final app = _app(engine: 'codex');
+ addTearDown(app.dispose);
+ final session = _RecordingSession();
+ session.terminal.write('Update available!\r\n› 1. Update now');
+ final pane = app.adoptSessionForTest(session);
+ String? problem = 'pending';
+ unawaited(
+ deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png')],
+ task: 'Look',
+ ).then((value) => problem = value),
+ );
+ await tester.pump(kAttachedTaskOpenTimeout + const Duration(seconds: 1));
+ expect(problem, 'pending');
+ app.panes.remove(pane);
+ app.notifyListeners();
+ await tester.pump();
+ expect(problem, contains('did not open in time'));
+ expect(session.calls, isEmpty);
+ session.dispose();
+ });
+
+ testWidgets(
+ 'keeps the task and image queued through a Codex startup update',
+ (tester) async {
+ final app = _app(engine: 'codex');
+ addTearDown(app.dispose);
+ final session = _RecordingSession();
+ session.terminal.write(
+ 'Update available!\r\n› 1. Update now\r\n 2. Skip\r\n'
+ 'Press enter to continue',
+ );
+ app.adoptSessionForTest(session);
+ String? problem = 'pending';
+ unawaited(
+ deliverAttachedTask(
+ app,
+ machineId: 'box',
+ agentId: 'a1',
+ files: [_file('shot.png')],
+ task: 'Fix the problem in this image',
+ ).then((value) => problem = value),
+ );
+ // The updater is a running Codex process with an input-capable terminal,
+ // but no conversation yet. Nothing may be pasted into its update menu.
+ await tester.pump(
+ kAttachedTaskOpenTimeout + const Duration(seconds: 30),
+ );
+ expect(session.calls, isEmpty);
+ expect(problem, 'pending');
+ app.notifyListeners(); // Rediscovery during installation is not readiness.
+ await tester.pump(const Duration(seconds: 30));
+ expect(session.calls, isEmpty);
+ session.terminal.write(
+ '\u001b[2J\u001b[HUpdating Codex via installer…',
+ );
+ await tester.pump(const Duration(seconds: 10));
+ expect(session.calls, isEmpty);
+ // A new empty chat is usable before its first session ID arrives. Only
+ // terminal output changes here; no agent inventory notification is sent.
+ session.terminal.write('\u001b[2J\u001b[H$_codexComposer');
+ await tester.pump(
+ kAttachedTaskSettle + const Duration(milliseconds: 10),
+ );
+ await tester.pump();
+ expect(problem, isNull);
+ expect(session.calls, [
+ 'file:shot.png',
+ 'paste: ',
+ 'send:Fix the problem in this image',
+ ]);
+ app.notifyListeners();
+ await tester.pump(const Duration(seconds: 1));
+ expect(session.calls, hasLength(3));
+ },
+ );
+
test('files first, each followed by a space, then the task', () async {
final app = _app();
addTearDown(app.dispose);