-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathcoordinator.ts
More file actions
1778 lines (1639 loc) · 67.2 KB
/
Copy pathcoordinator.ts
File metadata and controls
1778 lines (1639 loc) · 67.2 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
// Main-process coordinator for managing sub-agent tasks.
// Manages task lifecycle independently of the SolidJS renderer,
// using existing backend primitives (pty, git, tasks).
import { randomUUID, randomBytes } from 'crypto';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { unlinkSync, readFileSync, existsSync } from 'fs';
import {
readFile as fsReadFile,
writeFile as fsWriteFile,
unlink as fsUnlink,
access as fsAccess,
mkdir as fsMkdir,
} from 'fs/promises';
import { join, dirname } from 'path';
import os from 'os';
import { getSubTaskMcpConfigPath } from './config.js';
import { buildMcpLaunchArgs } from './agent-args.js';
import { validateBranchName } from './validation.js';
import { atomicWriteFileSync, atomicWriteFile } from './atomic.js';
import { ReplayCache } from './replay-cache.js';
import {
detectPreambleFiles,
filterDiffSections,
buildNormalizedPreambleFileDiff,
stripPreambleFromBranch,
} from './preamble.js';
const execAsync = promisify(execFile);
import type { BrowserWindow } from 'electron';
import { createTask as createBackendTask, deleteTask } from '../ipc/tasks.js';
import { getSkipPermissionsArgs } from '../ipc/agents.js';
import {
spawnAgent,
writeToAgent,
killAgent,
subscribeToAgent,
unsubscribeFromAgent,
getAgentScrollback,
onPtyEvent,
} from '../ipc/pty.js';
import {
getChangedFiles,
getAllFileDiffs,
getDiffBaseSha,
mergeTask as gitMergeTask,
} from '../ipc/git.js';
import { stripAnsi, chunkContainsAgentPrompt } from './prompt-detect.js';
import { SUB_TASK_PREAMBLE } from './sub-task-preamble.js';
import { warn as logWarn } from '../log.js';
import type {
CoordinatedTask,
PendingNotification,
CoordinatorState,
ApiTaskSummary,
ApiTaskDetail,
ApiDiffResult,
WaitForSignalDoneResult,
} from './types.js';
import { IPC } from '../ipc/channels.js';
const DEFAULT_WAIT_TIMEOUT_MS = 300_000; // 5 minutes
const PROMPT_WRITE_DELAY_MS = 50;
const REST_COORDINATOR_SENTINEL = 'api';
export class Coordinator {
private tasks = new Map<string, CoordinatedTask>();
private tailBuffers = new Map<string, string>();
private idleResolvers = new Map<
string,
Array<(result: { reason: 'idle' | 'human_control' | 'exited' | 'removed' }) => void>
>();
private anySignalResolvers = new Map<string, Array<(result: WaitForSignalDoneResult) => void>>();
private subscribers = new Map<string, (encoded: string) => void>();
private decoders = new Map<string, TextDecoder>();
private controlMap = new Map<string, 'coordinator' | 'human'>();
private blockedByHumanControl = new Set<string>();
private interruptedByHumanControl = new Set<string>();
private closingTaskIds = new Set<string>();
private activeSignalWaitCounts = new Map<string, number>();
private recentlyDelivered = new ReplayCache<WaitForSignalDoneResult>();
private win: BrowserWindow | null = null;
private projectRoot: string | null = null;
private projectId: string | null = null;
private defaultCoordinatorTaskId: string | null = null;
private coordinatorSpawnDefaults: { command: string; args: string[] } = {
command: 'claude',
args: [],
};
private coordinators = new Map<string, CoordinatorState>();
private notificationDelayMs = 30_000;
private readonly COORDINATOR_RESTAMP_DELAY_MS = 5 * 60_000;
private readonly MAX_ACKED_BATCH_IDS = 64;
// Serializes concurrent preamble writes to the same file path.
private preambleWriteQueue = new Map<string, Promise<void>>();
constructor() {
// Listen for PTY exits to update task status when agents are killed externally
// (e.g., user closes a child task from the UI).
// The singleton guard in enableCoordinatorMode (if (coordinator) return) ensures
// this constructor is called at most once per app lifetime; no teardown needed.
onPtyEvent('exit', (agentId, data) => {
for (const task of this.tasks.values()) {
if (task.agentId === agentId) {
const { exitCode } = (data ?? {}) as { exitCode?: number };
task.status = 'exited';
task.exitCode = exitCode ?? null;
// Resolve any idle waiters so they don't hang
const resolvers = this.idleResolvers.get(task.id);
if (resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'exited' });
this.idleResolvers.delete(task.id);
}
// Resolve any signal waiters so wait_for_signal_done doesn't hang
// when the last sub-task exits without calling signal_done.
const coordinatorId = task.coordinatorTaskId;
const anyResolvers = this.anySignalResolvers.get(coordinatorId);
const firstAnyResolver = anyResolvers?.length ? anyResolvers.shift() : undefined;
if (firstAnyResolver) {
// Suppress the exit notification — the signal waiter receives the
// exit info as its return value (mirrors the signalDone path).
this.suppressPendingNotificationForTask(task);
task.reviewNotificationQueued = true;
const remaining = this.countRemaining(coordinatorId);
firstAnyResolver({
taskId: task.id,
name: task.name,
status: 'exited',
signalDoneAt: new Date().toISOString(),
remaining,
});
this.finishSignalWait(coordinatorId);
}
if (this.closingTaskIds.has(task.id)) break;
this.maybeQueueReviewNotification(task, 'exited', exitCode ?? null);
break;
}
}
});
// Re-subscribe our output callback when the renderer reattaches to, or explicitly
// replaces, a managed agent. Without this, our outputCb is lost and we can never
// detect idle for that sub-task.
onPtyEvent('spawn', (agentId) => {
const outputCb = this.subscribers.get(agentId);
if (!outputCb) return; // not a coordinated agent, or initial spawn (not yet subscribed)
this.tailBuffers.set(agentId, ''); // discard stale data from the killed PTY
for (const task of this.tasks.values()) {
if (task.agentId === agentId && task.status === 'exited') {
task.status = 'running';
task.exitCode = null;
break;
}
}
subscribeToAgent(agentId, outputCb);
});
}
setTaskControl(taskId: string, who: 'coordinator' | 'human'): void {
if (!this.tasks.has(taskId)) {
throw new Error(`Task not found: ${taskId}`);
}
this.controlMap.set(taskId, who);
if (who === 'human') {
// Resolve any pending idle waiters immediately — human has taken over
const resolvers = this.idleResolvers.get(taskId);
if (resolvers?.length) {
this.interruptedByHumanControl.add(taskId);
for (const resolve of resolvers) resolve({ reason: 'human_control' });
this.idleResolvers.delete(taskId);
}
}
if (who === 'coordinator') {
// Fire any idle resolvers queued while human had control
const resolvers = this.idleResolvers.get(taskId);
if (resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'idle' });
this.idleResolvers.delete(taskId);
}
// Notify coordinator if it tried to send a prompt or had an idle wait interrupted.
if (this.blockedByHumanControl.has(taskId) || this.interruptedByHumanControl.has(taskId)) {
this.blockedByHumanControl.delete(taskId);
this.interruptedByHumanControl.delete(taskId);
const task = this.tasks.get(taskId);
const coordinator = task ? this.coordinators.get(task.coordinatorTaskId) : null;
if (task && coordinator) {
this.notifyRenderer(IPC.MCP_CoordinatorNotificationStaged, {
coordinatorTaskId: coordinator.taskId,
batchId: randomUUID(),
notificationIds: [],
text: `[Control update]\nTask "${task.name}" has been returned to coordinator control. You may now resume sending prompts to it.`,
autoFireAt: Date.now() + 2_000,
});
}
}
}
}
setWindow(win: BrowserWindow): void {
this.win = win;
}
setNotificationDelayMs(ms: number): void {
this.notificationDelayMs = Math.max(5_000, Math.min(300_000, ms));
}
setDefaultProject(projectId: string, projectRoot: string, coordinatorTaskId?: string): void {
this.projectId = projectId;
this.projectRoot = projectRoot;
if (coordinatorTaskId) this.defaultCoordinatorTaskId = coordinatorTaskId;
}
setMCPServerInfo(
coordinatorTaskId: string,
serverUrl: string,
token: string,
subtaskToken: string,
serverPath: string,
): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.mcpServerInfo = { serverUrl, token, subtaskToken, serverPath };
state.lifecycle = 'ready';
}
// Rewrite config files only for sub-tasks owned by this coordinator so a
// second coordinator starting up does not overwrite the first's task configs.
for (const task of this.tasks.values()) {
if (task.coordinatorTaskId !== coordinatorTaskId) continue;
if (!task.mcpConfigPath) continue;
// Preserve existing doneToken; generate a fresh one if not yet set (e.g. older persisted task).
if (!task.doneToken) task.doneToken = randomBytes(24).toString('base64url');
const mcpConfig = {
mcpServers: {
'parallel-code': {
type: 'stdio' as const,
command: 'node',
args: [serverPath, '--url', serverUrl, '--task-id', task.id],
env: {
PARALLEL_CODE_MCP_TOKEN: subtaskToken,
PARALLEL_CODE_MCP_DONE_TOKEN: task.doneToken,
},
},
},
};
atomicWriteFileSync(task.mcpConfigPath, JSON.stringify(mcpConfig, null, 2), { mode: 0o600 });
}
}
setCoordinatorSpawnDefaults(coordinatorTaskId: string, command: string, args: string[]): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.spawnDefaults = { command, args };
}
// Also update global fallback.
this.coordinatorSpawnDefaults = { command, args };
}
setDockerContainerName(coordinatorTaskId: string, name: string | null): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.dockerContainerName = name;
}
}
setDockerImage(coordinatorTaskId: string, image: string | null): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.dockerImage = image;
}
}
private maybeQueueReviewNotification(
task: CoordinatedTask,
state: 'idle' | 'exited',
exitCode: number | null,
delayOverrideMs?: number,
): void {
// Always notify for exits — a task killed before prompt delivery still needs to be
// reported so the coordinator doesn't think it's still running.
if (!task.assignedPromptDelivered && state !== 'exited') return;
const coordinator = this.coordinators.get(task.coordinatorTaskId);
if (!coordinator) {
if (task.reviewNotificationQueued) return;
task.reviewNotificationQueued = true;
this.notifyRenderer(IPC.MCP_CoordinatorOrphanedNotification, {
subTaskId: task.id,
notificationId: randomUUID(),
state,
text: `"${task.name}" ${state === 'exited' ? `terminated (exit ${exitCode})` : 'ready for review'} — branch: ${task.branchName}`,
});
return;
}
if (task.reviewNotificationQueued && state === 'exited') {
const existing = coordinator.pendingNotifications.find((n) => n.taskId === task.id);
if (existing && existing.state === 'idle') {
existing.state = 'exited';
existing.exitCode = exitCode;
this.stageBatch(coordinator);
return;
}
return;
}
if (task.reviewNotificationQueued) return;
task.reviewNotificationQueued = true;
const notification: PendingNotification = {
id: randomUUID(),
taskId: task.id,
taskName: task.name,
branchName: task.branchName,
state,
exitCode,
completedAt: new Date(),
};
coordinator.pendingNotifications.push(notification);
this.stageBatch(coordinator, delayOverrideMs);
}
private stageBatch(coordinator: CoordinatorState, delayOverrideMs?: number): void {
const pending = coordinator.pendingNotifications;
if (pending.length === 0) return;
if (this.hasActiveSignalWaiter(coordinator.taskId)) {
logWarn('coordinator.notification', 'stageBatch skipped', {
coordinatorTaskId: coordinator.taskId,
reason: 'active_signal_wait',
activeWaitCount: this.activeSignalWaitCounts.get(coordinator.taskId) ?? 0,
pendingTaskIds: this.pendingNotificationTaskIds(coordinator),
});
if (coordinator.restageTimer) {
clearTimeout(coordinator.restageTimer);
coordinator.restageTimer = null;
}
return;
}
// Clear any previously staged batches — they are superseded by this new batch.
// Leaving old entries causes stagedBatches to grow unboundedly and makes
// deregisterCoordinator incorrectly believe notifications are still pending.
coordinator.stagedBatches.clear();
const batchId = randomUUID();
const notificationIds = pending.map((n) => n.id);
coordinator.stagedBatches.set(batchId, notificationIds);
const anyNonZero = pending.some((n) => n.exitCode !== null && n.exitCode !== 0);
const defaultDelay = anyNonZero
? Math.max(10_000, this.notificationDelayMs / 4)
: this.notificationDelayMs;
const delay = delayOverrideMs ?? defaultDelay;
const autoFireAt = Date.now() + delay;
const text = this.formatNotificationText(pending);
logWarn('coordinator.notification', 'stageBatch emitted', {
coordinatorTaskId: coordinator.taskId,
batchId,
notificationIds,
pendingTaskIds: this.pendingNotificationTaskIds(coordinator),
delayMs: delay,
autoFireAt,
});
this.notifyRenderer(IPC.MCP_CoordinatorNotificationStaged, {
coordinatorTaskId: coordinator.taskId,
batchId,
notificationIds,
text,
autoFireAt,
});
if (coordinator.restageTimer) clearTimeout(coordinator.restageTimer);
coordinator.restageTimer = setTimeout(() => {
coordinator.restageTimer = null;
if (coordinator.pendingNotifications.length > 0) {
this.stageBatch(coordinator);
}
}, this.COORDINATOR_RESTAMP_DELAY_MS);
}
private formatNotificationText(pending: PendingNotification[]): string {
const header = `[Sub-task update — ${pending.length} task(s) completed]`;
const lines = pending.map((n) => {
const status = n.state === 'exited' ? `terminated (exit ${n.exitCode})` : 'ready for review';
const line = `- "${n.taskName}" ${status} — branch: ${n.branchName}`;
const warn =
n.exitCode !== null && n.exitCode !== 0
? '\n ⚠️ Non-zero exit — may need attention. Consider spawning a follow-up agent.'
: '';
return line + warn;
});
const footer =
"Please review each completed task: check its diff, confirm the work looks correct, then commit and merge what's ready. If there are items remaining on the backlog, spawn the next batch.";
return [header, '', ...lines, '', footer].join('\n');
}
async createTask(opts: {
name: string;
prompt?: string;
coordinatorTaskId: string;
projectId?: string;
projectRoot?: string;
agentCommand?: string;
agentArgs?: string[];
skipPermissions?: boolean;
baseBranch?: string;
}): Promise<CoordinatedTask> {
const coordinatorId =
opts.coordinatorTaskId !== REST_COORDINATOR_SENTINEL
? opts.coordinatorTaskId
: this.defaultCoordinatorTaskId;
if (!coordinatorId) {
throw new Error(
'No coordinator task registered yet. Ensure the coordinator task is fully initialized before calling create_task.',
);
}
const coordinatorState = this.coordinators.get(coordinatorId);
if (!coordinatorState) {
throw new Error(
`Unknown coordinator: ${coordinatorId}. Ensure the coordinator task is registered before creating sub-tasks.`,
);
}
if (opts.baseBranch !== undefined) {
validateBranchName(opts.baseBranch, 'baseBranch');
}
const root = opts.projectRoot ?? coordinatorState.projectRoot ?? this.projectRoot;
const projId = opts.projectId ?? coordinatorState.projectId ?? this.projectId;
if (!root || !projId) throw new Error('No project configured for coordinator');
// Create worktree + branch via existing backend
const result = await createBackendTask(
opts.name,
root,
['.claude', 'node_modules'],
'task',
opts.baseBranch,
);
// Re-check after async gap — deregisterCoordinator may have run while we awaited.
if (!this.coordinators.has(coordinatorId)) {
// Best-effort cleanup of the worktree we just created.
deleteTask({
agentIds: [],
branchName: result.branch_name,
deleteBranch: true,
projectRoot: root,
}).catch((err) => {
console.warn('Failed to clean up race-condition worktree:', err);
this.notifyRenderer(IPC.MCP_TaskCleanupFailed, {
taskId: result.id,
error: err instanceof Error ? err.message : String(err),
});
});
throw new Error(`Coordinator ${coordinatorId} was deregistered during task creation`);
}
const agentId = randomUUID();
const task: CoordinatedTask = {
id: result.id,
name: opts.name,
projectId: projId,
projectRoot: root,
branchName: result.branch_name,
baseBranch: opts.baseBranch,
worktreePath: result.worktree_path,
agentId,
coordinatorTaskId: coordinatorId,
status: 'creating',
exitCode: null,
dockerContainerName: this.coordinators.get(coordinatorId)?.dockerContainerName ?? null,
};
this.tasks.set(task.id, task);
this.tailBuffers.set(agentId, '');
// Subscribe to PTY output for prompt detection
const decoder = new TextDecoder();
this.decoders.set(agentId, decoder);
const outputCb = (encoded: string) => {
const bytes = Buffer.from(encoded, 'base64');
const text = (this.decoders.get(agentId) ?? new TextDecoder()).decode(bytes, {
stream: true,
});
const prev = this.tailBuffers.get(agentId) ?? '';
const combined = prev + text;
this.tailBuffers.set(
agentId,
combined.length > 4096 ? combined.slice(combined.length - 4096) : combined,
);
// Check for agent prompt
const stripped = stripAnsi(combined)
// eslint-disable-next-line no-control-regex
.replace(/[\x00-\x1f\x7f]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (chunkContainsAgentPrompt(stripped)) {
if (task.status === 'running') {
task.status = 'idle';
this.maybeQueueReviewNotification(task, 'idle', null);
}
// Resolve any waiting promises
const resolvers = this.idleResolvers.get(task.id);
if (resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'idle' });
this.idleResolvers.delete(task.id);
}
} else if (task.status === 'idle') {
task.status = 'running';
}
};
this.subscribers.set(agentId, outputCb);
// Spawn the agent process
if (!this.win) throw new Error('No window set on coordinator');
const agentCmd = (opts.agentCommand ?? coordinatorState.spawnDefaults.command).toLowerCase();
const preamble = `<sub-task-mode>\nThese rules override all skills and hooks:\n- When your work is complete, call the \`signal_done\` MCP tool. That is the finish line — do NOT use finishing-a-development-branch or offer merge/PR options.\n- Asking questions is fine when requirements are unclear or an action is risky.\n</sub-task-mode>`;
// Declared here so the catch block can restore preamble files on failure.
let preambleFilePath: string | undefined;
let preambleFileOriginalContent: string | null = null;
const dockerContainerName =
this.coordinators.get(task.coordinatorTaskId)?.dockerContainerName ?? null;
let subTaskMcpConfigPath: string | undefined;
try {
// Inject sub-task instructions via agent-specific mechanism.
// Inside try so preamble-write failures are cleaned up by the catch block.
// Serialized per file path to prevent races when multiple tasks target the same path.
const injectPreamble = async (filePath: string): Promise<void> => {
const prior = this.preambleWriteQueue.get(filePath) ?? Promise.resolve();
const next = prior.then(async () => {
let existing = '';
try {
await fsAccess(filePath);
existing = await fsReadFile(filePath, 'utf8');
preambleFileOriginalContent = existing;
} catch {
/* file does not exist */
}
await atomicWriteFile(filePath, existing ? `${existing}\n\n${preamble}` : preamble);
});
this.preambleWriteQueue.set(
filePath,
next
.catch(() => {})
.then(() => {
if (this.preambleWriteQueue.get(filePath) === next) {
this.preambleWriteQueue.delete(filePath);
}
}),
);
await next;
};
if (agentCmd.includes('codex') || agentCmd.includes('opencode')) {
const agentsPath = join(result.worktree_path, 'AGENTS.md');
preambleFilePath = agentsPath;
await injectPreamble(agentsPath);
} else if (agentCmd.includes('gemini')) {
const geminiPath = join(result.worktree_path, 'GEMINI.md');
preambleFilePath = geminiPath;
await injectPreamble(geminiPath);
} else if (agentCmd.includes('copilot')) {
const agentMdPath = join(result.worktree_path, '.agent.md');
preambleFilePath = agentMdPath;
await injectPreamble(agentMdPath);
} else {
// Claude and fallback: settings.local.json (gitignored, no restore needed)
const settingsDir = join(result.worktree_path, '.claude');
const settingsPath = join(settingsDir, 'settings.local.json');
await fsMkdir(settingsDir, { recursive: true });
const prior = this.preambleWriteQueue.get(settingsPath) ?? Promise.resolve();
const next = prior.then(async () => {
let existingSettings: Record<string, unknown> = {};
try {
await fsAccess(settingsPath);
existingSettings = JSON.parse(await fsReadFile(settingsPath, 'utf8'));
} catch {
/* ignore */
}
existingSettings.systemPrompt = existingSettings.systemPrompt
? `${existingSettings.systemPrompt}\n\n${preamble}`
: preamble;
await atomicWriteFile(settingsPath, JSON.stringify(existingSettings, null, 2));
});
this.preambleWriteQueue.set(
settingsPath,
next
.catch(() => {})
.then(() => {
if (this.preambleWriteQueue.get(settingsPath) === next) {
this.preambleWriteQueue.delete(settingsPath);
}
}),
);
await next;
}
task.preambleFileExistedBefore = preambleFileOriginalContent !== null;
// Write a per-sub-task MCP config so the agent can call signal_done.
// In Docker mode, write to the coordinator's .parallel-code/ dir (which IS the explicitly
// mounted volume) rather than the sub-task worktree (which may not be in the container).
// Always pass explicit MCP launch args so agents don't rely on auto-discovery.
const mcpServerInfoForTask = coordinatorState.mcpServerInfo;
let subTaskMcpConfig: Parameters<typeof buildMcpLaunchArgs>[2] | undefined;
if (mcpServerInfoForTask) {
const { serverUrl, subtaskToken, serverPath } = mcpServerInfoForTask;
const doneToken = randomBytes(24).toString('base64url');
task.doneToken = doneToken;
const mcpConfig = {
mcpServers: {
'parallel-code': {
type: 'stdio' as const,
command: 'node',
args: [serverPath, '--url', serverUrl, '--task-id', task.id],
env: {
PARALLEL_CODE_MCP_TOKEN: subtaskToken,
PARALLEL_CODE_MCP_DONE_TOKEN: doneToken,
},
},
},
};
subTaskMcpConfig = mcpConfig;
const configPath = getSubTaskMcpConfigPath(dockerContainerName, serverPath, task.id);
await atomicWriteFile(configPath, JSON.stringify(mcpConfig, null, 2), { mode: 0o600 });
subTaskMcpConfigPath = configPath;
task.mcpConfigPath = configPath;
}
const agentCommand = opts.agentCommand ?? coordinatorState.spawnDefaults.command;
const agentArgs = opts.agentArgs ?? coordinatorState.spawnDefaults.args;
const baseArgs = [
...agentArgs,
...(coordinatorState.propagateSkipPermissions ? getSkipPermissionsArgs(agentCommand) : []),
];
const mcpArgs = subTaskMcpConfig
? buildMcpLaunchArgs(agentCommand, subTaskMcpConfigPath, subTaskMcpConfig)
: [];
const agentFinalArgs = [...baseArgs, ...mcpArgs];
// In Docker coordinator mode, each sub-task gets its own `docker run` container
// so HOME directories are isolated and cleanup is clean (`docker stop` on the
// sub-task container, rather than killing processes inside the coordinator).
const channelId = randomUUID();
spawnAgent(this.win, {
taskId: task.id,
agentId,
command: agentCommand,
args: agentFinalArgs,
cwd: result.worktree_path,
env: {},
cols: 120,
rows: 40,
...(dockerContainerName
? {
dockerMode: true,
dockerImage: coordinatorState.dockerImage ?? undefined,
// Mount parent dir so the sub-task can reach the coordinator's
// .parallel-code/ dir (which holds the per-sub-task MCP config).
// resolveWorktreeGitDirMount adds the main .git dir mount.
dockerMountWorktreeParent: true,
}
: {}),
onOutput: { __CHANNEL_ID__: channelId },
});
// Subscribe for output monitoring
subscribeToAgent(agentId, outputCb);
task.status = 'running';
// Check scrollback in case the prompt was emitted before we subscribed
const scrollback = getAgentScrollback(agentId);
if (scrollback) {
const decoded = Buffer.from(scrollback, 'base64').toString('utf8');
const stripped = stripAnsi(decoded)
// eslint-disable-next-line no-control-regex
.replace(/[\x00-\x1f\x7f]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (chunkContainsAgentPrompt(stripped)) {
task.status = 'idle';
this.maybeQueueReviewNotification(task, 'idle', null);
}
}
// Notify renderer with the prompt — the renderer sets it as initialPrompt
// on the task, and PromptInput auto-delivers it using the same code path
// as manually created tasks (stability checks, quiescence detection, etc.)
// For renderer storage: only store the inner agent args (without docker wrapper).
// TaskAITerminal re-wraps with the coordinator's current container name at respawn time
// so stale container names don't get baked into persisted state.
const notifyAgentArgs = agentArgs;
this.notifyRenderer(IPC.MCP_TaskCreated, {
taskId: task.id,
name: task.name,
projectId: task.projectId,
branchName: task.branchName,
worktreePath: task.worktreePath,
agentId: task.agentId,
coordinatorTaskId: task.coordinatorTaskId,
prompt: opts.prompt ? SUB_TASK_PREAMBLE + opts.prompt : opts.prompt,
mcpConfigPath: subTaskMcpConfigPath,
preambleFileExistedBefore: task.preambleFileExistedBefore,
agentCommand: agentCommand,
agentArgs: notifyAgentArgs,
skipPermissions: coordinatorState.propagateSkipPermissions,
});
return task;
} catch (err) {
// Restore injected preamble file before cleaning up the worktree.
// Must await — fire-and-forget could race with cleanupTask removing the worktree.
if (preambleFilePath !== undefined) {
try {
if (preambleFileOriginalContent !== null) {
await fsWriteFile(preambleFilePath, preambleFileOriginalContent);
} else {
await fsUnlink(preambleFilePath);
}
} catch {
/* ignore — worktree cleanup follows */
}
}
// Best-effort cleanup: kill agent, remove worktree/branch, clear in-memory state.
// cleanupTask handles all of this; the task is still in this.tasks so it can find it.
// Also delete the MCP config if it was written but not yet stored on task.mcpConfigPath.
if (subTaskMcpConfigPath && !task.mcpConfigPath) {
fsUnlink(subTaskMcpConfigPath).catch(() => {});
}
this.cleanupTask(task.id).catch(() => {});
throw err;
}
}
listTasks(): ApiTaskSummary[] {
return Array.from(this.tasks.values()).map((t) => ({
id: t.id,
name: t.name,
branchName: t.branchName,
status: t.status,
coordinatorTaskId: t.coordinatorTaskId,
signalDoneAt: t.signalDoneAt?.toISOString(),
}));
}
getTaskStatus(taskId: string): ApiTaskDetail | null {
const task = this.tasks.get(taskId);
if (!task) return null;
return {
id: task.id,
name: task.name,
branchName: task.branchName,
worktreePath: task.worktreePath,
projectId: task.projectId,
agentId: task.agentId,
status: task.status,
coordinatorTaskId: task.coordinatorTaskId,
exitCode: task.exitCode,
pendingPrompt: task.pendingPrompt,
signalDoneAt: task.signalDoneAt?.toISOString(),
};
}
getTaskDoneToken(taskId: string): string | null {
return this.tasks.get(taskId)?.doneToken ?? null;
}
async sendPrompt(taskId: string, prompt: string): Promise<void> {
const task = this.tasks.get(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
if (this.controlMap.get(taskId) === 'human') {
this.blockedByHumanControl.add(taskId);
throw new Error(
'Task is under human control. Return control to coordinator before sending prompts.',
);
}
// Send text then Enter separately (like the frontend does)
writeToAgent(task.agentId, prompt);
await new Promise((r) => setTimeout(r, PROMPT_WRITE_DELAY_MS));
writeToAgent(task.agentId, '\r');
task.status = 'running';
task.pendingPrompt = undefined;
task.signalDoneAt = undefined;
this.notifyRenderer(IPC.MCP_TaskStateSync, {
taskId,
signalDoneReceived: false,
signalDoneAt: null,
signalDoneConsumed: false,
needsReview: false,
});
}
waitForIdle(
taskId: string,
timeoutMs?: number,
): Promise<{ reason: 'idle' | 'human_control' | 'exited' | 'removed' }> {
return this.waitForIdleInternal(taskId, timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS);
}
private waitForIdleInternal(
taskId: string,
timeoutMs: number,
): Promise<{ reason: 'idle' | 'human_control' | 'exited' | 'removed' }> {
const task = this.tasks.get(taskId);
if (!task) return Promise.reject(new Error(`Task not found: ${taskId}`));
if (this.controlMap.get(taskId) === 'human') {
this.interruptedByHumanControl.add(taskId);
return Promise.resolve({ reason: 'human_control' }); // resolve immediately — caller gets control-change event instead
}
if (task.status === 'exited') return Promise.resolve({ reason: 'exited' });
if (task.status === 'idle') return Promise.resolve({ reason: 'idle' });
return new Promise((resolve, reject) => {
const timerRef = { value: undefined as ReturnType<typeof setTimeout> | undefined };
const wrappedResolve = (result: {
reason: 'idle' | 'human_control' | 'exited' | 'removed';
}) => {
if (timerRef.value !== undefined) clearTimeout(timerRef.value);
resolve(result);
};
timerRef.value = setTimeout(() => {
const resolvers = this.idleResolvers.get(taskId);
if (resolvers) {
const idx = resolvers.indexOf(wrappedResolve);
if (idx >= 0) resolvers.splice(idx, 1);
}
reject(new Error(`Timed out waiting for task ${taskId} to become idle`));
}, timeoutMs);
let resolvers = this.idleResolvers.get(taskId);
if (!resolvers) {
resolvers = [];
this.idleResolvers.set(taskId, resolvers);
}
resolvers.push(wrappedResolve);
});
}
async getTaskDiff(taskId: string): Promise<ApiDiffResult> {
const task = this.tasks.get(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
// Compute baseSha first so detectDiffBase/pinHead results are cached.
// getChangedFiles and getAllFileDiffs internally call the same helpers;
// running all three concurrently causes three simultaneous cache misses.
const baseSha = await getDiffBaseSha(task.worktreePath, task.baseBranch);
const [files, diff] = await Promise.all([
getChangedFiles(task.worktreePath, task.baseBranch),
getAllFileDiffs(task.worktreePath, task.baseBranch),
]);
// For preamble-bearing files: strip the injected block and show only real sub-task edits.
// Files with no real changes beyond the preamble are excluded entirely.
// Files with real changes (before or after the preamble block) include a normalized diff.
const preambleFiles = await detectPreambleFiles(task.worktreePath);
let filteredFiles = files;
let filteredDiff = diff;
if (preambleFiles.size > 0) {
// Drop preamble file sections from the raw diff; we'll add normalized sections below.
filteredDiff = filterDiffSections(diff, preambleFiles);
// For each preamble file, generate a diff that excludes the injected block.
const normalizedSections = await Promise.all(
[...preambleFiles].map((f) =>
buildNormalizedPreambleFileDiff(f, task.worktreePath, baseSha),
),
);
const preambleFilesWithChanges = new Set<string>();
for (let i = 0; i < [...preambleFiles].length; i++) {
if (normalizedSections[i]) preambleFilesWithChanges.add([...preambleFiles][i]);
}
filteredDiff += normalizedSections.filter(Boolean).join('');
// Files list: exclude preamble-only files, keep files with real changes.
filteredFiles = files.filter(
(f) => !preambleFiles.has(f.path) || preambleFilesWithChanges.has(f.path),
);
}
const MAX_DIFF_BYTES = 50_000;
if (filteredDiff.length > MAX_DIFF_BYTES) {
return {
files: filteredFiles,
diff: filteredDiff.slice(0, MAX_DIFF_BYTES) + '\n... (diff truncated)',
truncated: true,
originalSizeBytes: filteredDiff.length,
};
}
return { files: filteredFiles, diff: filteredDiff };
}
getTaskOutput(taskId: string): string {
const task = this.tasks.get(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
// Try scrollback buffer first, fall back to tail buffer
const scrollback = getAgentScrollback(task.agentId);
if (scrollback) {
const decoded = Buffer.from(scrollback, 'base64').toString('utf8');
return stripAnsi(decoded);
}
return stripAnsi(this.tailBuffers.get(task.agentId) ?? '');
}
async mergeTask(
taskId: string,
opts?: { squash?: boolean; message?: string; cleanup?: boolean },
): Promise<{ mainBranch: string; linesAdded: number; linesRemoved: number }> {
const task = this.tasks.get(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
const root = task.projectRoot;
// Strip injected preamble files before staging so they don't land in history,
// then auto-commit any uncommitted changes in the task worktree before merging.
if (task.worktreePath) {
await stripPreambleFromBranch(task);
try {
await execAsync('git', ['add', '-A'], { cwd: task.worktreePath });
await execAsync('git', ['commit', '-m', 'WIP: auto-commit before merge'], {
cwd: task.worktreePath,
});
} catch {
// Commit failed — check if uncommitted changes still exist
const { stdout: statusOut } = await execAsync('git', ['status', '--porcelain'], {
cwd: task.worktreePath,
});
if (statusOut.trim()) {
throw new Error(
`Auto-commit failed and the task worktree still has uncommitted changes. ` +
`Please commit or discard changes in ${task.worktreePath} before merging.`,
);
}
// Nothing to commit — swallow silently
}
}
const coordinatorState = this.coordinators.get(task.coordinatorTaskId);
const runMerge = () =>
gitMergeTask(
root,
task.branchName,
opts?.squash ?? false,
opts?.message ?? null,
false, // worktree removal is handled by cleanupTask below, not gitMergeTask
task.baseBranch,
task.worktreePath,
coordinatorState?.worktreePath,
);
let result: Awaited<ReturnType<typeof runMerge>>;
try {
result = await runMerge();
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('Another git process') || msg.includes('index.lock')) {
// Stale git lock — wait for it to clear then retry once
await new Promise((r) => setTimeout(r, 2000));
result = await runMerge();
} else {
throw err;
}
}
if (opts?.cleanup) {
await this.cleanupTask(taskId);
}
return {
mainBranch: result.main_branch,
linesAdded: result.lines_added,
linesRemoved: result.lines_removed,
};
}
async reviewAndMergeTask(
taskId: string,
opts?: { squash?: boolean; message?: string },
): Promise<{
diff: ApiDiffResult;
merge: { mainBranch: string; linesAdded: number; linesRemoved: number };
}> {
const diff = await this.getTaskDiff(taskId);
const merge = await this.mergeTask(taskId, { ...opts, cleanup: true });
return { diff, merge };
}
async closeTask(taskId: string): Promise<void> {
const task = this.tasks.get(taskId);
if (!task) throw new Error(`Task not found: ${taskId}`);
await this.cleanupTask(taskId);
}