Skip to content

Fix Codex worker readiness on cursor-painted terminal screens - #22891

Closed
seonghobae wants to merge 1 commit into
stablyai:mainfrom
ContextualWisdomLab:orca-k16-agent-readiness
Closed

seonghobae wants to merge 1 commit into
stablyai:mainfrom
ContextualWisdomLab:orca-k16-agent-readiness

Conversation

@seonghobae

Copy link
Copy Markdown
Contributor

ELI5

A Codex worker can be sitting at its input prompt while Orca keeps waiting for it to start. Orca now checks the visible terminal screen during that wait.

What Changed

The terminal wait path starts a visible-screen probe for Codex even when its retained text is nonempty or its title looks idle. The probe asks for the rendered screen and retries at most every two seconds until the existing wait deadline. A ready screen settles the wait; an interactive prompt still blocks it.

Why

Codex 0.157 paints its banner with cursor movement. The retained text and short preview can omit the OpenAI Codex, model:, and directory: lines although the rendered screen shows all three. The previous probe skipped Codex when retained text was nonempty, and one early snapshot could miss a slow first paint. This uses Orca's existing screen reader and readiness matcher, with no new prompt-text rule.

Linked Issue

Fixes #22825

Visual Proof

N/A — the rendered UI does not change. Before: the existing s1 Codex 0.157 terminal shows the empty Ask Codex to do anything composer while terminal wait --for tui-idle --timeout-ms 1500 exits 1 with timeout. After: the focused regression supplies a boot screen followed by that ready screen; the wait resolves and the test exits 0. The patched runtime has not been deployed to s1.

Testing

  • Automated regression test added: ORCA_BACKGROUND_LAUNCH=1 node_modules/.bin/vitest run src/main/runtime/terminal-wait-name-only-idle.test.ts -t 'reads the visible Codex screen again' --reporter=dot — exit 0, one passed.
  • oxfmt --check and oxlint on the three changed files — exit 0.
  • Live patched runtime test. The two failed K16 terminals are preserved and the task circuit-break is respected.

Tested the focused regression on macOS. The affected worker was on a paired s1 runtime; no patched Linux or Windows run was performed.

Review

Agent skill upstream boundary

  • Not applicable; this change includes no agent skill source.

Notes

The probe uses the existing host-owned terminal screen API and existing timeout, so SSH and paired-host execution keep the same ownership boundary. It adds no wire field or Git command. The Codex-only retry is bounded by the waiter deadline; timers stop probing after the waiter settles. Full repository checks and builds were not run because of the current disk and memory constraint.

Checklist

  • This PR is small and focused.
  • Before/after behavior and mechanism are described.
  • No rendered UI change.
  • Self-reviewed for correctness and performance.
  • Cross-platform and remote boundary considered.
  • Full lint, typecheck, test, and build; CI will cover these checks.

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The PTY and leaf waiter checks now allow Codex panes to use the visible-screen probe. The probe requests screen snapshots for all agents and retries Codex reads when the snapshot is missing, is not a screen projection, or has neither a blocked reason nor a ready prompt. It stops when the waiter is no longer registered or the retry window is insufficient. A new test verifies that a Codex wait succeeds after a second screen read returns a ready header.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🔵 Low · up to 778c4

A Codex wait may occasionally time out when its screen becomes ready near the deadline. The narrow timing issue is worth fixing, but does not appear to prevent merging with owner awareness.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 778c4

The change broadens how Codex readiness is detected, but the reviewed path still requires a recognized visible prompt or a blocked state before completing a wait. No introduced security issue was established. Live behavior remains unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Additional screen reads and possible earlier wait completion apply to identified Codex terminal waiters. The reviewed change does not add a cross-service call or a new credential or deployment authority.

Trust Boundaries and Controls

  • observed — Terminal-rendered content can influence readiness only through the existing screen-sourced classifier; probe eligibility alone does not satisfy a wait. Structured launch retains a provider-proof step after wait completion.

