This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathnewTaskTool.spec.ts
More file actions
677 lines (589 loc) · 20.4 KB
/
Copy pathnewTaskTool.spec.ts
File metadata and controls
677 lines (589 loc) · 20.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
// npx vitest core/tools/__tests__/newTaskTool.spec.ts
import type { AskApproval, HandleError, NativeToolArgs, ToolUse } from "../../../shared/tools"
// Mock vscode module
vi.mock("vscode", () => ({
workspace: {
getConfiguration: vi.fn(() => ({
get: vi.fn(),
})),
},
}))
// Mock Package module
vi.mock("../../../shared/package", () => ({
Package: {
name: "roo-cline",
publisher: "RooVeterinaryInc",
version: "1.0.0",
outputChannel: "Roo-Code",
},
}))
// Mock other modules first - these are hoisted to the top
vi.mock("../../../shared/modes", () => ({
getModeBySlug: vi.fn(),
defaultModeSlug: "ask",
}))
vi.mock("../../prompts/responses", () => ({
formatResponse: {
toolError: vi.fn((msg: string) => `Tool Error: ${msg}`),
},
}))
vi.mock("../updateTodoListTool", () => ({
parseMarkdownChecklist: vi.fn((md: string) => {
// Simple mock implementation
const lines = md.split("\n").filter((line) => line.trim())
return lines.map((line, index) => {
let status = "pending"
let content = line
if (line.includes("[x]") || line.includes("[X]")) {
status = "completed"
content = line.replace(/^\[x\]\s*/i, "")
} else if (line.includes("[-]") || line.includes("[~]")) {
status = "in_progress"
content = line.replace(/^\[-\]\s*/, "").replace(/^\[~\]\s*/, "")
} else {
content = line.replace(/^\[\s*\]\s*/, "")
}
return {
id: `todo-${index}`,
content,
status,
}
})
}),
}))
// Define a minimal type for the resolved value
type MockClineInstance = { taskId: string }
// Mock dependencies after modules are mocked
const mockAskApproval = vi.fn<AskApproval>()
const mockHandleError = vi.fn<HandleError>()
const mockPushToolResult = vi.fn()
const mockEmit = vi.fn()
const mockRecordToolError = vi.fn()
const mockSayAndCreateMissingParamError = vi.fn()
const mockStartSubtask = vi
.fn<(message: string, todoItems: any[], mode: string) => Promise<MockClineInstance>>()
.mockResolvedValue({ taskId: "mock-subtask-id" })
// Adapter to satisfy legacy expectations while exercising new delegation path
const mockDelegateParentAndOpenChild = vi.fn(
async (args: { parentTaskId: string; message: string; initialTodos: any[]; mode: string }) => {
// Call legacy spy so existing expectations still pass
await mockStartSubtask(args.message, args.initialTodos, args.mode)
return { taskId: "child-1" }
},
)
const mockCheckpointSave = vi.fn()
// Mock the Cline instance and its methods/properties
const mockCline = {
ask: vi.fn(),
sayAndCreateMissingParamError: mockSayAndCreateMissingParamError,
emit: mockEmit,
recordToolError: mockRecordToolError,
consecutiveMistakeCount: 0,
isPaused: false,
pausedModeSlug: "ask",
taskId: "mock-parent-task-id",
enableCheckpoints: false,
checkpointSave: mockCheckpointSave,
startSubtask: mockStartSubtask,
providerRef: {
deref: vi.fn(() => ({
getState: vi.fn(() => ({ customModes: [], mode: "ask" })),
handleModeSwitch: vi.fn(),
delegateParentAndOpenChild: mockDelegateParentAndOpenChild,
})),
},
}
// Import the class to test AFTER mocks are set up
import { newTaskTool } from "../NewTaskTool"
import { getModeBySlug } from "../../../shared/modes"
import * as vscode from "vscode"
const withNativeArgs = (block: ToolUse<"new_task">): ToolUse<"new_task"> => ({
...block,
// Native tool calling: `nativeArgs` is the source of truth for tool execution.
// These tests intentionally exercise missing-param behavior, so we allow undefined
// values and let the tool's runtime validation handle it.
nativeArgs: {
mode: block.params.mode,
message: block.params.message,
todos: block.params.todos,
} as unknown as NativeToolArgs["new_task"],
})
describe("newTaskTool", () => {
beforeEach(() => {
// Reset mocks before each test
vi.clearAllMocks()
mockAskApproval.mockResolvedValue(true) // Default to approved
vi.mocked(getModeBySlug).mockReturnValue({
slug: "code",
name: "Code Mode",
roleDefinition: "Test role definition",
groups: ["command", "read", "edit"],
}) // Default valid mode
mockCline.consecutiveMistakeCount = 0
mockCline.isPaused = false
// Default: VSCode setting is disabled
const mockGet = vi.fn().mockReturnValue(false)
vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({
get: mockGet,
} as any)
})
it("should correctly un-escape \\\\@ to \\@ in the message passed to the new task", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use", // Add required 'type' property
name: "new_task", // Correct property name
params: {
mode: "code",
message: "Review this: \\\\@file1.txt and also \\\\\\\\@file2.txt", // Input with \\@ and \\\\@
todos: "[ ] First task\n[ ] Second task",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Verify askApproval was called
expect(mockAskApproval).toHaveBeenCalled()
// Verify the message passed to startSubtask reflects the code's behavior in unit tests
expect(mockStartSubtask).toHaveBeenCalledWith(
"Review this: \\@file1.txt and also \\\\\\@file2.txt", // Unit Test Expectation: \\@ -> \@, \\\\@ -> \\\\@
expect.arrayContaining([
expect.objectContaining({ content: "First task" }),
expect.objectContaining({ content: "Second task" }),
]),
"code",
)
// Verify side effects
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
it("should not un-escape single escaped \@", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use", // Add required 'type' property
name: "new_task", // Correct property name
params: {
mode: "code",
message: "This is already unescaped: \\@file1.txt",
todos: "[ ] Test todo",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
expect(mockStartSubtask).toHaveBeenCalledWith(
"This is already unescaped: \\@file1.txt", // Expected: \@ remains \@
expect.any(Array),
"code",
)
})
it("should not un-escape non-escaped @", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use", // Add required 'type' property
name: "new_task", // Correct property name
params: {
mode: "code",
message: "A normal mention @file1.txt",
todos: "[ ] Test todo",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
expect(mockStartSubtask).toHaveBeenCalledWith(
"A normal mention @file1.txt", // Expected: @ remains @
expect.any(Array),
"code",
)
})
it("should handle mixed escaping scenarios", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use", // Add required 'type' property
name: "new_task", // Correct property name
params: {
mode: "code",
message: "Mix: @file0.txt, \\@file1.txt, \\\\@file2.txt, \\\\\\\\@file3.txt",
todos: "[ ] Test todo",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
expect(mockStartSubtask).toHaveBeenCalledWith(
"Mix: @file0.txt, \\@file1.txt, \\@file2.txt, \\\\\\@file3.txt", // Unit Test Expectation: @->@, \@->\@, \\@->\@, \\\\@->\\\\@
expect.any(Array),
"code",
)
})
it("should handle missing todos parameter gracefully (backward compatibility)", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
// todos missing - should work for backward compatibility
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Should NOT error when todos is missing
expect(mockSayAndCreateMissingParamError).not.toHaveBeenCalledWith("new_task", "todos")
expect(mockCline.consecutiveMistakeCount).toBe(0)
expect(mockCline.recordToolError).not.toHaveBeenCalledWith("new_task")
// Should create task with empty todos array
expect(mockStartSubtask).toHaveBeenCalledWith("Test message", [], "code")
// Should complete successfully
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
it("should work with todos parameter when provided", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message with todos",
todos: "[ ] First task\n[ ] Second task",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Should parse and include todos when provided
expect(mockStartSubtask).toHaveBeenCalledWith(
"Test message with todos",
expect.arrayContaining([
expect.objectContaining({ content: "First task" }),
expect.objectContaining({ content: "Second task" }),
]),
"code",
)
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
it("should error when mode parameter is missing", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
// mode missing
message: "Test message",
todos: "[ ] Test todo",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
expect(mockSayAndCreateMissingParamError).toHaveBeenCalledWith("new_task", "mode")
expect(mockCline.consecutiveMistakeCount).toBe(1)
expect(mockCline.recordToolError).toHaveBeenCalledWith("new_task")
})
it("should error when message parameter is missing", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
// message missing
todos: "[ ] Test todo",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
expect(mockSayAndCreateMissingParamError).toHaveBeenCalledWith("new_task", "message")
expect(mockCline.consecutiveMistakeCount).toBe(1)
expect(mockCline.recordToolError).toHaveBeenCalledWith("new_task")
})
it("should parse todos with different statuses correctly", async () => {
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
todos: "[ ] Pending task\n[x] Completed task\n[-] In progress task",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
expect(mockStartSubtask).toHaveBeenCalledWith(
"Test message",
expect.arrayContaining([
expect.objectContaining({ content: "Pending task", status: "pending" }),
expect.objectContaining({ content: "Completed task", status: "completed" }),
expect.objectContaining({ content: "In progress task", status: "in_progress" }),
]),
"code",
)
})
describe("VSCode setting: newTaskRequireTodos", () => {
it("should NOT require todos when VSCode setting is disabled (default)", async () => {
// Ensure VSCode setting is disabled
const mockGet = vi.fn().mockReturnValue(false)
vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({
get: mockGet,
} as any)
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
// todos missing - should work when setting is disabled
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Should NOT error when todos is missing and setting is disabled
expect(mockSayAndCreateMissingParamError).not.toHaveBeenCalledWith("new_task", "todos")
expect(mockCline.consecutiveMistakeCount).toBe(0)
expect(mockCline.recordToolError).not.toHaveBeenCalledWith("new_task")
// Should create task with empty todos array
expect(mockStartSubtask).toHaveBeenCalledWith("Test message", [], "code")
// Should complete successfully
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
it("should REQUIRE todos when VSCode setting is enabled", async () => {
// Enable VSCode setting
const mockGet = vi.fn().mockReturnValue(true)
vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({
get: mockGet,
} as any)
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
// todos missing - should error when setting is enabled
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Should error when todos is missing and setting is enabled
expect(mockSayAndCreateMissingParamError).toHaveBeenCalledWith("new_task", "todos")
expect(mockCline.consecutiveMistakeCount).toBe(1)
expect(mockCline.recordToolError).toHaveBeenCalledWith("new_task")
// Should NOT create task
expect(mockStartSubtask).not.toHaveBeenCalled()
expect(mockPushToolResult).not.toHaveBeenCalledWith(
expect.stringContaining("Successfully created new task"),
)
})
it("should work with todos when VSCode setting is enabled", async () => {
// Enable VSCode setting
const mockGet = vi.fn().mockReturnValue(true)
vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({
get: mockGet,
} as any)
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
todos: "[ ] First task\n[ ] Second task",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Should NOT error when todos is provided and setting is enabled
expect(mockSayAndCreateMissingParamError).not.toHaveBeenCalledWith("new_task", "todos")
expect(mockCline.consecutiveMistakeCount).toBe(0)
// Should create task with parsed todos
expect(mockStartSubtask).toHaveBeenCalledWith(
"Test message",
expect.arrayContaining([
expect.objectContaining({ content: "First task" }),
expect.objectContaining({ content: "Second task" }),
]),
"code",
)
// Should complete successfully
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
it("should work with empty todos string when VSCode setting is enabled", async () => {
// Enable VSCode setting
const mockGet = vi.fn().mockReturnValue(true)
vi.mocked(vscode.workspace.getConfiguration).mockReturnValue({
get: mockGet,
} as any)
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
todos: "", // Empty string should be accepted
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Should NOT error when todos is empty string and setting is enabled
expect(mockSayAndCreateMissingParamError).not.toHaveBeenCalledWith("new_task", "todos")
expect(mockCline.consecutiveMistakeCount).toBe(0)
// Should create task with empty todos array
expect(mockStartSubtask).toHaveBeenCalledWith("Test message", [], "code")
// Should complete successfully
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
it("should check VSCode setting with Package.name configuration key", async () => {
const mockGet = vi.fn().mockReturnValue(false)
const mockGetConfiguration = vi.fn().mockReturnValue({
get: mockGet,
} as any)
vi.mocked(vscode.workspace.getConfiguration).mockImplementation(mockGetConfiguration)
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Verify that VSCode configuration was accessed with Package.name
expect(mockGetConfiguration).toHaveBeenCalledWith("roo-cline")
expect(mockGet).toHaveBeenCalledWith("newTaskRequireTodos", false)
})
it("should use current Package.name value (roo-code-nightly) when accessing VSCode configuration", async () => {
// Arrange: capture calls to VSCode configuration and ensure we can assert the namespace
const mockGet = vi.fn().mockReturnValue(false)
const mockGetConfiguration = vi.fn().mockReturnValue({
get: mockGet,
} as any)
vi.mocked(vscode.workspace.getConfiguration).mockImplementation(mockGetConfiguration)
// Mutate the mocked Package.name dynamically to simulate a different build variant
const pkg = await import("../../../shared/package")
;(pkg.Package as any).name = "roo-code-nightly"
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Test message",
},
partial: false,
}
await newTaskTool.handle(mockCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Assert: configuration was read using the dynamic nightly namespace
expect(mockGetConfiguration).toHaveBeenCalledWith("roo-code-nightly")
expect(mockGet).toHaveBeenCalledWith("newTaskRequireTodos", false)
})
})
// Add more tests for error handling (invalid mode, approval denied) if needed
})
describe("newTaskTool delegation flow", () => {
it("delegates to provider and does not call legacy startSubtask", async () => {
// Arrange: stub provider delegation
const providerSpy = {
getState: vi.fn().mockResolvedValue({
mode: "ask",
experiments: {},
}),
delegateParentAndOpenChild: vi.fn().mockResolvedValue({ taskId: "child-1" }),
handleModeSwitch: vi.fn(),
} as any
// Use a fresh local cline instance to avoid cross-test interference
const localStartSubtask = vi.fn()
const localEmit = vi.fn()
const localCline = {
ask: vi.fn(),
sayAndCreateMissingParamError: mockSayAndCreateMissingParamError,
emit: localEmit,
recordToolError: mockRecordToolError,
consecutiveMistakeCount: 0,
isPaused: false,
pausedModeSlug: "ask",
taskId: "mock-parent-task-id",
enableCheckpoints: false,
checkpointSave: mockCheckpointSave,
startSubtask: localStartSubtask,
providerRef: {
deref: vi.fn(() => providerSpy),
},
}
const block: ToolUse<"new_task"> = {
type: "tool_use",
name: "new_task",
params: {
mode: "code",
message: "Do something",
// no todos -> should default to []
},
partial: false,
}
// Act
await newTaskTool.handle(localCline as any, withNativeArgs(block), {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
})
// Assert: provider method called with correct params
expect(providerSpy.delegateParentAndOpenChild).toHaveBeenCalledWith({
parentTaskId: "mock-parent-task-id",
message: "Do something",
initialTodos: [],
mode: "code",
})
// Assert: legacy path not used
expect(localStartSubtask).not.toHaveBeenCalled()
// Assert: no pause/unpause events emitted in delegation path
const pauseEvents = (localEmit as any).mock.calls.filter(
(c: any[]) => c[0] === "taskPaused" || c[0] === "taskUnpaused",
)
expect(pauseEvents.length).toBe(0)
// Assert: tool result reflects delegation (pushed BEFORE delegation, so no child ID yet)
expect(mockPushToolResult).toHaveBeenCalledWith("Delegating to subtask...")
})
})