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.

Continue Harness Codex resumes in restricted mode (#3406)

harness-for-autonomous[bot]e052e399e41c
diff --git a/cli/src/engines/codex/openRestricted.spec.ts b/cli/src/engines/codex/openRestricted.spec.ts
index 592147c7c..a70a4839a 100644
--- a/cli/src/engines/codex/openRestricted.spec.ts
+++ b/cli/src/engines/codex/openRestricted.spec.ts
@@ -2,29 +2,33 @@ import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { openRestrictedKeys, screen } from './screen.js'
-/** As codex-cli 0.165.0 drew them in a tmux pane (2026-11-05, task #3009): a Team-written start's empty engine home with no
- * entry for its checkout, and the same home naming the checkout `untrusted`. */
+/** Real tmux captures: 0.165 on 2026-11-05 (#3009), and 0.166 on Linux on 2026-11-06 (#3904). */
const fixture = (name: string) => readFileSync(new URL(`../../superTabs/fixtures/screens/${name}.txt`, import.meta.url), 'utf8')
-const RESTRICTED = fixture('codex-0165-open-restricted')
const TRUST = fixture('codex-0165-trust-fresh-home')
// "Open restricted" keeps the folder's config, hooks and exec policies off and saves no trust: the answer an untrusted
// Team-written branch gets. "Trust and continue" would trust the branch, so nothing is ever sent on that screen.
-describe('opening an untrusted folder restricted in Codex', () => {
+describe.each([
+ { version: '0165', secondRow: 'Quit', escape: 'quit' },
+ { version: '0166', secondRow: 'Back to Agent Command Center', escape: 'back' },
+])('opening an untrusted folder restricted in Codex $version', ({ version, secondRow, escape }) => {
+ const RESTRICTED = fixture(`codex-${version}-open-restricted`)
+ const footer = `enter continue · esc ${escape}`
it('answers the restricted screen with Enter on its highlighted first row', () => {
expect(openRestrictedKeys(RESTRICTED)).toEqual(['Enter'])
})
it.each([
['the trust screen, whose first row trusts the folder', TRUST],
- ['Quit highlighted instead', RESTRICTED.replace('› 1. Open restricted', ' 1. Open restricted').replace(' 2. Quit', '› 2. Quit')],
- ['rows in another order', RESTRICTED.replace('› 1. Open restricted\n 2. Quit', '› 1. Quit\n 2. Open restricted')],
- ['an extra row', RESTRICTED.replace(' 2. Quit', ' 2. Quit\n 3. Trust and continue')],
- ['a missing Quit row', RESTRICTED.replace(' 2. Quit\n', '')],
+ ['the second row highlighted instead', RESTRICTED.replace('› 1. Open restricted', ' 1. Open restricted').replace(` 2. ${secondRow}`, `› 2. ${secondRow}`)],
+ ['rows in another order', RESTRICTED.replace(`› 1. Open restricted\n 2. ${secondRow}`, `› 1. ${secondRow}\n 2. Open restricted`)],
+ ['an extra row', RESTRICTED.replace(` 2. ${secondRow}`, ` 2. ${secondRow}\n 3. Trust and continue`)],
+ ['a missing second row', RESTRICTED.replace(` 2. ${secondRow}\n`, '')],
['no sentence saying untrusted folders stay disabled', RESTRICTED.replace('Config, hooks, and exec policies from untrusted folders stay disabled.', 'Folder settings will apply.')],
['a trust question on the same screen', `${TRUST}\n${RESTRICTED}`],
- ['another footer', RESTRICTED.replace('enter continue · esc quit', 'enter continue · esc skip')],
- ['no footer', RESTRICTED.replace('\n\n enter continue · esc quit', '')],
+ ['another footer', RESTRICTED.replace(footer, 'enter continue · esc skip')],
+ ['the other version\'s footer', RESTRICTED.replace(footer, `enter continue · esc ${escape === 'quit' ? 'back' : 'quit'}`)],
+ ['no footer', RESTRICTED.replace(`\n\n ${footer}`, '')],
['the screen left in scrollback above the composer', `${RESTRICTED}\n\n› Write tests\n gpt-6-astra high · ~/project\n`],
])('sends nothing on %s', (_name, capture) => {
expect(openRestrictedKeys(capture)).toBeNull()
diff --git a/cli/src/engines/codex/screen.ts b/cli/src/engines/codex/screen.ts
index bbf039272..7164ab4cc 100644
--- a/cli/src/engines/codex/screen.ts
+++ b/cli/src/engines/codex/screen.ts
@@ -49,8 +49,8 @@ export function updateDismissKeys(capture: string): string[] | null {
}
/**
- * The key that opens an untrusted folder restricted, or null unless the capture is exactly Codex's screen for it. Only for a
- * Team-written Swarm start (superTabs/machines.ts), whose engine home names its checkout untrusted (superTabs/start.ts): in
+ * The key that opens an untrusted folder restricted, or null unless the capture is exactly Codex's screen for it. For a
+ * Swarm start or resume, whose engine home names its checkout untrusted (superTabs/start.ts): in
* a home that names nothing, codex-cli 0.165 asks "Trust this folder?" instead, nobody answers it, and every such start
* timed out at 3 minutes (task #3009). "Open restricted" keeps the folder's config, hooks and exec policies off and saves no
* trust, which is what that home is for. It is Enter on the highlighted first row, so the screen must say so word for word:
@@ -63,8 +63,12 @@ export function openRestrictedKeys(capture: string): string[] | null {
const text = lines.join(' ')
if (/Trust this folder\?|Do you trust the contents/.test(text) || !text.includes(RESTRICTED_SENTENCE)) return null
const rows = lines.filter(line => /^[›>]?\s*\d+\./.test(line))
- const menu = rows.length === 2 && /^[›>]\s*1\. Open restricted$/.test(rows[0]) && rows[1] === '2. Quit'
- return menu && lines[lines.length - 1] === 'enter continue · esc quit' ? ['Enter'] : null
+ if (rows.length !== 2 || !/^[›>]\s*1\. Open restricted$/.test(rows[0])) return null
+ const footer = lines[lines.length - 1]
+ // 0.166 returns to Agent Command Center instead of quitting (#3904); both screens open restricted with Enter.
+ const menu = (rows[1] === '2. Quit' && footer === 'enter continue · esc quit')
+ || (rows[1] === '2. Back to Agent Command Center' && footer === 'enter continue · esc back')
+ return menu ? ['Enter'] : null
}
const RESTRICTED_SENTENCE = 'Config, hooks, and exec policies from untrusted folders stay disabled.'
diff --git a/cli/src/superTabs/fixtures/screens/codex-0166-open-restricted.txt b/cli/src/superTabs/fixtures/screens/codex-0166-open-restricted.txt
new file mode 100644
index 000000000..9cf235151
--- /dev/null
+++ b/cli/src/superTabs/fixtures/screens/codex-0166-open-restricted.txt
@@ -0,0 +1,11 @@
+
+ Folder access
+ /tmp/throwaway/repo
+
+ Config, hooks, and exec policies from untrusted folders stay disabled. Trusted project folders can still contribute
+ settings. Skills still load, and tools follow your permission settings. Opening will not change saved trust.
+
+› 1. Open restricted
+ 2. Back to Agent Command Center
+
+ enter continue · esc back
diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.ts
index 64c23e585..20495c24b 100644
--- a/cli/src/superTabs/machines.spec.ts
+++ b/cli/src/superTabs/machines.spec.ts
@@ -2957,11 +2957,12 @@ describe('a launched start whose engine stops on a screen', () => {
/** Two passes, 16 s apart: a screen fails a start only when two reads in a row show it the same (security review 1 of #3063). */
const twice = async (f: ReturnType<typeof fixture>) => { await f.machine.tick(); f.advance(); await f.machine.tick() }
- it('opens a Team-written Codex start\'s untrusted checkout restricted, with Enter on that exact screen alone', async () => {
- const { f, screen, inputIfScreen, failures } = launched(RESTRICTED, 'trust_open')
+ it.each(['0165', '0166'])('opens a Team-written Codex %s start\'s untrusted checkout restricted, with Enter on that exact screen alone', async version => {
+ const restricted = screens(`codex-${version}-open-restricted`)
+ const { f, screen, inputIfScreen, failures } = launched(restricted, 'trust_open')
await f.machine.tick()
expect(screen).toHaveBeenCalledWith('launched', 0)
- expect(inputIfScreen).toHaveBeenCalledWith('launched', ['Enter'], RESTRICTED)
+ expect(inputIfScreen).toHaveBeenCalledWith('launched', ['Enter'], restricted)
expect(failures()).toEqual([])
})
diff --git a/cli/src/superTabs/terminal.spec.ts b/cli/src/superTabs/terminal.spec.ts
index 2add33c98..b4de85cd6 100644
--- a/cli/src/superTabs/terminal.spec.ts
+++ b/cli/src/superTabs/terminal.spec.ts
@@ -1,4 +1,11 @@
-import { readFileSync } from 'node:fs'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { spawn } from 'node:child_process'
+import { createInterface } from 'node:readline'
+import { createSuperTabTerminal } from './inCore/terminal.js'
+import { screen as codexScreen } from '../engines/codex/screen.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import type { CoreApi, SuperTabScreen } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
@@ -651,3 +658,81 @@ describe('reading a model that keeps failing off a screen', () => {
expect(modelFailing(`I will make the client say "Unable to connect to API" when the relay is down.\n${'line\n'.repeat(30)}> `)).toBe(false)
})
})
+
+// #3904: a resumed Swarm Codex already has an identity, so startup settlement never sees its folder prompt.
+describe.each([
+ { version: '0165', secondRow: 'Quit' },
+ { version: '0166', secondRow: 'Back to Agent Command Center' },
+])('opening a Swarm Codex folder restricted after start or resume ($version)', ({ version, secondRow }) => {
+ const restricted = fixture(`codex-${version}-open-restricted`)
+ it.each(['start', 'resume'])('continues a fake Codex %s without granting trust', async (mode) => {
+ const home = mkdtempSync(join(tmpdir(), 'codex-restricted-'))
+ const config = join(home, 'config.toml')
+ const savedConfig = '[projects."/worktree"]\ntrust_level = "untrusted"\n'
+ writeFileSync(config, savedConfig)
+ // A separate fake engine waits on input on both startup paths, reading only its disposable home.
+ const child = spawn(process.execPath, ['--input-type=module', '-e', `
+ import { readFileSync } from 'node:fs';
+ import { createInterface } from 'node:readline';
+ const [mode, config, prompt] = process.argv.slice(1);
+ if (!['start', 'resume'].includes(mode) || !readFileSync(config, 'utf8').includes('"untrusted"')) process.exit(1);
+ console.log(JSON.stringify(prompt));
+ createInterface({ input: process.stdin }).on('line', key => {
+ if (key === 'Enter') console.log(JSON.stringify('› Ask Codex to do anything'));
+ });
+ `, mode, config, restricted], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true })
+ const lines = createInterface({ input: child.stdout })[Symbol.asyncIterator]()
+ const nextScreen = async () => {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ const line = await Promise.race([lines.next(), new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('Fake Codex did not draw its next screen')), 2_000)
+ })])
+ if (line.done) throw new Error('Fake Codex exited before drawing its screen')
+ return JSON.parse(line.value) as string
+ } finally { clearTimeout(timer) }
+ }
+ try {
+ let capture = await nextScreen()
+ const t = setup({ engine: 'codex' })
+ const terminal = createSuperTabTerminal({
+ resolve: id => id === 'h1' ? { agentId: id, engine: 'codex' } as RegisteredSession : undefined,
+ capture: async () => ({ state: 'succeeded', value: capture }),
+ read: async (_session, text) => codexScreen.inspect(text ?? ''),
+ type: async () => false,
+ key: async (_id, key) => { child.stdin.write(`${key}\n`); capture = await nextScreen(); return true },
+ locked: async (_id, write) => write(),
+ })
+ Object.assign(t.core.superTabs!, terminal)
+ await t.host.tick([row()])
+ expect(capture).toBe('› Ask Codex to do anything')
+ expect(readFileSync(config, 'utf8')).toBe(savedConfig)
+ t.wait(180_000); await t.host.tick([row()])
+ expect(t.alerts()).toEqual([])
+ } finally {
+ child.kill()
+ rmSync(home, { recursive: true, force: true })
+ }
+ })
+
+ it.each([
+ ['trust grant', CODEX_TRUST_PROMPT, 'codex', [row()]],
+ ['another engine', restricted, 'claude', [row()]],
+ ['personal session outside the roster', restricted, 'codex', []],
+ ['the second row highlighted', restricted.replace('› 1. Open restricted', ' 1. Open restricted').replace(` 2. ${secondRow}`, `› 2. ${secondRow}`), 'codex', [row()]],
+ ])('never types on %s', async (_name, text, engine, rows) => {
+ const t = setup({ engine, screen: () => ({ ok: true, text, hold: 'trust_open' }) })
+ await t.host.tick(rows)
+ expect(t.core.superTabs!.inputIfScreen).not.toHaveBeenCalled()
+ })
+
+ it('bounds failed conditional inputs and alerts when the prompt persists', async () => {
+ const t = setup({ engine: 'codex', screen: () => ({ ok: true, text: restricted, hold: 'trust_open' }) })
+ vi.mocked(t.core.superTabs!.inputIfScreen).mockResolvedValue({ ok: false, error: 'Screen changed.' })
+ for (let i = 0; i < 5; i++) { await t.host.tick([row()]); t.wait(15_000) }
+ expect(t.core.superTabs!.inputIfScreen).toHaveBeenCalledTimes(3)
+ expect(t.core.superTabs!.inputIfScreen).toHaveBeenCalledWith('h1', ['Enter'], restricted)
+ t.wait(180_000); await t.host.tick([row()])
+ expect(t.alerts()).toContainEqual(expect.objectContaining({ alert: 'prompt', active: true }))
+ })
+})
diff --git a/cli/src/superTabs/terminal.ts b/cli/src/superTabs/terminal.ts
index 826319bd7..8dc0f90d0 100644
--- a/cli/src/superTabs/terminal.ts
+++ b/cli/src/superTabs/terminal.ts
@@ -10,7 +10,7 @@
import { CommandRetries, permanentRefusal } from './retries.js'
import { createHash } from 'node:crypto'
import type { CoreApi, SuperTabScreen } from '../core/api.js'
-import { updateDismissKeys } from '../engines/codex/screen.js'
+import { openRestrictedKeys, updateDismissKeys } from '../engines/codex/screen.js'
import { feedbackDismissKeys } from '../engines/claude/screen.js'
import type { MessageHold } from '../engines/facets/screen.js'
import { backend } from './host.js'
@@ -29,7 +29,7 @@ export const SERVE_EVERY_MS = 3_000
/** A screen read per agent; the 3-minute prompt wait does not need it finer. */
const WATCH_EVERY_MS = 15_000
const PROMPT_WAIT_MS = 3 * 60_000
-/** How often Skip is typed for one stuck update screen before the 3-minute alert is left to say it did not work. */
+/** How often a safe dismissal is tried before the 3-minute alert is left to say it did not work. */
const SKIP_TRIES = 3
/** The spec's cap on what a screen read returns. */
const MAX_SCREEN_BYTES = 64 * 1024
@@ -340,7 +340,7 @@ export class TerminalHost {
// A screen that could not be read says nothing either way.
const read = await this.core.superTabs!.screen(agent.harnessId, 0).catch(() => null)
if (!read?.ok) continue
- state.skips = await this.skipUpdate(agent, read, state.skips ?? 0)
+ state.skips = await this.dismissScreen(agent, read, state.skips ?? 0)
const now = this.now()
const digest = screenDigest(read.text), seen = this.progress.get(agent.harnessId)
const failing = unanswered(read.text)
@@ -364,19 +364,20 @@ export class TerminalHost {
}
}
- /** Codex's "Update available" screen on a Swarm agent's terminal, where no one will answer it and its task waits: Esc, through
- * the core's door that types only while the screen is still exactly the one read here, so a screen another writer cleared
- * meanwhile gets nothing (superTabs/inCore/terminal.ts `inputIfScreen`). Never a row number and Enter (on a misread row
- * that could run the update), and only a screen read as exactly that prompt (engines/codex/screen.ts `updateDismissKeys`).
- * After [SKIP_TRIES] the 3-minute alert takes over. Returns the tries made for this screen, none once it is gone. The held
- * task goes on by itself: the mailbox types it again once the prompt is gone. */
- private async skipUpdate(agent: Own, read: Extract<SuperTabScreen, { ok: true }>, tries: number): Promise<number> {
- // Codex's update screen, or one of Claude Code's own feedback popups (engines/claude/screen.ts feedbackDismissKeys).
- const keys = read.hold === 'update_prompt_open' ? updateDismissKeys(read.text) : feedbackDismissKeys(read.text)
+ /** Safe choices on an unattended Swarm pane: skip an update or feedback popup, or open Codex restricted.
+ * The core rechecks the exact screen under its input lock, so another writer clearing it receives no stray key.
+ * After [SKIP_TRIES] the existing prompt alert takes over; the mailbox resumes once the screen is gone. */
+ private async dismissScreen(agent: Own, read: Extract<SuperTabScreen, { ok: true }>, tries: number): Promise<number> {
+ // Resumes already have a session identity, so startScreen cannot settle their folder-access prompt (#3904).
+ // Only the exact restricted choice is safe; never answer a trust grant or another engine's screen.
+ const restricted = read.hold === 'trust_open' && this.core.agents.byAgent(agent.harnessId)?.engine === 'codex'
+ ? openRestrictedKeys(read.text) : null
+ const keys = restricted ?? (read.hold === 'update_prompt_open' ? updateDismissKeys(read.text) : feedbackDismissKeys(read.text))
if (!keys) return 0
if (tries >= SKIP_TRIES) return tries
const dismissed = await this.core.superTabs!.inputIfScreen(agent.harnessId, keys, read.text).catch(error => ({ ok: false as const, error: String(error) }))
if (!dismissed.ok) this.log(`could not dismiss a screen for ${agent.agentId}: ${dismissed.error}`)
+ else if (restricted) this.log(`Opened Codex restricted for ${agent.agentId}; no folder trust granted`)
return tries + 1
}
diff --git a/docs/plans/2026-11-06-codex-restricted-resume-plan.md b/docs/plans/2026-11-06-codex-restricted-resume-plan.md
new file mode 100644
index 000000000..44b9158a2
--- /dev/null
+++ b/docs/plans/2026-11-06-codex-restricted-resume-plan.md
@@ -0,0 +1,39 @@
+# Codex restricted resume implementation plan
+
+> Implement task by task in this Engineer session, test first, with independent pull request reviews.
+
+**Goal:** Harness-run Codex starts and resumes continue past Open restricted without granting folder trust.
+**Architecture:** Reuse the exact-screen Codex recognizer and the core's conditional input door in the existing Swarm terminal watcher. The startup handler remains responsible for pre-session starts; the watcher handles resumed sessions.
+**Tech Stack:** TypeScript, Vitest, fake Codex terminal.
+**Spec:** Harness task #3904, conversation 10f805b0f0832aaf73da073d.
+
+## Global Constraints
+
+- Never mark a worktree trusted or enable untrusted config, hooks or exec policies.
+- Only Harness Swarm agents; personal sessions outside Harness are unaffected.
+- Two independent security reviewers must review sandbox and trust boundaries.
+- Bounded retries, conditional input against the exact captured screen, no new polling.
+- Platforms: macOS, Linux, Windows; no process launch behavior changes.
+
+## Design
+
+No new stored or exposed data. Growth, locking, read cost, scale, compatibility, migration, rollback, audience and identity: existing bounded Swarm terminal watch and conditional input contracts remain in use. Failure: after bounded attempts the existing visible prompt alert applies. Rollback: revert the watcher change.
+
+## Review Focus
+
+- A Trust and continue prompt must receive no input.
+- Changed or malformed screens must receive no input.
+- Other engines and sessions outside the Swarm roster must receive no input.
+- A stuck prompt must stop automatic attempts and retain the existing alert.
+- Fresh and resumed fake Codex sessions must continue with saved trust unchanged.
+
+## Task 1: Continue restricted Codex sessions in the Swarm watcher
+
+**Files:** Modify `cli/src/superTabs/terminal.ts`; test `cli/src/superTabs/terminal.spec.ts`; reuse `cli/src/engines/codex/screen.ts` and its tests.
+**Interfaces:** Consume `openRestrictedKeys(capture: string): string[] | null` and `inputIfScreen(harnessId, keys, capture)`; retain `TerminalHost.tick` API.
+
+- [ ] Add fake Codex start/resume tests that wait for Enter and then expose a working composer; assert no trust/config change. Cover wrong engine, non-roster session, trust prompt, changed screen and bounded attempts.
+- [ ] Commit tests; run affected tests and record the expected failure.
+- [ ] Extend the existing bounded dismissal path only for a Codex agent and the exact restricted screen.
+- [ ] Run affected terminal, engine recognizer and startup tests, typecheck, and compare watcher timing on the same idle workload before/after. Commit implementation.
+- [ ] Push draft, record red/green evidence, mark ready and hand off for two security reviews and platform testing.