Resilience and Maintainability Implications

  • observed — Timeout, abort, and competing resolution remove the original waiter. Late retry callbacks check that waiter's object identity before reading or settling, limiting stale-read effects on replacement waits.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: fixing Codex worker readiness on cursor-painted terminal screens.
Description check ✅ Passed The description covers the required sections, including the user impact, mechanism, reason, linked issue, visual-proof rationale, testing, scope considerations, and checklist status. It also clearly s…
Linked Issues check ✅ Passed The changes meet the coding objectives in [#22825]. runtime-terminal-wait.ts allows Codex panes to start the visible-screen probe for PTY and leaf waiters. `orca-runtime-start-tui-idle-visible-read-…
Out of Scope Changes check ✅ Passed The reviewed changes stay within [#22825]. The runtime edits enable and repeat the Codex visible-screen readiness probe. The test covers the reported false-negative case. No unrelated feature, launch-…
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: beb7bf3d-55ad-47fa-937b-ea857c8b326b

📥 Commits

Reviewing files that changed from the base of the PR and between 646e9a5 and 778c4f3.

📒 Files selected for processing (3)
  • src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts
  • src/main/runtime/runtime-terminal-wait.ts
  • src/main/runtime/terminal-wait-name-only-idle.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

if (remainingMs <= providerTimeoutMs + settleMarginMs) {
return
}
const timer = setTimeout(probe, Math.min(2_000, remainingMs - providerTimeoutMs))

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:

sed -n '1,145p' src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts
rg -n 'startTuiIdleVisibleReadProbe|settleMarginMs|providerTimeoutMs' src/main/runtime/runtime-terminal-wait.ts src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts

Repository: stablyai/orca

Length of output: 6824


🏁 Script executed:

set -o pipefail
printf '%s\n' '--- constants ---'
rg -n -C 8 'TUI_IDLE_VISIBLE_PROBE_SETTLE_MARGIN_MS|VISIBLE_TERMINAL_SNAPSHOT_TIMEOUT_MS' src/main/runtime
printf '%s\n' '--- probe callers and waiter lifecycle ---'
rg -n -C 12 'startTuiIdleVisibleReadProbe|setTimeout|deadline|waiterTimeoutMs|TerminalWaiter' src/main/runtime/runtime-terminal-wait.ts src/main/runtime
printf '%s\n' '--- focused runtime-terminal-wait source ---'
sed -n '1,260p' src/main/runtime/runtime-terminal-wait.ts

Repository: stablyai/orca

Length of output: 45662


🏁 Script executed:

set -o pipefail
rg -n -C 10 'TUI_IDLE_VISIBLE_PROBE_SETTLE_MARGIN_MS|VISIBLE_TERMINAL_SNAPSHOT_TIMEOUT_MS' src/main/runtime/orca-runtime-postlude.ts
rg -n -C 14 'startTuiIdleVisibleReadProbe' src/main/runtime
rg -n -C 12 'waiterTimeoutMs|setTimeout.*waiter|terminalWaiters.*resolve|waiter.*timeout|deadline' src/main/runtime/runtime-terminal-wait.ts src/main/runtime/terminal-wait* src/main/runtime/*terminal*wait*.ts

Repository: stablyai/orca

Length of output: 26357


Schedule the Codex retry before the settle margin is consumed.

VISIBLE_TERMINAL_SNAPSHOT_TIMEOUT_MS is 750 ms and settleMarginMs is 10 ms. For a remainingMs value just above 760 ms, the current delay starts the next probe with about 750 ms remaining. The waiter can then expire before a slow screen read classifies the ready screen.

Proposed change
-      const timer = setTimeout(probe, Math.min(2_000, remainingMs - providerTimeoutMs))
+      const timer = setTimeout(
+        probe,
+        Math.min(2_000, remainingMs - providerTimeoutMs - settleMarginMs)
+      )

Keep the <= guard. Exact equality provides no positive settle margin and should not schedule another retry.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const timer = setTimeout(probe, Math.min(2_000, remainingMs - providerTimeoutMs))
const timer = setTimeout(
probe,
Math.min(2_000, remainingMs - providerTimeoutMs - settleMarginMs)
)

@pullfrog pullfrog Bot left a comment

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.

Important

The Codex visible-screen probe resolves tui-idle without the first-party working-status veto or the quiescence gate that every other satisfaction site applies, and no captured Codex working-turn transcript exists to show the ready header is absent while Codex is mid-turn. Please pin the busy case before merging.

Reviewed changes

  • Codex joins the visible-read probe unconditionally — paneAgent === 'codex' is added to both gate clauses in the PTY and leaf paths, so the probe now runs for Codex even when retained text is nonempty and the last status is not null.
  • Probe retries for Codex — the single-shot probe becomes a bounded retry loop that re-reads the rendered screen roughly every two seconds until the waiter deadline; every other agent stays single-shot.
  • Probe always reads the rendered screen — read options change from {} to { screen: true } for all agents (Antigravity already passed screen: true), which is what lets Codex's cursor-painted banner be observed.
  • New focused regression test — spies on readTerminal to return a boot screen and then a ready header, asserting the wait settles after exactly two reads with { screen: true }.

⚠️ No captured Codex transcript pins the screen-reading rule

The new test replaces readTerminal with a spy, so it pins the retry loop and the read options but not the load-bearing claim that a real Codex 0.157 screen contains the ready header. src/main/runtime/__fixtures__/ has busy/ready pairs for Antigravity and Muse and none for Codex, and AGENTS.md/docs/reference/agent-pty-transcript-capture.md require any rule that reads an agent CLI's screen to be written against a captured raw transcript. Without a real Codex busy/ready pair, the false-idle window in the inline finding cannot be ruled out.

Technical details
# Pin Codex readiness to captured transcripts

## Affected sites
- `src/main/runtime/terminal-wait-name-only-idle.test.ts:298-319` — new test mocks `readTerminal`, so the actual rendered-screen path is never exercised.
- `src/main/runtime/__fixtures__/` — has `antigravity-busy-mid-turn.txt` / `antigravity-busy-turn-ended.txt` but no `codex-*` fixture.

## Required outcome
A raw `node-pty` capture of a real Codex pane in both the ready state and an active-turn state, replayable through `agent-transcript-pane-test-harness.ts`, so the detector's verdict on a working screen is observed rather than assumed.

## Suggested approach (optional)
Mirror `antigravity-readiness-transcripts.test.ts`: add a `codex-busy-mid-turn` / `codex-ready-composer` fixture pair and assert the wait refuses the busy screen and accepts the ready screen.

ℹ️ Nitpicks

  • The {} → { screen: true } change also applies to the null-agent / AGY-header probe paths. If that broadening is intended, the probe's JSDoc could name it; if not, gate it to the agents that need the rendered grid.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

// pane is identified as AGY (or its banner is present), regardless of that
// stale status.
(paneAgent === 'antigravity' ||
(paneAgent === 'codex' ||

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.

The added paneAgent === 'codex' gate starts the visible-screen probe while Codex may be mid-turn, and that probe resolves satisfied straight from isKnownReadyPromptPreview — it never consults getFirstPartyAgentStatus or the quiescence gate that isTuiIdleSatisfied applies to every other satisfaction site. Codex's ready header is a session-start history cell that stays in the viewport until the transcript scrolls it off, so a tui-idle wait created early in a turn can settle against a still-working Codex and the orchestrator will type into it. Please add a busy-screen guard (first-party working veto and/or a Codex interrupt/spinner marker) or a captured working-turn transcript proving the header is absent.

Technical details
# Codex probe bypasses the tui-idle evidence ranking

## Affected sites
- `src/main/runtime/runtime-terminal-wait.ts:157` and `:162` (PTY), `:259`/`:264` (leaf) — the added `paneAgent === 'codex'` gates start the probe when retained text is nonempty and the status is not null.
- `src/main/runtime/orca-runtime-start-tui-idle-visible-read-probe.ts:92-105` — `isKnownReadyPromptPreview(snapshotText)` decides readiness and `terminalWaiters.resolve` commits it without going through `isTuiIdleSatisfied`.
- `src/main/runtime/tui-idle-evidence.ts:59-61,168-170` — tier 2 documents that a fresh first-party `working`/`blocked` status vetoes inferred body evidence; the probe path never calls this, unlike the poll path.

## Required outcome
A Codex pane that is mid-turn must not resolve `satisfied: true` from a visible header alone. Route the probe verdict through the same ranking (at minimum the `getFirstPartyAgentStatus` veto and the quiescence demand), or reject a screen that still shows a live busy marker (e.g. `esc to interrupt`, a Codex spinner) after the header.

## Evidence
- `tests/e2e/ssh-codex-repro-remote-fixtures.ts:117-126` redraws `>_ OpenAI Codex` at the viewport top on every synthetic busy frame.
- `src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts:22-57` already asserts a booting Codex (MCP startup lines plus header) is idle from the tail path.
- `findCodexReadyPromptIndex` (`src/main/runtime/terminal-wait-detection.ts:143-151`) has no busy veto, unlike `findCursorReadyPromptIndex` at `:119-128`.

## Open question for the human
Is the Codex header guaranteed to have scrolled off the viewport before a completion `tui-idle` wait is created, or is settling during MCP startup accepted by design?

@GoldenFinger

Copy link
Copy Markdown

I independently reproduced the Codex 0.157 agent_readiness failure and tested a local fix against v1.4.213 and main at 668fa719 (the five touched files remain unchanged at current main 681f3ca1). Two observations may help this PR:

  1. The explicit { screen: true } read in this PR is necessary. My first local patch used readTerminal(handle, {}, { visibleScreenOnly: true }). A new regression test made that patch fail: when the retained tail is nonempty and Orca has not yet marked alternate-screen mode, the ordinary read may return source: stream without requesting the rendered screen. Changing that call to { screen: true } made the test pass. Please keep this part of Fix Codex worker readiness on cursor-painted terminal screens #22891.
  2. Please test the delayed-read boundary against terminal and status changes. The retry loop checks waiter membership. readTerminal also checks the live PTY handle on return, but the loop does not explicitly pin its starting incarnation or reject a newly known working state. A terminal replacement or status transition during an asynchronous read should not let an old ready screen settle the current wait. My local regression flips the incarnation, connection, cancellation, and first-party working state while the read is in flight; all four must leave the waiter unsettled. Serializing retries behind each bounded read also avoids overlapping provider snapshots.

Local evidence for the completed candidate: 74/74 focused Vitest tests; Node and CLI typechecks; oxlint/oxfmt on the five changed files; and 1/1 hidden Electron worker-start with fake Codex and prompt ACK. The new nonempty-tail case was RED against my initial patch and GREEN after the explicit screen request. The signed app has not been updated, so this is not a real Codex Worker GREEN on a released build. I can supply the tested patch or a focused follow-up PR if maintainers prefer. This comment is meant to help one of the existing overlapping PRs land, not to start a third competing implementation.

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @seonghobae for digging into the cursor-painted Codex 0.157 banner. Main already fixes this in #23475 (433986f), and the rules were later moved into rule files in #24375. For Codex panes, tui-idle now reads the live emulator screen, so a header painted by cell diff is rebuilt correctly whatever the retained text says. Because that check runs on every idle poll, a slow first paint gets picked up on a later tick, and the 0.158+ empty-composer screen is covered too. If terminal wait --for tui-idle still times out against a ready Codex prompt on the latest build, please comment or reopen.

@nwparker nwparker closed this Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Codex 0.157 worker-start times out at agent_readiness while the TUI is already at its prompt

3 participants