Skip to content

fix(native-chat): end a structured turn when the agent reports it failed - #22047

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/structured-chat-error-turn-end
Sep 21, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/structured-chat-error-turn-end

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​400 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​400
Prod 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​357 $\color{#cf222e}{\Huge{\mathbf{−}}}$​56 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​301

ELI5

When an agent hits an error that stops it mid-task — "Selected model is at capacity", for
example — the chat used to keep spinning "Working for N" forever, even though the agent had
already given up. It never stopped on its own.

Now the chat stops when the agent stops, and shows how long the turn actually ran.

What Changed

Before: the error appeared in the transcript, and the counter kept climbing — 50s, 5m, 40m —
for the rest of the session. The session also stayed listed as working in the sidebar,
worktree ps, and mobile, because all of those read the same status. The only way out was to
send another message or restart the app.

After: the turn settles the moment the agent reports it failed. The error stays exactly where
it was, and the turn shows "Worked for 21s" like any other finished turn.

Before After
final-before.png final-after.png

The second red row in the Before shot is deliberately left alone. A status frame whose payload
reports an error still surfaces, which is an existing tested guarantee that an unmodelled failure
always reaches the user. Quieting that row is a separate question from this fix.

The mechanism. A turn is shown as working while its durable turn row says running. Only two
things could ever write a terminal row for that turn: the agent's turn-completed notification, and
the agent process going away. An error that ends a turn is neither, so the running row stayed
put with nothing behind it to re-derive the truth — a latch with no way to die.

Three signals the agents already send now reach the code that owns the turn:

  1. Codex's error notification. It names the turn it ended and carries a retry flag: set when
    Codex is about to retry a stream error, clear when the error ended the turn. The turn-boundary
    owner gained a third terminal input alongside turn-completed and process-exit, and a clear
    retry flag settles the named turn as failed. A retrying error still ends nothing.

  2. Claude's session-state frame. Its idle arm is documented in the agent SDK as the
    authoritative turn-over signal — it fires once the held-back result has flushed. That now
    settles the open turn, with no verdict attached, because the frame says the turn is over and
    not how it ended. requires_action is not an end: the turn is parked on the user.

  3. Codex's thread-status frame. This deliberately settles no open turn — see Why. What it does
    settle is a send whose dispatch was never answered.

That third point fixes a second stall with the same shape: when a send's dispatch times out it is
recorded as "delivery unverified", which also reads as work still owed, and nothing in a live
session retired it — so one timed-out send left the chat reading working until the app restarted.
Retiring it never makes the send re-deliverable, since the agent may well have run it; a send still
awaiting its dispatch reply is left alone.

The Codex notification translator was split into two focused modules to stay inside its line
budget; no behavior rides on that split.

Why

The bug class is a durable flag with nothing re-deriving it. Adding a second guard in the renderer
would have hidden the symptom while leaving the same latch in the journal, where the sidebar,
worktree ps, and mobile all read it. Putting the terminal signal into the component that already
owns opening and settling the turn removes the class rather than the symptom.

Why the thread-status frame does not settle an open turn. It looks like the obvious signal and
it is the wrong one. The agent clears its internal running flag on every error, including the
ones it explicitly reports as not affecting turn status — so a turn still open when that frame
arrives is still running, and settling on it would falsely end live turns. Every path that clears
that flag was enumerated: turn-completed and turn-interrupted both ride with the notification we
already handle, process shutdown is the exit we already handle, and the error path either sends the
error notification handled above or means the turn is genuinely still running. The frame therefore
adds no correct turn settlement and only incorrect ones. It is used for the unanswered-send case
only, where no turn is open by definition.

Why no new retry or timeout. Time elapsing is not evidence an agent stopped; every signal used
here is the agent's own statement.

Linked Issue

Fixes #22044

Visual Proof

Attached above. Both frames are the real transcript components rendered from journal rows produced
by the real Codex translator — the Before frame from this branch's merge base, the After frame from
its head — so the difference is the change itself and not a hand-built mock.

Testing

Automated, at the layer where the bug lives:

  • A terminal error settles the turn it names and keeps the error row; a retrying error leaves the
    turn running; an error naming an already-settled turn does not overwrite its recorded duration;
    a later turn-completed does not reopen it.
  • Claude: idle settles the open turn with no verdict; running and requires_action do not; an
    error result's recorded verdict survives a later idle; the next send still opens a turn.
  • The thread-status frame reports not-running only when no turn is open.
  • The unanswered-send release retires an unverified send, leaves a send still awaiting its reply
    untouched, and keeps the sharper original reason.

Each of these was checked against a build with the change removed, so they pin this change rather
than pre-existing behavior. Verified locally: pnpm tc, oxlint, and the changed-code quality
gate clean; the Codex and native-chat suites pass (3380 tests).

Platforms: logic is platform-independent (no paths, shells, or process spawning). Exercised on
macOS. Nothing here is SSH-specific — the execution host owns turn state and this changes only what
that host concludes from frames it already receives.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

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

  • Backwards compatibility: the turn row keeps its existing shape; a settled-on-error turn uses
    the completed state with a failure verdict, which every reader already understands. No wire
    change, so a mixed-version client is unaffected.
  • Mobile: reads the same projected status and gets the fix with no mobile change.
  • Performance: two field reads per notification on frames already being parsed.
  • Security: no new process, network, or filesystem surface.

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)

