forked from doctly/switchboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb-server.js
More file actions
1017 lines (911 loc) · 41.7 KB
/
Copy pathweb-server.js
File metadata and controls
1017 lines (911 loc) · 41.7 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
'use strict';
/**
* Switchboard web server mode.
*
* Starts an HTTP + WebSocket server that serves the existing frontend and
* exposes all IPC handlers as HTTP endpoints, with terminal I/O over WebSocket.
*
* Usage:
* node web-server.js [--port 3000] [--host 0.0.0.0] [--token <token>]
*
* A bearer token is printed to stdout on startup. Pass it in subsequent
* requests as: Authorization: Bearer <token>
* or as a query parameter: ?token=<token>
*/
const http = require('http');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
const pty = require('node-pty');
const { WebSocketServer } = require('ws');
const { URL } = require('url');
// ── CLI args ─────────────────────────────────────────────────────────
const argv = process.argv.slice(2);
function argVal(flag) {
const i = argv.indexOf(flag);
return i !== -1 && argv[i + 1] ? argv[i + 1] : null;
}
const PORT = parseInt(argVal('--port') || process.env.SWITCHBOARD_PORT || '3000', 10);
const HOST = argVal('--host') || process.env.SWITCHBOARD_HOST || '127.0.0.1';
const TOKEN = argVal('--token') || process.env.SWITCHBOARD_TOKEN || crypto.randomBytes(24).toString('hex');
// ── Logging ───────────────────────────────────────────────────────────
const log = {
info: (...a) => console.log('[info]', ...a),
debug: (...a) => process.env.DEBUG ? console.log('[debug]', ...a) : undefined,
error: (...a) => console.error('[error]', ...a),
warn: (...a) => console.warn('[warn]', ...a),
};
// ── Module imports (same as main.js) ─────────────────────────────────
const { startMcpServer, shutdownMcpServer, shutdownAll: shutdownAllMcp,
resolvePendingDiff, rekeyMcpServer, cleanStaleLockFiles } = require('./mcp-bridge');
const { fetchAndTransformUsage } = require('./claude-auth');
const {
getMeta, getAllMeta, toggleStar, setName, setArchived,
isCachePopulated, getAllCached, getCachedByFolder, getCachedFolder, getCachedSession,
upsertCachedSessions, deleteCachedSession, deleteCachedFolder,
getFolderMeta, getAllFolderMeta, setFolderMeta,
upsertSearchEntries, updateSearchTitle, deleteSearchSession, deleteSearchFolder,
deleteSearchType, searchByType, isSearchIndexPopulated, searchFtsRecreated,
getSetting, setSetting, deleteSetting, closeDb,
} = require('./db');
const { discoverShellProfiles, getShellProfiles, resolveShell,
isWindows, isWslShell, windowsToWslPath, shellArgs } = require('./shell-profiles');
const { deriveProjectPath } = require('./derive-project-path');
// ── Constants ────────────────────────────────────────────────────────
const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
const plansDirs = require('./plans-dirs');
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;
const PUBLIC_DIR = path.join(__dirname, 'public');
const NODE_MODS_DIR = path.join(__dirname, 'node_modules');
const SETTING_DEFAULTS = {
permissionMode: null,
dangerouslySkipPermissions: false,
worktree: false,
worktreeName: '',
chrome: false,
preLaunchCmd: '',
addDirs: '',
visibleSessionCount: 5,
sidebarWidth: 340,
terminalTheme: 'switchboard',
mcpEmulation: false,
shellProfile: 'auto',
};
// ── Active PTY sessions (same structure as main.js) ──────────────────
const activeSessions = new Map();
// ── WebSocket broadcast (replaces mainWindow.webContents.send) ───────
const wsClients = new Set();
function broadcast(event, ...args) {
const msg = JSON.stringify({ type: 'event', event, args });
for (const ws of wsClients) {
if (ws.readyState === 1 /* OPEN */) {
ws.send(msg);
}
}
}
// ── Fake mainWindow object ────────────────────────────────────────────
// session-cache, session-transitions, and mcp-bridge all call
// mainWindow.webContents.send(event, ...args) — we intercept via broadcast().
const mainWindow = {
isDestroyed: () => false,
webContents: {
send: (event, ...args) => broadcast(event, ...args),
},
};
// ── Clean PTY env (same as main.js) ──────────────────────────────────
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'
)
);
// ── Session cache ─────────────────────────────────────────────────────
const sessionCache = require('./session-cache');
sessionCache.init({
PROJECTS_DIR,
activeSessions,
getMainWindow: () => mainWindow,
log,
db: {
deleteCachedFolder, getCachedByFolder, upsertCachedSessions, deleteCachedSession,
deleteSearchFolder, deleteSearchSession, upsertSearchEntries,
setFolderMeta, getAllMeta, getAllCached, getSetting, getMeta, setName,
},
});
const { readSessionFile, readFolderFromFilesystem, refreshFolder, populateCacheFromFilesystem,
buildProjectsFromCache, notifyRendererProjectsChanged, sendStatus,
populateCacheViaWorker } = sessionCache;
// ── Session transitions ───────────────────────────────────────────────
const sessionTransitions = require('./session-transitions');
sessionTransitions.init({ PROJECTS_DIR, activeSessions, getMainWindow: () => mainWindow, log, rekeyMcpServer });
const { detectSessionTransitions } = sessionTransitions;
// ── Auth helper ───────────────────────────────────────────────────────
function isAuthorized(req) {
const auth = req.headers['authorization'] || '';
if (auth.startsWith('Bearer ') && auth.slice(7) === TOKEN) return true;
try {
const u = new URL(req.url, `http://${req.headers.host}`);
if (u.searchParams.get('token') === TOKEN) return true;
} catch {}
return false;
}
// ── Static file serving ───────────────────────────────────────────────
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml',
'.woff': 'font/woff',
'.woff2':'font/woff2',
'.ttf': 'font/ttf',
'.json': 'application/json; charset=utf-8',
'.map': 'application/json; charset=utf-8',
};
function serveStatic(res, filePath) {
const ext = path.extname(filePath).toLowerCase();
const mime = MIME[ext] || 'application/octet-stream';
try {
const data = fs.readFileSync(filePath);
res.writeHead(200, { 'Content-Type': mime });
res.end(data);
} catch {
res.writeHead(404);
res.end('Not found');
}
}
// ── IPC handler logic ─────────────────────────────────────────────────
// Each function mirrors its ipcMain.handle counterpart in main.js.
function handleGetProjects(showArchived) {
try {
const needsPopulate = !isCachePopulated() || !isSearchIndexPopulated();
if (needsPopulate) { populateCacheViaWorker(); return []; }
return buildProjectsFromCache(showArchived);
} catch (err) {
log.error('get-projects:', err);
return [];
}
}
// Mirrors main.js: plansDirectory is per-project, so ~/.claude/plans is only the
// fallback and the set of directories is recomputed on each call.
function readJsonSafe(filePath) {
try { return JSON.parse(fs.readFileSync(filePath, 'utf8')); } catch { return null; }
}
function currentPlansDirs() {
let projectPaths = [];
try {
projectPaths = [...getAllFolderMeta().values()].map(m => m && m.projectPath).filter(Boolean);
} catch {}
return plansDirs.collectPlansDirs({
homeDir: os.homedir(), projectPaths, readJson: readJsonSafe,
dirExists: (d) => { try { return fs.statSync(d).isDirectory(); } catch { return false; } },
});
}
function resolvePlanPath(target, dirs) {
const raw = String(target || '');
if (!raw) return null;
const candidate = path.isAbsolute(raw)
? path.resolve(raw)
: path.join(plansDirs.defaultPlansDir(os.homedir()), path.basename(raw));
return plansDirs.isAllowedPlanPath(candidate, dirs) ? candidate : null;
}
function handleGetPlans() {
const dirs = currentPlansDirs();
try {
const plans = [];
for (const { dir, project } of dirs) {
if (!fs.existsSync(dir)) continue;
let files = [];
try { files = fs.readdirSync(dir).filter(f => f.endsWith('.md')); } catch { continue; }
for (const file of files) {
const filePath = path.join(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, path: filePath, project, title, modified: stat.mtime.toISOString() });
} catch {}
}
}
plans.sort((a, b) => new Date(b.modified) - new Date(a.modified));
try {
deleteSearchType('plan');
upsertSearchEntries(plans.map(p => ({
id: p.path, type: 'plan', folder: null,
title: p.title,
body: fs.readFileSync(p.path, 'utf8'),
})));
} catch {}
return { plans, dirs: dirs.map(d => d.dir) };
} catch (err) { log.error('get-plans:', err); return { plans: [], dirs: dirs.map(d => d.dir) }; }
}
function handleReadPlan(target) {
try {
const filePath = resolvePlanPath(target, currentPlansDirs());
if (!filePath) return { content: '', filePath: '', error: 'path outside plans directories' };
return { content: fs.readFileSync(filePath, 'utf8'), filePath };
} catch (err) { return { content: '', filePath: '' }; }
}
function handleSavePlan(filePath, content) {
try {
const resolved = resolvePlanPath(filePath, currentPlansDirs());
if (!resolved) return { ok: false, error: 'path outside plans directories' };
fs.writeFileSync(resolved, content, 'utf8');
return { ok: true };
} catch (err) { return { ok: false, error: err.message }; }
}
function handleGetStats() {
try {
if (!fs.existsSync(STATS_CACHE_PATH)) return null;
return JSON.parse(fs.readFileSync(STATS_CACHE_PATH, 'utf8'));
} catch { return null; }
}
async function handleRefreshStats() {
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',
};
function runClaude(args, { timeoutMs = 15000, waitFor = null } = {}) {
return new Promise((resolve) => {
let output = '', settled = false, trustAccepted = false, sawActivity = false;
const finish = () => {
if (settled) return; settled = true;
try { p.kill(); } catch {}
resolve(output);
};
const claudeCmd = `claude ${args}`;
const p = pty.spawn(statsShell, shellArgs(statsShell, claudeCmd, statsShellExtraArgs), {
name: 'xterm-256color', cols: 120, rows: 40, cwd: os.homedir(), env: ptyEnv,
});
const strip = (s) => s.replace(/\x1b\[[^@-~]*[@-~]/g, '').replace(/\x1b\][^\x07]*\x07/g, '').replace(/\x1b[^[\]].?/g, '');
p.onData((data) => {
output += data;
if (!trustAccepted && /trust\s*this\s*folder/i.test(strip(output))) {
trustAccepted = true;
try { p.write('\r'); } catch {}
return;
}
if (waitFor) { if (waitFor.test(strip(output))) finish(); return; }
if (!sawActivity) {
const oscTitle = data.match(/\x1b\]0;([^\x07\x1b]*)/);
if (oscTitle) {
const first = oscTitle[1].charAt(0);
if (first.charCodeAt(0) >= 0x2800 && first.charCodeAt(0) <= 0x28FF) sawActivity = true;
}
} else if (data.includes('\u2733')) finish();
});
p.onExit(() => finish());
setTimeout(finish, timeoutMs);
});
}
try {
const [, usage] = await Promise.all([
runClaude('"/stats"', { waitFor: /streak/i, timeoutMs: 10000 }),
fetchAndTransformUsage().catch(() => ({})),
]);
let stats = null;
try {
if (fs.existsSync(STATS_CACHE_PATH)) stats = JSON.parse(fs.readFileSync(STATS_CACHE_PATH, 'utf8'));
} catch {}
return { stats, usage: usage || {} };
} catch (err) { log.error('refresh-stats:', err); return { stats: null, usage: {} }; }
}
async function handleGetUsage() {
try { return await fetchAndTransformUsage() || {}; } catch { return {}; }
}
function folderToShortPath(folder) {
return folder.replace(/^-/, '').split('-').filter(Boolean).slice(-2).join('/');
}
function scanMdFiles(dir) {
const results = [];
try {
if (!fs.existsSync(dir)) return results;
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
if (e.isFile() && e.name.endsWith('.md')) {
const fp = path.join(dir, e.name);
const content = fs.readFileSync(fp, 'utf8').trim();
if (content) results.push({ filename: e.name, filePath: fp, modified: fs.statSync(fp).mtime.toISOString() });
}
}
} catch {}
return results;
}
function handleGetMemories() {
const global = getSetting('global') || {};
const hiddenProjects = new Set(global.hiddenProjects || []);
const globalFiles = scanMdFiles(CLAUDE_DIR).map(f => ({ ...f, displayPath: '~/.claude' }));
const projects = [];
try {
if (fs.existsSync(PROJECTS_DIR)) {
for (const d of fs.readdirSync(PROJECTS_DIR, { withFileTypes: true }).filter(d => d.isDirectory() && d.name !== '.git')) {
const folder = d.name;
const folderPath = path.join(PROJECTS_DIR, folder);
const projectPath = deriveProjectPath(folderPath, folder);
if (projectPath && hiddenProjects.has(projectPath)) continue;
const shortName = projectPath
? projectPath.split('/').filter(Boolean).slice(-2).join('/')
: folderToShortPath(folder);
const files = [], seenPaths = new Set();
for (const f of [...scanMdFiles(folderPath), ...scanMdFiles(path.join(folderPath, 'memory'))]) {
if (!seenPaths.has(f.filePath)) { files.push({ ...f, displayPath: '~/.claude', source: 'claude-home' }); seenPaths.add(f.filePath); }
}
if (projectPath) {
for (const name of ['CLAUDE.md', 'GEMINI.md', 'agents.md']) {
const fp = path.join(projectPath, name);
try {
if (fs.existsSync(fp) && !seenPaths.has(fp)) {
const content = fs.readFileSync(fp, 'utf8').trim();
if (content) {
files.push({ filename: name, filePath: fp, modified: fs.statSync(fp).mtime.toISOString(), displayPath: shortName + '/', source: 'project' });
seenPaths.add(fp);
}
}
} catch {}
}
const dotClaudeDir = path.join(projectPath, '.claude');
for (const f of [...scanMdFiles(dotClaudeDir), ...scanMdFiles(path.join(dotClaudeDir, 'commands'))]) {
if (!seenPaths.has(f.filePath)) { files.push({ ...f, displayPath: shortName + '/.claude/', source: 'project' }); seenPaths.add(f.filePath); }
}
}
if (files.length) projects.push({ folder, projectPath: projectPath || '', shortName, files });
}
}
} catch (err) { log.error('get-memories:', err); }
projects.sort((a, b) => Math.max(...b.files.map(f => new Date(f.modified))) - Math.max(...a.files.map(f => new Date(f.modified))));
try {
deleteSearchType('memory');
upsertSearchEntries([...globalFiles, ...projects.flatMap(p => p.files)].map(f => ({
id: f.filePath, type: 'memory', folder: null,
title: (f.displayPath || '') + ' ' + f.filename,
body: fs.readFileSync(f.filePath, 'utf8'),
})));
} catch {}
return { global: { files: globalFiles }, projects };
}
function handleReadMemory(filePath) {
try {
const resolved = path.resolve(filePath);
if (!resolved.endsWith('.md')) return '';
if (!resolved.startsWith(os.homedir() + path.sep)) return '';
return fs.readFileSync(resolved, 'utf8');
} catch { return ''; }
}
function handleSaveMemory(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) { return { ok: false, error: err.message }; }
}
function handleAddProject(projectPath) {
try {
const stat = fs.statSync(projectPath);
if (!stat.isDirectory()) return { error: 'Path is not a directory' };
const global = getSetting('global') || {};
if (global.hiddenProjects && global.hiddenProjects.includes(projectPath)) {
global.hiddenProjects = global.hiddenProjects.filter(p => p !== projectPath);
setSetting('global', global);
}
const folder = projectPath.replace(/[/_]/g, '-').replace(/^-/, '-');
const folderPath = path.join(PROJECTS_DIR, folder);
if (!fs.existsSync(folderPath)) fs.mkdirSync(folderPath, { recursive: true });
if (!fs.readdirSync(folderPath).some(f => f.endsWith('.jsonl'))) {
const seedId = crypto.randomUUID();
const now = new Date().toISOString();
const line = JSON.stringify({ type: 'user', cwd: projectPath, sessionId: seedId, uuid: crypto.randomUUID(), timestamp: now, message: { role: 'user', content: 'New project' } });
fs.writeFileSync(path.join(folderPath, seedId + '.jsonl'), line + '\n');
}
refreshFolder(folder);
notifyRendererProjectsChanged();
return { ok: true, folder, projectPath };
} catch (err) { return { error: err.message }; }
}
function handleRemoveProject(projectPath) {
try {
const global = getSetting('global') || {};
const hidden = global.hiddenProjects || [];
if (!hidden.includes(projectPath)) hidden.push(projectPath);
global.hiddenProjects = hidden;
setSetting('global', global);
const folder = projectPath.replace(/[/_]/g, '-').replace(/^-/, '-');
deleteCachedFolder(folder);
deleteSearchFolder(folder);
deleteSetting('project:' + projectPath);
notifyRendererProjectsChanged();
return { ok: true };
} catch (err) { return { error: err.message }; }
}
function handleSearch(type, query, titleOnly) {
return searchByType(type, query, 50, !!titleOnly);
}
function handleGetActiveSessions() {
const active = [];
for (const [id, s] of activeSessions) { if (!s.exited) active.push(id); }
return active;
}
function handleGetActiveTerminals() {
const terminals = [];
for (const [id, s] of activeSessions) {
if (!s.exited && s.isPlainTerminal) terminals.push({ sessionId: id, projectPath: s.projectPath });
}
return terminals;
}
function handleStopSession(sessionId) {
const s = activeSessions.get(sessionId);
if (!s || s.exited) return { ok: false, error: 'not running' };
s.pty.kill();
return { ok: true };
}
function handleToggleStar(sessionId) { return { starred: toggleStar(sessionId) }; }
function handleRenameSession(sessionId, name) {
setName(sessionId, name || null);
const cached = getCachedSession(sessionId);
updateSearchTitle(sessionId, 'session', (name ? name + ' ' : '') + (cached?.summary || ''));
return { name: name || null };
}
function handleArchiveSession(sessionId, archived) {
const val = archived ? 1 : 0;
setArchived(sessionId, val);
return { archived: val };
}
function handleReadSessionJsonl(sessionId) {
const folder = getCachedFolder(sessionId);
if (!folder) return { error: 'Session not found in cache' };
const jsonlPath = path.join(PROJECTS_DIR, folder, sessionId + '.jsonl');
try {
const entries = [];
for (const line of fs.readFileSync(jsonlPath, 'utf-8').split('\n')) {
if (line.trim()) try { entries.push(JSON.parse(line)); } catch {}
}
return { entries };
} catch (err) { return { error: err.message }; }
}
// Mirrors the 'get-session-tokens' handler in main.js: reads the tail of the
// transcript and returns the newest assistant usage entry, which feeds the
// status-bar context gauge.
function handleGetSessionTokens(sessionId) {
const folder = getCachedFolder(sessionId);
if (!folder) return null;
const jsonlPath = path.join(PROJECTS_DIR, folder, sessionId + '.jsonl');
try {
const stat = fs.statSync(jsonlPath);
const readSize = Math.min(stat.size, 32768);
const buf = Buffer.alloc(readSize);
const fd = fs.openSync(jsonlPath, 'r');
fs.readSync(fd, buf, 0, readSize, stat.size - readSize);
fs.closeSync(fd);
const lines = buf.toString('utf-8').split('\n').filter(Boolean).reverse();
for (const line of lines) {
try {
const entry = JSON.parse(line);
const u = entry.message?.usage;
if (u && (entry.type === 'assistant' || entry.message?.role === 'assistant')) {
const contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
return { contextTokens, model: entry.message?.model || entry.model || '' };
}
} catch {}
}
return null;
} catch {
return null;
}
}
function handleGetSetting(key) { return getSetting(key); }
function handleSetSetting(key, value) { setSetting(key, value); return { ok: true }; }
function handleDeleteSetting(key) { deleteSetting(key); return { ok: true }; }
function handleGetShellProfiles() { return getShellProfiles(); }
function handleGetEffectiveSettings(projectPath) {
const global = getSetting('global') || {};
const project = projectPath ? (getSetting('project:' + projectPath) || {}) : {};
const effective = { ...SETTING_DEFAULTS };
for (const key of Object.keys(SETTING_DEFAULTS)) {
if (global[key] !== undefined && global[key] !== null) effective[key] = global[key];
if (project[key] !== undefined && project[key] !== null) effective[key] = project[key];
}
return effective;
}
function handleReadFileForPanel(filePath) {
try {
const resolved = path.resolve(filePath);
if (!resolved.startsWith(os.homedir() + path.sep)) return { ok: false, error: 'Access denied' };
return { ok: true, content: fs.readFileSync(resolved, 'utf8') };
} catch (err) { return { ok: false, error: err.message }; }
}
function handleSaveFileForPanel(filePath, content) {
try {
const resolved = path.resolve(filePath);
if (!resolved.startsWith(os.homedir() + path.sep)) return { ok: false, error: 'Access denied' };
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 }; }
}
const fileWatchers = new Map();
function handleWatchFile(filePath) {
const resolved = path.resolve(filePath);
if (!resolved.startsWith(os.homedir() + path.sep)) return { ok: false, error: 'Access 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(() => broadcast('file-changed', resolved), 300);
});
fileWatchers.set(resolved, watcher);
return { ok: true };
} catch (err) { return { ok: false, error: err.message }; }
}
function handleUnwatchFile(filePath) {
const resolved = path.resolve(filePath);
const watcher = fileWatchers.get(resolved);
if (watcher) { watcher.close(); fileWatchers.delete(resolved); }
return { ok: true };
}
async function handleOpenTerminal(sessionId, projectPath, isNew, sessionOptions) {
// Reattach to existing session
if (activeSessions.has(sessionId)) {
const session = activeSessions.get(sessionId);
session.rendererAttached = true;
session.firstResize = !session.isPlainTerminal;
if (session.altScreen && !session.isPlainTerminal) broadcast('terminal-data', sessionId, '\x1b[?1049h');
for (const chunk of session.outputBuffer) broadcast('terminal-data', sessionId, chunk);
if (!session.isPlainTerminal) broadcast('terminal-data', sessionId, '\x1b[?25l');
return { ok: true, reattached: true, mcpActive: !!session.mcpServer };
}
if (!fs.existsSync(projectPath)) return { ok: false, error: `project directory no longer exists: ${projectPath}` };
const isPlainTerminal = sessionOptions?.type === 'terminal';
const effectiveProfileId = (() => {
const g = getSetting('global') || {};
const p = projectPath ? (getSetting('project:' + projectPath) || {}) : {};
let id = SETTING_DEFAULTS.shellProfile;
if (g.shellProfile != null) id = g.shellProfile;
if (p.shellProfile != null) id = p.shellProfile;
return id;
})();
const requestedProfile = resolveShell(effectiveProfileId);
const shellProfile = (isWslShell(requestedProfile.path) && !isPlainTerminal) ? resolveShell('auto') : requestedProfile;
const shell = shellProfile.path;
const shellExtraArgs = [...(shellProfile.args || [])];
const isWsl = isWslShell(shell);
if (isWsl) shellExtraArgs.unshift('--cd', windowsToWslPath(projectPath));
let knownJsonlFiles = new Set(), sessionSlug = null, projectFolder = null;
if (!isPlainTerminal) {
projectFolder = projectPath.replace(/[/_]/g, '-').replace(/^-/, '-');
const claudeProjectDir = path.join(PROJECTS_DIR, projectFolder);
if (fs.existsSync(claudeProjectDir)) {
try { knownJsonlFiles = new Set(fs.readdirSync(claudeProjectDir).filter(f => f.endsWith('.jsonl'))); } catch {}
}
if (!isNew) {
try {
const jsonlPath = path.join(claudeProjectDir, sessionId + '.jsonl');
const head = fs.readFileSync(jsonlPath, 'utf8').slice(0, 8000);
for (const line of head.split('\n').filter(Boolean)) {
const entry = JSON.parse(line);
if (entry.slug) { sessionSlug = entry.slug; break; }
}
} catch {}
}
}
let ptyProcess, mcpServer = null;
try {
if (isPlainTerminal) {
const claudeShim = 'claude() { echo "\\033[33mTo start a Claude session, use the + button in the sidebar.\\033[0m"; return 1; }; export -f claude 2>/dev/null;';
ptyProcess = pty.spawn(shell, shellArgs(shell, undefined, shellExtraArgs), {
name: 'xterm-256color', cols: 120, rows: 30,
cwd: isWsl ? os.homedir() : projectPath,
env: { ...cleanPtyEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor', TERM_PROGRAM: 'iTerm.app', TERM_PROGRAM_VERSION: '3.6.6', FORCE_COLOR: '3', ITERM_SESSION_ID: '1', CLAUDECODE: '1', ENV: claudeShim, BASH_ENV: claudeShim },
});
setTimeout(() => { if (!ptyProcess._isDisposed) try { ptyProcess.write(claudeShim + ' clear\n'); } catch {} }, 300);
} else {
let claudeCmd;
if (sessionOptions?.forkFrom) claudeCmd = `claude --resume "${sessionOptions.forkFrom}" --fork-session`;
else if (isNew) claudeCmd = `claude --session-id "${sessionId}"`;
else claudeCmd = `claude --resume "${sessionId}"`;
if (sessionOptions) {
if (sessionOptions.dangerouslySkipPermissions) claudeCmd += ' --dangerously-skip-permissions';
else if (sessionOptions.permissionMode) claudeCmd += ` --permission-mode "${sessionOptions.permissionMode}"`;
if (sessionOptions.worktree) { claudeCmd += ' --worktree'; if (sessionOptions.worktreeName) claudeCmd += ` "${sessionOptions.worktreeName}"`; }
if (sessionOptions.chrome) claudeCmd += ' --chrome';
if (sessionOptions.addDirs) {
for (const dir of sessionOptions.addDirs.split(',').map(d => d.trim()).filter(Boolean))
claudeCmd += ` --add-dir "${dir}"`;
}
}
if (sessionOptions?.preLaunchCmd) claudeCmd = sessionOptions.preLaunchCmd + ' ' + claudeCmd;
if (sessionOptions?.mcpEmulation !== false) {
try {
mcpServer = await startMcpServer(sessionId, [projectPath], mainWindow, log);
claudeCmd += ' --ide';
} catch (err) { log.error(`[mcp] Failed to start for ${sessionId}: ${err.message}`); }
}
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' };
if (mcpServer) ptyEnv.CLAUDE_CODE_SSE_PORT = String(mcpServer.port);
ptyProcess = pty.spawn(shell, shellArgs(shell, claudeCmd, shellExtraArgs), {
name: 'xterm-256color', cols: 120, rows: 30,
cwd: isWsl ? os.homedir() : projectPath,
env: ptyEnv,
});
}
} catch (err) { return { ok: false, error: `Error spawning PTY: ${err.message}` }; }
const session = {
pty: ptyProcess, rendererAttached: true, exited: false,
outputBuffer: [], outputBufferSize: 0, altScreen: false,
projectPath, firstResize: true,
projectFolder, knownJsonlFiles, sessionSlug,
isPlainTerminal, forkFrom: sessionOptions?.forkFrom || null,
mcpServer, _openedAt: Date.now(),
};
activeSessions.set(sessionId, session);
ptyProcess.onData(data => {
const currentId = session.realSessionId || sessionId;
if (data.includes('\x1b]')) {
for (const m of data.matchAll(/\x1b\](\d+);([^\x07\x1b]*)(?:\x07|\x1b\\)/g)) {
const code = m[1], payload = m[2].slice(0, 120);
if (code === '0') {
const firstChar = payload.charAt(0);
const isBusy = firstChar.charCodeAt(0) >= 0x2800 && firstChar.charCodeAt(0) <= 0x28FF;
const isIdle = firstChar === '\u2733';
if (isBusy && !session._cliBusy) { session._cliBusy = true; session._oscIdle = false; broadcast('cli-busy-state', currentId, true); }
else if (isIdle && session._cliBusy) { session._cliBusy = false; session._oscIdle = true; broadcast('cli-busy-state', currentId, false); }
}
}
for (const osc9 of data.matchAll(/\x1b\]9;([^\x07\x1b]*)(?:\x07|\x1b\\)/g)) {
const payload = osc9[1];
if (payload.startsWith('4;')) {
const level = payload.split(';')[1];
if (level === '0') continue;
if ((level === '1' || level === '2' || level === '3') && !session._cliBusy) {
session._cliBusy = true; session._oscIdle = false; broadcast('cli-busy-state', currentId, true);
}
} else { broadcast('terminal-notification', currentId, payload); }
}
}
if (data.includes('\x1b[?')) {
if (data.includes('\x1b[?1049h') || data.includes('\x1b[?47h')) session.altScreen = true;
if (data.includes('\x1b[?1049l') || data.includes('\x1b[?47l')) session.altScreen = false;
}
if (!session._suppressBuffer) {
session.outputBuffer.push(data);
session.outputBufferSize += data.length;
while (session.outputBufferSize > MAX_BUFFER_SIZE && session.outputBuffer.length > 1)
session.outputBufferSize -= session.outputBuffer.shift().length;
}
broadcast('terminal-data', currentId, data);
});
ptyProcess.onExit(({ exitCode }) => {
session.exited = true;
const mcpId = session.realSessionId || sessionId;
shutdownMcpServer(mcpId);
session.mcpServer = null;
const realId = session.realSessionId || sessionId;
broadcast('process-exited', realId, exitCode);
if (realId !== sessionId && activeSessions.has(sessionId)) broadcast('process-exited', sessionId, exitCode);
activeSessions.delete(realId);
activeSessions.delete(sessionId);
});
return { ok: true, reattached: false, mcpActive: !!mcpServer };
}
// ── HTTP request handler ──────────────────────────────────────────────
async function handleRequest(req, res) {
const u = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
const pathname = u.pathname;
// Auth check — skip for root page so browsers can display a login error
if (pathname !== '/' && !pathname.startsWith('/node_modules/') && !isAuthorized(req)) {
// Allow unauthenticated load of the app shell so the UI can prompt for token
const isPublicAsset = pathname.startsWith('/public/') || ['.js', '.css', '.png', '.ico', '.svg', '.woff', '.woff2'].some(e => pathname.endsWith(e));
if (!isPublicAsset) {
res.writeHead(401, { 'WWW-Authenticate': 'Bearer realm="Switchboard"', 'Content-Type': 'text/plain' });
res.end('Unauthorized');
return;
}
}
// ── Static files ──
if (pathname === '/' || pathname === '/index.html') {
return serveStatic(res, path.join(PUBLIC_DIR, 'index.html'));
}
if (pathname.startsWith('/node_modules/')) {
const nmFile = path.resolve(path.join(__dirname, pathname));
if (!nmFile.startsWith(NODE_MODS_DIR + path.sep)) { res.writeHead(403); res.end('Forbidden'); return; }
return serveStatic(res, nmFile);
}
const localFile = path.resolve(path.join(PUBLIC_DIR, pathname.replace(/^\//, '')));
if (!pathname.startsWith('/api/') && localFile.startsWith(PUBLIC_DIR + path.sep) && fs.existsSync(localFile) && fs.statSync(localFile).isFile()) {
return serveStatic(res, localFile);
}
// ── API ──
if (pathname === '/api/invoke' && req.method === 'POST') {
let body = '';
req.on('data', d => { body += d; });
req.on('end', async () => {
let parsed;
try { parsed = JSON.parse(body); } catch {
res.writeHead(400); res.end('Bad JSON'); return;
}
const { channel, args = [] } = parsed;
let result;
try {
result = await dispatch(channel, args);
} catch (err) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
return;
}
res.writeHead(404);
res.end('Not found');
}
async function dispatch(channel, args) {
switch (channel) {
case 'get-projects': return handleGetProjects(args[0]);
case 'get-plans': return handleGetPlans();
case 'read-plan': return handleReadPlan(args[0]);
case 'save-plan': return handleSavePlan(args[0], args[1]);
case 'get-stats': return handleGetStats();
case 'refresh-stats': return handleRefreshStats();
case 'get-usage': return handleGetUsage();
case 'get-memories': return handleGetMemories();
case 'read-memory': return handleReadMemory(args[0]);
case 'save-memory': return handleSaveMemory(args[0], args[1]);
case 'add-project': return handleAddProject(args[0]);
case 'remove-project': return handleRemoveProject(args[0]);
case 'search': return handleSearch(args[0], args[1], args[2]);
case 'get-active-sessions': return handleGetActiveSessions();
case 'get-active-terminals': return handleGetActiveTerminals();
case 'stop-session': return handleStopSession(args[0]);
case 'toggle-star': return handleToggleStar(args[0]);
case 'rename-session': return handleRenameSession(args[0], args[1]);
case 'archive-session': return handleArchiveSession(args[0], args[1]);
case 'read-session-jsonl': return handleReadSessionJsonl(args[0]);
case 'get-session-tokens': return handleGetSessionTokens(args[0]);
case 'get-setting': return handleGetSetting(args[0]);
case 'set-setting': return handleSetSetting(args[0], args[1]);
case 'delete-setting': return handleDeleteSetting(args[0]);
case 'get-shell-profiles': return handleGetShellProfiles();
case 'get-effective-settings': return handleGetEffectiveSettings(args[0]);
case 'read-file-for-panel': return handleReadFileForPanel(args[0]);
case 'save-file-for-panel': return handleSaveFileForPanel(args[0], args[1]);
case 'watch-file': return handleWatchFile(args[0]);
case 'unwatch-file': return handleUnwatchFile(args[0]);
case 'open-terminal': return handleOpenTerminal(args[0], args[1], args[2], args[3]);
case 'browse-folder': return null; // no native dialog in web mode
case 'open-external': return null; // browser handles this natively
case 'get-app-version': {
try { return require('./package.json').version; } catch { return '0.0.0'; }
}
case 'updater-check': return { available: false, web: true };
case 'updater-download': return null;
case 'updater-install': return null;
default: throw new Error(`Unknown channel: ${channel}`);
}
}
// ── Projects watcher ─────────────────────────────────────────────────
function startProjectsWatcher() {
if (!fs.existsSync(PROJECTS_DIR)) return;
const pending = new Set();
let timer = null;
function flush() {
timer = null;
const folders = new Set(pending); pending.clear();
let changed = false;
for (const folder of folders) {
const fp = path.join(PROJECTS_DIR, folder);
if (fs.existsSync(fp)) { detectSessionTransitions(folder); refreshFolder(folder); }
else deleteCachedFolder(folder);
changed = true;
}
if (changed) notifyRendererProjectsChanged();
}
try {
const watcher = fs.watch(PROJECTS_DIR, { recursive: true }, (_type, filename) => {
if (!filename) return;
const parts = filename.split(path.sep);
const folder = parts[0];
if (!folder || folder === '.git') return;
const basename = parts[parts.length - 1];
if (parts.length === 1 || basename.endsWith('.jsonl')) {
pending.add(folder);
if (timer) clearTimeout(timer);
timer = setTimeout(flush, 500);
}
});
watcher.on('error', err => log.error('Projects watcher error:', err));
} catch (err) { log.error('Failed to start projects watcher:', err); }
}
// ── Start ─────────────────────────────────────────────────────────────
function start() {
if (searchFtsRecreated) populateCacheViaWorker();
cleanStaleLockFiles && cleanStaleLockFiles();
startProjectsWatcher();
const server = http.createServer(handleRequest);
// WebSocket server on same HTTP server
const wss = new WebSocketServer({ server });
wss.on('connection', (ws, req) => {
// Auth check for WS (token in query string)
try {
const u = new URL(req.url, `http://${req.headers.host}`);
if (u.searchParams.get('token') !== TOKEN) { ws.close(4001, 'Unauthorized'); return; }
} catch { ws.close(4001, 'Unauthorized'); return; }
wsClients.add(ws);
ws.on('message', (raw) => {
let msg;
try { msg = JSON.parse(raw); } catch { return; }
switch (msg.type) {
case 'terminal-input': {
const s = activeSessions.get(msg.sessionId);
if (s && !s.exited) s.pty.write(msg.data);
break;
}
case 'terminal-resize': {
const s = activeSessions.get(msg.sessionId);
if (s && !s.exited) {
if (s.isPlainTerminal) s._suppressBuffer = true;
s.pty.resize(msg.cols, msg.rows);
if (s.isPlainTerminal) setTimeout(() => { s._suppressBuffer = false; }, 200);
if (s.firstResize && !s.isPlainTerminal) {
s.firstResize = false;
setTimeout(() => {
try { s.pty.resize(msg.cols + 1, msg.rows); setTimeout(() => { try { s.pty.resize(msg.cols, msg.rows); } catch {} }, 50); } catch {}
}, 50);
}
}
break;
}
case 'close-terminal': {
const s = activeSessions.get(msg.sessionId);
if (s) { s.rendererAttached = false; if (s.exited) activeSessions.delete(msg.sessionId); }
break;
}
case 'mcp-diff-response': {
resolvePendingDiff(msg.sessionId, msg.diffId, msg.action, msg.editedContent);
break;
}
}
});
ws.on('close', () => wsClients.delete(ws));
ws.on('error', () => wsClients.delete(ws));
});
server.listen(PORT, HOST, () => {
console.log('');
console.log(' Switchboard web server running');
console.log(` URL: http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}`);
console.log(` Token: ${TOKEN}`);
console.log('');
console.log(' Open the URL in your browser. When prompted, enter the token above.');