Skip to content

fix(codex): a message whose turn was stopped before Codex took it is withdrawn, not stuck - #23618

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/codex-accept-at-answer
Sep 28, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/codex-accept-at-answer

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​539 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​539
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​313 $\color{#cf222e}{\Huge{\mathbf{−}}}$​39 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​274

ELI5

In a Codex chat, if you pressed Stop just as Codex started, or sent a follow-up while Codex was answering and then pressed Stop, the chat could get stuck saying "Working…" forever and the message stayed as "sent". Codex had thrown that message away, but Orca kept waiting for Codex to confirm it. Now, when the turn a message was sent into ends without Codex taking it, Orca takes the message back and the chat goes idle.

What Changed

Before

  • Orca marks a Codex message delivered only when Codex repeats it back as the turn's user message (the "echo").
  • Codex answers the turn/start request first, and repeats the message a little later. A follow-up sent during a turn is folded into that turn and repeated later still.
  • If the turn is interrupted in between, Codex throws the message away (it clears the turn's pending input on interrupt). No echo ever comes, so the message stays "sent, waiting" until the Codex process exits.
  • Orca counts a waiting message as work in progress, so the tab, the sidebar and the chat all read Working. The follow-up bubble stays, with no answer.
  • This reproduced on main: 3 of 6 quick Stops right after a first message, and 3 of 3 follow-ups stopped mid-answer, were still stuck up to 14 minutes later, when the test ended.

After

  • When Codex answers turn/start, Orca notes in memory which turn that message went into. For a follow-up, that is the running turn.
  • When that turn ends, any message it was carrying that Codex never repeated back is settled from how the turn ended:
    • Interrupted: withdrawn, the same outcome as a message Stop takes back before it is handed over. The bubble leaves and the chat returns to Send.
    • Failed: shown as not accepted, with Codex's reason and Retry.
    • Completed: left waiting. Codex repeats everything a completed turn took before it reports the turn completed, so this does not happen in practice (it never did in live QA). If it ever does, the existing recovery when the Codex process exits still settles it.
  • The echo is still what marks a message delivered, with its identity. Nothing changes for a normal send.

Mechanism

  • startCodexTurn returns the turn id from the answer. bindTurn (codex-structured-dispatch-echo.ts) records it on that message's pending-echo entry, for the main thread only.
  • settleCodexSendsInEndedTurn (codex-structured-turn-end-settlement.ts) runs on each main-thread turn/completed and settles that turn's un-echoed messages through the existing late-settlement path. The journal already refuses to change a message once it is settled, so an echo that arrives later changes nothing.
  • An answer can be read after its turn has already ended, when both arrive in one read. A small in-memory record of recent turn endings (64, cleared when the Codex process exits) lets that message settle from the recorded ending, rather than wait forever.
  • A failed turn settles only at turn/completed, not at its error frame. Codex keeps a failed turn's pending input and repeats it before reporting the turn complete, so settling at the error would reject a message Codex actually kept. Retry would then send it twice.

Nothing new is saved. The message-to-turn link lives only in memory, for the life of the Codex process. The settlements use outcomes the journal already stores.

Why

The waiting state had no way to end except the Codex process exiting, and nothing in Orca watched the one fact that decides it: how the turn carrying the message ended. Codex's own rule is simple. An interrupted turn discards its pending input, and a finished or failed one records it first. So reading the turn's ending gives a true answer for every message, with no timer and no guess.

Alternatives considered:

  • Mark the message delivered as soon as Codex answers turn/start. Orca did this before fix(codex): settle a structured send on admission, and stop minting a colliding identity #20138 and removed it. A follow-up is answered with the running turn's id, so two messages ended up with the same saved identity, which rewind, restore and turn timing all rely on being unique. It would also record as delivered a message the model never received.
  • Mark it delivered at the answer without an identity, and fill the identity in from the echo later. This needs a new journal rule for filling in identities, and it still records the discarded message as delivered.
  • Time the message out. A timer cannot tell "Codex is slow" from "Codex discarded it", and a long first turn would be cut off.

Differences from the common pattern

  • Matches: taking the turn id from Codex's answer to turn/start, and keeping the per-message link in memory only.
  • Deviates: a common approach marks the message accepted when Codex answers. Here, acceptance stays on the echo, and a message whose turn was interrupted before the echo is withdrawn. Two reasons: Orca saves each delivered message's identity, which only the echo carries; and Codex discards interrupted input, so "accepted" would be false.
  • Known limit: a turn that Codex answers but never starts (older Codex versions did this) leaves its message waiting until the process exits, as on main today.

Linked Issue

No issue. Found in live QA of #23026 against real Codex. It reproduces on main with main's own Stop.

Visual Proof

Live QA on this laptop with the real Codex app-server (0.157), in structured Codex chats, with an isolated app profile. Before is main, after is this PR; both also carry #23552 for the test rig.

Scenario Before (main) After
Stop the moment the turn opens (6 runs) 3 stuck "Working…" for good; one more read Working because an earlier one was stuck 0 stuck. The 2 runs that landed before the echo were withdrawn within 13 ms of the turn ending; the rest were delivered normally
Follow-up sent during an answer, then Stop (3 runs) 3 of 3 stuck: bubble stays, chat reads Working 3 of 3 withdrawn within 51 ms of the turn ending; the chat returned to Send
Follow-up during an answer, no Stop (3 runs) not run Codex took it into the same turn and answered it; delivered once
Cold send, a second send, Stop mid-answer not run All normal; each message recorded once

Before: a follow-up stopped mid-answer, still "Working" 80 s later:

Before: the follow-up bubble stays and the chat reads Working for 1m 20s

After: the stopped turns stay, the withdrawn follow-ups are gone, and the composer shows Send:

After: stopped turns, no stuck follow-up, Send is back

Before: a Stop right as the turn opened, stuck:

Before: Cancellation requested, then Working with no way out

After: the same Stop, settled:

After: the message is withdrawn and the chat is idle

What a user sees with this PR alone: the withdrawn message leaves the transcript, and its text does not come back. Returning it to the message box is #23026's job. The "Cancellation requested." row and the tab's red interrupted dot are main's existing design.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • codex-structured-turn-end-settlement.test.ts (16 tests):

    • interrupted with no echo is withdrawn; failed with no echo is refused with Codex's reason;
    • completed with no echo is left waiting;
    • an echo before the ending wins;
    • a failed turn whose input Codex repeats after its error frame is accepted;
    • two messages in one turn each settle once;
    • child threads are ignored;
    • an answer read after its turn already ended as interrupted, failed or completed settles by that ending;
    • an answer that timed out still accepts on its echo;
    • the record of endings is cleared with the process.
  • structured-agent-session-codex-turn-end-settlement.test.ts (host, end to end): a quick Stop and a stopped follow-up both end withdrawn, and the session reads idle.

  • codex-turn-lifecycle-fake.ts: a fake Codex that refuses an interrupt before turn/started, as Codex 0.157 does, and that can deliver its answer out of order with turn/started and turn/completed.

  • Each behaviour was removed in turn, and its own test failed by assertion, not by timeout: 13 ablations across three review rounds.

  • pnpm tc:node and tc:cli, full oxlint on every changed file, check:code-quality:changed and check:react-doctor:changed pass. The related Codex test files (dispatch echo and admission, session adapter, session close, turn timing) pass.

  • Live: the table above. The real ~/.codex and ~/.claude files were checked before and after every run (65 checks) and never changed.

  • Not run: SSH, Windows and Linux. The change is in the Codex adapter on the machine that runs Codex, so it behaves the same on an SSH host.

AI Disclosure

Review

Three review rounds.

  • Round 1 found that a failed turn rejected a follow-up that Codex had kept (it settled at the error frame), and removed an unneeded wait before the settlement write.
  • Round 2 corrected comments about when a completed turn repeats its input.
  • Round 3 was clean and added the tests for an answer read after its turn ended.
  • An independent review of the plan, before the build, changed it from "delivered at the answer" to this design.

Mixed versions

Nothing on the wire changes. The rows are existing states: a withdrawn message and a refused message, each with an existing reason. An older client already shows both. It now sees one of them where it used to see a message stuck as sent.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security: none affected.
  • Cross-platform: same on macOS, Linux and Windows.
  • Remote SSH: the adapter runs on the execution host.
  • Mobile: reads the same journal rows.
  • Performance: a map write per turn ending, plus a scan of at most 256 waiting messages only on interrupted or failed endings.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author: @BrennanKB5

…fter that turn's rows

A settlement that says a streamed turn ended waits for the session's event
sink to drain before writing its dispatch row. The journal reducer still
refuses to overwrite an accepted or rejected send.
…into

The turn/start answer names the turn that holds a send. The send's echo
entry now keeps that binding, in memory only. If the bound turn is
interrupted without echoing the send, the send is withdrawn: Codex clears a
turn's pending input on interrupt, so the model never saw it. If the turn
fails first, the send is rejected in Codex's words. A completed turn settles
nothing, since Codex records pending input when it finishes and the echo is
still due. An answer read after its turn already ended is settled by that
end. The echo is still the acceptance and carries the item key.
…t into

The fake Codex keeps 0.157's turn bookkeeping, and can deliver the turn/start
answer after turn/started or after turn/completed. The tests cover:
- a Stop before any echo withdraws the send, and the working rule reads idle;
- a steered follow-up is withdrawn when the turn is interrupted;
- a failed turn rejects the send in Codex's words;
- a completed turn leaves the send to its echo;
- a normal echo and a late echo;
- two steered sends in one turn;
- an answer read after the turn ended;
- a timed-out answer;
- child-thread turns;
- how a binding dies.
…ettlement

Nothing reads the order of a dispatch row against the turn's terminal row:
the reducer keeps a settled send terminal and the working state is derived
from both. The echo acceptance on the same path never waited either, and the
wait could drop the settlement on a failed sink barrier.
Codex keeps a failed turn's pending input and records it after the error
frame, before turn/completed. Settling at the error rejected a steered
follow-up the model had in fact received, so a Retry would send it twice.
Codex records a completed turn's pending input before `turn/completed`, so
a bound send that turn never echoed is left for recovery, not awaiting an
echo. The comments and one test title said the echo was still due.
… or completed

A failed turn that ended before the answer rejects the send in Codex's words,
once; a completed one leaves it admitted and still armed for its echo.

@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.

✅ No new issues found.

Reviewed changes

This settles a Codex send whose turn ended without echoing it, replacing a wait that only ended when the Codex process exited.

  • Turn binding (codex-structured-dispatch-echo.ts) — armed sends gain an optional turn key; bindTurn records the turn Codex answered into and returns any already-recorded end, and endTurn records recent ends (bounded at 64) and returns the sends that end settles. Only non-completed ends settle, matching Codex echoing a completed turn's input before it ends.
  • Settlement policy (codex-structured-turn-end-settlement.ts) — reads the end from a turn/completed, maps interrupted→cancelled (withdrawn) and failed→providerRejected with turn.error.message, ignores non-primary threads and other frames. codexDispatchRejection moved here from turn-start.ts.
  • Dispatch path (codex-structured-turn-start.ts) — startCodexTurn returns the answered turn; an answer read after that turn already ended returns the ending's rejection directly.
  • Adapter wiring — settlements fire on an already-admitted notification and route through the existing late-settlement path; the deps union and settleStructuredAgentSessionLateDispatch already handle the rejected arm, and the journal reducer keeps accepted/rejected terminal for idempotence.
  • Tests — unit coverage for the echo/end orderings, late answers, timeouts, child threads, and process-exit clearing; host end-to-end coverage that a quick Stop and a stopped follow-up both end withdrawn with nothing owed.

I verified the load-bearing Codex contract against its source: TurnCompletedNotification { thread_id, turn }, Turn.status, and Turn.error.message on a failed turn (the completion handler in bespoke_event_handling.rs populates turn.error from the turn's recorded last_error), so the failed-turn reason is real and not only on the separate error frame. The retry queue is FIFO, so an accepted echo cannot be overtaken by the turn's completion.

pnpm test on both new files (18 passed) and pnpm tc:node are clean. The documented residual gaps (a send into a completed turn that never echoes; a turn/start answer that timed out is never bound) are pre-existing limits, not regressions.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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.

✅ No new issues found.

Reviewed changes

Incremental review of the one commit pushed since the prior review (3380874e).

  • Typed failed-turn reason reader — the failed-turn reason moved from a local field/errorDetail pair in codex-structured-turn-end-settlement.ts to readCodexTurnErrorMessage on codex-structured-thread-facts.ts, reading payload.turn.error.message through the existing record/nonEmptyString helpers and rejecting empty strings. The settlement now maps failed→providerRejected with that detail. Behavior-preserving; the sentence builder already trimmed an empty detail to nothing, so no user-visible change.

No other files changed. The core mechanism reviewed earlier is untouched.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Status

Ready for review. Head 3380874e532, based on main. CI green: 41 checks, none failed.

The failure: Orca marks a Codex message delivered only when Codex repeats it back. If the turn it was sent into is interrupted first, Codex discards it (it clears the turn's pending input on interrupt), so the message stayed waiting until the Codex process exited and the chat read Working.

The fix: it removes that cause rather than guarding it. Each message is linked, in memory, to the turn Codex's answer named, and it is settled from how that turn ended: interrupted means withdrawn; failed means refused with Codex's reason and Retry; completed means left to its echo, which Codex sends before reporting the turn completed. Nothing new is saved, and nothing on the wire changes.

Review

  • A plan review before the build dropped "delivered as soon as Codex answers". Orca did that before fix(codex): settle a structured send on admission, and stop minting a colliding identity #20138 and removed it, because a follow-up gets the running turn's id and two messages then shared one saved identity. It would also record as delivered a message Codex had discarded.
  • Three code review rounds. Round 1 fixed a failed turn rejecting a follow-up that Codex had kept, which Retry would have sent twice; a failed turn now settles only at turn/completed. Round 2 was wording. Round 3 was clean and added tests. After push, CI's anti-slop audit asked for a typed field read, which is now a shared thread-fact reader.

Validation

  • Live, with real Codex and an isolated profile, main against this PR:
    • a Stop right as the turn opened stuck 3 of 6 on main and none here;
    • a follow-up then Stop stuck 3 of 3 on main and was withdrawn 3 of 3 here;
    • a follow-up with no Stop was taken into the same turn 3 of 3;
    • normal sends and a mid-turn Stop are unchanged.
  • 13 ablations, each failing by assertion. tc:node, tc:cli, oxlint, the changed-lines gate, React Doctor and the anti-slop audit pass.

Known, not in this PR

  • A withdrawn message's text does not come back to the message box yet. That is fix(native-chat): Stop is there from the moment a message is sent #23026, which builds on this.
  • A turn Codex answers but never starts (older Codex versions) still leaves its message waiting until the process exits, as on main.
  • Codex's late reply to a request Orca stopped waiting for still shows as a raw row. A separate small PR moves it to diagnostics.

Review session at 3380874e532

  • Readiness checklist: PASS at the start and at the end, with no P0, P1 or P2 findings.
  • Final review loop: CLEAN, with no changes. It covered the whole diff, including the typed-reader commit made after CI.
  • Residual, unproven risks:
    • if more than 64 turn endings are read before one message's answer, that message waits until the Codex process exits;
    • a message re-sent with the same id after a timeout binds only to the later answer's turn.

@coderabbitai

coderabbitai Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 757765a4-f671-4a57-ba1e-4438191efe89

📥 Commits

Reviewing files that changed from the base of the PR and between 21f8e0f and 3380874.

📒 Files selected for processing (10)
  • src/main/codex/codex-structured-dispatch-echo.ts
  • src/main/codex/codex-structured-dispatch-test-support.ts
  • src/main/codex/codex-structured-session-adapter.ts
  • src/main/codex/codex-structured-session-state.ts
  • src/main/codex/codex-structured-thread-facts.ts
  • src/main/codex/codex-structured-turn-end-settlement.test.ts
  • src/main/codex/codex-structured-turn-end-settlement.ts
  • src/main/codex/codex-structured-turn-start.ts
  • src/main/codex/codex-turn-lifecycle-fake.ts
  • src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

Turn-start responses now provide a turn ID that dispatch sends can bind to. Matching interrupted and failed turn-end notifications settle bound sends as rejected; completed turns leave un-echoed sends pending. The adapter reports late settlements, and unit and runtime tests cover turn-end outcomes, delayed responses, echoes, and Stop scenarios.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 33808

The turn-end settlement change is mergeable after normal checks; no actionable issue remains from this review.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 33808

The change is confined to Codex message settlement within an existing session. No new external access or expanded privileges were identified. Rare delayed responses and failure recovery remain uncertain.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The new settlement path operates on the session’s tracked sends and journal rather than introducing a new external ingress. Its effective exposure still depends on the existing provider-connection boundary, whose authentication was not established in this review.

Trust Boundaries and Controls

  • observed — The adapter returns on refused notification admission before attempting settlement. For admitted turn ends, thread equality and the tracker’s thread/turn key constrain which pending messages can be withdrawn.

Resilience and Maintainability Implications

  • inferred — The tracker deletes a settled send before the asynchronous journal write completes. A failed write is reported by the runtime callback rather than retried by a duplicate turn end; session-exit recovery is a remaining fallback. This extends an existing late-settlement pattern, and the reviewed evidence does not show that the PR worsens its security exposure.

Hardening Proposals

  • proposed — Establish a provider response-delay or turn-ID uniqueness guarantee, or retain a turn’s outcome while a turn-start response can still bind to it. This would make the 64-entry recovery window’s adequacy explicit.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 10 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 primary fix: withdrawing Codex messages whose turns stop before Codex accepts them.
Description check ✅ Passed The description is detailed and covers the required explanation, user-visible behavior, mechanism, rationale, testing, visual proof, compatibility considerations, and review notes. The linked issue is…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@brennanb2025
brennanb2025 merged commit d691486 into main Sep 28, 2026
41 checks passed
brennanb2025 added a commit that referenced this pull request Sep 29, 2026
…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.
brennanb2025 added a commit that referenced this pull request Sep 30, 2026
Main now settles a Codex send from the turn it was answered into
(#23618, #23679, #23850): an interrupted or failed turn that never
echoed a send withdraws or refuses it, and a completed turn leaves it
to its echo, which Codex records before turn/completed. That replaces
this branch's own mechanism, so every conflict resolves to main:

- journal-level terminal settlement (ownerEndedClientMessageIds,
  multi-row enqueueMany, terminalTurnFences, canResolveDispatch,
  hasTerminalTurn, turn_settled_before_acknowledgement) and the sink's
  onCommitted/onAbandoned/onDiscarded plumbing
- the dispatch-echo ownership model (start candidates, started
  evidence, terminal snapshots) and the late-settlement retry
- the connection's onResult response observer
- the shared-predicate command admission, which main expresses with
  its own fence and handover rules (#23524)

Codex's turn/steer, the part the host-owned queue still needs, is
re-expressed on main's model in the following commit.
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.

1 participant