merge(dev): resolve latest sync-task conflict for delegated fallback PR

Sync the PR branch with the latest dev branch and resolve the remaining conflict in sync-task.test.ts while preserving both the new upstream poll-recovery coverage and this branch's delegated bootstrap cleanup and isolation coverage. Re-verified the affected delegated fallback suites and typecheck after the merge resolution.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
tw-yshuang
2026-05-12 00:37:01 +08:00
113 changed files with 6674 additions and 492 deletions
@@ -107,7 +107,8 @@ describe("BackgroundManager.cancelTask cleanup", () => {
expect(cancelled).toBe(true)
expect(getPendingByParent(manager).get(task.parentSessionId)).toBeUndefined()
runScheduledCleanup(manager, task.id)
expect(manager.getTask(task.id)).toBeUndefined()
expect(getTaskMap(manager).has(task.id)).toBe(false)
expect(manager.getTask(task.id)?.sessionId).toBe(task.sessionId)
})
test("#given a running task #when cancelTask called with skipNotification=false #then task is also eventually removed", async () => {
@@ -131,7 +132,8 @@ describe("BackgroundManager.cancelTask cleanup", () => {
// then
expect(cancelled).toBe(true)
runScheduledCleanup(manager, task.id)
expect(manager.getTask(task.id)).toBeUndefined()
expect(getTaskMap(manager).has(task.id)).toBe(false)
expect(manager.getTask(task.id)?.sessionId).toBe(task.sessionId)
})
test("#given a running task #when cancelTask called with skipNotification=true #then concurrency slot is freed and pending tasks can start", async () => {
@@ -5248,6 +5248,67 @@ describe("BackgroundManager.handleEvent - session.error", () => {
manager.shutdown()
})
test("completes task on session.status idle after todo-continuation finishes", async () => {
//#given
const sessionID = "ses-status-idle-after-todo-continuation"
const client = {
session: {
prompt: async () => ({}),
promptAsync: async () => ({}),
abort: async () => ({}),
messages: async () => ({
data: [
{
info: { role: "assistant" },
parts: [{ type: "text", text: "final verified result" }],
},
],
}),
todo: async () => ({ data: [] }),
},
}
const manager = new BackgroundManager({ pluginContext: createPluginInput(client) })
stubNotifyParentSession(manager)
mockVerifySessionExists(manager, true)
const task = createMockTask({
id: "task-status-idle-after-todo-continuation",
sessionId: sessionID,
parentSessionId: "parent-session",
parentMessageId: "msg-status-idle",
description: "task that finished after todo-continuation",
agent: "explore",
status: "running",
startedAt: new Date(Date.now() - (MIN_IDLE_TIME_MS + 10)),
})
getTaskMap(manager).set(task.id, task)
manager.handleEvent({
type: "todo.updated",
properties: {
sessionID,
todos: [{ id: "todo-1", content: "compile result", status: "completed", priority: "high" }],
},
})
//#when
manager.handleEvent({
type: "session.status",
properties: {
sessionID,
status: { type: "idle" },
},
})
await flushBackgroundNotifications()
//#then
expect(task.status).toBe("completed")
expect(task.completedAt).toBeDefined()
manager.shutdown()
})
test("retry path releases current concurrency slot and prefers current provider in fallback entry", async () => {
//#given
const manager = createBackgroundManager()
@@ -6216,6 +6277,68 @@ describe("BackgroundManager regression fixes - resume and aborted notification",
manager.shutdown()
})
test("should keep completed task retrievable after scheduled removal", () => {
//#given
const manager = createBackgroundManager()
const task: BackgroundTask = {
id: "task-archive-regression",
sessionId: "session-archive-regression",
parentSessionId: "parent-session",
parentMessageId: "msg-1",
description: "archive regression",
prompt: "test",
agent: "explore",
status: "completed",
startedAt: new Date(),
completedAt: new Date(),
}
getTaskMap(manager).set(task.id, task)
//#when
;(cast<{ removeTask: (task: BackgroundTask) => void }>(manager)).removeTask(task)
//#then
expect(getTaskMap(manager).has(task.id)).toBe(false)
const archivedTask = manager.getTask(task.id)
expect(archivedTask?.sessionId).toBe(task.sessionId)
expect(archivedTask?.prompt).toBe("[redacted]")
expect(archivedTask?.startedAt).toEqual(task.startedAt)
manager.shutdown()
})
test("should cap completed task archive size at 100 entries", () => {
//#given
const manager = createBackgroundManager()
//#when
for (let index = 0; index < 120; index += 1) {
const task: BackgroundTask = {
id: `task-archive-${index}`,
sessionId: `session-archive-${index}`,
parentSessionId: "parent-session",
parentMessageId: "msg-1",
description: "archive cap regression",
prompt: `sensitive-${index}`,
agent: "explore",
status: "completed",
startedAt: new Date(),
completedAt: new Date(),
}
;(cast<{ removeTask: (task: BackgroundTask) => void }>(manager)).removeTask(task)
}
//#then
const archive = cast<Map<string, unknown>>(Reflect.get(manager, "completedTaskArchive"))
expect(archive.size).toBe(100)
expect(archive.has("task-archive-0")).toBe(false)
expect(archive.has("task-archive-19")).toBe(false)
expect(archive.has("task-archive-20")).toBe(true)
expect(archive.has("task-archive-119")).toBe(true)
manager.shutdown()
})
})
describe("BackgroundManager - tool permission spread order", () => {
+148 -35
View File
@@ -103,12 +103,14 @@ type ParentWakePromptContext = {
tools?: Record<string, boolean>
}
type PendingParentWake = {
promptContext: ParentWakePromptContext
notifications: string[]
}
type SessionStatusInfo = { type?: string }
const BACKGROUND_PARENT_WAKE_PROMPT = `<system-reminder>
[BACKGROUND TASK NOTIFICATION READY]
A background task notification was already added to this session. Continue from that notification.
</system-reminder>`
const PENDING_PARENT_WAKE_RETRY_MS = 1_000
interface MessagePartInfo {
id?: string
@@ -192,6 +194,7 @@ export interface SubagentSessionCreatedEvent {
export type OnSubagentSessionCreated = (event: SubagentSessionCreatedEvent) => Promise<void>
const MAX_TASK_REMOVAL_RESCHEDULES = 6
const MAX_COMPLETED_TASK_ARCHIVE_SIZE = 100
export interface BackgroundManagerConfig {
pluginContext: PluginInput
@@ -226,10 +229,12 @@ export class BackgroundManager {
private queuesByKey: Map<string, QueueItem[]> = new Map()
private processingKeys: Set<string> = new Set()
private completionTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()
private completedTaskArchive: Map<string, BackgroundTask> = new Map()
private completedTaskSummaries: Map<string, BackgroundTaskNotificationTask[]> = new Map()
private idleDeferralTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()
private notificationQueueByParent: Map<string, Promise<void>> = new Map()
private pendingParentWakes: Map<string, ParentWakePromptContext> = new Map()
private pendingParentWakes: Map<string, PendingParentWake> = new Map()
private pendingParentWakeTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()
private observedOutputSessions: Set<string> = new Set()
private observedIncompleteTodosBySession: Map<string, boolean> = new Map()
private rootDescendantCounts: Map<string, number>
@@ -357,6 +362,7 @@ export class BackgroundManager {
}
private addTask(task: BackgroundTask): void {
this.completedTaskArchive.delete(task.id)
this.tasks.set(task.id, task)
if (!task.parentSessionId) {
return
@@ -368,10 +374,47 @@ export class BackgroundManager {
}
private removeTask(task: BackgroundTask): void {
this.archiveCompletedTask(task)
this.tasks.delete(task.id)
this.removeTaskFromParentIndex(task.id, task.parentSessionId)
}
private archiveCompletedTask(task: BackgroundTask): void {
if (!task.sessionId) {
return
}
if (task.status === "running" || task.status === "pending") {
return
}
const archivedTask: BackgroundTask = {
id: task.id,
parentSessionId: task.parentSessionId,
parentMessageId: task.parentMessageId,
description: task.description,
prompt: "[redacted]",
agent: task.agent,
sessionId: task.sessionId,
status: task.status,
queuedAt: task.queuedAt,
startedAt: task.startedAt,
completedAt: task.completedAt,
model: task.model,
error: task.error,
category: task.category,
}
this.completedTaskArchive.set(task.id, archivedTask)
if (this.completedTaskArchive.size <= MAX_COMPLETED_TASK_ARCHIVE_SIZE) {
return
}
const oldestTaskID = this.completedTaskArchive.keys().next().value
if (typeof oldestTaskID === "string") {
this.completedTaskArchive.delete(oldestTaskID)
}
}
private updateTaskParent(task: BackgroundTask, parentSessionID: string): void {
if (task.parentSessionId === parentSessionID) {
return
@@ -849,7 +892,7 @@ The fallback retry session is now created and can be inspected directly.
}
getTask(id: string): BackgroundTask | undefined {
return this.tasks.get(id)
return this.tasks.get(id) ?? this.completedTaskArchive.get(id)
}
getTasksByParentSession(sessionID: string): BackgroundTask[] {
@@ -1507,7 +1550,14 @@ The fallback retry session is now created and can be inspected directly.
if (event.type === "session.status") {
const sessionID = props?.sessionID as string | undefined
const status = props?.status as { type?: string; message?: string } | undefined
if (!sessionID || status?.type !== "retry") return
if (!sessionID || !status?.type) return
if (status.type === "idle") {
this.handleEvent({ type: "session.idle", properties: { sessionID } })
return
}
if (status.type !== "retry") return
const resolved = this.resolveTaskAttemptBySession(sessionID)
if (!resolved?.isCurrent) return
@@ -2202,34 +2252,40 @@ The task was re-queued on a fallback model after a retryable failure.
}
const shouldDeferReply = shouldReply && await this.isSessionActive(task.parentSessionId)
try {
await this.client.session.promptAsync({
path: { id: task.parentSessionId },
body: {
noReply: shouldDeferReply || !shouldReply,
...parentPromptContext,
parts: [createInternalAgentTextPart(notification)],
},
})
if (shouldDeferReply) {
this.pendingParentWakes.set(task.parentSessionId, parentPromptContext)
}
log("[background-agent] Sent notification to parent session:", {
if (shouldDeferReply) {
this.queuePendingParentWake(task.parentSessionId, notification, parentPromptContext)
log("[background-agent] Deferred notification until parent session is idle:", {
taskId: task.id,
allComplete,
isTaskFailure,
noReply: shouldDeferReply || !shouldReply,
deferredReply: shouldDeferReply,
})
} catch (error) {
if (isAbortedSessionError(error)) {
log("[background-agent] Parent session aborted while sending notification; continuing cleanup:", {
taskId: task.id,
parentSessionID: task.parentSessionId,
} else {
try {
await this.client.session.promptAsync({
path: { id: task.parentSessionId },
body: {
noReply: !shouldReply,
...parentPromptContext,
parts: [createInternalAgentTextPart(notification)],
},
})
this.queuePendingNotification(task.parentSessionId, notification)
} else {
log("[background-agent] Failed to send notification:", error)
log("[background-agent] Sent notification to parent session:", {
taskId: task.id,
allComplete,
isTaskFailure,
noReply: !shouldReply,
deferredReply: false,
})
} catch (error) {
if (isAbortedSessionError(error)) {
log("[background-agent] Parent session aborted while sending notification; continuing cleanup:", {
taskId: task.id,
parentSessionID: task.parentSessionId,
})
this.queuePendingNotification(task.parentSessionId, notification)
} else {
log("[background-agent] Failed to send notification:", error)
}
}
}
} else {
@@ -2274,37 +2330,89 @@ The task was re-queued on a fallback model after a retryable failure.
}
}
private queuePendingParentWake(
sessionID: string,
notification: string,
promptContext: ParentWakePromptContext,
): void {
const pendingWake = this.pendingParentWakes.get(sessionID)
if (pendingWake) {
pendingWake.notifications.push(notification)
pendingWake.promptContext = promptContext
} else {
this.pendingParentWakes.set(sessionID, {
promptContext,
notifications: [notification],
})
}
this.schedulePendingParentWakeFlush(sessionID)
}
private async flushPendingParentWake(sessionID: string): Promise<void> {
const wakeContext = this.pendingParentWakes.get(sessionID)
if (!wakeContext) return
const pendingWake = this.pendingParentWakes.get(sessionID)
if (!pendingWake) {
this.clearPendingParentWakeTimer(sessionID)
return
}
if (await this.isSessionActive(sessionID)) {
this.schedulePendingParentWakeFlush(sessionID)
return
}
this.pendingParentWakes.delete(sessionID)
this.clearPendingParentWakeTimer(sessionID)
await settleAfterSessionIdle()
if (await this.isSessionActive(sessionID)) {
this.pendingParentWakes.set(sessionID, wakeContext)
this.pendingParentWakes.set(sessionID, pendingWake)
this.schedulePendingParentWakeFlush(sessionID)
return
}
const notificationContent = pendingWake.notifications.join("\n\n")
try {
await this.client.session.promptAsync({
path: { id: sessionID },
body: {
noReply: false,
...wakeContext,
parts: [createInternalAgentTextPart(BACKGROUND_PARENT_WAKE_PROMPT)],
...pendingWake.promptContext,
parts: [createInternalAgentTextPart(notificationContent)],
},
})
log("[background-agent] Sent deferred parent wake:", { sessionID })
} catch (error) {
this.queuePendingNotification(sessionID, notificationContent)
log("[background-agent] Failed to send deferred parent wake:", { sessionID, error })
}
}
private schedulePendingParentWakeFlush(sessionID: string): void {
if (this.pendingParentWakeTimers.has(sessionID)) {
return
}
const timer = setTimeout(() => {
this.pendingParentWakeTimers.delete(sessionID)
void this.enqueueNotificationForParent(sessionID, () => this.flushPendingParentWake(sessionID)).catch((error) => {
log("[background-agent] Failed to retry pending parent wake:", { sessionID, error })
})
}, PENDING_PARENT_WAKE_RETRY_MS)
this.pendingParentWakeTimers.set(sessionID, timer)
}
private clearPendingParentWakeTimer(sessionID: string): void {
const timer = this.pendingParentWakeTimers.get(sessionID)
if (!timer) {
return
}
clearTimeout(timer)
this.pendingParentWakeTimers.delete(sessionID)
}
private pruneStaleTasksAndNotifications(allStatuses?: SessionStatusMap): void {
pruneStaleTasksAndNotifications({
tasks: this.tasks,
@@ -2618,6 +2726,11 @@ The task was re-queued on a fallback model after a retryable failure.
}
this.idleDeferralTimers.clear()
for (const timer of this.pendingParentWakeTimers.values()) {
clearTimeout(timer)
}
this.pendingParentWakeTimers.clear()
for (const sessionID of trackedSessionIDs) {
subagentSessions.delete(sessionID)
this.cleanupDelegatedSessionContext(sessionID)
@@ -54,6 +54,7 @@ function createManager(enableParentSessionNotifications: boolean): {
function createManager(
enableParentSessionNotifications: boolean,
sessionStatuses?: Record<string, { type: string }>,
promptAsyncImpl?: (call: PromptAsyncCall) => Promise<unknown>,
): {
manager: BackgroundManager
promptAsyncCalls: PromptAsyncCall[]
@@ -66,6 +67,9 @@ function createManager(
prompt: async () => ({}),
promptAsync: async (call: PromptAsyncCall) => {
promptAsyncCalls.push(call)
if (promptAsyncImpl) {
return promptAsyncImpl(call)
}
return {}
},
abort: async () => ({}),
@@ -142,6 +146,10 @@ function getPendingByParent(manager: BackgroundManager): Map<string, Set<string>
return Reflect.get(manager, "pendingByParent") as Map<string, Set<string>>
}
function getPendingNotifications(manager: BackgroundManager): Map<string, string[]> {
return Reflect.get(manager, "pendingNotifications") as Map<string, string[]>
}
function getCompletionTimers(manager: BackgroundManager): Map<string, ReturnType<typeof setTimeout>> {
return Reflect.get(manager, "completionTimers") as Map<string, ReturnType<typeof setTimeout>>
}
@@ -155,6 +163,10 @@ function waitForDeferredWake(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 180))
}
function waitForDeferredWakeRetry(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 1_180))
}
function getRequiredTimer(manager: BackgroundManager, taskID: string): ReturnType<typeof setTimeout> {
const timer = getCompletionTimers(manager).get(taskID)
expect(timer).toBeDefined()
@@ -208,7 +220,7 @@ describe("BackgroundManager.notifyParentSession cleanup scheduling", () => {
})
})
describe("#given 2 tasks for same parent and both completed", () => {
describe("#given background tasks for same parent", () => {
test("#when the second completion notification is sent #then ALL BACKGROUND TASKS COMPLETE notification still works correctly", async () => {
// given
const { manager, promptAsyncCalls } = createManager(true)
@@ -260,12 +272,10 @@ describe("BackgroundManager.notifyParentSession cleanup scheduling", () => {
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")
expect(promptAsyncCalls).toHaveLength(0)
})
test("#when deferred parent session becomes idle #then wake prompt is sent once without duplicating the notification", async () => {
test("#when deferred parent session becomes idle #then completion notification wakes the parent without a pointer reminder", async () => {
// given
const sessionStatuses: Record<string, { type: string }> = {
"parent-1": { type: "busy" },
@@ -283,12 +293,63 @@ describe("BackgroundManager.notifyParentSession cleanup scheduling", () => {
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")
expect(promptAsyncCalls).toHaveLength(1)
expect(promptAsyncCalls[0]?.body.noReply).toBe(false)
const wakePayload = JSON.stringify(promptAsyncCalls[0]?.body.parts)
expect(wakePayload).toContain("ALL BACKGROUND TASKS COMPLETE")
expect(wakePayload).not.toContain("BACKGROUND TASK NOTIFICATION READY")
})
test("#when a single background task finishes during a stale busy parent status #then completion notification is retried after the parent becomes idle", async () => {
// given
const sessionStatuses: Record<string, { type: string }> = {
"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)
sessionStatuses["parent-1"] = { type: "idle" }
await waitForDeferredWakeRetry()
// then
expect(promptAsyncCalls).toHaveLength(1)
expect(promptAsyncCalls[0]?.body.noReply).toBe(false)
const wakePayload = JSON.stringify(promptAsyncCalls[0]?.body.parts)
expect(wakePayload).toContain("ALL BACKGROUND TASKS COMPLETE")
expect(wakePayload).not.toContain("BACKGROUND TASK NOTIFICATION READY")
})
test("#when deferred completion notification send fails #then notification is queued for the next user message", async () => {
// given
const sessionStatuses: Record<string, { type: string }> = {
"parent-1": { type: "busy" },
}
const promptError = new Error("promptAsync failed")
const { manager, promptAsyncCalls } = createManager(true, sessionStatuses, async () => {
throw promptError
})
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(1)
const queuedNotifications = getPendingNotifications(manager).get("parent-1") ?? []
expect(queuedNotifications).toHaveLength(1)
expect(queuedNotifications[0]).toContain("ALL BACKGROUND TASKS COMPLETE")
expect(queuedNotifications[0]).not.toContain("BACKGROUND TASK NOTIFICATION READY")
})
})