…failed (#22044)

A turn reads as working while its durable turn row says `running`, and only two
events could write a terminal row: the provider's turn-completed notification and
the provider process going away. A provider error that ends a turn is neither, so
the row stayed `running` with nothing re-deriving it, and the chat counted
"Working for N" for the life of the session.

Codex reports such a failure as an `error` notification naming the turn it ended,
with `willRetry` distinguishing it from a stream error it is about to retry. That
frame now settles the turn it names. Claude's CLI reports the same through its
session-state frame, whose `idle` arm the SDK documents as the authoritative
turn-over signal; that now settles the open turn too.

Codex's `thread/status/changed` deliberately settles no open turn: the app server
clears `running` on every error, including ones it reports as not affecting turn
status, so a turn still open there is still running. What it does settle is a send
whose dispatch was never answered — a timed-out dispatch is recorded as unverified
delivery, reads as work still owed, and nothing in a live session retired it.
Retiring it never makes the send re-deliverable.

Splits the codex notification translator so the file stays inside its line budget.
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

📝 Walkthrough

Walkthrough

Claude structured launches now force session-state events and complete turns when Claude reports idle. Codex translation now handles terminal provider errors, centralizes notification routing, and reports stopped primary threads after active turns close. The runtime releases unanswered unknown dispatches with a provider-idle reason and preserves existing dispatch reasons. Tests cover terminal errors, thread states, Claude session states, launch configuration, and dispatch recovery.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to f34e9

A provider that resumes after reporting idle can have its outstanding dispatch marked recovered when the turn completes, leaving the session incorrectly idle while work is still active. Clear the deferred state before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 25 functions across 23 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 identifies the primary fix: ending a structured turn after the agent reports a terminal failure. It does not mention the additional Claude session-state and unanswered-dispatch handl…
Description check ✅ Passed The description is complete and matches the repository template. It includes the user impact, implementation details, rationale, linked issue, visual proof, testing results, platform considerations, A…
Linked Issues check ✅ Passed Issue [#22044] requires provider-ended turns to stop, preserve the error row, and retire appropriate timed-out dispatch work. Codex non-retryable error notifications now fail the named active turn. Re…
Out of Scope Changes check ✅ Passed The changed files support [#22044]. Provider verdict readers, turn-boundary handling, Claude session-state launch and translation changes, Codex thread-status routing, unanswered-dispatch release logi…
  • 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.

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 7e1224ea-50f3-432a-ad37-5c2e26f0e12d

📥 Commits

Reviewing files that changed from the base of the PR and between 663d670 and dcc31efd47dc197984d00296b01cd6f4c84dcc6c.

📒 Files selected for processing (21)
  • src/main/claude/claude-session-state-turn-over.ts
  • src/main/claude/claude-structured-journal-translation-turn-timing.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/codex/codex-structured-journal-contracts.ts
  • src/main/codex/codex-structured-journal-generic-frames.ts
  • src/main/codex/codex-structured-journal-provider-verdicts.ts
  • src/main/codex/codex-structured-journal-thread-item-routing.ts
  • src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
  • src/main/codex/codex-structured-journal-translation-turn-state.ts
  • src/main/codex/codex-structured-journal-translation-turns.ts
  • src/main/codex/codex-structured-journal-translation.test.ts
  • src/main/codex/codex-structured-journal-translation.ts
  • src/main/codex/codex-structured-session-acquire.ts
  • src/main/codex/codex-structured-session-state.ts
  • src/main/codex/codex-structured-thread-facts.ts
  • src/main/native-chat/agent-session-journal/journal-dispatch-doubt-reasons.ts
  • src/main/native-chat/agent-session-wire/provider-frame-disposition.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unanswered-dispatch-release.test.ts
  • src/main/runtime/structured-agent-session-runtime.ts

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

Comment on lines +233 to +244
if (admission.accepted) {
if (turnLifecycle) {
this.recentTurns.remember(
event.threadId,
turnLifecycle,
requestOrigin,
latestDispatchSequence
)
}
this.deps.items.ordinals.forgetTurn(event.threadId, turnId)
this.deps.activeTurns.forget(event.threadId, turnId)
this.deps.resetActivity(event.threadId)

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '90,260p' src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
sed -n '104,180p' src/main/codex/codex-structured-journal-settlement.ts
rg -n 'late|completion follows|turn/completed|recentTurns|isActive' src/main/codex/codex-structured-journal-translation.test.ts src/main/codex/codex-structured-journal-translation-turn-boundaries.ts

Repository: stablyai/orca

Length of output: 13857


🏁 Script executed:

sed -n '1,120p' src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
sed -n '240,310p' src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
sed -n '320,475p' src/main/codex/codex-structured-journal-translation.test.ts
rg -n -C 8 'class CodexJournalRecentTurns|recentTurns|function codexTurnLifecycleBody|codexTurnLifecycleBody|type AgentJournalTurnLifecycle|interface AgentJournalTurnLifecycle' src/main/codex src/main

Repository: stablyai/orca

Length of output: 42231


🏁 Script executed:

sed -n '240,300p' src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
sed -n '340,425p' src/main/codex/codex-structured-journal-translation.test.ts

Repository: stablyai/orca

Length of output: 4917


Ignore turn/completed for recently settled turn IDs.

fail() settles the turn, stores its lifecycle in recentTurns, and removes it from activeTurns. A later complete() with the same explicit ID still builds a new lifecycle and writes it under the same identity. Because settled() reads metadata only from activeTurns, the new body can lose startedAt and duration. If the completion omits status, it can also replace the failure with a clean completion.

Guard complete() against recently settled turn IDs. Update the late-completion test to assert that the complete lifecycle body remains unchanged.

@@ -89,6 +89,7 @@ export async function acquireCodexStructuredSession(input: {
sessionId,
...(deps.now ? { now: deps.now } : {}),
primaryThreadId: () => primaryThreadId,
onPrimaryThreadStoppedRunning: () => deps.onPrimaryThreadStoppedRunning?.({ sessionId }),

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 -euo pipefail

rg -n -C5 \
  'class CodexAcquisitionRegistry|function .*deliver|deliver\s*[:=]|assertCurrent|onPrimaryThreadStoppedRunning|releaseUnansweredDispatches' \
  src/main

Repository: stablyai/orca

Length of output: 42675


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- candidate files ---'
git ls-files 'src/main/codex/*' | rg 'acquisition|acquire|adapter|registry|journal|runtime|dispatch'

printf '%s\n' '--- symbol locations ---'
rg -n -C4 \
  'class CodexAcquisitionRegistry|CodexAcquisitionRegistry|function deliverCodex|deliver\(acquisition|onPrimaryThreadStoppedRunning|releaseUnansweredDispatches|createCodexJournalTranslator|handle\(' \
  src/main/codex src/main/native-chat src/main/runtime \
  | head -n 500

printf '%s\n' '--- acquisition callback context ---'
sed -n '1,135p' src/main/codex/codex-structured-session-acquire.ts

printf '%s\n' '--- adapter delivery context ---'
sed -n '1,180p' src/main/codex/codex-structured-session-adapter.ts

Repository: stablyai/orca

Length of output: 42494


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- state and acquisition window ---'
sed -n '1,280p' src/main/codex/codex-structured-session-state.ts
sed -n '1,260p' src/main/codex/codex-structured-acquisition-window.ts

printf '%s\n' '--- acquire connection callback wiring ---'
sed -n '120,285p' src/main/codex/codex-structured-session-acquire.ts

printf '%s\n' '--- release callback consumers ---'
rg -n -C8 \
  'onPrimaryThreadStoppedRunning|DISPATCH_DOUBT_PROVIDER_IDLE|releaseUnansweredDispatches|onDispatchSettledLate' \
  src/main/codex src/main/native-chat src/main/runtime

Repository: stablyai/orca

Length of output: 44081


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- superseded acquisition lifecycle ---'
rg -n -C12 \
  'stopSupersededCodexAcquisition|closeFailedCodexAcquisition|cancelCodexAcquisitionAttempt|previousAttempt|acquisitions.start' \
  src/main/codex/codex-structured-acquisition-lifecycle.ts \
  src/main/codex/codex-structured-session-acquire.ts

printf '%s\n' '--- stale delivery tests and lifecycle tests ---'
rg -n -C10 \
  'supersed|stale|old|previous|buffer|drop|delivery|connection' \
  src/main/codex/codex-structured-session-adapter.test.ts \
  src/main/codex/codex-structured-session-adapter-lifecycle.test.ts \
  src/main/codex/codex-structured-acquisition-exit-proof.test.ts

Repository: stablyai/orca

Length of output: 42482


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C18 \
  'function closeCodexPublishedSession|closeCodexPublishedSession|sessions\.delete|requestedClose|ended\s*=' \
  src/main/codex/codex-structured-session-close.ts \
  src/main/codex/codex-structured-session-teardown.ts

Repository: stablyai/orca

Length of output: 19808


Fence primary-thread stop callbacks to their acquisition.

During replacement, the old session remains indexed while closeCodexPublishedSession waits for its connection to close. CodexStructuredSessionAdapter.deliver accepts events from that connection because it checks only connection identity. The old translator can then invoke onPrimaryThreadStoppedRunning, and the runtime releases unanswered dispatches by sessionId, which can affect the replacement’s dispatches.

Pass the acquisition identity through delivery and reject stale events before translator.handle().

Source: Learnings

@brennanb2025
brennanb2025 force-pushed the brennanb2025/structured-chat-error-turn-end branch from dcc31ef to 60fa174 Compare September 21, 2026 18:24

@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

Marking notification:thread/status/changed as covered by a typed reader removes the only error surface for systemError arms that have no companion error notification, and it leaves an existing test failing (codex-structured-journal-translation-streams.test.ts:560, confirmed by running it). The Codex/claude protocol work underneath is otherwise well-grounded — details below.

Reviewed changes

  • Claude turn-over on idle — a new claudeSessionStateEndsTurn settles the open turn as completed with no verdict when session_state_changed reports idle.
  • Codex terminal error — readCodexProviderVerdict treats an error notification with willRetry !== true as a turn end, settling the named turn as completed/failure (CodexJournalTurnBoundaries.fail).
  • Unanswered-send release — thread/status/changed reporting not-running with no open primary turn now retires live unknown dispatches (releaseStructuredAgentSessionUnansweredDispatches).
  • Bare-opcode suppression — notification:thread/status/changed is added to CODEX_TYPED_TRANSLATOR_KINDS, so its generic fallback row disappears.
  • Refactor — item/started|item/completed routing and echo attribution moved to codex-structured-journal-thread-item-routing.ts.

I verified the two external contracts the fix leans on: willRetry is the correct camelCase wire field, an error with willRetry === false is genuinely turn-ending, ThreadStatus is the four-arm tagged union assumed, and the SDK ships the result-before-idle ordering the PR relies on.

ℹ️ Claude idle settles whichever turn is open, and its emission is opt-in

Two things worth confirming about the Claude half, neither proven wrong. First, idle carries no turn identity, so any idle — including a late trailing one from an already-settled turn — closes whatever turn happens to be open at that moment; the ACP adapter for this frame has needed a debt counter for exactly that reason. Second, the CLI gates these frames behind CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS, which this repo sets nowhere, and the visual proof is Codex-only.

Technical details
# Claude `idle` attribution and emission

## Affected sites
- `src/main/claude/claude-session-state-turn-over.ts:21` — `claudeSessionStateEndsTurn` returns true on any `idle`, with no turn id on the frame.
- `src/main/claude/claude-structured-journal-translation.ts:232` — settles the currently open turn unconditionally.
- `src/main/native-chat/agent-session-wire/claude-stream-json-frame-schema.ts:32` — frame is catalogued but no existing test builds a real one; only the PR's new unit test does.

## Open questions for the human
- Was a real Claude session exercised end-to-end for this path? The attached proof is a Codex transcript, and the CLI only emits `session_state_changed` when `CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS` is truthy. If it is not enabled on Orca's spawn, `claudeSessionStateEndsTurn` never fires.
- If a trailing `idle` can land after the next send has opened a turn, that new turn is closed `completed` with no outcome. The frame has no turn id, so the settlement has no attribution to check.

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

type ThreadItemEvent = Extract<CodexStructuredSessionEvent, { type: 'notification' }>

/** Null means no arm claimed the item; the caller falls back to a generic row. */
export type CodexThreadItemRouting = CodexJournalTranslationAdmission | null

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.

createCodexThreadItemRouter never returns null — every arm returns an admission, and appendUnhandled always returns one — so this null contract is dead and the caller's fallback at codex-structured-journal-translation.ts:253 can never be taken. Drop the | null arm and the comment, or actually return null for an unclaimed item and let the caller fall back.

@@ -56,3 +56,17 @@ export function readCodexTurnDurationMs(payload: unknown): number | null {
const value = record(root.turn)?.durationMs ?? root.durationMs
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
}

/** `error` carries `willRetry`: Codex sets it on a stream error it is about to

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.

Minor doc inaccuracy: upstream ErrorNotification.willRetry is a required bool (camelCase serde of will_retry), always present, so it is never omitted — it is hardcoded true/false at the two construction sites. Suggest rewording to "always present; true on a stream error Codex is about to retry."

@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 in this delta — the deferred release is correct and covered, and the previously blocking error-surface concern is resolved.

Reviewed changes

  • Removed the thread/status/changed covered-kind suppression — provider-frame-disposition.ts and codex-structured-journal-generic-frames.ts are gone from the diff, so a systemError still surfaces through the generic error path (codex-structured-journal-translation-streams.test.ts:560 is green again).
  • Deferred the unanswered-dispatch release until the open turn ends — a primaryThreadStoppedRunning flag plus reportPrimaryThreadStoppedRunning(), fired after an accepted turn boundary or fail(), so a thread/status/changed frame arriving before the terminal error/turn/completed still retires the dispatch once the turn closes rather than being dropped entirely.
  • Added two ordering tests — status-before-terminal-error and status-before-turn-completion, both of which fail against the pre-deferral code.

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

@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: 0d235e03-baed-4ca5-b360-55656c672723

📥 Commits

Reviewing files that changed from the base of the PR and between dcc31efd47dc197984d00296b01cd6f4c84dcc6c and f34e91a.

📒 Files selected for processing (4)
  • src/main/claude/claude-structured-launch-resolution.test.ts
  • src/main/claude/claude-structured-launch-resolution.ts
  • src/main/codex/codex-structured-journal-translation.test.ts
  • src/main/codex/codex-structured-journal-translation.ts

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

Comment on lines +271 to +277
const verdict = readCodexProviderVerdict(event.method, event.params)
if (
verdict === 'thread-stopped-running' &&
event.threadId === (deps.primaryThreadId?.() ?? null)
) {
primaryThreadStoppedRunning = true
reportPrimaryThreadStoppedRunning()

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

🔎 Supported by static analysis

🏁 Script executed:

sed -n '70,125p' src/main/codex/codex-structured-journal-translation.ts
sed -n '225,305p' src/main/codex/codex-structured-journal-translation.ts
sed -n '1,120p' src/main/codex/codex-structured-journal-provider-verdicts.ts
sed -n '50,85p' src/main/codex/codex-structured-thread-facts.ts
sed -n '400,520p' src/main/codex/codex-structured-journal-translation.test.ts

Repository: stablyai/orca

Length of output: 12044


🏁 Script executed:

printf '%s\n' '--- translator symbols and relevant branch ---'
rg -n -C 8 'primaryThreadStoppedRunning|readCodexProviderVerdict|thread/status/changed|turn/completed' src/main/codex/codex-structured-journal-translation.ts
printf '%s\n' '--- verdict implementation and consumers ---'
rg -n -C 6 'readCodexProviderVerdict|codexThreadStoppedRunning|CodexProviderVerdict' src/main/codex src --glob '*.ts'
printf '%s\n' '--- status-transition tests ---'
rg -n -C 10 'statusChanged|thread/status/changed|idle.*active|active.*completed|stopped running' src/main/codex --glob '*.test.ts'

Repository: stablyai/orca

Length of output: 35183


Clear the deferred stopped state when the thread becomes active again.

An idle or systemError status sets primaryThreadStoppedRunning while a turn is open. A later active status does not clear the flag because readCodexProviderVerdict returns null for active. When the turn completes, reportPrimaryThreadStoppedRunning can invoke onPrimaryThreadStoppedRunning although the provider is active.

Recognize active in the provider-status contract and clear the deferred flag when it arrives. Add an idle → active → turn/completed regression test that expects no callback.

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

ℹ️ One minor note on the new enabler; the env var itself is correct and the coverage is genuine.

Reviewed changes

  • Enabled CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS for structured Claude launches — exported the name and forced it to '1' after the inherited overlay, so Claude's session_state_changed(idle) frame reaches claudeSessionStateEndsTurn even when the user's overlay disables it. This is the piece the earlier review could not confirm was in place.
  • Covered it with two assertions — the steady-state launch env carries the flag, and an overlay setting '0' is overridden; I verified the second fails without the forced assignment.

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

...(overlay ? cloneDefinedEnv(overlay) : {})
...(overlay ? cloneDefinedEnv(overlay) : {}),
// The turn translator relies on Claude's authoritative idle frame when no result arrives.
[CLAUDE_SESSION_STATE_EVENTS_ENV]: '1'

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.

CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS is undocumented and only read by recent CLI builds — the ACP adapter hit the unsupported case on claude 2.1.77, and it first appears around 2.1.138. On an older binary resolved from PATH/nvm/pnpm the var is silently ignored and session_state_changed(idle) never fires, so the Claude half of this fix degrades to the old latch with nothing surfacing why. Harmless, but the prerequisite is currently undiscoverable — a one-line note here (or a probe, as claudeVersionSupportsSessionEnd does for the SessionEnd hook) would make it findable.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Hidden CDP check of f34e91a52d in this worktree.

The dev app identity was Orca: brennanb2025/structured-chat-error-turn-end with repo root /Users/brennanbenson/orca/workspaces/orca/porpoise. The renderer helper was bound to --user-data-dir=/tmp/orca-pr22047-profile.Sat9cS and remote debugging port 9441. Structured chat flags were enabled in the store.

This frame is the empty project shell (no workspace, no chat). It does not show a provider-reported failure, a stopped working indicator, or an error with a settled duration. That rendered flow was not exercised in this pass.

app shell

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review complete: CLEAN and mergeable.\n\nThe review found and pushed two meaningful lifecycle fixes:\n- Codex now treats non-retryable provider errors as terminal turns, preserves the provider error row, and defers unanswered-dispatch recovery until the primary thread has no tracked active turns. The provider ordering and retry protocol were checked; the deferred latch is conservative for out-of-order turns.\n- Claude structured launches now force the SDK session-state events required for the authoritative idle signal. An idle frame settles only an open turn without replacing an existing result verdict.\n\nValidation:\n- Same-agent review/fix loop returned CLEAN, including a final challenge of the deferred Codex latch.\n- Readiness checklist passed at both start and end.\n- 174 targeted tests across 9 files, full pnpm tc, pnpm tc:node, changed-code quality gate, changed-file oxlint, and git diff --check passed.\n- All PR CI checks are green; no docs or unrelated scope were added.\n- Hidden Electron/CDP proof verified the exact branch identity and structured-chat flags. The real renderer shell screenshot is attached here: https://github.com/user-attachments/assets/cd57123c-cc3c-4bcf-b390-884ea7a4bf79. A live provider-failure turn was not rendered before the validation timebox, so the screenshot does not claim to prove that UI state.\n\nNon-blocking performance note: unanswered-dispatch recovery scans the retained submission list; the existing status projection already scans that list, and no measured regression was found.

@brennanb2025
brennanb2025 merged commit dc8cf30 into main Sep 21, 2026
31 checks passed
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]: A provider error that ends a turn leaves structured chat stuck on "Working for N"

1 participant