Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/main/runtime/orca-runtime-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 15 additions & 1 deletion src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,14 +128,28 @@ export class OrcaRuntimeWithCreateAgentPromptRenderGate extends OrcaRuntimeWithW
}
}

waitForTerminal(
async waitForTerminal(
handle: string,
options?: {
condition?: RuntimeTerminalWaitCondition
timeoutMs?: number
signal?: AbortSignal
}
): Promise<RuntimeTerminalWait> {
if (options?.condition === 'tui-idle') {
try {
const ptyId = this.getTerminalAgentStatusPtyId(handle)
if (this.terminalAgentStatus.hasModalToRefresh(handle, ptyId)) {
await this.terminalAgentStatus.refreshModal(handle, ptyId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -e
rg -n -C 12 'refreshModal|readVisibleTerminalState|terminalWait\.wait|waitForTerminal|renderer.*reload|reload.*renderer' src/main

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- target file ---'
sed -n '1,190p' src/main/runtime/orca-runtime-create-agent-prompt-render-gate.ts
printf '%s\n' '--- definition files ---'
rg -l 'readVisibleTerminalState|refreshModal' src/main --glob '*.ts' --glob '*.tsx' | sort
printf '%s\n' '--- waiter definitions ---'
rg -l 'class .*Terminal.*Wait|terminalWait|waitForTerminal' src/main --glob '*.ts' --glob '*.tsx' | sort | head -80

Repository: stablyai/orca

Length of output: 10423


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- status implementation locations ---'
rg -n -C 10 'refreshModal|readVisibleTerminalState|hasModalToRefresh|isModalComposerReady' \
  src/main/runtime/runtime-terminal-agent-status-query.ts \
  src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts \
  src/main/runtime/orca-runtime-get-terminal-interactive-wait.ts \
  src/main/runtime/orca-runtime-visible-snapshot-preview.ts
printf '%s\n' '--- waiter implementation ---'
sed -n '1,280p' src/main/runtime/runtime-terminal-wait.ts
printf '%s\n' '--- reload/read bindings ---'
rg -n -C 8 'readVisibleTerminalState|markRendererReloading|rendererGraph|reloading|webContents|executeJavaScript|invoke' \
  src/main/runtime/runtime-terminal-agent-status-query.ts \
  src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts \
  src/main/runtime --glob '*.ts' | head -500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- visible-state read implementation ---'
sed -n '30,145p' src/main/runtime/orca-runtime-visible-snapshot-preview.ts
printf '%s\n' '--- visible-state helpers and lifecycle invalidation ---'
rg -n -C 10 'loadVisibleTerminalState|providerVisibleStateReadsByPtyId|readRendererVisibleSnapshotLines|readVisibleState|clear.*Visible|delete\(ptyId\)|getPtyLifecycleGeneration' \
  src/main/runtime/orca-runtime-visible-snapshot-preview.ts \
  src/main/runtime/orca-runtime-capture-provider-terminal-buffer.ts \
  src/main/runtime --glob '*.ts' | head -400

Repository: stablyai/orca

Length of output: 42651


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- provider snapshot acquisition ---'
rg -n -C 18 'serializeProviderTerminalBuffer|VISIBLE_TERMINAL_SNAPSHOT_TIMEOUT_MS|withTimeout|providerSnapshotPreferredPtys' \
  src/main/runtime/orca-runtime-capture-provider-terminal-buffer.ts \
  src/main/runtime/orca-runtime-visible-snapshot-preview.ts \
  src/main/runtime/runtime-async-boundaries.ts \
  src/main/runtime --glob '*.ts' | head -500
printf '%s\n' '--- provider controller contract ---'
rg -n -C 12 'serializeProviderBuffer|serializeBuffer' src/main/runtime src/main/pty src/main --glob '*.ts' | head -350

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- provider buffer method ---'
sed -n '1,90p' src/main/runtime/orca-runtime-capture-provider-terminal-buffer.ts
printf '%s\n' '--- timeout contract ---'
rg -n -C 12 'export.*withTimeout|function withTimeout|promise-timeout-fallback|VISIBLE_TERMINAL_SNAPSHOT_TIMEOUT_MS' \
  src/shared src/main/runtime --glob '*.ts' | head -220
printf '%s\n' '--- preferred-set transitions ---'
rg -n -C 8 'providerSnapshotPreferredPtys\.(add|delete)|providerSnapshotPreferredPtys\s*=' \
  src/main/runtime --glob '*.ts' | head -260

Repository: stablyai/orca

Length of output: 46085


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- bounded provider acquisition ---'
rg -n -C 18 'serializeProviderTerminalBuffer|class OrcaRuntimeWithSerializeTerminalBufferFromAvailableState' \
  src/main/runtime/orca-runtime-serialize-terminal-buffer-from-available-state.ts
printf '%s\n' '--- headless write-chain construction ---'
rg -n -C 12 'writeChain\s*=|writeChain:|createPtyHeadlessTerminalState|acceptPtyData' \
  src/main/runtime/orca-runtime-create-pty-headless-terminal-state.ts \
  src/main/runtime/orca-runtime-serialize-main-terminal-buffer.ts \
  src/main/runtime/orca-runtime-accept-pty-data.ts \
  src/main/runtime --glob '*.ts' | head -450
printf '%s\n' '--- modal/reload tests ---'
rg -n -C 14 'refreshModal|readVisibleTerminalState|renderer reload|markRendererReloading|request_aborted|timeout' \
  src/main/runtime/terminal-codex-modal-runtime.test.ts \
  src/main/runtime/terminal-interactive-wait-visibility.test.ts \
  src/main/runtime/orca-runtime-tests --glob '*.spec.ts' | head -500

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -e
sed -n '108,165p' src/main/runtime/orca-runtime-serialize-terminal-buffer-from-available-state.ts
printf '%s\n' '--- renderer reload lifecycle entry points ---'
rg -n -C 12 'markRendererReloading|markRendererGraph|renderer.*reloading|reloading.*renderer|disposeHeadlessTerminal|replaceHeadlessTerminalAfterExecutionContextChange' \
  src/main/runtime/orca-runtime-*.ts | head -450

Repository: stablyai/orca

Length of output: 45808


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- headless data chain ---'
sed -n '145,185p' src/main/runtime/orca-runtime-maybe-hydrate-headless-from-renderer.ts
printf '%s\n' '--- emulator write contract ---'
rg -n -C 15 'async write|write\(' src/main/daemon/headless-emulator.ts src/main/daemon --glob '*.ts' | head -260
printf '%s\n' '--- renderer reload implementation ---'
sed -n '20,115p' src/main/runtime/orca-runtime-has-terminals-for-worktree.ts

Repository: stablyai/orca

Length of output: 27401


Preserve timeout and abort during modal refresh.

refreshModal does not use the caller's signal or deadline. Its provider path has a separate 750 ms timeout, while its headless path awaits writeChain without that deadline. Because this runs before terminalWait.wait binds the options, a short timeout or abort cannot take effect until the refresh returns. Register the waiter first, or apply the same signal and remaining timeout to the refresh.

}
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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/main/runtime/orca-runtime-runtime-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
},
Expand Down
7 changes: 7 additions & 0 deletions src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
7 changes: 6 additions & 1 deletion src/main/runtime/orca-runtime-terminal-projection.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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())
Expand All @@ -38,6 +42,7 @@ export function projectTerminalVisibleLines(emulator: HeadlessEmulator): {
}
return {
lines: visibleNonBlankTerminalLines(visible),
codexComposer: hasTerminalComposerPlaceholder(emulator.getCursorLineContext()),
...(draft ? { draft: draft.text } : {})
}
}
5 changes: 4 additions & 1 deletion src/main/runtime/orca-runtime-write-terminal-agent-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@ export class OrcaRuntimeWithWriteTerminalAgentPrompt extends OrcaRuntimeWithReso
): Promise<number> {
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')
Expand Down
62 changes: 56 additions & 6 deletions src/main/runtime/runtime-terminal-agent-status-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -26,6 +32,9 @@ export type RuntimeTerminalAgentStatusSnapshot = {
}

type Dependencies = {
getModalFence(ptyId: string): TerminalModalFence
readVisibleState(ptyId: string): Promise<RuntimeVisibleTerminalState | null>
isCodex(ptyId: string): boolean
getController(): RuntimePtyController | null
getLivePty(handle: string): { pty: RuntimePtyWorktreeRecord } | null
getLiveLeaf(handle: string): { leaf: RuntimeLeafRecord }
Expand All @@ -41,6 +50,7 @@ type Dependencies = {
}

export class RuntimeTerminalAgentStatusQuery {
private readonly modal = new TerminalCodexModalObservation()
private readonly inFlight = new Map<string, Promise<RuntimeTerminalAgentStatus>>()

constructor(private readonly deps: Dependencies) {}
Expand All @@ -63,6 +73,7 @@ export class RuntimeTerminalAgentStatusQuery {

private async readStatus(handle: string): Promise<RuntimeTerminalAgentStatus> {
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)
Expand Down Expand Up @@ -129,6 +140,49 @@ 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<void> {
if (!this.hasModalToRefresh(handle, ptyId)) {
return
}
const snapshot = this.getSnapshot(handle, ptyId)
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reconcile a reopened picker before applying retirement.

TerminalCodexModalObservation.read ignores newer outputSequence values. A later identical picker in the same generation and permission sequence can therefore be stripped again. hasModalToRefresh then sees filtered text, skips refreshModal, and does not inspect the visible state. The wait path can admit tui-idle, allowing prompt submission while the picker is active. Detect the picker from raw wait text, clear retirement when newer visible state shows the active picker, and retain retirement only for confirmed composer echoes. Add a regression test for reopening the identical picker in one PTY generation.

}

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)
const statuses = [
terminal.titleStatus,
this.deps.getExplicitStatus(handle)?.status,
this.deps.getLifecycleStatus(ptyId)?.status
]
return (
!statuses.some((status) => status === 'permission' || status === 'working') &&
this.modal.isReady(record, text, this.deps.getModalFence(ptyId))
)
}

getPtyId(handle: string): string {
const pty = this.deps.getLivePty(handle)
if (pty) {
Expand Down Expand Up @@ -184,11 +238,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,
Expand Down Expand Up @@ -216,7 +266,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,
Expand Down
6 changes: 3 additions & 3 deletions src/main/runtime/runtime-terminal-idle-polls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ 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'

type RuntimeTerminalIdlePollDependencies = {
intervalMs: number
quiescenceMs: number
getTabTitle(tabId: string): string | null
getWaitText(record: RuntimePtyWorktreeRecord | RuntimeLeafRecord): string
getForegroundProcess(ptyId: string): Promise<string | null> | null
getAdoptedPtyIdleStatus(pty: RuntimePtyWorktreeRecord): AgentStatus | null
resolve(waiter: TerminalWaiter, result: RuntimeTerminalWait): void
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions src/main/runtime/runtime-terminal-state-records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export type RuntimeHeadlessTerminal = {

export type RuntimeVisibleTerminalState = {
lines: string[]
codexComposer?: boolean
draft?: string
isAlternateScreen: boolean
sequence: number
Expand Down
22 changes: 5 additions & 17 deletions src/main/runtime/runtime-terminal-wait.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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
}

Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
65 changes: 65 additions & 0 deletions src/main/runtime/terminal-codex-modal-observation.test.ts
Original file line number Diff line number Diff line change
@@ -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('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)
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)
})
})
Loading
Loading