@siteboon/claude-code-ui 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/.env.example +12 -0
  2. package/.nvmrc +1 -0
  3. package/LICENSE +675 -0
  4. package/README.md +275 -0
  5. package/index.html +48 -0
  6. package/package.json +84 -0
  7. package/postcss.config.js +6 -0
  8. package/public/convert-icons.md +53 -0
  9. package/public/favicon.png +0 -0
  10. package/public/favicon.svg +9 -0
  11. package/public/generate-icons.js +49 -0
  12. package/public/icons/claude-ai-icon.svg +1 -0
  13. package/public/icons/cursor.svg +1 -0
  14. package/public/icons/generate-icons.md +19 -0
  15. package/public/icons/icon-128x128.png +0 -0
  16. package/public/icons/icon-128x128.svg +12 -0
  17. package/public/icons/icon-144x144.png +0 -0
  18. package/public/icons/icon-144x144.svg +12 -0
  19. package/public/icons/icon-152x152.png +0 -0
  20. package/public/icons/icon-152x152.svg +12 -0
  21. package/public/icons/icon-192x192.png +0 -0
  22. package/public/icons/icon-192x192.svg +12 -0
  23. package/public/icons/icon-384x384.png +0 -0
  24. package/public/icons/icon-384x384.svg +12 -0
  25. package/public/icons/icon-512x512.png +0 -0
  26. package/public/icons/icon-512x512.svg +12 -0
  27. package/public/icons/icon-72x72.png +0 -0
  28. package/public/icons/icon-72x72.svg +12 -0
  29. package/public/icons/icon-96x96.png +0 -0
  30. package/public/icons/icon-96x96.svg +12 -0
  31. package/public/icons/icon-template.svg +12 -0
  32. package/public/logo.svg +9 -0
  33. package/public/manifest.json +61 -0
  34. package/public/screenshots/cli-selection.png +0 -0
  35. package/public/screenshots/desktop-main.png +0 -0
  36. package/public/screenshots/mobile-chat.png +0 -0
  37. package/public/screenshots/tools-modal.png +0 -0
  38. package/public/sw.js +49 -0
  39. package/server/claude-cli.js +391 -0
  40. package/server/cursor-cli.js +250 -0
  41. package/server/database/db.js +86 -0
  42. package/server/database/init.sql +16 -0
  43. package/server/index.js +1167 -0
  44. package/server/middleware/auth.js +80 -0
  45. package/server/projects.js +1063 -0
  46. package/server/routes/auth.js +135 -0
  47. package/server/routes/cursor.js +794 -0
  48. package/server/routes/git.js +823 -0
  49. package/server/routes/mcp-utils.js +48 -0
  50. package/server/routes/mcp.js +552 -0
  51. package/server/routes/taskmaster.js +1971 -0
  52. package/server/utils/mcp-detector.js +198 -0
  53. package/server/utils/taskmaster-websocket.js +129 -0
  54. package/src/App.jsx +751 -0
  55. package/src/components/ChatInterface.jsx +3485 -0
  56. package/src/components/ClaudeLogo.jsx +11 -0
  57. package/src/components/ClaudeStatus.jsx +107 -0
  58. package/src/components/CodeEditor.jsx +422 -0
  59. package/src/components/CreateTaskModal.jsx +88 -0
  60. package/src/components/CursorLogo.jsx +9 -0
  61. package/src/components/DarkModeToggle.jsx +35 -0
  62. package/src/components/DiffViewer.jsx +41 -0
  63. package/src/components/ErrorBoundary.jsx +73 -0
  64. package/src/components/FileTree.jsx +480 -0
  65. package/src/components/GitPanel.jsx +1283 -0
  66. package/src/components/ImageViewer.jsx +54 -0
  67. package/src/components/LoginForm.jsx +110 -0
  68. package/src/components/MainContent.jsx +577 -0
  69. package/src/components/MicButton.jsx +272 -0
  70. package/src/components/MobileNav.jsx +88 -0
  71. package/src/components/NextTaskBanner.jsx +695 -0
  72. package/src/components/PRDEditor.jsx +871 -0
  73. package/src/components/ProtectedRoute.jsx +44 -0
  74. package/src/components/QuickSettingsPanel.jsx +262 -0
  75. package/src/components/Settings.jsx +2023 -0
  76. package/src/components/SetupForm.jsx +135 -0
  77. package/src/components/Shell.jsx +663 -0
  78. package/src/components/Sidebar.jsx +1665 -0
  79. package/src/components/StandaloneShell.jsx +106 -0
  80. package/src/components/TaskCard.jsx +210 -0
  81. package/src/components/TaskDetail.jsx +406 -0
  82. package/src/components/TaskIndicator.jsx +108 -0
  83. package/src/components/TaskList.jsx +1054 -0
  84. package/src/components/TaskMasterSetupWizard.jsx +603 -0
  85. package/src/components/TaskMasterStatus.jsx +86 -0
  86. package/src/components/TodoList.jsx +91 -0
  87. package/src/components/Tooltip.jsx +91 -0
  88. package/src/components/ui/badge.jsx +31 -0
  89. package/src/components/ui/button.jsx +46 -0
  90. package/src/components/ui/input.jsx +19 -0
  91. package/src/components/ui/scroll-area.jsx +23 -0
  92. package/src/contexts/AuthContext.jsx +158 -0
  93. package/src/contexts/TaskMasterContext.jsx +324 -0
  94. package/src/contexts/TasksSettingsContext.jsx +95 -0
  95. package/src/contexts/ThemeContext.jsx +94 -0
  96. package/src/contexts/WebSocketContext.jsx +29 -0
  97. package/src/hooks/useAudioRecorder.js +109 -0
  98. package/src/hooks/useVersionCheck.js +39 -0
  99. package/src/index.css +822 -0
  100. package/src/lib/utils.js +6 -0
  101. package/src/main.jsx +10 -0
  102. package/src/utils/api.js +141 -0
  103. package/src/utils/websocket.js +109 -0
  104. package/src/utils/whisper.js +37 -0
  105. package/tailwind.config.js +63 -0
  106. package/vite.config.js +29 -0
