-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathprovider-delegation.spec.ts
More file actions
389 lines (343 loc) · 13.4 KB
/
Copy pathprovider-delegation.spec.ts
File metadata and controls
389 lines (343 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// npx vitest run __tests__/provider-delegation.spec.ts
import { describe, it, expect, vi } from "vitest"
import type { HistoryItem } from "@roo-code/types"
import { RooCodeEventName } from "@roo-code/types"
import { ClineProvider } from "../core/webview/ClineProvider"
import { TaskScheduler } from "../core/task/TaskScheduler"
const parentHistoryItem: HistoryItem = {
id: "parent-1",
task: "Parent",
tokensIn: 0,
tokensOut: 0,
totalCost: 0,
childIds: [],
} as unknown as HistoryItem
/** Minimal taskHistoryStore stub whose atomicReadAndUpdate calls the updater with the parent item. */
function makeStoreStub(
overrides: Partial<{ atomicReadAndUpdate: ReturnType<typeof vi.fn>; get: ReturnType<typeof vi.fn> }> = {},
) {
return {
atomicReadAndUpdate: vi.fn(async (_taskId: string, updater: (h: HistoryItem) => HistoryItem) => {
updater(parentHistoryItem)
return []
}),
get: vi.fn().mockReturnValue(undefined),
...overrides,
}
}
/**
* Parent task double with the methods delegateParentAndOpenChild reads from
* `parent`. Without flushPendingToolResultsToHistory the method hits its
* non-fatal flush-error branch and never reaches the happy delegation path.
*/
const makeParentTask = () =>
({
taskId: "parent-1",
emit: vi.fn(),
flushPendingToolResultsToHistory: vi.fn().mockResolvedValue(true),
retrySaveApiConversationHistory: vi.fn(),
}) as any
describe("ClineProvider.delegateParentAndOpenChild()", () => {
it("persists parent delegation metadata via atomicReadAndUpdate and emits TaskDelegated", async () => {
const providerEmit = vi.fn()
const parentTask = makeParentTask()
const childRun = vi.fn().mockResolvedValue(undefined)
const removeClineFromStack = vi.fn().mockResolvedValue(undefined)
const createTask = vi.fn().mockResolvedValue({ taskId: "child-1", start: vi.fn(), run: childRun })
const handleModeSwitch = vi.fn().mockResolvedValue(undefined)
const taskHistoryStore = makeStoreStub()
const provider = {
taskScheduler: new TaskScheduler(),
emit: providerEmit,
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack,
createTask,
handleModeSwitch,
log: vi.fn(),
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
const child = await (ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Do something",
initialTodos: [],
mode: "code",
})
await Promise.resolve() // drain scheduler microtask so child.run() is invoked
expect(child.taskId).toBe("child-1")
// Invariant: parent closed before child creation
expect(removeClineFromStack).toHaveBeenCalledTimes(1)
// Child task created with startTask: false and initialStatus: "active"
expect(createTask).toHaveBeenCalledWith("Do something", undefined, parentTask, {
initialTodos: [],
initialStatus: "active",
startTask: false,
})
// Delegation metadata written via atomicReadAndUpdate with correct taskId
expect(taskHistoryStore.atomicReadAndUpdate).toHaveBeenCalledTimes(1)
const [calledTaskId, updater] = taskHistoryStore.atomicReadAndUpdate.mock.calls[0]
expect(calledTaskId).toBe("parent-1")
// The updater must produce the correct delegation fields
const result = updater(parentHistoryItem)
expect(result).toMatchObject({
id: "parent-1",
status: "delegated",
delegatedToId: "child-1",
awaitingChildId: "child-1",
childIds: expect.arrayContaining(["child-1"]),
})
// child.run() called AFTER parent metadata is persisted (via taskScheduler)
expect(childRun).toHaveBeenCalledTimes(1)
// Provider-level event
expect(providerEmit).toHaveBeenCalledWith(RooCodeEventName.TaskDelegated, "parent-1", "child-1")
// Mode switch
expect(handleModeSwitch).toHaveBeenCalledWith("code")
})
it("posts taskHistoryItemUpdated to the webview when isViewLaunched is true", async () => {
const updatedParent = { ...parentHistoryItem, status: "delegated" } as HistoryItem
const postMessageToWebview = vi.fn().mockResolvedValue(undefined)
const parentTask = makeParentTask()
const taskHistoryStore = makeStoreStub({
get: vi.fn().mockReturnValue(updatedParent),
})
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
createTask: vi.fn().mockResolvedValue({ taskId: "child-1", start: vi.fn(), run: () => Promise.resolve() }),
handleModeSwitch: vi.fn().mockResolvedValue(undefined),
postMessageToWebview,
log: vi.fn(),
isViewLaunched: true,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
await (ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Do something",
initialTodos: [],
mode: "code",
})
expect(postMessageToWebview).toHaveBeenCalledWith({
type: "taskHistoryItemUpdated",
taskHistoryItem: updatedParent,
})
})
it("skips postMessageToWebview when isViewLaunched is true but store returns undefined", async () => {
const postMessageToWebview = vi.fn().mockResolvedValue(undefined)
const parentTask = makeParentTask()
const taskHistoryStore = makeStoreStub({
get: vi.fn().mockReturnValue(undefined),
})
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
createTask: vi.fn().mockResolvedValue({ taskId: "child-1", start: vi.fn(), run: () => Promise.resolve() }),
handleModeSwitch: vi.fn().mockResolvedValue(undefined),
postMessageToWebview,
log: vi.fn(),
isViewLaunched: true,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
await (ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Do something",
initialTodos: [],
mode: "code",
})
expect(postMessageToWebview).not.toHaveBeenCalled()
})
it("calls child.run() only after atomicReadAndUpdate completes (no race condition)", async () => {
const callOrder: string[] = []
const parentTask = makeParentTask()
const childRun = vi.fn(async () => callOrder.push("child.run"))
const removeClineFromStack = vi.fn().mockResolvedValue(undefined)
const createTask = vi.fn(async () => {
callOrder.push("createTask")
return { taskId: "child-1", start: vi.fn(), run: childRun }
})
const handleModeSwitch = vi.fn().mockResolvedValue(undefined)
const taskHistoryStore = makeStoreStub({
atomicReadAndUpdate: vi.fn(async (_taskId: string, _updater: (h: HistoryItem) => HistoryItem) => {
callOrder.push("atomicReadAndUpdate")
return []
}),
})
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => parentTask),
removeClineFromStack,
createTask,
handleModeSwitch,
log: vi.fn(),
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
await (ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Do something",
initialTodos: [],
mode: "code",
})
await Promise.resolve() // drain scheduler microtask so child.run() is invoked
// createTask → atomicReadAndUpdate → child.run: scheduler admits child only after metadata is persisted
expect(callOrder).toEqual(["createTask", "atomicReadAndUpdate", "child.run"])
})
it("implicitly severs interrupted awaited child and re-delegates when parent is already delegated", async () => {
const oldChildId = "old-child"
const oldChild = { id: oldChildId, status: "interrupted" } as unknown as HistoryItem
const alreadyDelegatedParent: HistoryItem = {
...parentHistoryItem,
status: "delegated",
awaitingChildId: oldChildId,
delegatedToId: oldChildId,
childIds: [oldChildId],
} as unknown as HistoryItem
const taskHistoryStore = makeStoreStub({
// store returns: parent (delegated), old child (interrupted)
get: vi.fn((id: string) =>
id === "parent-1" ? alreadyDelegatedParent : id === oldChildId ? oldChild : undefined,
),
atomicReadAndUpdate: vi.fn(async (_taskId: string, updater: (h: HistoryItem) => HistoryItem) => {
updater(alreadyDelegatedParent)
return []
}),
})
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask: vi.fn(() => makeParentTask()),
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
createTask: vi.fn().mockResolvedValue({ taskId: "child-2", start: vi.fn(), run: () => Promise.resolve() }),
handleModeSwitch: vi.fn().mockResolvedValue(undefined),
log: vi.fn(),
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
await (ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Continue",
initialTodos: [],
mode: "code",
})
// The updater must sever the old link and apply the new delegation
const [, updater] = taskHistoryStore.atomicReadAndUpdate.mock.calls[0]
const result = updater(alreadyDelegatedParent)
expect(result).toMatchObject({
status: "delegated",
awaitingChildId: "child-2",
delegatedToId: "child-2",
})
// Old child ID preserved in childIds (audit trail)
expect(result.childIds).toContain(oldChildId)
expect(result.childIds).toContain("child-2")
})
it("rejects with 'Cannot re-delegate' when the existing awaited child is still active", async () => {
const oldChildId = "old-child"
const activeChild = { id: oldChildId, status: "active" } as unknown as HistoryItem
const alreadyDelegatedParent: HistoryItem = {
...parentHistoryItem,
status: "delegated",
awaitingChildId: oldChildId,
delegatedToId: oldChildId,
} as unknown as HistoryItem
const child = { taskId: "child-2", start: vi.fn(), run: vi.fn().mockResolvedValue(undefined) }
const getCurrentTask = vi.fn().mockReturnValue(makeParentTask())
const createTask = vi.fn().mockImplementation(async () => {
getCurrentTask.mockReturnValue(child)
return child
})
const taskHistoryStore = makeStoreStub({
get: vi.fn((id: string) =>
id === "parent-1" ? alreadyDelegatedParent : id === oldChildId ? activeChild : undefined,
),
// Real atomicReadAndUpdate behaviour: call the updater and propagate any throw
atomicReadAndUpdate: vi.fn(async (_taskId: string, updater: (h: HistoryItem) => HistoryItem) => {
updater(alreadyDelegatedParent)
return []
}),
})
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
removeClineFromStack: vi.fn().mockResolvedValue(undefined),
createTask,
handleModeSwitch: vi.fn().mockResolvedValue(undefined),
deleteTaskWithId: vi.fn().mockResolvedValue(undefined),
getTaskWithId: vi.fn().mockResolvedValue({ historyItem: alreadyDelegatedParent }),
createTaskWithHistoryItem: vi.fn().mockResolvedValue(undefined),
log: vi.fn(),
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
await expect(
(ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Continue",
initialTodos: [],
mode: "code",
}),
).rejects.toThrow("Cannot re-delegate")
// Rollback: child must not have run, and must be cleaned up
expect(child.run).not.toHaveBeenCalled()
expect((provider as any).deleteTaskWithId).toHaveBeenCalledWith("child-2", false)
})
it("rolls back the paused child and restores the parent when atomicReadAndUpdate fails", async () => {
const persistError = new Error("parent metadata persist failed")
const parentTask = makeParentTask()
const childRun = vi.fn().mockResolvedValue(undefined)
const removeClineFromStack = vi.fn().mockResolvedValue(undefined)
const deleteTaskWithId = vi.fn().mockResolvedValue(undefined)
const createTaskWithHistoryItem = vi.fn().mockResolvedValue(undefined)
const getTaskWithId = vi.fn().mockResolvedValue({ historyItem: parentHistoryItem })
const taskHistoryStore = makeStoreStub({
atomicReadAndUpdate: vi.fn().mockRejectedValue(persistError),
})
const child = { taskId: "child-1", start: vi.fn(), run: childRun }
// Before createTask: getCurrentTask returns parent (used by step 3 close).
// After createTask: returns child so the rollback guard passes and the child is popped.
const getCurrentTask = vi.fn().mockReturnValue(parentTask)
const createTask = vi.fn().mockImplementation(async () => {
getCurrentTask.mockReturnValue(child)
return child
})
const provider = {
taskScheduler: new TaskScheduler(),
emit: vi.fn(),
getCurrentTask,
removeClineFromStack,
createTask,
getTaskWithId,
handleModeSwitch: vi.fn().mockResolvedValue(undefined),
deleteTaskWithId,
createTaskWithHistoryItem,
log: vi.fn(),
isViewLaunched: false,
recentTasksCache: undefined,
taskHistoryStore,
} as unknown as ClineProvider
await expect(
(ClineProvider.prototype as any).delegateParentAndOpenChild.call(provider, {
parentTaskId: "parent-1",
message: "Do something",
initialTodos: [],
mode: "code",
}),
).rejects.toThrow(persistError)
expect(childRun).not.toHaveBeenCalled()
expect(removeClineFromStack).toHaveBeenNthCalledWith(1)
expect(removeClineFromStack).toHaveBeenNthCalledWith(2)
expect(deleteTaskWithId).toHaveBeenCalledWith("child-1", false)
expect(createTaskWithHistoryItem).toHaveBeenCalledWith(parentHistoryItem)
})
})