-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
746 lines (717 loc) · 32.2 KB
/
Copy pathserver.js
File metadata and controls
746 lines (717 loc) · 32.2 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
// Claude Session Manager — local web app to overview & manage all Claude Code sessions.
// No external dependencies. Run: node server.js -> http://localhost:4317
const http = require('http');
const fs = require('fs');
const path = require('path');
const os = require('os');
const readline = require('readline');
const { exec, execSync } = require('child_process');
let PORT = process.env.PORT || 4317; // may be overridden by settings before listen
const CLAUDE_DIR = path.join(os.homedir(), '.claude');
const SESSIONS_DIR = path.join(CLAUDE_DIR, 'sessions');
const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
const STATE_FILE = path.join(CLAUDE_DIR, 'session-manager-state.json'); // our own sidecar
const CONFIG_FILE = path.join(CLAUDE_DIR, 'session-manager-config.json');
const LANG_DIR = path.join(__dirname, 'lang');
const DEFAULT_BACKUP_DIR = path.join(CLAUDE_DIR, 'session-backup');
// Terminal launch templates per platform. {cwd} and {id} get substituted.
const TERMINAL_PRESETS = {
win32: {
powershell: `start "" powershell -NoExit -Command "Set-Location -LiteralPath '{cwd}'; claude --resume {id}"`,
cmd: `start "" cmd /k "cd /d \"{cwd}\" && claude --resume {id}"`,
'windows-terminal': `wt -d "{cwd}" powershell -NoExit -Command "claude --resume {id}"`,
},
darwin: {
terminal: `osascript -e 'tell application "Terminal" to do script "cd \\"{cwd}\\" && claude --resume {id}"' -e 'tell application "Terminal" to activate'`,
iterm: `osascript -e 'tell application "iTerm" to tell current window to create tab with default profile' -e 'tell application "iTerm" to tell current session of current window to write text "cd \\"{cwd}\\" && claude --resume {id}"'`,
},
linux: {
'gnome-terminal': `gnome-terminal --working-directory="{cwd}" -- bash -c "claude --resume {id}; exec bash"`,
konsole: `konsole --workdir "{cwd}" -e bash -c "claude --resume {id}; exec bash"`,
xterm: `xterm -e bash -c "cd '{cwd}'; claude --resume {id}; exec bash"`,
},
};
const DEFAULT_TERMINAL = { win32: 'powershell', darwin: 'terminal', linux: 'gnome-terminal' };
// Declarative settings schema — drives both defaults and the (schema-generated) settings UI.
// Adding a setting here = it appears in the UI and in settings.json. (Precursor to a plugin
// "contributes.configuration" model.)
// Labels/groups/options are i18n KEYS resolved client-side against lang/<code>.json.
const SETTINGS_SCHEMA = [
{ group: 'group.general', items: [
{ key: 'language', type: 'select', label: 'set.language', options: [], default: 'en' },
{ key: 'theme', type: 'select', label: 'set.theme',
options: [{ v: 'hell', l: 'opt.light' }, { v: 'dunkel', l: 'opt.dark' }], default: 'hell' },
{ key: 'defaultView', type: 'select', label: 'set.defaultView',
options: [{ v: 'list', l: 'opt.list' }, { v: 'timeline', l: 'opt.timeline' }, { v: 'board', l: 'opt.board' }], default: 'list' },
{ key: 'refreshSeconds', type: 'number', label: 'set.refresh', default: 5, min: 2, max: 300 },
{ key: 'port', type: 'number', label: 'set.port', default: 4317, min: 1, max: 65535 },
]},
{ group: 'group.kanban', items: [
{ key: 'columns', type: 'list', label: 'set.columns',
default: ['New', 'In progress', 'Waiting', 'Done', 'Archive'] },
]},
{ group: 'group.terminal', items: [
{ key: 'terminal', type: 'terminal', label: 'set.terminal' },
]},
{ group: 'group.backup', items: [
{ key: 'backupRemote', type: 'text', label: 'set.backupRemote', default: '' },
{ key: 'backupIntervalHours', type: 'number', label: 'set.backupInterval', default: 6, min: 0, max: 168 },
{ key: 'backupDir', type: 'text', label: 'set.backupDir', default: '' },
]},
];
function scanLanguages() {
let files = [];
try { files = fs.readdirSync(LANG_DIR).filter(f => f.endsWith('.json')); } catch {}
return files.map(f => {
const code = f.replace(/\.json$/, '');
const d = safeReadJson(path.join(LANG_DIR, f), {});
return { code, name: d._name || code };
});
}
// schema with the language item's options filled from available language files
function buildSchema() {
const langs = scanLanguages();
return SETTINGS_SCHEMA.map(g => ({
group: g.group,
items: g.items.map(it => it.key === 'language'
? Object.assign({}, it, { options: langs.map(l => ({ v: l.code, l: l.name })) })
: it),
}));
}
function settingsDefaults() {
const d = {};
for (const g of SETTINGS_SCHEMA) for (const it of g.items) {
if (it.type === 'terminal') { d.terminal = DEFAULT_TERMINAL[process.platform] || 'custom'; d.customCommand = ''; }
else d[it.key] = Array.isArray(it.default) ? it.default.slice() : it.default;
}
return d;
}
function loadSettings() {
return Object.assign(settingsDefaults(), safeReadJson(CONFIG_FILE, {}));
}
function resolveTerminalCmd(cwd, id) {
const cfg = loadSettings();
const presets = TERMINAL_PRESETS[process.platform] || {};
let tmpl = (cfg.terminal === 'custom') ? cfg.customCommand
: (presets[cfg.terminal] || presets[DEFAULT_TERMINAL[process.platform]]);
if (!tmpl) return null;
return tmpl.split('{cwd}').join(cwd).split('{id}').join(id);
}
// ---------- helpers ----------
function safeReadJson(file, fallback) {
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; }
}
// Claude Code encodes a session's cwd into its project-dir name by replacing : \ / with '-'.
// Used to pick the AUTHORITATIVE cwd from a transcript (ignoring sub-agent/Task cwds).
function encPath(cwd) { return cwd.replace(/[:\\/]/g, '-'); }
// Read first `headBytes` and last `tailBytes` of a (possibly huge) file as text.
function readHeadTail(file, headBytes = 65536, tailBytes = 262144) {
const fd = fs.openSync(file, 'r');
try {
const size = fs.fstatSync(fd).size;
if (size <= headBytes + tailBytes) {
const buf = Buffer.alloc(size);
fs.readSync(fd, buf, 0, size, 0);
return { head: buf.toString('utf8'), tail: '' };
}
const head = Buffer.alloc(headBytes);
fs.readSync(fd, head, 0, headBytes, 0);
const tail = Buffer.alloc(tailBytes);
fs.readSync(fd, tail, 0, tailBytes, size - tailBytes);
return { head: head.toString('utf8'), tail: tail.toString('utf8') };
} finally {
fs.closeSync(fd);
}
}
function extractText(content) {
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content.map(c => (c && typeof c === 'object' ? (c.text || '') : '')).join(' ').trim();
}
return '';
}
// Parse a transcript .jsonl into compact metadata.
// dirName = the project-dir name this file lives in (authoritative cwd source).
function parseTranscript(file, dirName) {
const meta = {
cwd: null, firstCwd: null, matchedCwd: null, gitBranch: null, version: null,
customTitle: null, aiTitle: null, lastPrompt: null,
firstUserPrompt: null, firstTs: null, lastTs: null,
};
let content;
try { content = readHeadTail(file); } catch { return meta; }
const scan = (text, isHead) => {
const lines = text.split('\n');
for (const line of lines) {
const s = line.trim();
if (!s || s[0] !== '{') continue;
let d; try { d = JSON.parse(s); } catch { continue; }
switch (d.type) {
case 'custom-title': if (d.customTitle) meta.customTitle = d.customTitle; break;
case 'ai-title': if (d.aiTitle) meta.aiTitle = d.aiTitle; break;
case 'last-prompt': if (d.lastPrompt) meta.lastPrompt = d.lastPrompt; break;
case 'user':
case 'assistant':
if (d.cwd) {
if (!meta.firstCwd) meta.firstCwd = d.cwd;
if (!meta.matchedCwd && dirName && encPath(d.cwd).toLowerCase() === dirName.toLowerCase()) meta.matchedCwd = d.cwd;
meta.cwd = d.cwd; // last-seen fallback
}
if (d.gitBranch) meta.gitBranch = d.gitBranch;
if (d.version) meta.version = d.version;
if (d.timestamp) { if (!meta.firstTs) meta.firstTs = d.timestamp; meta.lastTs = d.timestamp; }
if (d.type === 'user' && isHead && !meta.firstUserPrompt) {
const t = extractText(d.message && d.message.content);
if (t && !t.startsWith('<') && t.length > 1) meta.firstUserPrompt = t.slice(0, 240);
}
break;
}
}
};
scan(content.head, true);
if (content.tail) scan(content.tail, false);
// authoritative cwd: the one matching the project dir, else first-seen, else last-seen
meta.cwd = meta.matchedCwd || meta.firstCwd || meta.cwd;
return meta;
}
// Set of alive PIDs on this machine (Windows: tasklist).
function getAlivePids() {
return new Promise(resolve => {
if (process.platform !== 'win32') {
exec('ps -e -o pid=', (e, out) => {
if (e) return resolve(null);
resolve(new Set(out.split('\n').map(l => l.trim()).filter(Boolean)));
});
return;
}
exec('tasklist /FO CSV /NH', { maxBuffer: 8 * 1024 * 1024 }, (e, out) => {
if (e) return resolve(null);
const pids = new Set();
for (const line of out.split('\n')) {
const m = line.match(/^"[^"]*","(\d+)"/);
if (m) pids.add(m[1]);
}
resolve(pids);
});
});
}
async function scanSessions() {
// 1) live session files (by PID)
const live = {}; // sessionId -> liveInfo
let liveFiles = [];
try { liveFiles = fs.readdirSync(SESSIONS_DIR).filter(f => f.endsWith('.json')); } catch {}
const alivePids = await getAlivePids();
for (const f of liveFiles) {
const d = safeReadJson(path.join(SESSIONS_DIR, f), null);
if (!d || !d.sessionId) continue;
const pid = String(d.pid);
const alive = alivePids ? alivePids.has(pid) : null;
live[d.sessionId] = {
pid: d.pid, alive, cwd: d.cwd, startedAt: d.startedAt,
entrypoint: d.entrypoint, version: d.version,
liveStatus: d.status || null, updatedAt: d.updatedAt || null,
};
}
// 2) transcripts
const sessions = {};
let projDirs = [];
try { projDirs = fs.readdirSync(PROJECTS_DIR); } catch {}
for (const dir of projDirs) {
const full = path.join(PROJECTS_DIR, dir);
let files = [];
try { files = fs.readdirSync(full).filter(f => f.endsWith('.jsonl')); } catch { continue; }
for (const f of files) {
const file = path.join(full, f);
const sessionId = f.replace(/\.jsonl$/, '');
let st; try { st = fs.statSync(file); } catch { continue; }
const meta = parseTranscript(file, dir);
sessions[sessionId] = {
sessionId,
title: meta.customTitle || meta.aiTitle || meta.firstUserPrompt || '(ohne Titel)',
customTitle: meta.customTitle, aiTitle: meta.aiTitle,
cwd: meta.cwd, gitBranch: meta.gitBranch, version: meta.version,
lastPrompt: meta.lastPrompt || meta.firstUserPrompt,
firstUserPrompt: meta.firstUserPrompt,
sizeBytes: st.size,
mtime: st.mtimeMs,
firstTs: meta.firstTs, lastTs: meta.lastTs,
};
}
}
// 2b) archived sessions: present only in the backup mirror (already cleaned up locally)
const bproj = path.join(backupDirPath(), 'projects');
let bdirs = [];
try { bdirs = fs.readdirSync(bproj); } catch {}
for (const dir of bdirs) {
let files = [];
try { files = fs.readdirSync(path.join(bproj, dir)).filter(f => f.endsWith('.jsonl')); } catch { continue; }
for (const f of files) {
const sessionId = f.replace(/\.jsonl$/, '');
if (sessions[sessionId]) continue; // still exists locally
const file = path.join(bproj, dir, f);
let st; try { st = fs.statSync(file); } catch { continue; }
const meta = parseTranscript(file, dir);
sessions[sessionId] = {
sessionId,
title: meta.customTitle || meta.aiTitle || meta.firstUserPrompt || '(ohne Titel)',
customTitle: meta.customTitle, aiTitle: meta.aiTitle,
cwd: meta.cwd, gitBranch: meta.gitBranch, version: meta.version,
lastPrompt: meta.lastPrompt || meta.firstUserPrompt,
firstUserPrompt: meta.firstUserPrompt,
sizeBytes: st.size, mtime: st.mtimeMs,
firstTs: meta.firstTs, lastTs: meta.lastTs,
archived: true,
};
}
}
// 3) merge live info (include live-only sessions too)
for (const [id, l] of Object.entries(live)) {
if (!sessions[id]) {
sessions[id] = { sessionId: id, title: '(laufende Session)', cwd: l.cwd, sizeBytes: 0, mtime: l.updatedAt || l.startedAt };
}
const s = sessions[id];
s.live = l;
if (!s.cwd) s.cwd = l.cwd;
// derive lastActivity
s.lastActivity = Math.max(s.mtime || 0, l.updatedAt || 0, l.startedAt || 0);
}
for (const s of Object.values(sessions)) {
if (!s.lastActivity) s.lastActivity = s.mtime || 0;
// live status: green=alive&recent, yellow=alive&stale(>30min idle), black=not running
if (s.live && s.live.alive) {
const idleMs = Date.now() - (s.lastActivity || 0);
s.status = idleMs > 30 * 60 * 1000 ? 'idle' : 'running';
} else if (s.archived) {
s.status = 'archived';
} else {
s.status = 'closed';
}
s.project = s.cwd ? s.cwd.split(/[\\/]/).filter(Boolean).pop() : '?';
}
return Object.values(sessions).sort((a, b) => (b.lastActivity || 0) - (a.lastActivity || 0));
}
// Locate the transcript file for a sessionId — live dir first, then the backup mirror.
function findTranscript(id) {
const bases = [PROJECTS_DIR, path.join(backupDirPath(), 'projects')];
for (const base of bases) {
let projDirs = [];
try { projDirs = fs.readdirSync(base); } catch { continue; }
for (const dir of projDirs) {
const f = path.join(base, dir, id + '.jsonl');
if (fs.existsSync(f)) return f;
}
}
return null;
}
// Full parse of a single session (on demand): summary, prompt history, images.
function sessionDetail(id) {
return new Promise(resolve => {
const file = findTranscript(id);
if (!file) return resolve({ error: 'Session-Datei nicht gefunden' });
const out = {
sessionId: id, file, messageCount: 0, userCount: 0, assistantCount: 0,
prompts: [], images: [], firstTs: null, lastTs: null,
cwd: null, gitBranch: null, customTitle: null, aiTitle: null,
};
const MAX_IMAGES = 12;
const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
rl.on('line', line => {
const s = line.trim();
if (!s || s[0] !== '{') return;
let d; try { d = JSON.parse(s); } catch { return; }
if (d.type === 'custom-title' && d.customTitle) out.customTitle = d.customTitle;
if (d.type === 'ai-title' && d.aiTitle) out.aiTitle = d.aiTitle;
if (d.type !== 'user' && d.type !== 'assistant') return;
if (d.cwd) out.cwd = d.cwd;
if (d.gitBranch) out.gitBranch = d.gitBranch;
if (d.timestamp) { if (!out.firstTs) out.firstTs = d.timestamp; out.lastTs = d.timestamp; }
out.messageCount++;
if (d.type === 'user') out.userCount++; else out.assistantCount++;
const content = d.message && d.message.content;
if (Array.isArray(content)) {
for (const c of content) {
if (!c || typeof c !== 'object') continue;
if (c.type === 'image' && c.source && c.source.data && out.images.length < MAX_IMAGES) {
out.images.push('data:' + (c.source.media_type || 'image/png') + ';base64,' + c.source.data);
}
}
}
if (d.type === 'user') {
const t = extractText(content);
if (t && !t.startsWith('<') && !t.startsWith('[') && t.length > 1) {
out.prompts.push({ ts: d.timestamp || null, text: t.slice(0, 600) });
}
}
});
rl.on('close', () => {
out.goal = out.prompts.length ? out.prompts[0].text : null;
out.lastPrompt = out.prompts.length ? out.prompts[out.prompts.length - 1].text : null;
resolve(out);
});
rl.on('error', () => resolve(out));
});
}
// First image of a session (for project tiles). Caps bytes read; caches by mtime.
const thumbCache = {};
function sessionThumb(id) {
return new Promise(resolve => {
const file = findTranscript(id);
if (!file) return resolve(null);
let st; try { st = fs.statSync(file); } catch { return resolve(null); }
const c = thumbCache[id];
if (c && c.mtime === st.mtimeMs) return resolve(c.image);
let done = false;
const stream = fs.createReadStream(file, { encoding: 'utf8', start: 0, end: 15 * 1024 * 1024 });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
const finish = img => {
if (done) return; done = true;
thumbCache[id] = { mtime: st.mtimeMs, image: img };
try { rl.close(); stream.destroy(); } catch {}
resolve(img);
};
rl.on('line', line => {
if (done || line.indexOf('"type":"image"') < 0) return;
try {
const d = JSON.parse(line.trim());
const content = d.message && d.message.content;
if (Array.isArray(content)) for (const x of content)
if (x && x.type === 'image' && x.source && x.source.data)
return finish('data:' + (x.source.media_type || 'image/png') + ';base64,' + x.source.data);
} catch {}
});
rl.on('close', () => finish(null));
rl.on('error', () => finish(null));
});
}
// Prompt markers per session for the Gantt timeline. Caches by mtime.
const markerCache = {};
function sessionMarkers(id, file, mtime) {
return new Promise(resolve => {
const c = markerCache[id];
if (c && c.mtime === mtime) return resolve(c);
const o = { sessionId: id, mtime, firstTs: null, lastTs: null, prompts: [], msgCount: 0 };
const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
rl.on('line', line => {
const s = line.trim();
if (!s || s[0] !== '{') return;
let d; try { d = JSON.parse(s); } catch { return; }
if (d.type !== 'user' && d.type !== 'assistant') return;
o.msgCount++;
const t = d.timestamp ? Date.parse(d.timestamp) : null;
if (t) { if (!o.firstTs) o.firstTs = t; o.lastTs = t; }
if (d.type === 'user' && t) {
const tx = extractText(d.message && d.message.content);
if (tx && !tx.startsWith('<') && !tx.startsWith('[') && tx.length > 1)
o.prompts.push({ t, text: tx.slice(0, 110) });
}
});
rl.on('close', () => { markerCache[id] = o; resolve(o); });
rl.on('error', () => resolve(o));
});
}
async function timelineData() {
const res = [];
let projDirs = [];
try { projDirs = fs.readdirSync(PROJECTS_DIR); } catch {}
for (const dir of projDirs) {
let files = [];
try { files = fs.readdirSync(path.join(PROJECTS_DIR, dir)).filter(f => f.endsWith('.jsonl')); } catch { continue; }
for (const f of files) {
const file = path.join(PROJECTS_DIR, dir, f);
let st; try { st = fs.statSync(file); } catch { continue; }
res.push(await sessionMarkers(f.replace(/\.jsonl$/, ''), file, st.mtimeMs));
}
}
return res;
}
// ---------- git backup status ----------
const projGitCache = {}; // cwd -> {t, status}
function gitStatus(dir) {
const c = projGitCache[dir];
if (c && Date.now() - c.t < 10000) return c.status;
const run = args => {
try { return execSync(`git -C "${dir}" ${args}`, { stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 }).toString().trim(); }
catch { return null; }
};
const s = { git: false, remote: null, branch: null, dirty: false, ahead: 0, hasUpstream: false, lastCommit: null };
if (run('rev-parse --is-inside-work-tree') === 'true') {
s.git = true;
s.remote = run('config --get remote.origin.url');
s.branch = run('rev-parse --abbrev-ref HEAD');
s.dirty = !!run('status --porcelain');
s.lastCommit = run('log -1 --format=%cI');
const up = run('rev-parse --abbrev-ref --symbolic-full-name @{u}');
if (up) { s.hasUpstream = true; const n = run('rev-list --count @{u}..HEAD'); s.ahead = n ? (parseInt(n, 10) || 0) : 0; }
}
projGitCache[dir] = { t: Date.now(), status: s };
return s;
}
// unique project folders (from session cwds) + their backup status
async function listProjects() {
const sessions = await scanSessions();
const map = {};
for (const s of sessions) {
if (!s.cwd) continue;
const key = s.cwd.toLowerCase();
if (!map[key]) map[key] = { cwd: s.cwd, project: s.project, sessions: 0, lastActivity: 0 };
map[key].sessions++;
map[key].lastActivity = Math.max(map[key].lastActivity, s.lastActivity || 0);
}
const out = [];
for (const p of Object.values(map)) {
let exists = true;
try { fs.accessSync(p.cwd); } catch { exists = false; }
out.push(Object.assign({}, p, { exists, git: exists ? gitStatus(p.cwd) : null }));
}
out.sort((a, b) => b.lastActivity - a.lastActivity);
return out;
}
// ---------- session-history backup ----------
function backupDirPath() { const d = loadSettings().backupDir; return (d && d.trim()) ? d.trim() : DEFAULT_BACKUP_DIR; }
let backupState = { running: false, lastBackup: null, lastResult: null };
function walkJsonl(root, rel, cb) {
let ents = [];
try { ents = fs.readdirSync(root, { withFileTypes: true }); } catch { return; }
for (const e of ents) {
const full = path.join(root, e.name);
const r = rel ? rel + '/' + e.name : e.name;
if (e.isDirectory()) walkJsonl(full, r, cb);
else if (e.name.endsWith('.jsonl')) cb(full, r);
}
}
function gitRun(dir, args) { return execSync(`git -C "${dir}" ${args}`, { stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000 }).toString(); }
async function backupSessions() {
if (backupState.running) return backupState.lastResult || { ok: false, error: 'already running' };
backupState.running = true;
const dir = backupDirPath();
const res = { ok: false, copied: 0, committed: false, pushed: false, dir, remote: '', error: null, ts: Date.now() };
try {
fs.mkdirSync(dir, { recursive: true });
let isRepo = false;
try { if (gitRun(dir, 'rev-parse --is-inside-work-tree').trim() === 'true') isRepo = true; } catch {}
if (!isRepo) gitRun(dir, 'init');
// incremental copy of all transcripts into <dir>/projects mirror
const destRoot = path.join(dir, 'projects');
walkJsonl(PROJECTS_DIR, '', (full, rel) => {
const dst = path.join(destRoot, rel);
let need = true;
try { const a = fs.statSync(full), b = fs.statSync(dst); need = (a.size !== b.size || a.mtimeMs > b.mtimeMs); } catch { need = true; }
if (need) { fs.mkdirSync(path.dirname(dst), { recursive: true }); fs.copyFileSync(full, dst); res.copied++; }
});
gitRun(dir, 'add -A');
try { gitRun(dir, `commit -m "Session backup ${new Date().toISOString()}"`); res.committed = true; }
catch { /* nothing to commit */ }
const remote = (loadSettings().backupRemote || '').trim();
res.remote = remote;
if (remote) {
let hasOrigin = false;
try { gitRun(dir, 'remote get-url origin'); hasOrigin = true; } catch {}
if (!hasOrigin) gitRun(dir, `remote add origin "${remote}"`);
else { try { if (gitRun(dir, 'remote get-url origin').trim() !== remote) gitRun(dir, `remote set-url origin "${remote}"`); } catch {} }
const br = (gitRun(dir, 'rev-parse --abbrev-ref HEAD').trim()) || 'master';
gitRun(dir, `push -u origin ${br}`); res.pushed = true;
}
res.ok = true;
} catch (e) { res.error = (e.stderr && e.stderr.toString()) || e.message; }
backupState.running = false; backupState.lastBackup = res.ts; backupState.lastResult = res;
return res;
}
// ---------- full-text search over transcripts ----------
function makeSnippet(text, term) {
const i = text.toLowerCase().indexOf(term);
if (i < 0) return null;
const start = Math.max(0, i - 60), end = Math.min(text.length, i + term.length + 90);
return (start > 0 ? '…' : '') + text.slice(start, end).replace(/\s+/g, ' ').trim() + (end < text.length ? '…' : '');
}
function searchFile(file, terms) {
return new Promise(resolve => {
const seen = new Set(); let count = 0; const snippets = [];
const rl = readline.createInterface({ input: fs.createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
rl.on('line', line => {
const low = line.toLowerCase();
let hit = null;
for (const term of terms) if (low.indexOf(term) >= 0) { seen.add(term); if (!hit) hit = term; }
if (hit) {
count++;
if (snippets.length < 3) {
try {
const d = JSON.parse(line.trim());
if (d.type === 'user' || d.type === 'assistant') {
const txt = extractText(d.message && d.message.content);
const sn = txt && makeSnippet(txt, hit);
if (sn) snippets.push({ role: d.type, text: sn });
}
} catch {}
}
}
});
rl.on('close', () => resolve({ matchedAll: terms.every(t => seen.has(t)), count, snippets }));
rl.on('error', () => resolve({ matchedAll: false, count: 0, snippets: [] }));
});
}
async function searchTranscripts(q) {
const terms = q.toLowerCase().split(/\s+/).filter(Boolean);
if (!terms.length) return [];
const seenIds = new Set(); const files = [];
for (const base of [PROJECTS_DIR, path.join(backupDirPath(), 'projects')]) {
let dirs = [];
try { dirs = fs.readdirSync(base); } catch { continue; }
for (const d of dirs) {
let list = [];
try { list = fs.readdirSync(path.join(base, d)).filter(f => f.endsWith('.jsonl')); } catch { continue; }
for (const f of list) {
const id = f.replace(/\.jsonl$/, '');
if (seenIds.has(id)) continue;
seenIds.add(id);
files.push({ id, file: path.join(base, d, f) });
}
}
}
const results = [];
for (const { id, file } of files) {
const r = await searchFile(file, terms);
if (r.matchedAll) results.push({ sessionId: id, count: r.count, snippets: r.snippets });
}
results.sort((a, b) => b.count - a.count);
return results.slice(0, 100);
}
// ---------- http ----------
function send(res, code, body, type = 'application/json') {
res.writeHead(code, { 'Content-Type': type, 'Cache-Control': 'no-store' });
res.end(typeof body === 'string' ? body : JSON.stringify(body));
}
function readBody(req) {
return new Promise(resolve => {
let b = ''; req.on('data', c => (b += c)); req.on('end', () => { try { resolve(JSON.parse(b)); } catch { resolve({}); } });
});
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`);
try {
if (url.pathname === '/') {
return send(res, 200, fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8'), 'text/html; charset=utf-8');
}
if (url.pathname.startsWith('/lang/')) {
const name = path.basename(url.pathname);
if (!/^[a-z0-9_-]+\.json$/i.test(name)) return send(res, 400, { error: 'bad name' });
const file = path.join(LANG_DIR, name);
if (!fs.existsSync(file)) return send(res, 404, { error: 'not found' });
return send(res, 200, fs.readFileSync(file, 'utf8'), 'application/json; charset=utf-8');
}
if (url.pathname === '/api/sessions') {
const sessions = await scanSessions();
const state = safeReadJson(STATE_FILE, {});
let htmlVersion = 0;
try { htmlVersion = fs.statSync(path.join(__dirname, 'index.html')).mtimeMs; } catch {}
return send(res, 200, { sessions, state, scannedAt: Date.now(), htmlVersion });
}
if (url.pathname === '/api/session') {
const id = url.searchParams.get('id');
if (!id) return send(res, 400, { error: 'id fehlt' });
return send(res, 200, await sessionDetail(id));
}
if (url.pathname === '/api/projects') {
return send(res, 200, { projects: await listProjects() });
}
if (url.pathname === '/api/backup-status') {
const cfg = loadSettings();
return send(res, 200, {
dir: backupDirPath(), remote: (cfg.backupRemote || '').trim(),
intervalHours: +cfg.backupIntervalHours || 0,
running: backupState.running, lastBackup: backupState.lastBackup, lastResult: backupState.lastResult,
});
}
if (url.pathname === '/api/backup-run' && req.method === 'POST') {
return send(res, 200, await backupSessions());
}
if (url.pathname === '/api/git-push' && req.method === 'POST') {
const { cwd, commit } = await readBody(req);
if (!cwd) return send(res, 400, { ok: false, error: 'cwd fehlt' });
const steps = [];
const run = (args, label) => {
try {
const o = execSync(`git -C "${cwd}" ${args}`, { stdio: ['ignore', 'pipe', 'pipe'], timeout: 120000 }).toString();
steps.push({ label, ok: true, out: o.trim() }); return true;
} catch (e) {
steps.push({ label, ok: false, out: ((e.stdout && e.stdout.toString()) || '') + ((e.stderr && e.stderr.toString()) || e.message) });
return false;
}
};
if (commit) {
run('add -A', 'add');
try { execSync(`git -C "${cwd}" commit -m "Backup ${new Date().toISOString()}"`, { stdio: ['ignore', 'pipe', 'pipe'] }); steps.push({ label: 'commit', ok: true }); }
catch { steps.push({ label: 'commit', ok: true, out: 'nothing to commit' }); }
}
const ok = run('push', 'push');
delete projGitCache[cwd];
return send(res, 200, { ok, steps });
}
if (url.pathname === '/api/search') {
const q = (url.searchParams.get('q') || '').trim();
if (!q) return send(res, 200, { q, results: [] });
return send(res, 200, { q, results: await searchTranscripts(q) });
}
if (url.pathname === '/api/thumb') {
const id = url.searchParams.get('id');
if (!id) return send(res, 400, { error: 'id fehlt' });
return send(res, 200, { image: await sessionThumb(id) });
}
if (url.pathname === '/api/timeline') {
return send(res, 200, { markers: await timelineData() });
}
if (url.pathname === '/api/state' && req.method === 'POST') {
const body = await readBody(req); // { sessionId, patch: {column?, notes?, archived?} }
const state = safeReadJson(STATE_FILE, {});
if (body.sessionId) {
state[body.sessionId] = Object.assign({}, state[body.sessionId], body.patch || {});
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}
return send(res, 200, { ok: true, state });
}
if (url.pathname === '/api/open-folder' && req.method === 'POST') {
const { cwd } = await readBody(req);
if (!cwd) return send(res, 400, { ok: false, error: 'cwd fehlt' });
if (process.platform === 'win32') exec(`start "" "${cwd}"`, { shell: 'cmd.exe' }, () => {});
else if (process.platform === 'darwin') exec(`open "${cwd}"`, () => {});
else exec(`xdg-open "${cwd}"`, () => {});
return send(res, 200, { ok: true });
}
if (url.pathname === '/api/settings') {
if (req.method === 'POST') {
const body = await readBody(req);
const cur = safeReadJson(CONFIG_FILE, {});
const next = Object.assign(cur, body || {});
fs.writeFileSync(CONFIG_FILE, JSON.stringify(next, null, 2));
return send(res, 200, { ok: true, values: loadSettings() });
}
return send(res, 200, {
schema: buildSchema(),
values: loadSettings(),
languages: scanLanguages(),
platform: process.platform,
terminalPresets: Object.keys(TERMINAL_PRESETS[process.platform] || {}),
terminalTemplates: TERMINAL_PRESETS[process.platform] || {},
});
}
if (url.pathname === '/api/resume' && req.method === 'POST') {
const { sessionId, cwd } = await readBody(req);
if (!sessionId || !cwd) return send(res, 400, { ok: false, error: 'sessionId/cwd fehlt' });
const cmd = resolveTerminalCmd(cwd, sessionId);
if (!cmd) return send(res, 500, { ok: false, error: 'Kein Terminal konfiguriert' });
exec(cmd, process.platform === 'win32' ? { shell: 'cmd.exe' } : {}, e => { if (e) console.error('resume:', e.message); });
return send(res, 200, { ok: true });
}
send(res, 404, { error: 'not found' });
} catch (e) {
send(res, 500, { error: String(e && e.stack || e) });
}
});
PORT = process.env.PORT || loadSettings().port || PORT;
server.listen(PORT, () => {
console.log(`Claude Session Manager -> http://localhost:${PORT}`);
console.log(`Scanning: ${CLAUDE_DIR}`);
// auto-backup: run shortly after start, then on the configured interval
setTimeout(() => { backupSessions().then(r => console.log(`Backup: ${r.copied} new file(s), committed=${r.committed}, pushed=${r.pushed}${r.error ? ', error: ' + r.error : ''}`)); }, 4000);
const hrs = +loadSettings().backupIntervalHours || 0;
if (hrs > 0) setInterval(() => backupSessions(), hrs * 3600 * 1000);
});