[Bug]: A send that would release a session's background work is refused, though the same message queued behind a turn is accepted
Before submitting
- [x] I searched existing issues and did not find a duplicate.
- [x] I included enough detail to reproduce or investigate the problem.
Area
apps/server
Steps to reproduce
- In a thread, let the agent leave background work running past the end of its turn: a native subagent, a command still running, or an MCP tool call still waiting.
- After the turn ends, while that work still runs, pick a model from another provider (or another account of the same provider) in the composer and send a message.
- For comparison, send the same message while a turn is still running, so it queues behind the turn and starts when the turn ends, while the work is still running.
Expected behavior
The direct send behaves like the queued one in step 3. startNextQueuedRun already handles that case without refusing:
- A hand-off to another provider (or a fresh session) starts and leaves the busy session running, so its background work is not ended.
- An account switch that resumes the busy session's native thread waits, and starts once that work has ended.
The message is never bounced back to the user.
Actual behavior
The send is refused with:
The previous provider is still running background agents or commands, and switching would end them. Wait for them to finish, or press Stop, then send the message again.
The user has to watch the thread and resend, or press Stop and lose the background work. On mobile this happens often in long threads where the main agent waits on subagents.
The direct path in Orchestrator.ts refuses whenever any session the send would release still has background work (sessionHasBackgroundWork over sessionsToDetach). The queued path in startNextQueuedRun checks the same sessions, keeps busy ones up for hand-offs and fresh sessions, and only waits for restart_and_resume. The tests pin both behaviours side by side in ProviderSwitch.integration.test.ts: "refuses the hand-off while the previous instance still runs background work" (direct) and "keeps a busy previous session running when a queued hand-off starts" (queued).
A related gap: the queued account switch is held (queueHeld), and nothing starts it when the work ends. The user has to resume the queue by hand.
Impact
Major degradation: switching the main model while subagents or long commands run (for example because the current account is running low) requires waiting and resending, or killing the work.
Version or commit
main at 240446e2d9
Environment
Windows 11 desktop server, iPhone app client. Codex (GPT-6.1 Sol) thread with running subagents, switching to Claude Opus 5.5.
Logs or stack traces
The previous provider is still running background agents or commands, and switching would end them. Wait for them to finish, or press Stop, then send the message again.
Screenshots, recordings, or supporting files
No response
Workaround
Wait until the background work ends, then resend; or press Stop, which ends the work.
One possible fix, which I run in a fork with tests: mika/queue-busy-switch. A direct send gets the queued-start semantics above. An account switch that has to wait is queued without a hold, and a check every two seconds retries startNextQueuedRun for threads that wait this way, so every existing queue guard (Stop, failures, usage limits, worktree) still applies. A send that arrives while one waits queues behind it.
Another case, with two differences from the report above: nothing visible was still running, and the refusal is silent in the desktop app.
Version: 0.1.9-nightly.20261110.4465, macOS desktop
What happened
- A thread on
claudeAgenthad earlier turns that started sixdelegate_taskchildren on another provider (acpRegistry). All six finished, and their completion notifications arrived before the thread's last turn. - The last turn completed. The thread had no active run, no queued messages and no pending requests.
- I picked Claude Opus 5.5 on a GitHub Copilot (
acpRegistry) instance in the composer. It showed "Context handoff pending: Opus 5.5 → Opus 5.5". - Pressing Enter or clicking Send did nothing visible: no error banner, and the message stayed in the composer.
What the server logged
All 13 sends over seven minutes failed in orchestration.dispatchCommand (message.dispatch), each with:
OrchestrationV2DispatchCommandError: The previous provider is still running background agents or commands, and switching would end them. Wait for them to finish, or press Stop, then send the message again.
At that time:
t3_thread_listwithincludeSubagentsshowed no running, waiting, queued or starting thread for it.- The thread's Claude CLI process had no child processes other than those started with the session (no shell commands).
- There was no Stop button, because the thread was idle.
I then terminated the idle Claude CLI process. The four sends after that were refused with the same error, so killing the process did not clear it.
The refusal comes from sessionHasBackgroundWork over sessionsToDetach. On the Claude adapter, hasPendingBackgroundWork checks pendingBackgroundTasksByNativeThread, sessionSubagentsByTaskId (status running) and wakeBuffers. I could not see which of these was non-empty.
Asks
- Show the refusal in the composer. Right now the send just looks dead.
- When the session is idle and nothing is visibly running, name what the guard thinks is still running, or offer a way to release it. "Press Stop" doesn't help when there is no Stop button.
- If the fix here keeps busy sessions running during a hand-off, as
startNextQueuedRunalready does, that would also unblock this case.
@qsc-rade-zivanovic Thanks, that's a useful second case. Here's what I found reading upstream main (41443e5706). None of it is reproduced against your logs, so treat the "which structure" part as the most likely explanation, not proof.
The delegated children are probably a bystander. Their completion notifications go through ProviderContinuationService as ordinary queued messages, so they never touch any of the three structures the guard checks.
What can stay set on an idle Claude session:
pendingBackgroundTasksByNativeThreadis cleared when the process exits (ClaudeAdapterV2.ts#L8380-L8409), so killing the CLI rules it out.wakeBuffersis the likely one. It holds frames that arrived while no turn was active. It survives process exit (the comment at L8410 keeps it on purpose), and a normal user turn only reads it.- Only a provider-continuation drain empties it (L11404-L11478). The other paths that clear it are a process replaced with a different native id, an open failure, or an interrupt with
requestRuntimeRestart. - If the one continuation offer fails or has no route,
requestedContinuationsstops any re-offer (L8639-L8648), and the buffer stays.
- Only a provider-continuation drain empties it (L11404-L11478). The other paths that clear it are a process replaced with a different native id, an open failure, or an interrupt with
- The session-level
hasPendingBackgroundWork(L11866-L11890) is looser thanliveProcessRunsBackgroundWork(L10824-L10855). It also counts subagents from earlier processes and finished wake buffers.
All of this is in-memory session state, so it clears on a server restart, or when the idle release finally lets the session go. That release is held by the same check, for up to the 4 h idle pin after the 30 min idle timeout (ProviderSessionManager.ts#L1192-L1232).
Log lines that would confirm it: claude-wake-turn-detected, claude-wake-turn-unroutable, provider-continuation.dispatch-failed, driver-session.idle-release-deferred.
Smallest fix I'd suggest:
- Have the session check count only work a detach would actually end. That means: no live process (or it's stopping) →
false; otherwiseliveProcessRunsBackgroundWork(live), plus root frames after the last bufferedresult. A wake buffer that already ends inresultis finished output, not running work. The same check also releases the idle pin. - Put what the guard found (
background_task/subagent/wake_turn+ label) into the error's existingdetailfield. When there's no Stop button, offer "release session", which maps to the existing interrupt withrequestRuntimeRestart. - Show
message.dispatchfailures at the composer. Today the web client only sets the thread error and restores the draft (useComposerSend.ts), which matches the send looking dead.
On your third ask: my branch for this issue (mika/queue-busy-switch) already does that for a switch to another driver. Claude → Copilot ACP is a create_with_handoff, and the busy session is kept instead of detached, so your send would go through. A same-provider account switch still waits in the queue there, and with stale state like yours it would wait until the idle release. That's why fix 1 belongs in the adapter, and I'll add it to the branch with a regression test.
The adapter fix is now on the branch: ca6212ae on mika/queue-busy-switch, rebased on today's main.
- What counts as running work: with no live process (or one that's stopping), nothing does. Otherwise it's the same work
liveProcessRunsBackgroundWorkcounts, plus a wake turn the CLI is still producing. A wake buffer that already ends inresultno longer holds a switch, and no longer holds the idle release either. - Naming the work: the guard now says what it found. The refusal reads e.g.
Still running: background task "npm test", wake turn., carried in the existingdetailfield. The same text appears in the "queue waits" log. - Tests:
- New tests cover your case: a finished wake buffer and then the CLI killed, which is no longer busy.
- A live background Bash task and a wake turn in progress still count as busy.
- A subagent from an earlier process doesn't count.
- A same-provider account switch with a stale finished wake now starts at once instead of waiting in the queue. That test runs the real Claude adapter with a fake query runner.
- Every new test fails without the fix. 406/406 in the adapter and provider-switch suites, 732/732 across the 21 related orchestration files.
- Not done yet: showing the refusal at the composer, and a "release session" action when there's no Stop button.
A third case, on the OpenCode adapter, where the guard dead-ends an idle thread. The fix branch above covers the Claude adapter only.
Build: T3 Code Nightly (Linux AppImage), packaged server runtimeLayer-TcYkIsVc.mjs.
Sequence
-
Root thread on the
opencodeinstance (OpenRouter model). It had severaldelegate_taskchildren running. -
The provider's credits ran out. Each child that finished woke the parent, and every wake run failed at once with the provider's 402-style "requires more credits" error (runs 3309, 3311 and 3312, 5 to 7 seconds each).
-
All children finished. The thread is idle, its status is
failed, and no run is active. -
The user picks a Claude model in the composer and sends. Both attempts are refused:
The previous provider is still running background agents or commands, and switching would end them. Wait for them to finish, or press Stop, then send the message again.
There is no Stop button, because nothing is running. The only provider the thread can still use is the one that cannot run, so the thread cannot move to another provider either.
Where it holds: sessionHasBackgroundWork → OpenCode2Adapter.hasPendingBackgroundWorkForThread → owesWork(state) = state.wakes.length > 0 || state.reports.size > 0 || (subagent busy) || some call.background. The parent's projection shows pendingBackgroundTasks: [], and every child is terminal. So the hold is most likely the reports (or wake) of children that never reached the parent, because every wake turn failed before takeReports/runWake could consume them. Not proven: that state is in memory and not exposed.
Expected: report-only state (finished children whose results are simply undelivered) should not count as "running work" that a switch "would end". If it must be kept, the target provider should receive it as part of the handoff. When the guard does refuse an idle thread, it needs a working way out, since "press Stop" has no button there. interruptTurn with requestRuntimeRestart runs stopBackground before it checks for an active turn, so an idle Stop could reach it.
@WhiteWarrior625 You were right that my fix only covered Claude. OpenCode has the same pattern, and so does Pi. Both are now on the branch: c8fb6b34 on mika/queue-busy-switch, rebased on today's main.
OpenCode (packages/provider-opencode/src/server/v2/adapter.ts): owesWork counts two things that are no longer running.
- An undelivered report.
state.reportsonly drains onsession.inbox.delivered/cancelledor when OpenCode starts a new execution itself. If the parent turn fails first (your 402), neither happens. - A wake whose execution already ended. It stays in
state.wakesuntil a continuation picks it up withrunWake.
The probes now count only work a detach would actually end: active background subagent calls, a busy subagent session, a wake OpenCode is still executing, and children such a wake started. owesWork still feeds the published pendingBackgroundWork snapshots, so ingestion stays open for native subagent continuations (#21460).
Pi: a wake stayed "busy" after agent_settled. It is now marked settled.
Tests: each new test fails without the fix.
- OpenCode: a finished child's report is waiting, the parent fails with 402, and the session is no longer busy. Same for a wake whose execution failed at once.
- An orchestrator integration test with the real OpenCode adapter (replay) covers your exact case. It fails an OpenCode thread with a finished child, then switches to Claude: the run starts and the OpenCode session is released. A control case with a still-running child keeps the session up.
- Pi: a settled wake is no longer busy.
- Results: server 1150/1150 across 27 files,
provider-opencode181/181,provider-pi121/121.
Same class, not fixed yet:
- Muse: a held wake that completed without a continuation offer stays forever. It's entangled with compaction, so it needs care.
- ACP/Grok: on process exit,
handleRuntimeTerminationAtGenerationreturns early for Grok and keepsrunningBackgroundTaskIds/wakeBufferset, so a Grok crash during a background task blocks a switch until the next session. - Codex: no gap on the switch path.
I'm on those next, along with your second point: a way out for an idle thread with no Stop button, and showing the refusal at the composer.
Same class as the usage-limit case reported in #34665 (closed as a duplicate of this one): the provider runs out of usage limit mid-thread while delegated subagents are still running on it, and the user cannot move the thread to another provider.
I checked against the current PR diff (#32508): it fixes the dispatch refusal (path 2) and the adapter probes, but there is a second gate before it that the diff does not touch.
Where it holds: thread.model-selection.set / provider.switch is refused with OrchestratorProviderSelectionBusyError ("Thread ... has an active turn. Wait for it to finish, then retry the provider selection change."):
apps/server/src/orchestration-v2/Orchestrator.ts:4053-4063— if the switch plan changes the instance, the command fails whenprojection.runs.some(isActiveRun).apps/server/src/orchestration-v2/CommandPolicy.ts:120-127—isActiveRunincludes"waiting".apps/server/src/orchestration-v2/RunExecutionService.ts:728-737— a run whose provider turn completed is persisted as"waiting"(not"completed") exactly while background work (subagents) holds completion. So while the subagents run, the run counts as an "active turn" indefinitely.
Effect: with subagents still running on the exhausted provider, the composer pick itself fails before any send. The user cannot even select the new provider; the dispatch-path fix only helps once the subagents have finished.
Why this looks like a gap worth closing here: the run in waiting has no steerable provider turn left — the only thing active is background work holding completion, which is the same situation the queued path already handles without refusing (startNextQueuedRun keeps the busy session up, Orchestrator.ts:2348-2369). Treating waiting as an active turn for instance-changing switches leaves the thread wedged on a provider that cannot execute anything until the limit resets (and the auto-resume re-pins the same provider, Orchestrator.ts:6222).
Possible shape: allow the instance-changing selection to land when every active run is only held by pending background work (no steerable provider turn), letting the handoff at dispatch time do the existing "busy session stays up" handling.
Thanks @Ryan-Carloso, I can confirm this. The gate came with #22755 (94f54a5, merged Nov 11). #32508 is based on an older main (b3fdf2b), so it can't touch it, and after a rebase the composer pick is refused before any send reaches #32508's dispatch handling.
There's a second half: applying a selection detaches releaseProviderSessionIds right away (provider-session.detached plus a detach effect). Only the dispatch path checks sessionHasBackgroundWork, so on main, a selection made after the turn has completed already ends the old session's background work.
I put a fix for both on a branch on current main: https://github.com/pingdotgg/t3code/compare/main...MikaMcFlurry:t3code:mika/selection-waiting-run
- The #22755 gate no longer counts runs that are only
waiting. Preparing, starting and running runs still block it, so #22755's case (a selection during a live foreground turn) is still refused. - Selection commands detach only sessions without background work. A busy session stays attached for the dispatch-time handling: on main that's the existing refusal; with #32508 the hand-off keeps it running.
- A same-instance selection that would restart a busy session is refused with a background-work message, so the restart isn't silently lost.
Each case has a test that fails without the change. A delegated completion that arrives after the switch is delivered on the new instance. The selection, switch and delegated-completion suites pass 300/300 (on cf906e1).
Happy to open it as a PR, on its own or folded into #32508.
Follow-up to my branch above: testing it further turned up one more case, now fixed in 9e32db0 (same branch, with a regression test and an independent review).
A message sent during the waiting run queues behind it. If the user then picks another account that shares native history, startQueuedRunOnce no longer saw a switch: the thread's selection already matched the queued run, and switchFromActiveProvider also required followsCurrent. So the queued run started beside the still-busy old session, which was never detached. Queued starts now plan from the active provider thread's instance, as direct dispatch already does: the start waits while the old session is busy and detaches it once the work ends.
Another case of this. We run a build based on upstream, and the code involved is the same on current main (6a29d58).
Setup: several Claude provider instances, each with its own config dir. That makes each instance a separate continuation group.
What happened (observed):
- A thread with pending delegated child tasks was running on Claude instance A. One of its turns hit the account's weekly usage limit, and the run ended as failed.
- After that, the model picker greyed out every other Claude instance with: "
is unavailable in this thread. Start a new thread to switch providers." - At the same time, the composer showed "Context handoff pending Opus 5.5 → Opus".
- A provider handoff to another instance was then recorded on the next run, and it succeeded. Later runs completed normally. So the server accepts the switch, and only the picker blocks it.
Code pointers (checked):
- The picker lock clears only when
threadSupportsProviderHandoff()(packages/client-runtime/src/state/threadWorkflows.ts) returns true. - The "handoff pending" banner (
packages/client-runtime/src/handoff.ts) uses a separate check. That is why the UI can show "handoff pending" and "unavailable" at the same time.
Our guess (not confirmed): no run was active at the time, so the active-run branch should not apply. We think the provider-thread association check near the end of threadSupportsProviderHandoff() is the branch returning false. We could not see the session or capability state through the public routes to prove it, so please treat this as a lead only.
Posted by Claude Opus 5.5, an AI agent, on behalf of the reporter.
@khairm's picker case reproduces in a unit test on upstream/main (2c4622efb4, includes 6a29d58):
threadSupportsProviderHandoff()returnsfalsewhen the session is gone, no run is active,activeProviderThreadIdpoints at a provider thread on instance A, andthread.modelSelection.instanceIdis B. With A = A it returnstrue.- An open delegated child doesn't change the result; its runs aren't runs of the parent thread.
- The
falsecomes from theproviderInstanceId === modelSelection.instanceIdcheck atpackages/client-runtime/src/state/threadWorkflows.ts:121. Dropping that one condition (keeping "belongs to this app thread") turns the test green; the otherthreadWorkflowstests and the mobilethread-provider-switchingtests still pass.
Not reproduced: how the live thread reached that state (selection on B without a provider thread on B yet). #32508 is server-only and doesn't touch this file. Happy to open a small PR with the test and fix if that's wanted.
Related gap on the steer path. When the provider is switched by a send while a held Antigravity run still has a background command, dispatchSteerIntoRun forces an interrupt and restart with a detach session transition. It never calls sessionHasBackgroundWork, so it neither refuses like the direct path nor keeps the busy session up like the queued path. The detached session's finalizer sends session/close, and agy 1.5.13 answers with ForceStopCascadeTree and kill_background_tasks=true, which ends the command with no notice to the user or to the next agent. Seen on nightly with a run held by a hung npm test. #36397 does not touch this path.