Skip to content

Commit bfbe019

Browse files
committed
fix(delegation): report rehydration installation result to history navigation callers
restartTaskIfCurrent and showTaskWithId now see whether the in-place replacement was installed; showTaskWithId no longer posts chatButtonClicked or records success when a newer task took ownership. Adds cross-provider and reservation-ordering coverage for the re-delegation commit.
1 parent 43be7e1 commit bfbe019

3 files changed

Lines changed: 182 additions & 30 deletions

File tree

‎src/__tests__/ClineProvider.delegation.spec.ts‎

Lines changed: 105 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -910,7 +910,83 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
910910
expect(taskRegistry.push).toHaveBeenCalledOnce()
911911
})
912912

913-
it("rejects re-delegation when the interrupted awaited child becomes live before the commit", async () => {
913+
it.each(["this provider", "another provider"] as const)(
914+
"rejects re-delegation when the interrupted awaited child becomes live in %s before the commit",
915+
async (owner) => {
916+
const oldChildId = "old-child"
917+
const parent: HistoryItem = {
918+
...parentHistoryItem,
919+
status: "delegated",
920+
awaitingChildId: oldChildId,
921+
delegatedToId: oldChildId,
922+
childIds: [oldChildId],
923+
}
924+
const records = new Map<string, HistoryItem>([
925+
["parent-1", parent],
926+
[oldChildId, { ...parentHistoryItem, id: oldChildId, status: "interrupted", parentTaskId: "parent-1" }],
927+
])
928+
let oldChildIsLive = false
929+
const isLiveIn = (target: typeof owner) => (id: string) =>
930+
owner === target && id === oldChildId && oldChildIsLive
931+
const taskHistoryStore = makeStoreStub({
932+
get: vi.fn((id: string) => records.get(id)),
933+
atomicReadAndUpdate: vi.fn(async (taskId: string, updater: (item: HistoryItem) => HistoryItem) => {
934+
records.set(taskId, updater(records.get(taskId)!))
935+
return []
936+
}),
937+
})
938+
const parentTask = makeParentTask()
939+
const provider = {
940+
_disposed: false,
941+
taskScheduler: new TaskScheduler(),
942+
taskRegistry: { hasRunning: vi.fn(isLiveIn("this provider")) },
943+
emit: vi.fn(),
944+
getCurrentTask: vi.fn(() => parentTask),
945+
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
946+
// The old child is resumed after the pre-check but before the parent commit.
947+
createTask: vi.fn(async () => {
948+
oldChildIsLive = true
949+
return { taskId: "child-2", run: vi.fn().mockResolvedValue(undefined) }
950+
}),
951+
deleteTaskWithId: vi.fn().mockResolvedValue(undefined),
952+
getTaskWithId: vi.fn(async () => ({ historyItem: records.get("parent-1") })),
953+
createTaskWithHistoryItem: vi.fn().mockResolvedValue(undefined),
954+
log: vi.fn(),
955+
isViewLaunched: false,
956+
recentTasksCache: undefined,
957+
taskHistoryStore,
958+
} as unknown as ClineProvider
959+
Object.assign(provider, {
960+
isTaskRunningInAnyProvider: ClineProvider.prototype["isTaskRunningInAnyProvider"],
961+
})
962+
const otherProvider = {
963+
taskRegistry: { hasRunning: vi.fn(isLiveIn("another provider")) },
964+
} as unknown as ClineProvider
965+
const activeInstances = Reflect.get(ClineProvider, "activeInstances")
966+
if (!(activeInstances instanceof Set)) throw new Error("ClineProvider active instance registry unavailable")
967+
activeInstances.add(otherProvider)
968+
969+
try {
970+
await expect(
971+
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
972+
parentTaskId: "parent-1",
973+
message: "Continue",
974+
initialTodos: [],
975+
mode: "code",
976+
}),
977+
).rejects.toThrow(`awaited child ${oldChildId} became live before delegation commit`)
978+
} finally {
979+
activeInstances.delete(otherProvider)
980+
}
981+
expect(records.get("parent-1")).toMatchObject({
982+
status: "delegated",
983+
awaitingChildId: oldChildId,
984+
delegatedToId: oldChildId,
985+
})
986+
},
987+
)
988+
989+
it("delays awaited child registration until the re-delegation commit finishes", async () => {
914990
const oldChildId = "old-child"
915991
const parent: HistoryItem = {
916992
...parentHistoryItem,
@@ -923,52 +999,61 @@ describe("ClineProvider.delegateParentAndOpenChild()", () => {
923999
["parent-1", parent],
9241000
[oldChildId, { ...parentHistoryItem, id: oldChildId, status: "interrupted", parentTaskId: "parent-1" }],
9251001
])
926-
let oldChildIsLive = false
1002+
let releaseCommit!: () => void
1003+
const commitBlocked = new Promise<void>((resolve) => {
1004+
releaseCommit = resolve
1005+
})
9271006
const taskHistoryStore = makeStoreStub({
9281007
get: vi.fn((id: string) => records.get(id)),
9291008
atomicReadAndUpdate: vi.fn(async (taskId: string, updater: (item: HistoryItem) => HistoryItem) => {
9301009
records.set(taskId, updater(records.get(taskId)!))
1010+
await commitBlocked
9311011
return []
9321012
}),
9331013
})
9341014
const parentTask = makeParentTask()
1015+
const taskRegistry = { hasRunning: vi.fn().mockReturnValue(false), push: vi.fn() }
9351016
const provider = {
9361017
_disposed: false,
9371018
taskScheduler: new TaskScheduler(),
938-
taskRegistry: { hasRunning: vi.fn((id: string) => id === oldChildId && oldChildIsLive) },
1019+
taskRegistry,
9391020
emit: vi.fn(),
9401021
getCurrentTask: vi.fn(() => parentTask),
9411022
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
942-
// The old child is resumed elsewhere after the pre-check but before the parent commit.
943-
createTask: vi.fn(async () => {
944-
oldChildIsLive = true
945-
return { taskId: "child-2", run: vi.fn().mockResolvedValue(undefined) }
946-
}),
1023+
createTask: vi.fn(async () => ({ taskId: "child-2", run: vi.fn().mockResolvedValue(undefined) })),
9471024
deleteTaskWithId: vi.fn().mockResolvedValue(undefined),
9481025
getTaskWithId: vi.fn(async () => ({ historyItem: records.get("parent-1") })),
9491026
createTaskWithHistoryItem: vi.fn().mockResolvedValue(undefined),
9501027
log: vi.fn(),
9511028
isViewLaunched: false,
9521029
recentTasksCache: undefined,
9531030
taskHistoryStore,
1031+
throwIfTaskRegistrationCancelled: ClineProvider.prototype["throwIfTaskRegistrationCancelled"],
1032+
performPreparationTasks: vi.fn(),
1033+
getState: vi.fn().mockResolvedValue({ mode: "code" }),
9541034
} as unknown as ClineProvider
9551035
Object.assign(provider, {
9561036
isTaskRunningInAnyProvider: ClineProvider.prototype["isTaskRunningInAnyProvider"],
9571037
})
9581038

959-
await expect(
960-
ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
961-
parentTaskId: "parent-1",
962-
message: "Continue",
963-
initialTodos: [],
964-
mode: "code",
965-
}),
966-
).rejects.toThrow(`awaited child ${oldChildId} became live before delegation commit`)
967-
expect(records.get("parent-1")).toMatchObject({
968-
status: "delegated",
969-
awaitingChildId: oldChildId,
970-
delegatedToId: oldChildId,
1039+
const delegation = ClineProvider.prototype.delegateParentAndOpenChild.call(provider, {
1040+
parentTaskId: "parent-1",
1041+
message: "Continue",
1042+
initialTodos: [],
1043+
mode: "code",
9711044
})
1045+
await vi.waitFor(() => expect(taskHistoryStore.atomicReadAndUpdate).toHaveBeenCalled())
1046+
const registration = ClineProvider.prototype.addClineToStack.call(provider, {
1047+
taskId: oldChildId,
1048+
emit: vi.fn(),
1049+
} as never)
1050+
await new Promise((resolve) => setTimeout(resolve, 0))
1051+
expect(taskRegistry.push).not.toHaveBeenCalled()
1052+
1053+
releaseCommit()
1054+
await Promise.all([delegation, registration])
1055+
expect(taskRegistry.push).toHaveBeenCalledOnce()
1056+
expect(records.get("parent-1")).toMatchObject({ status: "delegated", awaitingChildId: "child-2" })
9721057
})
9731058

9741059
it("does not recover when a descendant is live in another provider", async () => {

‎src/core/webview/ClineProvider.ts‎

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,10 @@ type GetStateOptions = {
233233
includeTaskHistory?: boolean
234234
}
235235

236+
// `installed` is false when a newer task took ownership during restoration; the
237+
// returned task was then aborted and never registered.
238+
type HistoryTaskInstallation = { task: Task; installed: boolean }
239+
236240
function removeTaskEventListeners(listeners: WeakMap<Task, Array<() => void>>, task: Task): void {
237241
const cleanupFunctions = listeners.get(task)
238242
if (cleanupFunctions) {
@@ -1445,19 +1449,27 @@ export class ClineProvider
14451449
await this.handleZooCodeCallback(token)
14461450
}
14471451

1448-
public createTaskWithHistoryItem(
1452+
public async createTaskWithHistoryItem(
14491453
historyItem: HistoryItem & { rootTask?: Task; parentTask?: Task },
14501454
options?: { startTask?: boolean },
14511455
): Promise<Task> {
1456+
const { task } = await ClineProvider.prototype.installTaskWithHistoryItem.call(this, historyItem, options)
1457+
return task
1458+
}
1459+
1460+
private installTaskWithHistoryItem(
1461+
historyItem: HistoryItem & { rootTask?: Task; parentTask?: Task },
1462+
options?: { startTask?: boolean },
1463+
): Promise<HistoryTaskInstallation> {
14521464
// History navigation can arrive concurrently (for example, two rapid
14531465
// showTaskWithId messages). Serialize the full eviction/installation
14541466
// transition so both callers cannot observe the same previous registry
14551467
// state and schedule distinct Task instances for one history item.
14561468
// Fail forward so one rejected restoration does not poison the queue.
14571469
return ClineProvider.prototype.enqueueHistoryTaskTransition.call<
14581470
ClineProvider,
1459-
[() => Promise<Task>],
1460-
Promise<Task>
1471+
[() => Promise<HistoryTaskInstallation>],
1472+
Promise<HistoryTaskInstallation>
14611473
>(this, () => ClineProvider.prototype.createTaskWithHistoryItemUnlocked.call(this, historyItem, options))
14621474
}
14631475

@@ -1478,8 +1490,11 @@ export class ClineProvider
14781490
if (this.getCurrentTask() !== task) {
14791491
return false
14801492
}
1481-
await ClineProvider.prototype.createTaskWithHistoryItemUnlocked.call(this, historyItem)
1482-
return true
1493+
const { installed } = await ClineProvider.prototype.createTaskWithHistoryItemUnlocked.call(
1494+
this,
1495+
historyItem,
1496+
)
1497+
return installed
14831498
})
14841499
}
14851500

@@ -1496,7 +1511,7 @@ export class ClineProvider
14961511
private async createTaskWithHistoryItemUnlocked(
14971512
historyItem: HistoryItem & { rootTask?: Task; parentTask?: Task },
14981513
options?: { startTask?: boolean },
1499-
): Promise<Task> {
1514+
): Promise<HistoryTaskInstallation> {
15001515
const isCliRuntime = process.env.ROO_CLI_RUNTIME === "1"
15011516
// CLI injects runtime provider settings from command flags/env at startup.
15021517
// Restoring provider profiles from task history can overwrite those
@@ -1646,7 +1661,7 @@ export class ClineProvider
16461661
if (oldTask !== currentTask) {
16471662
removeTaskEventListeners(this.taskEventListeners, task)
16481663
await task.abortTask(true).catch(() => {})
1649-
return task
1664+
return { task, installed: false }
16501665
}
16511666

16521667
if (oldTask) {
@@ -1671,7 +1686,7 @@ export class ClineProvider
16711686
if (!installed) {
16721687
removeTaskEventListeners(this.taskEventListeners, task)
16731688
await task.abortTask(true).catch(() => {})
1674-
return task
1689+
return { task, installed: false }
16751690
}
16761691
}
16771692

@@ -1746,7 +1761,7 @@ export class ClineProvider
17461761
}, 100) // Small delay to ensure task is fully ready
17471762
}
17481763

