diff --git a/src/features/background-agent/manager.ts b/src/features/background-agent/manager.ts index 1b0d4acdf..e1a07e64d 100644 --- a/src/features/background-agent/manager.ts +++ b/src/features/background-agent/manager.ts @@ -88,9 +88,24 @@ import { resolveSubagentSpawnContext, type SubagentSpawnContext, } from "./subagent-spawn-limits" +import { settleAfterSessionIdle } from "../../hooks/shared/session-idle-settle" type OpencodeClient = PluginInput["client"] +type ParentWakePromptContext = { + agent?: string + model?: { providerID: string; modelID: string } + variant?: string + tools?: Record +} + +type SessionStatusInfo = { type?: string } + +const BACKGROUND_PARENT_WAKE_PROMPT = ` +[BACKGROUND TASK NOTIFICATION READY] +A background task notification was already added to this session. Continue from that notification. +` + interface MessagePartInfo { id?: string sessionID?: string @@ -210,6 +225,7 @@ export class BackgroundManager { private completedTaskSummaries: Map = new Map() private idleDeferralTimers: Map> = new Map() private notificationQueueByParent: Map> = new Map() + private pendingParentWakes: Map = new Map() private observedOutputSessions: Set = new Set() private observedIncompleteTodosBySession: Map = new Map() private rootDescendantCounts: Map @@ -1360,6 +1376,12 @@ The fallback retry session is now created and can be inspected directly. if (event.type === "session.idle") { if (!props || typeof props !== "object") return + const sessionID = typeof props.sessionID === "string" ? props.sessionID : undefined + if (sessionID) { + void this.enqueueNotificationForParent(sessionID, () => this.flushPendingParentWake(sessionID)).catch((error) => { + log("[background-agent] Failed to flush pending parent wake:", { sessionID, error }) + }) + } handleSessionIdleBackgroundEvent({ properties: props as Record, findBySession: (id) => { @@ -2152,24 +2174,32 @@ The task was re-queued on a fallback model after a retryable failure. const shouldReply = allComplete || isTaskFailure const variant = promptContext?.model?.variant + const parentPromptContext: ParentWakePromptContext = { + ...(agent !== undefined ? { agent } : {}), + ...(model !== undefined ? { model } : {}), + ...(variant !== undefined ? { variant } : {}), + ...(resolvedTools ? { tools: resolvedTools } : {}), + } + const shouldDeferReply = shouldReply && await this.isSessionActive(task.parentSessionId) try { await this.client.session.promptAsync({ path: { id: task.parentSessionId }, body: { - noReply: !shouldReply, - ...(agent !== undefined ? { agent } : {}), - ...(model !== undefined ? { model } : {}), - ...(variant !== undefined ? { variant } : {}), - ...(resolvedTools ? { tools: resolvedTools } : {}), + noReply: shouldDeferReply || !shouldReply, + ...parentPromptContext, parts: [createInternalAgentTextPart(notification)], }, }) + if (shouldDeferReply) { + this.pendingParentWakes.set(task.parentSessionId, parentPromptContext) + } log("[background-agent] Sent notification to parent session:", { taskId: task.id, allComplete, isTaskFailure, - noReply: !shouldReply, + noReply: shouldDeferReply || !shouldReply, + deferredReply: shouldDeferReply, }) } catch (error) { if (isAbortedSessionError(error)) { @@ -2201,6 +2231,60 @@ The task was re-queued on a fallback model after a retryable failure. return false } + private async isSessionActive(sessionID: string): Promise { + const sessionStatusMethod = this.client?.session?.status + if (typeof sessionStatusMethod !== "function") { + return false + } + + try { + const statusResult = await this.client.session.status() + const statuses = normalizeSDKResponse( + statusResult, + {} as Record, + ) + const status = statuses[sessionID] + return typeof status?.type === "string" && isActiveSessionStatus(status.type) + } catch (error) { + log("[background-agent] Unable to check parent session status before wake:", { + sessionID, + error, + }) + return false + } + } + + private async flushPendingParentWake(sessionID: string): Promise { + const wakeContext = this.pendingParentWakes.get(sessionID) + if (!wakeContext) return + + if (await this.isSessionActive(sessionID)) { + return + } + + this.pendingParentWakes.delete(sessionID) + await settleAfterSessionIdle() + + if (await this.isSessionActive(sessionID)) { + this.pendingParentWakes.set(sessionID, wakeContext) + return + } + + try { + await this.client.session.promptAsync({ + path: { id: sessionID }, + body: { + noReply: false, + ...wakeContext, + parts: [createInternalAgentTextPart(BACKGROUND_PARENT_WAKE_PROMPT)], + }, + }) + log("[background-agent] Sent deferred parent wake:", { sessionID }) + } catch (error) { + log("[background-agent] Failed to send deferred parent wake:", { sessionID, error }) + } + } + private pruneStaleTasksAndNotifications(): void { pruneStaleTasksAndNotifications({ tasks: this.tasks, @@ -2525,6 +2609,7 @@ The task was re-queued on a fallback model after a retryable failure. this.pendingNotifications.clear() this.pendingByParent.clear() this.notificationQueueByParent.clear() + this.pendingParentWakes.clear() this.rootDescendantCounts.clear() this.queuesByKey.clear() this.processingKeys.clear() diff --git a/src/features/background-agent/task-completion-cleanup.test.ts b/src/features/background-agent/task-completion-cleanup.test.ts index b15a84af4..f8cdf51a5 100644 --- a/src/features/background-agent/task-completion-cleanup.test.ts +++ b/src/features/background-agent/task-completion-cleanup.test.ts @@ -50,11 +50,19 @@ function createTask(overrides: Partial & { id: string; parentSes function createManager(enableParentSessionNotifications: boolean): { manager: BackgroundManager promptAsyncCalls: PromptAsyncCall[] +} +function createManager( + enableParentSessionNotifications: boolean, + sessionStatuses?: Record, +): { + manager: BackgroundManager + promptAsyncCalls: PromptAsyncCall[] } { const promptAsyncCalls: PromptAsyncCall[] = [] const client = { session: { messages: async () => [], + status: async () => ({ data: sessionStatuses ?? {} }), prompt: async () => ({}), promptAsync: async (call: PromptAsyncCall) => { promptAsyncCalls.push(call) @@ -143,6 +151,10 @@ async function notifyParentSessionForTest(manager: BackgroundManager, task: Back return notifyParentSession.call(manager, task) } +function waitForDeferredWake(): Promise { + return new Promise((resolve) => setTimeout(resolve, 180)) +} + function getRequiredTimer(manager: BackgroundManager, taskID: string): ReturnType { const timer = getCompletionTimers(manager).get(taskID) expect(timer).toBeDefined() @@ -232,6 +244,52 @@ describe("BackgroundManager.notifyParentSession cleanup scheduling", () => { expect(allCompletePayload).toContain(taskA.description) expect(allCompletePayload).toContain(taskB.description) }) + + test("#when parent session is busy #then all-complete notification does not start an overlapping parent reply", async () => { + // given + const sessionStatuses: Record = { + "parent-1": { type: "busy" }, + } + const { manager, promptAsyncCalls } = createManager(true, sessionStatuses) + managerUnderTest = manager + const task = createTask({ id: "task-a", parentSessionId: "parent-1", description: "task A", status: "completed", completedAt: new Date("2026-03-11T00:01:00.000Z") }) + getTasks(manager).set(task.id, task) + getPendingByParent(manager).set(task.parentSessionId, new Set([task.id])) + + // when + await notifyParentSessionForTest(manager, task) + + // then + expect(promptAsyncCalls).toHaveLength(1) + expect(promptAsyncCalls[0]?.body.noReply).toBe(true) + expect(JSON.stringify(promptAsyncCalls[0]?.body.parts)).toContain("ALL BACKGROUND TASKS COMPLETE") + }) + + test("#when deferred parent session becomes idle #then wake prompt is sent once without duplicating the notification", async () => { + // given + const sessionStatuses: Record = { + "parent-1": { type: "busy" }, + } + const { manager, promptAsyncCalls } = createManager(true, sessionStatuses) + managerUnderTest = manager + const task = createTask({ id: "task-a", parentSessionId: "parent-1", description: "task A", status: "completed", completedAt: new Date("2026-03-11T00:01:00.000Z") }) + getTasks(manager).set(task.id, task) + getPendingByParent(manager).set(task.parentSessionId, new Set([task.id])) + await notifyParentSessionForTest(manager, task) + + // when + sessionStatuses["parent-1"] = { type: "idle" } + manager.handleEvent({ type: "session.idle", properties: { sessionID: "parent-1" } }) + await waitForDeferredWake() + + // then + expect(promptAsyncCalls).toHaveLength(2) + expect(promptAsyncCalls[0]?.body.noReply).toBe(true) + expect(promptAsyncCalls[1]?.body.noReply).toBe(false) + const wakePayload = JSON.stringify(promptAsyncCalls[1]?.body.parts) + expect(wakePayload).toContain("BACKGROUND TASK NOTIFICATION READY") + expect(wakePayload).not.toContain("ALL BACKGROUND TASKS COMPLETE") + }) }) describe("#given a completed task with cleanup timer scheduled", () => {