-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathcoordinator.test.ts
More file actions
3639 lines (3078 loc) · 137 KB
/
Copy pathcoordinator.test.ts
File metadata and controls
3639 lines (3078 loc) · 137 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
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import os from 'os';
import { join, dirname } from 'path';
import { getChangedFiles, getAllFileDiffs, getDiffBaseSha } from '../ipc/git.js';
// --- fs / child_process mocks (must come before dynamic import) ---
const mockExecFile = vi.fn(
(
_cmd: string,
_args: string[],
_opts: unknown,
cb: (err: Error | null, stdout: string, stderr: string) => void,
) => {
cb(null, '', '');
},
);
vi.mock('child_process', () => ({
execFile: mockExecFile,
}));
const mockWriteFileSync = vi.fn();
const mockReadFileSync = vi.fn(() => '# existing\n');
const mockExistsSync = vi.fn(() => false);
const mockUnlinkSync = vi.fn();
const mockMkdirSync = vi.fn();
vi.mock('fs', () => ({
writeFileSync: mockWriteFileSync,
readFileSync: mockReadFileSync,
existsSync: mockExistsSync,
unlinkSync: mockUnlinkSync,
mkdirSync: mockMkdirSync,
}));
// fs/promises mocks — mirror the sync mocks above
const mockFsWriteFile = vi.fn().mockResolvedValue(undefined);
const mockFsReadFile = vi.fn().mockResolvedValue('# existing\n');
const mockFsAccess = vi
.fn()
.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
const mockFsUnlink = vi.fn().mockResolvedValue(undefined);
const mockFsMkdir = vi.fn().mockResolvedValue(undefined);
vi.mock('fs/promises', () => ({
writeFile: mockFsWriteFile,
readFile: mockFsReadFile,
access: mockFsAccess,
unlink: mockFsUnlink,
mkdir: mockFsMkdir,
}));
// --- other mocks ---
const mockNotifyRenderer = vi.fn();
const mockOnPtyEvent = vi.fn();
const mockSpawnAgent = vi.fn();
const mockSubscribeToAgent = vi.fn();
const mockGetAgentScrollback = vi.fn<() => string | null>(() => null);
const mockCreateBackendTask = vi.fn().mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
const mockAtomicWriteFileSync = vi.fn();
const mockAtomicWriteFile = vi.fn().mockResolvedValue(undefined);
vi.mock('./atomic.js', () => ({
atomicWriteFileSync: mockAtomicWriteFileSync,
atomicWriteFile: mockAtomicWriteFile,
}));
vi.mock('./prompt-detect.js', () => ({
stripAnsi: (s: string) => s,
chunkContainsAgentPrompt: (s: string) => s.includes('❯'),
}));
vi.mock('../ipc/pty.js', () => ({
spawnAgent: mockSpawnAgent,
writeToAgent: vi.fn(),
killAgent: vi.fn(),
subscribeToAgent: mockSubscribeToAgent,
unsubscribeFromAgent: vi.fn(),
getAgentScrollback: mockGetAgentScrollback,
onPtyEvent: mockOnPtyEvent,
}));
vi.mock('../ipc/git.js', () => ({
getChangedFiles: vi.fn().mockResolvedValue([]),
getAllFileDiffs: vi.fn().mockResolvedValue(''),
getDiffBaseSha: vi.fn().mockResolvedValue('abc123sha'),
mergeTask: vi.fn(),
}));
vi.mock('../ipc/tasks.js', () => ({
createTask: mockCreateBackendTask,
deleteTask: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('../ipc/channels.js', () => ({
IPC: {
MCP_TaskCreated: 'mcp_task_created',
MCP_TaskClosed: 'mcp_task_closed',
MCP_TaskCleanupFailed: 'mcp_task_cleanup_failed',
MCP_TaskStateSync: 'mcp_task_state_sync',
MCP_CoordinatorNotificationStaged: 'mcp_coordinator_notification_staged',
MCP_CoordinatorNotificationCleared: 'mcp_coordinator_notification_cleared',
MCP_CoordinatorOrphanedNotification: 'mcp_coordinator_orphaned_notification',
MCP_CoordinatorDeregistered: 'mcp_coordinator_deregistered',
MCP_CoordinatorNotificationAck: 'mcp_coordinator_notification_ack',
},
}));
// Import after mocks
const { Coordinator } = await import('./coordinator.js');
const { removePreambleBlock } = await import('./preamble.js');
// --- helpers ---
function getExitHandler(): (agentId: string, data: unknown) => void {
const call = mockOnPtyEvent.mock.calls.find((c) => c[0] === 'exit');
if (!call) throw new Error('exit handler not registered');
return call[1] as (agentId: string, data: unknown) => void;
}
function getOutputCb(): (encoded: string) => void {
const call = mockSubscribeToAgent.mock.calls[0];
if (!call) throw new Error('subscribeToAgent not called');
return call[1] as (encoded: string) => void;
}
function getAgentId(): string {
const call = mockSubscribeToAgent.mock.calls[0];
if (!call) throw new Error('subscribeToAgent not called');
return call[0] as string;
}
function encode(s: string): string {
return Buffer.from(s).toString('base64');
}
const mockWin = {
isDestroyed: () => false,
webContents: { send: mockNotifyRenderer },
} as unknown as import('electron').BrowserWindow;
// ─── registerCoordinator idempotency and restore path ────────────────────────
describe('Coordinator registerCoordinator — idempotency', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
});
it('registerCoordinator is idempotent — second call is a no-op', () => {
coordinator.registerCoordinator('coord-1', 'proj-1', { worktreePath: '/tmp/project' });
coordinator.registerCoordinator('coord-1', 'proj-1', { worktreePath: '/tmp/project' });
// createTask should work — only one CoordinatorState entry
expect(() =>
coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' }),
).not.toThrow();
});
it('createTask succeeds when registerCoordinator is called before (not after) createTask', async () => {
// Simulates the restore path: StartMCPServer calls registerCoordinator, then
// the agent calls create_task over MCP. MCP_CoordinatorRegistered has NOT been
// sent (App.tsx restore loop does not send it).
coordinator.registerCoordinator('coord-1', 'proj-1');
await expect(
coordinator.createTask({ name: 'restore-task', prompt: 'do', coordinatorTaskId: 'coord-1' }),
).resolves.toBeDefined();
expect(mockNotifyRenderer).toHaveBeenCalledWith('mcp_task_created', expect.anything());
});
it('createTask notifies coordinator when coordinator registered only via registerCoordinator', async () => {
// Simulates restore: StartMCPServer calls registerCoordinator internally.
// No separate MCP_CoordinatorRegistered call occurs.
coordinator.registerCoordinator('coord-1', 'proj-1');
coordinator.setMCPServerInfo(
'coord-1',
'http://localhost:3001',
'tok',
'subtask-tok',
'/path/server.js',
);
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
// Should get a task created notification (not "coordinator not found" error)
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_task_created',
expect.objectContaining({ name: 'test' }),
);
});
});
// ─── coordinator notification tests ───────────────────────────────────────────
describe('Coordinator coordinator notifications', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
});
it('does not notify when assignedPromptDelivered is false (startup idle)', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({
name: 'test',
prompt: 'do work',
coordinatorTaskId: 'coord-1',
});
const outputCb = getOutputCb();
outputCb(encode('Welcome ❯ '));
expect(mockNotifyRenderer).not.toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.anything(),
);
});
it('notifies coordinator when sub-task exits before prompt delivery (user closed early)', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do work', coordinatorTaskId: 'coord-1' });
const agentId = getAgentId();
const exitHandler = getExitHandler();
// Never call markPromptDelivered — simulates user closing the task before prompt lands
exitHandler(agentId, { exitCode: null });
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({ coordinatorTaskId: 'coord-1' }),
);
});
it('notifies coordinator when sub-task idles after prompt delivery', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({
name: 'test',
prompt: 'do work',
coordinatorTaskId: 'coord-1',
});
const outputCb = getOutputCb();
coordinator.markPromptDelivered('task-1');
outputCb(encode('Working... ❯ '));
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({
coordinatorTaskId: 'coord-1',
notificationIds: expect.any(Array),
}),
);
});
it('does not enqueue duplicate notification for repeated idles', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Done ❯ '));
outputCb(encode('Still here '));
outputCb(encode('Idle again ❯ '));
const calls = mockNotifyRenderer.mock.calls.filter(
(c) => c[0] === 'mcp_coordinator_notification_staged',
);
const lastPayload = calls[calls.length - 1]?.[1] as { notificationIds: string[] };
expect(lastPayload.notificationIds).toHaveLength(1);
});
it('upgrades idle→exited on PTY exit without adding duplicate', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
const agentId = getAgentId();
const exitHandler = getExitHandler();
outputCb(encode('Done ❯ '));
mockNotifyRenderer.mockClear();
exitHandler(agentId, { exitCode: 0 });
const stagedCalls = mockNotifyRenderer.mock.calls.filter(
(c) => c[0] === 'mcp_coordinator_notification_staged',
);
expect(stagedCalls).toHaveLength(1);
const payload = stagedCalls[0][1] as { notificationIds: string[] };
expect(payload.notificationIds).toHaveLength(1);
});
it('ack removes only the pending IDs in that batch', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'task-a', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Done ❯ '));
const stagedCallAck = mockNotifyRenderer.mock.calls.find(
(c) => c[0] === 'mcp_coordinator_notification_staged',
);
if (!stagedCallAck) throw new Error('No staged call found');
const { batchId } = stagedCallAck[1] as { batchId: string };
coordinator.ackNotification('coord-1', batchId);
const task = coordinator.getTask('task-1');
expect(task?.reviewNotificationQueued).toBe(false);
});
it('ack is idempotent', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Done ❯ '));
const stagedCallIdempotent = mockNotifyRenderer.mock.calls.find(
(c) => c[0] === 'mcp_coordinator_notification_staged',
);
if (!stagedCallIdempotent) throw new Error('No staged call found');
const { batchId } = stagedCallIdempotent[1] as { batchId: string };
expect(() => {
coordinator.ackNotification('coord-1', batchId);
coordinator.ackNotification('coord-1', batchId);
}).not.toThrow();
});
it('uses shortened delay for non-zero exit', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const agentId = getAgentId();
const exitHandler = getExitHandler();
exitHandler(agentId, { exitCode: 1 });
const stagedCallDelay = mockNotifyRenderer.mock.calls.find(
(c) => c[0] === 'mcp_coordinator_notification_staged',
);
if (!stagedCallDelay) throw new Error('No staged call found');
const { autoFireAt } = stagedCallDelay[1] as { autoFireAt: number };
expect(autoFireAt - Date.now()).toBeLessThanOrEqual(15_500);
expect(autoFireAt - Date.now()).toBeGreaterThan(9_000);
});
it('createTask rejects an unknown coordinator ID', async () => {
await expect(
coordinator.createTask({
name: 'orphan',
prompt: 'do',
coordinatorTaskId: 'missing-coord',
}),
).rejects.toThrow('Unknown coordinator: missing-coord');
});
it('clears staged notification when a notified task is closed', async () => {
vi.useFakeTimers();
try {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Done ❯ '));
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({ coordinatorTaskId: 'coord-1' }),
);
mockNotifyRenderer.mockClear();
await coordinator.closeTask('task-1');
expect(mockNotifyRenderer).toHaveBeenCalledWith('mcp_coordinator_notification_cleared', {
coordinatorTaskId: 'coord-1',
});
mockNotifyRenderer.mockClear();
vi.advanceTimersByTime(5 * 60_000);
expect(mockNotifyRenderer).not.toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.anything(),
);
} finally {
vi.useRealTimers();
}
});
});
// ─── signal_done tests ────────────────────────────────────────────────────────
describe('Coordinator signal_done', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
});
it('stages notification with 5s delay without requiring markPromptDelivered', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.signalDone('task-1');
const stagedCall = mockNotifyRenderer.mock.calls.find(
(c) => c[0] === 'mcp_coordinator_notification_staged',
);
if (!stagedCall) throw new Error('No staged call found');
const { autoFireAt } = stagedCall[1] as { autoFireAt: number };
expect(autoFireAt - Date.now()).toBeLessThanOrEqual(5_500);
expect(autoFireAt - Date.now()).toBeGreaterThan(4_000);
});
it('sends MCP_TaskStateSync to renderer', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.signalDone('task-1');
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_task_state_sync',
expect.objectContaining({
taskId: 'task-1',
signalDoneReceived: true,
}),
);
});
it('sets signalDoneAt on the task', async () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const before = new Date();
coordinator.signalDone('task-1');
const after = new Date();
const task = coordinator.getTask('task-1');
expect(task?.signalDoneAt).toBeDefined();
expect(task?.signalDoneAt?.getTime()).toBeGreaterThanOrEqual(before.getTime());
expect(task?.signalDoneAt?.getTime()).toBeLessThanOrEqual(after.getTime());
});
it('is a no-op for unknown taskId', () => {
coordinator.registerCoordinator('coord-1', 'proj-1');
expect(() => coordinator.signalDone('nonexistent-task')).not.toThrow();
expect(mockNotifyRenderer).not.toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.anything(),
);
});
});
// ─── spawn defaults / skipPermissions tests ───────────────────────────────────
describe('Coordinator sub-agent spawn settings', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
coordinator.registerCoordinator('coord-1', 'proj-1');
});
it('defaults to bare claude command', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
expect(mockSpawnAgent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ command: 'claude' }),
);
});
it('inherits coordinator command via setCoordinatorSpawnDefaults', async () => {
coordinator.setCoordinatorSpawnDefaults('coord-1', '/usr/local/bin/claude', []);
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
expect(mockSpawnAgent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ command: '/usr/local/bin/claude' }),
);
});
it('inherits coordinator base args (e.g. --model)', async () => {
coordinator.setCoordinatorSpawnDefaults('coord-1', 'claude', ['--model', 'claude-opus-4-7']);
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const spawnArgs = mockSpawnAgent.mock.calls[0][1].args as string[];
expect(spawnArgs).toContain('--model');
expect(spawnArgs).toContain('claude-opus-4-7');
});
it('adds --dangerously-skip-permissions when coordinator has propagateSkipPermissions', async () => {
// skipPermissions is inherited from coordinator state, not from createTask opts.
coordinator.registerCoordinator('coord-skip', 'proj-1', { skipPermissions: true });
await coordinator.createTask({
name: 'test',
prompt: 'do',
coordinatorTaskId: 'coord-skip',
});
const spawnArgs = mockSpawnAgent.mock.calls[0][1].args as string[];
expect(spawnArgs).toContain('--dangerously-skip-permissions');
});
it('does not add --dangerously-skip-permissions when coordinator does not propagate', async () => {
await coordinator.createTask({
name: 'test',
prompt: 'do',
coordinatorTaskId: 'coord-1',
});
const spawnArgs = mockSpawnAgent.mock.calls[0][1].args as string[];
expect(spawnArgs).not.toContain('--dangerously-skip-permissions');
});
it('inherited args do not include --dangerously-skip-permissions (handled separately)', async () => {
// skip_permissions_args should not be passed as agentArgs — only agentDef.args (base args)
coordinator.setCoordinatorSpawnDefaults('coord-1', 'claude', ['--model', 'claude-opus-4-7']);
await coordinator.createTask({
name: 'test',
prompt: 'do',
coordinatorTaskId: 'coord-1',
skipPermissions: false,
});
const spawnArgs = mockSpawnAgent.mock.calls[0][1].args as string[];
expect(spawnArgs).not.toContain('--dangerously-skip-permissions');
expect(spawnArgs).toContain('--model');
});
it('spawns sub-agent in the sub-task worktree path', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
expect(mockSpawnAgent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ cwd: '/tmp/test' }),
);
});
it('uses docker run (dockerMode: true) when dockerContainerName is set — sub-task gets its own container', async () => {
coordinator.setDockerContainerName('coord-1', 'my-container');
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
expect(mockSpawnAgent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
// Sub-task uses docker run (dockerMode: true), not docker exec
dockerMode: true,
// Command is the agent command, not 'docker'
command: 'claude',
// Args are the agent args (not docker exec wrapper)
args: expect.not.arrayContaining(['exec']),
}),
);
// Coordinator container name is NOT in the args (sub-task has its own container)
const spawnArgs = mockSpawnAgent.mock.calls[0][1].args as string[];
expect(spawnArgs).not.toContain('my-container');
});
it('does not use docker mode when dockerContainerName is null', async () => {
coordinator.setDockerContainerName('coord-1', null);
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
expect(mockSpawnAgent).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ command: 'claude' }),
);
const spawnCall = mockSpawnAgent.mock.calls[0][1] as { dockerMode?: boolean; args: string[] };
expect(spawnCall.dockerMode).toBeUndefined();
expect(spawnCall.args).not.toContain('docker');
});
it('docker run cwd is the sub-task worktree path, not the coordinator projectRoot', async () => {
coordinator.setDockerContainerName('coord-1', 'my-container');
// coordinator projectRoot is '/tmp/project', sub-task worktree is '/tmp/test'
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
// cwd (passed to pty.ts) is the sub-task worktree, not the coordinator's projectRoot
const spawnCall = mockSpawnAgent.mock.calls[0][1] as { cwd: string };
expect(spawnCall.cwd).toBe('/tmp/test');
expect(spawnCall.cwd).not.toBe('/tmp/project');
});
});
// ─── settings.local.json injection tests ─────────────────────────────────────
describe('Coordinator settings.local.json sub-task injection', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
coordinator.registerCoordinator('coord-1', 'proj-1');
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
});
it('writes settings.local.json with systemPrompt when file does not exist', async () => {
mockFsAccess.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const settingsWrite = mockAtomicWriteFile.mock.calls.find((c) =>
(c[0] as string).endsWith('settings.local.json'),
);
expect(settingsWrite).toBeDefined();
const written = JSON.parse(settingsWrite?.[1] as string);
expect(written.systemPrompt).toContain('signal_done');
expect(written.systemPrompt).toContain('sub-task-mode');
});
it('appends preamble to existing systemPrompt in settings.local.json', async () => {
mockFsAccess.mockResolvedValue(undefined);
mockFsReadFile.mockResolvedValue(JSON.stringify({ systemPrompt: 'existing prompt' }));
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const settingsWrite = mockAtomicWriteFile.mock.calls.find((c) =>
(c[0] as string).endsWith('settings.local.json'),
);
expect(settingsWrite).toBeDefined();
const written = JSON.parse(settingsWrite?.[1] as string);
expect(written.systemPrompt).toContain('existing prompt');
expect(written.systemPrompt).toContain('signal_done');
});
it('preserves other keys in existing settings.local.json', async () => {
mockFsAccess.mockResolvedValue(undefined);
mockFsReadFile.mockResolvedValue(JSON.stringify({ permissions: { allow: ['Bash'] } }));
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const settingsWrite = mockAtomicWriteFile.mock.calls.find((c) =>
(c[0] as string).endsWith('settings.local.json'),
);
expect(settingsWrite).toBeDefined();
const written = JSON.parse(settingsWrite?.[1] as string);
expect(written.permissions).toEqual({ allow: ['Bash'] });
expect(written.systemPrompt).toContain('signal_done');
});
it('does not restore settings.local.json on idle (no restore needed)', async () => {
mockFsAccess.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Working ❯ '));
const settingsWriteCallsAfterIdle = mockAtomicWriteFile.mock.calls.filter((c) =>
(c[0] as string).endsWith('settings.local.json'),
);
// Only the initial write; no re-write on idle
expect(settingsWriteCallsAfterIdle).toHaveLength(1);
});
it('does not write to CLAUDE.md', async () => {
mockFsAccess.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const claudeWrite = mockAtomicWriteFile.mock.calls.find((c) =>
(c[0] as string).endsWith('CLAUDE.md'),
);
expect(claudeWrite).toBeUndefined();
});
});
// ─── waitForIdle tests ────────────────────────────────────────────────────────
describe('Coordinator waitForIdle', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
coordinator.registerCoordinator('coord-1', 'proj-1');
});
afterEach(() => {
vi.useRealTimers();
});
it('rejects for unknown taskId', async () => {
await expect(coordinator.waitForIdle('nonexistent')).rejects.toThrow('Task not found');
});
it('resolves immediately when task is already idle', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Done ❯ '));
await expect(coordinator.waitForIdle('task-1')).resolves.toEqual({ reason: 'idle' });
});
it('resolves when agent outputs prompt', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const outputCb = getOutputCb();
const waitPromise = coordinator.waitForIdle('task-1');
outputCb(encode('working...'));
outputCb(encode('Done ❯ '));
await expect(waitPromise).resolves.toEqual({ reason: 'idle' });
});
it('resolves immediately when task is under human control', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.setTaskControl('task-1', 'human');
await expect(coordinator.waitForIdle('task-1')).resolves.toEqual({ reason: 'human_control' });
});
it('rejects control changes for unknown tasks', () => {
expect(() => coordinator.setTaskControl('missing-task', 'human')).toThrow(
'Task not found: missing-task',
);
});
it('rejects after timeout when task never idles', async () => {
vi.useFakeTimers();
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const waitPromise = coordinator.waitForIdle('task-1', 1_000);
vi.advanceTimersByTime(1_001);
await expect(waitPromise).rejects.toThrow('Timed out');
});
it('resolves when task exits (PTY exit fires idle resolvers)', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const agentId = getAgentId();
const exitHandler = getExitHandler();
const waitPromise = coordinator.waitForIdle('task-1');
exitHandler(agentId, { exitCode: 0 });
await expect(waitPromise).resolves.toEqual({ reason: 'exited' });
});
it('fires pending idle resolvers when control returns to coordinator', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
// The real scenario: task is running, coordinator calls waitForIdle, user takes control, coordinator returns
const waitPromise = coordinator.waitForIdle('task-1');
coordinator.setTaskControl('task-1', 'coordinator');
await expect(waitPromise).resolves.toEqual({ reason: 'idle' });
});
it('notifies coordinator when releasing control after waitForIdle was interrupted', async () => {
await coordinator.createTask({ name: 'my-task', prompt: 'do', coordinatorTaskId: 'coord-1' });
const waitPromise = coordinator.waitForIdle('task-1');
coordinator.setTaskControl('task-1', 'human');
await expect(waitPromise).resolves.toEqual({ reason: 'human_control' });
mockNotifyRenderer.mockClear();
coordinator.setTaskControl('task-1', 'coordinator');
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({
coordinatorTaskId: 'coord-1',
text: expect.stringContaining('"my-task" has been returned to coordinator control'),
}),
);
});
});
// ─── waitForSignalDone tests ──────────────────────────────────────────────────
describe('Coordinator waitForSignalDone', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
coordinator.registerCoordinator('coord-1', 'proj-1');
});
afterEach(() => {
vi.useRealTimers();
});
it('rejects for unknown coordinatorId', async () => {
await expect(coordinator.waitForSignalDone('nonexistent-coord')).rejects.toThrow(
'Coordinator not found',
);
});
it('resolves immediately with unconsumed signal if already signalled', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.signalDone('task-1');
await expect(coordinator.waitForSignalDone('coord-1')).resolves.toMatchObject({
taskId: 'task-1',
name: 'test',
remaining: 0,
status: expect.any(String),
signalDoneAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/),
});
});
it('resolves when signalDone is called, with remaining count', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const waitPromise = coordinator.waitForSignalDone('coord-1');
coordinator.signalDone('task-1');
await expect(waitPromise).resolves.toMatchObject({
taskId: 'task-1',
name: 'test',
remaining: 0,
status: expect.any(String),
signalDoneAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/),
});
});
it('resolves with timedOut:true when signal never arrives', async () => {
vi.useFakeTimers();
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
const waitPromise = coordinator.waitForSignalDone('coord-1', 1_000);
vi.advanceTimersByTime(1_001);
const result = await waitPromise;
expect(result.timedOut).toBe(true);
expect(result.remaining).toBeGreaterThanOrEqual(0);
});
it('returns remaining=1 when another task is still running', async () => {
mockCreateBackendTask
.mockResolvedValueOnce({ id: 'task-1', branch_name: 'task/a', worktree_path: '/tmp/a' })
.mockResolvedValueOnce({ id: 'task-2', branch_name: 'task/b', worktree_path: '/tmp/b' });
await coordinator.createTask({ name: 'task-a', prompt: 'do', coordinatorTaskId: 'coord-1' });
await coordinator.createTask({ name: 'task-b', prompt: 'do', coordinatorTaskId: 'coord-1' });
const waitPromise = coordinator.waitForSignalDone('coord-1');
coordinator.signalDone('task-1');
await expect(waitPromise).resolves.toMatchObject({
taskId: 'task-1',
name: 'task-a',
remaining: 1,
status: expect.any(String),
signalDoneAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/),
});
});
it('does not stage pending notifications while any signal_done wait is active', async () => {
mockCreateBackendTask
.mockResolvedValueOnce({ id: 'task-1', branch_name: 'task/a', worktree_path: '/tmp/a' })
.mockResolvedValueOnce({ id: 'task-2', branch_name: 'task/b', worktree_path: '/tmp/b' });
await coordinator.createTask({ name: 'task-a', prompt: 'do', coordinatorTaskId: 'coord-1' });
await coordinator.createTask({ name: 'task-b', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-2');
mockNotifyRenderer.mockClear();
const waitPromise = coordinator.waitForSignalDone('coord-1');
const task2OutputCb = mockSubscribeToAgent.mock.calls[1][1] as (encoded: string) => void;
task2OutputCb(encode('Done ❯ '));
expect(mockNotifyRenderer).not.toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.anything(),
);
coordinator.signalDone('task-1');
await expect(waitPromise).resolves.toMatchObject({ taskId: 'task-1' });
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({
coordinatorTaskId: 'coord-1',
text: expect.stringContaining('"task-b" ready for review'),
}),
);
});
it('clears an already staged notification when a signal_done wait starts', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.markPromptDelivered('task-1');
const outputCb = getOutputCb();
outputCb(encode('Done ❯ '));
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({ coordinatorTaskId: 'coord-1' }),
);
mockNotifyRenderer.mockClear();
const waitPromise = coordinator.waitForSignalDone('coord-1');
expect(mockNotifyRenderer).toHaveBeenCalledWith('mcp_coordinator_notification_cleared', {
coordinatorTaskId: 'coord-1',
});
coordinator.signalDone('task-1');
await expect(waitPromise).resolves.toMatchObject({ taskId: 'task-1' });
expect(mockNotifyRenderer).not.toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.anything(),
);
});
});
// ─── sendPrompt tests ─────────────────────────────────────────────────────────
describe('Coordinator sendPrompt', () => {
let coordinator: InstanceType<typeof Coordinator>;
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(false);
mockCreateBackendTask.mockResolvedValue({
id: 'task-1',
branch_name: 'task/test',
worktree_path: '/tmp/test',
});
coordinator = new Coordinator();
coordinator.setWindow(mockWin);
coordinator.setDefaultProject('proj-1', '/tmp/project');
coordinator.registerCoordinator('coord-1', 'proj-1');
});
it('rejects for unknown taskId', async () => {
await expect(coordinator.sendPrompt('nonexistent', 'hello')).rejects.toThrow('Task not found');
});
it('rejects when task is under human control', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.setTaskControl('task-1', 'human');
await expect(coordinator.sendPrompt('task-1', 'hello')).rejects.toThrow('human control');
});
it('notifies coordinator when control returns after a blocked send_prompt', async () => {
await coordinator.createTask({ name: 'my-task', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.setTaskControl('task-1', 'human');
await expect(coordinator.sendPrompt('task-1', 'hello')).rejects.toThrow('human control');
mockNotifyRenderer.mockClear();
coordinator.setTaskControl('task-1', 'coordinator');
expect(mockNotifyRenderer).toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.objectContaining({
coordinatorTaskId: 'coord-1',
text: expect.stringContaining('"my-task" has been returned to coordinator control'),
}),
);
});
it('does not notify coordinator when control returns without a prior blocked send_prompt', async () => {
await coordinator.createTask({ name: 'my-task', prompt: 'do', coordinatorTaskId: 'coord-1' });
coordinator.setTaskControl('task-1', 'human');
mockNotifyRenderer.mockClear();
coordinator.setTaskControl('task-1', 'coordinator');
expect(mockNotifyRenderer).not.toHaveBeenCalledWith(
'mcp_coordinator_notification_staged',
expect.anything(),
);
});
it('syncs frontend done/review flags back to running when sending a new prompt', async () => {
await coordinator.createTask({ name: 'test', prompt: 'do', coordinatorTaskId: 'coord-1' });
mockNotifyRenderer.mockClear();
await coordinator.sendPrompt('task-1', 'new work');
expect(mockNotifyRenderer).toHaveBeenCalledWith('mcp_task_state_sync', {
taskId: 'task-1',
signalDoneReceived: false,
signalDoneAt: null,
signalDoneConsumed: false,
needsReview: false,
});
});
});
// ─── deregisterCoordinator tests ──────────────────────────────────────────────
describe('Coordinator deregisterCoordinator', () => {
let coordinator: InstanceType<typeof Coordinator>;