From fe065eb4c3fb5bdb8760bad8861c5489bfbee36b Mon Sep 17 00:00:00 2001 From: YidaWeng <84164537+YidaWeng@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:10:18 +0800 Subject: [PATCH 1/8] fix(muse): keep background monitors visible and stoppable Muse monitors and backgrounded tool calls outlive their turn, but the adapter only tracked running subagent items. A monitor was never listed as pending work, the idle release could close its session, and Stop refused once the turn had ended. Track them from the item's background flag and reconcile against task/list, and end them with task/stopAll. --- .../provider-muse/src/server/adapter.test.ts | 94 ++++++++++++++ packages/provider-muse/src/server/adapter.ts | 120 ++++++++++++++---- packages/provider-muse/src/server/protocol.ts | 13 ++ 3 files changed, 202 insertions(+), 25 deletions(-) diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..2b8b354f71419 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -1727,6 +1727,100 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect("lists a running monitor as pending background work and stops it with the thread", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + const harness = yield* makeHarness(fake); + const turn = yield* startConversation(harness, fake); + const monitor = { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + }; + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { ...monitor, revision: 1 }, + }); + const listed = yield* harness.takeEvent( + "provider_thread.updated", + (event) => + event.providerThread.pendingBackgroundTasks?.some( + (task) => task.taskId === "monitor-1", + ) === true, + ); + assert.deepEqual(listed.providerThread.pendingBackgroundTasks, [ + { taskId: "monitor-1", kind: "monitor", description: "monitor", awaited: true }, + ]); + + // The turn ends while Muse keeps watching; the listing keeps the thread waiting. + fake.queueResponse("task/list", { + tasks: [ + { taskId: "monitor-1", kind: "tool.monitor", status: "inProgress", tool: "monitor" }, + ], + }); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "completed" }); + yield* harness.takeEvent("turn.terminal"); + assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); + + const stopped = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(stopped._tag, "Success"); + assert.strictEqual((yield* fake.takeCall("task/stopAll")).method, "task/stopAll"); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("lists a backgrounded tool call as a command and a monitor found on attach", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + const harness = yield* makeHarness(fake); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/updated", { + turnId: turn.nativeId, + item: { + itemId: "shell-1", + kind: "toolCall", + revision: 2, + status: "completed", + turnId: turn.nativeId, + tool: "shell", + background: true, + }, + }); + const listed = yield* harness.takeEvent( + "provider_thread.updated", + (event) => + event.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "shell-1") === + true, + ); + assert.deepEqual(listed.providerThread.pendingBackgroundTasks, [ + { taskId: "shell-1", kind: "command", description: "shell" }, + ]); + + // A monitor started before this client attached comes from `task/list` alone. + const resumed = yield* makeFakeMuse("resumed"); + resumed.queueResponse("task/list", { + tasks: [{ taskId: "monitor-2", kind: "tool.monitor", status: "inProgress" }], + }); + const attached = yield* makeHarness(resumed); + assert.deepEqual(attached.providerThread.pendingBackgroundTasks, [ + { taskId: "monitor-2", kind: "monitor", description: "monitor", awaited: true }, + ]); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("ends a compaction whose item names the held wake as its run", () => Effect.gen(function* () { const fake = yield* makeFakeMuse(); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..c0265a6b6accb 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -6,6 +6,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ProviderCapabilities, type OrchestrationV2ProviderRetry, type OrchestrationV2ProviderSession, @@ -33,6 +34,7 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; @@ -52,6 +54,7 @@ import { MuseItemEvent, MuseSessionResult, MuseSubscriptionUsage, + MuseTaskList, MuseTokenUsageEvent, MuseTodoList, MuseRetryScheduled, @@ -275,6 +278,29 @@ const nativeRef = (nativeId: string) => ({ /** The roster lists a child under its turn item's native id, so readers can pair the two. */ const backgroundTaskId = (item: MuseItem) => item.kind === "subagent" ? item.childSessionId || item.subagentId || item.itemId : item.itemId; + +/** One live row of `task/list`, kept until a later listing or Stop clears it. */ +interface LiveBackgroundTask { + readonly kind: "monitor" | "command"; + readonly description?: string; + readonly awaited?: true; +} +const isMonitorTask = (task: { readonly kind: string; readonly tool?: string | undefined }) => + task.tool?.toLowerCase() === "monitor" || task.kind.toLowerCase().includes("monitor"); +const liveBackgroundTask = (task: { + readonly kind: string; + readonly tool?: string | undefined; +}): LiveBackgroundTask => { + const monitor = isMonitorTask(task); + // Registry-only rows carry a `tool.` kind instead of a tool name. + const description = task.tool ?? task.kind.replace(/^tool\./, ""); + return { + kind: monitor ? "monitor" : "command", + ...(description ? { description } : {}), + // A monitor wakes the session when it reports, so the thread waits on it like a subagent. + ...(monitor ? { awaited: true as const } : {}), + }; +}; const recordSchema = Schema.Record(Schema.String, Schema.Unknown); const INFORMATIONAL_NOTIFICATIONS = new Set([ "session/contextUsage", @@ -368,6 +394,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const pending = new Map(); const seenTerminals = new Set(); const observedChildren = new Map(); + const liveTasks = new Map(); const childrenByItemId = new Map(); const agentTitles = new Map(); const finishedBackground: Array = []; @@ -385,7 +412,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( params: Record, command = true, commandId?: string, - ) => + ): Effect.Effect, ProviderAdapter.ProviderAdapterProtocolError> => Effect.tryPromise({ try: () => command @@ -752,20 +779,42 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( } }); const syncBackground = Effect.fnUntraced(function* () { - yield* updateThread({ - pendingBackgroundTasks: [...observedChildren].flatMap(([itemId, owner]) => { - const item = owner.items.get(itemId); - const description = item?.objective ?? item?.entryId ?? item?.fallbackText; - return [ - { - taskId: item ? backgroundTaskId(item) : itemId, - kind: - item?.kind === "subagent" ? ("subagent" as const) : ("background_task" as const), - ...(description ? { description } : {}), - }, - ]; - }), - }); + const tasks: OrchestrationV2PendingBackgroundTask[] = []; + const listed = new Set(); + for (const [itemId, owner] of observedChildren) { + const item = owner.items.get(itemId); + const taskId = item ? backgroundTaskId(item) : itemId; + if (listed.has(taskId)) continue; + listed.add(taskId); + const description = item?.objective ?? item?.entryId ?? item?.fallbackText; + tasks.push({ + taskId, + kind: item?.kind === "subagent" ? "subagent" : "background_task", + ...(description ? { description } : {}), + }); + } + // A monitor has no running turn item, so `task/list` is the only place it shows up. + for (const [taskId, task] of liveTasks) { + if (listed.has(taskId)) continue; + listed.add(taskId); + tasks.push({ taskId, ...task }); + } + yield* updateThread({ pendingBackgroundTasks: tasks }); + }); + // The item stream says a tool was backgrounded; only `task/list` says whether it still runs. + const refreshBackgroundTasks = Effect.fnUntraced(function* () { + const listed = yield* request("task/list", {}, false).pipe( + Effect.flatMap((value) => decode(MuseTaskList, value)), + // Never hold the event stream long on a host that will not answer. + Effect.timeoutOption(5_000), + Effect.option, + ); + // A host that cannot list tasks keeps what the items told us. + if (Option.isNone(listed) || Option.isNone(listed.value)) return; + liveTasks.clear(); + for (const task of listed.value.value.tasks) + if (task.status === "inProgress") liveTasks.set(task.taskId, liveBackgroundTask(task)); + yield* syncBackground(); }); const publishItem = Effect.fnUntraced(function* ( turn: ActiveTurn, @@ -806,6 +855,14 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (wasRunning !== running || (running && !listed)) yield* syncBackground(); } const streaming = status === "running"; + // A backgrounded tool call completes as a call but keeps running as work. + if (item.kind === "toolCall" && item.background === true) { + const task = liveBackgroundTask({ kind: item.kind, tool: item.tool }); + if (liveTasks.get(item.itemId)?.description !== task.description) { + liveTasks.set(item.itemId, task); + yield* syncBackground(); + } + } const base = { ...baseItem(turn, item.itemId, time), status, @@ -984,6 +1041,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (item) yield* publishItem(owner, item, status); } observedChildren.clear(); + // The process owns its background work, so stopping or losing the turn ends it too. + liveTasks.clear(); if (thread?.pendingBackgroundTasks?.length) yield* syncBackground(); for (const entry of pending.values()) yield* resolvePending(entry, "cancelled"); }); @@ -1575,6 +1634,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( "reusable", result.error?.quota, ); + // Background work outlives the turn that started it; re-read what Muse still runs. + yield* refreshBackgroundTasks(); break; } case "approval/requested": @@ -2022,6 +2083,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( driver: MUSE_PROVIDER, providerThread: thread, }); + // A monitor started before this client attached still keeps the thread waiting. + yield* refreshBackgroundTasks(); return thread; }).pipe( Effect.onError((cause) => @@ -2279,9 +2342,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( providerSession: session, events: Stream.fromQueue(events), backgroundTasksEndWithProcess: true, - // A running workflow or a held Muse turn keeps the host: idle release must wait. + // A running workflow, a live monitor, or a held Muse turn keeps the host: idle release must wait. hasPendingBackgroundWork: Effect.sync( - () => observedChildren.size > 0 || wake !== undefined, + () => observedChildren.size > 0 || liveTasks.size > 0 || wake !== undefined, ), ensureThread: (args) => register(args).pipe( @@ -2363,14 +2426,19 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( interruptTurn: Effect.fn("MuseAdapter.interruptTurn")( function* (args) { const turn = active; - // Recovering an ended turn is done unless Muse still runs work Stop cannot end. - if ( - !turn && - args.requestRuntimeRestart === true && - observedChildren.size === 0 && - wake === undefined - ) - return; + // Recovering an ended turn is done unless Muse still runs work Stop can end. + if (!turn && args.requestRuntimeRestart === true) { + if (liveTasks.size === 0) { + // A child or a held wake is not this call's to end; an idle turn is done. + if (observedChildren.size === 0 && wake === undefined) return; + } else { + // A monitor outlives its turn, so Stop must reach Muse's own task registry. + yield* request("task/stopAll", {}).pipe(Effect.ignore); + yield* settleObservedChildren("interrupted"); + wake = undefined; + return; + } + } if ( !turn || turn.providerTurn.id !== args.providerTurnId || @@ -2401,6 +2469,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( for (const joined of turn.joined) yield* request("turn/interrupt", { turnId: joined }).pipe(Effect.ignore); yield* request("turn/interrupt", { turnId: turn.nativeId }); + // Monitors and backgrounded tools are Muse-side work; the turn ending does not stop them. + yield* request("task/stopAll", {}).pipe(Effect.ignore); yield* Deferred.await(turn.done).pipe( Effect.timeout(options.requestTimeoutMs ?? 30_000), Effect.mapError((cause) => protocolError("Muse did not confirm interruption", cause)), diff --git a/packages/provider-muse/src/server/protocol.ts b/packages/provider-muse/src/server/protocol.ts index 87c9c922ef592..4705761165625 100644 --- a/packages/provider-muse/src/server/protocol.ts +++ b/packages/provider-muse/src/server/protocol.ts @@ -14,6 +14,8 @@ const MuseUsage = Schema.Struct({ export const MuseItem = Schema.Struct({ entryId: Schema.optional(Schema.String), + /** `toolCall`: `true` once Muse durably backgrounded the task; the work outlives the call. */ + background: Schema.optional(Schema.Boolean), children: Schema.optional( Schema.Array( Schema.Struct({ @@ -161,6 +163,17 @@ export const MuseTurnCompleted = Schema.Struct({ ), usage: Schema.optional(MuseUsage), }); +/** `task/list`: one row per live background workload, monitors and backgrounded tool calls alike. */ +export const MuseTaskList = Schema.Struct({ + tasks: Schema.Array( + Schema.Struct({ + taskId: NonEmptyString, + kind: Schema.String, + status: Schema.String, + tool: Schema.optional(Schema.String), + }), + ), +}); /** The latest instant a JavaScript Date holds; formatting a later one throws. */ export const LATEST_DATE_MS = 8.64e15; const DateMillis = Schema.Finite.check( From b5a04edafcdd48d62b40de9c4eda17ce98f614f1 Mon Sep 17 00:00:00 2001 From: YidaWeng <84164537+YidaWeng@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:18:20 +0800 Subject: [PATCH 2/8] fix(muse): end a woken turn when Stop stops its monitor A monitor that already woke the session leaves a Muse turn running. Stopping its task also interrupts that turn so no events are dropped on the floor. --- packages/provider-muse/src/server/adapter.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index c0265a6b6accb..ab22e946fb0d3 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -2434,6 +2434,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( } else { // A monitor outlives its turn, so Stop must reach Muse's own task registry. yield* request("task/stopAll", {}).pipe(Effect.ignore); + // A monitor that already woke the session left a turn this call must end too. + if (wake) + yield* request("turn/interrupt", { turnId: wake.nativeId }).pipe(Effect.ignore); yield* settleObservedChildren("interrupted"); wake = undefined; return; From 722436cbff1bcf12522c51d6915d2789f6e7bca6 Mon Sep 17 00:00:00 2001 From: YidaWeng <84164537+YidaWeng@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:23:49 +0800 Subject: [PATCH 3/8] fix(muse): label a registry-only monitor as a monitor A registry-only row has a work id in kind, not a tool name, so use the monitor label instead of the id. --- packages/provider-muse/src/server/adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index ab22e946fb0d3..9033abe062bf4 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -293,7 +293,7 @@ const liveBackgroundTask = (task: { }): LiveBackgroundTask => { const monitor = isMonitorTask(task); // Registry-only rows carry a `tool.` kind instead of a tool name. - const description = task.tool ?? task.kind.replace(/^tool\./, ""); + const description = task.tool ?? (monitor ? "monitor" : task.kind.replace(/^tool\./, "")); return { kind: monitor ? "monitor" : "command", ...(description ? { description } : {}), From ea5bddfd031b07452db15593047ccea90aa337f8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:25:56 +0000 Subject: [PATCH 4/8] refactor(muse): infer the request helper's return type Co-Authored-By: Claude Opus 5.5 --- packages/provider-muse/src/server/adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 9033abe062bf4..7926c90ceecc9 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -412,7 +412,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( params: Record, command = true, commandId?: string, - ): Effect.Effect, ProviderAdapter.ProviderAdapterProtocolError> => + ) => Effect.tryPromise({ try: () => command From 79fc28f170df1823fb9e22016a720c1c38cb43ed Mon Sep 17 00:00:00 2001 From: YidaWeng <84164537+YidaWeng@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:27:03 +0800 Subject: [PATCH 5/8] fix(muse): label a backgrounded call by its entry when it has no tool A backgrounded call without a tool name fell back to the item kind, which reads as toolCall in the waiting banner. --- packages/provider-muse/src/server/adapter.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 7926c90ceecc9..063df083c8dab 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -287,13 +287,17 @@ interface LiveBackgroundTask { } const isMonitorTask = (task: { readonly kind: string; readonly tool?: string | undefined }) => task.tool?.toLowerCase() === "monitor" || task.kind.toLowerCase().includes("monitor"); -const liveBackgroundTask = (task: { - readonly kind: string; - readonly tool?: string | undefined; -}): LiveBackgroundTask => { +const liveBackgroundTask = ( + task: { + readonly kind: string; + readonly tool?: string | undefined; + }, + label?: string, +): LiveBackgroundTask => { const monitor = isMonitorTask(task); // Registry-only rows carry a `tool.` kind instead of a tool name. - const description = task.tool ?? (monitor ? "monitor" : task.kind.replace(/^tool\./, "")); + const description = + label ?? task.tool ?? (monitor ? "monitor" : task.kind.replace(/^tool\./, "")); return { kind: monitor ? "monitor" : "command", ...(description ? { description } : {}), @@ -857,7 +861,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const streaming = status === "running"; // A backgrounded tool call completes as a call but keeps running as work. if (item.kind === "toolCall" && item.background === true) { - const task = liveBackgroundTask({ kind: item.kind, tool: item.tool }); + const task = liveBackgroundTask( + { kind: item.kind, tool: item.tool }, + item.tool ?? item.entryId, + ); if (liveTasks.get(item.itemId)?.description !== task.description) { liveTasks.set(item.itemId, task); yield* syncBackground(); From ada720d5857bfa310a55f7a31ee7740ba808d82a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:30:38 +0000 Subject: [PATCH 6/8] fix(muse): a failed task/stopAll keeps the monitor listed Stopping an ended turn's monitors swallowed a failed task/stopAll and cleared the listing anyway, so the thread looked idle while Muse still ran the work. Co-Authored-By: Claude Opus 5.5 --- packages/provider-muse/src/server/adapter.test.ts | 9 +++++++-- packages/provider-muse/src/server/adapter.ts | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index 2b8b354f71419..99d57ecddc023 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -1765,14 +1765,19 @@ describe("MuseAdapterV2", () => { yield* harness.takeEvent("turn.terminal"); assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); - const stopped = yield* harness.runtime + const stop = harness.runtime .interruptTurn({ providerThread: harness.providerThread, providerTurnId: turn.providerTurn.id, requestRuntimeRestart: true, }) .pipe(Effect.exit); - assert.strictEqual(stopped._tag, "Success"); + fake.queueResponse("task/stopAll", new Error("stop rejected")); + assert.strictEqual((yield* stop)._tag, "Failure"); + assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); + yield* fake.takeCall("task/stopAll"); + + assert.strictEqual((yield* stop)._tag, "Success"); assert.strictEqual((yield* fake.takeCall("task/stopAll")).method, "task/stopAll"); yield* harness.takeEvent( "provider_thread.updated", diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 063df083c8dab..8472b64519de4 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -2440,7 +2440,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (observedChildren.size === 0 && wake === undefined) return; } else { // A monitor outlives its turn, so Stop must reach Muse's own task registry. - yield* request("task/stopAll", {}).pipe(Effect.ignore); + // A failed stop keeps the listing, so the thread still shows work to stop. + yield* request("task/stopAll", {}); // A monitor that already woke the session left a turn this call must end too. if (wake) yield* request("turn/interrupt", { turnId: wake.nativeId }).pipe(Effect.ignore); From a3e9524182efcc689769dab0216221f7849dd4a6 Mon Sep 17 00:00:00 2001 From: YidaWeng <84164537+YidaWeng@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:37:23 +0800 Subject: [PATCH 7/8] fix(muse): make Stop's task state survive a racing refresh A task/list read started before Stop could put the stopped monitor back, and a failed stop still cleared the rows. Gate the refresh on a Stop generation and keep the rows when the stop fails. --- .../provider-muse/src/server/adapter.test.ts | 113 ++++++++++++++++++ packages/provider-muse/src/server/adapter.ts | 29 ++++- 2 files changed, 138 insertions(+), 4 deletions(-) diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index 99d57ecddc023..500300eb53fa8 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -1826,6 +1826,119 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect("drops a task list read that predates Stop", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + // A notification the adapter handles only after the held refresh returns. + const drained = yield* Deferred.make(); + const harness = yield* makeHarness( + fake, + INSTANCE_ID, + undefined, + undefined, + undefined, + runtimePolicy, + { onUsageLimits: () => Deferred.succeed(drained, undefined).pipe(Effect.asVoid) }, + ); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + revision: 1, + }, + }); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + + // The refresh that follows the terminal event is held open while Stop runs. + const gate = pendingPromise>(); + fake.queueResponse("task/list", gate.promise); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "completed" }); + yield* harness.takeEvent("turn.terminal"); + yield* fake.takeCall("task/list"); + + const stopped = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(stopped._tag, "Success"); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + + // The held read predates the stop, so its rows must not come back. + gate.resolve({ + tasks: [ + { taskId: "monitor-1", kind: "tool.monitor", status: "inProgress", tool: "monitor" }, + ], + }); + // The adapter handles this only after the held refresh has returned. + yield* fake.emitHostWide("usage/changed", SUBSCRIPTION_USAGE); + yield* Deferred.await(drained); + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + + it.effect("clears a stopped monitor when the turn ends before Stop's reply", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + const harness = yield* makeHarness(fake); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + revision: 1, + }, + }); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + + // Muse reports the turn as ended before it answers the interrupt. + const gate = pendingPromise>(); + fake.queueResponse("turn/interrupt", gate.promise); + const stopping = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit, Effect.forkScoped); + yield* fake.takeCall("turn/interrupt"); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "cancelled" }); + yield* harness.takeEvent("turn.terminal"); + gate.resolve({}); + + const stopped = yield* Fiber.join(stopping); + assert.strictEqual(stopped._tag, "Success"); + // The clear happens inside Stop, so it is settled as soon as the call returns. + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("ends a compaction whose item names the held wake as its run", () => Effect.gen(function* () { const fake = yield* makeFakeMuse(); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 8472b64519de4..0dcaa56258527 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -399,6 +399,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const seenTerminals = new Set(); const observedChildren = new Map(); const liveTasks = new Map(); + // Stop invalidates a `task/list` read already in flight; its rows predate the stop. + let taskListGeneration = 0; const childrenByItemId = new Map(); const agentTitles = new Map(); const finishedBackground: Array = []; @@ -807,12 +809,15 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( }); // The item stream says a tool was backgrounded; only `task/list` says whether it still runs. const refreshBackgroundTasks = Effect.fnUntraced(function* () { + const generation = taskListGeneration; const listed = yield* request("task/list", {}, false).pipe( Effect.flatMap((value) => decode(MuseTaskList, value)), // Never hold the event stream long on a host that will not answer. Effect.timeoutOption(5_000), Effect.option, ); + // Stop cleared the work while this read was in flight; the rows are already stale. + if (generation !== taskListGeneration) return; // A host that cannot list tasks keeps what the items told us. if (Option.isNone(listed) || Option.isNone(listed.value)) return; liveTasks.clear(); @@ -1049,7 +1054,11 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( } observedChildren.clear(); // The process owns its background work, so stopping or losing the turn ends it too. - liveTasks.clear(); + if (liveTasks.size > 0) { + // Discard a `task/list` read that started before these rows were dropped. + taskListGeneration++; + liveTasks.clear(); + } if (thread?.pendingBackgroundTasks?.length) yield* syncBackground(); for (const entry of pending.values()) yield* resolvePending(entry, "cancelled"); }); @@ -1642,7 +1651,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( result.error?.quota, ); // Background work outlives the turn that started it; re-read what Muse still runs. - yield* refreshBackgroundTasks(); + // Stop already cleared the listing, and a read now can predate `task/stopAll`. + if (status !== "interrupted") yield* refreshBackgroundTasks(); break; } case "approval/requested": @@ -2440,7 +2450,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( if (observedChildren.size === 0 && wake === undefined) return; } else { // A monitor outlives its turn, so Stop must reach Muse's own task registry. - // A failed stop keeps the listing, so the thread still shows work to stop. + // Without a live turn this is the only stop attempt, so a failed stop surfaces + // and keeps the listing for the caller to retry. yield* request("task/stopAll", {}); // A monitor that already woke the session left a turn this call must end too. if (wake) @@ -2481,7 +2492,17 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( yield* request("turn/interrupt", { turnId: joined }).pipe(Effect.ignore); yield* request("turn/interrupt", { turnId: turn.nativeId }); // Monitors and backgrounded tools are Muse-side work; the turn ending does not stop them. - yield* request("task/stopAll", {}).pipe(Effect.ignore); + // Keep the rows if the stop fails: those tasks can still be running. + const stopped = yield* request("task/stopAll", {}).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + if (stopped) { + // A `task/list` read started before this stop must not put the rows back. + taskListGeneration++; + liveTasks.clear(); + yield* syncBackground(); + } yield* Deferred.await(turn.done).pipe( Effect.timeout(options.requestTimeoutMs ?? 30_000), Effect.mapError((cause) => protocolError("Muse did not confirm interruption", cause)), From 5a7d4cc5832a924e4c67caf1dca094cbfe890892 Mon Sep 17 00:00:00 2001 From: YidaWeng <84164537+YidaWeng@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:44:04 +0800 Subject: [PATCH 8/8] fix(muse): keep a woken turn stoppable when its interrupt fails Ignoring the wake turn's interrupt left a Muse agent turn running with no way to reach it. Let the failure surface, keep the wake and the listing, and retry both. --- .../provider-muse/src/server/adapter.test.ts | 68 +++++++++++++++++++ packages/provider-muse/src/server/adapter.ts | 4 +- 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index 500300eb53fa8..2d34aabe03ef5 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -1891,6 +1891,74 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect("keeps a woken turn on a failed Stop so a retry can end it", () => + Effect.gen(function* () { + const fake = yield* makeFakeMuse(); + // `turn/started` sets the held wake before it offers the continuation. + const woken = yield* Deferred.make(); + const harness = yield* makeHarness( + fake, + INSTANCE_ID, + undefined, + undefined, + undefined, + runtimePolicy, + { continuationRequests: { offer: () => Deferred.succeed(woken, undefined) } }, + ); + const turn = yield* startConversation(harness, fake); + yield* fake.emit("item/completed", { + turnId: turn.nativeId, + item: { + itemId: "monitor-1", + kind: "toolCall", + status: "completed", + turnId: turn.nativeId, + tool: "monitor", + background: true, + revision: 1, + }, + }); + yield* harness.takeEvent( + "provider_thread.updated", + (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, + ); + fake.queueResponse("task/list", { + tasks: [ + { taskId: "monitor-1", kind: "tool.monitor", status: "inProgress", tool: "monitor" }, + ], + }); + yield* fake.emit("turn/completed", { turnId: turn.nativeId, terminal: "completed" }); + yield* harness.takeEvent("turn.terminal"); + + // The monitor's report already woke a new Muse turn. + yield* fake.emit("turn/started", { turnId: "wake-1" }); + yield* Deferred.await(woken); + + fake.queueResponse("turn/interrupt", new Error("interrupt rejected")); + const failed = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(failed._tag, "Failure"); + assert.strictEqual((yield* fake.takeCall("task/stopAll")).method, "task/stopAll"); + assert.isTrue(yield* harness.runtime.hasPendingBackgroundWork!); + + const retried = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: turn.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit); + assert.strictEqual(retried._tag, "Success"); + assert.strictEqual((yield* fake.takeCall("turn/interrupt")).params.turnId, "wake-1"); + assert.isFalse(yield* harness.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("clears a stopped monitor when the turn ends before Stop's reply", () => Effect.gen(function* () { const fake = yield* makeFakeMuse(); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0dcaa56258527..722bd5a0c66ff 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -2454,8 +2454,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( // and keeps the listing for the caller to retry. yield* request("task/stopAll", {}); // A monitor that already woke the session left a turn this call must end too. - if (wake) - yield* request("turn/interrupt", { turnId: wake.nativeId }).pipe(Effect.ignore); + // Keep the wake and the listing if that fails, so a retry can finish the job. + if (wake) yield* request("turn/interrupt", { turnId: wake.nativeId }); yield* settleObservedChildren("interrupted"); wake = undefined; return;