forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2080 lines (1858 loc) · 73.1 KB
/
main.js
File metadata and controls
2080 lines (1858 loc) · 73.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
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, dialog, ipcMain, Menu, 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');
const { getFolderIndexMtimeMs } = require('./folder-index-state');
const { startMcpServer, shutdownMcpServer, shutdownAll: shutdownAllMcp, resolvePendingDiff, rekeyMcpServer, cleanStaleLockFiles } = require('./mcp-bridge');
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 — strip Electron internals that cause nested
// Electron apps (or node-pty inside them) to malfunction.
const cleanPtyEnv = Object.fromEntries(
Object.entries(process.env).filter(([k]) =>
!k.startsWith('ELECTRON_') &&
!k.startsWith('GOOGLE_API_KEY') &&
k !== 'NODE_OPTIONS' &&
k !== 'ORIGINAL_XDG_CURRENT_DESKTOP' &&
k !== 'WT_SESSION'
)
);
// --- Cross-platform shell resolution ---
const isWindows = process.platform === 'win32';
// Discover available shell profiles on this system.
// Returns an array of { id, name, path, args? } objects.
function discoverShellProfiles() {
const profiles = [];
if (isWindows) {
const { execSync } = require('child_process');
// CMD
const comspec = process.env.COMSPEC || 'C:\\WINDOWS\\system32\\cmd.exe';
if (fs.existsSync(comspec)) {
profiles.push({ id: 'cmd', name: 'Command Prompt', path: comspec });
}
// PowerShell 7+ (pwsh)
const pwshCandidates = [
path.join(process.env.ProgramFiles || 'C:\\Program Files', 'PowerShell', '7', 'pwsh.exe'),
path.join(process.env.ProgramFiles || 'C:\\Program Files', 'PowerShell', '7-preview', 'pwsh.exe'),
];
for (const p of pwshCandidates) {
if (fs.existsSync(p)) {
profiles.push({ id: 'pwsh', name: 'PowerShell 7', path: p });
break;
}
}
// Windows PowerShell 5.x
const ps5 = path.join(process.env.SystemRoot || 'C:\\WINDOWS', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
if (fs.existsSync(ps5)) {
profiles.push({ id: 'powershell', name: 'Windows PowerShell', path: ps5 });
}
// Git Bash
const gitBashCandidates = [
path.join(process.env.ProgramFiles || 'C:\\Program Files', 'Git', 'bin', 'bash.exe'),
path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Git', 'bin', 'bash.exe'),
path.join(process.env.LOCALAPPDATA || '', 'Programs', 'Git', 'bin', 'bash.exe'),
];
for (const p of gitBashCandidates) {
if (p && fs.existsSync(p)) {
profiles.push({ id: 'git-bash', name: 'Git Bash', path: p });
break;
}
}
// MSYS2
if (fs.existsSync('C:\\msys64\\usr\\bin\\bash.exe')) {
profiles.push({ id: 'msys2', name: 'MSYS2', path: 'C:\\msys64\\usr\\bin\\bash.exe' });
}
// WSL distributions
try {
const raw = execSync('wsl.exe --list --quiet', { timeout: 5000, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
const distros = raw.replace(/\0/g, '').split(/\r?\n/).map(s => s.trim()).filter(Boolean);
for (const distro of distros) {
profiles.push({ id: 'wsl:' + distro, name: 'WSL — ' + distro, path: 'wsl.exe', args: ['-d', distro] });
}
} catch {}
} else {
// macOS / Linux: read /etc/shells for the canonical list
const seen = new Set();
const shellNames = {
'zsh': 'Zsh', 'bash': 'Bash', 'sh': 'POSIX Shell',
'fish': 'Fish', 'nu': 'Nushell', 'pwsh': 'PowerShell',
'dash': 'Dash', 'ksh': 'Korn Shell', 'tcsh': 'tcsh', 'csh': 'C Shell',
};
try {
const lines = fs.readFileSync('/etc/shells', 'utf8').split('\n')
.map(l => l.trim())
.filter(l => l && !l.startsWith('#'));
for (const shellPath of lines) {
if (!fs.existsSync(shellPath)) continue;
const base = path.basename(shellPath);
// Deduplicate by basename (e.g. /bin/bash and /usr/bin/bash)
if (seen.has(base)) continue;
seen.add(base);
const name = shellNames[base] || base;
profiles.push({ id: base, name, path: shellPath });
}
} catch {
// Fallback if /etc/shells is unreadable
for (const [id, name, p] of [
['zsh', 'Zsh', '/bin/zsh'],
['bash', 'Bash', '/bin/bash'],
['sh', 'POSIX Shell', '/bin/sh'],
]) {
if (fs.existsSync(p)) {
profiles.push({ id, name, path: p });
}
}
}
}
return profiles;
}
// Cache profiles (discovered once on startup, refreshed via IPC if needed)
let _shellProfiles = null;
function getShellProfiles() {
if (!_shellProfiles) _shellProfiles = discoverShellProfiles();
return _shellProfiles;
}
function resolveShell(profileId) {
// If a profile is selected, use it
if (profileId && profileId !== 'auto') {
const profiles = getShellProfiles();
const profile = profiles.find(p => p.id === profileId);
if (profile && (profile.path === 'wsl.exe' || fs.existsSync(profile.path))) {
return profile;
}
}
// Auto: original detection logic
// 1. Respect explicit SHELL env (set by Git Bash, MSYS2, WSL, etc.)
if (process.env.SHELL && fs.existsSync(process.env.SHELL)) {
return { id: 'auto', name: 'Auto', path: process.env.SHELL };
}
if (isWindows) {
// 2. Look for Git Bash in common locations
const candidates = [
path.join(process.env.ProgramFiles || 'C:\\Program Files', 'Git', 'bin', 'bash.exe'),
path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Git', 'bin', 'bash.exe'),
path.join(process.env.LOCALAPPDATA || '', 'Programs', 'Git', 'bin', 'bash.exe'),
'C:\\msys64\\usr\\bin\\bash.exe',
];
for (const c of candidates) {
if (c && fs.existsSync(c)) return { id: 'auto', name: 'Auto', path: c };
}
// 3. Fall back to PowerShell / cmd
return { id: 'auto', name: 'Auto', path: process.env.COMSPEC || 'powershell.exe' };
}
// Unix fallback chain
for (const s of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
if (fs.existsSync(s)) return { id: 'auto', name: 'Auto', path: s };
}
return { id: 'auto', name: 'Auto', path: '/bin/sh' };
}
// Convert a Windows path to a WSL /mnt/ path
function windowsToWslPath(winPath) {
if (!winPath) return winPath;
// C:\Users\foo → /mnt/c/Users/foo
const normalized = winPath.replace(/\\/g, '/');
const match = normalized.match(/^([A-Za-z]):(\/.*)/);
if (match) return '/mnt/' + match[1].toLowerCase() + match[2];
return normalized;
}
function isWslShell(shellPath) {
const base = path.basename(shellPath).toLowerCase();
return base === 'wsl.exe' || base === 'wsl';
}
// Returns spawn args appropriate for the resolved shell
function shellArgs(shellPath, cmd, extraArgs) {
const base = path.basename(shellPath).toLowerCase();
const isBashLike = base.includes('bash') || base.includes('zsh') || base === 'sh';
// WSL: pass command via -- to the distribution shell
// cwd is handled separately via --cd in the spawn call
if (isWslShell(shellPath)) {
if (cmd) return [...(extraArgs || []), '--', 'bash', '-l', '-i', '-c', cmd];
return [...(extraArgs || []), '--', 'bash', '-l', '-i'];
}
if (cmd) {
if (isBashLike) return ['-l', '-i', '-c', cmd];
if (base.includes('powershell') || base.includes('pwsh')) return ['-NoLogo', '-Command', cmd];
return ['/C', cmd];
}
if (isBashLike) return ['-l', '-i'];
if (base.includes('powershell') || base.includes('pwsh')) return ['-NoLogo', '-NoExit'];
return [];
}
// --- 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 {
getAllMeta, toggleStar, setName, setArchived,
isCachePopulated, getAllCached, getCachedByFolder, getCachedFolder, getCachedSession, upsertCachedSessions,
deleteCachedSession, deleteCachedFolder,
getFolderMeta, getAllFolderMeta, setFolderMeta,
upsertSearchEntries, updateSearchTitle, deleteSearchSession, deleteSearchFolder, deleteSearchType,
searchByType, isSearchIndexPopulated,
getSetting, setSetting, deleteSetting,
closeDb,
} = require('./db');
const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
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;
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,
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);
}
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 ---
/** Derive the real project path by reading cwd from the first JSONL entry in the folder */
function deriveProjectPath(folderPath, folder) {
try {
const entries = fs.readdirSync(folderPath, { withFileTypes: true });
// Check direct .jsonl files first
for (const e of entries) {
if (e.isFile() && e.name.endsWith('.jsonl')) {
const firstLine = fs.readFileSync(path.join(folderPath, e.name), 'utf8').split('\n')[0];
if (firstLine) {
const parsed = JSON.parse(firstLine);
if (parsed.cwd) return parsed.cwd;
}
}
}
// Check session subdirectories (UUID folders with subagent .jsonl files)
for (const e of entries) {
if (!e.isDirectory()) continue;
const subDir = path.join(folderPath, e.name);
try {
// Look for .jsonl directly in session dir or in subagents/
const subFiles = fs.readdirSync(subDir, { withFileTypes: true });
for (const sf of subFiles) {
let jsonlPath;
if (sf.isFile() && sf.name.endsWith('.jsonl')) {
jsonlPath = path.join(subDir, sf.name);
} else if (sf.isDirectory() && sf.name === 'subagents') {
const agentFiles = fs.readdirSync(path.join(subDir, 'subagents')).filter(f => f.endsWith('.jsonl'));
if (agentFiles.length > 0) jsonlPath = path.join(subDir, 'subagents', agentFiles[0]);
}
if (jsonlPath) {
const firstLine = fs.readFileSync(jsonlPath, 'utf8').split('\n')[0];
if (firstLine) {
const parsed = JSON.parse(firstLine);
if (parsed.cwd) return parsed.cwd;
}
}
}
} catch {}
}
} catch {}
// No cwd found — return null so callers can skip this folder
return null;
}
/** Parse a single .jsonl file into a session object (or null if invalid) */
function readSessionFile(filePath, folder, projectPath) {
const sessionId = path.basename(filePath, '.jsonl');
try {
const stat = fs.statSync(filePath);
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n').filter(Boolean);
let summary = '';
let messageCount = 0;
let textContent = '';
let slug = null;
let customTitle = null;
for (const line of lines) {
const entry = JSON.parse(line);
if (entry.slug && !slug) slug = entry.slug;
if (entry.type === 'custom-title' && entry.customTitle) {
customTitle = entry.customTitle;
}
if (entry.type === 'user' || entry.type === 'assistant' ||
(entry.type === 'message' && (entry.role === 'user' || entry.role === 'assistant'))) {
messageCount++;
}
const msg = entry.message;
const text = typeof msg === 'string' ? msg :
(typeof msg?.content === 'string' ? msg.content :
(msg?.content?.[0]?.text || ''));
if (!summary && (entry.type === 'user' || (entry.type === 'message' && entry.role === 'user'))) {
if (text) summary = text.slice(0, 120);
}
if (text && textContent.length < 8000) {
textContent += text.slice(0, 500) + '\n';
}
}
if (!summary || messageCount < 1) return null;
return {
sessionId, folder, projectPath,
summary, firstPrompt: summary,
created: stat.birthtime.toISOString(),
modified: stat.mtime.toISOString(),
messageCount, textContent, slug, customTitle,
};
} catch {
return null;
}
}
/** Read one folder from filesystem by scanning .jsonl files directly */
function readFolderFromFilesystem(folder) {
const folderPath = path.join(PROJECTS_DIR, folder);
const projectPath = deriveProjectPath(folderPath, folder);
if (!projectPath) return { projectPath: null, sessions: [] };
const sessions = [];
try {
const jsonlFiles = fs.readdirSync(folderPath).filter(f => f.endsWith('.jsonl'));
for (const file of jsonlFiles) {
const s = readSessionFile(path.join(folderPath, file), folder, projectPath);
if (s) sessions.push(s);
}
} catch {}
return { projectPath, sessions };
}
/** Refresh a single folder incrementally: only re-read changed/new .jsonl files */
function refreshFolder(folder) {
const folderPath = path.join(PROJECTS_DIR, folder);
if (!fs.existsSync(folderPath)) {
deleteCachedFolder(folder);
return;
}
const projectPath = deriveProjectPath(folderPath, folder);
if (!projectPath) {
setFolderMeta(folder, null, getFolderIndexMtimeMs(folderPath));
return;
}
// Get what's currently cached for this folder
const cachedSessions = getCachedByFolder(folder);
const cachedMap = new Map(); // sessionId → modified ISO string
for (const row of cachedSessions) {
cachedMap.set(row.sessionId, row.modified);
}
// Scan current .jsonl files
let jsonlFiles;
try {
jsonlFiles = fs.readdirSync(folderPath).filter(f => f.endsWith('.jsonl'));
} catch { return; }
const currentIds = new Set();
let changed = false;
// Collect all changes first, then batch DB writes to minimize lock duration
const sessionsToUpsert = [];
const searchEntriesToUpsert = [];
const namesToSet = [];
const sessionsToDelete = [];
for (const file of jsonlFiles) {
const filePath = path.join(folderPath, file);
const sessionId = path.basename(file, '.jsonl');
currentIds.add(sessionId);
// Check if file mtime changed
let fileMtime;
try { fileMtime = fs.statSync(filePath).mtime.toISOString(); } catch { continue; }
if (cachedMap.has(sessionId) && cachedMap.get(sessionId) === fileMtime) {
continue; // unchanged, skip
}
// File is new or modified — re-read it
const s = readSessionFile(filePath, folder, projectPath);
if (s) {
sessionsToUpsert.push(s);
searchEntriesToUpsert.push({
id: s.sessionId, type: 'session', folder: s.folder,
title: s.summary, body: s.textContent,
});
if (s.customTitle) namesToSet.push({ id: s.sessionId, name: s.customTitle });
}
changed = true;
}
// Remove sessions whose .jsonl files were deleted
for (const sessionId of cachedMap.keys()) {
if (!currentIds.has(sessionId)) {
sessionsToDelete.push(sessionId);
changed = true;
}
}
// Batch all DB writes to reduce lock contention
if (sessionsToUpsert.length > 0) {
upsertCachedSessions(sessionsToUpsert);
}
for (const entry of searchEntriesToUpsert) {
deleteSearchSession(entry.id);
}
if (searchEntriesToUpsert.length > 0) {
upsertSearchEntries(searchEntriesToUpsert);
}
for (const { id, name } of namesToSet) {
setName(id, name);
}
for (const sessionId of sessionsToDelete) {
deleteCachedSession(sessionId);
deleteSearchSession(sessionId);
}
// Update folder mtime
setFolderMeta(folder, projectPath, getFolderIndexMtimeMs(folderPath));
}
/** Populate entire cache from filesystem (cold start) */
function populateCacheFromFilesystem() {
try {
const folders = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.filter(d => d.isDirectory() && d.name !== '.git')
.map(d => d.name);
for (const folder of folders) {
refreshFolder(folder);
}
} catch (err) {
console.error('Error populating cache:', err);
}
}
/** Build projects response from cached data */
function buildProjectsFromCache(showArchived) {
const metaMap = getAllMeta();
const cachedRows = getAllCached();
const global = getSetting('global') || {};
const hiddenProjects = new Set(global.hiddenProjects || []);
// Group by folder
const folderMap = new Map();
for (const row of cachedRows) {
if (hiddenProjects.has(row.projectPath)) continue;
if (!folderMap.has(row.folder)) {
folderMap.set(row.folder, { folder: row.folder, projectPath: row.projectPath, sessions: [] });
}
const meta = metaMap.get(row.sessionId);
const s = {
sessionId: row.sessionId,
summary: row.summary,
firstPrompt: row.firstPrompt,
created: row.created,
modified: row.modified,
messageCount: row.messageCount,
projectPath: row.projectPath,
slug: row.slug || null,
name: meta?.name || null,
starred: meta?.starred || 0,
archived: meta?.archived || 0,
};
if (!showArchived && s.archived) continue;
folderMap.get(row.folder).sessions.push(s);
}
// Include empty project directories (no sessions yet)
try {
const dirs = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
.filter(d => d.isDirectory() && d.name !== '.git');
for (const d of dirs) {
if (!folderMap.has(d.name)) {
const projectPath = deriveProjectPath(path.join(PROJECTS_DIR, d.name), d.name);
if (projectPath && !hiddenProjects.has(projectPath)) {
folderMap.set(d.name, { folder: d.name, projectPath, sessions: [] });
}
}
}
} catch {}
const projects = [];
for (const proj of folderMap.values()) {
proj.sessions.sort((a, b) => new Date(b.modified) - new Date(a.modified));
projects.push(proj);
}
projects.sort((a, b) => {
// Empty projects go to the bottom
if (a.sessions.length === 0 && b.sessions.length > 0) return 1;
if (b.sessions.length === 0 && a.sessions.length > 0) return -1;
const aDate = a.sessions[0]?.modified || '';
const bDate = b.sessions[0]?.modified || '';
return new Date(bDate) - new Date(aDate);
});
return projects;
}
function notifyRendererProjectsChanged() {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('projects-changed');
}
}
function sendStatus(text, type) {
if (text) log.info(`[status] (${type || 'info'}) ${text}`);
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('status-update', text, type || 'info');
}
}
// --- Worker-based cache population (non-blocking) ---
let populatingCache = false;
function populateCacheViaWorker() {
if (populatingCache) return;
populatingCache = true;
sendStatus('Scanning projects\u2026', 'active');
const worker = new Worker(path.join(__dirname, 'workers', 'scan-projects.js'), {
workerData: { projectsDir: PROJECTS_DIR },
});
worker.on('message', (msg) => {
// Progress updates from worker
if (msg.type === 'progress') {
sendStatus(msg.text, 'active');
return;
}
if (!msg.ok) {
console.error('Worker scan error:', msg.error);
sendStatus('Scan failed: ' + msg.error, 'error');
populatingCache = false;
return;
}
sendStatus(`Indexing ${msg.results.length} projects\u2026`, 'active');
// Write results to DB on main thread (fast)
let sessionCount = 0;
for (const { folder, projectPath, sessions, indexMtimeMs } of msg.results) {
deleteCachedFolder(folder);
deleteSearchFolder(folder);
if (sessions.length > 0) {
sessionCount += sessions.length;
upsertCachedSessions(sessions);
for (const s of sessions) {
if (s.customTitle) setName(s.sessionId, s.customTitle);
}
upsertSearchEntries(sessions.map(s => ({
id: s.sessionId, type: 'session', folder: s.folder,
title: (s.customTitle ? s.customTitle + ' ' : '') + s.summary,
body: s.textContent,
})));
}
setFolderMeta(folder, projectPath, indexMtimeMs);
}
populatingCache = false;
sendStatus(`Indexed ${sessionCount} sessions across ${msg.results.length} projects`, 'done');
// Clear status after a few seconds
setTimeout(() => sendStatus(''), 5000);
notifyRendererProjectsChanged();
});
worker.on('error', (err) => {
console.error('Worker error:', err);
sendStatus('Worker error: ' + err.message, 'error');
populatingCache = false;
});
// If the worker exits abnormally (SIGSEGV, OOM, uncaught exception) without
// sending a message, neither the 'message' nor 'error' handler will fire.
// Reset the flag here to prevent a permanent lockout where the session list
// stays empty because populateCacheViaWorker() returns immediately.
worker.on('exit', (code) => {
if (populatingCache) {
populatingCache = false;
if (code !== 0) {
sendStatus('Scan worker exited unexpectedly', 'error');
}
}
});
}
// --- 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);
setSetting('global', global);
}
// Create the corresponding folder in ~/.claude/projects/ so it persists
const folder = projectPath.replace(/[/_]/g, '-').replace(/^-/, '-');
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;
setSetting('global', global);
// Clean up DB cache and search index for this folder
const folder = projectPath.replace(/[/_]/g, '-').replace(/^-/, '-');
deleteCachedFolder(folder);
deleteSearchFolder(folder);
deleteSetting('project:' + projectPath);
notifyRendererProjectsChanged();
return { ok: true };
} catch (err) {
return { error: err.message };
}
});
// --- IPC: get-projects ---
ipcMain.handle('open-external', (_event, url) => {
log.info('[open-external IPC]', url);
if (/^https?:\/\//i.test(url)) return shell.openExternal(url);
});
// --- IPC: MCP bridge ---
ipcMain.on('mcp-diff-response', (_event, sessionId, diffId, action, editedContent) => {
resolvePendingDiff(sessionId, diffId, action, editedContent);
});
ipcMain.handle('read-file-for-panel', async (_event, filePath) => {
try {
const content = fs.readFileSync(filePath, 'utf8');
return { ok: true, content };
} catch (err) {
return { ok: false, error: err.message };
}
});
ipcMain.handle('get-projects', (_event, showArchived) => {
try {
const needsPopulate = !isCachePopulated() || !isSearchIndexPopulated();
if (needsPopulate) {
populateCacheViaWorker();
return [];
}
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', () => {
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 (run /stats + /usage via PTY) ---
ipcMain.handle('refresh-stats', async () => {
// For stats, use the configured shell profile
const globalSettings = getSetting('global') || {};
const statsProfileId = globalSettings.shellProfile || SETTING_DEFAULTS.shellProfile;
const statsShellProfile = resolveShell(statsProfileId);
const statsShell = statsShellProfile.path;
const statsShellExtraArgs = statsShellProfile.args || [];
const ptyEnv = {
...cleanPtyEnv,
TERM: 'xterm-256color',
COLORTERM: 'truecolor',
TERM_PROGRAM: 'iTerm.app',
TERM_PROGRAM_VERSION: '3.6.6',
FORCE_COLOR: '3',
ITERM_SESSION_ID: '1',
};
// Helper: spawn claude with args, collect output, auto-accept trust, kill when idle
// waitFor: optional regex tested against stripped output — finish only when matched
function runClaude(args, { timeoutMs = 15000, waitFor = null } = {}) {