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
Fix Cmd-N task focus and closing exited Codex panes (#616)
Dee47fa6bc7f8c3
diff --git a/cli/src/lib/codexSessionLifecycle.spec.ts b/cli/src/lib/codexSessionLifecycle.spec.tsindex d20507b94..ffa2b4dce 100644--- a/cli/src/lib/codexSessionLifecycle.spec.ts+++ b/cli/src/lib/codexSessionLifecycle.spec.ts@@ -52,6 +52,30 @@ it('requires a verified process before accepting an unused conversation', asyncexpect(confirmUnused).not.toHaveBeenCalled()expect(deps.connect).not.toHaveBeenCalled()})+it('does not ask an unrelated shared server to identify an exited, unbound client', async () => {+ row.sessionId = ''+ row.processIdentity = { pid: 99, executable: 'node', startMarker: 'exited client' }+ await stopSharedCodexSession(row, () => true, deps)+ expect(deps.daemonIdentity).not.toHaveBeenCalled()+ expect(deps.connect).not.toHaveBeenCalled()+ await expect(stopSharedCodexSession(row, () => false, deps)).rejects.toThrow('cancelled')+})+it.each(['live', 'recycled', 'bound', 'transcript', 'resuming', 'unreadable'])('does not treat an unbound client as safely exited when %s', async state => {+ row.sessionId = ''+ row.processIdentity = { pid: 99, executable: 'node', startMarker: 'client' }+ if (state === 'live' || state === 'recycled') {+ vi.mocked(deps.rows).mockResolvedValue([+ ...(await deps.rows())!, { ...row.processIdentity, parentPid: 1, args: 'node /bin/codex',+ startMarker: state === 'live' ? 'client' : 'replacement' },+ ])+ }+ if (state === 'bound') row.boundAt = 1+ if (state === 'transcript') row.transcriptPath = '/history'+ if (state === 'resuming') row.resumeOnly = true+ if (state === 'unreadable') vi.mocked(deps.rows).mockResolvedValue(null)+ await expect(stopSharedCodexSession(row, () => true, deps)).rejects.toThrow(state === 'unreadable' ? 'verify' : 'identify')+ expect(deps.connect).not.toHaveBeenCalled()+})it('rechecks cancellation after confirming an unused conversation', async () => {row.sessionId = ''row.processIdentity = { pid: 99, executable: 'codex', startMarker: 'born' }diff --git a/cli/src/lib/codexSessionLifecycle.ts b/cli/src/lib/codexSessionLifecycle.tsindex a0c571457..3ffeef78d 100644--- a/cli/src/lib/codexSessionLifecycle.ts+++ b/cli/src/lib/codexSessionLifecycle.ts@@ -97,6 +97,17 @@ export async function stopSharedCodexSession(session: RegisteredSession, currentconst home = session.codexHome || env.CODEX_HOMEconst rows = await deps.rows()if (!rows) throw new Error('Could not verify the Codex server before stopping')+ const guard = () => { if (!current()) throw new Error('The close request was cancelled or the session changed') }+ // Close can beat discovery's exit reconciliation: the client has already+ // returned to its shell, with no conversation ever bound. Its checkpoint is+ // saved, and an unrelated shared server is not a reason to keep that pane.+ // Missing/recycled process identity and previously bound conversations still+ // need the normal verification below.+ if (session.processIdentity && !rows.some(row => row.pid === session.processIdentity!.pid)+ && !session.sessionId && !session.transcriptPath && session.boundAt == null && !session.resumeOnly) {+ guard()+ return+ }const owner = rows.find(row => row.pid === session.processIdentity?.pid && row.startMarker === session.processIdentity?.startMarker && row.executable === session.processIdentity?.executable)if (owner) {const args = argvTokens(owner.args)@@ -114,7 +125,6 @@ export async function stopSharedCodexSession(session: RegisteredSession, currentif (!daemon) return // Older/process-owned Codex has no detached writer.const normalize = (value: string) => value.trim().replace(/\s+/g, ' ')if (!rows.some(row => row.pid === daemon.pid && normalize(row.startMarker) === normalize(daemon.processStartTime))) return- const guard = () => { if (!current()) throw new Error('The close request was cancelled or the session changed') }if (!session.sessionId) {// An unused TUI has no conversation to unload. Close supplies fresh proof// of its empty composer after saving the screen; Pause and uncertaindiff --git a/cli/src/lib/unusedCodexClose.spec.ts b/cli/src/lib/unusedCodexClose.spec.tsindex cfaa3013c..65751180b 100644--- a/cli/src/lib/unusedCodexClose.spec.ts+++ b/cli/src/lib/unusedCodexClose.spec.ts@@ -9,7 +9,9 @@ import { CloseAgentService, inspectCloseActivity } from './closeAgentService.js'import { createStopAgentService } from './stopAgentService.js'import { SessionCheckpointStore } from './sessionCheckpoint.js'import { processRows } from './tmux.js'-import { terminateDeletedAgent } from './deleteAgentFallback.js'+import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'+import { TmuxBackend } from './tmuxBackend.js'+import { isolatedTmux } from '../testing/isolatedTmux.js'vi.mock('./tmux.js', async importOriginal => ({...await importOriginal<typeof import('./tmux.js')>(),@@ -25,7 +27,7 @@ let row: RegisteredSessionlet service: CloseAgentServicelet screen: string | nulllet checkpointDirectory: string-const killPane = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))+const killPane = vi.fn<TmuxBackend['kill']>(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))beforeEach(() => {vi.clearAllMocks()@@ -94,3 +96,58 @@ it.each(['working', 'draft', 'unreadable', 'bound', 'resuming'] as const)('doesexpect(killPane).not.toHaveBeenCalled()expect(registry.byAgent(row.agentId)).toBe(row)})++it('closes the saved shell when an unbound Codex client exits before discovery catches up', async () => {+ screen = '$ codex\n$ '+ vi.mocked(processRows).mockResolvedValue((await processRows())!.filter(process => process.pid !== row.processIdentity!.pid))+ vi.mocked(terminateDeletedAgent).mockResolvedValue('gone')+ const request = { agentId: row.agentId, sessionId: '', createdAt: new Date(row.registeredAt).toISOString() }+ expect(await service.request({ ...request, mode: 'inspect' })).toEqual({ activity: 'unknown' })+ expect(await service.request({ ...request, mode: 'idle' })).toMatchObject({ error: 'SESSION_NOT_IDLE' })+ expect(await service.request({ ...request, mode: 'now' })).toEqual({ closed: true })+ expect(killPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%500' })+ expect(registry.byAgent(row.agentId)).toBeUndefined()+ const manifest = JSON.parse(readFileSync(join(checkpointDirectory, readdirSync(checkpointDirectory).find(file => /^[a-f0-9]{64}\.json$/.test(file))!), 'utf8'))+ expect(JSON.parse(readFileSync(join(checkpointDirectory, manifest.file), 'utf8')).screen).toBe(screen)+})++it.runIf(process.env.RUN_REAL_TMUX_DISCOVERY === '1')('closes only the exited client pane in a real private tmux server', async () => {+ const server = await isolatedTmux()+ const actualTmux = await vi.importActual<typeof import('./tmux.js')>('./tmux.js')+ const actualStop = await vi.importActual<typeof import('./deleteAgentFallback.js')>('./deleteAgentFallback.js')+ vi.stubEnv('TMUX', undefined)+ vi.stubEnv('TMUX_PANE', undefined)+ vi.stubEnv('TMUX_TMPDIR', server.root)+ vi.mocked(processRows).mockImplementation(actualTmux.processRows)+ vi.mocked(checkPidRuntime).mockImplementation(actualStop.checkPidRuntime)+ vi.mocked(terminateDeletedAgent).mockImplementation(actualStop.terminateDeletedAgent)+ killPane.mockImplementation(runtime => new TmuxBackend().kill(runtime))+ try {+ const sibling = await server.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', 'close-fixture', 'sleep 600')+ const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`+ const script = 'console.log("fixture Codex client"); setInterval(() => {}, 1000)'+ const pane = await server.run('split-window', '-h', '-P', '-F', '#{pane_id}', '-t', sibling,+ `${quote(process.execPath)} -e ${quote(script)}; exec /bin/sh`)+ const shellPid = Number(await server.run('display-message', '-p', '-t', pane, '#{pane_pid}'))+ await vi.waitFor(async () => {+ const child = (await processRows())?.find(process => process.parentPid === shellPid && process.args.includes('fixture Codex client'))+ expect(child).toBeDefined()+ row.processIdentity = { pid: child!.pid, executable: child!.executable, startMarker: child!.startMarker }+ })+ row.runtimes = [{ backend: 'tmux', paneId: pane }]+ const unrelatedServer = (await processRows())!.find(row => row.pid === process.pid)!+ writeFileSync(join(row.codexHome!, 'app-server-daemon', 'daemon.pid'), JSON.stringify({ pid: unrelatedServer.pid, processStartTime: unrelatedServer.startMarker }))+ // Signal only this fixture child; terminal Ctrl-C also reaches its shell.+ process.kill(row.processIdentity!.pid, 'SIGTERM')+ await vi.waitFor(async () => expect((await processRows())!.some(process => process.pid === row.processIdentity!.pid)).toBe(false))+ screen = await server.run('capture-pane', '-p', '-t', pane)+ const result = await service.request({ agentId: row.agentId, sessionId: '', createdAt: new Date(row.registeredAt).toISOString(), mode: 'now' })+ expect(result).toEqual({ closed: true })+ expect(await server.run('list-panes', '-t', 'close-fixture', '-F', '#{pane_id}')).toBe(sibling)+ expect(await server.run('display-message', '-p', '-t', sibling, '#{pane_dead}')).toBe('0')+ expect((await processRows())!.some(row => row.pid === unrelatedServer.pid)).toBe(true)+ } finally {+ await server.close()+ vi.unstubAllEnvs()+ }+}, 15_000)diff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dartindex 10b72c14b..bd2ff0d52 100644--- a/desktop/integration_test/native_workspace_e2e_test.dart+++ b/desktop/integration_test/native_workspace_e2e_test.dart@@ -1084,6 +1084,46 @@ void main() {},);+ testWidgets('native Cmd-N focuses the restored task without a click', (+ tester,+ ) async {+ final connection = _CreationConnection();+ final app = createApp(connectionForTest: (_) => connection);+ app.gitProjectReaderForTest = (_, _) async => {'isGit': false};+ seedMixedAgents(app);+ app.machineStates['m']!+ ..localOnly = true+ ..terminalCapabilityAvailable = true;+ await app.agentPreference.remember('codex');+ await app.agentPreference.selectLaunch('terminal');+ final terminalInput = <TerminalBinaryFrame>[];+ app.adoptSessionForTest(terminal('a0', terminalInput));+ addTearDown(app.dispose);+ addTearDown(connection.close);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(notifier: app, nativeTabs: true),+ ),+ );+ await tester.pump(const Duration(milliseconds: 200));+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);+ await tester.pumpAndSettle();+ final field = find.byKey(const ValueKey('new-harness-task'));+ expect(tester.widget<TextField>(field).focusNode!.hasPrimaryFocus, isTrue);+ final box = tester+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))+ .controller;+ expect(box.engine, 'codex');+ await tester.enterText(field, 'Ready to type');+ expect(box.task, 'Ready to type');+ expect(connection.creates, isEmpty);+ expect(terminalInput, isEmpty);+ await tester.tap(find.byKey(const ValueKey('new-harness-close')));+ await tester.pumpAndSettle();+ await tester.pumpWidget(const SizedBox());+ });+testWidgets('native first workspace offers the shared composer without starting work',(tester) async {diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex 0051c1f6a..5e93aadd2 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -153,7 +153,9 @@ class NewHarnessFormState extends State<NewHarnessForm> {box.useDesktopChoices(widget.desktop);if (box.checking) _row = _Row.start;_syncField();- (widget.desktop ? _desktopDefaultFocus : _focus).requestFocus();+ // Restoring the successful agent can replace an unfocusable Terminal+ // editor and its attachment wrappers. Let that rebuild finish first.+ _focusEditor();});}diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dartindex 961ce9d2d..8f30625f3 100644--- a/desktop/test/new_harness_entry_rules_test.dart+++ b/desktop/test/new_harness_entry_rules_test.dart@@ -722,6 +722,26 @@ void main() {await tester.pumpWidget(const SizedBox());});+ testWidgets('Cmd-N focuses the task after restoring the successful agent', (+ tester,+ ) async {+ await mount(tester, store: false);+ await app.agentPreference.selectLaunch('terminal');+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);+ await tester.pumpAndSettle();+ expect(box(tester).engine, 'codex');+ final task = tester.widget<TextField>(+ find.byKey(const ValueKey('new-harness-task')),+ );+ expect(task.focusNode!.hasPrimaryFocus, isTrue);+ tester.testTextInput.enterText('Type immediately after Cmd-N');+ await tester.pump();+ expect(box(tester).task, 'Type immediately after Cmd-N');+ expect(connections.values.expand((c) => c.starts), isEmpty);+ await dismiss(tester);+ await tester.pumpWidget(const SizedBox());+ });+testWidgets('Cmd-N follows the focused project and discards cancelled task edits',(tester) async {