forked from johannesjo/parallel-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregister.ts
More file actions
526 lines (498 loc) · 18.1 KB
/
register.ts
File metadata and controls
526 lines (498 loc) · 18.1 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
import { ipcMain, dialog, shell, app, BrowserWindow, clipboard } from 'electron';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { IPC } from './channels.js';
import {
spawnAgent,
writeToAgent,
resizeAgent,
pauseAgent,
resumeAgent,
killAgent,
countRunningAgents,
killAllAgents,
getAgentMeta,
} from './pty.js';
import { ensurePlansDirectory, startPlanWatcher } from './plans.js';
import { startRemoteServer } from '../remote/server.js';
import {
getGitIgnoredDirs,
getMainBranch,
getCurrentBranch,
getChangedFiles,
getChangedFilesFromBranch,
getFileDiff,
getFileDiffFromBranch,
getWorktreeStatus,
commitAll,
discardUncommitted,
checkMergeStatus,
mergeTask,
getBranchLog,
pushTask,
rebaseTask,
createWorktree,
removeWorktree,
} from './git.js';
import { createTask, deleteTask } from './tasks.js';
import { listAgents } from './agents.js';
import { saveAppState, loadAppState } from './persistence.js';
import { spawn } from 'child_process';
import path from 'path';
import {
assertString,
assertInt,
assertBoolean,
assertStringArray,
assertOptionalString,
assertOptionalBoolean,
} from './validate.js';
/** Reject paths that are non-absolute or attempt directory traversal. */
function validatePath(p: unknown, label: string): void {
if (typeof p !== 'string') throw new Error(`${label} must be a string`);
if (!path.isAbsolute(p)) throw new Error(`${label} must be absolute`);
if (p.includes('..')) throw new Error(`${label} must not contain ".."`);
}
/** Reject relative paths that attempt directory traversal or are absolute. */
function validateRelativePath(p: unknown, label: string): void {
if (typeof p !== 'string') throw new Error(`${label} must be a string`);
if (path.isAbsolute(p)) throw new Error(`${label} must not be absolute`);
if (p.includes('..')) throw new Error(`${label} must not contain ".."`);
}
/** Reject branch names that could be misinterpreted as git flags. */
function validateBranchName(name: unknown, label: string): void {
if (typeof name !== 'string' || !name) throw new Error(`${label} must be a non-empty string`);
if (name.startsWith('-')) throw new Error(`${label} must not start with "-"`);
}
export function registerAllHandlers(win: BrowserWindow): void {
// --- Remote access state ---
let remoteServer: ReturnType<typeof startRemoteServer> | null = null;
const taskNames = new Map<string, string>();
// --- PTY commands ---
ipcMain.handle(IPC.SpawnAgent, (_e, args) => {
if (args.cwd) validatePath(args.cwd, 'cwd');
if (!args.isShell && args.cwd) {
try {
ensurePlansDirectory(args.cwd);
} catch (err) {
console.warn('Failed to set up plans directory:', err);
}
}
const result = spawnAgent(win, args);
if (!args.isShell && args.cwd) {
try {
startPlanWatcher(win, args.taskId, args.cwd);
} catch (err) {
console.warn('Failed to start plan watcher:', err);
}
}
return result;
});
ipcMain.handle(IPC.WriteToAgent, (_e, args) => {
assertString(args.agentId, 'agentId');
assertString(args.data, 'data');
return writeToAgent(args.agentId, args.data);
});
ipcMain.handle(IPC.ResizeAgent, (_e, args) => {
assertString(args.agentId, 'agentId');
assertInt(args.cols, 'cols');
assertInt(args.rows, 'rows');
return resizeAgent(args.agentId, args.cols, args.rows);
});
ipcMain.handle(IPC.PauseAgent, (_e, args) => {
assertString(args.agentId, 'agentId');
return pauseAgent(args.agentId);
});
ipcMain.handle(IPC.ResumeAgent, (_e, args) => {
assertString(args.agentId, 'agentId');
return resumeAgent(args.agentId);
});
ipcMain.handle(IPC.KillAgent, (_e, args) => {
assertString(args.agentId, 'agentId');
return killAgent(args.agentId);
});
ipcMain.handle(IPC.CountRunningAgents, () => countRunningAgents());
ipcMain.handle(IPC.KillAllAgents, () => killAllAgents());
// --- Agent commands ---
ipcMain.handle(IPC.ListAgents, () => listAgents());
// --- Task commands ---
ipcMain.handle(IPC.CreateTask, (_e, args) => {
assertString(args.name, 'name');
validatePath(args.projectRoot, 'projectRoot');
assertStringArray(args.symlinkDirs, 'symlinkDirs');
assertOptionalString(args.branchPrefix, 'branchPrefix');
const result = createTask(args.name, args.projectRoot, args.symlinkDirs, args.branchPrefix);
result.then((r: { id: string }) => taskNames.set(r.id, args.name)).catch(() => {});
return result;
});
ipcMain.handle(IPC.DeleteTask, (_e, args) => {
assertStringArray(args.agentIds, 'agentIds');
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
assertBoolean(args.deleteBranch, 'deleteBranch');
return deleteTask(args.agentIds, args.branchName, args.deleteBranch, args.projectRoot);
});
// --- Git commands ---
ipcMain.handle(IPC.GetChangedFiles, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
return getChangedFiles(args.worktreePath);
});
ipcMain.handle(IPC.GetChangedFilesFromBranch, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
return getChangedFilesFromBranch(args.projectRoot, args.branchName);
});
ipcMain.handle(IPC.GetFileDiff, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
validateRelativePath(args.filePath, 'filePath');
return getFileDiff(args.worktreePath, args.filePath);
});
ipcMain.handle(IPC.GetFileDiffFromBranch, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
validateRelativePath(args.filePath, 'filePath');
return getFileDiffFromBranch(args.projectRoot, args.branchName, args.filePath);
});
ipcMain.handle(IPC.GetGitignoredDirs, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
return getGitIgnoredDirs(args.projectRoot);
});
ipcMain.handle(IPC.GetWorktreeStatus, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
return getWorktreeStatus(args.worktreePath);
});
ipcMain.handle(IPC.CommitAll, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
assertString(args.message, 'message');
return commitAll(args.worktreePath, args.message);
});
ipcMain.handle(IPC.DiscardUncommitted, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
return discardUncommitted(args.worktreePath);
});
ipcMain.handle(IPC.CheckMergeStatus, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
return checkMergeStatus(args.worktreePath);
});
ipcMain.handle(IPC.MergeTask, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
assertBoolean(args.squash, 'squash');
assertOptionalString(args.message, 'message');
assertOptionalBoolean(args.cleanup, 'cleanup');
return mergeTask(args.projectRoot, args.branchName, args.squash, args.message, args.cleanup);
});
ipcMain.handle(IPC.GetBranchLog, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
return getBranchLog(args.worktreePath);
});
ipcMain.handle(IPC.PushTask, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
return pushTask(args.projectRoot, args.branchName);
});
ipcMain.handle(IPC.RebaseTask, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
return rebaseTask(args.worktreePath);
});
ipcMain.handle(IPC.GetMainBranch, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
return getMainBranch(args.projectRoot);
});
ipcMain.handle(IPC.GetCurrentBranch, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
return getCurrentBranch(args.projectRoot);
});
// --- Persistence ---
// Extract task names from persisted state so the remote server can
// show them (taskNames is only populated on CreateTask otherwise).
function syncTaskNamesFromJson(json: string): void {
try {
const state = JSON.parse(json) as { tasks?: Record<string, { id: string; name: string }> };
if (state.tasks) {
for (const t of Object.values(state.tasks)) {
if (t.id && t.name) taskNames.set(t.id, t.name);
}
}
} catch (e) {
console.warn('Ignoring malformed saved state:', e);
}
}
ipcMain.handle(IPC.SaveAppState, (_e, args) => {
assertString(args.json, 'json');
syncTaskNamesFromJson(args.json);
return saveAppState(args.json);
});
ipcMain.handle(IPC.LoadAppState, () => {
const json = loadAppState();
if (json) syncTaskNamesFromJson(json);
return json;
});
// --- Arena persistence ---
ipcMain.handle(IPC.SaveArenaData, (_e, args) => {
assertString(args.filename, 'filename');
assertString(args.json, 'json');
const filePath = path.join(app.getPath('userData'), args.filename);
const basename = path.basename(filePath);
if (basename !== args.filename) throw new Error('Invalid filename');
if (!basename.startsWith('arena-') || !basename.endsWith('.json'))
throw new Error('Arena files must be arena-*.json');
const tmpPath = filePath + '.tmp';
fs.writeFileSync(tmpPath, args.json, 'utf-8');
fs.renameSync(tmpPath, filePath);
});
ipcMain.handle(IPC.LoadArenaData, (_e, args) => {
assertString(args.filename, 'filename');
const filePath = path.join(app.getPath('userData'), args.filename);
const basename = path.basename(filePath);
if (basename !== args.filename) throw new Error('Invalid filename');
if (!basename.startsWith('arena-') || !basename.endsWith('.json'))
throw new Error('Arena files must be arena-*.json');
try {
return fs.readFileSync(filePath, 'utf-8');
} catch {
return null;
}
});
ipcMain.handle(IPC.CreateArenaWorktree, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
return createWorktree(args.projectRoot, args.branchName, args.symlinkDirs ?? [], true);
});
ipcMain.handle(IPC.RemoveArenaWorktree, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
validateBranchName(args.branchName, 'branchName');
return removeWorktree(args.projectRoot, args.branchName, true);
});
ipcMain.handle(IPC.CheckPathExists, (_e, args) => {
validatePath(args.path, 'path');
return fs.existsSync(args.path);
});
// --- Window management ---
ipcMain.handle(IPC.WindowIsFocused, () => win.isFocused());
ipcMain.handle(IPC.WindowIsMaximized, () => win.isMaximized());
ipcMain.handle(IPC.WindowMinimize, () => win.minimize());
ipcMain.handle(IPC.WindowToggleMaximize, () => {
if (win.isMaximized()) win.unmaximize();
else win.maximize();
});
ipcMain.handle(IPC.WindowClose, () => win.close());
ipcMain.handle(IPC.WindowForceClose, () => win.destroy());
ipcMain.handle(IPC.WindowHide, () => win.hide());
ipcMain.handle(IPC.WindowMaximize, () => win.maximize());
ipcMain.handle(IPC.WindowUnmaximize, () => win.unmaximize());
ipcMain.handle(IPC.WindowSetSize, (_e, args) => {
assertInt(args.width, 'width');
assertInt(args.height, 'height');
return win.setSize(args.width, args.height);
});
ipcMain.handle(IPC.WindowSetPosition, (_e, args) => {
assertInt(args.x, 'x');
assertInt(args.y, 'y');
return win.setPosition(args.x, args.y);
});
ipcMain.handle(IPC.WindowGetPosition, () => {
const [x, y] = win.getPosition();
return { x, y };
});
ipcMain.handle(IPC.WindowGetSize, () => {
const [width, height] = win.getSize();
return { width, height };
});
// --- Dialog ---
ipcMain.handle(IPC.DialogConfirm, async (_e, args) => {
const result = await dialog.showMessageBox(win, {
type: args.kind === 'warning' ? 'warning' : 'question',
title: args.title || 'Confirm',
message: args.message,
buttons: [args.okLabel || 'OK', args.cancelLabel || 'Cancel'],
defaultId: 0,
cancelId: 1,
});
return result.response === 0;
});
ipcMain.handle(IPC.DialogOpen, async (_e, args) => {
const properties: Array<'openDirectory' | 'openFile' | 'multiSelections'> = [];
if (args?.directory) properties.push('openDirectory');
else properties.push('openFile');
if (args?.multiple) properties.push('multiSelections');
const result = await dialog.showOpenDialog(win, { properties });
if (result.canceled) return null;
return args?.multiple ? result.filePaths : (result.filePaths[0] ?? null);
});
// --- Clipboard ---
ipcMain.handle(IPC.ClipboardRead, (_e, args) => {
const target = args?.target;
if (target !== undefined && target !== 'clipboard' && target !== 'selection') {
throw new Error('target must be "clipboard" or "selection"');
}
if (target === 'selection' && process.platform === 'linux') {
return clipboard.readText('selection');
}
return clipboard.readText();
});
ipcMain.handle(IPC.ClipboardWrite, (_e, args) => {
assertString(args?.text, 'text');
const target = args?.target;
if (
target !== undefined &&
target !== 'clipboard' &&
target !== 'selection' &&
target !== 'both'
) {
throw new Error('target must be "clipboard", "selection", or "both"');
}
if (target !== 'selection') clipboard.writeText(args.text);
if ((target === 'selection' || target === 'both') && process.platform === 'linux') {
clipboard.writeText(args.text, 'selection');
}
});
// --- Shell/Opener ---
ipcMain.handle(IPC.ShellReveal, (_e, args) => {
validatePath(args.filePath, 'filePath');
shell.showItemInFolder(args.filePath);
});
ipcMain.handle(IPC.ShellOpenFile, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
validateRelativePath(args.filePath, 'filePath');
return shell.openPath(path.join(args.worktreePath, args.filePath));
});
ipcMain.handle(IPC.ShellOpenInEditor, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
if (typeof args.editorCommand !== 'string' || !args.editorCommand.trim()) {
throw new Error('editorCommand must be a non-empty string');
}
const cmd = args.editorCommand.trim();
if (/[;&|`$(){}[\]<>\\'"*?!#~]/.test(cmd)) {
throw new Error('editorCommand must not contain shell metacharacters');
}
return new Promise<void>((resolve, reject) => {
let settled = false;
const child = spawn(cmd, [args.worktreePath], {
detached: true,
stdio: 'ignore',
});
child.on('error', (err) => {
if (!settled) {
settled = true;
reject(new Error(`Failed to launch "${cmd}": ${err.message}`));
}
});
child.on('spawn', () => {
if (!settled) {
settled = true;
child.unref();
resolve();
}
});
});
});
// --- Remote access ---
ipcMain.handle(IPC.StartRemoteServer, (_e, args: { port?: number }) => {
if (remoteServer)
return {
url: remoteServer.url,
wifiUrl: remoteServer.wifiUrl,
tailscaleUrl: remoteServer.tailscaleUrl,
token: remoteServer.token,
port: remoteServer.port,
};
const thisDir = path.dirname(fileURLToPath(import.meta.url));
const distRemote = path.join(thisDir, '..', '..', 'dist-remote');
remoteServer = startRemoteServer({
port: args.port ?? 7777,
staticDir: distRemote,
getTaskName: (taskId: string) => taskNames.get(taskId) ?? taskId,
getAgentStatus: (agentId: string) => {
const meta = getAgentMeta(agentId);
return {
status: meta ? ('running' as const) : ('exited' as const),
exitCode: null,
lastLine: '',
};
},
});
return {
url: remoteServer.url,
wifiUrl: remoteServer.wifiUrl,
tailscaleUrl: remoteServer.tailscaleUrl,
token: remoteServer.token,
port: remoteServer.port,
};
});
ipcMain.handle(IPC.StopRemoteServer, async () => {
if (remoteServer) {
await remoteServer.stop();
remoteServer = null;
}
});
ipcMain.handle(IPC.GetRemoteStatus, () => {
if (!remoteServer) return { enabled: false, connectedClients: 0 };
return {
enabled: true,
connectedClients: remoteServer.connectedClients(),
url: remoteServer.url,
wifiUrl: remoteServer.wifiUrl,
tailscaleUrl: remoteServer.tailscaleUrl,
token: remoteServer.token,
port: remoteServer.port,
};
});
// --- Forward window events to renderer ---
win.on('focus', () => {
if (!win.isDestroyed()) win.webContents.send(IPC.WindowFocus);
});
win.on('blur', () => {
if (!win.isDestroyed()) win.webContents.send(IPC.WindowBlur);
});
// Leading+trailing throttle: fire immediately, suppress for 100ms, then fire once more
// if events arrived during suppression (ensures the final state is always forwarded).
let resizeThrottled = false;
let resizePending = false;
win.on('resize', () => {
if (win.isDestroyed()) return;
if (resizeThrottled) {
resizePending = true;
return;
}
resizeThrottled = true;
win.webContents.send(IPC.WindowResized);
setTimeout(() => {
resizeThrottled = false;
if (resizePending) {
resizePending = false;
if (!win.isDestroyed()) win.webContents.send(IPC.WindowResized);
}
}, 100);
});
let moveThrottled = false;
let movePending = false;
win.on('move', () => {
if (win.isDestroyed()) return;
if (moveThrottled) {
movePending = true;
return;
}
moveThrottled = true;
win.webContents.send(IPC.WindowMoved);
setTimeout(() => {
moveThrottled = false;
if (movePending) {
movePending = false;
if (!win.isDestroyed()) win.webContents.send(IPC.WindowMoved);
}
}, 100);
});
win.on('close', (e) => {
e.preventDefault();
if (!win.isDestroyed()) {
win.webContents.send(IPC.WindowCloseRequested);
// Fallback: force-close if renderer doesn't respond within 5 seconds.
// If the renderer calls WindowForceClose first, win.isDestroyed()
// will be true and this is a no-op.
setTimeout(() => {
if (!win.isDestroyed()) win.destroy();
}, 5_000);
}
});
}