From e06960454c4037ebd833ee981b70113ad45ffaed Mon Sep 17 00:00:00 2001 From: BluePlexus <10006158+BluePlexus@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:13:37 -0600 Subject: [PATCH 1/2] fix(acp): keep the session alive for commands still running when the post-settle hold expires When the hold expires with only running commands holding the turn, record their tool-call IDs so hasPendingBackgroundWork pins the session through idle release. Each terminal tool update clears only its own command; runtime death, replacement and Stop clear all. Without this, idle release ends agy acp and kills the command before its wake can arrive. --- .../Adapters/AntigravityAdapterV2.test.ts | 73 ++++++++++++++++++- packages/provider-acp/src/server/adapter.ts | 50 +++++++++++-- 2 files changed, 115 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 9924d6c831833..81c8a372b9e52 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1691,7 +1691,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { // an empty pending list and a finished reply above Stop. it.effect("settles a silent background command after the post-settle hold timeout", () => Effect.gen(function* () { - const { command, offers, startTurn, until, throughPromptSettled } = + const { session, command, offers, startTurn, until, throughPromptSettled, runtimeDies } = yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); yield* startTurn(1, false); const prompt = yield* throughPromptSettled; @@ -1718,6 +1718,77 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", "the silent command is no longer left as live activity on a settled run", ); + assert.isTrue(yield* session.hasPendingBackgroundWork!, "idle release must keep agy alive"); + yield* runtimeDies; + assert.isFalse(yield* session.hasPendingBackgroundWork!, "a dead runtime cannot wake"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("pins both silent commands and continues on their independent wakes", () => + Effect.gen(function* () { + const commands = ["call_fetch", "call_tests"].map( + (toolCallId): EffectAcpSchema.SessionUpdate => ({ + sessionUpdate: "tool_call", + toolCallId, + kind: "execute", + title: `node ${toolCallId}.mjs`, + rawInput: { CommandLine: `node ${toolCallId}.mjs`, WaitMsBeforeAsync: 10000 }, + status: "in_progress", + }), + ); + const { session, offers, startTurn, send, usage, throughPromptSettled, throughTerminal } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + initialToolCalls: commands, + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("31 minutes"); + yield* throughTerminal; + yield* TestClock.adjust("31 minutes"); + assert.isTrue( + yield* session.hasPendingBackgroundWork!, + "both commands outlive the idle window", + ); + assert.lengthOf(offers, 0, "elapsed time alone cannot start a continuation"); + + // The first wake has no task id. It must run without dropping either command's pin. + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "The fetch finished." }, + }); + assert.lengthOf(offers, 1); + yield* offers[0]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(2, true); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_fetch", + status: "completed", + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + assert.include(JSON.stringify(yield* throughTerminal), "The fetch finished."); + assert.isTrue( + yield* session.hasPendingBackgroundWork!, + "the second command is still running", + ); + + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_tests", + status: "failed", + }); + assert.lengthOf(offers, 2); + yield* offers[1]!.dispatchIfCurrent!(Effect.void); + yield* startTurn(3, true); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "The tests failed." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + assert.include(JSON.stringify(yield* throughTerminal), "The tests failed."); + assert.isFalse(yield* session.hasPendingBackgroundWork!, "all command pins have cleared"); + assert.lengthOf(offers, 2); }).pipe(Effect.provide(layerSession)), ); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c4b90adc0c3d1..2f21b38e4bbd3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2698,6 +2698,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // Grok re-prompts on stale monitor notices; suppress output until a genuine terminal or app turn. const suppressPostSettleMonitorPrompt = yield* Ref.make(false); const runningBackgroundTaskIds = yield* Ref.make>(new Set()); + // These commands keep the session alive but must not gate other commands' wakes. + const expiredHoldCommandIds = new Set(); // Background command task id → the completed turn that owns its row. Ended commands stay, // bounded, so a later authoritative terminal still corrects the row on its run. const detachedBackgroundCommands = yield* Ref.make>( @@ -2842,6 +2844,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runtimeGeneration, Effect.gen(function* () { yield* Ref.set(runtimeRestartRequired, true); + expiredHoldCommandIds.clear(); if (!followsAgentWorkState) { // An open prompt fails with its transport. A turn held open for a running tool // has no prompt, so nothing else ends it. @@ -7292,6 +7295,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* markSessionCompacted(normalized.sessionId, normalized.update.compactionId); } yield* handleSessionUpdate(normalized); + const update = normalized.update; + if ( + (update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update") && + (update.status === "completed" || + update.status === "failed" || + update.status === "cancelled") + ) { + expiredHoldCommandIds.delete( + sessionScopedId(normalized.sessionId, update.toolCallId), + ); + } }, Effect.mapError( (cause) => @@ -8166,6 +8181,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(wakeReports, noWakeReports); yield* Ref.set(continuationRequested, false); yield* Ref.set(runningBackgroundTaskIds, new Set()); + expiredHoldCommandIds.clear(); yield* Ref.set(detachedBackgroundCommands, new Map()); yield* Ref.set(endedBackgroundTaskIds, new Set()); yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); @@ -8730,6 +8746,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(wakeReports, noWakeReports); yield* Ref.set(continuationRequested, false); yield* Ref.set(runningBackgroundTaskIds, new Set()); + expiredHoldCommandIds.clear(); yield* Ref.set(detachedBackgroundCommands, new Map()); yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); yield* Ref.set(carryoverSubagents, null); @@ -9013,6 +9030,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const timeoutMillis = Duration.toMillis(hold.timeout); const isRunningCommand = (tool: AcpToolCallState) => toolStatus(tool.status) === "running" && hold.isCommand(tool); + const generation = yield* Ref.get(runtimeCallbackGeneration); let quietSince = yield* Clock.currentTimeMillis; // Armed even without a command yet: a pending reply can still start one. yield* Effect.gen(function* () { @@ -9024,13 +9042,30 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Effect.sleep(Duration.millis(remaining)); continue; } - if ( - context.tools.values().some(isRunningCommand) && - !hasDeferredBackgroundWork(context, isRunningCommand) - ) { - yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); - return; - } + const settled = yield* runRuntimeCallbackAtGeneration( + generation, + Effect.gen(function* () { + if (context.finalized || context.interrupted) return true; + if (context.lastProgressAt + timeoutMillis > now) return false; + const commands = [...context.tools.values()].filter(isRunningCommand); + if ( + commands.length === 0 || + hasDeferredBackgroundWork(context, isRunningCommand) + ) + return false; + const status = context.promptSettledStatus ?? "completed"; + if (status === "completed") { + for (const { toolCallId } of commands) { + expiredHoldCommandIds.add( + sessionScopedId(context.nativeThreadId, toolCallId), + ); + } + } + yield* finalizeTurn(context, status); + return true; + }), + ); + if (Option.getOrElse(settled, () => true)) return; // Something else still holds the turn; count silence again once it clears. quietSince = now; } @@ -10313,6 +10348,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; if (yield* Ref.get(continuationRequested)) return true; if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; + if (expiredHoldCommandIds.size > 0) return true; const active = yield* Ref.get(activeTurn); if ( active !== null && From e5baf7bb0691b145e197a44581fd2ddd83b25ecd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 22:35:23 +0000 Subject: [PATCH 2/2] fix(acp): expired-hold command pins defer idle release only The pins made hasPendingBackgroundWork true, which also drives the detach, provider-switch and fresh-session guards. Those commands are not shown as pending tasks and have no Stop control, so a switch could be refused for hours. A new keepsIdleSessionAlive probe is read only by idle release. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AntigravityAdapterV2.test.ts | 20 ++++----- .../ProviderSessionManager.test.ts | 45 +++++++++++++++++++ .../ProviderSessionManager.ts | 5 +++ packages/provider-acp/src/server/adapter.ts | 2 +- .../src/server/ProviderAdapter.ts | 5 +++ 5 files changed, 65 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 81c8a372b9e52..9ae4ea18acf7a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1718,9 +1718,13 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", "the silent command is no longer left as live activity on a settled run", ); - assert.isTrue(yield* session.hasPendingBackgroundWork!, "idle release must keep agy alive"); + assert.isTrue(yield* session.keepsIdleSessionAlive!, "idle release must keep agy alive"); + assert.isFalse( + yield* session.hasPendingBackgroundWork!, + "a pin the user cannot stop must not block provider switches", + ); yield* runtimeDies; - assert.isFalse(yield* session.hasPendingBackgroundWork!, "a dead runtime cannot wake"); + assert.isFalse(yield* session.keepsIdleSessionAlive!, "a dead runtime cannot wake"); }).pipe(Effect.provide(layerSession)), ); @@ -1745,10 +1749,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* TestClock.adjust("31 minutes"); yield* throughTerminal; yield* TestClock.adjust("31 minutes"); - assert.isTrue( - yield* session.hasPendingBackgroundWork!, - "both commands outlive the idle window", - ); + assert.isTrue(yield* session.keepsIdleSessionAlive!, "both commands outlive the idle window"); assert.lengthOf(offers, 0, "elapsed time alone cannot start a continuation"); // The first wake has no task id. It must run without dropping either command's pin. @@ -1767,10 +1768,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* send(usage); yield* TestClock.adjust("3 seconds"); assert.include(JSON.stringify(yield* throughTerminal), "The fetch finished."); - assert.isTrue( - yield* session.hasPendingBackgroundWork!, - "the second command is still running", - ); + assert.isTrue(yield* session.keepsIdleSessionAlive!, "the second command is still running"); yield* send({ sessionUpdate: "tool_call_update", @@ -1787,7 +1785,7 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* send(usage); yield* TestClock.adjust("3 seconds"); assert.include(JSON.stringify(yield* throughTerminal), "The tests failed."); - assert.isFalse(yield* session.hasPendingBackgroundWork!, "all command pins have cleared"); + assert.isFalse(yield* session.keepsIdleSessionAlive!, "all command pins have cleared"); assert.lengthOf(offers, 2); }).pipe(Effect.provide(layerSession)), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index e6652c5963905..69bf631a77cd6 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -484,6 +484,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly initialProviderItemIdentityVersion?: 2; }) => Effect.Effect; readonly hasPendingBackgroundWork?: Effect.Effect; + readonly keepsIdleSessionAlive?: Effect.Effect; readonly hasPendingBackgroundWorkForThread?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; @@ -599,6 +600,9 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ...(options.hasPendingBackgroundWork === undefined ? {} : { hasPendingBackgroundWork: options.hasPendingBackgroundWork }), + ...(options.keepsIdleSessionAlive === undefined + ? {} + : { keepsIdleSessionAlive: options.keepsIdleSessionAlive }), ...(options.hasPendingBackgroundWorkForThread === undefined ? {} : { @@ -674,6 +678,7 @@ function layerTest(input: { readonly paused: Deferred.Deferred; }; readonly hasPendingBackgroundWork?: Effect.Effect; + readonly keepsIdleSessionAlive?: Effect.Effect; readonly hasPendingBackgroundWorkForThread?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; @@ -720,6 +725,9 @@ function layerTest(input: { ...(input.hasPendingBackgroundWork === undefined ? {} : { hasPendingBackgroundWork: input.hasPendingBackgroundWork }), + ...(input.keepsIdleSessionAlive === undefined + ? {} + : { keepsIdleSessionAlive: input.keepsIdleSessionAlive }), ...(input.hasPendingBackgroundWorkForThread === undefined ? {} : { hasPendingBackgroundWorkForThread: input.hasPendingBackgroundWorkForThread }), @@ -2139,6 +2147,43 @@ it.effect.each([ }), ); +it.effect( + "ProviderSessionManagerV2 keeps an idle session a runtime pins until the pin budget ends", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread-idle-pin"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }), + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + yield* TestClock.adjust("3 seconds"); + assert.isTrue(yield* manager.isLive(providerSessionId)); + yield* TestClock.adjust("3 seconds"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1_000, + maxIdlePinMs: 4_000, + keepsIdleSessionAlive: Effect.succeed(true), + }), + ), + ); + }), +); + const idleReleaseAroundRun = (start: "compactThread" | "resumeTurn") => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 291ac02272a26..0bc708a149703 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -1663,6 +1663,11 @@ export const layerWithOptions = ( : yield* probedRuntime.hasPendingBackgroundWork.pipe( Effect.catchCause(() => Effect.succeed(false)), )) || + (probedRuntime.keepsIdleSessionAlive === undefined + ? false + : yield* probedRuntime.keepsIdleSessionAlive.pipe( + Effect.catchCause(() => Effect.succeed(false)), + )) || // Closing now would skip the archive of a child whose parent has not taken its result. Option.isSome( yield* Effect.findFirst(entry.idleThreadUnloads.values(), ({ threadId }) => diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 2f21b38e4bbd3..83479d209ac09 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -10348,7 +10348,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if ((yield* Ref.get(midTurnUnreportedCompletedTaskIds)).size > 0) return true; if (yield* Ref.get(continuationRequested)) return true; if ((yield* Ref.get(runningBackgroundTaskIds)).size > 0) return true; - if (expiredHoldCommandIds.size > 0) return true; const active = yield* Ref.get(activeTurn); if ( active !== null && @@ -10365,6 +10364,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } return false; }), + keepsIdleSessionAlive: Effect.sync(() => expiredHoldCommandIds.size > 0), } : {}), ensureThread: Effect.fn("AcpAdapterV2.ensureThread")( diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 015a68f48982b..93a3526798fef 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -771,6 +771,11 @@ export interface ProviderAdapterV2SessionRuntime { /** Manager runtimes broadcast independent subscriptions; adapters may expose only a single-consumer stream. */ readonly subscribeEvents?: Effect.Effect; readonly hasPendingBackgroundWork?: Effect.Effect; + /** + * Defers idle release only, within the idle-pin budget. For work the user cannot see or stop, + * so it must not block detach, provider switches or fresh sessions. + */ + readonly keepsIdleSessionAlive?: Effect.Effect; /** Root-subscription probe; replacement checks opt in to subagents owned by the live process. */ readonly hasPendingBackgroundWorkForThread?: ( providerThread: OrchestrationV2ProviderThread,