-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1560 lines (1379 loc) · 56.1 KB
/
server.js
File metadata and controls
1560 lines (1379 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import fs from 'fs';
import path from 'path';
import os from 'os';
import { fileURLToPath } from 'url';
import { execFile, execFileSync } from 'child_process';
import AnthropicBedrock from '@anthropic-ai/bedrock-sdk';
import { getClient as getValkeyClient, isReady as isValkeyReady } from './lib/valkey.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = 6767;
const PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
const GLOBAL_RADAR_CONFIG = path.join(os.homedir(), '.claude', 'radar.json');
const { currentUsername, avatarUrl } = (() => {
// 1. gh CLI — gives both login and avatar_url in one call
try {
const raw = execFileSync('gh', ['api', 'user'], { encoding: 'utf-8', timeout: 5000 });
const user = JSON.parse(raw);
if (user.login) return { currentUsername: user.login, avatarUrl: user.avatar_url || '' };
} catch {}
// 2. Explicit git config (username only, no avatar)
try {
const r = execFileSync('git', ['config', 'github.user'], { encoding: 'utf-8', timeout: 2000 }).trim();
if (r) return { currentUsername: r, avatarUrl: '' };
} catch {}
// 3. Env var
if (process.env.GITHUB_USERNAME) return { currentUsername: process.env.GITHUB_USERNAME, avatarUrl: '' };
// 4. OS username, no avatar
try { return { currentUsername: os.userInfo().username, avatarUrl: '' }; } catch {}
return { currentUsername: '', avatarUrl: '' };
})();
const bedrock = new AnthropicBedrock({ aws_region: process.env.AWS_REGION || 'eu-west-1' });
// Cache parsed session files so we don't re-read unchanged files every poll
const fileCache = new Map(); // key: filePath, value: { mtime, data }
// Activity map — populated by hook-based POST /api/activity events.
// key: sessionId, value: { event, timestamp }
const activityMap = new Map();
function setActivity(sessionId, data) {
activityMap.set(sessionId, data);
try {
const filePath = findSessionFile(sessionId);
if (filePath) {
const projPath = resolveProjectPath(path.basename(path.dirname(filePath)));
for (const { client, swimlane } of getProjectPushTargets(projPath)) {
client.set(`radar:${swimlane}:activity:${sessionId}`, JSON.stringify(data), 'EX', 7200).catch(() => {});
}
}
} catch {}
}
function getActivity(sessionId) {
return activityMap.get(sessionId);
}
// Persistent cache helper: stores { value: string, fileSize: number } per session.
// Reads from JSON file at startup; writes back to JSON file on every set.
// Per-project Valkey sync is handled separately via syncToValkey().
function createPersistentCache(filePath) {
const map = new Map();
try {
const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
for (const [id, entry] of Object.entries(data)) {
// Migrate old { title, fileSize } format
if (entry.value === undefined && entry.title !== undefined) {
map.set(id, { value: entry.title, fileSize: entry.fileSize });
} else {
map.set(id, entry);
}
}
} catch {}
return {
get(id) { return map.get(id); },
has(id) { return map.has(id); },
loadEntry(id, entry) { map.set(id, entry); },
set(id, value, fileSize) {
map.set(id, { value, fileSize });
const obj = Object.fromEntries(map);
fs.writeFileSync(filePath, JSON.stringify(obj), 'utf-8');
},
needsRefresh(id, sessionFilePath) {
const cached = map.get(id);
if (!cached || !cached.value) return true;
try {
const currentSize = fs.statSync(sessionFilePath).size;
return currentSize - cached.fileSize >= 10240;
} catch { return false; }
},
};
}
const titleCache = createPersistentCache(path.join(__dirname, 'titles.json'));
const blurbCache = createPersistentCache(path.join(__dirname, 'blurbs.json'));
// swimlaneKey → [projectPath, ...] — rebuilt on each GET /api/sessions, used by config endpoint
const swimlaneProjectPaths = new Map();
// Remote sessions pulled from subscriptions — key: "{url}:{swimlane}", value: [session, ...]
const remoteSessionsCache = new Map();
let lastSessionPush = 0;
function makeSlug(name, branch) {
const base = (name || 'unnamed').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
const b = (branch || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
return (b && b !== 'main' && b !== 'master') ? `${base}-${b}` : base;
}
function readGlobalRadarConfig() {
try { return JSON.parse(fs.readFileSync(GLOBAL_RADAR_CONFIG, 'utf-8')); } catch { return null; }
}
// Returns all push targets for a project: [{ client, swimlane }]
function getProjectPushTargets(projectPath) {
const pushList = readRadarConfig(projectPath)?.push;
if (!Array.isArray(pushList) || pushList.length === 0) return [];
return pushList
.filter(p => p?.valkey?.url)
.map(p => ({
client: getValkeyClient(p.valkey.url, p.valkey.password || ''),
swimlane: p.swimlane || 'default',
}));
}
// Push a cache entry to all of the project's Valkey targets (fire-and-forget)
// cacheType is 'titles' or 'blurbs' — keyed as radar:{swimlane}:{cacheType}
function syncToValkey(filePath, cacheType, sessionId, value, fileSize) {
if (!value) return;
try {
const projPath = resolveProjectPath(path.basename(path.dirname(filePath)));
for (const { client, swimlane } of getProjectPushTargets(projPath)) {
client.hset(`radar:${swimlane}:${cacheType}`, sessionId, JSON.stringify({ value, fileSize }))
.catch(() => {});
}
} catch {}
}
async function pushSessionsToValkey(projects) {
for (const project of projects) {
if (!project.valkeyPush?.length) continue;
for (const { url, swimlane } of project.valkeyPush) {
const radarConfig = readRadarConfig(project.projectPath);
const password = radarConfig?.push?.find(p => p?.valkey?.url === url)?.valkey?.password || '';
const client = getValkeyClient(url, password);
if (client.status !== 'ready') continue;
for (const s of project.sessions) {
const key = `${s.username}:${s.sessionId}`;
const payload = JSON.stringify({
sessionId: s.sessionId, username: s.username, avatarUrl: s.avatarUrl,
title: s.title, blurb: s.blurb, status: s.status,
modified: s.modified, created: s.created,
messageCount: s.messageCount, gitBranch: s.gitBranch, isSidechain: s.isSidechain,
slug: project.slug, projectName: project.projectName,
swimlaneTitle: project.swimlaneTitle, repoUrl: project.repoUrl, branch: project.branch,
pushedAt: Date.now(),
});
client.hset(`radar:${swimlane}:sessions`, key, payload).catch(() => {});
}
}
}
}
function maybePushSessionsToValkey(projects) {
if (Date.now() - lastSessionPush < 30000) return;
lastSessionPush = Date.now();
pushSessionsToValkey(projects).catch(() => {});
}
async function pullSubscriptions() {
const subs = (readGlobalRadarConfig()?.subscriptions || []).filter(s => s?.valkey?.url);
for (const sub of subs) {
const swimlane = sub.swimlane || 'default';
const cacheKey = `${sub.valkey.url}:${swimlane}`;
try {
const client = getValkeyClient(sub.valkey.url, sub.valkey.password || '');
await Promise.race([
new Promise(r => client.status === 'ready' ? r() : client.once('ready', r)),
new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 3000)),
]);
const hash = await client.hgetall(`radar:${swimlane}:sessions`);
const sessions = Object.values(hash || {})
.map(v => { try { return JSON.parse(v); } catch {} })
.filter(Boolean)
.filter(s => Date.now() - s.pushedAt < 86400000);
remoteSessionsCache.set(cacheKey, sessions);
const [titles, blurbs] = await Promise.all([
client.hgetall(`radar:${swimlane}:titles`),
client.hgetall(`radar:${swimlane}:blurbs`),
]);
if (titles) for (const [id, j] of Object.entries(titles)) try { titleCache.loadEntry(id, JSON.parse(j)); } catch {}
if (blurbs) for (const [id, j] of Object.entries(blurbs)) try { blurbCache.loadEntry(id, JSON.parse(j)); } catch {}
} catch {}
}
}
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Find the .jsonl file for a session ID by scanning project dirs
function findSessionFile(sessionId) {
try {
for (const dir of fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })) {
if (!dir.isDirectory()) continue;
const fp = path.join(PROJECTS_DIR, dir.name, sessionId + '.jsonl');
if (fs.existsSync(fp)) return fp;
}
} catch {}
return null;
}
// ── Progressive compaction ─────────────────────────────────────────────────
// One compaction file per session: ~/.claude/radar-compact/{dirName}/{sessionId}.json
// { summary, coveredUpToBytes, generatedAt }
//
// The summary covers bytes 0..coveredUpToBytes. When the session grows, we extend
// the summary by incorporating new content in CHUNK-sized increments:
// new_summary = compact(old_summary + raw_new_content)
// This ensures each title/blurb generation call costs at most one extra compact call
// once the session is larger than one chunk.
const CHUNK = 131072; // 128KB
const COMPACT_BASE = path.join(os.homedir(), '.claude', 'radar-compact');
// Extract user/assistant text turns from a raw .jsonl text blob
function extractTurns(text) {
const seen = new Set();
const turns = [];
for (const line of text.split('\n')) {
if (!line.trim()) continue;
try {
const obj = JSON.parse(line);
if (obj.type !== 'user' && obj.type !== 'assistant') continue;
const id = obj.message?.id || obj.uuid;
if (id) { if (seen.has(id)) continue; seen.add(id); }
const content = obj.message?.content;
let t = '';
if (typeof content === 'string') t = content;
else if (Array.isArray(content)) {
t = content.filter(c => c?.type === 'text' && c.text).map(c => c.text).join(' ');
}
if (t.trim()) turns.push({ role: obj.type, text: t.slice(0, 1000) });
} catch {}
}
return turns;
}
function compactFilePath(dirName, sessionId) {
return path.join(COMPACT_BASE, dirName, `${sessionId}.json`);
}
function readCompaction(dirName, sessionId) {
try {
return JSON.parse(fs.readFileSync(compactFilePath(dirName, sessionId), 'utf-8'));
} catch { return null; }
}
function writeCompaction(dirName, sessionId, summary, coveredUpToBytes) {
const dir = path.join(COMPACT_BASE, dirName);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(compactFilePath(dirName, sessionId), JSON.stringify({ summary, coveredUpToBytes, generatedAt: Date.now() }), 'utf-8');
}
// Read bytes [from, to) from an open fd and return as formatted turn text
function readChunkAsText(fd, from, to) {
const buf = Buffer.alloc(to - from);
fs.readSync(fd, buf, 0, to - from, from);
const turns = extractTurns(buf.toString('utf-8'));
return turns.map(t => `${t.role}: ${t.text}`).join('\n\n');
}
// Compact a text blob into a dense summary via Haiku
async function compactWithHaiku(inputText) {
const resp = await bedrock.messages.create({
model: 'eu.anthropic.claude-haiku-4-5-20251001-v1:0',
max_tokens: 800,
messages: [{
role: 'user',
content: `Summarize this coding session transcript into a dense summary (300-500 words) preserving: the main goal, key decisions, technologies and files involved, and current state of progress. This summary will be used alongside newer messages for final summarization.\n\n${inputText.slice(0, 60000)}`,
}],
});
return (resp.content[0]?.text || '').trim();
}
// Return the best available conversation context for title/blurb generation.
// SYNCHRONOUS — never calls Haiku. Uses stored compaction if available, else raw head+tail.
// Compaction building is handled separately by buildSessionCompaction().
function getConversationContext(sessionId, filePath) {
const size = fs.statSync(filePath).size;
const dirName = path.basename(path.dirname(filePath));
const fd = fs.openSync(filePath, 'r');
try {
if (size <= CHUNK) {
const buf = Buffer.alloc(size);
fs.readSync(fd, buf, 0, size, 0);
const turns = extractTurns(buf.toString('utf-8'));
return turns.map(t => `${t.role}: ${t.text}`).join('\n\n');
}
const tailStart = size - CHUNK;
const tailText = readChunkAsText(fd, tailStart, size);
const existing = readCompaction(dirName, sessionId);
let headText;
if (existing && existing.coveredUpToBytes >= tailStart) {
// Compaction covers the entire head — best case
headText = existing.summary;
} else if (existing) {
// Compaction is stale: use it + raw bridge to tailStart
const bridgeText = readChunkAsText(fd, existing.coveredUpToBytes, tailStart);
headText = bridgeText ? `${existing.summary}\n\n${bridgeText}` : existing.summary;
} else {
// No compaction yet: fall back to raw first CHUNK of head
const headEnd = Math.min(tailStart, CHUNK);
headText = readChunkAsText(fd, 0, headEnd);
}
return `${headText}\n\n${tailText}`;
} finally {
fs.closeSync(fd);
}
}
// Build or extend the stored compaction for a session.
// Called from the background compaction pass, not from title/blurb generation.
async function buildSessionCompaction(sessionId, filePath) {
const size = fs.statSync(filePath).size;
if (size <= CHUNK) return; // No compaction needed for small sessions
const dirName = path.basename(path.dirname(filePath));
const tailStart = size - CHUNK;
const existing = readCompaction(dirName, sessionId);
if (existing && existing.coveredUpToBytes >= tailStart) return; // Already current
let summary = existing?.summary || '';
let coveredUpTo = existing?.coveredUpToBytes || 0;
const fd = fs.openSync(filePath, 'r');
try {
while (coveredUpTo < tailStart) {
const nextBoundary = Math.min(coveredUpTo + CHUNK, tailStart);
const rawText = readChunkAsText(fd, coveredUpTo, nextBoundary);
const input = summary
? `Previous summary:\n${summary}\n\nContinued:\n${rawText}`
: rawText;
summary = await compactWithHaiku(input);
coveredUpTo = nextBoundary;
writeCompaction(dirName, sessionId, summary, coveredUpTo);
}
} finally {
fs.closeSync(fd);
}
}
// Detect Haiku refusal/meta-responses (e.g. "I don't have a coding session...")
function isHaikuRefusal(text) {
if (!text) return false;
const t = text.toLowerCase();
return (t.startsWith('i don') || t.startsWith('i can') || t.startsWith('i need')
|| t.startsWith('there') || t.startsWith('no coding')
|| t.includes('coding session') || t.includes('to summarize'));
}
// Generate a tweet-length blurb via Haiku
async function generateBlurb(sessionId) {
const filePath = findSessionFile(sessionId);
if (!filePath) return;
let fileSize = 0;
try { fileSize = fs.statSync(filePath).size; } catch { return; }
let convo = '';
try { convo = getConversationContext(sessionId, filePath); } catch {}
if (!convo) {
blurbCache.set(sessionId, '', fileSize);
return;
}
try {
const resp = await bedrock.messages.create({
model: 'eu.anthropic.claude-haiku-4-5-20251001-v1:0',
max_tokens: 120,
messages: [{
role: 'user',
content: `Summarize this coding session in one sentence (under 200 chars), like a tweet. Focus on what was accomplished or is in progress. No hashtags or emoji. Just the substance.\n\n${convo}`,
}],
});
let blurb = (resp.content[0] && resp.content[0].text || '').trim();
if (isHaikuRefusal(blurb)) blurb = '';
blurbCache.set(sessionId, blurb, fileSize);
syncToValkey(filePath, 'blurbs', sessionId, blurb, fileSize);
} catch (err) {
console.error('Blurb generation failed:', err.message);
blurbCache.set(sessionId, '', fileSize);
}
}
// needsTitle/needsBlurb are just wrappers around the cache's needsRefresh
function needsTitle(sessionId, filePath) {
return titleCache.needsRefresh(sessionId, filePath);
}
// Generate a short title via Haiku
async function generateTitle(sessionId) {
const filePath = findSessionFile(sessionId);
if (!filePath) return;
let fileSize = 0;
try { fileSize = fs.statSync(filePath).size; } catch { return; }
let convo = '';
try { convo = getConversationContext(sessionId, filePath); } catch {}
if (!convo) {
titleCache.set(sessionId, '', fileSize);
return;
}
try {
const resp = await bedrock.messages.create({
model: 'eu.anthropic.claude-haiku-4-5-20251001-v1:0',
max_tokens: 40,
messages: [{
role: 'user',
content: `Summarize this coding session in 3-8 words as a title. No quotes, no punctuation, no preamble. Just the title.\n\n${convo}`,
}],
});
let title = (resp.content[0] && resp.content[0].text || '').trim();
// Discard Haiku refusals/meta-responses
if (isHaikuRefusal(title)) title = '';
titleCache.set(sessionId, title, fileSize);
syncToValkey(filePath, 'titles', sessionId, title, fileSize);
} catch (err) {
console.error('Title generation failed:', err.message);
titleCache.set(sessionId, '', fileSize);
}
}
// Hook endpoint — receives activity events from Claude Code hooks
app.post('/api/activity', (req, res) => {
const { sessionId, event } = req.body || {};
if (!sessionId || !event) return res.status(400).json({ error: 'missing sessionId or event' });
setActivity(sessionId, { event, timestamp: Date.now() });
// Generate title and blurb on stop events (if stale)
if (event === 'stop') {
const filePath = findSessionFile(sessionId);
if (filePath) {
if (needsTitle(sessionId, filePath)) generateTitle(sessionId).catch(() => {});
if (blurbCache.needsRefresh(sessionId, filePath)) generateBlurb(sessionId).catch(() => {});
}
}
res.json({ ok: true });
});
// Determine session status. Uses hook-reported activity when available,
// falls back to file-tail heuristics for sessions without hook data.
// Read tail lines from a .jsonl file (shared helper)
function readTailLines(filePath) {
try {
const fd = fs.openSync(filePath, 'r');
const stat = fs.fstatSync(fd);
const size = stat.size;
const readSize = Math.min(8192, size);
const buf = Buffer.alloc(readSize);
fs.readSync(fd, buf, 0, readSize, size - readSize);
fs.closeSync(fd);
return buf.toString('utf-8').split('\n').filter(l => l.trim());
} catch {}
return [];
}
// Read the last message (any type) from the tail of a .jsonl file
function readLastMessage(filePath) {
const lines = readTailLines(filePath);
for (let i = lines.length - 1; i >= 0; i--) {
try {
const obj = JSON.parse(lines[i]);
if (obj.type === 'assistant' || obj.type === 'user') return obj;
} catch { /* partial line */ }
}
return null;
}
// Read the last assistant-only message from the tail of a .jsonl file
function readLastAssistantMessage(filePath) {
const lines = readTailLines(filePath);
for (let i = lines.length - 1; i >= 0; i--) {
try {
const obj = JSON.parse(lines[i]);
if (obj.type === 'assistant') return obj;
} catch { /* partial line */ }
}
return null;
}
// Check if the last assistant message is waiting for user input:
// - Contains AskUserQuestion or ExitPlanMode tool use
// - Last text block ends with a question mark
function isWaitingForInput(lastMsg) {
if (!lastMsg || lastMsg.type !== 'assistant') return false;
const content = (lastMsg.message || {}).content;
if (!Array.isArray(content)) return false;
let lastText = '';
for (const c of content) {
if (!c || typeof c !== 'object') continue;
if (c.type === 'tool_use') {
const name = (c.name || '').toLowerCase();
if (name === 'askuserquestion' || name === 'exitplanmode') return true;
}
if (c.type === 'text' && c.text) {
lastText = c.text;
}
}
return lastText.trimEnd().endsWith('?');
}
function detectSessionStatus(sessionId, filePath, mtimeMs) {
const now = Date.now();
// Check hook-reported activity first
const activity = getActivity(sessionId);
if (activity) {
const ageMs = now - activity.timestamp;
if (activity.event === 'working' || activity.event === 'prompt') {
if (ageMs < 60000) return 'working';
return 'idle';
}
if (activity.event === 'stop') {
if (ageMs < 3600000) {
const lastMsg = readLastAssistantMessage(filePath);
return isWaitingForInput(lastMsg) ? 'waiting' : 'idle';
}
return 'idle';
}
if (activity.event === 'idle') {
// Don't downgrade to idle if the session is waiting for user input
const lastMsg = readLastAssistantMessage(filePath);
if (isWaitingForInput(lastMsg)) return 'waiting';
return 'idle';
}
}
// Fallback: file-based heuristic for sessions without hook data
const fileAge = now - mtimeMs;
if (fileAge < 30000) {
const lastMsg = readLastMessage(filePath);
if (!lastMsg) return 'idle';
if (lastMsg.type === 'assistant') {
const stopReason = (lastMsg.message || {}).stop_reason || null;
if (stopReason === null || stopReason === 'tool_use') return 'working';
}
if (lastMsg.type === 'user') {
const content = lastMsg.message && lastMsg.message.content;
if (Array.isArray(content)) {
for (const c of content) {
if (c && c.type === 'tool_result') return 'working';
}
}
return 'working';
}
}
if (fileAge < 3600000) {
const lastAssistant = readLastAssistantMessage(filePath);
return isWaitingForInput(lastAssistant) ? 'waiting' : 'idle';
}
return 'idle';
}
// Resolve a project dirName (e.g. "-Users-DavidCampey-clode-claude-kanban")
// back to a real filesystem path. Hyphens are ambiguous (path separator vs literal),
// so we walk the filesystem to find the matching directory.
const projectPathCache = new Map();
function resolveProjectPath(dirName) {
if (projectPathCache.has(dirName)) return projectPathCache.get(dirName);
const parts = dirName.replace(/^-/, '').split('-');
function walk(idx, currentPath) {
if (idx >= parts.length) {
try {
if (fs.statSync(currentPath).isDirectory()) return currentPath;
} catch {}
return null;
}
// Try consuming progressively more parts as a single segment (with hyphens)
for (let end = parts.length; end > idx; end--) {
const segment = parts.slice(idx, end).join('-');
const candidate = path.join(currentPath, segment);
const result = walk(end, candidate);
if (result) return result;
}
return null;
}
const resolved = walk(0, '/') || '/' + parts.join('/');
projectPathCache.set(dirName, resolved);
return resolved;
}
// Normalize a git remote URL to canonical HTTPS form
function normalizeGitUrl(url) {
url = url.trim();
const sshMatch = url.match(/^git@([^:]+):(.+)$/);
if (sshMatch) url = `https://${sshMatch[1]}/${sshMatch[2]}`;
return url.replace(/\.git$/, '');
}
// Parse [remote "name"] sections from git config text
function parseGitRemotes(text) {
const remotes = {};
let current = null;
for (const line of text.split('\n')) {
const secMatch = line.match(/^\[remote\s+"([^"]+)"\]/);
if (secMatch) { current = secMatch[1]; remotes[current] = {}; continue; }
if (current && line.match(/^\[/)) current = null;
if (current) {
const kv = line.match(/^\s*(\w+)\s*=\s*(.+)$/);
if (kv) remotes[current][kv[1]] = kv[2].trim();
}
}
return remotes;
}
// Cache git repo info — remotes don't change mid-session
const repoInfoCache = new Map();
function getRepoInfo(projectPath) {
if (repoInfoCache.has(projectPath)) return repoInfoCache.get(projectPath);
const empty = { repoUrl: '', branch: '' };
try {
let gitDir = path.join(projectPath, '.git');
let gitStat;
try { gitStat = fs.statSync(gitDir); } catch { repoInfoCache.set(projectPath, empty); return empty; }
// Worktree support: .git may be a file pointing to the real gitdir
if (!gitStat.isDirectory()) {
const content = fs.readFileSync(gitDir, 'utf-8').trim();
const m = content.match(/^gitdir:\s*(.+)$/);
if (!m) { repoInfoCache.set(projectPath, empty); return empty; }
gitDir = path.resolve(projectPath, m[1]);
}
let branch = '';
try {
const head = fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf-8').trim();
const m = head.match(/^ref:\s*refs\/heads\/(.+)$/);
if (m) branch = m[1];
} catch {}
let repoUrl = '';
try {
const configText = fs.readFileSync(path.join(gitDir, 'config'), 'utf-8');
const remotes = parseGitRemotes(configText);
const remote = remotes['origin'] || remotes[Object.keys(remotes)[0]];
if (remote && remote.url) repoUrl = normalizeGitUrl(remote.url);
} catch {}
const result = { repoUrl, branch };
repoInfoCache.set(projectPath, result);
return result;
} catch {
repoInfoCache.set(projectPath, empty);
return empty;
}
}
// Per-project radar.json config cache
const radarConfigCache = new Map();
function readRadarConfig(projectPath) {
const configPath = path.join(projectPath, '.claude', 'radar.json');
try {
const mtime = fs.statSync(configPath).mtimeMs;
const cached = radarConfigCache.get(projectPath);
if (cached && cached.mtime === mtime) return cached.config;
const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
radarConfigCache.set(projectPath, { mtime, config });
return config;
} catch {
return null;
}
}
// System artifacts injected by Claude Code that aren't real user prompts
const ARTIFACT_PREFIXES = [
'[Request interrupted',
'<local-command-',
'<command-name>',
'<command-message>',
'<ide_opened_file>',
];
function isArtifact(text) {
const t = text.trimStart();
return !t || ARTIFACT_PREFIXES.some(p => t.startsWith(p));
}
// Clean a title string: strip plan boilerplate, collapse whitespace, trim length
function cleanTitle(text) {
let t = text.replace(/^Implement the following plan:\s*/i, '');
t = t.replace(/^#\s*Plan:\s*/i, '');
t = t.replace(/<[^>]+>/g, ''); // strip XML-like tags
// Cut at markdown headers or section breaks
t = t.split(/\s*##\s/)[0];
t = t.split(/\s*\n\s*\n/)[0];
// Strip leading markdown header markers (e.g. "# Title" → "Title")
t = t.replace(/^#+\s*/, '');
t = t.replace(/\s+/g, ' ').trim();
// Skip system-injected boilerplate
if (t.startsWith('Base directory for this skill:')) t = '';
if (t.startsWith('This session is being continued')) t = '';
return t.slice(0, 80) || '';
}
// Read first user prompt, parent session ID, and estimated message count from a
// .jsonl file. Only reads the first ~32KB — enough for prompt/parent detection.
// Message count is estimated from file size (avg ~1.5KB per message turn) to avoid
// scanning potentially huge (100MB+) files.
// Uses cache to avoid re-reading unchanged files.
function parseSessionFile(filePath) {
let stat;
try {
stat = fs.statSync(filePath);
} catch {
return null;
}
const mtimeMs = stat.mtimeMs;
const cached = fileCache.get(filePath);
if (cached && cached.mtime === mtimeMs) return cached.data;
let firstPrompt = '';
let parentSessionId = '';
let messageCount = 0;
const sessionId = path.basename(filePath, '.jsonl');
let summary = '';
try {
const fd = fs.openSync(filePath, 'r');
const fileSize = fs.fstatSync(fd).size;
const headSize = Math.min(32768, fileSize);
const headBuf = Buffer.alloc(headSize);
fs.readSync(fd, headBuf, 0, headSize, 0);
// Also read tail for blurb extraction
const tailSize = Math.min(16384, fileSize);
const tailBuf = Buffer.alloc(tailSize);
fs.readSync(fd, tailBuf, 0, tailSize, fileSize - tailSize);
fs.closeSync(fd);
const head = headBuf.toString('utf-8');
const headLines = head.split('\n');
let hasMessages = false;
for (const line of headLines) {
if (!line.trim()) continue;
let obj;
try { obj = JSON.parse(line); } catch { continue; }
if (obj.type === 'user' || obj.type === 'assistant') hasMessages = true;
if (obj.type === 'user') {
if (!parentSessionId && obj.sessionId && obj.sessionId !== sessionId) {
parentSessionId = obj.sessionId;
}
if (!firstPrompt) {
const msg = obj.message;
if (msg && typeof msg === 'object') {
const ct = msg.content;
if (Array.isArray(ct)) {
for (const c of ct) {
if (c && c.type === 'text' && c.text && !isArtifact(c.text)) {
firstPrompt = c.text.slice(0, 200);
break;
}
}
} else if (typeof ct === 'string' && !isArtifact(ct)) {
firstPrompt = ct.slice(0, 200);
}
}
}
}
if (firstPrompt && parentSessionId) break;
}
// Extract summary from the tail
const tailLines = tailBuf.toString('utf-8').split('\n').filter(l => l.trim());
for (let i = tailLines.length - 1; i >= 0; i--) {
try {
const obj = JSON.parse(tailLines[i]);
if (obj.type === 'summary' && obj.summary) {
summary = obj.summary;
break;
}
} catch { /* partial line */ }
}
// Estimate message count from file size (~1.5KB per message turn on average)
// Mark as 0 if the head contained no user/assistant messages (empty session)
messageCount = hasMessages ? Math.max(1, Math.round(fileSize / 1500)) : 0;
} catch {
// Unreadable file
}
const data = { firstPrompt, messageCount, parentSessionId, summary };
fileCache.set(filePath, { mtime: mtimeMs, data });
return data;
}
app.get('/api/sessions', (req, res) => {
const projects = [];
let dirEntries;
try {
dirEntries = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true });
} catch {
return res.json({ projects: [] });
}
for (const dirent of dirEntries) {
if (!dirent.isDirectory()) continue;
const projectDir = path.join(PROJECTS_DIR, dirent.name);
// Read the index if it exists
let indexData = { entries: [] };
try {
const raw = fs.readFileSync(path.join(projectDir, 'sessions-index.json'), 'utf-8');
indexData = JSON.parse(raw);
} catch {
// No index — we'll still scan for .jsonl files
}
// Build a map of indexed sessions by ID
const indexedById = new Map();
for (const entry of (indexData.entries || [])) {
indexedById.set(entry.sessionId, entry);
}
// Scan for all .jsonl session files in this project directory
let files;
try {
files = fs.readdirSync(projectDir).filter(f => f.endsWith('.jsonl'));
} catch {
continue;
}
if (files.length === 0 && indexedById.size === 0) continue;
const rawSessions = [];
let projectPath = '';
let mostRecent = 0;
for (const file of files) {
const sessionId = path.basename(file, '.jsonl');
const filePath = path.join(projectDir, file);
// Get actual file timestamps
let stat;
try {
stat = fs.statSync(filePath);
} catch {
continue;
}
const lastActivity = stat.mtimeMs;
const fileCreated = stat.birthtimeMs || stat.ctimeMs;
// Always parse the file for parentSessionId and message count
const parsed = parseSessionFile(filePath);
const parentSessionId = parsed ? parsed.parentSessionId : '';
const indexed = indexedById.get(sessionId);
let title, firstPrompt, messageCount, gitBranch, created, isSidechain, status;
const blurbEntry = blurbCache.get(sessionId);
const blurb = blurbEntry ? blurbEntry.value : '';
const parsedSummary = parsed ? parsed.summary : '';
const titleEntry = titleCache.get(sessionId);
const cachedTitle = titleEntry ? titleEntry.value : '';
if (indexed) {
title = indexed.summary || cachedTitle || parsedSummary || '';
firstPrompt = indexed.firstPrompt || '';
messageCount = indexed.messageCount || (parsed ? parsed.messageCount : 0);
gitBranch = indexed.gitBranch || '';
created = indexed.created;
isSidechain = indexed.isSidechain || false;
status = detectSessionStatus(sessionId, filePath, lastActivity);
if (!projectPath) projectPath = indexed.projectPath || '';
} else {
firstPrompt = parsed ? parsed.firstPrompt : '';
messageCount = parsed ? parsed.messageCount : 0;
status = detectSessionStatus(sessionId, filePath, lastActivity);
title = cachedTitle || parsedSummary || '';
gitBranch = '';
created = new Date(fileCreated).toISOString();
isSidechain = false;
}
// Skip empty sessions (e.g. started and immediately abandoned)
if (messageCount === 0 && !firstPrompt) continue;
if (lastActivity > mostRecent) mostRecent = lastActivity;
rawSessions.push({
sessionId,
dirName: dirent.name,
username: currentUsername,
avatarUrl,
parentSessionId,
title: cleanTitle(title || firstPrompt) || '(no title)',
blurb: blurb || '',
firstPrompt: firstPrompt || '',
messageCount,
gitBranch,
status,
created: created || new Date(fileCreated).toISOString(),
modified: new Date(lastActivity).toISOString(),
isSidechain,
});
}
// Merge continuation chains: collapse parent→child sequences into one entry.
// The latest session in each chain inherits the root's created time and
// accumulates message counts. Previous sessions are kept in an array.
const byId = new Map();
for (const s of rawSessions) byId.set(s.sessionId, s);
// Find which sessions are parents (have a child pointing to them)
const isParent = new Set();
for (const s of rawSessions) {
if (s.parentSessionId && byId.has(s.parentSessionId)) {
isParent.add(s.parentSessionId);
}
}
const sessions = [];
for (const s of rawSessions) {
if (isParent.has(s.sessionId)) continue; // skip — will be folded into child
// Walk back through parent chain
const chain = [];
let cur = s;
while (cur.parentSessionId && byId.has(cur.parentSessionId)) {
const parent = byId.get(cur.parentSessionId);
chain.unshift(parent);
cur = parent;
}
if (chain.length > 0) {
// Use root session's created time
s.created = chain[0].created;
// Aggregate message counts
s.messageCount = chain.reduce((sum, p) => sum + p.messageCount, 0) + s.messageCount;
// Use root's title/firstPrompt if current one is generic
if (chain[0].firstPrompt && (!s.firstPrompt || s.title === '(no title)')) {
s.firstPrompt = chain[0].firstPrompt;
s.title = chain[0].title;
}
// Attach previous sessions for the UI
s.previousSessions = chain.map(p => ({
sessionId: p.sessionId,
created: p.created,
modified: p.modified,
messageCount: p.messageCount,
title: p.title,
}));
}
delete s.parentSessionId;
sessions.push(s);
}
if (sessions.length === 0) continue;
// Derive projectPath from dirName if not set from sessions-index.json
if (!projectPath) {
projectPath = resolveProjectPath(dirent.name);
}
let { repoUrl, branch } = getRepoInfo(projectPath);
// If no git in this dir, check parent wip/worktrees.json (for topic-level worktree dirs)
if (!branch) {
try {
const wipJson = path.join(projectPath, '..', 'worktrees.json');
const wipData = JSON.parse(fs.readFileSync(wipJson, 'utf-8'));
const topicId = path.basename(projectPath);