forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
3020 lines (2731 loc) · 122 KB
/
Copy pathmain.js
File metadata and controls
3020 lines (2731 loc) · 122 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, screen, session, shell } = require('electron');
const { Worker } = require('worker_threads');
const { execFile } = require('child_process');
const path = require('path');
const fs = require('fs');
const os = require('os');
const pty = require('node-pty');
const log = require('electron-log');
// Dev builds default to a separate SQLite DB so they don't race on
// session_cache with a running installed AppImage. Honors an explicit
// SWITCHBOARD_DATA_DIR env var if set (test sandboxes, agent runs). This MUST
// happen before db.js is required — db.js resolves DATA_DIR at module load.
if (!app.isPackaged && !process.env.SWITCHBOARD_DATA_DIR) {
process.env.SWITCHBOARD_DATA_DIR = path.join(os.homedir(), '.switchboard-dev');
}
// getFolderIndexMtimeMs moved to session-cache.js
const { appendToOutputBuffer, MAX_BUFFER_SIZE } = require('./output-buffer');
const { startMcpServer, shutdownMcpServer, shutdownAll: shutdownAllMcp, resolvePendingDiff, rekeyMcpServer, cleanStaleLockFiles } = require('./mcp-bridge');
const { fetchAndTransformUsage } = require('./claude-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';
// Opt-in activity trace — see docs/activity-trace.md.
const activityTrace = require('./activity-trace');
const { state: TRACE, trace, codePoints, controlOffset, busyDecision, progressDecision } = activityTrace;
const { classifyTitleActivity } = require('./classify-title-activity');
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'
)
);
// Windows: prefer node-pty's bundled ConPTY (conpty.dll + OpenConsole.exe)
// over the OS inbox one. The inbox ConPTY re-renders TUI frames itself and is a
// known source of ghost/duplicated lines and torn rows during Claude Code
// redraws — artifacts that end up in the xterm buffer, so no renderer-side
// repaint can remove them. VS Code ships the same flag for the same reason.
// SWITCHBOARD_NO_CONPTY_DLL=1 reverts to the inbox ConPTY without a rebuild.
function spawnPty(file, args, opts) {
if (process.platform === 'win32' && !process.env.SWITCHBOARD_NO_CONPTY_DLL) {
try {
return pty.spawn(file, args, { ...opts, useConptyDll: true });
} catch (err) {
// e.g. conpty.dll not found next to the binding — inbox ConPTY still works
log.warn(`[pty] useConptyDll spawn failed, falling back to inbox ConPTY: ${err.message}`);
}
}
return pty.spawn(file, args, opts);
}
// Shell profiles → shell-profiles.js
const { discoverShellProfiles, getShellProfiles, resolveShell, isWindows, isWslShell, windowsToWslPath, shellArgs, quoteArgvForShell } = require('./shell-profiles');
const { startScheduler } = require('./schedule-runner');
const { encodeProjectPath } = require('./encode-project-path');
const { isSensitivePath, isAllowedMemoryPath: _isAllowedMemoryPath, resolveAllowedMemoryPath: _resolveAllowedMemoryPath, isKnownProjectRoot: _isKnownProjectRoot } = require('./ipc-path-validator');
const { validatePreLaunchCmd } = require('./pre-launch-cmd-guard');
const { normalizePtySize } = require('./pty-size');
const { setPtyOpLogger, resizePty, killPty } = require('./pty-ops');
const { createComposerState } = require('./composer-state');
const { handleTerminalInput } = require('./terminal-input');
const { createTriggerContext } = require('./trigger-context');
const { createTmuxAttachAdapter } = require('./remote-attach');
const { createRemoteStopAdapter } = require('./remote-stop');
const { createGitChangesRunner } = require('./git-changes-runner');
const gitChangesTarget = require('./git-changes-target');
setPtyOpLogger(log);
// --- 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);
// With Automatic Updates off there are no scheduled checks, so this event
// can only come from the user pressing "Check for Updates". electron-updater
// does not fetch in that case — AppUpdater's downloadPromise is null unless
// autoDownload — and nothing else calls downloadUpdate(), so a deliberate
// check would otherwise stall at "found, never downloaded". Install still
// waits for the user, since autoInstallOnAppQuit is off too.
if (!autoUpdater.autoDownload) {
autoUpdater.downloadUpdate().catch(err =>
log.error('[updater] manual download failed:', err?.message || String(err)));
}
});
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, getCachedByParent, getCachedFolder, getCachedSession, upsertCachedSessions,
deleteCachedSession, deleteCachedFolder, replaceSessionMetrics, touchCachedModified,
getFolderMeta, getAllFolderMeta, setFolderMeta,
upsertSearchEntries, updateSearchTitle, deleteSearchSession, deleteSearchFolder, deleteSearchType,
searchByType, isSearchIndexPopulated, searchFtsRecreated,
getSetting, setSetting, deleteSetting,
isInitialScanComplete, setInitialScanComplete,
getDailyMetrics, getDailyModelTokens, getModelUsage, getTotalCounts,
closeDb,
DB_PATH,
} = require('./db');
// The trace file sits next to switchboard.db — DB_PATH is the one resolution
// of SWITCHBOARD_DATA_DIR, never re-derived here.
const TRACE_DIR = path.dirname(DB_PATH);
activityTrace.init(TRACE_DIR);
activityTrace.setEnabled(
activityTrace.initialEnabled(process.env, (getSetting('global') || {}).activityTrace)
);
if (TRACE.on) {
log.info(`[activity-trace] enabled → ${activityTrace.currentFile() || '(failed to open)'}`);
}
// One-shot cleanup: the Plans tab was removed, so nothing indexes or clears
// FTS rows of type 'plan' anymore. Purge any left behind by earlier versions.
try { deleteSearchType('plan'); } catch {}
// --- Search query worker ---
// Routes 'search' IPC off the main thread so that a slow FTS5 phrase query
// (e.g. a 60-char pasted URL) never blocks the Electron event loop.
// better-sqlite3 is synchronous; on the main thread a slow query stalls ALL
// IPC (terminal data, OSC, sidebar) → visible UI freeze. The worker opens a
// read-only WAL connection which coexists safely with the main thread's writer.
//
// A dedicated worker is used instead of the existing scan-projects worker because
// that worker is used for cold-start indexing and may be occupied with a long
// sequential scan when the user types a query.
//
// Protocol logic (correlation IDs, pending map, drain, backoff, circuit-breaker)
// lives in search-worker-client.js so it can be unit-tested without Electron.
const { createSearchWorkerClient } = require('./search-worker-client');
const searchClient = createSearchWorkerClient({
workerFactory: (dbPath) => new Worker(
path.join(__dirname, 'workers', 'search-query.js'),
{ workerData: { dbPath } }
),
searchByType,
log,
dbPath: DB_PATH,
});
searchClient.startWorker();
/**
* Send a search query to the worker and return a Promise<results[]>.
* Falls back to the synchronous searchByType on the main thread if the
* worker is not yet ready (first-launch race or circuit-breaker open).
*/
const searchViaWorker = searchClient.searchViaWorker;
const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
// Ceiling for a file opened in the viewer panel, mirroring read-work-file.
const PANEL_FILE_MAX_BYTES = 2 * 1024 * 1024;
const CLAUDE_DIR = path.join(os.homedir(), '.claude');
const STATS_CACHE_PATH = path.join(CLAUDE_DIR, 'stats-cache.json');
// MAX_BUFFER_SIZE imported from output-buffer.js (single source of truth)
// Active PTY sessions
const activeSessions = new Map();
let mainWindow = null;
// Every project root Switchboard currently knows about: live sessions plus
// every indexed project (same enumeration as the get-memories handler).
// Shared by every guard that needs to bound a renderer-supplied path to "a
// project this install actually knows about" — the memory allowlist below,
// and the worktree-path containment check next to WORKTREE_PATH_RE.
function getKnownProjectPaths() {
const projectPaths = new Set();
for (const [, s] of activeSessions) {
if (s.projectPath) projectPaths.add(s.projectPath);
}
try {
const { deriveProjectPath } = require('./derive-project-path');
if (fs.existsSync(PROJECTS_DIR)) {
for (const d of fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })) {
if (!d.isDirectory() || d.name === '.git') continue;
const folderPath = path.join(PROJECTS_DIR, d.name);
const p = deriveProjectPath(folderPath, d.name);
if (p) projectPaths.add(p);
}
}
} catch {}
return projectPaths;
}
// Wrapper that plumbs the set of known project roots into isAllowedMemoryPath.
// The Memory panel (get-memories) surfaces CLAUDE.md / agents.md and
// .claude/*.md from EVERY indexed project — not just ones with a live session —
// so the allowlist must cover every known project root, otherwise reading a
// memory file for a project without an open session would be rejected.
function isAllowedMemoryPath(filePath) {
return _isAllowedMemoryPath(filePath, [...getKnownProjectPaths()]);
}
// Same allowlist, but returns the resolved path to read/write instead of a
// boolean — callers with a filesystem operation to perform must use this and
// operate on the returned value, not on their own path.resolve(filePath).
// See ipc-path-validator.js and resolve-path-on-disk.js.
function resolveAllowedMemoryPath(filePath) {
return _resolveAllowedMemoryPath(filePath, [...getKnownProjectPaths()]);
}
// Subagent live-tail watchers (watchId → { filePath, parentSessionId, agentId, teardown })
const subagentWatchers = new Map();
let subagentWatcherSeq = 0;
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 };
}
}
}
const appTitle = app.isPackaged ? 'Switchboard' : 'Switchboard (dev)';
mainWindow = new BrowserWindow({
...bounds,
minWidth: 800,
minHeight: 500,
title: appTitle,
icon: path.join(__dirname, 'build', 'icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
// The sandboxed preload cannot require activity-trace.js, so main's
// resolution of the flag is handed to it instead of parsed twice.
additionalArguments: TRACE.on ? ['--switchboard-activity-trace'] : [],
},
});
// 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'));
mainWindow.webContents.on('console-message', (_e, level, message, line, sourceId) => {
if (level >= 2) log.error(`[renderer:${level}] ${sourceId}:${line} ${message}`);
});
// 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();
});
// Renderer-driven fullscreen toggle (F11 lands in xterm, which consumes the
// keydown before the menu accelerator can fire — the terminal forwards it
// here instead). Notify the renderer on every change, whatever triggered it
// (menu click, IPC, OS shortcut), so it can refocus the active terminal —
// otherwise the focus is lost on the transition and typing goes nowhere.
const sendFullScreenChanged = () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
mainWindow.webContents.send('full-screen-changed', mainWindow.isFullScreen());
};
mainWindow.on('enter-full-screen', sendFullScreenChanged);
mainWindow.on('leave-full-screen', sendFullScreenChanged);
// 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) killPty(session, id);
activeSessions.delete(id);
}
// Release all subagent file watchers (closes fs.watch handles + clears any
// debounce timers / polling fallbacks via the stored teardown closure)
for (const [, entry] of subagentWatchers) {
try { entry.teardown(); } catch {}
}
subagentWatchers.clear();
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, resolveSessionRealCwd, sessionTranscriptExists, isGitRepo } = require('./derive-project-path');
const { resolveDeletionTargets } = require('./delete-session-target');
// Session cache → session-cache.js
const sessionCache = require('./session-cache');
sessionCache.init({
PROJECTS_DIR,
activeSessions,
getMainWindow: () => mainWindow,
log,
db: {
deleteCachedFolder, getCachedByFolder, upsertCachedSessions, deleteCachedSession, replaceSessionMetrics, touchCachedModified,
deleteSearchFolder, deleteSearchSession, upsertSearchEntries,
setFolderMeta, getFolderMeta, getAllFolderMeta, getAllMeta, getAllCached, getSetting, getMeta, setName,
isInitialScanComplete, setInitialScanComplete,
},
});
const { readSessionFile, readFolderFromFilesystem, refreshFolder, reconcileCacheFromFilesystem,
buildProjectsFromCache, notifyRendererProjectsChanged, sendStatus, populateCacheViaWorker,
scanFoldersViaWorker, setRemoteRoots, resolveFolderDir } = sessionCache;
const { resolveJsonlPath, enumerateSessionFiles } = require('./read-session-file');
// --- Remote SSH hosts (observation only) — see .ai/contexts/session-cache.md ---
const { isRemoteFolder, parseFolderKey, joinFolderKey, enabledHosts } = require('./remote-hosts');
const REMOTE_READ_ONLY = 'remote sessions are read-only — this build observes them, it does not attach to them';
const { createSshTransport } = require('./remote-transport');
const { createRemoteIndexer } = require('./remote-index');
const { createRemoteWatcher } = require('./remote-watch');
const { createRemoteActivityTracker } = require('./remote-activity');
const { createLocalTranscriptTracker } = require('./local-transcript-activity');
const remoteTransport = createSshTransport({ log });
const remoteIndexer = createRemoteIndexer({
getHosts: () => (getSetting('global') || {}).remoteHosts,
getRefreshMs: () => (getSetting('global') || {}).remoteRefreshMs,
dataDir: path.dirname(DB_PATH),
transport: remoteTransport,
scanFolders: scanFoldersViaWorker,
listIndexedFolderKeys: () => [...getAllFolderMeta().keys()],
dropFolder: (folderKey) => { deleteCachedFolder(folderKey); deleteSearchFolder(folderKey); },
setRemoteRoots,
notify: notifyRendererProjectsChanged,
log,
});
// see .ai/contexts/session-cache.md ("Remote hosts — watch channel")
const remoteWatcher = createRemoteWatcher({ log });
let watchedAliases = new Set();
function onRemoteWatchEvent(alias) { remoteIndexer.refreshHostNow(alias).catch(() => {}); }
// see .ai/contexts/session-cache.md ("Remote hosts — busy spinner (issue #242)")
const remoteActivityTracker = createRemoteActivityTracker({});
function onRemoteWatchActivity(alias, rel) {
const result = remoteActivityTracker.record(alias, rel);
if (!result) return;
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('remote-activity', result);
}
}
function startWatcherForHost(host) {
remoteWatcher.start(host.alias, onRemoteWatchEvent, onRemoteWatchActivity);
}
function syncRemoteWatchers() {
const declared = enabledHosts((getSetting('global') || {}).remoteHosts);
const wanted = new Set(declared.map(h => h.alias));
for (const alias of watchedAliases) {
if (!wanted.has(alias)) remoteWatcher.stop(alias);
}
for (const host of declared) {
if (!remoteWatcher.isRunning(host.alias)) startWatcherForHost(host);
}
watchedAliases = wanted;
}
// see .ai/contexts/session-cache.md ("Remote hosts backoff" — manual reconnect, issue #252)
function restartWatcherForAlias(alias) {
const declared = enabledHosts((getSetting('global') || {}).remoteHosts);
const host = declared.find(h => h.alias === alias);
if (!host) return;
remoteWatcher.stop(alias);
startWatcherForHost(host);
watchedAliases.add(alias);
}
// see .ai/contexts/session-cache.md ("Remote hosts — tmux attach")
const remoteAttachAdapter = createTmuxAttachAdapter({
spawnPty: (file, args, ptyOpts) => spawnPty(file, args, { ...ptyOpts, cwd: os.homedir(), env: cleanPtyEnv }),
log,
});
// see .ai/contexts/session-state.md ("The two lifecycle verbs: detach and stop")
const remoteStopAdapter = createRemoteStopAdapter({ log });
// Joins the sidebar's remote sessions to the indexer's live descriptors so the
// renderer can route a click without ever naming an attach mechanism itself
// — see .ai/contexts/session-cache.md ("Remote hosts — tmux attach").
function annotateRemoteAttachable(projects) {
const hostInfoByAlias = new Map();
function hostInfo(alias) {
if (!hostInfoByAlias.has(alias)) {
const { sessions, at, error } = remoteIndexer.getRemoteSessions(alias);
const { nextAttemptAt } = remoteIndexer.getRemoteHostState(alias);
hostInfoByAlias.set(alias, { at, error, nextAttemptAt, byId: new Map(sessions.map(d => [d.sessionId, d])) });
}
return hostInfoByAlias.get(alias);
}
for (const project of projects) {
if (project.remoteAlias) {
const info = hostInfo(project.remoteAlias);
project.remoteHostAt = info.at;
project.remoteHostError = info.error;
project.remoteHostNextAttemptAt = info.nextAttemptAt || null;
}
for (const session of project.sessions) {
if (session.remoteAlias) {
const descriptor = hostInfo(session.remoteAlias).byId.get(session.sessionId);
session.remoteAttachable = !!(descriptor && remoteAttachAdapter.supports(descriptor));
session.status = descriptor ? (descriptor.status || null) : null;
session.statusUpdatedAt = descriptor ? (descriptor.statusUpdatedAt || null) : null;
session.remoteActiveAt = remoteActivityTracker.activeAt(session.remoteAlias, session.sessionId);
// listed descriptor = live process (ALIVE filter) — see .ai/contexts/session-state.md
session.remoteDescriptorSeen = !!descriptor;
} else {
// Same descriptor vocabulary, read from the local ~/.claude/sessions/<pid>.json
// instead of a remote host's mirror -- see .ai/contexts/cli-session-state.md
const local = cliSessionState.getStatus(session.sessionId);
session.status = local ? local.status : undefined;
session.statusUpdatedAt = local ? local.statusUpdatedAt : undefined;
}
}
}
return projects;
}
// see .ai/contexts/session-cache.md ("Remote hosts — descriptor-only sessions")
function toSidebarPlaceholderSession(ph) {
return {
sessionId: ph.sessionId,
summary: ph.summary,
firstPrompt: null,
created: null,
modified: ph.modified,
messageCount: 0,
projectPath: ph.projectPath,
slug: null,
aiTitle: null,
parentSessionId: null,
agentId: null,
subagentType: null,
description: null,
name: null,
starred: 0,
archived: 0,
remoteAlias: ph.remoteAlias,
remoteDescriptorSeen: ph.remoteDescriptorSeen,
status: ph.status,
statusUpdatedAt: ph.statusUpdatedAt,
placeholder: true,
};
}
function mergePlaceholderSessions(projects) {
const placeholders = remoteIndexer.getAllPlaceholderSessions();
for (const ph of placeholders) {
const project = projects.find(p => p.remoteAlias === ph.remoteAlias && p.projectPath === ph.projectPath);
if (project) {
if (project.sessions.some(s => s.sessionId === ph.sessionId)) continue;
project.sessions.push(toSidebarPlaceholderSession(ph));
} else {
projects.push({
folder: joinFolderKey(ph.remoteAlias, ph.folder),
projectPath: ph.projectPath,
remoteAlias: ph.remoteAlias,
sessions: [toSidebarPlaceholderSession(ph)],
missing: false,
});
}
}
return projects;
}
/** Directory holding a folder key's transcripts, local or mirrored. */
function projectsDirForFolder(folder) {
return resolveFolderDir(folder);
}
/** resolveJsonlPath for a cache row whose `folder` may carry an alias prefix. */
function resolveSessionJsonlPath(row) {
const dir = projectsDirForFolder(row && row.folder);
if (!dir) return null;
return resolveJsonlPath(dir, { ...row, folder: '.' });
}
// --- 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 = 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, folderKey) => {
try {
// Add to hidden projects list
const global = getSetting('global') || {};
const hidden = global.hiddenProjects || [];
const { alias } = folderKey ? parseFolderKey(folderKey) : { alias: null };
const hiddenEntry = alias === null ? projectPath : joinFolderKey(alias, projectPath);
if (!hidden.includes(hiddenEntry)) hidden.push(hiddenEntry);
global.hiddenProjects = hidden;
setSetting('global', global);
// Clean up DB cache and search index for this folder
const folder = folderKey || encodeProjectPath(projectPath);
deleteCachedFolder(folder);
deleteSearchFolder(folder);
deleteSetting('project:' + projectPath);
notifyRendererProjectsChanged();
return { ok: true };
} catch (err) {
return { error: err.message };
}
});
// --- IPC: remap-project ---
/**
* Atomically rewrite cwd occurrences of oldPath → newPath in a single JSONL
* file. Uses a .tmp sibling + rename for crash safety. On any failure the .tmp
* orphan is cleaned up so it cannot block a future remap attempt.
*/
function rewriteJsonlAtomic(filePath, oldPath, newPath) {
const tmp = filePath + '.tmp';
try {
const content = fs.readFileSync(filePath, 'utf8');
const updated = content.split('\n').map(line => {
if (!line) return line;
try {
const parsed = JSON.parse(line);
if (parsed.cwd === oldPath) {
parsed.cwd = newPath;
return JSON.stringify(parsed);
}
} catch {}
return line;
}).join('\n');
fs.writeFileSync(tmp, updated);
fs.renameSync(tmp, filePath);
} catch (err) {
try { fs.unlinkSync(tmp); } catch {}
throw err;
}
}
ipcMain.handle('remap-project', (_event, oldPath, newPath) => {
try {
// Validate oldPath/newPath are strings (basic sanitisation)
if (typeof oldPath !== 'string' || typeof newPath !== 'string') {
return { error: 'Invalid arguments' };
}
// Re-check at handler entry: if oldPath came back, no remap is needed
if (fs.existsSync(oldPath)) {
return { error: 'Project path now exists — remap no longer needed' };
}
// Validate the new path exists and is a directory
let stat;
try { stat = fs.lstatSync(newPath); } catch { return { error: 'Path does not exist' }; }
if (!stat.isDirectory()) return { error: 'Path is not a directory' };
// Find the session folder for the old project path using the same encoding the CLI uses
const folder = encodeProjectPath(oldPath);
const folderPath = path.join(PROJECTS_DIR, folder);
if (!fs.existsSync(folderPath)) return { error: 'No session data found for this project' };
// Refuse if any active PTY session is running for this folder — rewriting
// files while a live claude process is appending them risks data loss
// (our snapshot + rename would silently drop lines appended between read
// and rename). The user must stop all sessions for this project first.
for (const [, session] of activeSessions) {
if (!session.exited && encodeProjectPath(session.projectPath) === folder) {
return { error: 'Active sessions for this project — stop them first' };
}
}
// Rewrite cwd in all session JSONL files (top-level + subagents) so
// `claude --resume` from CLI also picks up the new path.
const sessionFiles = enumerateSessionFiles(folderPath);
for (const { filePath } of sessionFiles) {
rewriteJsonlAtomic(filePath, oldPath, newPath);
}
// Refresh the folder cache so the new path takes effect in the UI
refreshFolder(folder);
notifyRendererProjectsChanged();
return { ok: true };
} catch (err) {
return { error: err.message };
}
});
// --- IPC: delete-worktree ---
// Validated path pattern: <project>/.<segment>/[worktrees/]<name>
// Matches .claude/worktrees/<n>, .claude-worktrees/<n>, .worktrees/<n>
const WORKTREE_PATH_RE = /^(.+?)\/\.(?:claude\/worktrees|claude-worktrees|worktrees)\/([^/]+)\/?$/;
// WORKTREE_PATH_RE only checks *shape* (a string that looks like
// <something>/.claude/worktrees/<name>) — match[1] can be any string with
// that suffix stripped, including a directory this install has never heard
// of. Bind it to a project root Switchboard actually knows about before
// letting `git -C <parentRepo> worktree remove` run against it.
function isKnownProjectRoot(candidatePath) {
return _isKnownProjectRoot(candidatePath, [...getKnownProjectPaths()]);
}
ipcMain.handle('delete-worktree', (_event, worktreePath) => {
return new Promise((resolve) => {
// Normalize trailing slash
const normalizedPath = worktreePath.replace(/\/$/, '');
// Validate path matches a known worktree layout
const match = normalizedPath.match(WORKTREE_PATH_RE);
if (!match) {
return resolve({ ok: false, error: 'Path does not match a recognized worktree layout' });
}
const parentRepo = match[1];
if (!isKnownProjectRoot(parentRepo)) {
return resolve({ ok: false, error: 'Parent repository is not a known project' });
}
// Helper: run git worktree remove, optionally double-force
function runRemove(doubleForce, callback) {
const args = ['-C', parentRepo, 'worktree', 'remove', '-f'];
if (doubleForce) args.push('-f');
args.push('--', normalizedPath);
execFile('git', args, (err, _stdout, stderr) => callback(err, stderr));
}
runRemove(false, (err, stderr) => {
if (err && /locked/i.test(stderr || err.message || '')) {
// Retry with double force for locked worktrees
runRemove(true, (err2, stderr2) => {
if (err2) return resolve({ ok: false, error: (stderr2 || err2.message || String(err2)).trim() });
afterRemove();
});
} else if (err) {
return resolve({ ok: false, error: (stderr || err.message || String(err)).trim() });
} else {
afterRemove();
}
});
function afterRemove() {
// Clean up DB cache: delete all sessions whose projectPath matches worktreePath
let removed = 0;
try {
const allRows = getAllCached();
for (const row of allRows) {
if (row.projectPath === normalizedPath) {
deleteCachedSession(row.sessionId);
deleteSearchSession(row.sessionId);
removed++;
}
}
} catch (dbErr) {
log.warn('[delete-worktree] DB cleanup error:', dbErr.message);
}
// Remove from hiddenProjects if present
try {
const global = getSetting('global') || {};
if (Array.isArray(global.hiddenProjects) && global.hiddenProjects.includes(normalizedPath)) {
global.hiddenProjects = global.hiddenProjects.filter(p => p !== normalizedPath);
setSetting('global', global);
}
} catch {}
// Also clean up folder meta
try {
const folder = encodeProjectPath(normalizedPath);
deleteCachedFolder(folder);
deleteSearchFolder(folder);
} catch {}
log.info(`[delete-worktree] removed=${normalizedPath} sessions=${removed}`);
notifyRendererProjectsChanged();
resolve({ ok: true, removed });
}
});
});
// --- IPC: worktree-status ---
ipcMain.handle('worktree-status', (_event, worktreePath) => {
return new Promise((resolve) => {
const normalizedPath = worktreePath.replace(/\/$/, '');
const match = normalizedPath.match(WORKTREE_PATH_RE);
if (!match) {
return resolve({ ok: false, error: 'Path does not match a recognized worktree layout' });
}
const parentRepo = match[1];
if (!isKnownProjectRoot(parentRepo)) {
return resolve({ ok: false, error: 'Parent repository is not a known project' });
}
execFile('git', ['-C', parentRepo, '-C', normalizedPath, 'status', '--porcelain'], (err, stdout, stderr) => {
if (err) {
return resolve({ ok: false, error: (stderr || err.message || String(err)).trim() });
}
const dirty = stdout.split('\n').map(l => l.trimEnd()).filter(Boolean);
resolve({ ok: true, dirty, total: dirty.length });
});
});
});
// --- 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: open a local file in the OS default app (terminal right-click menu) ---
ipcMain.handle('open-path', (_event, filePath) => {
if (typeof filePath !== 'string' || !filePath) return;
const resolved = path.resolve(filePath);
// Mirror the read/save-file-for-panel guard: never hand a sensitive path
// (~/.ssh, credentials, etc.) to the OS default opener.
if (isSensitivePath(resolved)) return;
return shell.openPath(resolved);
});
// --- IPC: read clipboard (terminal right-click paste; see clipboard-write-text) ---
ipcMain.handle('read-clipboard', () => clipboard.readText());
// --- 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);
});
ipcMain.handle('toggle-full-screen', () => {
if (!mainWindow || mainWindow.isDestroyed()) return false;
mainWindow.setFullScreen(!mainWindow.isFullScreen());
return mainWindow.isFullScreen();
});
// --- IPC: does the clipboard hold an image? ---
// A terminal is a text stream, so an image can't ride a text paste. When one is on
// the clipboard the renderer forwards Ctrl+V (0x16) to the PTY instead of doing a
// text paste, so the child — e.g. Claude Code — runs its own native clipboard paste
// and reads the image straight off the system clipboard (the same thing a regular
// terminal does). This just reports whether to take that path.
ipcMain.handle('clipboard-has-image', () => !clipboard.readImage().isEmpty());
// --- 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 resolved = path.resolve(filePath);
if (isSensitivePath(resolved)) return { ok: false, error: 'access to sensitive path denied' };
// A file link in terminal output decides this path, so the size is not
// ours -- see .ai/contexts/viewer-panel.md, "Bounds".
const stat = fs.statSync(resolved);
if (stat.size > PANEL_FILE_MAX_BYTES) {
return { ok: false, error: 'file too large to display' };
}
const buf = fs.readFileSync(resolved);
if (buf.includes(0)) return { ok: false, error: 'binary file' };
return { ok: true, content: buf.toString('utf8') };
} catch (err) {
return { ok: false, error: err.message };
}
});
ipcMain.handle('save-file-for-panel', async (_event, filePath, content) => {
try {
const resolved = path.resolve(filePath);
if (isSensitivePath(resolved)) return { ok: false, error: 'access to sensitive path denied' };
if (!fs.existsSync(resolved)) return { ok: false, error: 'File does not exist' };
fs.writeFileSync(resolved, content, 'utf8');
// Close the sub-second window between save and search: if the saved file
// belongs to a type that the FTS index tracks, invalidate its signature so
// the next get-work-files / get-memories call triggers a full reindex
// (matching the explicit invalidation in save-memory / delete-work-file).
if (resolved.includes('/.work-files/')) invalidateFtsSignature('work-file');
if (resolved.endsWith('.md')) invalidateFtsSignature('memory');
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 (isSensitivePath(resolved)) return { ok: false, error: 'access to sensitive path denied' };
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);