Repository navigation
fix(native-chat): only Codex's turn completion ends a Codex turn - #23682
Conversation
… the journal does The journal applies a lifecycle batch's settlement id once and skips any later batch with the same id. The deferred sink queue coalesced the same key the other way: a second batch replaced the first while it was still queued. So which record survived depended on whether the first had drained yet. A lifecycle batch now keeps the queued operation with its key, and a later one is accepted and dropped, which is what the journal does once the first is written.
Codex follows every turn-ending `error` (willRetry=false) with a failed `turn/completed` for the same turn, 0-32 ms later. That was captured from the real app-server on 0.141.0 and 0.158.0 across eight failure scenarios, and it is how Codex builds a failed turn: it records the error as the turn's last error, records any pending input, and then derives `failed` from that error when it completes the turn. The translator ended the turn twice: once on the error, and again on the completion, with a guard to make the first end final. Ending on the error threw away what only the completion carries: Codex's duration, and the completion's receipt time. It also forgot the turn before Codex recorded the turn's pending input. Now the error is only the row the user reads, inside the still-open turn, and `turn/completed` is the turn's only live end. A process exit between the two is the existing exit sweep's observed end, recorded as interrupted. A failed completion is stored as completed with outcome failure, live and on restore alike. Only `interrupted` maps to the interrupted state. The first-end-final guard is gone. Codex sends one completion per turn, the only redelivery Orca has is the retry of a refused frame (which changes nothing), and the settlement id already keeps the first record in the queue and the journal.
…ment The translator settled a streamed item when the transport rejected its notification as oversized. Nothing can produce that frame. The Codex stdio reader frames with `maxLineBytes: Number.POSITIVE_INFINITY` (codex-app-server-record-reader.ts), which it has done since the app-server records were uncapped. With an infinite limit the framer never reports `line-too-long`: no line, pending suffix or paused queue can exceed it. So the dispatcher never emits `frame:oversized-notification`, and the arm that settles it never runs. The arm, its helper module and its test go. In place of the test, the connection test now proves the reason: a notification past the old 16 MiB wire limit arrives whole, and no oversized frame is reported.
…h synthetic ones The replay reads ids only to group frames, so the real thread, turn and response ids from the capture account carry nothing the test needs. The fixture moves beside the Codex tests that read it.
'cancelled' read as a stop being recorded as a completion.
…h no verdict Codex's history carries the same status field as the live completion, so the restore path is pinned to the same mapping: completed, and no outcome.
|
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (20)
💤 Files with no reviewable changes (5)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughCodex turn errors no longer settle turns as failures; Priority: ➖ Normal Merge Risk: 🔵 Low · up to Codex turns now end only when Codex reports completion, and failed turns are recorded as completed with a failure verdict. Captured traces show this holds today. A Codex version that emits a terminal error without a completion could leave a turn appearing to run. This is a small residual risk that the owner should be aware of. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to The change makes failed turns more consistent, but turn completion now carries more responsibility for closing and attributing a turn. A duplicate or missing completion could leave the recorded lifecycle or its request attribution incomplete. No security exploit is established. Retained concerns
Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 19.05% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 14 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — read the complete raw diff (20 files, 7 commits), traced the deleted symbols for dangling references, and ran the focused Codex/agent-session-wire suites (226 tests) plus pnpm tc:node, all green.
- Only
turn/completedends a Codex turn — theerrorframe is now just anotification:errorrow inside the still-open turn.readCodexProviderVerdict,CodexJournalTurnBoundaries.fail()/end(), the first-end-finalrecentTurns.hasguard, andCodexJournalActiveTurns.isActiveare removed; a failed turn settles on Codex's own completion with its duration and the host start. - Failed completions store as
completed, failed—codexTurnLifecycleStatenow maps onlyinterruptedtointerrupted; the same change applies to the restore/history path, so live and restored failed turns agree. - Sink queue agrees with the journal on first-write-wins — a per-operation
keepsFirstflag drops a lifecycle batch whoselifecycle:<settlementId>is already queued, mirroring the reducer's applied-settlement-id rule. Set only onappendLifecycleBatch. - Unreachable oversized-notification path deleted — settler, its frame arm, and its test are gone; a new connection test proves a 16 MiB+1 notification arrives whole.
frame:oversized-notificationis still emitted and now falls through to a generic row, explicitly deferred to a separate change. - New evidence — a committed fixture of real 0.141.0/0.158.0 turn-ending frame orders (synthetic ids) replayed through the translator, plus journal-queue and refuse-then-retry settlement tests.
The one real trade-off — a Codex build that skipped the completion would leave the turn "Working" until the exit sweep marks it interrupted with no verdict — is called out in the PR body's rejected alternatives, and the chunk-splitting gap against a duplicate completion is likewise documented. Both are reasoned and acceptable.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
#23682 established that only `turn/completed` ends a Codex turn and deleted `codex-structured-journal-provider-verdicts.ts`, but the child-turn reader kept importing `readCodexProviderVerdict` and branching on its `turn-failed` verdict. The module is gone, so the import resolves to nothing: typecheck and static analysis fail on every pull request, which skips the whole unit matrix behind them, and the esbuild pass behind Bun profile scope detection throws, so every run falls back to all six platforms. A closed thread is now the only child-turn end without `turn/completed`, which is what #23682 intended: Codex follows a turn-ending `error` with a failed `turn/completed` for the same turn 0-32 ms later, and that completion carries the duration and receipt time the error does not.
…ot retry #23801 removed the child-path reading of Codex's turn-ending `error` along with the import of the module #23682 deleted. That was the wrong half to remove: the primary journal path can rely on Codex's failed `turn/completed` arriving within ~32 ms, which is what #23682 established, but a child turn has no such guarantee, and without the error as its end the child's lifecycle row latches on `working` for the life of the session. Three tests assert exactly that and could not run, because the unresolved import had been skipping the unit matrix since #23682 merged. The reading is restored inline against `readCodexErrorWillRetry`, itself restored to `codex-structured-thread-facts.ts`, rather than by reviving the deleted module: its `thread-stopped-running` arm lost its only consumer when #23682 rewrote the primary path, so restoring the file would re-add dead code. Also drops `pr-workflow-parallelism.test.mjs`'s read of `.github/workflows/track-community-prs.yaml`, which #23796 deleted while leaving the assertion behind. Same failure class, and it fails the same shard.
…3614) into #23059 Conflicts, resolved to keep main's mechanism and #23059's turn facts: - Codex turn boundaries and translator: main's #23682 wins; the error-driven `fail` end and the oversized-notification settler are gone, and only `turn/completed` ends a turn, a command's turn included. - Codex adapter: the compaction tracker stays deleted; #23618's settlement of sends in an ended turn is kept, and `codexDispatchRejection` is imported from its new home. - Journal reducer: main's per-item creating fence (#23456) moves into the item and submission folds this branch split out of the reducer. - Stale-turn verdict: main's proof-of-death revision; every turn revision states the thread scope. - Failure words: main's retry-control rules (#23608) with this branch's any-command retry step; `commandRefused` drops its retry step beside a Retry, as hostFault does. - Delivery: both the commit wake and main's death-evidence resettle and dispose. - Fold row and transcript slots: both the turn-outcome flag and main's `agentId`. - pr.yml and pnpm-lock.yaml taken from main. Beyond the conflicts, the merged files needed: - use-structured-agent-session: both sides added the same `submissions` key; one kept. - structured-agent-session-projection: the root-item import main still used is unused here. - The desktop message list and the mobile chat view each grew past the line limit from both sides' additions: the turn-membership memo moves into its own hook, and the mobile list footer (live status, then waiting rows) into its own helper.
…ot retry (#23808) #23801 removed the child-path reading of Codex's turn-ending `error` along with the import of the module #23682 deleted. That was the wrong half to remove: the primary journal path can rely on Codex's failed `turn/completed` arriving within ~32 ms, which is what #23682 established, but a child turn has no such guarantee, and without the error as its end the child's lifecycle row latches on `working` for the life of the session. Three tests assert exactly that and could not run, because the unresolved import had been skipping the unit matrix since #23682 merged. The reading is restored inline against `readCodexErrorWillRetry`, itself restored to `codex-structured-thread-facts.ts`, rather than by reviving the deleted module: its `thread-stopped-running` arm lost its only consumer when #23682 rewrote the primary path, so restoring the file would re-add dead code. Also drops `pr-workflow-parallelism.test.mjs`'s read of `.github/workflows/track-community-prs.yaml`, which #23796 deleted while leaving the assertion behind. Same failure class, and it fails the same shard.
…ts own turn/completed (#23783) * fix(native-chat): a Codex child's turn ends on its own turn/completed #22553 ended a child thread's turn on an `error` Codex will not retry, reading the verdict module #23682 deleted when it made turn/completed the only end of a Codex turn. The two landed minutes apart with no textual conflict, so main no longer typechecks. Codex runs every thread's events, spawned children included, through the same per-thread handler: a turn-ending error is recorded as the turn's last error and the turn then completes as failed. So a child's failed turn/completed is its end, as on the primary thread, and a closed thread stays the one child ending with no completion. * refactor(native-chat): a closed Codex child thread is its own frame With a child's turn now ending only on its own turn/completed, the turn-ended frame carried a fixed turnId (null) and state (unverifiable), and endTurn took parameters nothing passed. Name the one remaining case: a thread-closed frame, and closeThread ending the running turn as unverifiable. Drop a test step that no longer exercised anything.
A merge resolution kept this module while main's #23682 removed the only export it imports, so nothing built. Main already dropped the error path it served.

ELI5
When Codex fails a turn (for example "Selected model is at capacity"), it sends two messages: an error, and a few milliseconds later its own "this turn is finished, and it failed" message. Orca used to treat the error as the end of the turn and mostly ignore the finish message that followed. Now the error is only the message you read in the chat, and Codex's own finish message is the one thing that ends the turn. The failed turn is recorded the same way whether you watch it live or reopen the chat later.
What Changed
Before
errorframe. The finish message Codex sent right after it was dropped, so the stored turn kept the error's arrival time and never got Codex's own duration.errorframe that named no turn ended whatever turn was running, even though Codex was still working on it./compact.After
turn/completedis the only live end of a Codex turn. The failed completion arrives 0-32 ms after the error in every captured case, and it settles the turn with Codex's duration, its arrival time, and the start and send Orca already saw.errorframe writes the same error row as before, inside the turn that is still open. A retrying error (willRetry: true) is unchanged: the turn keeps running.interruptedcompletion is stored as interrupted.For the user this is a small change on screen. The error message and the stop look the same. "Working" lasts the extra few milliseconds until Codex's finish message. Reopening the chat shows the stored record, as before, and that record now carries Codex's duration.
Why
One ending, from the provider's own completion. Codex decides that a turn failed at the moment it completes it: it keeps the error as the turn's last error, records any queued input, and then marks the completed turn failed because of that error. The completion is Codex's own record of the turn. It carries the verdict, the duration and the error. Ending on the error meant ending on half of that record and then guarding against the other half. With one end there is nothing to guard. The idempotence the old rule gave now comes from the settlement id, which the queue and the journal already key on.
Evidence. The real
codex app-serverwas run with only the upstream model provider faked, on 0.141.0 (the oldest version Orca exercises; it is the pin in the SSH end-to-end test) and on 0.158.0 (the latest). It covered seven failure scenarios: model rejected, model too new for the CLI, "at capacity" by stream and by HTTP 503, stream dropped, connection refused, and/compactat capacity, plus a successful control and a turn with a bad working directory, which Codex accepted and completed normally. There were 13 turn-ending errors, and each was followed by a failedturn/completedfor the same turn 0-32 ms later. An interrupt never sendserror. On 0.158.0, connection refused retries for four minutes withwillRetry: trueand no completion, because the turn really is still open. A trimmed copy of those frame orders, with synthetic ids, is committed as a test fixture and replayed through the translator.The #23514 rule. It is removed, because a duplicate completion does not occur and would not matter if it did.
turn/interruptsent 30 s after a failed completion got "no active turn to interrupt" and no second completion.Alternatives rejected.
/compact.Differences from the common pattern
Linked Issue
This revisits #22044 ("a provider error that ends a turn leaves structured chat stuck on Working"), fixed by #22047. For Codex, #22047 ended the turn on the error, on the premise that Codex might never send
turn/completedafter it. Before #22047 a failed completion already ended the turn, so a stuck Codex chat needed a completion that never arrived. The captures found none: all 13 turn-ending errors were followed by their failed completion. The rest of #22047 is unchanged: Claude'sidlestill ends a Claude turn, and a Codex thread that stops running still releases a send whose dispatch was never answered. If a Codex build ever did skip the completion, the turn would read "Working" until Codex exits, when the exit sweep ends it.It also follows up #23514, which left "end on
turn/completedalone" for when there was a capture from the oldest Codex showing that the completion always follows the error. The captures above are that evidence. #23059 can then end a failed/compacton its completion the same way, instead of keeping its copy of the first-end-final rule.Visual Proof
Live QA on a Mac with real Codex (an app-server launched by Orca, with a model the account rejects, which makes Codex send an error and then a failed completion for the same turn). Built at 85f3c6f; the later commits change tests only.
A failed Codex turn settles as one turn that reads Failed, with its "Worked for":
Expanded, the model error row sits inside that turn:
After restarting the app, the turn still reads Failed:
Pressing Stop mid-answer (cases 3 and 4 ran in the same chat). The answer is cut off where Stop landed, with "Worked for 14s", and the tab's status dot is red; its label reads Interrupted. The stored record is interrupted with outcome cancellation. The transcript itself draws no stopped mark on that turn, which is the same on main and outside this PR:
A normal turn sent next in the same chat completes:
After it, that chat's tab shows a green check, the status of this newest turn (the other Codex tab, red, is the failed chat from case 1):
The stored turn record for the failed turn is completed with outcome failure, with its start time and a 1945 ms duration. It was unchanged 10 seconds later and after the restart. On main the same turn looks the same on screen but is stored at the moment the error arrived, with no duration.
Two things in these screenshots also appear on main and are not caused by this PR: the red "codex · notification:thread/status/changed" row, which is Codex's own "system error" status frame printed as a row, and a settled turn header whose screen-reader label still says "Agent is responding".
Testing
Manual test: real Codex, launched by Orca on a Mac, with a model the account rejects, so Codex sends an error and then a failed completion for the same turn. The turn settled once and read Failed, with "Worked for 2s" and the error row inside it. Its stored record was completed with outcome failure and a 1945 ms duration, unchanged 10 seconds later and after an app restart. After Stop, the turn's stored record was interrupted with outcome cancellation and the tab read Interrupted (the transcript itself shows no stopped mark, as on main); a normal turn sent next completed. On main the failed turn looked the same on screen, but its record kept the error's arrival time and had no duration.
Each new test was written first and failed against
main's behaviour, then passed after the change:main; the control, interrupt and bad-cwd cases passed on both.Tests that pass on
maintoo, and pin behaviour that must not change: an interrupt stays interrupted with outcome "cancellation", 0.158.0's four minutes ofwillRetry: truekeep the turn running until the exit sweep ends it, and a completion the sink refused settles once on its retry.Each behaviour was then broken on purpose to check its test fails: ending the turn on the error again (21 failures), a verdict on the exit sweep (2), the old failed-to-interrupted mapping (22), a queue that lets the later write win (2), an interrupt stored as completed (4), a retrying error that ends the turn (23), a capped stdio reader (2), and a completion that forgets the turn before the sink accepts it (1).
Lint, the changed-code quality gate, the main-process typecheck, and the Codex, agent-session-wire and journal unit tests (287 files) pass.
Notes
turn/completedwrites "completed, failed" instead of "interrupted, failed". That is the shape a failed turn already had live, so released clients read it. When Codex's turn history is restored, which happens only for a Codex too old to skip it on resume, a failed turn in it is written in the new shape. Rows already stored in either shape are left as they are and display the same.completed,interrupted,failedorinProgress, and a completion only ever carries the first three. AninProgressor unrecognised status on a completion is now stored as completed with no verdict, where it used to be stored as interrupted. A completion proves the turn ended, not how it ended. "Interrupted" would claim a stop nobody asked for, and a success verdict would claim a clean finish, which is what lights the "agent finished" notification. With no verdict Orca sends no finished notification and shows no Failed or Stopped mark.frame:oversized-notificationit still emits, which now falls through to an ordinary unhandled-frame row. It is left for a separate change, because it also covers responses and requests, which this PR does not touch.Author X: @BrennanKB5
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)