@@ -0,0 +1,794 @@
1
+ import express from 'express';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { spawn } from 'child_process';
6
+ import sqlite3 from 'sqlite3';
7
+ import { open } from 'sqlite';
8
+ import crypto from 'crypto';
9
+
10
+ const router = express.Router();
11
+
12
+ // GET /api/cursor/config - Read Cursor CLI configuration
13
+ router.get('/config', async (req, res) => {
14
+ try {
15
+ const configPath = path.join(os.homedir(), '.cursor', 'cli-config.json');
16
+
17
+ try {
18
+ const configContent = await fs.readFile(configPath, 'utf8');
19
+ const config = JSON.parse(configContent);
20
+
21
+ res.json({
22
+ success: true,
23
+ config: config,
24
+ path: configPath
25
+ });
26
+ } catch (error) {
27
+ // Config doesn't exist or is invalid
28
+ console.log('Cursor config not found or invalid:', error.message);
29
+
30
+ // Return default config
31
+ res.json({
32
+ success: true,
33
+ config: {
34
+ version: 1,
35
+ model: {
36
+ modelId: "gpt-5",
37
+ displayName: "GPT-5"
38
+ },
39
+ permissions: {
40
+ allow: [],
41
+ deny: []
42
+ }
43
+ },
44
+ isDefault: true
45
+ });
46
+ }
47
+ } catch (error) {
48
+ console.error('Error reading Cursor config:', error);
49
+ res.status(500).json({
50
+ error: 'Failed to read Cursor configuration',
51
+ details: error.message
52
+ });
53
+ }
54
+ });
55
+
56
+ // POST /api/cursor/config - Update Cursor CLI configuration
57
+ router.post('/config', async (req, res) => {
58
+ try {
59
+ const { permissions, model } = req.body;
60
+ const configPath = path.join(os.homedir(), '.cursor', 'cli-config.json');
61
+
62
+ // Read existing config or create default
63
+ let config = {
64
+ version: 1,
65
+ editor: {
66
+ vimMode: false
67
+ },
68
+ hasChangedDefaultModel: false,
69
+ privacyCache: {
70
+ ghostMode: false,
71
+ privacyMode: 3,
72
+ updatedAt: Date.now()
73
+ }
74
+ };
75
+
76
+ try {
77
+ const existing = await fs.readFile(configPath, 'utf8');
78
+ config = JSON.parse(existing);
79
+ } catch (error) {
80
+ // Config doesn't exist, use defaults
81
+ console.log('Creating new Cursor config');
82
+ }
83
+
84
+ // Update permissions if provided
85
+ if (permissions) {
86
+ config.permissions = {
87
+ allow: permissions.allow || [],
88
+ deny: permissions.deny || []
89
+ };
90
+ }
91
+
92
+ // Update model if provided
93
+ if (model) {
94
+ config.model = model;
95
+ config.hasChangedDefaultModel = true;
96
+ }
97
+
98
+ // Ensure directory exists
99
+ const configDir = path.dirname(configPath);
100
+ await fs.mkdir(configDir, { recursive: true });
101
+
102
+ // Write updated config
103
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2));
104
+
105
+ res.json({
106
+ success: true,
107
+ config: config,
108
+ message: 'Cursor configuration updated successfully'
109
+ });
110
+ } catch (error) {
111
+ console.error('Error updating Cursor config:', error);
112
+ res.status(500).json({
113
+ error: 'Failed to update Cursor configuration',
114
+ details: error.message
115
+ });
116
+ }
117
+ });
118
+
119
+ // GET /api/cursor/mcp - Read Cursor MCP servers configuration
120
+ router.get('/mcp', async (req, res) => {
121
+ try {
122
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
123
+
124
+ try {
125
+ const mcpContent = await fs.readFile(mcpPath, 'utf8');
126
+ const mcpConfig = JSON.parse(mcpContent);
127
+
128
+ // Convert to UI-friendly format
129
+ const servers = [];
130
+ if (mcpConfig.mcpServers && typeof mcpConfig.mcpServers === 'object') {
131
+ for (const [name, config] of Object.entries(mcpConfig.mcpServers)) {
132
+ const server = {
133
+ id: name,
134
+ name: name,
135
+ type: 'stdio',
136
+ scope: 'cursor',
137
+ config: {},
138
+ raw: config
139
+ };
140
+
141
+ // Determine transport type and extract config
142
+ if (config.command) {
143
+ server.type = 'stdio';
144
+ server.config.command = config.command;
145
+ server.config.args = config.args || [];
146
+ server.config.env = config.env || {};
147
+ } else if (config.url) {
148
+ server.type = config.transport || 'http';
149
+ server.config.url = config.url;
150
+ server.config.headers = config.headers || {};
151
+ }
152
+
153
+ servers.push(server);
154
+ }
155
+ }
156
+
157
+ res.json({
158
+ success: true,
159
+ servers: servers,
160
+ path: mcpPath
161
+ });
162
+ } catch (error) {
163
+ // MCP config doesn't exist
164
+ console.log('Cursor MCP config not found:', error.message);
165
+ res.json({
166
+ success: true,
167
+ servers: [],
168
+ isDefault: true
169
+ });
170
+ }
171
+ } catch (error) {
172
+ console.error('Error reading Cursor MCP config:', error);
173
+ res.status(500).json({
174
+ error: 'Failed to read Cursor MCP configuration',
175
+ details: error.message
176
+ });
177
+ }
178
+ });
179
+
180
+ // POST /api/cursor/mcp/add - Add MCP server to Cursor configuration
181
+ router.post('/mcp/add', async (req, res) => {
182
+ try {
183
+ const { name, type = 'stdio', command, args = [], url, headers = {}, env = {} } = req.body;
184
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
185
+
186
+ console.log(`➕ Adding MCP server to Cursor config: ${name}`);
187
+
188
+ // Read existing config or create new
189
+ let mcpConfig = { mcpServers: {} };
190
+
191
+ try {
192
+ const existing = await fs.readFile(mcpPath, 'utf8');
193
+ mcpConfig = JSON.parse(existing);
194
+ if (!mcpConfig.mcpServers) {
195
+ mcpConfig.mcpServers = {};
196
+ }
197
+ } catch (error) {
198
+ console.log('Creating new Cursor MCP config');
199
+ }
200
+
201
+ // Build server config based on type
202
+ let serverConfig = {};
203
+
204
+ if (type === 'stdio') {
205
+ serverConfig = {
206
+ command: command,
207
+ args: args,
208
+ env: env
209
+ };
210
+ } else if (type === 'http' || type === 'sse') {
211
+ serverConfig = {
212
+ url: url,
213
+ transport: type,
214
+ headers: headers
215
+ };
216
+ }
217
+
218
+ // Add server to config
219
+ mcpConfig.mcpServers[name] = serverConfig;
220
+
221
+ // Ensure directory exists
222
+ const mcpDir = path.dirname(mcpPath);
223
+ await fs.mkdir(mcpDir, { recursive: true });
224
+
225
+ // Write updated config
226
+ await fs.writeFile(mcpPath, JSON.stringify(mcpConfig, null, 2));
227
+
228
+ res.json({
229
+ success: true,
230
+ message: `MCP server "${name}" added to Cursor configuration`,
231
+ config: mcpConfig
232
+ });
233
+ } catch (error) {
234
+ console.error('Error adding MCP server to Cursor:', error);
235
+ res.status(500).json({
236
+ error: 'Failed to add MCP server',
237
+ details: error.message
238
+ });
239
+ }
240
+ });
241
+
242
+ // DELETE /api/cursor/mcp/:name - Remove MCP server from Cursor configuration
243
+ router.delete('/mcp/:name', async (req, res) => {
244
+ try {
245
+ const { name } = req.params;
246
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
247
+
248
+ console.log(`🗑️ Removing MCP server from Cursor config: ${name}`);
249
+
250
+ // Read existing config
251
+ let mcpConfig = { mcpServers: {} };
252
+
253
+ try {
254
+ const existing = await fs.readFile(mcpPath, 'utf8');
255
+ mcpConfig = JSON.parse(existing);
256
+ } catch (error) {
257
+ return res.status(404).json({
258
+ error: 'Cursor MCP configuration not found'
259
+ });
260
+ }
261
+
262
+ // Check if server exists
263
+ if (!mcpConfig.mcpServers || !mcpConfig.mcpServers[name]) {
264
+ return res.status(404).json({
265
+ error: `MCP server "${name}" not found in Cursor configuration`
266
+ });
267
+ }
268
+
269
+ // Remove server from config
270
+ delete mcpConfig.mcpServers[name];
271
+
272
+ // Write updated config
273
+ await fs.writeFile(mcpPath, JSON.stringify(mcpConfig, null, 2));
274
+
275
+ res.json({
276
+ success: true,
277
+ message: `MCP server "${name}" removed from Cursor configuration`,
278
+ config: mcpConfig
279
+ });
280
+ } catch (error) {
281
+ console.error('Error removing MCP server from Cursor:', error);
282
+ res.status(500).json({
283
+ error: 'Failed to remove MCP server',
284
+ details: error.message
285
+ });
286
+ }
287
+ });
288
+
289
+ // POST /api/cursor/mcp/add-json - Add MCP server using JSON format
290
+ router.post('/mcp/add-json', async (req, res) => {
291
+ try {
292
+ const { name, jsonConfig } = req.body;
293
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
294
+
295
+ console.log(`➕ Adding MCP server to Cursor config via JSON: ${name}`);
296
+
297
+ // Validate and parse JSON config
298
+ let parsedConfig;
299
+ try {
300
+ parsedConfig = typeof jsonConfig === 'string' ? JSON.parse(jsonConfig) : jsonConfig;
301
+ } catch (parseError) {
302
+ return res.status(400).json({
303
+ error: 'Invalid JSON configuration',
304
+ details: parseError.message
305
+ });
306
+ }
307
+
308
+ // Read existing config or create new
309
+ let mcpConfig = { mcpServers: {} };
310
+
311
+ try {
312
+ const existing = await fs.readFile(mcpPath, 'utf8');
313
+ mcpConfig = JSON.parse(existing);
314
+ if (!mcpConfig.mcpServers) {
315
+ mcpConfig.mcpServers = {};
316
+ }
317
+ } catch (error) {
318
+ console.log('Creating new Cursor MCP config');
319
+ }
320
+
321
+ // Add server to config
322
+ mcpConfig.mcpServers[name] = parsedConfig;
323
+
324
+ // Ensure directory exists
325
+ const mcpDir = path.dirname(mcpPath);
326
+ await fs.mkdir(mcpDir, { recursive: true });
327
+
328
+ // Write updated config
329
+ await fs.writeFile(mcpPath, JSON.stringify(mcpConfig, null, 2));
330
+
331
+ res.json({
332
+ success: true,
333
+ message: `MCP server "${name}" added to Cursor configuration via JSON`,
334
+ config: mcpConfig
335
+ });
336
+ } catch (error) {
337
+ console.error('Error adding MCP server to Cursor via JSON:', error);
338
+ res.status(500).json({
339
+ error: 'Failed to add MCP server',
340
+ details: error.message
341
+ });
342
+ }
343
+ });
344
+
345
+ // GET /api/cursor/sessions - Get Cursor sessions from SQLite database
346
+ router.get('/sessions', async (req, res) => {
347
+ try {
348
+ const { projectPath } = req.query;
349
+
350
+ // Calculate cwdID hash for the project path (Cursor uses MD5 hash)
351
+ const cwdId = crypto.createHash('md5').update(projectPath || process.cwd()).digest('hex');
352
+ const cursorChatsPath = path.join(os.homedir(), '.cursor', 'chats', cwdId);
353
+
354
+
355
+ // Check if the directory exists
356
+ try {
357
+ await fs.access(cursorChatsPath);
358
+ } catch (error) {
359
+ // No sessions for this project
360
+ return res.json({
361
+ success: true,
362
+ sessions: [],
363
+ cwdId: cwdId,
364
+ path: cursorChatsPath
365
+ });
366
+ }
367
+
368
+ // List all session directories
369
+ const sessionDirs = await fs.readdir(cursorChatsPath);
370
+ const sessions = [];
371
+
372
+ for (const sessionId of sessionDirs) {
373
+ const sessionPath = path.join(cursorChatsPath, sessionId);
374
+ const storeDbPath = path.join(sessionPath, 'store.db');
375
+ let dbStatMtimeMs = null;
376
+
377
+ try {
378
+ // Check if store.db exists
379
+ await fs.access(storeDbPath);
380
+
381
+ // Capture store.db mtime as a reliable fallback timestamp (last activity)
382
+ try {
383
+ const stat = await fs.stat(storeDbPath);
384
+ dbStatMtimeMs = stat.mtimeMs;
385
+ } catch (_) {}
386
+
387
+ // Open SQLite database
388
+ const db = await open({
389
+ filename: storeDbPath,
390
+ driver: sqlite3.Database,
391
+ mode: sqlite3.OPEN_READONLY
392
+ });
393
+
394
+ // Get metadata from meta table
395
+ const metaRows = await db.all(`
396
+ SELECT key, value FROM meta
397
+ `);
398
+
399
+ let sessionData = {
400
+ id: sessionId,
401
+ name: 'Untitled Session',
402
+ createdAt: null,
403
+ mode: null,
404
+ projectPath: projectPath,
405
+ lastMessage: null,
406
+ messageCount: 0
407
+ };
408
+
409
+ // Parse meta table entries
410
+ for (const row of metaRows) {
411
+ if (row.value) {
412
+ try {
413
+ // Try to decode as hex-encoded JSON
414
+ const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
415
+ if (hexMatch) {
416
+ const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
417
+ const data = JSON.parse(jsonStr);
418
+
419
+ if (row.key === 'agent') {
420
+ sessionData.name = data.name || sessionData.name;
421
+ // Normalize createdAt to ISO string in milliseconds
422
+ let createdAt = data.createdAt;
423
+ if (typeof createdAt === 'number') {
424
+ if (createdAt < 1e12) {
425
+ createdAt = createdAt * 1000; // seconds -> ms
426
+ }
427
+ sessionData.createdAt = new Date(createdAt).toISOString();
428
+ } else if (typeof createdAt === 'string') {
429
+ const n = Number(createdAt);
430
+ if (!Number.isNaN(n)) {
431
+ const ms = n < 1e12 ? n * 1000 : n;
432
+ sessionData.createdAt = new Date(ms).toISOString();
433
+ } else {
434
+ // Assume it's already an ISO/date string
435
+ const d = new Date(createdAt);
436
+ sessionData.createdAt = isNaN(d.getTime()) ? null : d.toISOString();
437
+ }
438
+ } else {
439
+ sessionData.createdAt = sessionData.createdAt || null;
440
+ }
441
+ sessionData.mode = data.mode;
442
+ sessionData.agentId = data.agentId;
443
+ sessionData.latestRootBlobId = data.latestRootBlobId;
444
+ }
445
+ } else {
446
+ // If not hex, use raw value for simple keys
447
+ if (row.key === 'name') {
448
+ sessionData.name = row.value.toString();
449
+ }
450
+ }
451
+ } catch (e) {
452
+ console.log(`Could not parse meta value for key ${row.key}:`, e.message);
453
+ }
454
+ }
455
+ }
456
+
457
+ // Get message count from JSON blobs only (actual messages, not DAG structure)
458
+ try {
459
+ const blobCount = await db.get(`
460
+ SELECT COUNT(*) as count
461
+ FROM blobs
462
+ WHERE substr(data, 1, 1) = X'7B'
463
+ `);
464
+ sessionData.messageCount = blobCount.count;
465
+
466
+ // Get the most recent JSON blob for preview (actual message, not DAG structure)
467
+ const lastBlob = await db.get(`
468
+ SELECT data FROM blobs
469
+ WHERE substr(data, 1, 1) = X'7B'
470
+ ORDER BY rowid DESC
471
+ LIMIT 1
472
+ `);
473
+
474
+ if (lastBlob && lastBlob.data) {
475
+ try {
476
+ // Try to extract readable preview from blob (may contain binary with embedded JSON)
477
+ const raw = lastBlob.data.toString('utf8');
478
+ let preview = '';
479
+ // Attempt direct JSON parse
480
+ try {
481
+ const parsed = JSON.parse(raw);
482
+ if (parsed?.content) {
483
+ if (Array.isArray(parsed.content)) {
484
+ const firstText = parsed.content.find(p => p?.type === 'text' && p.text)?.text || '';
485
+ preview = firstText;
486
+ } else if (typeof parsed.content === 'string') {
487
+ preview = parsed.content;
488
+ }
489
+ }
490
+ } catch (_) {}
491
+ if (!preview) {
492
+ // Strip non-printable and try to find JSON chunk
493
+ const cleaned = raw.replace(/[^\x09\x0A\x0D\x20-\x7E]/g, '');
494
+ const s = cleaned;
495
+ const start = s.indexOf('{');
496
+ const end = s.lastIndexOf('}');
497
+ if (start !== -1 && end > start) {
498
+ const jsonStr = s.slice(start, end + 1);
499
+ try {
500
+ const parsed = JSON.parse(jsonStr);
501
+ if (parsed?.content) {
502
+ if (Array.isArray(parsed.content)) {
503
+ const firstText = parsed.content.find(p => p?.type === 'text' && p.text)?.text || '';
504
+ preview = firstText;
505
+ } else if (typeof parsed.content === 'string') {
506
+ preview = parsed.content;
507
+ }
508
+ }
509
+ } catch (_) {
510
+ preview = s;
511
+ }
512
+ } else {
513
+ preview = s;
514
+ }
515
+ }
516
+ if (preview && preview.length > 0) {
517
+ sessionData.lastMessage = preview.substring(0, 100) + (preview.length > 100 ? '...' : '');
518
+ }
519
+ } catch (e) {
520
+ console.log('Could not parse blob data:', e.message);
521
+ }
522
+ }
523
+ } catch (e) {
524
+ console.log('Could not read blobs:', e.message);
525
+ }
526
+
527
+ await db.close();
528
+
529
+ // Finalize createdAt: use parsed meta value when valid, else fall back to store.db mtime
530
+ if (!sessionData.createdAt) {
531
+ if (dbStatMtimeMs && Number.isFinite(dbStatMtimeMs)) {
532
+ sessionData.createdAt = new Date(dbStatMtimeMs).toISOString();
533
+ }
534
+ }
535
+
536
+ sessions.push(sessionData);
537
+
538
+ } catch (error) {
539
+ console.log(`Could not read session ${sessionId}:`, error.message);
540
+ }
541
+ }
542
+
543
+ // Fallback: ensure createdAt is a valid ISO string (use session directory mtime as last resort)
544
+ for (const s of sessions) {
545
+ if (!s.createdAt) {
546
+ try {
547
+ const sessionDir = path.join(cursorChatsPath, s.id);
548
+ const st = await fs.stat(sessionDir);
549
+ s.createdAt = new Date(st.mtimeMs).toISOString();
550
+ } catch {
551
+ s.createdAt = new Date().toISOString();
552
+ }
553
+ }
554
+ }
555
+ // Sort sessions by creation date (newest first)
556
+ sessions.sort((a, b) => {
557
+ if (!a.createdAt) return 1;
558
+ if (!b.createdAt) return -1;
559
+ return new Date(b.createdAt) - new Date(a.createdAt);
560
+ });
561
+
562
+ res.json({
563
+ success: true,
564
+ sessions: sessions,
565
+ cwdId: cwdId,
566
+ path: cursorChatsPath
567
+ });
568
+
569
+ } catch (error) {
570
+ console.error('Error reading Cursor sessions:', error);
571
+ res.status(500).json({
572
+ error: 'Failed to read Cursor sessions',
573
+ details: error.message
574
+ });
575
+ }
576
+ });
577
+
578
+ // GET /api/cursor/sessions/:sessionId - Get specific Cursor session from SQLite
579
+ router.get('/sessions/:sessionId', async (req, res) => {
580
+ try {
581
+ const { sessionId } = req.params;
582
+ const { projectPath } = req.query;
583
+
584
+ // Calculate cwdID hash for the project path
585
+ const cwdId = crypto.createHash('md5').update(projectPath || process.cwd()).digest('hex');
586
+ const storeDbPath = path.join(os.homedir(), '.cursor', 'chats', cwdId, sessionId, 'store.db');
587
+
588
+
589
+ // Open SQLite database
590
+ const db = await open({
591
+ filename: storeDbPath,
592
+ driver: sqlite3.Database,
593
+ mode: sqlite3.OPEN_READONLY
594
+ });
595
+
596
+ // Get all blobs to build the DAG structure
597
+ const allBlobs = await db.all(`
598
+ SELECT rowid, id, data FROM blobs
599
+ `);
600
+
601
+ // Build the DAG structure from parent-child relationships
602
+ const blobMap = new Map(); // id -> blob data
603
+ const parentRefs = new Map(); // blob id -> [parent blob ids]
604
+ const childRefs = new Map(); // blob id -> [child blob ids]
605
+ const jsonBlobs = []; // Clean JSON messages
606
+
607
+ for (const blob of allBlobs) {
608
+ blobMap.set(blob.id, blob);
609
+
610
+ // Check if this is a JSON blob (actual message) or protobuf (DAG structure)
611
+ if (blob.data && blob.data[0] === 0x7B) { // Starts with '{' - JSON blob
612
+ try {
613
+ const parsed = JSON.parse(blob.data.toString('utf8'));
614
+ jsonBlobs.push({ ...blob, parsed });
615
+ } catch (e) {
616
+ console.log('Failed to parse JSON blob:', blob.rowid);
617
+ }
618
+ } else if (blob.data) { // Protobuf blob - extract parent references
619
+ const parents = [];
620
+ let i = 0;
621
+
622
+ // Scan for parent references (0x0A 0x20 followed by 32-byte hash)
623
+ while (i < blob.data.length - 33) {
624
+ if (blob.data[i] === 0x0A && blob.data[i+1] === 0x20) {
625
+ const parentHash = blob.data.slice(i+2, i+34).toString('hex');
626
+ if (blobMap.has(parentHash)) {
627
+ parents.push(parentHash);
628
+ }
629
+ i += 34;
630
+ } else {
631
+ i++;
632
+ }
633
+ }
634
+
635
+ if (parents.length > 0) {
636
+ parentRefs.set(blob.id, parents);
637
+ // Update child references
638
+ for (const parentId of parents) {
639
+ if (!childRefs.has(parentId)) {
640
+ childRefs.set(parentId, []);
641
+ }
642
+ childRefs.get(parentId).push(blob.id);
643
+ }
644
+ }
645
+ }
646
+ }
647
+
648
+ // Perform topological sort to get chronological order
649
+ const visited = new Set();
650
+ const sorted = [];
651
+
652
+ // DFS-based topological sort
653
+ function visit(nodeId) {
654
+ if (visited.has(nodeId)) return;
655
+ visited.add(nodeId);
656
+
657
+ // Visit all parents first (dependencies)
658
+ const parents = parentRefs.get(nodeId) || [];
659
+ for (const parentId of parents) {
660
+ visit(parentId);
661
+ }
662
+
663
+ // Add this node after all its parents
664
+ const blob = blobMap.get(nodeId);
665
+ if (blob) {
666
+ sorted.push(blob);
667
+ }
668
+ }
669
+
670
+ // Start with nodes that have no parents (roots)
671
+ for (const blob of allBlobs) {
672
+ if (!parentRefs.has(blob.id)) {
673
+ visit(blob.id);
674
+ }
675
+ }
676
+
677
+ // Visit any remaining nodes (disconnected components)
678
+ for (const blob of allBlobs) {
679
+ visit(blob.id);
680
+ }
681
+
682
+ // Now extract JSON messages in the order they appear in the sorted DAG
683
+ const messageOrder = new Map(); // JSON blob id -> order index
684
+ let orderIndex = 0;
685
+
686
+ for (const blob of sorted) {
687
+ // Check if this blob references any JSON messages
688
+ if (blob.data && blob.data[0] !== 0x7B) { // Protobuf blob
689
+ // Look for JSON blob references
690
+ for (const jsonBlob of jsonBlobs) {
691
+ try {
692
+ const jsonIdBytes = Buffer.from(jsonBlob.id, 'hex');
693
+ if (blob.data.includes(jsonIdBytes)) {
694
+ if (!messageOrder.has(jsonBlob.id)) {
695
+ messageOrder.set(jsonBlob.id, orderIndex++);
696
+ }
697
+ }
698
+ } catch (e) {
699
+ // Skip if can't convert ID
700
+ }
701
+ }
702
+ }
703
+ }
704
+
705
+ // Sort JSON blobs by their appearance order in the DAG
706
+ const sortedJsonBlobs = jsonBlobs.sort((a, b) => {
707
+ const orderA = messageOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
708
+ const orderB = messageOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
709
+ if (orderA !== orderB) return orderA - orderB;
710
+ // Fallback to rowid if not in order map
711
+ return a.rowid - b.rowid;
712
+ });
713
+
714
+ // Use sorted JSON blobs
715
+ const blobs = sortedJsonBlobs.map((blob, idx) => ({
716
+ ...blob,
717
+ sequence_num: idx + 1,
718
+ original_rowid: blob.rowid
719
+ }));
720
+
721
+ // Get metadata from meta table
722
+ const metaRows = await db.all(`
723
+ SELECT key, value FROM meta
724
+ `);
725
+
726
+ // Parse metadata
727
+ let metadata = {};
728
+ for (const row of metaRows) {
729
+ if (row.value) {
730
+ try {
731
+ // Try to decode as hex-encoded JSON
732
+ const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
733
+ if (hexMatch) {
734
+ const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
735
+ metadata[row.key] = JSON.parse(jsonStr);
736
+ } else {
737
+ metadata[row.key] = row.value.toString();
738
+ }
739
+ } catch (e) {
740
+ metadata[row.key] = row.value.toString();
741
+ }
742
+ }
743
+ }
744
+
745
+ // Extract messages from sorted JSON blobs
746
+ const messages = [];
747
+ for (const blob of blobs) {
748
+ try {
749
+ // We already parsed JSON blobs earlier
750
+ const parsed = blob.parsed;
751
+
752
+ if (parsed) {
753
+ // Filter out ONLY system messages at the server level
754
+ // Check both direct role and nested message.role
755
+ const role = parsed?.role || parsed?.message?.role;
756
+ if (role === 'system') {
757
+ continue; // Skip only system messages
758
+ }
759
+ messages.push({
760
+ id: blob.id,
761
+ sequence: blob.sequence_num,
762
+ rowid: blob.original_rowid,
763
+ content: parsed
764
+ });
765
+ }
766
+ } catch (e) {
767
+ // Skip blobs that cause errors
768
+ console.log(`Skipping blob ${blob.id}: ${e.message}`);
769
+ }
770
+ }
771
+
772
+ await db.close();
773
+
774
+ res.json({
775
+ success: true,
776
+ session: {
777
+ id: sessionId,
778
+ projectPath: projectPath,
779
+ messages: messages,
780
+ metadata: metadata,
781
+ cwdId: cwdId
782
+ }
783
+ });
784
+
785
+ } catch (error) {
786
+ console.error('Error reading Cursor session:', error);
787
+ res.status(500).json({
788
+ error: 'Failed to read Cursor session',
789
+ details: error.message
790
+ });
791
+ }
792
+ });
793
+
794
+ export default router;