From 5016254395dee6c784b4fc408a67fe3fcd844e6a Mon Sep 17 00:00:00 2001 From: Zubair Ahsan Date: Mon, 7 Sep 2026 18:47:37 +0800 Subject: [PATCH 1/3] fix: retire closed Codex model picker permission observations --- src/main/runtime/orca-runtime-core.ts | 2 +- ...runtime-create-agent-prompt-render-gate.ts | 9 +- ...a-runtime-get-terminal-interactive-wait.ts | 1 + src/main/runtime/orca-runtime-runtime-id.ts | 2 + .../orca-runtime-stop-requested-pty-ids.ts | 7 + .../orca-runtime-terminal-projection.ts | 7 +- ...rca-runtime-write-terminal-agent-prompt.ts | 5 +- .../runtime-terminal-agent-status-query.ts | 56 ++++- .../runtime/runtime-terminal-idle-polls.ts | 6 +- .../runtime/runtime-terminal-state-records.ts | 1 + src/main/runtime/runtime-terminal-wait.ts | 22 +- .../terminal-codex-modal-observation.test.ts | 65 ++++++ .../terminal-codex-modal-observation.ts | 76 +++++++ .../terminal-codex-modal-runtime.test.ts | 208 ++++++++++++++++++ 14 files changed, 437 insertions(+), 30 deletions(-) create mode 100644 src/main/runtime/terminal-codex-modal-observation.test.ts create mode 100644 src/main/runtime/terminal-codex-modal-observation.ts create mode 100644 src/main/runtime/terminal-codex-modal-runtime.test.ts diff --git a/src/main/runtime/orca-runtime-core.ts b/src/main/runtime/orca-runtime-core.ts index 8214f7506761..e85e4af37449 100644 --- a/src/main/runtime/orca-runtime-core.ts +++ b/src/main/runtime/orca-runtime-core.ts @@ -97,7 +97,7 @@ export const PROVEN_ABSENT_LEAF_PTY_TTL_MS = 15_000 export const TERMINAL_INTERACTIVE_WAIT_PROBE_TIMEOUT_MS = 2_000 -export type RuntimeTerminalProjection = { lines: string[]; draft?: string } +export type RuntimeTerminalProjection = { lines: string[]; draft?: string; codexComposer?: boolean } export function assertAgentPromptRequestActive(signal?: AbortSignal): void { if (signal?.aborted) { diff --git a/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts b/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts index 6afde0468301..6cedd543f63d 100644 --- a/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts +++ b/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts @@ -128,7 +128,7 @@ export class OrcaRuntimeWithCreateAgentPromptRenderGate extends OrcaRuntimeWithW } } - waitForTerminal( + async waitForTerminal( handle: string, options?: { condition?: RuntimeTerminalWaitCondition @@ -136,6 +136,13 @@ export class OrcaRuntimeWithCreateAgentPromptRenderGate extends OrcaRuntimeWithW signal?: AbortSignal } ): Promise { + if (options?.condition === 'tui-idle') { + const ptyId = this.getTerminalAgentStatusPtyId(handle) + await this.terminalAgentStatus.refreshModal(handle, ptyId) + if (this.terminalAgentStatus.isModalComposerReady(handle)) { + return this.buildTuiIdleProbeResult(handle, null) + } + } return this.terminalWait.wait(handle, options) } } diff --git a/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts b/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts index f428404de900..d9218ddf952d 100644 --- a/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts +++ b/src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts @@ -22,6 +22,7 @@ export class OrcaRuntimeWithGetTerminalInteractiveWait extends OrcaRuntimeWithAd let terminal: RuntimeTerminalAgentStatusSnapshot try { ptyId = this.getTerminalAgentStatusPtyId(handle) + await this.terminalAgentStatus.refreshModal(handle, ptyId) terminal = this.getTerminalAgentStatusSnapshot(handle, ptyId) } catch { return undefined diff --git a/src/main/runtime/orca-runtime-runtime-id.ts b/src/main/runtime/orca-runtime-runtime-id.ts index 2d56a587c08c..68e47506af3b 100644 --- a/src/main/runtime/orca-runtime-runtime-id.ts +++ b/src/main/runtime/orca-runtime-runtime-id.ts @@ -279,6 +279,7 @@ export class OrcaRuntimeWithRuntimeId { intervalMs: TUI_IDLE_POLL_INTERVAL_MS, quiescenceMs: TUI_IDLE_QUIESCENCE_MS, getTabTitle: (tabId) => this.tabs.get(tabId)?.title ?? null, + getWaitText: (record) => this.terminalAgentStatus.getWaitText(record, record.ptyId), getForegroundProcess: (ptyId) => this.ptyController?.getForegroundProcess(ptyId) ?? null, getAdoptedPtyIdleStatus: (pty) => this.getAdoptedPtyExplicitIdleStatus(pty), resolve: (waiter, result) => this.terminalWaiters.resolve(waiter, result) @@ -291,6 +292,7 @@ export class OrcaRuntimeWithRuntimeId { getLiveLeaf: (handle) => this.getLiveLeafForHandle(handle), getAdoptedPtyIdleStatus: (pty) => this.getAdoptedPtyExplicitIdleStatus(pty), getTabTitle: (tabId) => this.tabs.get(tabId)?.title ?? null, + getWaitText: (record) => this.terminalAgentStatus.getWaitText(record, record.ptyId), startVisibleReadProbe: (waiter, waiterTimeoutMs) => this.startTuiIdleVisibleReadProbe(waiter, waiterTimeoutMs) }, diff --git a/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts b/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts index 233e739911bf..f9ffdba380f4 100644 --- a/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts +++ b/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts @@ -154,6 +154,13 @@ export class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWithRuntimeId }) protected readonly terminalAgentStatus = new RuntimeTerminalAgentStatusQuery({ + getModalFence: (ptyId) => ({ + generation: this.getPtyLifecycleGeneration(ptyId), + outputSequence: this.getPtyOutputSequence(ptyId), + permissionSequence: this.agentPromptPermissionSequenceByPtyId.get(ptyId) ?? 0 + }), + readVisibleState: (ptyId) => this.readVisibleTerminalState(ptyId), + isCodex: (ptyId) => this.getPtyAgent(ptyId) === 'codex', getController: () => this.ptyController, getLivePty: (handle) => this.getLivePtyForHandle(handle), getLiveLeaf: (handle) => this.getLiveLeafForHandle(handle), diff --git a/src/main/runtime/orca-runtime-terminal-projection.ts b/src/main/runtime/orca-runtime-terminal-projection.ts index 7bd45bbfb51d..9d765ab21c22 100644 --- a/src/main/runtime/orca-runtime-terminal-projection.ts +++ b/src/main/runtime/orca-runtime-terminal-projection.ts @@ -1,4 +1,7 @@ -import { detectTerminalComposerDraft } from '../../shared/terminal-composer-draft' +import { + detectTerminalComposerDraft, + hasTerminalComposerPlaceholder +} from '../../shared/terminal-composer-draft' import type { HeadlessEmulator } from '../daemon/headless-emulator' import { visibleNonBlankTerminalLines } from './terminal-tail-read' @@ -27,6 +30,7 @@ export function projectTerminalTailLines( export function projectTerminalVisibleLines(emulator: HeadlessEmulator): { lines: string[] draft?: string + codexComposer: boolean } { const visible = emulator.getVisibleLines() const draft = detectTerminalComposerDraft(emulator.getCursorLineContext()) @@ -38,6 +42,7 @@ export function projectTerminalVisibleLines(emulator: HeadlessEmulator): { } return { lines: visibleNonBlankTerminalLines(visible), + codexComposer: hasTerminalComposerPlaceholder(emulator.getCursorLineContext()), ...(draft ? { draft: draft.text } : {}) } } diff --git a/src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts b/src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts index a2c40a08bdc4..2fa76b2fef22 100644 --- a/src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts +++ b/src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts @@ -28,8 +28,11 @@ export class OrcaRuntimeWithWriteTerminalAgentPrompt extends OrcaRuntimeWithReso ): Promise { assertAgentPromptRequestActive(options.signal) this.assertAgentPromptGeneration(ptyId, generation) + const observationBaseline = this.getAgentPromptActivity(handle, ptyId) + await this.terminalAgentStatus.refreshModal(handle, ptyId) + this.assertAgentPromptGeneration(ptyId, generation) const permissionBaseline = this.getAgentPromptActivity(handle, ptyId) - this.assertAgentPromptPermissionSafe(permissionBaseline, permissionBaseline) + this.assertAgentPromptPermissionSafe(observationBaseline, permissionBaseline) const admitted = agentSessionPtyWriteGate.assertAdmitted(ptyId) const writeHostPlatform = this.getPtyWriteHostPlatform(ptyId) const pasteByteLength = Buffer.byteLength(pastePayload, 'utf8') diff --git a/src/main/runtime/runtime-terminal-agent-status-query.ts b/src/main/runtime/runtime-terminal-agent-status-query.ts index 5a06ea3f688b..8a6e31d7afd0 100644 --- a/src/main/runtime/runtime-terminal-agent-status-query.ts +++ b/src/main/runtime/runtime-terminal-agent-status-query.ts @@ -16,6 +16,12 @@ import { import { detectTerminalWaitBlockedReason } from './terminal-wait-detection' import { getTerminalState } from './terminal-wait-results' import { buildTerminalWaitText } from './terminal-wait-tail-state' +import { + TerminalCodexModalObservation, + hasCodexModelPickerTail, + type TerminalModalFence +} from './terminal-codex-modal-observation' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' export type RuntimeTerminalAgentStatusSnapshot = { waitText: string @@ -26,6 +32,9 @@ export type RuntimeTerminalAgentStatusSnapshot = { } type Dependencies = { + getModalFence(ptyId: string): TerminalModalFence + readVisibleState(ptyId: string): Promise + isCodex(ptyId: string): boolean getController(): RuntimePtyController | null getLivePty(handle: string): { pty: RuntimePtyWorktreeRecord } | null getLiveLeaf(handle: string): { leaf: RuntimeLeafRecord } @@ -41,6 +50,7 @@ type Dependencies = { } export class RuntimeTerminalAgentStatusQuery { + private readonly modal = new TerminalCodexModalObservation() private readonly inFlight = new Map>() constructor(private readonly deps: Dependencies) {} @@ -63,6 +73,7 @@ export class RuntimeTerminalAgentStatusQuery { private async readStatus(handle: string): Promise { const ptyId = this.getPtyId(handle) + await this.refreshModal(handle, ptyId) const terminal = this.getSnapshot(handle, ptyId) const explicitStatus = this.deps.getExplicitStatus(handle) const lifecycle = this.deps.getLifecycleStatus(ptyId) @@ -129,6 +140,43 @@ export class RuntimeTerminalAgentStatusQuery { return { handle, isRunningAgent, status: null } } + async refreshModal(handle: string, ptyId: string): Promise { + if (!this.deps.isCodex(ptyId)) { + return + } + const snapshot = this.getSnapshot(handle, ptyId) + if (!hasCodexModelPickerTail(snapshot.waitText)) { + return + } + const record = this.deps.getLivePty(handle)?.pty ?? this.deps.getLiveLeaf(handle).leaf + const before = this.deps.getModalFence(ptyId) + const screen = await this.deps.readVisibleState(ptyId).catch(() => null) + this.assertTerminalAgentStatusPtyBinding(handle, ptyId) + const current = this.deps.getLivePty(handle)?.pty ?? this.deps.getLiveLeaf(handle).leaf + if (record !== current) { + return + } + this.modal.reconcile(record, snapshot.waitText, before, this.deps.getModalFence(ptyId), screen) + } + + getWaitText(record: RuntimePtyWorktreeRecord | RuntimeLeafRecord, ptyId: string | null): string { + const text = buildTerminalWaitText(record.tailBuffer, record.tailPartialLine, record.preview) + return ptyId ? this.modal.read(record, text, this.deps.getModalFence(ptyId)) : text + } + + isModalComposerReady(handle: string): boolean { + const ptyId = this.getPtyId(handle) + const record = this.deps.getLivePty(handle)?.pty ?? this.deps.getLiveLeaf(handle).leaf + const text = buildTerminalWaitText(record.tailBuffer, record.tailPartialLine, record.preview) + const terminal = this.getSnapshot(handle, ptyId) + return ( + terminal.titleStatus !== 'permission' && + this.deps.getExplicitStatus(handle)?.status !== 'permission' && + this.deps.getLifecycleStatus(ptyId)?.status !== 'permission' && + this.modal.isReady(record, text, this.deps.getModalFence(ptyId)) + ) + } + getPtyId(handle: string): string { const pty = this.deps.getLivePty(handle) if (pty) { @@ -184,11 +232,7 @@ export class RuntimeTerminalAgentStatusQuery { { title: pty.pty.title, updatedAt: pty.pty.titleUpdatedAt }, { title: pty.pty.lastOscTitle, updatedAt: pty.pty.lastOscTitleAt } ) - const waitText = buildTerminalWaitText( - pty.pty.tailBuffer, - pty.pty.tailPartialLine, - pty.pty.preview - ) + const waitText = this.getWaitText(pty.pty, expectedPtyId) return { waitText, waitBlockedAt: pty.pty.waitBlockedAt, @@ -216,7 +260,7 @@ export class RuntimeTerminalAgentStatusQuery { { title: this.deps.getTabTitle(leaf.tabId), updatedAt: 0 } ) return { - waitText: buildTerminalWaitText(leaf.tailBuffer, leaf.tailPartialLine, leaf.preview), + waitText: this.getWaitText(leaf, expectedPtyId), waitBlockedAt: leaf.waitBlockedAt, title: title?.title ?? null, titleStatus: title ? detectAgentStatusFromTitle(title.title) : leaf.lastAgentStatus, diff --git a/src/main/runtime/runtime-terminal-idle-polls.ts b/src/main/runtime/runtime-terminal-idle-polls.ts index c3a0e04ceb3d..a0a03b370fa2 100644 --- a/src/main/runtime/runtime-terminal-idle-polls.ts +++ b/src/main/runtime/runtime-terminal-idle-polls.ts @@ -11,7 +11,6 @@ import { buildTerminalWaitBlockedResult, buildTerminalWaitResult } from './terminal-wait-results' -import { buildTerminalWaitText } from './terminal-wait-tail-state' import type { TerminalWaiter } from './runtime-terminal-contracts' import type { RuntimeLeafRecord, RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' @@ -19,6 +18,7 @@ type RuntimeTerminalIdlePollDependencies = { intervalMs: number quiescenceMs: number getTabTitle(tabId: string): string | null + getWaitText(record: RuntimePtyWorktreeRecord | RuntimeLeafRecord): string getForegroundProcess(ptyId: string): Promise | null getAdoptedPtyIdleStatus(pty: RuntimePtyWorktreeRecord): AgentStatus | null resolve(waiter: TerminalWaiter, result: RuntimeTerminalWait): void @@ -46,7 +46,7 @@ export class RuntimeTerminalIdlePolls { this.deps.resolve(waiter, buildTerminalWaitResult(waiter.handle, 'tui-idle', leaf)) return } - const waitText = buildTerminalWaitText(leaf.tailBuffer, leaf.tailPartialLine, leaf.preview) + const waitText = this.deps.getWaitText(leaf) const blockedReason = detectTerminalWaitBlockedReason(waitText) if (blockedReason) { this.stop(waiter) @@ -101,7 +101,7 @@ export class RuntimeTerminalIdlePolls { this.deps.resolve(waiter, buildPtyTerminalWaitResult(waiter.handle, 'tui-idle', pty)) return } - const waitText = buildTerminalWaitText(pty.tailBuffer, pty.tailPartialLine, pty.preview) + const waitText = this.deps.getWaitText(pty) const blockedReason = detectTerminalWaitBlockedReason(waitText) if (blockedReason) { this.stop(waiter) diff --git a/src/main/runtime/runtime-terminal-state-records.ts b/src/main/runtime/runtime-terminal-state-records.ts index 68be05b8ad1a..a8f573cda73b 100644 --- a/src/main/runtime/runtime-terminal-state-records.ts +++ b/src/main/runtime/runtime-terminal-state-records.ts @@ -103,6 +103,7 @@ export type RuntimeHeadlessTerminal = { export type RuntimeVisibleTerminalState = { lines: string[] + codexComposer?: boolean draft?: string isAlternateScreen: boolean sequence: number diff --git a/src/main/runtime/runtime-terminal-wait.ts b/src/main/runtime/runtime-terminal-wait.ts index de7ccdc674a5..333fd171e5a1 100644 --- a/src/main/runtime/runtime-terminal-wait.ts +++ b/src/main/runtime/runtime-terminal-wait.ts @@ -14,7 +14,6 @@ import { buildTerminalWaitResult, getTerminalState } from './terminal-wait-results' -import { buildTerminalWaitText } from './terminal-wait-tail-state' import type { TerminalWaiter } from './runtime-terminal-contracts' import type { RuntimeLeafRecord, RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' import type { AgentStatus } from '../../shared/agent-detection' @@ -27,6 +26,7 @@ type RuntimeTerminalWaitDependencies = { getLiveLeaf(handle: string): { leaf: RuntimeLeafRecord } getAdoptedPtyIdleStatus(pty: RuntimePtyWorktreeRecord): AgentStatus | null getTabTitle(tabId: string): string | null + getWaitText(record: RuntimePtyWorktreeRecord | RuntimeLeafRecord): string startVisibleReadProbe(waiter: TerminalWaiter, waiterTimeoutMs: number): void } @@ -51,11 +51,7 @@ export class RuntimeTerminalWait { if (condition === 'exit' && !pty.pty.connected) { return buildPtyTerminalWaitResult(handle, condition, pty.pty) } - const ptyWaitText = buildTerminalWaitText( - pty.pty.tailBuffer, - pty.pty.tailPartialLine, - pty.pty.preview - ) + const ptyWaitText = this.deps.getWaitText(pty.pty) const ptyBlockedReason = detectTerminalWaitBlockedReason(ptyWaitText) if (condition === 'tui-idle' && ptyBlockedReason) { return buildPtyTerminalWaitBlockedResult(handle, condition, pty.pty, ptyBlockedReason) @@ -104,11 +100,7 @@ export class RuntimeTerminalWait { } else if (condition === 'exit' && !live.pty.connected) { this.waiters.resolve(waiter, buildPtyTerminalWaitResult(handle, condition, live.pty)) } else if (condition === 'tui-idle') { - const livePtyWaitText = buildTerminalWaitText( - live.pty.tailBuffer, - live.pty.tailPartialLine, - live.pty.preview - ) + const livePtyWaitText = this.deps.getWaitText(live.pty) const blockedReason = detectTerminalWaitBlockedReason(livePtyWaitText) if (blockedReason) { this.waiters.resolve( @@ -136,7 +128,7 @@ export class RuntimeTerminalWait { return buildTerminalWaitResult(handle, condition, leaf) } - const leafWaitText = buildTerminalWaitText(leaf.tailBuffer, leaf.tailPartialLine, leaf.preview) + const leafWaitText = this.deps.getWaitText(leaf) const leafBlockedReason = detectTerminalWaitBlockedReason(leafWaitText) if (condition === 'tui-idle' && leafBlockedReason) { return buildTerminalWaitBlockedResult(handle, condition, leaf, leafBlockedReason) @@ -203,11 +195,7 @@ export class RuntimeTerminalWait { if (getTerminalState(live.leaf) === 'exited') { this.waiters.resolve(waiter, buildTerminalWaitResult(handle, condition, live.leaf)) } else if (condition === 'tui-idle') { - const liveLeafWaitText = buildTerminalWaitText( - live.leaf.tailBuffer, - live.leaf.tailPartialLine, - live.leaf.preview - ) + const liveLeafWaitText = this.deps.getWaitText(live.leaf) const blockedReason = detectTerminalWaitBlockedReason(liveLeafWaitText) if (blockedReason) { this.waiters.resolve( diff --git a/src/main/runtime/terminal-codex-modal-observation.test.ts b/src/main/runtime/terminal-codex-modal-observation.test.ts new file mode 100644 index 000000000000..c4e5802d9a1d --- /dev/null +++ b/src/main/runtime/terminal-codex-modal-observation.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { + TerminalCodexModalObservation, + type TerminalModalFence +} from './terminal-codex-modal-observation' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' + +const text = + 'Select model for Codex\nPress enter to confirm or esc to go back\nModel changed to gpt-6-astra medium' +const fence: TerminalModalFence = { generation: 1, outputSequence: 20, permissionSequence: 4 } +const screen: RuntimeVisibleTerminalState = { + lines: ['› Ask Codex to do anything', 'gpt-6-astra · medium'], + codexComposer: true, + generation: 1, + sequence: 20, + isAlternateScreen: false +} + +describe('model modal evidence fences', () => { + it.each([ + ['unavailable screen', null, fence], + ['unreadable composer', { ...screen, codexComposer: undefined }, fence], + ['stale output', { ...screen, sequence: 19 }, fence], + ['future output', { ...screen, sequence: 21 }, fence], + ['stale incarnation', { ...screen, generation: 0 }, fence], + ['generation changes during read', screen, { ...fence, generation: 2 }], + ['output changes during read', screen, { ...fence, outputSequence: 21 }], + ['permission arrives during read', screen, { ...fence, permissionSequence: 5 }], + [ + 'approval above the composer', + { ...screen, lines: ['Codex permission required', 'Allow once', 'Reject', ...screen.lines] }, + fence + ] + ])('keeps %s fail closed', (_name, visible, after) => { + const observation = new TerminalCodexModalObservation() + const record = {} + observation.reconcile(record, text, fence, after, visible) + expect(observation.read(record, text, after)).toBe(text) + }) + + it('does not retire a real approval even when it has disappeared', () => { + const observation = new TerminalCodexModalObservation() + const record = {} + const approval = 'Codex permission required\nAllow once\nReject' + observation.reconcile(record, approval, fence, fence, screen) + expect(observation.read(record, approval, fence)).toBe(approval) + const newerApproval = `${text}\n${approval}` + observation.reconcile(record, newerApproval, fence, fence, screen) + expect(observation.read(record, newerApproval, fence)).toBe(newerApproval) + }) + + it('fences a retirement by pane, generation, permission sequence and the exact retained prefix', () => { + const observation = new TerminalCodexModalObservation() + const record = {} + observation.reconcile(record, text, fence, fence, screen) + expect(observation.read(record, text, fence)).toBe('') + expect(observation.read({}, text, fence)).toBe(text) + expect(observation.read(record, text, { ...fence, generation: 2 })).toBe(text) + expect(observation.read(record, text, { ...fence, permissionSequence: 5 })).toBe(text) + expect(observation.read(record, `different history\n${text}`, fence)).toContain('Press enter') + const next = `${text}\nCodex permission required\nAllow once\nReject` + expect(observation.read(record, next, fence)).toContain('Codex permission required') + expect(observation.isReady(record, text, { ...fence, outputSequence: 21 })).toBe(false) + }) +}) diff --git a/src/main/runtime/terminal-codex-modal-observation.ts b/src/main/runtime/terminal-codex-modal-observation.ts new file mode 100644 index 000000000000..881a530f0676 --- /dev/null +++ b/src/main/runtime/terminal-codex-modal-observation.ts @@ -0,0 +1,76 @@ +import { + detectTerminalWaitBlockedReason, + findActionableTerminalWaitBlockedSignal +} from './terminal-wait-detection' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' + +export type TerminalModalFence = { + generation: number + outputSequence: number + permissionSequence: number +} + +type Retirement = TerminalModalFence & { prefix: string } + +// Only the model/effort picker can be retired without an agent lifecycle event. +export function hasCodexModelPickerTail(text: string): boolean { + const normalized = text.toLowerCase() + const signal = findActionableTerminalWaitBlockedSignal(normalized) + const prompt = normalized.lastIndexOf('press enter to confirm') + if (prompt === -1 || signal?.reason !== 'codex-interactive-prompt' || signal.index !== prompt) { + return false + } + const context = text.slice(Math.max(0, prompt - 600), prompt) + return ( + /(?:select|choose) (?:a )?(?:model|reasoning effort)/i.test(context) && + !/permission|approval|allow once|allow always|reject|deny|trust|sandbox|hook/i.test(context) + ) +} + +export class TerminalCodexModalObservation { + private readonly retired = new WeakMap() + + read(record: object, text: string, fence: TerminalModalFence): string { + const retired = this.retired.get(record) + if ( + retired?.generation !== fence.generation || + retired.permissionSequence !== fence.permissionSequence || + !text.startsWith(retired.prefix) + ) { + return text + } + return text.slice(retired.prefix.length) + } + + isReady(record: object, text: string, fence: TerminalModalFence): boolean { + const retired = this.retired.get(record) + return ( + retired?.outputSequence === fence.outputSequence && this.read(record, text, fence) !== text + ) + } + + reconcile( + record: object, + text: string, + before: TerminalModalFence, + after: TerminalModalFence, + screen: RuntimeVisibleTerminalState | null + ): void { + if ( + !hasCodexModelPickerTail(text) || + before.generation !== after.generation || + before.outputSequence !== after.outputSequence || + before.permissionSequence !== after.permissionSequence || + screen?.generation !== after.generation || + screen.sequence !== after.outputSequence || + screen.codexComposer !== true || + detectTerminalWaitBlockedReason(screen.lines.join('\n')) !== null || + /would you like to|yes, proceed|approve|approval|allow once|allow always|reject|deny/i.test( + screen.lines.join('\n') + ) + ) { + return + } + this.retired.set(record, { ...after, prefix: text }) + } +} diff --git a/src/main/runtime/terminal-codex-modal-runtime.test.ts b/src/main/runtime/terminal-codex-modal-runtime.test.ts new file mode 100644 index 000000000000..108fb006f8a1 --- /dev/null +++ b/src/main/runtime/terminal-codex-modal-runtime.test.ts @@ -0,0 +1,208 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { RuntimeVisibleTerminalState } from './runtime-terminal-state-records' +import { createAgentPromptSubmissionRuntime } from './agent-prompt-submission-runtime-test-fixture' + +vi.mock('../git/worktree', () => ({ + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/test', + isBare: false, + isMainWorktree: false + } + ]), + listWorktreesStrict: vi.fn().mockResolvedValue([ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/test', + isBare: false, + isMainWorktree: false + } + ]) +})) + +const PICKER = + 'Select model for Codex\r\n gpt-6-astra\r\nPress enter to confirm or esc to go back\r\n' +const COMPOSER = + '\x1b[2J\x1b[HModel changed to gpt-6-astra medium\r\n\r\n\x1b[1m›\x1b[0m \x1b[2mAsk Codex to do anything\x1b[0m\r\n\r\n gpt-6-astra · medium\x1b[3;3H\x1b[?25h' +const APPROVAL = '\x1b[2J\x1b[HCodex permission required\r\nAllow once\r\nReject\r\n' + +async function pane( + onPaste?: ( + runtime: Awaited>['runtime'] + ) => void +) { + return createAgentPromptSubmissionRuntime((runtime, data) => { + if (data === '\r') { + runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + } else { + onPaste?.(runtime) + } + }, 'codex') +} + +describe('Codex model picker observation lifecycle', () => { + afterEach(() => vi.useRealTimers()) + + it('retires erased picker history and admits a prompt in the same pane', async () => { + const { runtime, handle, writes } = await pane() + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + await expect(runtime.getTerminalAgentStatus(handle)).resolves.toMatchObject({ + status: 'permission' + }) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.getTerminalAgentStatus(handle)).resolves.not.toMatchObject({ + status: 'permission' + }) + await expect(runtime.getTerminalInteractiveWait(handle)).resolves.toBeNull() + await expect( + runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1000 }) + ).resolves.toMatchObject({ satisfied: true }) + await expect( + runtime.sendTerminalAgentPrompt(handle, 'continue the task') + ).resolves.toMatchObject({ accepted: true }) + expect(writes.filter((data) => data === '\r')).toHaveLength(1) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it('reconciles direct submission without a prior status read', async () => { + const { runtime, handle } = await pane() + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).resolves.toMatchObject({ + accepted: true + }) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it.each([ + ['open picker', PICKER], + ['actual approval', APPROVAL], + [ + 'quoted composer', + '\r\nModel changed to gpt-6-astra medium\r\n› Ask Codex to do anything\r\n gpt-6-astra · medium\r\n' + ], + ['trust prompt', '\x1b[2J\x1b[HDo you trust this workspace?\r\nPress enter to confirm\r\n'], + ['hook review', '\x1b[2J\x1b[HCodex hooks need review\r\nPress enter to confirm\r\n'] + ])('keeps %s blocked', async (_name, next) => { + const { runtime, handle, writes } = await pane() + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', next, Date.now()) + await expect(runtime.getTerminalAgentStatus(handle)).resolves.toMatchObject({ + status: 'permission' + }) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).rejects.toThrow( + 'agent_prompt_blocked' + ) + expect(writes).toHaveLength(0) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it('keeps the retired modal closed while the new prompt redraws in the composer', async () => { + const { runtime, handle } = await pane((runtime) => { + runtime.onPtyData( + 'pty-prompt', + COMPOSER.replace('Ask Codex to do anything', 'continue'), + Date.now() + ) + }) + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).resolves.toMatchObject({ + accepted: true + }) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it.each(['Codex permission required', 'Codex waiting'])( + 'preserves live permission title %s after close', + async (title) => { + const { runtime, handle, writes } = await pane() + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + runtime.onPtyData('pty-prompt', `\x1b]0;${title}\x07`, Date.now()) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).rejects.toThrow( + 'agent_prompt_blocked' + ) + expect(writes).toHaveLength(0) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + } + ) + + it('refuses submission when the screen cannot be read', async () => { + const { runtime, handle, writes } = await pane() + const reader = runtime as unknown as { + readVisibleTerminalState(ptyId: string): Promise + } + vi.spyOn(reader, 'readVisibleTerminalState').mockResolvedValue(null) + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).rejects.toThrow( + 'agent_prompt_blocked' + ) + expect(writes).toHaveLength(0) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it('fences a permission cycle occurring during the foreground screen read', async () => { + const { runtime, handle, writes } = await pane() + const reader = runtime as unknown as { + readVisibleTerminalState(ptyId: string): Promise + } + const read = reader.readVisibleTerminalState.bind(reader) + vi.spyOn(reader, 'readVisibleTerminalState').mockImplementationOnce(async (ptyId) => { + const result = await read(ptyId) + runtime.onPtyData(ptyId, '\x1b]0;Codex permission required\x07', Date.now()) + runtime.onPtyData(ptyId, '\x1b]0;Codex working\x07', Date.now()) + return result + }) + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).rejects.toThrow( + 'agent_prompt_blocked' + ) + expect(writes).toHaveLength(0) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it('preserves a newer permission during paste even after the modal was retired', async () => { + const { runtime, handle, writes } = await pane((runtime) => { + runtime.onPtyData('pty-prompt', APPROVAL, Date.now()) + runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + }) + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).rejects.toThrow( + 'agent_prompt_blocked' + ) + expect(writes).toHaveLength(1) + expect(writes).not.toContain('\r') + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) +}) From d9a5197ee7b51a665a6e27b0415986f2cde90a67 Mon Sep 17 00:00:00 2001 From: Zubair Ahsan Date: Mon, 7 Sep 2026 18:59:51 +0800 Subject: [PATCH 2/3] fix: retain modal retirement across paste echoes and preserve working state --- .../runtime-terminal-agent-status-query.ts | 9 +++-- .../terminal-codex-modal-observation.test.ts | 2 +- .../terminal-codex-modal-observation.ts | 8 ++++- .../terminal-codex-modal-runtime.test.ts | 36 +++++++++++++++++++ 4 files changed, 50 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/runtime-terminal-agent-status-query.ts b/src/main/runtime/runtime-terminal-agent-status-query.ts index 8a6e31d7afd0..01fa1c84b339 100644 --- a/src/main/runtime/runtime-terminal-agent-status-query.ts +++ b/src/main/runtime/runtime-terminal-agent-status-query.ts @@ -169,10 +169,13 @@ export class RuntimeTerminalAgentStatusQuery { const record = this.deps.getLivePty(handle)?.pty ?? this.deps.getLiveLeaf(handle).leaf const text = buildTerminalWaitText(record.tailBuffer, record.tailPartialLine, record.preview) const terminal = this.getSnapshot(handle, ptyId) + const statuses = [ + terminal.titleStatus, + this.deps.getExplicitStatus(handle)?.status, + this.deps.getLifecycleStatus(ptyId)?.status + ] return ( - terminal.titleStatus !== 'permission' && - this.deps.getExplicitStatus(handle)?.status !== 'permission' && - this.deps.getLifecycleStatus(ptyId)?.status !== 'permission' && + !statuses.some((status) => status === 'permission' || status === 'working') && this.modal.isReady(record, text, this.deps.getModalFence(ptyId)) ) } diff --git a/src/main/runtime/terminal-codex-modal-observation.test.ts b/src/main/runtime/terminal-codex-modal-observation.test.ts index c4e5802d9a1d..b029e3cb3e85 100644 --- a/src/main/runtime/terminal-codex-modal-observation.test.ts +++ b/src/main/runtime/terminal-codex-modal-observation.test.ts @@ -53,7 +53,7 @@ describe('model modal evidence fences', () => { const observation = new TerminalCodexModalObservation() const record = {} observation.reconcile(record, text, fence, fence, screen) - expect(observation.read(record, text, fence)).toBe('') + expect(observation.read(record, text, fence)).toBe('Model changed to gpt-6-astra medium') expect(observation.read({}, text, fence)).toBe(text) expect(observation.read(record, text, { ...fence, generation: 2 })).toBe(text) expect(observation.read(record, text, { ...fence, permissionSequence: 5 })).toBe(text) diff --git a/src/main/runtime/terminal-codex-modal-observation.ts b/src/main/runtime/terminal-codex-modal-observation.ts index 881a530f0676..5455c843c735 100644 --- a/src/main/runtime/terminal-codex-modal-observation.ts +++ b/src/main/runtime/terminal-codex-modal-observation.ts @@ -71,6 +71,12 @@ export class TerminalCodexModalObservation { ) { return } - this.retired.set(record, { ...after, prefix: text }) + // The composer can redraw in place during paste; it is not part of the dismissed modal. + const prompt = text.toLowerCase().lastIndexOf('press enter to confirm') + const lineEnd = text.indexOf('\n', prompt) + this.retired.set(record, { + ...after, + prefix: text.slice(0, lineEnd === -1 ? text.length : lineEnd + 1) + }) } } diff --git a/src/main/runtime/terminal-codex-modal-runtime.test.ts b/src/main/runtime/terminal-codex-modal-runtime.test.ts index 108fb006f8a1..3212c490c72d 100644 --- a/src/main/runtime/terminal-codex-modal-runtime.test.ts +++ b/src/main/runtime/terminal-codex-modal-runtime.test.ts @@ -83,6 +83,42 @@ describe('Codex model picker observation lifecycle', () => { } }) + it('keeps the modal retired during an in-place composer paste echo', async () => { + const { runtime, handle, writes } = await pane((runtime) => { + runtime.onPtyData('pty-prompt', '\x1b[2K\r\x1b[1m›\x1b[0m continue', Date.now()) + }) + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + await expect(runtime.getTerminalAgentStatus(handle)).resolves.not.toMatchObject({ + status: 'permission' + }) + await expect(runtime.sendTerminalAgentPrompt(handle, 'continue')).resolves.toMatchObject({ + accepted: true + }) + expect(writes.filter((data) => data === '\r')).toHaveLength(1) + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + + it('does not treat a closed picker composer as idle while Codex is working', async () => { + const { runtime, handle } = await pane() + try { + runtime.onPtyData('pty-prompt', PICKER, Date.now()) + runtime.onPtyData('pty-prompt', COMPOSER, Date.now()) + runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now()) + await expect(runtime.getTerminalAgentStatus(handle)).resolves.toMatchObject({ + status: 'working' + }) + await expect( + runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 50 }) + ).rejects.toThrow('timeout') + } finally { + runtime.onPtyExit('pty-prompt', 0) + } + }) + it.each([ ['open picker', PICKER], ['actual approval', APPROVAL], From b872ca49c27ff64473f8891ae5a15bbd81a7a6b7 Mon Sep 17 00:00:00 2001 From: Zubair Ahsan Date: Mon, 7 Sep 2026 19:13:11 +0800 Subject: [PATCH 3/3] fix: preserve synchronous terminal waiter admission across reloads --- ...rca-runtime-create-agent-prompt-render-gate.ts | 15 +++++++++++---- .../runtime-terminal-agent-status-query.ts | 11 +++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts b/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts index 6cedd543f63d..347a4f36e6cb 100644 --- a/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts +++ b/src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts @@ -137,10 +137,17 @@ export class OrcaRuntimeWithCreateAgentPromptRenderGate extends OrcaRuntimeWithW } ): Promise { if (options?.condition === 'tui-idle') { - const ptyId = this.getTerminalAgentStatusPtyId(handle) - await this.terminalAgentStatus.refreshModal(handle, ptyId) - if (this.terminalAgentStatus.isModalComposerReady(handle)) { - return this.buildTuiIdleProbeResult(handle, null) + try { + const ptyId = this.getTerminalAgentStatusPtyId(handle) + if (this.terminalAgentStatus.hasModalToRefresh(handle, ptyId)) { + await this.terminalAgentStatus.refreshModal(handle, ptyId) + } + if (this.terminalAgentStatus.isModalComposerReady(handle)) { + return this.buildTuiIdleProbeResult(handle, null) + } + } catch { + // Renderer reloads can retire the live projection during this optional read. + // The existing waiter owns retained-handle continuity and stale-handle errors. } } return this.terminalWait.wait(handle, options) diff --git a/src/main/runtime/runtime-terminal-agent-status-query.ts b/src/main/runtime/runtime-terminal-agent-status-query.ts index 01fa1c84b339..140fdab565fe 100644 --- a/src/main/runtime/runtime-terminal-agent-status-query.ts +++ b/src/main/runtime/runtime-terminal-agent-status-query.ts @@ -140,14 +140,17 @@ export class RuntimeTerminalAgentStatusQuery { return { handle, isRunningAgent, status: null } } + hasModalToRefresh(handle: string, ptyId: string): boolean { + return ( + this.deps.isCodex(ptyId) && hasCodexModelPickerTail(this.getSnapshot(handle, ptyId).waitText) + ) + } + async refreshModal(handle: string, ptyId: string): Promise { - if (!this.deps.isCodex(ptyId)) { + if (!this.hasModalToRefresh(handle, ptyId)) { return } const snapshot = this.getSnapshot(handle, ptyId) - if (!hasCodexModelPickerTail(snapshot.waitText)) { - return - } const record = this.deps.getLivePty(handle)?.pty ?? this.deps.getLiveLeaf(handle).leaf const before = this.deps.getModalFence(ptyId) const screen = await this.deps.readVisibleState(ptyId).catch(() => null)