-
Notifications
You must be signed in to change notification settings - Fork 14.3k
Expand file tree
/
Copy pathscheduler.test.ts
More file actions
1684 lines (1440 loc) · 53.8 KB
/
Copy pathscheduler.test.ts
File metadata and controls
1684 lines (1440 loc) · 53.8 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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
describe,
it,
expect,
vi,
beforeEach,
afterEach,
type Mock,
type Mocked,
} from 'vitest';
import { randomUUID } from 'node:crypto';
vi.mock('node:crypto', () => ({
randomUUID: vi.fn(),
}));
const runInDevTraceSpan = vi.hoisted(() =>
vi.fn(async (opts, fn) => {
const metadata = { attributes: opts.attributes || {} };
return fn({
metadata,
});
}),
);
vi.mock('../telemetry/trace.js', () => ({
runInDevTraceSpan,
}));
import { logToolCall } from '../telemetry/loggers.js';
vi.mock('../telemetry/loggers.js', () => ({
logToolCall: vi.fn(),
}));
vi.mock('../telemetry/types.js', () => ({
ToolCallEvent: vi.fn().mockImplementation((call) => ({ ...call })),
}));
import {
SchedulerStateManager,
type TerminalCallHandler,
} from './state-manager.js';
import { resolveConfirmation } from './confirmation.js';
import { checkPolicy, updatePolicy } from './policy.js';
import { ToolExecutor } from './tool-executor.js';
import { ToolModificationHandler } from './tool-modifier.js';
import { MessageBusType, type Message } from '../confirmation-bus/types.js';
vi.mock('./state-manager.js');
vi.mock('./confirmation.js');
vi.mock('./policy.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('./policy.js')>();
return {
...actual,
checkPolicy: vi.fn(),
updatePolicy: vi.fn(),
};
});
vi.mock('./tool-executor.js');
vi.mock('./tool-modifier.js');
import { Scheduler } from './scheduler.js';
import type { Config } from '../config/config.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import type { PolicyEngine } from '../policy/policy-engine.js';
import type { ToolRegistry } from '../tools/tool-registry.js';
import { PolicyDecision, ApprovalMode } from '../policy/types.js';
import {
ToolConfirmationOutcome,
type AnyDeclarativeTool,
type AnyToolInvocation,
} from '../tools/tools.js';
import { UPDATE_TOPIC_TOOL_NAME } from '../tools/tool-names.js';
import {
CoreToolCallStatus,
ROOT_SCHEDULER_ID,
type ToolCallRequestInfo,
type ValidatingToolCall,
type SuccessfulToolCall,
type ErroredToolCall,
type CancelledToolCall,
type CompletedToolCall,
type ToolCallResponseInfo,
type ExecutingToolCall,
type Status,
type ToolCall,
} from './types.js';
import { ToolErrorType } from '../tools/tool-error.js';
import { GeminiCliOperation } from '../telemetry/constants.js';
import * as ToolUtils from '../utils/tool-utils.js';
import type { EditorType } from '../utils/editor.js';
import {
getToolCallContext,
type ToolCallContext,
} from '../utils/toolCallContext.js';
import {
coreEvents,
CoreEvent,
type McpProgressPayload,
} from '../utils/events.js';
describe('Scheduler (Orchestrator)', () => {
let scheduler: Scheduler;
let signal: AbortSignal;
let abortController: AbortController;
// Mocked Services (Injected via Config/Options)
let mockConfig: Mocked<Config>;
let mockMessageBus: Mocked<MessageBus>;
let mockPolicyEngine: Mocked<PolicyEngine>;
let mockToolRegistry: Mocked<ToolRegistry>;
let getPreferredEditor: Mock<() => EditorType | undefined>;
// Mocked Sub-components (Instantiated by Scheduler)
let mockStateManager: Mocked<SchedulerStateManager>;
let mockExecutor: Mocked<ToolExecutor>;
let mockModifier: Mocked<ToolModificationHandler>;
// Test Data
const req1: ToolCallRequestInfo = {
callId: 'call-1',
name: 'test-tool',
args: { foo: 'bar' },
isClientInitiated: false,
prompt_id: 'prompt-1',
schedulerId: ROOT_SCHEDULER_ID,
parentCallId: undefined,
};
const req2: ToolCallRequestInfo = {
callId: 'call-2',
name: 'test-tool',
args: { foo: 'baz', wait_for_previous: true },
isClientInitiated: false,
prompt_id: 'prompt-1',
schedulerId: ROOT_SCHEDULER_ID,
parentCallId: undefined,
};
const mockTool = {
name: 'test-tool',
build: vi.fn(),
} as unknown as AnyDeclarativeTool;
const mockInvocation = {
shouldConfirmExecute: vi.fn(),
};
beforeEach(() => {
vi.mocked(randomUUID).mockReturnValue(
'123e4567-e89b-12d3-a456-426614174000',
);
abortController = new AbortController();
signal = abortController.signal;
// --- Setup Injected Mocks ---
mockPolicyEngine = {
check: vi.fn().mockResolvedValue({ decision: PolicyDecision.ALLOW }),
} as unknown as Mocked<PolicyEngine>;
mockToolRegistry = {
getTool: vi.fn().mockReturnValue(mockTool),
getAllToolNames: vi.fn().mockReturnValue(['test-tool']),
} as unknown as Mocked<ToolRegistry>;
mockConfig = {
getPolicyEngine: vi.fn().mockReturnValue(mockPolicyEngine),
toolRegistry: mockToolRegistry,
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
getHookSystem: vi.fn().mockReturnValue(undefined),
isInteractive: vi.fn().mockReturnValue(true),
getEnableHooks: vi.fn().mockReturnValue(true),
setApprovalMode: vi.fn(),
getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
getTelemetryLogPromptsEnabled: vi.fn().mockReturnValue(false),
getTelemetryTracesEnabled: vi.fn().mockReturnValue(false),
getSessionId: vi.fn().mockReturnValue('test-session-id'),
} as unknown as Mocked<Config>;
(mockConfig as unknown as { config: Config }).config = mockConfig as Config;
mockMessageBus = {
publish: vi.fn(),
subscribe: vi.fn(),
} as unknown as Mocked<MessageBus>;
(mockConfig as unknown as { toolRegistry: ToolRegistry }).toolRegistry =
mockToolRegistry;
(mockConfig as unknown as { messageBus: MessageBus }).messageBus =
mockMessageBus;
getPreferredEditor = vi.fn().mockReturnValue('vim');
// --- Setup Sub-component Mocks ---
const mockActiveCallsMap = new Map<string, ToolCall>();
const mockQueue: ToolCall[] = [];
mockStateManager = {
enqueue: vi.fn((calls: ToolCall[]) => {
// Clone to preserve initial state for Phase 1 tests
mockQueue.push(...calls.map((c) => ({ ...c }) as ToolCall));
}),
dequeue: vi.fn(() => {
const next = mockQueue.shift();
if (next) mockActiveCallsMap.set(next.request.callId, next);
return next;
}),
peekQueue: vi.fn(() => mockQueue[0]),
getToolCall: vi.fn((id: string) => mockActiveCallsMap.get(id)),
updateStatus: vi.fn((id: string, status: Status) => {
const call = mockActiveCallsMap.get(id);
if (call) (call as unknown as { status: Status }).status = status;
}),
finalizeCall: vi.fn((id: string) => {
const call = mockActiveCallsMap.get(id);
if (call) {
mockActiveCallsMap.delete(id);
capturedTerminalHandler?.(call as CompletedToolCall);
}
}),
updateArgs: vi.fn(),
setOutcome: vi.fn(),
cancelAllQueued: vi.fn(() => {
mockQueue.length = 0;
}),
clearBatch: vi.fn(),
replaceActiveCallWithTailCall: vi.fn((id: string, nextCall: ToolCall) => {
if (mockActiveCallsMap.has(id)) {
mockActiveCallsMap.delete(id);
mockQueue.unshift(nextCall);
}
}),
} as unknown as Mocked<SchedulerStateManager>;
// Define getters for accessors idiomatically
Object.defineProperty(mockStateManager, 'isActive', {
get: vi.fn(() => mockActiveCallsMap.size > 0),
configurable: true,
});
Object.defineProperty(mockStateManager, 'allActiveCalls', {
get: vi.fn(() => Array.from(mockActiveCallsMap.values())),
configurable: true,
});
Object.defineProperty(mockStateManager, 'queueLength', {
get: vi.fn(() => mockQueue.length),
configurable: true,
});
Object.defineProperty(mockStateManager, 'firstActiveCall', {
get: vi.fn(() => mockActiveCallsMap.values().next().value),
configurable: true,
});
Object.defineProperty(mockStateManager, 'completedBatch', {
get: vi.fn().mockReturnValue([]),
configurable: true,
});
vi.spyOn(mockStateManager, 'cancelAllQueued').mockImplementation(() => {});
vi.spyOn(mockStateManager, 'clearBatch').mockImplementation(() => {});
vi.mocked(resolveConfirmation).mockReset();
vi.mocked(checkPolicy).mockReset();
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.ALLOW,
rule: undefined,
});
vi.mocked(updatePolicy).mockReset();
mockExecutor = {
execute: vi.fn(),
} as unknown as Mocked<ToolExecutor>;
mockModifier = {
handleModifyWithEditor: vi.fn(),
applyInlineModify: vi.fn(),
} as unknown as Mocked<ToolModificationHandler>;
let capturedTerminalHandler: TerminalCallHandler | undefined;
vi.mocked(SchedulerStateManager).mockImplementation(
(_messageBus, _schedulerId, onTerminalCall) => {
capturedTerminalHandler = onTerminalCall;
return mockStateManager as unknown as SchedulerStateManager;
},
);
mockStateManager.finalizeCall.mockImplementation((callId: string) => {
const call = mockActiveCallsMap.get(callId);
if (call) {
mockActiveCallsMap.delete(callId);
capturedTerminalHandler?.(call as CompletedToolCall);
}
});
mockStateManager.cancelAllQueued.mockImplementation((_reason: string) => {
// In tests, we usually mock the queue or completed batch.
// For the sake of telemetry tests, we manually trigger if needed,
// but most tests here check if finalizing is called.
});
vi.mocked(ToolExecutor).mockReturnValue(
mockExecutor as unknown as Mocked<ToolExecutor>,
);
mockExecutor.execute.mockResolvedValue({
status: 'success',
response: {
callId: 'default',
responseParts: [],
} as unknown as ToolCallResponseInfo,
} as unknown as SuccessfulToolCall);
vi.mocked(ToolModificationHandler).mockReturnValue(
mockModifier as unknown as Mocked<ToolModificationHandler>,
);
// Initialize Scheduler
scheduler = new Scheduler({
context: mockConfig,
messageBus: mockMessageBus,
getPreferredEditor,
schedulerId: 'root',
});
// Reset Tool build behavior
vi.mocked(mockTool.build).mockReturnValue(
mockInvocation as unknown as AnyToolInvocation,
);
});
afterEach(() => {
vi.clearAllMocks();
});
describe('Phase 1: Ingestion & Resolution', () => {
it('should create an ErroredToolCall if tool is not found', async () => {
vi.mocked(mockToolRegistry.getTool).mockReturnValue(undefined);
vi.spyOn(ToolUtils, 'getToolSuggestion').mockReturnValue(
' (Did you mean "test-tool"?)',
);
await scheduler.schedule(req1, signal);
// Verify it was enqueued with an error status
expect(mockStateManager.enqueue).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
status: CoreToolCallStatus.Error,
response: expect.objectContaining({
errorType: ToolErrorType.TOOL_NOT_REGISTERED,
}),
}),
]),
);
});
it('should create an ErroredToolCall if tool.build throws (invalid args)', async () => {
vi.mocked(mockTool.build).mockImplementation(() => {
throw new Error('Invalid schema');
});
await scheduler.schedule(req1, signal);
expect(mockStateManager.enqueue).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
status: CoreToolCallStatus.Error,
response: expect.objectContaining({
errorType: ToolErrorType.INVALID_TOOL_PARAMS,
}),
}),
]),
);
});
it('should propagate subagent name to checkPolicy', async () => {
const { checkPolicy } = await import('./policy.js');
const scheduler = new Scheduler({
context: mockConfig,
schedulerId: 'sub-scheduler',
subagent: 'my-agent',
getPreferredEditor: () => undefined,
});
const request: ToolCallRequestInfo = {
callId: 'call-1',
name: 'test-tool',
args: {},
isClientInitiated: false,
prompt_id: 'p1',
};
await scheduler.schedule([request], new AbortController().signal);
expect(checkPolicy).toHaveBeenCalledWith(
expect.anything(),
expect.anything(),
'my-agent',
);
});
it('should correctly build ValidatingToolCalls for happy path', async () => {
await scheduler.schedule(req1, signal);
expect(mockStateManager.enqueue).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
status: CoreToolCallStatus.Validating,
request: expect.objectContaining(req1),
tool: mockTool,
invocation: mockInvocation,
schedulerId: ROOT_SCHEDULER_ID,
startTime: expect.any(Number),
}),
]),
);
expect(runInDevTraceSpan).toHaveBeenCalledWith(
expect.objectContaining({
operation: GeminiCliOperation.ScheduleToolCalls,
}),
expect.any(Function),
);
const spanArgs = vi.mocked(runInDevTraceSpan).mock.calls[0];
const fn = spanArgs[1];
const metadata = { attributes: {} };
await fn({ metadata });
expect(metadata).toMatchObject({
input: [req1],
});
});
it('should set approvalMode to PLAN when config returns PLAN', async () => {
mockConfig.getApprovalMode.mockReturnValue(ApprovalMode.PLAN);
await scheduler.schedule(req1, signal);
expect(mockStateManager.enqueue).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({
status: CoreToolCallStatus.Validating,
approvalMode: ApprovalMode.PLAN,
}),
]),
);
});
it('should sort UPDATE_TOPIC_TOOL_NAME to the front of the batch', async () => {
const topicReq: ToolCallRequestInfo = {
callId: 'call-topic',
name: UPDATE_TOPIC_TOOL_NAME,
args: { title: 'New Chapter' },
prompt_id: 'p1',
isClientInitiated: false,
};
const otherReq: ToolCallRequestInfo = {
callId: 'call-other',
name: 'test-tool',
args: {},
prompt_id: 'p1',
isClientInitiated: false,
};
// Mock tool registry to return a tool for update_topic
vi.mocked(mockToolRegistry.getTool).mockImplementation((name) => {
if (name === UPDATE_TOPIC_TOOL_NAME) {
return {
name: UPDATE_TOPIC_TOOL_NAME,
build: vi.fn().mockReturnValue({}),
} as unknown as AnyDeclarativeTool;
}
return mockTool;
});
// Schedule in reverse order (other first, topic second)
await scheduler.schedule([otherReq, topicReq], signal);
// Verify they were enqueued in the correct sorted order (topic first)
const enqueueCalls = vi.mocked(mockStateManager.enqueue).mock.calls;
const lastCall = enqueueCalls[enqueueCalls.length - 1][0];
expect(lastCall[0].request.callId).toBe('call-topic');
expect(lastCall[1].request.callId).toBe('call-other');
});
});
describe('Phase 2: Queue Management', () => {
it('should drain the queue if multiple calls are scheduled', async () => {
// Execute is the end of the loop, stub it
mockExecutor.execute.mockResolvedValue({
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall);
await scheduler.schedule(req1, signal);
// Verify loop ran once for this schedule call (which had 1 request)
// schedule(req1) enqueues 1 request.
expect(mockExecutor.execute).toHaveBeenCalledTimes(1);
});
it('should execute tool calls sequentially (first completes before second starts)', async () => {
const executionLog: string[] = [];
// Mock executor to push to log with a deterministic microtask delay
mockExecutor.execute.mockImplementation(async ({ call }) => {
const id = call.request.callId;
executionLog.push(`start-${id}`);
// Yield to the event loop deterministically using queueMicrotask
await new Promise<void>((resolve) => queueMicrotask(resolve));
executionLog.push(`end-${id}`);
return {
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall;
});
// Action: Schedule batch of 2 tools
await scheduler.schedule([req1, req2], signal);
// Assert: The second tool only started AFTER the first one ended
expect(executionLog).toEqual([
'start-call-1',
'end-call-1',
'start-call-2',
'end-call-2',
]);
});
it('should queue and process multiple schedule() calls made synchronously', async () => {
// Executor succeeds instantly
mockExecutor.execute.mockResolvedValue({
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall);
// ACT: Call schedule twice synchronously (without awaiting the first)
const promise1 = scheduler.schedule(req1, signal);
const promise2 = scheduler.schedule(req2, signal);
await Promise.all([promise1, promise2]);
// ASSERT: Both requests were eventually pulled from the queue and executed
expect(mockExecutor.execute).toHaveBeenCalledTimes(2);
expect(mockStateManager.finalizeCall).toHaveBeenCalledWith('call-1');
expect(mockStateManager.finalizeCall).toHaveBeenCalledWith('call-2');
});
it('should queue requests when scheduler is busy (overlapping batches)', async () => {
// 2. Setup Executor with a controllable lock for the first batch
const executionLog: string[] = [];
let finishFirstBatch: (value: unknown) => void;
const firstBatchPromise = new Promise((resolve) => {
finishFirstBatch = resolve;
});
mockExecutor.execute.mockImplementationOnce(async () => {
executionLog.push('start-batch-1');
await firstBatchPromise; // Simulating long-running tool execution
executionLog.push('end-batch-1');
return {
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall;
});
mockExecutor.execute.mockImplementationOnce(async () => {
executionLog.push('start-batch-2');
executionLog.push('end-batch-2');
return {
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall;
});
// 3. ACTIONS
// Start Batch 1 (it will block indefinitely inside execution)
const promise1 = scheduler.schedule(req1, signal);
// Schedule Batch 2 WHILE Batch 1 is executing
const promise2 = scheduler.schedule(req2, signal);
// Yield event loop to let promise2 hit the queue
await new Promise((r) => setTimeout(r, 0));
// At this point, Batch 2 should NOT have started
expect(executionLog).not.toContain('start-batch-2');
// Now resolve Batch 1, which should trigger the request queue drain
finishFirstBatch!({});
await Promise.all([promise1, promise2]);
// 4. ASSERTIONS
// Verify complete sequential ordering of the two overlapping batches
expect(executionLog).toEqual([
'start-batch-1',
'end-batch-1',
'start-batch-2',
'end-batch-2',
]);
});
it('should cancel all queues if AbortSignal is triggered during loop', async () => {
Object.defineProperty(mockStateManager, 'queueLength', {
get: vi.fn().mockReturnValue(1),
configurable: true,
});
abortController.abort(); // Signal aborted
await scheduler.schedule(req1, signal);
expect(mockStateManager.cancelAllQueued).toHaveBeenCalledWith(
'Operation cancelled',
);
expect(mockStateManager.dequeue).not.toHaveBeenCalled(); // Loop broke
});
it('should not enqueue or validate tool calls when scheduled with an already-aborted signal (regression #28091)', async () => {
// If a delayed tool-call chunk reaches the scheduler after the user
// cancelled, we must not invoke the tool registry / validators or
// enqueue the call — the late side effect would run before the queue
// processor's own abort check kicked in.
abortController.abort();
await scheduler.schedule(req1, signal);
expect(mockStateManager.enqueue).not.toHaveBeenCalled();
expect(mockStateManager.cancelAllQueued).toHaveBeenCalledWith(
'Operation cancelled',
);
});
it('should not leak queued batches when scheduled with an already-aborted signal (regression #28091)', async () => {
// The aborted-signal short-circuit must still drain the request
// queue via the `finally` block — otherwise a follow-up batch
// queued behind it would never resolve and hang the caller.
abortController.abort();
// First batch is rejected by the abort guard.
await scheduler.schedule(req1, signal);
// A second batch scheduled with a fresh, non-aborted signal must
// still make progress (i.e. the scheduler must not be stuck in the
// "busy" state after the early-return path).
const fresh = new AbortController();
await expect(
scheduler.schedule(req2, fresh.signal),
).resolves.toBeDefined();
});
it('cancelAll() should cancel active call and clear queue', () => {
const activeCall: ValidatingToolCall = {
status: CoreToolCallStatus.Validating,
request: req1,
tool: mockTool,
invocation: mockInvocation as unknown as AnyToolInvocation,
};
mockStateManager.enqueue([activeCall]);
mockStateManager.dequeue();
scheduler.cancelAll();
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Cancelled,
'Operation cancelled by user',
);
// finalizeCall is handled by the processing loop, not synchronously by cancelAll
// expect(mockStateManager.finalizeCall).toHaveBeenCalledWith('call-1');
expect(mockStateManager.cancelAllQueued).toHaveBeenCalledWith(
'Operation cancelled by user',
);
});
it('cancelAll() should clear the requestQueue and reject pending promises', async () => {
// 1. Setup a busy scheduler with one batch processing
Object.defineProperty(mockStateManager, 'isActive', {
get: vi.fn().mockReturnValue(true),
configurable: true,
});
const promise1 = scheduler.schedule(req1, signal);
// Catch promise1 to avoid unhandled rejection when we cancelAll
promise1.catch(() => {});
// 2. Queue another batch while the first is busy
const promise2 = scheduler.schedule(req2, signal);
// 3. ACT: Cancel everything
scheduler.cancelAll();
// 4. ASSERT: The second batch's promise should be rejected
await expect(promise2).rejects.toThrow('Operation cancelled by user');
});
});
describe('Phase 3: Policy & Confirmation Loop', () => {
beforeEach(() => {});
it('should update state to error with POLICY_VIOLATION if Policy returns DENY', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.DENY,
rule: undefined,
});
await scheduler.schedule(req1, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Error,
expect.objectContaining({
errorType: ToolErrorType.POLICY_VIOLATION,
}),
);
// Deny shouldn't throw, execution is just skipped, state is updated
expect(mockExecutor.execute).not.toHaveBeenCalled();
});
it('should include denyMessage in error response if present', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.DENY,
rule: {
toolName: '*',
decision: PolicyDecision.DENY,
denyMessage: 'Custom denial reason',
},
});
await scheduler.schedule(req1, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Error,
expect.objectContaining({
errorType: ToolErrorType.POLICY_VIOLATION,
responseParts: expect.arrayContaining([
expect.objectContaining({
functionResponse: expect.objectContaining({
response: {
error:
'Tool execution denied by policy. Custom denial reason',
},
}),
}),
]),
}),
);
});
it('should use originalRequestName when generating an error response', async () => {
const error = new Error('Some error');
vi.mocked(checkPolicy).mockRejectedValue(error);
const tailReq = { ...req1, originalRequestName: 'original-tool-name' };
await scheduler.schedule(tailReq, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Error,
expect.objectContaining({
errorType: ToolErrorType.UNHANDLED_EXCEPTION,
responseParts: expect.arrayContaining([
expect.objectContaining({
functionResponse: expect.objectContaining({
name: 'original-tool-name',
response: { error: 'Some error' },
}),
}),
]),
}),
);
});
it('should handle errors from checkPolicy (e.g. non-interactive ASK_USER)', async () => {
const error = new Error('Not interactive');
vi.mocked(checkPolicy).mockRejectedValue(error);
await scheduler.schedule(req1, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Error,
expect.objectContaining({
errorType: ToolErrorType.UNHANDLED_EXCEPTION,
responseParts: expect.arrayContaining([
expect.objectContaining({
functionResponse: expect.objectContaining({
response: { error: 'Not interactive' },
}),
}),
]),
}),
);
});
it('should return POLICY_VIOLATION error type when denied in Plan Mode', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.DENY,
rule: { toolName: '*', decision: PolicyDecision.DENY },
});
mockConfig.getApprovalMode.mockReturnValue(ApprovalMode.PLAN);
await scheduler.schedule(req1, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Error,
expect.objectContaining({
errorType: ToolErrorType.POLICY_VIOLATION,
responseParts: expect.arrayContaining([
expect.objectContaining({
functionResponse: expect.objectContaining({
response: {
error: 'Tool execution denied by policy.',
},
}),
}),
]),
}),
);
});
it('should return POLICY_VIOLATION and custom deny message when denied in Plan Mode with rule message', async () => {
const customMessage = 'Custom Plan Mode Deny';
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.DENY,
rule: {
toolName: '*',
decision: PolicyDecision.DENY,
denyMessage: customMessage,
},
});
mockConfig.getApprovalMode.mockReturnValue(ApprovalMode.PLAN);
await scheduler.schedule(req1, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Error,
expect.objectContaining({
errorType: ToolErrorType.POLICY_VIOLATION,
responseParts: expect.arrayContaining([
expect.objectContaining({
functionResponse: expect.objectContaining({
response: {
error: `Tool execution denied by policy. ${customMessage}`,
},
}),
}),
]),
}),
);
});
it('should bypass confirmation and ProceedOnce if Policy returns ALLOW (YOLO/AllowedTools)', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.ALLOW,
rule: undefined,
});
// Provide a mock execute to finish the loop
mockExecutor.execute.mockResolvedValue({
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall);
await scheduler.schedule(req1, signal);
// Never called coordinator
expect(resolveConfirmation).not.toHaveBeenCalled();
// State recorded as ProceedOnce
expect(mockStateManager.setOutcome).toHaveBeenCalledWith(
'call-1',
ToolConfirmationOutcome.ProceedOnce,
);
// Triggered execution
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Executing,
);
expect(mockExecutor.execute).toHaveBeenCalled();
});
it('should auto-approve remaining identical tools in batch after ProceedAlways', async () => {
// First call requires confirmation, second is auto-approved (simulating policy update)
vi.mocked(checkPolicy)
.mockResolvedValueOnce({
decision: PolicyDecision.ASK_USER,
rule: undefined,
})
.mockResolvedValueOnce({
decision: PolicyDecision.ALLOW,
rule: undefined,
});
vi.mocked(resolveConfirmation).mockResolvedValue({
outcome: ToolConfirmationOutcome.ProceedAlways,
lastDetails: undefined,
});
mockExecutor.execute.mockResolvedValue({
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall);
await scheduler.schedule([req1, req2], signal);
// resolveConfirmation only called ONCE
expect(resolveConfirmation).toHaveBeenCalledTimes(1);
// updatePolicy called for the first tool
expect(updatePolicy).toHaveBeenCalled();
// execute called TWICE
expect(mockExecutor.execute).toHaveBeenCalledTimes(2);
});
it('should call resolveConfirmation and updatePolicy when ASK_USER', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.ASK_USER,
rule: undefined,
});
const resolution = {
outcome: ToolConfirmationOutcome.ProceedAlways,
lastDetails: {
type: 'info' as const,
title: 'Title',
prompt: 'Confirm?',
},
};
vi.mocked(resolveConfirmation).mockResolvedValue(resolution);
mockExecutor.execute.mockResolvedValue({
status: CoreToolCallStatus.Success,
} as unknown as SuccessfulToolCall);
await scheduler.schedule(req1, signal);
expect(resolveConfirmation).toHaveBeenCalledWith(
expect.anything(), // toolCall
signal,
expect.objectContaining({
config: mockConfig,
messageBus: expect.anything(),
state: mockStateManager,
schedulerId: ROOT_SCHEDULER_ID,
}),
);
expect(updatePolicy).toHaveBeenCalledWith(
mockTool,
resolution.outcome,
resolution.lastDetails,
mockConfig,
expect.anything(),
expect.anything(),
);
expect(mockExecutor.execute).toHaveBeenCalled();
});
it('should cancel and NOT execute if resolveConfirmation returns Cancel', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.ASK_USER,
rule: undefined,
});
const resolution = {
outcome: ToolConfirmationOutcome.Cancel,
lastDetails: undefined,
};
vi.mocked(resolveConfirmation).mockResolvedValue(resolution);
await scheduler.schedule(req1, signal);
expect(mockStateManager.updateStatus).toHaveBeenCalledWith(
'call-1',
CoreToolCallStatus.Cancelled,
'User denied execution.',
);
expect(mockStateManager.setOutcome).toHaveBeenCalledWith(
'call-1',
ToolConfirmationOutcome.Cancel,
);
expect(mockStateManager.cancelAllQueued).toHaveBeenCalledWith(
'User cancelled operation',
);
expect(mockExecutor.execute).not.toHaveBeenCalled();
});
it('should mark as cancelled (not errored) when abort happens during confirmation error', async () => {
vi.mocked(checkPolicy).mockResolvedValue({
decision: PolicyDecision.ASK_USER,
rule: undefined,
});
// Simulate shouldConfirmExecute logic throwing while aborted
vi.mocked(resolveConfirmation).mockImplementation(async () => {
// Trigger abort
abortController.abort();
throw new Error('Some internal network abort error');
});