-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathmain.js
More file actions
2177 lines (1975 loc) · 86.3 KB
/
Copy pathmain.js
File metadata and controls
2177 lines (1975 loc) · 86.3 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
const { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, protocol, screen, shell } = require('electron');
const { Worker } = require('worker_threads');
const path = require('path');
const fs = require('fs');
const os = require('os');
const pty = require('node-pty');
const log = require('electron-log');
// getFolderIndexMtimeMs moved to session-cache.js
const { startMcpServer, shutdownMcpServer, shutdownAll: shutdownAllMcp, resolvePendingDiff, rekeyMcpServer, cleanStaleLockFiles } = require('./mcp-bridge');
const { fetchAndTransformUsage } = require('./claude-auth');
const { runStatsCommand, refreshStatsCache } = require('./stats-refresh');
const { readHead } = require('./jsonl-scan');
const codexAuth = require('./codex-auth');
// SWITCHBOARD_DATA_DIR isolates a dev/test instance from the installed app:
// db.js puts switchboard.db under it, and pointing userData there gives the
// instance its own single-instance lock (requestSingleInstanceLock keys on
// userData), so both can run side by side.
if (process.env.SWITCHBOARD_DATA_DIR) {
app.setPath('userData', path.resolve(process.env.SWITCHBOARD_DATA_DIR, 'electron'));
}
log.transports.file.level = app.isPackaged ? 'info' : 'debug';
log.transports.console.level = app.isPackaged ? 'info' : 'debug';
try { require('electron-reloader')(module, { watchRenderer: true }); } catch {};
// Clean env for child processes — strips Electron internals that cause nested
// Electron apps (or node-pty inside them) to malfunction, and pins a UTF-8
// LC_CTYPE when the launch environment has no locale. See pty-env.js.
const { buildPtyEnv } = require('./pty-env');
const cleanPtyEnv = buildPtyEnv(process.env);
const { shouldStartFresh, shouldBlockArchivedSession } = require('./session-launch');
const { createTerminalActivity } = require('./terminal-activity');
// Shell profiles → shell-profiles.js
const { discoverShellProfiles, getShellProfiles, resolveShell, isWindows, isWslShell, windowsToWslPath, shellArgs, quoteArgvForShell } = require('./shell-profiles');
const { scanSchedules } = require('./schedule-runner');
const { encodeProjectPath } = require('./encode-project-path');
const { resolveEffectiveSettings } = require('./resolve-effective-settings');
const { listProjectDirectory, readProjectFile, readPreviewFile, openFileExternally } = require('./project-files');
const { manageProjectEntry } = require('./file-management');
const { resolveTerminalFiles } = require('./terminal-file-links');
const { PREVIEW_SCHEME, PREVIEW_SCHEMES, handlePreviewAssetRequest } = require('./preview-assets');
protocol.registerSchemesAsPrivileged(PREVIEW_SCHEMES);
const { createTaskManager } = require('./task-manager');
const { lastAssistantMessage } = require('./session-preview');
// --- Auto-updater (only in packaged builds) ---
let autoUpdater = null;
if (app.isPackaged || process.env.FORCE_UPDATER) {
autoUpdater = require('electron-updater').autoUpdater;
autoUpdater.logger = log;
autoUpdater.autoDownload = true;
autoUpdater.autoInstallOnAppQuit = true;
if (!app.isPackaged) autoUpdater.forceDevUpdateConfig = true;
function sendUpdaterEvent(type, data) {
log.info(`[updater] ${type}`, data || '');
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('updater-event', type, data);
}
}
autoUpdater.on('checking-for-update', () => sendUpdaterEvent('checking'));
autoUpdater.on('update-available', (info) => sendUpdaterEvent('update-available', info));
autoUpdater.on('update-not-available', (info) => sendUpdaterEvent('update-not-available', info));
autoUpdater.on('download-progress', (progress) => sendUpdaterEvent('download-progress', progress));
autoUpdater.on('update-downloaded', (info) => sendUpdaterEvent('update-downloaded', info));
autoUpdater.on('error', (err) => {
log.error('[updater] Error:', err?.message || String(err));
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('updater-event', 'error', { message: err?.message || String(err) });
}
});
}
const {
getMeta, getAllMeta, toggleStar, setName, setArchived,
isCachePopulated, getAllCached, getCachedByFolder, getCachedSession, upsertCachedSessions,
updateCachedAiTitle,
deleteCachedSession, deleteCachedFolder,
getFolderMeta, getAllFolderMeta, setFolderMeta,
upsertSearchEntries, updateSearchTitle, deleteSearchSession, deleteSearchFolder, deleteSearchType,
searchByType, isSearchIndexPopulated, searchFtsRecreated,
getSetting, setSetting, deleteSetting,
copySessionAssignment, moveSessionAssignment, rekeyPlanLinks,
closeDb,
} = require('./db');
const dbModule = require('./db');
const { getHarness, DEFAULT_HARNESS, transcriptPath, availableHarnesses, allHarnesses, progressBusyState,
harnessForFolder: getHarnessForFolder } = require('./harnesses');
const claudeHarness = getHarness(DEFAULT_HARNESS);
const PROJECTS_DIR = claudeHarness.sessionsRoot();
const PLANS_DIR = path.join(os.homedir(), '.claude', 'plans');
const CLAUDE_DIR = path.join(os.homedir(), '.claude');
const STATS_CACHE_PATH = path.join(CLAUDE_DIR, 'stats-cache.json');
const MAX_BUFFER_SIZE = 256 * 1024;
// Active PTY sessions
const activeSessions = new Map();
let mainWindow = null;
let appIsQuitting = false;
function createWindow() {
// Restore saved window bounds
const savedBounds = getSetting('global')?.windowBounds;
let bounds = { width: 1400, height: 900 };
let restorePosition = null;
if (savedBounds && savedBounds.width && savedBounds.height) {
bounds.width = savedBounds.width;
bounds.height = savedBounds.height;
// Only restore position if it's on a visible display
if (savedBounds.x != null && savedBounds.y != null) {
const displays = screen.getAllDisplays();
const onScreen = displays.some(d => {
const b = d.bounds;
return savedBounds.x >= b.x - 100 && savedBounds.x < b.x + b.width &&
savedBounds.y >= b.y - 100 && savedBounds.y < b.y + b.height;
});
if (onScreen) {
restorePosition = { x: savedBounds.x, y: savedBounds.y };
}
}
}
mainWindow = new BrowserWindow({
...bounds,
minWidth: 800,
minHeight: 500,
title: 'Switchboard',
icon: path.join(__dirname, 'build', 'icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
nodeIntegrationInSubFrames: false,
contextIsolation: true,
},
});
// Set position after creation to prevent macOS from clamping size
if (restorePosition) {
mainWindow.setBounds({ ...restorePosition, width: bounds.width, height: bounds.height });
}
mainWindow.loadFile(path.join(__dirname, 'public', 'index.html'));
// Open external links in the system browser instead of a child BrowserWindow
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//i.test(url)) shell.openExternal(url).catch(() => {});
return { action: 'deny' };
});
mainWindow.webContents.on('will-navigate', (event, url) => {
if (url !== mainWindow.webContents.getURL()) {
event.preventDefault();
if (/^https?:\/\//i.test(url)) shell.openExternal(url).catch(() => {});
}
});
// Override window.open so xterm WebLinksAddon's default handler (which does
// window.open() then sets location.href) routes through our IPC instead of
// creating a child BrowserWindow.
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.executeJavaScript(`
window.open = function(url) {
if (url && /^https?:\\/\\//i.test(url)) { window.api.openExternal(url); return null; }
const proxy = {};
Object.defineProperty(proxy, 'location', { get() {
const loc = {};
Object.defineProperty(loc, 'href', {
set(u) { if (/^https?:\\/\\//i.test(u)) window.api.openExternal(u); }
});
return loc;
}});
return proxy;
};
void 0;
`);
});
// Prevent Cmd+R / Ctrl+Shift+R from reloading the page (Chromium built-in).
// Ctrl+R alone on macOS is NOT a reload shortcut and must pass through to xterm
// for reverse-i-search.
mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.type !== 'keyDown') return;
const key = input.key.toLowerCase();
if (key === 'r' && input.meta) event.preventDefault();
if (key === 'r' && input.control && input.shift) event.preventDefault();
});
// Save window bounds on move/resize (debounced)
let boundsTimer = null;
const saveBounds = () => {
if (boundsTimer) clearTimeout(boundsTimer);
boundsTimer = setTimeout(() => {
if (!mainWindow || mainWindow.isDestroyed() || mainWindow.isMinimized()) return;
const b = mainWindow.getBounds();
const global = getSetting('global') || {};
global.windowBounds = { x: b.x, y: b.y, width: b.width, height: b.height };
setSetting('global', global);
}, 500);
};
mainWindow.on('resize', saveBounds);
mainWindow.on('move', saveBounds);
// Also save immediately before close (debounce may not have flushed)
mainWindow.on('close', () => {
if (boundsTimer) clearTimeout(boundsTimer);
if (!mainWindow.isMinimized()) {
const b = mainWindow.getBounds();
const global = getSetting('global') || {};
global.windowBounds = { x: b.x, y: b.y, width: b.width, height: b.height };
setSetting('global', global);
}
});
mainWindow.on('closed', () => {
// On macOS the app stays alive in the dock after the last window closes.
// Kill all running PTY processes so orphaned `claude` processes don't
// accumulate in the background with no way for the user to interact.
for (const [id, session] of activeSessions) {
if (!session.exited) {
try { session.pty.kill(); } catch {}
}
activeSessions.delete(id);
}
taskManager.shutdown();
mainWindow = null;
});
}
function buildMenu() {
const template = [
{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectAll' },
],
},
{
label: 'View',
submenu: [
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
],
},
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
// --- Session cache helpers ---
const { deriveProjectPath } = claudeHarness;
// Session cache → session-cache.js
const sessionCache = require('./session-cache');
sessionCache.init({
PROJECTS_DIR,
activeSessions,
getMainWindow: () => mainWindow,
log,
db: {
deleteCachedFolder, getCachedByFolder, getCachedSession, upsertCachedSessions, deleteCachedSession,
deleteSearchFolder, deleteSearchSession, upsertSearchEntries,
setFolderMeta, getAllFolderMeta, getAllMeta, getAllCached, getSetting, setSetting, getMeta, setName,
updateCachedAiTitle, updateSearchTitle,
},
});
const { refreshFolder, reconcileCacheFromFilesystem, buildProjectsFromCache,
notifyRendererProjectsChanged, sendStatus, populateCacheViaWorker,
refreshHarnessTitles, initializeHiddenProjectTimestamps } = sessionCache;
// --- Projects (a piece of work with a folder on disk) ---
const projects = require('./projects');
projects.init({
db: dbModule,
log,
buildProjectsFromCache,
notifyRendererProjectsChanged,
isHarnessId: (id) => allHarnesses().some(h => h.id === id),
plansDir: PLANS_DIR,
});
// An upgrade can change the working rules in the brief. Bring every project's
// managed blocks up to date once at startup; unchanged files are not written.
projects.syncAllProjectBriefs().catch(err => log.error('[projects] brief sync failed:', err?.message || String(err)));
// Watch every project's plan-tracker.md and todos.md so a tick made by a
// session is credited to it and the page refreshes.
projects.initPlanWatch({
activeSessions,
send: (channel, ...args) => {
if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, ...args);
},
});
// --- IPC: browse-folder ---
ipcMain.handle('browse-folder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory', 'createDirectory'],
title: 'Select Project Folder',
});
if (result.canceled || !result.filePaths.length) return null;
return result.filePaths[0];
});
// --- IPC: add-project ---
ipcMain.handle('add-project', (_event, projectPath) => {
try {
// Validate the path exists and is a directory
const stat = fs.statSync(projectPath);
if (!stat.isDirectory()) return { error: 'Path is not a directory' };
// Unhide if previously hidden
const global = getSetting('global') || {};
if (global.hiddenProjects && global.hiddenProjects.includes(projectPath)) {
global.hiddenProjects = global.hiddenProjects.filter(p => p !== projectPath);
if (global.hiddenProjectTimestamps) {
delete global.hiddenProjectTimestamps[projectPath];
}
setSetting('global', global);
}
// Create the corresponding folder in ~/.claude/projects/ so it persists
const folder = encodeProjectPath(projectPath);
const folderPath = path.join(PROJECTS_DIR, folder);
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
// Seed a minimal .jsonl so deriveProjectPath can read the cwd
if (!fs.readdirSync(folderPath).some(f => f.endsWith('.jsonl'))) {
const seedId = require('crypto').randomUUID();
const seedFile = path.join(folderPath, seedId + '.jsonl');
const now = new Date().toISOString();
const line = JSON.stringify({ type: 'user', cwd: projectPath, sessionId: seedId, uuid: require('crypto').randomUUID(), timestamp: now, message: { role: 'user', content: 'New project' } });
fs.writeFileSync(seedFile, line + '\n');
}
// Immediately index the new folder so it's in cache before frontend renders
refreshFolder(folder);
notifyRendererProjectsChanged();
return { ok: true, folder, projectPath };
} catch (err) {
return { error: err.message };
}
});
// --- IPC: remove-project ---
ipcMain.handle('remove-project', (_event, projectPath) => {
try {
// Add to hidden projects list
const global = getSetting('global') || {};
const hidden = global.hiddenProjects || [];
if (!hidden.includes(projectPath)) hidden.push(projectPath);
global.hiddenProjects = hidden;
global.hiddenProjectTimestamps = {
...(global.hiddenProjectTimestamps || {}),
[projectPath]: Date.now(),
};
setSetting('global', global);
// Clean up DB cache and search index for this folder
const folder = encodeProjectPath(projectPath);
deleteCachedFolder(folder);
deleteSearchFolder(folder);
deleteSetting('project:' + projectPath);
notifyRendererProjectsChanged();
return { ok: true };
} catch (err) {
return { error: err.message };
}
});
// --- IPC: projects ---
// Every mutating handler notifies the renderer itself (projects.js), so both
// the Sessions and the Projects tab refresh from one event.
function guarded(fn) {
return async (_event, ...args) => {
try { return await fn(...args); } catch (err) {
log.error('[projects]', err);
return { error: err.message };
}
};
}
ipcMain.handle('get-project-tree', guarded((showArchived) => {
// Mirrors get-projects: until the cache is populated there is nothing to
// file, and the renderer is told via projects-changed once there is.
if (!isCachePopulated() || !isSearchIndexPopulated()) return { projects: [] };
return projects.buildProjectTree(!!showArchived);
}));
ipcMain.handle('create-project', guarded((spec) => projects.createProject(spec || {})));
ipcMain.handle('update-project', guarded((id, patch) => projects.updateProject(id, patch || {})));
ipcMain.handle('delete-project', guarded((id) => projects.deleteProject(id)));
ipcMain.handle('attach-project-folder', guarded((id, spec) => projects.attachFolder(id, spec || {})));
ipcMain.handle('detach-project-folder', guarded((id, folderPath, opts) => projects.detachFolder(id, folderPath, opts || {})));
ipcMain.handle('set-session-assignment', guarded((sessionId, projectId, trackId) => {
const cleanProjectId = projectId || null;
const cleanTrackId = trackId || null;
const result = projects.assignSession(sessionId, cleanProjectId, cleanTrackId);
// Raw terminals have no transcript to rehydrate this relationship from.
// Keep the live PTY metadata aligned with the durable renderer descriptor so
// a renderer reload cannot put a moved terminal back in its old location.
if (!result?.error) {
const session = activeSessions.get(sessionId);
if (session?.isPlainTerminal) {
session.projectId = cleanProjectId;
session.trackId = cleanProjectId ? cleanTrackId : null;
}
}
return result;
}));
// Scheduled tasks. The tick that fires them is startScheduleTicker below.
ipcMain.handle('list-schedules', guarded(() => projects.listSchedules()));
ipcMain.handle('create-schedule', guarded((spec) => projects.createSchedule(spec || {})));
ipcMain.handle('update-schedule', guarded((id, patch) => projects.updateSchedule(id, patch || {})));
ipcMain.handle('delete-schedule', guarded((id) => projects.deleteSchedule(id)));
ipcMain.handle('resolve-schedule-launch', guarded((id) => projects.resolveScheduleLaunch(id)));
ipcMain.handle('get-schedule-context', guarded((spec) => projects.resolveScheduleContext(spec || {})));
ipcMain.handle('create-track', guarded((projectId, spec) => projects.createTrack(projectId, spec || {})));
ipcMain.handle('update-track', guarded((id, patch) => projects.updateTrack(id, patch || {})));
ipcMain.handle('delete-track', guarded((id, options = {}) => {
const track = dbModule.getTrack(id);
if (!track) return { error: 'Track not found' };
const archiveSessions = options.archiveSessions === true;
// Raw terminals have no transcript row, but participate in track deletion.
for (const [sid, session] of activeSessions) {
if (session.trackId === id && session.isPlainTerminal) dbModule.setSessionAssignment(sid, track.projectId, id);
}
const result = projects.deleteTrack(id, { archiveSessions });
if (result.error) return result;
const affected = new Set(result.sessionIds);
for (const [sid, session] of activeSessions) {
if (session.trackId !== id && !affected.has(sid)) continue;
session.trackId = null;
session.formerTrackName = track.name;
if (archiveSessions && !session.exited) {
session.stopRequested = true;
try { session.pty.kill(); } catch (error) { log.error('[delete-track] stop failed', error); }
}
}
return result;
}));
ipcMain.handle('get-projects-root', guarded(() => projects.projectsRoot()));
ipcMain.handle('get-project-git-status', guarded((id, opts) => projects.folderGitStatus(id, opts || {})));
ipcMain.handle('get-project-git-info', guarded((id) => projects.projectGitInfo(id)));
ipcMain.handle('get-project-git-diff', guarded((id, folderPath, filePath) => projects.projectGitDiff(id, folderPath, filePath)));
ipcMain.handle('get-folder-git-status', guarded((folderPath) => projects.folderGitInfo(String(folderPath || ''))));
// The .env files a folder has, and the ones the dialog ticks by default,
// so a new worktree can be offered its repository's local environment.
ipcMain.handle('list-env-files', guarded((folderPath) => ({
ok: true,
files: projects.listEnvFiles(String(folderPath || '')),
defaults: projects.defaultEnvSelection(String(folderPath || '')),
})));
ipcMain.handle('save-project-brief', guarded((id, content) => projects.saveBrief(id, content)));
ipcMain.handle('create-project-file', guarded((id, name, content) => projects.createProjectFile(id, name, content)));
ipcMain.handle('add-project-files', guarded((id, sourcePaths) => projects.addProjectFiles(id, sourcePaths)));
ipcMain.handle('list-recent-project-files', guarded((id) => projects.listRecentProjectFiles(id)));
ipcMain.handle('get-project-plan', guarded((id) => projects.readProjectPlan(id)));
ipcMain.handle('set-plan-item', guarded((id, kind, line, done) => projects.setPlanItem(id, kind, line, done)));
ipcMain.handle('append-plan-item', guarded((id, kind, text) => projects.appendPlanItem(id, kind, text)));
ipcMain.handle('edit-plan-item', guarded((id, kind, line, text) => projects.editPlanItem(id, kind, line, text)));
ipcMain.handle('adopt-plan', guarded((id, filename, opts) => projects.adoptPlan(id, filename, opts || {})));
ipcMain.handle('list-templates', guarded(() => projects.listTemplates()));
// --- IPC: get-projects ---
ipcMain.handle('open-external', (_event, url) => {
log.info('[open-external IPC]', url);
if (/^https?:\/\//i.test(url)) return shell.openExternal(url);
});
// Reveal a folder in the OS file manager. Only existing directories, so a
// renderer value can never launch a file.
ipcMain.handle('open-path', async (_event, target) => {
try {
const resolved = path.resolve(String(target || ''));
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) return { error: 'Not a folder' };
const err = await shell.openPath(resolved);
return err ? { error: err } : { ok: true };
} catch (err) {
return { error: err.message };
}
});
// --- IPC: clipboard write ---
// The renderer's navigator.clipboard.writeText is gated on focus/user-activation and
// is flaky-to-dead on Linux/Wayland (Ozone). The main-process clipboard has no such
// strings attached, so all terminal copies go through here.
ipcMain.handle('clipboard-write-text', (_event, text) => {
if (typeof text === 'string') clipboard.writeText(text);
});
// --- IPC: MCP bridge ---
ipcMain.on('mcp-diff-response', (_event, sessionId, diffId, action, editedContent) => {
resolvePendingDiff(sessionId, diffId, action, editedContent);
});
ipcMain.handle('resolve-terminal-files', (_event, references) => resolveTerminalFiles(references));
ipcMain.handle('open-file-externally', async (_event, filePath, projectRoot) => {
try {
return { ok: true, ...await openFileExternally(filePath, projectRoot, shell) };
} catch (err) {
return { ok: false, error: err.message };
}
});
ipcMain.handle('read-file-for-panel', async (_event, filePath) => {
try {
return { ok: true, ...readPreviewFile(filePath) };
} catch (err) {
return { ok: false, error: err.message, code: err.code };
}
});
ipcMain.handle('list-project-directory', async (_event, projectPath, relativePath) => {
try {
return { ok: true, entries: listProjectDirectory(projectPath, relativePath) };
} catch (err) {
return { ok: false, error: err.message };
}
});
ipcMain.handle('manage-project-entry', async (_event, projectPath, relativePath, action, newName) => {
try {
const result = await manageProjectEntry(projectPath, relativePath, action, newName, {
shell,
confirmTrash: async (filePath, isDirectory) => {
const destination = process.platform === 'win32' ? 'Recycle Bin' : 'Trash';
const choice = await dialog.showMessageBox(mainWindow, {
type: 'question',
message: `Move "${path.basename(filePath)}" to the ${destination}?`,
detail: `${isDirectory ? 'The folder and its contents' : 'The file'} can be restored from the ${destination}. Open previews of this item will close; unsaved edits will be discarded.`,
buttons: ['Cancel', `Move to ${destination}`], defaultId: 0, cancelId: 0,
noLink: true,
});
return choice.response === 1;
},
});
return { ok: true, ...result };
} catch (err) {
return { ok: false, error: err.message };
}
});
ipcMain.handle('read-project-file', async (_event, projectPath, relativePath) => {
try {
return { ok: true, ...readProjectFile(projectPath, relativePath) };
} catch (err) {
return { ok: false, error: err.message, code: err.code };
}
});
ipcMain.handle('save-file-for-panel', async (_event, filePath, content) => {
try {
const resolved = path.resolve(filePath);
if (!fs.existsSync(resolved)) return { ok: false, error: 'File does not exist' };
fs.writeFileSync(resolved, content, 'utf8');
return { ok: true };
} catch (err) {
return { ok: false, error: err.message };
}
});
// ── File Watching (for viewer panels) ────────────────────────────────
const fileWatchers = new Map(); // filePath → FSWatcher
ipcMain.handle('watch-file', (_event, filePath) => {
const resolved = path.resolve(filePath);
if (fileWatchers.has(resolved)) return { ok: true };
try {
let debounce = null;
const watcher = fs.watch(resolved, (eventType) => {
if (eventType !== 'change') return;
if (debounce) clearTimeout(debounce);
debounce = setTimeout(() => {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('file-changed', resolved);
}
}, 300);
});
fileWatchers.set(resolved, watcher);
return { ok: true };
} catch (err) {
return { ok: false, error: err.message };
}
});
ipcMain.handle('unwatch-file', (_event, filePath) => {
const resolved = path.resolve(filePath);
const watcher = fileWatchers.get(resolved);
if (watcher) {
watcher.close();
fileWatchers.delete(resolved);
}
return { ok: true };
});
ipcMain.handle('get-projects', (_event, showArchived) => {
try {
const needsPopulate = !isCachePopulated() || !isSearchIndexPopulated();
if (needsPopulate) {
populateCacheViaWorker();
return [];
}
// Pick up folders changed while the app was closed, or never indexed by an
// older build, so sessions/worktrees don't silently go missing. Stat-gated,
// so it's cheap when nothing has changed.
reconcileCacheFromFilesystem();
// Backstop for a dropped fs.watch event: a session waiting for its
// transcript would otherwise stay stuck under its temporary id. Only runs
// while something is actually waiting.
if (hasPendingLaunches()) sweepPendingLaunches();
return buildProjectsFromCache(showArchived);
} catch (err) {
console.error('Error listing projects:', err);
return [];
}
});
// --- IPC: get-plans ---
ipcMain.handle('get-plans', () => {
try {
if (!fs.existsSync(PLANS_DIR)) return [];
const files = fs.readdirSync(PLANS_DIR).filter(f => f.endsWith('.md'));
const plans = [];
for (const file of files) {
const filePath = path.join(PLANS_DIR, file);
try {
const stat = fs.statSync(filePath);
const content = fs.readFileSync(filePath, 'utf8');
const firstLine = content.split('\n').find(l => l.trim());
const title = firstLine && firstLine.startsWith('# ')
? firstLine.slice(2).trim()
: file.replace(/\.md$/, '');
plans.push({ filename: file, title, modified: stat.mtime.toISOString() });
} catch {}
}
plans.sort((a, b) => new Date(b.modified) - new Date(a.modified));
// Index plans for FTS
try {
deleteSearchType('plan');
upsertSearchEntries(plans.map(p => ({
id: p.filename, type: 'plan', folder: null,
title: p.title,
body: fs.readFileSync(path.join(PLANS_DIR, p.filename), 'utf8'),
})));
} catch {}
return plans;
} catch (err) {
console.error('Error reading plans:', err);
return [];
}
});
// --- IPC: read-plan ---
ipcMain.handle('read-plan', (_event, filename) => {
try {
const filePath = path.join(PLANS_DIR, path.basename(filename));
const content = fs.readFileSync(filePath, 'utf8');
return { content, filePath };
} catch (err) {
console.error('Error reading plan:', err);
return { content: '', filePath: '' };
}
});
// --- IPC: save-plan ---
ipcMain.handle('save-plan', (_event, filePath, content) => {
try {
const resolved = path.resolve(filePath);
if (!resolved.startsWith(PLANS_DIR)) {
return { ok: false, error: 'path outside plans directory' };
}
fs.writeFileSync(resolved, content, 'utf8');
return { ok: true };
} catch (err) {
console.error('Error saving plan:', err);
return { ok: false, error: err.message };
}
});
// --- IPC: get-stats ---
ipcMain.handle('get-stats', () => {
if (!harnessEnabled(DEFAULT_HARNESS)) return null;
try {
if (!fs.existsSync(STATS_CACHE_PATH)) return null;
const raw = fs.readFileSync(STATS_CACHE_PATH, 'utf8');
return JSON.parse(raw);
} catch (err) {
console.error('Error reading stats cache:', err);
return null;
}
});
// --- IPC: refresh-stats ---
let statsRefreshInFlight = null;
ipcMain.handle('refresh-stats', async () => {
if (!harnessEnabled(DEFAULT_HARNESS)) return { stats: null, usage: {} };
if (statsRefreshInFlight) return statsRefreshInFlight;
statsRefreshInFlight = (async () => {
const usagePromise = fetchAndTransformUsage().catch(() => ({}));
const result = await refreshStatsCache(STATS_CACHE_PATH, () => {
const globalSettings = getSetting('global') || {};
const profile = resolveShell(globalSettings.shellProfile || SETTING_DEFAULTS.shellProfile);
return runStatsCommand({
spawn: (...args) => pty.spawn(...args),
shell: profile.path,
args: shellArgs(profile.path, 'claude "/stats"', profile.args || []),
options: {
name: 'xterm-256color', cols: 120, rows: 40, cwd: os.homedir(),
env: {
...cleanPtyEnv,
TERM: 'xterm-256color', COLORTERM: 'truecolor',
TERM_PROGRAM: 'iTerm.app', TERM_PROGRAM_VERSION: '3.6.6',
FORCE_COLOR: '3', ITERM_SESSION_ID: '1',
},
},
});
});
if (result.statsError) log.warn('Error refreshing stats:', result.statsError);
return { ...result, usage: await usagePromise || {} };
})();
try { return await statsRefreshInFlight; }
finally { statsRefreshInFlight = null; }
});
// --- IPC: get-usage (lightweight, API-only, no PTY) ---
ipcMain.handle('get-usage', async () => {
if (!harnessEnabled(DEFAULT_HARNESS)) return {};
try {
return await fetchAndTransformUsage() || {};
} catch (err) {
log.error('Error fetching usage:', err);
return {};
}
});
// --- IPC: get-codex-usage --- (same idea for the codex account)
ipcMain.handle('get-codex-usage', async () => {
// Nothing is fetched for a CLI the user switched off, or one that was never
// signed in — no request, no error surfaced.
if (!harnessEnabled('codex')) return {};
try {
return await codexAuth.fetchAndTransformUsage() || {};
} catch (err) {
log.error('Error fetching codex usage:', err);
return {};
}
});
// --- IPC: get-memories ---
function folderToShortPath(folder) {
// Convert "-Users-me-dev-my-app" → "dev/my-app"
const parts = folder.replace(/^-/, '').split('-');
const meaningful = parts.filter(Boolean);
return meaningful.slice(-2).join('/');
}
/** Scan a directory for .md files (non-recursive). Returns array of { filename, filePath, modified }. */
function scanMdFiles(dir) {
const results = [];
try {
if (!fs.existsSync(dir)) return results;
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const e of entries) {
if (e.isFile() && e.name.endsWith('.md')) {
const fp = path.join(dir, e.name);
const content = fs.readFileSync(fp, 'utf8').trim();
if (content) {
const stat = fs.statSync(fp);
results.push({ filename: e.name, filePath: fp, modified: stat.mtime.toISOString() });
}
}
}
} catch {}
return results;
}
ipcMain.handle('get-memories', () => {
const global = getSetting('global') || {};
const hiddenProjects = new Set(global.hiddenProjects || []);
// --- Global files ---
const globalFiles = scanMdFiles(CLAUDE_DIR).map(f => ({ ...f, displayPath: '~/.claude' }));
// --- Per-project files ---
const projects = [];
try {
if (fs.existsSync(PROJECTS_DIR)) {
const folders = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.filter(d => d.isDirectory() && d.name !== '.git')
.map(d => d.name);
for (const folder of folders) {
const folderPath = path.join(PROJECTS_DIR, folder);
const projectPath = deriveProjectPath(folderPath, folder);
if (projectPath && hiddenProjects.has(projectPath)) continue;
// Use same 2-deep short path as Sessions tab (e.g. "dev/my-app")
// Splits on both separators — `cwd` is backslash-separated on Windows,
// where splitting on '/' alone left the whole path as one segment.
const shortName = projectPath
? projectPath.split(/[\\/]/).filter(Boolean).slice(-2).join('/')
: folderToShortPath(folder);
const files = [];
const seenPaths = new Set();
// 1. ~/.claude/projects/{folder}/ — claude-home .md files
const claudeHomeFiles = scanMdFiles(folderPath);
for (const f of claudeHomeFiles) {
files.push({ ...f, displayPath: '~/.claude', source: 'claude-home' });
seenPaths.add(f.filePath);
}
// memory/MEMORY.md
const memoryDir = path.join(folderPath, 'memory');
const memoryFiles = scanMdFiles(memoryDir);
for (const f of memoryFiles) {
files.push({ ...f, displayPath: '~/.claude', source: 'claude-home' });
seenPaths.add(f.filePath);
}
// 2. {projectPath}/ — project root CLAUDE.md, agents.md
if (projectPath) {
for (const name of ['CLAUDE.md', 'GEMINI.md', 'agents.md']) {
const fp = path.join(projectPath, name);
try {
if (fs.existsSync(fp)) {
const content = fs.readFileSync(fp, 'utf8').trim();
if (content && !seenPaths.has(fp)) {
const stat = fs.statSync(fp);
files.push({ filename: name, filePath: fp, modified: stat.mtime.toISOString(), displayPath: shortName + '/', source: 'project' });
seenPaths.add(fp);
}
}
} catch {}
}
// 3. {projectPath}/.claude/ — commands/*.md and other .md files
const dotClaudeDir = path.join(projectPath, '.claude');
const dotClaudeFiles = scanMdFiles(dotClaudeDir);
for (const f of dotClaudeFiles) {
if (!seenPaths.has(f.filePath)) {
files.push({ ...f, displayPath: shortName + '/.claude/', source: 'project' });
seenPaths.add(f.filePath);
}
}
// commands/*.md
const commandsDir = path.join(dotClaudeDir, 'commands');
const commandFiles = scanMdFiles(commandsDir);
for (const f of commandFiles) {
if (!seenPaths.has(f.filePath)) {
files.push({ ...f, displayPath: shortName + '/.claude/commands/', source: 'project' });
seenPaths.add(f.filePath);
}
}
}
if (files.length > 0) {
projects.push({ folder, projectPath: projectPath || '', shortName, files });
}
}
}
} catch (err) {
console.error('Error scanning memories:', err);
}
// Sort projects by most recent file modified date
projects.sort((a, b) => {
const aMax = Math.max(...a.files.map(f => new Date(f.modified).getTime()));
const bMax = Math.max(...b.files.map(f => new Date(f.modified).getTime()));
return bMax - aMax;
});
const result = { global: { files: globalFiles }, projects };
// Index all files for FTS
try {
deleteSearchType('memory');
const allFiles = [
...globalFiles.map(f => ({ ...f, label: 'Global' })),
...projects.flatMap(p => p.files.map(f => ({ ...f, label: p.shortName }))),
];
upsertSearchEntries(allFiles.map(f => ({
id: f.filePath, type: 'memory', folder: null,
title: f.label + ' ' + f.filename,
body: fs.readFileSync(f.filePath, 'utf8'),
})));
} catch {}
return result;
});
// --- IPC: read-memory ---
ipcMain.handle('read-memory', (_event, filePath) => {
try {
const resolved = path.resolve(filePath);
// Allow paths under ~/.claude/ or any .md file that exists
if (!resolved.endsWith('.md')) return '';
if (!resolved.startsWith(CLAUDE_DIR) && !fs.existsSync(resolved)) return '';
return fs.readFileSync(resolved, 'utf8');
} catch (err) {
console.error('Error reading memory file:', err);
return '';
}
});
// --- IPC: save-memory ---
ipcMain.handle('save-memory', (_event, filePath, content) => {
try {
const resolved = path.resolve(filePath);
if (!resolved.endsWith('.md')) return { ok: false, error: 'not a .md file' };
if (!fs.existsSync(resolved)) return { ok: false, error: 'file does not exist' };
fs.writeFileSync(resolved, content, 'utf8');
return { ok: true };
} catch (err) {
console.error('Error saving memory file:', err);
return { ok: false, error: err.message };
}
});
// --- IPC: search ---
ipcMain.handle('search-session-ids', (_event, query, sessionIds) => {
if (typeof query !== 'string' || !Array.isArray(sessionIds) || sessionIds.some(id => typeof id !== 'string')) return [];
return dbModule.searchSessionIds(query, sessionIds);
});
ipcMain.handle('search', (_event, type, query, titleOnly) => {
return searchByType(type, query, 50, !!titleOnly);
});
// --- IPC: settings ---
ipcMain.handle('get-setting', (_event, key) => {
return getSetting(key);
});
ipcMain.handle('set-setting', (_event, key, value) => {
const beforeSet = key === 'global' ? disabledHarnessIds() : null;
const before = beforeSet ? [...beforeSet].sort().join(',') : null;
if (key === 'global' && Array.isArray(value?.disabledHarnesses)) {
// At least one CLI has to stay on, or the app has nothing to show and no
// way to start anything. The settings panel already prevents this; this is
// the guard for any other writer. The id that was just switched off is the
// one refused, which is what the UI does too.
const launchable = allHarnesses().filter(h => h.buildLaunchArgs).map(h => h.id);
const disabled = new Set(value.disabledHarnesses);
if (launchable.length && launchable.every(id => disabled.has(id))) {
const justAdded = launchable.filter(id => disabled.has(id) && !beforeSet.has(id));
const keep = justAdded[0] || launchable[0];
log.warn(`[harness-toggle] refusing to disable every CLI; keeping ${keep} on`);
value = { ...value, disabledHarnesses: value.disabledHarnesses.filter(id => id !== keep) };
}
}
setSetting(key, value);
if (key === 'global') {
const after = [...disabledHarnessIds()].sort().join(',');
if (before !== after) {
// Something was switched on or off. Watchers follow the new set, and a
// reconcile picks up whatever a newly-enabled harness did while it was
// being ignored — incremental, because its cached rows were kept and the
// folder mtime gate re-reads only what actually changed.
stopHarnessWatchers();
startHarnessWatchers();
try { projectsWatcher?.close(); } catch {}
projectsWatcher = null;
startProjectsWatcher();
try { reconcileCacheFromFilesystem(); } catch (err) { log.error('[harness-toggle]', err.message); }