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 restart pane loss and isolate desktop workspace tests (#597)

Dee769c001c1f54
diff --git a/cli/package.json b/cli/package.json
index 5cffdd2e3..052545b18 100644
--- a/cli/package.json
+++ b/cli/package.json
@@ -20,7 +20,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 --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/restartDiscovery.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/restartDiscovery.real.spec.ts b/cli/src/lib/restartDiscovery.real.spec.ts
new file mode 100644
index 000000000..75c3c7f59
--- /dev/null
+++ b/cli/src/lib/restartDiscovery.real.spec.ts
@@ -0,0 +1,53 @@
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'
+import { buildEngineLaunchArgv } from './engineLaunch.js'
+import { resolvePaneEngineProcess } from './tmux.js'
+
+let server: IsolatedTmux | undefined
+afterEach(async () => {
+ await server?.close()
+ server = undefined
+ vi.unstubAllEnvs()
+})
+
+describe.skipIf(process.env.RUN_REAL_TMUX_DISCOVERY !== '1')('restart startup discovery', () => {
+ it('waits past the capability probe for the real interactive process', async () => {
+ server = await isolatedTmux()
+ vi.stubEnv('TMUX_TMPDIR', server.root)
+ vi.stubEnv('TMUX', undefined)
+ vi.stubEnv('TMUX_PANE', undefined)
+ // No real engine or account: the normal launch wrapper probes a fake Codex
+ // in a private tmux server. Hold --help open to expose the restart race.
+ const binary = join(server.root, '@openai/codex/bin/codex.js')
+ const probe = join(server.root, 'probe')
+ const release = join(server.root, 'release')
+ const running = join(server.root, 'running')
+ await mkdir(join(server.root, '@openai/codex/bin'), { recursive: true })
+ await writeFile(binary, `#!${process.execPath}
+const fs = require('node:fs');
+if (process.argv.includes('--help')) {
+ fs.writeFileSync(${JSON.stringify(probe)}, String(process.pid));
+ setInterval(() => {
+ if (fs.existsSync(${JSON.stringify(release)})) {
+ console.log('--no-daemon'); process.exit(0);
+ }
+ }, 10);
+} else {
+ fs.writeFileSync(${JSON.stringify(running)}, String(process.pid));
+ setInterval(() => {}, 1000);
+}
+`, { mode: 0o755 })
+ const argv = buildEngineLaunchArgv('codex', { cwd: server.root }, '/bin/zsh')
+ argv[argv.indexOf('harness-engine') + 2] = binary
+ const pane = await server.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', 'restart-probe', ...argv)
+ await vi.waitFor(async () => expect(Number(await readFile(probe, 'utf8'))).toBeGreaterThan(0), { timeout: 5_000 })
+ expect(await resolvePaneEngineProcess(pane, 'codex')).toBeNull()
+ await writeFile(release, '')
+ await vi.waitFor(async () => {
+ const pid = Number(await readFile(running, 'utf8'))
+ expect(await resolvePaneEngineProcess(pane, 'codex')).toMatchObject({ pid })
+ }, { timeout: 8_000 })
+ }, 20_000)
+})
diff --git a/cli/src/lib/terminalAgentDiscovery.spec.ts b/cli/src/lib/terminalAgentDiscovery.spec.ts
index 60a543fb3..2fbafce9c 100644
--- a/cli/src/lib/terminalAgentDiscovery.spec.ts
+++ b/cli/src/lib/terminalAgentDiscovery.spec.ts
@@ -16,6 +16,25 @@ const nested: TerminalRootObservation = {
}
describe('process discovery', () => {
+ it('ignores the startup help probe and discovers only the subsequent Codex resume', () => {
+ const probe: ProcessRow = {
+ pid: 30, parentPid: 20, executable: 'node', startMarker: start,
+ args: 'node /opt/node_modules/@openai/codex/bin/codex.js --help',
+ }
+ const snapshot = (engine: ProcessRow) => discoverTerminalAgentsFromSnapshot(
+ [tmux], [shell(10, 1), shell(20, 10), engine], 999, ['tmux'],
+ )
+ expect(snapshot(probe).agents).toEqual([])
+ const live = snapshot({ ...probe, pid: 31,
+ args: 'node /opt/node_modules/@openai/codex/bin/codex.js --no-daemon resume 01234567-89ab-cdef-0123-456789abcdef',
+ })
+ expect(live.agents).toHaveLength(1)
+ expect(live.agents[0]).toMatchObject({
+ engine: 'codex', processIdentity: { pid: 31 },
+ resumeSessionId: '01234567-89ab-cdef-0123-456789abcdef',
+ })
+ })
+
it('deduplicates nested roots by engine PID and start marker', () => {
const result = discoverTerminalAgentsFromSnapshot(
[tmux, nested],
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index bf085505c..ed0fad3cd 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -154,6 +154,33 @@ describe('tmux process primitives', () => {
expect(engineProcessMatchScore({ executable: '/Users/demo/.grok/bin/grok', args: 'grok' }, 'grok')).toBe(3)
})
+ it.each([
+ 'codex --help',
+ '/opt/bin/codex -h',
+ 'codex --version',
+ 'codex -V',
+ 'node /opt/node_modules/@openai/codex/bin/codex.js --help',
+ 'node --require setup.js /opt/node_modules/@openai/codex/bin/codex.js --help',
+ 'env CODEX_HOME=/tmp/profile codex --help',
+ 'ori --log-level debug codex --help',
+ ])('does not adopt a capability probe as the restarted engine: %s', args => {
+ const commands: AgentCommandOwnershipSnapshot = {
+ ...ownership(), engineFileKeys: new Map([['codex', new Set(['codex-file'])]]),
+ }
+ // A known binary is still only a probe. File ownership must not override argv.
+ expect(engineProcessMatchScore({ executable: 'codex', args, imageFileKey: 'codex-file' }, 'codex', commands)).toBe(0)
+ })
+
+ it.each([
+ 'codex resume 01234567-89ab-cdef-0123-456789abcdef',
+ 'codex --no-daemon resume 01234567-89ab-cdef-0123-456789abcdef',
+ 'codex "explain --help"',
+ 'codex -- "--help"',
+ 'codex --model --help',
+ ])('keeps interactive launches and prompt text: %s', args => {
+ expect(engineProcessMatchScore({ executable: 'codex', args }, 'codex')).toBeGreaterThan(0)
+ })
+
it.each([
['codex', 'codex-aarch64-apple-darwin'],
['codex', 'codex-x86_64-unknown-linux-musl'],
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 7030a961e..c36d3425c 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -93,8 +93,7 @@ const INLINE_CODE_OPTIONS = new Set(['-c', '--command', '-e', '--eval', '--print
* shell in `comm`, so for those interpreters the first non-option token is the real entrypoint. Absolute
* prefixes are deliberately retained only for suffix/package-layout checks and are never hard-coded.
*/
-function processEntrypoint(args: string): string {
- const next = argvPrefix(args)
+function processEntrypoint(args: string, next = argvPrefix(args)): string {
let token = next() ?? ''
let command = basename(token).toLowerCase()
if (command === 'env') {
@@ -129,6 +128,18 @@ function processEntrypoint(args: string): string {
return token
}
+/** A launcher's capability check is not the interactive engine it is about to start.
+ * In particular, Codex startup runs `codex --help` before the real resume. Adopting
+ * that short-lived PID ends a restart too early and discovery then evicts its pane.
+ * Only a standalone probe argument counts: prompt text and option values do not. */
+function engineCapabilityProbe(args: string): boolean {
+ const next = argvPrefix(args)
+ if (!processEntrypoint(args, next)) return false
+ const option = next()
+ return (option === '--help' || option === '-h' || option === '--version' || option === '-V')
+ && next() === undefined
+}
+
function hasCursorPackageEntrypoint(args: string): boolean {
// Cursor's launcher uses `exec -a "$0" node .../index.js`, so argv[0] may stay `agent` instead of
// `node`. Restrict this scan to the executable prefix: prompt text can appear later and is not proof.
@@ -559,6 +570,7 @@ export function engineProcessMatch(
engine: RegisteredSession['engine'],
ownership = agentCommandOwnershipSnapshot(),
): EngineProcessMatch {
+ if (engineCapabilityProbe(row.args)) return { score: 0, evidence: 'none' }
const owners = engineFileOwners([row.imageFileKey, row.entrypointFileKey], ownership)
if (owners.length === 1) {
return owners[0] === engine
@@ -597,6 +609,7 @@ export function ambiguousAgentProcess(
row: Pick<ProcessRow, 'executable' | 'args' | 'imageFileKey' | 'entrypointFileKey'>,
ownership = agentCommandOwnershipSnapshot(),
): boolean {
+ if (engineCapabilityProbe(row.args)) return false
if (!agentAliasCandidate(row) || hasCursorPackageEntrypoint(row.args)) return false
const executable = basename(row.executable).toLowerCase()
const entrybase = basename(processEntrypoint(row.args)).toLowerCase()
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 766bd4530..9f10a3334 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -5,6 +5,7 @@ import 'package:dio/dio.dart';
import '../auth/auth_session.dart';
import '../core/config.dart';
import '../core/models.dart';
+import '../core/test_run.dart';
import '../logging/http_log.dart';
import '../viewer/device_log.dart';
import '../viewer/device_log_sync.dart' show DeviceLogAppendAnswer, DeviceLogFetched;
@@ -57,6 +58,37 @@ class ApiClient {
),
),
);
+ if (kUnderTest) {
+ // Plain Dart tests do not install Flutter's HTTP override. A partial API
+ // fake can otherwise inherit desk()/deskOps() and seed fixture tabs into
+ // the signed-in user's real account through the local daemon.
+ dio.interceptors.insert(
+ 0,
+ InterceptorsWrapper(
+ onRequest: (options, handler) {
+ final uri = options.uri;
+ final fixture =
+ (uri.scheme == 'http' || uri.scheme == 'https') &&
+ const {'127.0.0.1', 'localhost', '::1'}.contains(uri.host) &&
+ uri.hasPort &&
+ uri.port != Uri.parse(AppConfig.dev.localCliBaseUrl).port;
+ if (fixture) {
+ handler.next(options);
+ } else {
+ handler.reject(
+ DioException(
+ requestOptions: options,
+ error: StateError(
+ 'Tests must use a fake API or an isolated local server; '
+ 'access to live services is disabled.',
+ ),
+ ),
+ );
+ }
+ },
+ ),
+ );
+ }
final transport = localTransport;
if (auth == null && transport != null) {
dio.httpClientAdapter = LocalDaemonHttpAdapter(
diff --git a/desktop/test/api_client_test.dart b/desktop/test/api_client_test.dart
index 7e5721f11..5d2c50ac8 100644
--- a/desktop/test/api_client_test.dart
+++ b/desktop/test/api_client_test.dart
@@ -8,6 +8,50 @@ import 'package:harness/core/config.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
+ // Deliberately plain tests: no widget binding's HTTP override to hide the
+ // account-lifecycle fixture's inherited calls into the real local daemon.
+ for (final url in [
+ AppConfig.dev.localCliBaseUrl,
+ 'http://localhost:18473',
+ 'http://[::1]:18473',
+ AppConfig.defaultApiUrl,
+ ]) {
+ test(
+ 'test API refuses live reads and writes before opening HTTP: $url',
+ () async {
+ var clients = 0;
+ await HttpOverrides.runZoned(
+ () async {
+ final api = ApiClient(
+ config: AppConfig(
+ apiBaseUrl: AppConfig.defaultApiUrl,
+ localCliBaseUrl: url,
+ ),
+ session: AuthSession(),
+ );
+ final blocked = isA<DioException>().having(
+ (error) => error.error.toString(),
+ 'reason',
+ contains('access to live services is disabled'),
+ );
+ await expectLater(api.desk(), throwsA(blocked));
+ await expectLater(
+ api.deskOps([
+ {'op': 'seed', 'tabs': []},
+ ]),
+ throwsA(blocked),
+ );
+ expect(clients, 0);
+ },
+ createHttpClient: (_) {
+ clients++;
+ throw StateError('A test attempted to open a real HTTP client');
+ },
+ );
+ },
+ );
+ }
+
test(
'account experiment writes include identity and the local proxy header',
() async {
diff --git a/desktop/test/workspace_account_lifecycle_test.dart b/desktop/test/workspace_account_lifecycle_test.dart
index 948c71471..465a440e8 100644
--- a/desktop/test/workspace_account_lifecycle_test.dart
+++ b/desktop/test/workspace_account_lifecycle_test.dart
@@ -61,6 +61,8 @@ class _Api extends ApiClient {
var inventoryRequests = 0;
Object? inventoryFailure;
@override
+ Future<Map<String, dynamic>?> desk() async => null;
+ @override
Future<Map<String, dynamic>?> me() async => {
'user': {'id': 'fixture-account', 'email': '[email protected]'},
};