fix(server): Stop always ends the background work a thread shows #14636
t3code/codex-turn-mapping fromrefs/pull/14636/head·merged by juliusmarminge View on GitHubPressing Stop on the composer's "Waiting on …" strip could do nothing. The orchestrator accepted the Stop, but ProviderTurnControlService dropped it for any settled turn whose adapter has no per-thread pending-work probe (every adapter except Claude and Codex). Codex's probe also missed work its process no longer tracked, and with no live provider session the Stop was rejected outright. The strip kept showing work nothing would ever end.
Fix#
- Stop always reaches the adapter.
ProviderTurnControlService.interruptnow forwards a settled turn's Stop withrequestRuntimeRestart: trueinstead of returning early. The adapter stops whatever it still runs, or reports there's nothing left. It still returns early in one case: no live session, so no adapter to call. - Adapters accept a settled Stop. A settled-turn Stop with nothing live is a no-op success in every adapter, so the settle step always runs.
- Claude: with no CLI process left for the thread (it exited after the turn), Stop succeeds and drops that gone process's roster. It used to fail with "has no live query" before anything was settled.
- Cursor and Pi: no-op success. Turn finalization already ended their tools, and Pi runs nothing between prompts.
- OpenCode: aborts the session's descendants, since a background
taskchild can outlive its turn. - Codex: a settled Stop it tracks nothing for returns instead of failing. Terminating a background terminal whose app-server already exited counts as terminated.
- Leftover work is settled after the adapter returns. The effect worker then dispatches a new internal command,
thread.background-work.settle. It marksinterruptedany background item (command_execution,dynamic_tool,subagent) the thread still shows on that provider thread, or on provider threads with no live session. It also clears the pending-work roster of a dead process. It does nothing if a new run has started since the Stop.- Bound to the stopped run. The command carries the stopped provider turn and settles only that run's work and older runs'. An item with no run counts as the stopped run's. A later run's work survives an earlier Stop.
- Idempotent. Its command id derives from the Stop command. A settle that ends nothing still records its receipt, so a replayed Stop effect (crash, failed outbox completion) hits the receipt instead of settling work that appeared since.
- No live session is no longer an error. A Stop on a settled turn with no live session settles directly, in the Stop command itself.
- Shared selection.
pendingBackgroundTurnItems(shared) is the selection the strip and the settle now both use, so they can't disagree.ProjectionStoregains aturnItemStatusesrecord filter so Stop reads only active items, not a thread's whole history.
Provider specifics stay in the adapters. The orchestrator only settles projected items that no live process will report on.
What Stop now does, per provider#
| Provider | Background work after the turn settles | Stop on the strip |
|---|---|---|
| Claude | Background Bash and subagents in the CLI process | Unchanged: the adapter closes the query, killing the tasks and clearing the roster. With the CLI process already gone, no-op plus roster reset, then leftovers are settled |
| Codex | Background terminals (unified exec) | Adapter terminates tracked terminals; work it no longer tracks (process gone, lost item/completed) is settled interrupted |
| Grok | Held runs stay running, so the regular Stop applies | Settled turn: ACP contains the orphan runtime (process-group kill), then leftovers are settled |
| ACP registry, Antigravity | Tools left open by a failed/cancelled prompt | Adapter no-op, then leftovers are settled interrupted |
| Cursor | None (finalization ends every tool) | No-op, anything shown is settled |
| OpenCode | Background task child sessions | Aborts descendants, then leftovers are settled |
| Pi | Tools left open by transport death or a rejected prompt | No-op, then leftovers are settled |
| Any, provider session released or restarted | Whatever the projection still shows | Settled directly by the Stop command |
Codex: is the stale item an adapter bug?#
I checked against Codex 0.156.1 source. Codex always sends item/completed for a background terminal, with the original turnId, including after turn/completed:
- Exit watcher:
core/src/unified_exec/async_watcher.rs:165-247. - Kill paths also complete the item (as
failed): terminate, clean, prune and timeout, inprocess_manager.rs:1725,1798,1835and:649-657. - Turn end never kills terminals:
core/src/tasks/mod.rs:782. - The adapter handles a late completion: via
resolveItemEventContext/settledTurns.
So there is no adapter bug to fix with a fixture. A projected item outlives its command only when the notification never reaches T3:
- the app-server exits or is released;
- the thread is unsubscribed on detach;
- a notification fails schema decode, which the client drops silently (
effect-codex-app-server/src/client.ts:165-170).
The maintainer's thread probably ran on a Mac, so I couldn't inspect it here.
Verification#
All server tests ran inside unshare -U --map-current-user -p -f --mount-proc. The branch contains the pid-1 group-kill guard (6562235).
- New tests: each fails on the base branch and passes with the fix.
CodexAdapterV2.test.ts, "Stop ends a background command no Codex process tracks any more". Through the orchestrator: a Codex background command is still running when the app-server exits. On base the command staysrunning.stop_background_work_after_failed_turn/acpRegistryreplay fixture, for an adapter without the probe. An ACP prompt fails while anexecutetool is in progress; the frames are hand-ported from the registry tool frames plus the recordedgrok_prompt_errorerror frame. On base the strip still listsdev-serverafter Stop.stop_background_work_after_release/acpRegistryreplay fixture. The same thread after the idle timeout released its session. On base Stop is rejected with "Provider session … is not active".
- Review follow-up tests: each fails on the previous head (813da49) and passes now.
ClaudeAdapterV2.test.ts, "a settled Stop with no CLI process left succeeds and clears the roster". The CLI exits after the turn settled with a background task on the roster. On 813da49 Stop fails with "has no live query".Orchestrator.control-reads.test.ts, "settles only the stopped run's background work, once". Two settled runs each have a running background command. The settle for run 1's Stop leaves run 2's command running. A settle that ended nothing replays as a no-op after new work appears. On 813da49 run 2's command is interrupted.
- Existing background Stop tests still pass:
claude_background_task_interrupt;- the Codex background terminal Stop tests ("stops a command after root completion…", "interrupts a completed run's background command through orchestration");
- Claude "stops background work after the turn settled" and its replaced-process sibling.
- Full files run:
OrchestratorReplayFixtures.integration.test.ts,CodexReplayFixtures.integration.test.ts,ProviderTurnControlService.test.ts,EffectWorker.test.ts,ProjectionControlReads.test.ts, and the Codex, Claude, Cursor, Pi and OpenCode adapter tests. 470 passed.ProjectionControlReads.test.tsasserted the old drop and was updated.packages/sharedorchestrationV2PendingBackgroundWork.test.ts: 31 passed.
- Review follow-up run (head 4743813), inside the PID namespace:
Orchestrator.control-reads.test.ts,EffectWorker.test.ts,ProjectionControlReads.test.ts,ProviderTurnControlService.test.ts,OrchestratorReplayFixtures.integration.test.tsand.contract.test.ts,ClaudeReplayFixtures.integration.test.ts,CodexReplayFixtures.integration.test.ts,CodexAdapterV2.test.ts,ClaudeAdapterV2.test.ts. 10 files, 395 passed. AcpAdapterV2.test.ts, outside the namespace (its process-tree tests need real process groups), 5 runs: 5 of 5 runs, 114/114 each (the 5 failures the first run reported were from running it inside the namespace). CI's "carries a live subagent lineage across an interrupt" failure on 813da49 is a timing flake, not this change. This PR touches no ACP adapter, runtime, test or mock-agent code, and that test callsinterruptTurnwithoutrequestRuntimeRestart, directly on the adapter, so the always-forward change inProviderTurnControlServiceis not on its path.- Static checks:
tsc --noEmitexits 0 with 0 errors for apps/server and packages/contracts (re-run on 4743813); packages/shared unchanged since.vp linton the touched files shows only pre-existing warnings.knipreports nothing in the files this PR touches.
- CI on 4743813: all six server shards, Check, Typecheck, Lint, Build and Macroscope Correctness are green.
- Not run: repo-wide checks, web/mobile clients, live providers.
Model: Claude Opus 5.5 (Claude Code)
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge added labelsmacroscope-review
- apps/server/src/orchestration-v2/EffectWorker.ts line 177Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -166,3 +166,12 @@166166 providerTurnId: effect.request.providerTurnId,167167 })168168 .pipe(169+ // The provider has stopped what it still ran and reported it.170+ // Whatever the thread still shows on that provider thread is171+ // work no process will report on, so the Stop ends it too.172+ Effect.andThen(173+ threads.dispatch({174+ type: "thread.background-work.settle",175+ commandId: CommandId.make(`${effect.commandId}:background-work-settled`),176+ threadId: effect.threadId,177+ providerThreadId: effect.request.providerThreadId,
🟡 Medium
orchestration-v2/EffectWorker.ts:177This settle command can mark a later run's pending background work as
interruptedafter an earlier Stop, because it targets every item onproviderThreadIdwithout binding settlement to the interrupted turn or run. If the initial execution returns beforecommitCommand, replaying the effect after a crash or failed outbox completion can repeat that settlement without a receipt. Bind the settlement to the original run/turn, or persist an idempotency receipt even when there are no events.Also found in 1 other location(s)
apps/server/src/orchestration-v2/Orchestrator.ts:9331Returning before
commitCommandleaves an emptythread.background-work.settleinvocation with no command receipt. The interrupt effect can be reclaimed after a process crash or a failed outbox completion and will dispatch its deterministic settle command again; if a later run has since finished with pending background items, that replay is no longer deduplicated and can mark the later run's itemsinterruptedeven though the original Stop did not target them. Persist an idempotency receipt (or bind settlement to the original run) even when the plan has no events.🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @apps/server/src/orchestration-v2/EffectWorker.ts around line 177: This settle command can mark a later run's pending background work as `interrupted` after an earlier Stop, because it targets every item on `providerThreadId` without binding settlement to the interrupted turn or run. If the initial execution returns before `commitCommand`, replaying the effect after a crash or failed outbox completion can repeat that settlement without a receipt. Bind the settlement to the original run/turn, or persist an idempotency receipt even when there are no events. Also found in 1 other location(s): - apps/server/src/orchestration-v2/Orchestrator.ts:9331 -- Returning before `commitCommand` leaves an empty `thread.background-work.settle` invocation with no command receipt. The interrupt effect can be reclaimed after a process crash or a failed outbox completion and will dispatch its deterministic settle command again; if a later run has since finished with pending background items, that replay is no longer deduplicated and can mark the later run's items `interrupted` even though the original Stop did not target them. Persist an idempotency receipt (or bind settlement to the original run) even when the plan has no events.Fixed in 4743813, both parts:
- Bound to the stopped run.
thread.background-work.settlenow carries the stoppedproviderTurnId. The settle resolves that turn's run and ends only work owned by that run or older ones. An item with no run counts as the stopped run's. A later run's pending work survives an earlier Stop's settle. - Idempotent on replay. The command id is already derived from the Stop (
<stop commandId>:background-work-settled). A settle that ends nothing now records an accepted receipt even with no events (theOrchestrator.tssite you flagged). A replayed effect hits that receipt instead of re-settling.
Test:
Orchestrator.control-reads.test.ts› "settles only the stopped run's background work, once". Two settled runs each have a running command; the settle for run 1 leaves run 2's running. Then an empty settle is replayed after new matching work appears, and is a no-op. On 813da49, run 2's command is interrupted.apps/server/src/orchestration-v2/ProviderTurnControlService.ts line 179Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -176,9 +176,4 @@176176 ? loaded.session177177 : yield* sessions.get(input.providerSessionId);178178 if (Option.isNone(session)) return;179- if (180- loaded.providerTurn.status !== "running" &&181- (session.value.hasPendingBackgroundWorkForThread === undefined ||182- !(yield* session.value.hasPendingBackgroundWorkForThread(loaded.providerThread)))183- )184- return;179+ // A settled turn reaches its adapter too: only the adapter knows🟡 Medium
orchestration-v2/ProviderTurnControlService.ts:179Forwarding a settled turn to
session.value.interruptTurnmakes an idle Claude session reject the stop withhas no live query, so the effect fails before dispatchingthread.background-work.settleand the waiting item remains stuck. Restore the per-threadhasPendingBackgroundWorkForThreadguard so settled turns without live background work skipinterruptTurn.🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @apps/server/src/orchestration-v2/ProviderTurnControlService.ts around line 179: Forwarding a settled turn to `session.value.interruptTurn` makes an idle Claude session reject the stop with `has no live query`, so the effect fails before dispatching `thread.background-work.settle` and the waiting item remains stuck. Restore the per-thread `hasPendingBackgroundWorkForThread` guard so settled turns without live background work skip `interruptTurn`.Fixed in 4743813, but not by restoring the guard. The guard is what made Stop do nothing on adapters without the probe.
Instead, a settled-turn Stop with nothing live is now a no-op success in the Claude adapter too, as it already was for Codex, Cursor, Pi, OpenCode and ACP. When the Claude session has no CLI process for that native thread,
interruptTurnwithrequestRuntimeRestartreturns. It also drops that gone process's roster and wake state. The settle follow-up then runs and clears what the thread still shows.Test:
ClaudeAdapterV2.test.ts› "a settled Stop with no CLI process left succeeds and clears the roster". On 813da49 it fails with "has no live query". - Bound to the stopped run.
Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This PR substantially changes Stop behavior across multiple production providers, including aborting descendants, terminating background processes, and durably settling orphaned work through a new orchestration path. The cross-provider runtime and process-lifecycle impact is broader than a small self-contained fix.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
ℹ️ No successful
mainbaseline artifact is available yet. This run establishes the initial measurement.Provider Metric Main baseline This PR Impact PR ceiling Codex Total thread wire — 4.9 KiB — 6.8 KiB ✅ Codex Thread snapshot wire — 3.7 KiB — 4.9 KiB ✅ Codex Live turn WebSocket wire — 1.2 KiB — 2.0 KiB ✅ Codex Live turn WebSocket decoded — 20.4 KiB — 29.3 KiB ✅ Codex Live turn messages — 2 — 8 ✅ Claude Total thread wire — 4.9 KiB — 6.8 KiB ✅ Claude Thread snapshot wire — 3.7 KiB — 4.9 KiB ✅ Claude Live turn WebSocket wire — 1.2 KiB — 2.0 KiB ✅ Claude Live turn WebSocket decoded — 20.8 KiB — 29.3 KiB ✅ Claude Live turn messages — 2 — 8 ✅ Baseline: unavailable · PR result:
4743813· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
- Codex decoded thread snapshot: 106.1 KiB
- Claude decoded thread snapshot: 106.4 KiB
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge merged this66a9107
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed