-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathserver.js
More file actions
500 lines (414 loc) · 15.2 KB
/
server.js
File metadata and controls
500 lines (414 loc) · 15.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
#!/usr/bin/env node
const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const { existsSync, readdirSync, readFileSync, statSync, createReadStream } = require('fs');
const readline = require('readline');
const chokidar = require('chokidar');
const os = require('os');
const app = express();
const DEFAULT_PORT = 3456;
const explicitPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;
const MAX_PORT_ATTEMPTS = 10;
// Parse --dir flag for custom Claude directory
function getClaudeDir() {
const dirIndex = process.argv.findIndex(arg => arg.startsWith('--dir'));
if (dirIndex !== -1) {
const arg = process.argv[dirIndex];
if (arg.includes('=')) {
const dir = arg.split('=')[1];
return dir.startsWith('~') ? dir.replace('~', os.homedir()) : dir;
} else if (process.argv[dirIndex + 1]) {
const dir = process.argv[dirIndex + 1];
return dir.startsWith('~') ? dir.replace('~', os.homedir()) : dir;
}
}
return process.env.CLAUDE_DIR || path.join(os.homedir(), '.claude');
}
const CLAUDE_DIR = getClaudeDir();
const TASKS_DIR = path.join(CLAUDE_DIR, 'tasks');
const PROJECTS_DIR = path.join(CLAUDE_DIR, 'projects');
// Get running Claude Code containers with their project paths
// SSE clients for live updates
const clients = new Set();
// Cache for session metadata (refreshed periodically)
let sessionMetadataCache = {};
let lastMetadataRefresh = 0;
const METADATA_CACHE_TTL = 10000; // 10 seconds
// Parse JSON bodies
app.use(express.json());
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
/**
* Read customTitle and slug from a JSONL file
* Returns { customTitle, slug } - customTitle from /rename, slug from session
*/
function readSessionInfoFromJsonl(jsonlPath) {
const result = { customTitle: null, slug: null, projectPath: null };
try {
if (!existsSync(jsonlPath)) return result;
// Read first 64KB - should contain custom-title and at least one message with slug/cwd
const fd = require('fs').openSync(jsonlPath, 'r');
const buffer = Buffer.alloc(65536);
const bytesRead = require('fs').readSync(fd, buffer, 0, 65536, 0);
require('fs').closeSync(fd);
const content = buffer.toString('utf8', 0, bytesRead);
const lines = content.split('\n');
for (const line of lines) {
if (!line.trim()) continue;
try {
const data = JSON.parse(line);
// Check for custom-title entry (from /rename command)
if (data.type === 'custom-title' && data.customTitle) {
result.customTitle = data.customTitle;
}
// Check for slug in user/assistant messages
if (data.slug && !result.slug) {
result.slug = data.slug;
}
// Extract project path from cwd field (actual path, no encoding issues)
if (data.cwd && !result.projectPath) {
result.projectPath = data.cwd;
}
// Stop early if we found all three
if (result.customTitle && result.slug && result.projectPath) break;
} catch (e) {
// Skip malformed lines
}
}
} catch (e) {
// Return partial results
}
return result;
}
/**
* Scan all project directories to find session JSONL files and extract slugs
*/
function loadSessionMetadata() {
const now = Date.now();
if (now - lastMetadataRefresh < METADATA_CACHE_TTL) {
return sessionMetadataCache;
}
const metadata = {};
try {
if (!existsSync(PROJECTS_DIR)) {
return metadata;
}
const projectDirs = readdirSync(PROJECTS_DIR, { withFileTypes: true })
.filter(d => d.isDirectory());
for (const projectDir of projectDirs) {
const projectPath = path.join(PROJECTS_DIR, projectDir.name);
// Find all .jsonl files (session logs)
const files = readdirSync(projectPath).filter(f => f.endsWith('.jsonl'));
for (const file of files) {
const sessionId = file.replace('.jsonl', '');
const jsonlPath = path.join(projectPath, file);
// Read customTitle, slug, and actual project path from JSONL
const sessionInfo = readSessionInfoFromJsonl(jsonlPath);
metadata[sessionId] = {
customTitle: sessionInfo.customTitle,
slug: sessionInfo.slug,
project: sessionInfo.projectPath || null,
jsonlPath: jsonlPath
};
}
// Also check sessions-index.json for custom names (if /rename was used)
const indexPath = path.join(projectPath, 'sessions-index.json');
if (existsSync(indexPath)) {
try {
const indexData = JSON.parse(readFileSync(indexPath, 'utf8'));
const entries = indexData.entries || [];
for (const entry of entries) {
if (entry.sessionId && metadata[entry.sessionId]) {
// Add other useful fields
metadata[entry.sessionId].description = entry.description || null;
metadata[entry.sessionId].gitBranch = entry.gitBranch || null;
metadata[entry.sessionId].created = entry.created || null;
}
}
} catch (e) {
// Skip invalid index files
}
}
}
} catch (e) {
console.error('Error loading session metadata:', e);
}
sessionMetadataCache = metadata;
lastMetadataRefresh = now;
return metadata;
}
/**
* Get display name for a session: customTitle > slug > null (frontend shows UUID)
*/
function getSessionDisplayName(sessionId, meta) {
if (meta?.customTitle) return meta.customTitle;
if (meta?.slug) return meta.slug;
return null; // Frontend will show UUID as fallback
}
// API: List all sessions
app.get('/api/sessions', async (req, res) => {
// Prevent browser caching
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
try {
// Parse limit parameter (default: 20, "all" for unlimited)
const limitParam = req.query.limit || '20';
const limit = limitParam === 'all' ? null : parseInt(limitParam, 10);
const metadata = loadSessionMetadata();
const sessionsMap = new Map();
// First, add sessions that have tasks directories
if (existsSync(TASKS_DIR)) {
const entries = readdirSync(TASKS_DIR, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const sessionPath = path.join(TASKS_DIR, entry.name);
const stat = statSync(sessionPath);
const taskFiles = readdirSync(sessionPath).filter(f => f.endsWith('.json'));
// Get task summary and find newest task file
let completed = 0;
let inProgress = 0;
let pending = 0;
let newestTaskMtime = null;
for (const file of taskFiles) {
try {
const taskPath = path.join(sessionPath, file);
const task = JSON.parse(readFileSync(taskPath, 'utf8'));
if (task.status === 'completed') completed++;
else if (task.status === 'in_progress') inProgress++;
else pending++;
// Track newest task file mtime
const taskStat = statSync(taskPath);
if (!newestTaskMtime || taskStat.mtime > newestTaskMtime) {
newestTaskMtime = taskStat.mtime;
}
} catch (e) {
// Skip invalid files
}
}
// Get metadata for this session
const meta = metadata[entry.name] || {};
// Use newest task file mtime, or fall back to directory mtime if no tasks
const modifiedAt = newestTaskMtime ? newestTaskMtime.toISOString() : stat.mtime.toISOString();
sessionsMap.set(entry.name, {
id: entry.name,
name: getSessionDisplayName(entry.name, meta),
slug: meta.slug || null,
project: meta.project || null,
description: meta.description || null,
gitBranch: meta.gitBranch || null,
taskCount: taskFiles.length,
completed,
inProgress,
pending,
createdAt: meta.created || null,
modifiedAt: modifiedAt
});
}
}
}
// Convert map to array and sort by most recently modified
let sessions = Array.from(sessionsMap.values());
sessions.sort((a, b) => new Date(b.modifiedAt) - new Date(a.modifiedAt));
// Apply limit if specified
if (limit !== null && limit > 0) {
sessions = sessions.slice(0, limit);
}
res.json(sessions);
} catch (error) {
console.error('Error listing sessions:', error);
res.status(500).json({ error: 'Failed to list sessions' });
}
});
// API: Get tasks for a session
app.get('/api/sessions/:sessionId', async (req, res) => {
try {
const sessionPath = path.join(TASKS_DIR, req.params.sessionId);
if (!existsSync(sessionPath)) {
return res.status(404).json({ error: 'Session not found' });
}
const taskFiles = readdirSync(sessionPath).filter(f => f.endsWith('.json'));
const tasks = [];
for (const file of taskFiles) {
try {
const taskPath = path.join(sessionPath, file);
const task = JSON.parse(readFileSync(taskPath, 'utf8'));
const taskStat = statSync(taskPath);
task.createdAt = taskStat.birthtime.toISOString();
task.updatedAt = taskStat.mtime.toISOString();
tasks.push(task);
} catch (e) {
console.error(`Error parsing ${file}:`, e);
}
}
// Sort by ID (numeric)
tasks.sort((a, b) => parseInt(a.id) - parseInt(b.id));
res.json(tasks);
} catch (error) {
console.error('Error getting session:', error);
res.status(500).json({ error: 'Failed to get session' });
}
});
// API: Get all tasks across all sessions
app.get('/api/tasks/all', async (req, res) => {
try {
if (!existsSync(TASKS_DIR)) {
return res.json([]);
}
const metadata = loadSessionMetadata();
const sessionDirs = readdirSync(TASKS_DIR, { withFileTypes: true })
.filter(d => d.isDirectory());
const allTasks = [];
for (const sessionDir of sessionDirs) {
const sessionPath = path.join(TASKS_DIR, sessionDir.name);
const taskFiles = readdirSync(sessionPath).filter(f => f.endsWith('.json'));
const meta = metadata[sessionDir.name] || {};
for (const file of taskFiles) {
try {
const taskPath = path.join(sessionPath, file);
const task = JSON.parse(readFileSync(taskPath, 'utf8'));
const taskStat = statSync(taskPath);
allTasks.push({
...task,
createdAt: taskStat.birthtime.toISOString(),
updatedAt: taskStat.mtime.toISOString(),
sessionId: sessionDir.name,
sessionName: getSessionDisplayName(sessionDir.name, meta),
project: meta.project || null
});
} catch (e) {
// Skip invalid files
}
}
}
res.json(allTasks);
} catch (error) {
console.error('Error getting all tasks:', error);
res.status(500).json({ error: 'Failed to get all tasks' });
}
});
// API: Add note to a task
app.post('/api/tasks/:sessionId/:taskId/note', async (req, res) => {
try {
const { sessionId, taskId } = req.params;
const { note } = req.body;
if (!note || !note.trim()) {
return res.status(400).json({ error: 'Note cannot be empty' });
}
const taskPath = path.join(TASKS_DIR, sessionId, `${taskId}.json`);
if (!existsSync(taskPath)) {
return res.status(404).json({ error: 'Task not found' });
}
// Read current task
const task = JSON.parse(await fs.readFile(taskPath, 'utf8'));
// Append note to description
const noteBlock = `\n\n---\n\n#### [Note added by user]\n\n${note.trim()}`;
task.description = (task.description || '') + noteBlock;
// Write updated task
await fs.writeFile(taskPath, JSON.stringify(task, null, 2));
res.json({ success: true, task });
} catch (error) {
console.error('Error adding note:', error);
res.status(500).json({ error: 'Failed to add note' });
}
});
// API: Delete a task
app.delete('/api/tasks/:sessionId/:taskId', async (req, res) => {
try {
const { sessionId, taskId } = req.params;
const taskPath = path.join(TASKS_DIR, sessionId, `${taskId}.json`);
if (!existsSync(taskPath)) {
return res.status(404).json({ error: 'Task not found' });
}
// Check if this task blocks other tasks
const sessionPath = path.join(TASKS_DIR, sessionId);
const taskFiles = readdirSync(sessionPath).filter(f => f.endsWith('.json'));
for (const file of taskFiles) {
const otherTask = JSON.parse(readFileSync(path.join(sessionPath, file), 'utf8'));
if (otherTask.blockedBy && otherTask.blockedBy.includes(taskId)) {
return res.status(400).json({
error: 'Cannot delete task that blocks other tasks',
blockedTasks: [otherTask.id]
});
}
}
// Delete the task file
await fs.unlink(taskPath);
res.json({ success: true, taskId });
} catch (error) {
console.error('Error deleting task:', error);
res.status(500).json({ error: 'Failed to delete task' });
}
});
// SSE endpoint for live updates
app.get('/api/events', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
clients.add(res);
req.on('close', () => {
clients.delete(res);
});
// Send initial ping
res.write('data: {"type":"connected"}\n\n');
});
// Broadcast update to all SSE clients
function broadcast(data) {
const message = `data: ${JSON.stringify(data)}\n\n`;
for (const client of clients) {
client.write(message);
}
}
// Watch for file changes (chokidar handles non-existent paths)
const watcher = chokidar.watch(TASKS_DIR, {
persistent: true,
ignoreInitial: true,
depth: 2
});
watcher.on('all', (event, filePath) => {
if (filePath.endsWith('.json')) {
const relativePath = path.relative(TASKS_DIR, filePath);
const sessionId = relativePath.split(path.sep)[0];
broadcast({
type: 'update',
event,
sessionId,
file: path.basename(filePath)
});
}
});
console.log(`Watching for changes in: ${TASKS_DIR}`);
// Also watch projects dir for metadata changes
const projectsWatcher = chokidar.watch(PROJECTS_DIR, {
persistent: true,
ignoreInitial: true,
depth: 2
});
projectsWatcher.on('all', (event, filePath) => {
if (filePath.endsWith('.jsonl')) {
// Invalidate cache on any change
lastMetadataRefresh = 0;
broadcast({ type: 'metadata-update' });
}
});
// Start server with auto port discovery
function startServer(port, attempt = 0) {
const server = app.listen(port, () => {
console.log(`Claude Task Viewer running at http://localhost:${port}`);
// Open browser if --open flag is passed
if (process.argv.includes('--open')) {
import('open').then(open => open.default(`http://localhost:${port}`));
}
});
server.on('error', (err) => {
if (err.code === 'EADDRINUSE' && !explicitPort && attempt < MAX_PORT_ATTEMPTS) {
console.log(`Port ${port} is in use, trying ${port + 1}...`);
startServer(port + 1, attempt + 1);
} else {
console.error(`Failed to start server on port ${port}: ${err.message}`);
process.exit(1);
}
});
}
startServer(explicitPort || DEFAULT_PORT);