1749-
return task
1764+
return { task, installed: true }
17501765
}
17511766

17521767
public async postMessageToWebview(message: ExtensionMessage) {
@@ -2822,7 +2837,18 @@ export class ClineProvider
28222837
if (id !== this.getCurrentTask()?.taskId) {
28232838
// Non-current task.
28242839
const { historyItem } = await this.getTaskWithId(id)
2825-
await this.createTaskWithHistoryItem(historyItem) // Clears existing task.
2840+
const { installed } = await this.installTaskWithHistoryItem(historyItem) // Clears existing task.
2841+
if (!installed) {
2842+
// A newer task took ownership while this one was being restored.
2843+
this.diagnosticsRecorder.record({
2844+
boundary: "task-navigation",
2845+
phase: "failure",
2846+
type: "show-task",
2847+
taskId: id,
2848+
elapsedMs: Date.now() - startedAt,
2849+
})
2850+
return
2851+
}
28262852
}
28272853

28282854
await this.postMessageToWebview({ type: "action", action: "chatButtonClicked" })

‎src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,47 @@ describe("ClineProvider flicker-free cancel", () => {
498498
expect(provider["taskRegistry"].current).toBe(mockTask2)
499499
})
500500

501+
describe("when a newer task takes ownership during in-place rehydration", () => {
502+
const newerTask = { taskId: "task-newer", instanceId: "instance-newer", emit: vi.fn() }
503+
504+
beforeEach(() => {
505+
mockTask2.abortTask = vi.fn().mockResolvedValue(undefined)
506+
// A newer top-level task replaces the old task while it is being aborted.
507+
mockTask1.abortTask = vi.fn().mockImplementation(async () => {
508+
provider["taskRegistry"].replace(mockTask1.taskId, newerTask as unknown as Task)
509+
})
510+
})
511+
512+
it("restartTaskIfCurrent reports that the replacement was not installed", async () => {
513+
seedRegistry(provider, mockTask1)
514+
515+
await expect(provider.restartTaskIfCurrent(mockTask1 as unknown as Task)).resolves.toBe(false)
516+
517+
expect(provider["taskRegistry"].current).toBe(newerTask)
518+
expect(mockTask2.abortTask).toHaveBeenCalledWith(true)
519+
})
520+
521+
it("showTaskWithId does not report a successful navigation", async () => {
522+
const previousTask = { taskId: "task-0", instanceId: "instance-0", emit: vi.fn() }
523+
seedRegistry(provider, previousTask)
524+
const getTaskWithId = provider.getTaskWithId
525+
// An earlier queued navigation made task-1 current before this one was restored.
526+
provider.getTaskWithId = vi.fn().mockImplementation(async (id: string) => {
527+
provider["taskRegistry"].replace(previousTask.taskId, mockTask1 as unknown as Task)
528+
return getTaskWithId(id)
529+
})
530+
const postMessageToWebview = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined)
531+
const record = vi.spyOn(provider["diagnosticsRecorder"], "record")
532+
533+
await provider.showTaskWithId("task-1")
534+
535+
expect(provider["taskRegistry"].current).toBe(newerTask)
536+
expect(postMessageToWebview).not.toHaveBeenCalledWith({ type: "action", action: "chatButtonClicked" })
537+
expect(record).not.toHaveBeenCalledWith(expect.objectContaining({ type: "show-task", phase: "success" }))
538+
expect(record).toHaveBeenCalledWith(expect.objectContaining({ type: "show-task", phase: "failure" }))
539+
})
540+
})
541+
501542
it("should remove task from stack when creating different task", async () => {
502543
// Setup: Add a task to the registry first
503544
seedRegistry(provider, mockTask1)

0 commit comments

Comments
 (0)