notioncode 0.1.1 → 0.1.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 (77) hide show
  1. package/README.md +10 -4
  2. package/agent-runtime-server/package-lock.json +4377 -0
  3. package/agent-runtime-server/package.json +36 -0
  4. package/agent-runtime-server/scripts/fix-node-pty.js +67 -0
  5. package/agent-runtime-server/server/agent-session-service.js +816 -0
  6. package/agent-runtime-server/server/claude-sdk.js +836 -0
  7. package/agent-runtime-server/server/cli.js +330 -0
  8. package/agent-runtime-server/server/constants/config.js +5 -0
  9. package/agent-runtime-server/server/cursor-cli.js +335 -0
  10. package/agent-runtime-server/server/database/db.js +653 -0
  11. package/agent-runtime-server/server/database/init.sql +99 -0
  12. package/agent-runtime-server/server/gemini-cli.js +460 -0
  13. package/agent-runtime-server/server/gemini-response-handler.js +79 -0
  14. package/agent-runtime-server/server/index.js +2569 -0
  15. package/agent-runtime-server/server/load-env.js +32 -0
  16. package/agent-runtime-server/server/middleware/auth.js +132 -0
  17. package/agent-runtime-server/server/openai-codex.js +512 -0
  18. package/agent-runtime-server/server/projects.js +2594 -0
  19. package/agent-runtime-server/server/providers/claude/adapter.js +278 -0
  20. package/agent-runtime-server/server/providers/codex/adapter.js +248 -0
  21. package/agent-runtime-server/server/providers/cursor/adapter.js +353 -0
  22. package/agent-runtime-server/server/providers/gemini/adapter.js +186 -0
  23. package/agent-runtime-server/server/providers/registry.js +44 -0
  24. package/agent-runtime-server/server/providers/types.js +119 -0
  25. package/agent-runtime-server/server/providers/utils.js +29 -0
  26. package/agent-runtime-server/server/routes/agent-sessions.js +238 -0
  27. package/agent-runtime-server/server/routes/agent.js +1244 -0
  28. package/agent-runtime-server/server/routes/auth.js +144 -0
  29. package/agent-runtime-server/server/routes/cli-auth.js +478 -0
  30. package/agent-runtime-server/server/routes/codex.js +329 -0
  31. package/agent-runtime-server/server/routes/commands.js +596 -0
  32. package/agent-runtime-server/server/routes/cursor.js +798 -0
  33. package/agent-runtime-server/server/routes/gemini.js +24 -0
  34. package/agent-runtime-server/server/routes/git.js +1508 -0
  35. package/agent-runtime-server/server/routes/mcp-utils.js +48 -0
  36. package/agent-runtime-server/server/routes/mcp.js +552 -0
  37. package/agent-runtime-server/server/routes/messages.js +61 -0
  38. package/agent-runtime-server/server/routes/plugins.js +307 -0
  39. package/agent-runtime-server/server/routes/projects.js +548 -0
  40. package/agent-runtime-server/server/routes/settings.js +276 -0
  41. package/agent-runtime-server/server/routes/taskmaster.js +1963 -0
  42. package/agent-runtime-server/server/routes/user.js +123 -0
  43. package/agent-runtime-server/server/services/notification-orchestrator.js +227 -0
  44. package/agent-runtime-server/server/services/vapid-keys.js +35 -0
  45. package/agent-runtime-server/server/sessionManager.js +226 -0
  46. package/agent-runtime-server/server/utils/commandParser.js +303 -0
  47. package/agent-runtime-server/server/utils/frontmatter.js +18 -0
  48. package/agent-runtime-server/server/utils/gitConfig.js +34 -0
  49. package/agent-runtime-server/server/utils/mcp-detector.js +198 -0
  50. package/agent-runtime-server/server/utils/plugin-loader.js +457 -0
  51. package/agent-runtime-server/server/utils/plugin-process-manager.js +184 -0
  52. package/agent-runtime-server/server/utils/taskmaster-websocket.js +129 -0
  53. package/agent-runtime-server/shared/modelConstants.js +12 -0
  54. package/agent-runtime-server/shared/modelConstants.test.js +34 -0
  55. package/agent-runtime-server/shared/networkHosts.js +22 -0
  56. package/agent-runtime-server/test_sdk.mjs +16 -0
  57. package/bin/bridges/darwin-x64/nocode-bridge +0 -0
  58. package/bin/{nocode-local.js → notioncode.js} +0 -0
  59. package/dist/assets/icon-CQtd7WEB.png +0 -0
  60. package/dist/assets/index-D_1ZrHDe.js +1 -0
  61. package/dist/assets/index-DhCWie1Z.css +1 -0
  62. package/dist/assets/index-DkGqIiwF.js +689 -0
  63. package/dist/index.html +46 -0
  64. package/dist/onboarding/step1_create.png +0 -0
  65. package/dist/onboarding/step2_capabilities.png +0 -0
  66. package/dist/onboarding/step2b_content_access.png +0 -0
  67. package/dist/onboarding/step2c_page_access.png +0 -0
  68. package/dist/onboarding/step3_token.png +0 -0
  69. package/dist/onboarding/step4_webhook.png +0 -0
  70. package/dist/onboarding/step6a_verify.png +0 -0
  71. package/dist/onboarding/step6b_copy_verify_token.png +0 -0
  72. package/dist/tinyfish-fish-only.png +0 -0
  73. package/lib/install.js +33 -2
  74. package/lib/start.js +157 -25
  75. package/package.json +7 -4
  76. package/src/shared/modelRegistry.d.ts +24 -0
  77. package/src/shared/modelRegistry.js +163 -0
@@ -0,0 +1,2569 @@
1
+ #!/usr/bin/env node
2
+ // Load environment variables before other imports execute
3
+ import './load-env.js';
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import { dirname } from 'path';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = dirname(__filename);
11
+
12
+ const installMode = fs.existsSync(path.join(__dirname, '..', '.git')) ? 'git' : 'npm';
13
+
14
+ // ANSI color codes for terminal output
15
+ const colors = {
16
+ reset: '\x1b[0m',
17
+ bright: '\x1b[1m',
18
+ cyan: '\x1b[36m',
19
+ green: '\x1b[32m',
20
+ yellow: '\x1b[33m',
21
+ blue: '\x1b[34m',
22
+ dim: '\x1b[2m',
23
+ };
24
+
25
+ const c = {
26
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
27
+ ok: (text) => `${colors.green}${text}${colors.reset}`,
28
+ warn: (text) => `${colors.yellow}${text}${colors.reset}`,
29
+ tip: (text) => `${colors.blue}${text}${colors.reset}`,
30
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
31
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
32
+ };
33
+
34
+ console.log('SERVER_PORT from env:', process.env.SERVER_PORT);
35
+
36
+ import express from 'express';
37
+ import { WebSocketServer, WebSocket } from 'ws';
38
+ import os from 'os';
39
+ import http from 'http';
40
+ import cors from 'cors';
41
+ import { promises as fsPromises } from 'fs';
42
+ import { spawn } from 'child_process';
43
+ import pty from 'node-pty';
44
+ import fetch from 'node-fetch';
45
+ import mime from 'mime-types';
46
+
47
+ import { getProjects, getSessions, renameProject, deleteSession, deleteProject, addProjectManually, extractProjectDirectory, clearProjectDirectoryCache, searchConversations } from './projects.js';
48
+ import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions, resolveToolApproval, getPendingApprovalsForSession, reconnectSessionWriter } from './claude-sdk.js';
49
+ import { spawnCursor, abortCursorSession, isCursorSessionActive, getActiveCursorSessions } from './cursor-cli.js';
50
+ import { queryCodex, abortCodexSession, isCodexSessionActive, getActiveCodexSessions } from './openai-codex.js';
51
+ import { spawnGemini, abortGeminiSession, isGeminiSessionActive, getActiveGeminiSessions } from './gemini-cli.js';
52
+ import sessionManager from './sessionManager.js';
53
+ import gitRoutes from './routes/git.js';
54
+ import authRoutes from './routes/auth.js';
55
+ import mcpRoutes from './routes/mcp.js';
56
+ import cursorRoutes from './routes/cursor.js';
57
+ import taskmasterRoutes from './routes/taskmaster.js';
58
+ import mcpUtilsRoutes from './routes/mcp-utils.js';
59
+ import commandsRoutes from './routes/commands.js';
60
+ import settingsRoutes from './routes/settings.js';
61
+ import agentRoutes from './routes/agent.js';
62
+ import projectsRoutes, { WORKSPACES_ROOT, validateWorkspacePath } from './routes/projects.js';
63
+ import cliAuthRoutes from './routes/cli-auth.js';
64
+ import userRoutes from './routes/user.js';
65
+ import codexRoutes from './routes/codex.js';
66
+ import geminiRoutes from './routes/gemini.js';
67
+ import pluginsRoutes from './routes/plugins.js';
68
+ import messagesRoutes from './routes/messages.js';
69
+ import { createNormalizedMessage } from './providers/types.js';
70
+ import { startEnabledPluginServers, stopAllPlugins, getPluginPort } from './utils/plugin-process-manager.js';
71
+ import { initializeDatabase, sessionNamesDb, applyCustomSessionNames } from './database/db.js';
72
+ import { configureWebPush } from './services/vapid-keys.js';
73
+ import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
74
+ import { IS_PLATFORM } from './constants/config.js';
75
+ import { getConnectableHost } from '../shared/networkHosts.js';
76
+
77
+ import agentSessionRoutes from './routes/agent-sessions.js';
78
+ const VALID_PROVIDERS = ['claude', 'codex', 'cursor', 'gemini'];
79
+
80
+ // File system watchers for provider project/session folders
81
+ const PROVIDER_WATCH_PATHS = [
82
+ { provider: 'claude', rootPath: path.join(os.homedir(), '.claude', 'projects') },
83
+ { provider: 'cursor', rootPath: path.join(os.homedir(), '.cursor', 'chats') },
84
+ { provider: 'codex', rootPath: path.join(os.homedir(), '.codex', 'sessions') },
85
+ { provider: 'gemini', rootPath: path.join(os.homedir(), '.gemini', 'projects') },
86
+ { provider: 'gemini_sessions', rootPath: path.join(os.homedir(), '.gemini', 'sessions') }
87
+ ];
88
+ const WATCHER_IGNORED_PATTERNS = [
89
+ '**/node_modules/**',
90
+ '**/.git/**',
91
+ '**/dist/**',
92
+ '**/build/**',
93
+ '**/*.tmp',
94
+ '**/*.swp',
95
+ '**/.DS_Store'
96
+ ];
97
+ const WATCHER_DEBOUNCE_MS = 300;
98
+ let projectsWatchers = [];
99
+ let projectsWatcherDebounceTimer = null;
100
+ const connectedClients = new Set();
101
+ let isGetProjectsRunning = false; // Flag to prevent reentrant calls
102
+
103
+ // Broadcast progress to all connected WebSocket clients
104
+ function broadcastProgress(progress) {
105
+ const message = JSON.stringify({
106
+ type: 'loading_progress',
107
+ ...progress
108
+ });
109
+ connectedClients.forEach(client => {
110
+ if (client.readyState === WebSocket.OPEN) {
111
+ client.send(message);
112
+ }
113
+ });
114
+ }
115
+
116
+ // Setup file system watchers for Claude, Cursor, and Codex project/session folders
117
+ async function setupProjectsWatcher() {
118
+ const chokidar = (await import('chokidar')).default;
119
+
120
+ if (projectsWatcherDebounceTimer) {
121
+ clearTimeout(projectsWatcherDebounceTimer);
122
+ projectsWatcherDebounceTimer = null;
123
+ }
124
+
125
+ await Promise.all(
126
+ projectsWatchers.map(async (watcher) => {
127
+ try {
128
+ await watcher.close();
129
+ } catch (error) {
130
+ console.error('[WARN] Failed to close watcher:', error);
131
+ }
132
+ })
133
+ );
134
+ projectsWatchers = [];
135
+
136
+ const debouncedUpdate = (eventType, filePath, provider, rootPath) => {
137
+ if (projectsWatcherDebounceTimer) {
138
+ clearTimeout(projectsWatcherDebounceTimer);
139
+ }
140
+
141
+ projectsWatcherDebounceTimer = setTimeout(async () => {
142
+ // Prevent reentrant calls
143
+ if (isGetProjectsRunning) {
144
+ return;
145
+ }
146
+
147
+ try {
148
+ isGetProjectsRunning = true;
149
+
150
+ // Clear project directory cache when files change
151
+ clearProjectDirectoryCache();
152
+
153
+ // Get updated projects list
154
+ const updatedProjects = await getProjects(broadcastProgress);
155
+
156
+ // Notify all connected clients about the project changes
157
+ const updateMessage = JSON.stringify({
158
+ type: 'projects_updated',
159
+ projects: updatedProjects,
160
+ timestamp: new Date().toISOString(),
161
+ changeType: eventType,
162
+ changedFile: path.relative(rootPath, filePath),
163
+ watchProvider: provider
164
+ });
165
+
166
+ connectedClients.forEach(client => {
167
+ if (client.readyState === WebSocket.OPEN) {
168
+ client.send(updateMessage);
169
+ }
170
+ });
171
+
172
+ } catch (error) {
173
+ console.error('[ERROR] Error handling project changes:', error);
174
+ } finally {
175
+ isGetProjectsRunning = false;
176
+ }
177
+ }, WATCHER_DEBOUNCE_MS);
178
+ };
179
+
180
+ for (const { provider, rootPath } of PROVIDER_WATCH_PATHS) {
181
+ try {
182
+ // chokidar v4 emits ENOENT via the "error" event for missing roots and will not auto-recover.
183
+ // Ensure provider folders exist before creating the watcher so watching stays active.
184
+ await fsPromises.mkdir(rootPath, { recursive: true });
185
+
186
+ // Initialize chokidar watcher with optimized settings
187
+ const watcher = chokidar.watch(rootPath, {
188
+ ignored: WATCHER_IGNORED_PATTERNS,
189
+ persistent: true,
190
+ ignoreInitial: true, // Don't fire events for existing files on startup
191
+ followSymlinks: false,
192
+ depth: 10, // Reasonable depth limit
193
+ awaitWriteFinish: {
194
+ stabilityThreshold: 100, // Wait 100ms for file to stabilize
195
+ pollInterval: 50
196
+ }
197
+ });
198
+
199
+ // Set up event listeners
200
+ watcher
201
+ .on('add', (filePath) => debouncedUpdate('add', filePath, provider, rootPath))
202
+ .on('change', (filePath) => debouncedUpdate('change', filePath, provider, rootPath))
203
+ .on('unlink', (filePath) => debouncedUpdate('unlink', filePath, provider, rootPath))
204
+ .on('addDir', (dirPath) => debouncedUpdate('addDir', dirPath, provider, rootPath))
205
+ .on('unlinkDir', (dirPath) => debouncedUpdate('unlinkDir', dirPath, provider, rootPath))
206
+ .on('error', (error) => {
207
+ console.error(`[ERROR] ${provider} watcher error:`, error);
208
+ })
209
+ .on('ready', () => {
210
+ });
211
+
212
+ projectsWatchers.push(watcher);
213
+ } catch (error) {
214
+ console.error(`[ERROR] Failed to setup ${provider} watcher for ${rootPath}:`, error);
215
+ }
216
+ }
217
+
218
+ if (projectsWatchers.length === 0) {
219
+ console.error('[ERROR] Failed to setup any provider watchers');
220
+ }
221
+ }
222
+
223
+
224
+ const app = express();
225
+ const server = http.createServer(app);
226
+
227
+ const ptySessionsMap = new Map();
228
+ const PTY_SESSION_TIMEOUT = 30 * 60 * 1000;
229
+ // Single WebSocket server that handles both paths
230
+ const wss = new WebSocketServer({
231
+ server,
232
+ verifyClient: (info) => {
233
+ console.log('WebSocket connection attempt to:', info.req.url);
234
+
235
+ // Platform mode: always allow connection
236
+ if (IS_PLATFORM) {
237
+ const user = authenticateWebSocket(null); // Will return first user
238
+ if (!user) {
239
+ console.log('[WARN] Platform mode: No user found in database');
240
+ return false;
241
+ }
242
+ info.req.user = user;
243
+ console.log('[OK] Platform mode WebSocket authenticated for user:', user.username);
244
+ return true;
245
+ }
246
+
247
+ // Normal mode: verify token
248
+ // Extract token from query parameters or headers
249
+ const url = new URL(info.req.url, 'http://localhost');
250
+ const token = url.searchParams.get('token') ||
251
+ info.req.headers.authorization?.split(' ')[1];
252
+
253
+ // Verify token
254
+ const user = authenticateWebSocket(token);
255
+ if (!user) {
256
+ console.log('[WARN] WebSocket authentication failed');
257
+ return false;
258
+ }
259
+
260
+ // Store user info in the request for later use
261
+ info.req.user = user;
262
+ console.log('[OK] WebSocket authenticated for user:', user.username);
263
+ return true;
264
+ }
265
+ });
266
+
267
+ // Make WebSocket server available to routes
268
+ app.locals.wss = wss;
269
+
270
+ app.use(cors({ exposedHeaders: ['X-Refreshed-Token'] }));
271
+ app.use(express.json({
272
+ limit: '50mb',
273
+ type: (req) => {
274
+ // Skip multipart/form-data requests (for file uploads like images)
275
+ const contentType = req.headers['content-type'] || '';
276
+ if (contentType.includes('multipart/form-data')) {
277
+ return false;
278
+ }
279
+ return contentType.includes('json');
280
+ }
281
+ }));
282
+ app.use(express.urlencoded({ limit: '50mb', extended: true }));
283
+
284
+ // Public health check endpoint (no authentication required)
285
+ app.get('/health', (req, res) => {
286
+ res.json({
287
+ status: 'ok',
288
+ timestamp: new Date().toISOString(),
289
+ installMode,
290
+ platformMode: IS_PLATFORM
291
+ });
292
+ });
293
+
294
+ // Optional API key validation (if configured)
295
+ app.use('/api', validateApiKey);
296
+
297
+ // Authentication routes (public)
298
+ app.use('/api/auth', authRoutes);
299
+
300
+ // Projects API Routes (protected)
301
+ app.use('/api/projects', authenticateToken, projectsRoutes);
302
+
303
+ // Git API Routes (protected)
304
+ app.use('/api/git', authenticateToken, gitRoutes);
305
+
306
+ // MCP API Routes (protected)
307
+ app.use('/api/mcp', authenticateToken, mcpRoutes);
308
+
309
+ // Cursor API Routes (protected)
310
+ app.use('/api/cursor', authenticateToken, cursorRoutes);
311
+
312
+ // TaskMaster API Routes (protected)
313
+ app.use('/api/taskmaster', authenticateToken, taskmasterRoutes);
314
+
315
+ // MCP utilities
316
+ app.use('/api/mcp-utils', authenticateToken, mcpUtilsRoutes);
317
+
318
+ // Commands API Routes (protected)
319
+ app.use('/api/commands', authenticateToken, commandsRoutes);
320
+
321
+ // Settings API Routes (protected)
322
+ app.use('/api/settings', authenticateToken, settingsRoutes);
323
+
324
+ // CLI Authentication API Routes (protected)
325
+ app.use('/api/cli', authenticateToken, cliAuthRoutes);
326
+
327
+ // User API Routes (protected)
328
+ app.use('/api/user', authenticateToken, userRoutes);
329
+
330
+ // Codex API Routes (protected)
331
+ app.use('/api/codex', authenticateToken, codexRoutes);
332
+
333
+ // Gemini API Routes (protected)
334
+ app.use('/api/gemini', authenticateToken, geminiRoutes);
335
+
336
+ // Plugins API Routes (protected)
337
+ app.use('/api/plugins', authenticateToken, pluginsRoutes);
338
+
339
+ // Unified session messages route (protected)
340
+ app.use('/api/sessions', authenticateToken, messagesRoutes);
341
+
342
+ // Agent API Routes (uses API key authentication)
343
+ app.use('/api/agent', agentRoutes);
344
+ app.use('/api/agent', authenticateToken, agentSessionRoutes);
345
+
346
+ // Serve public files (like api-docs.html)
347
+ app.use(express.static(path.join(__dirname, '../public')));
348
+
349
+ // Static files served after API routes
350
+ // Add cache control: HTML files should not be cached, but assets can be cached
351
+ app.use(express.static(path.join(__dirname, '../dist'), {
352
+ setHeaders: (res, filePath) => {
353
+ if (filePath.endsWith('.html')) {
354
+ // Prevent HTML caching to avoid service worker issues after builds
355
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
356
+ res.setHeader('Pragma', 'no-cache');
357
+ res.setHeader('Expires', '0');
358
+ } else if (filePath.match(/\.(js|css|woff2?|ttf|eot|svg|png|jpg|jpeg|gif|ico)$/)) {
359
+ // Cache static assets for 1 year (they have hashed names)
360
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
361
+ }
362
+ }
363
+ }));
364
+
365
+ // API Routes (protected)
366
+ // /api/config endpoint removed - no longer needed
367
+ // Frontend now uses window.location for WebSocket URLs
368
+
369
+ // System update endpoint
370
+ app.post('/api/system/update', authenticateToken, async (req, res) => {
371
+ try {
372
+ // Get the project root directory (parent of server directory)
373
+ const projectRoot = path.join(__dirname, '..');
374
+
375
+ console.log('Starting system update from directory:', projectRoot);
376
+
377
+ // Run the update command based on install mode
378
+ const updateCommand = installMode === 'git'
379
+ ? 'git checkout main && git pull && npm install'
380
+ : 'npm install -g @siteboon/claude-code-ui@latest';
381
+
382
+ const child = spawn('sh', ['-c', updateCommand], {
383
+ cwd: installMode === 'git' ? projectRoot : os.homedir(),
384
+ env: process.env
385
+ });
386
+
387
+ let output = '';
388
+ let errorOutput = '';
389
+
390
+ child.stdout.on('data', (data) => {
391
+ const text = data.toString();
392
+ output += text;
393
+ console.log('Update output:', text);
394
+ });
395
+
396
+ child.stderr.on('data', (data) => {
397
+ const text = data.toString();
398
+ errorOutput += text;
399
+ console.error('Update error:', text);
400
+ });
401
+
402
+ child.on('close', (code) => {
403
+ if (code === 0) {
404
+ res.json({
405
+ success: true,
406
+ output: output || 'Update completed successfully',
407
+ message: 'Update completed. Please restart the server to apply changes.'
408
+ });
409
+ } else {
410
+ res.status(500).json({
411
+ success: false,
412
+ error: 'Update command failed',
413
+ output: output,
414
+ errorOutput: errorOutput
415
+ });
416
+ }
417
+ });
418
+
419
+ child.on('error', (error) => {
420
+ console.error('Update process error:', error);
421
+ res.status(500).json({
422
+ success: false,
423
+ error: error.message
424
+ });
425
+ });
426
+
427
+ } catch (error) {
428
+ console.error('System update error:', error);
429
+ res.status(500).json({
430
+ success: false,
431
+ error: error.message
432
+ });
433
+ }
434
+ });
435
+
436
+ app.get('/api/projects', authenticateToken, async (req, res) => {
437
+ try {
438
+ const projects = await getProjects(broadcastProgress);
439
+ res.json(projects);
440
+ } catch (error) {
441
+ res.status(500).json({ error: error.message });
442
+ }
443
+ });
444
+
445
+ app.get('/api/projects/:projectName/sessions', authenticateToken, async (req, res) => {
446
+ try {
447
+ const { limit = 5, offset = 0 } = req.query;
448
+ const result = await getSessions(req.params.projectName, parseInt(limit), parseInt(offset));
449
+ applyCustomSessionNames(result.sessions, 'claude');
450
+ res.json(result);
451
+ } catch (error) {
452
+ res.status(500).json({ error: error.message });
453
+ }
454
+ });
455
+
456
+ // Rename project endpoint
457
+ app.put('/api/projects/:projectName/rename', authenticateToken, async (req, res) => {
458
+ try {
459
+ const { displayName } = req.body;
460
+ await renameProject(req.params.projectName, displayName);
461
+ res.json({ success: true });
462
+ } catch (error) {
463
+ res.status(500).json({ error: error.message });
464
+ }
465
+ });
466
+
467
+ // Delete session endpoint
468
+ app.delete('/api/projects/:projectName/sessions/:sessionId', authenticateToken, async (req, res) => {
469
+ try {
470
+ const { projectName, sessionId } = req.params;
471
+ console.log(`[API] Deleting session: ${sessionId} from project: ${projectName}`);
472
+ await deleteSession(projectName, sessionId);
473
+ sessionNamesDb.deleteName(sessionId, 'claude');
474
+ console.log(`[API] Session ${sessionId} deleted successfully`);
475
+ res.json({ success: true });
476
+ } catch (error) {
477
+ console.error(`[API] Error deleting session ${req.params.sessionId}:`, error);
478
+ res.status(500).json({ error: error.message });
479
+ }
480
+ });
481
+
482
+ // Rename session endpoint
483
+ app.put('/api/sessions/:sessionId/rename', authenticateToken, async (req, res) => {
484
+ try {
485
+ const { sessionId } = req.params;
486
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
487
+ if (!safeSessionId || safeSessionId !== String(sessionId)) {
488
+ return res.status(400).json({ error: 'Invalid sessionId' });
489
+ }
490
+ const { summary, provider } = req.body;
491
+ if (!summary || typeof summary !== 'string' || summary.trim() === '') {
492
+ return res.status(400).json({ error: 'Summary is required' });
493
+ }
494
+ if (summary.trim().length > 500) {
495
+ return res.status(400).json({ error: 'Summary must not exceed 500 characters' });
496
+ }
497
+ if (!provider || !VALID_PROVIDERS.includes(provider)) {
498
+ return res.status(400).json({ error: `Provider must be one of: ${VALID_PROVIDERS.join(', ')}` });
499
+ }
500
+ sessionNamesDb.setName(safeSessionId, provider, summary.trim());
501
+ res.json({ success: true });
502
+ } catch (error) {
503
+ console.error(`[API] Error renaming session ${req.params.sessionId}:`, error);
504
+ res.status(500).json({ error: error.message });
505
+ }
506
+ });
507
+
508
+ // Delete project endpoint (force=true to delete with sessions)
509
+ app.delete('/api/projects/:projectName', authenticateToken, async (req, res) => {
510
+ try {
511
+ const { projectName } = req.params;
512
+ const force = req.query.force === 'true';
513
+ await deleteProject(projectName, force);
514
+ res.json({ success: true });
515
+ } catch (error) {
516
+ res.status(500).json({ error: error.message });
517
+ }
518
+ });
519
+
520
+ // Create project endpoint
521
+ app.post('/api/projects/create', authenticateToken, async (req, res) => {
522
+ try {
523
+ const { path: projectPath } = req.body;
524
+
525
+ if (!projectPath || !projectPath.trim()) {
526
+ return res.status(400).json({ error: 'Project path is required' });
527
+ }
528
+
529
+ const project = await addProjectManually(projectPath.trim());
530
+ res.json({ success: true, project });
531
+ } catch (error) {
532
+ console.error('Error creating project:', error);
533
+ res.status(500).json({ error: error.message });
534
+ }
535
+ });
536
+
537
+ // Search conversations content (SSE streaming)
538
+ app.get('/api/search/conversations', authenticateToken, async (req, res) => {
539
+ const query = typeof req.query.q === 'string' ? req.query.q.trim() : '';
540
+ const parsedLimit = Number.parseInt(String(req.query.limit), 10);
541
+ const limit = Number.isNaN(parsedLimit) ? 50 : Math.max(1, Math.min(parsedLimit, 100));
542
+
543
+ if (query.length < 2) {
544
+ return res.status(400).json({ error: 'Query must be at least 2 characters' });
545
+ }
546
+
547
+ res.writeHead(200, {
548
+ 'Content-Type': 'text/event-stream',
549
+ 'Cache-Control': 'no-cache',
550
+ 'Connection': 'keep-alive',
551
+ 'X-Accel-Buffering': 'no',
552
+ });
553
+
554
+ let closed = false;
555
+ const abortController = new AbortController();
556
+ req.on('close', () => { closed = true; abortController.abort(); });
557
+
558
+ try {
559
+ await searchConversations(query, limit, ({ projectResult, totalMatches, scannedProjects, totalProjects }) => {
560
+ if (closed) return;
561
+ if (projectResult) {
562
+ res.write(`event: result\ndata: ${JSON.stringify({ projectResult, totalMatches, scannedProjects, totalProjects })}\n\n`);
563
+ } else {
564
+ res.write(`event: progress\ndata: ${JSON.stringify({ totalMatches, scannedProjects, totalProjects })}\n\n`);
565
+ }
566
+ }, abortController.signal);
567
+ if (!closed) {
568
+ res.write(`event: done\ndata: {}\n\n`);
569
+ }
570
+ } catch (error) {
571
+ console.error('Error searching conversations:', error);
572
+ if (!closed) {
573
+ res.write(`event: error\ndata: ${JSON.stringify({ error: 'Search failed' })}\n\n`);
574
+ }
575
+ } finally {
576
+ if (!closed) {
577
+ res.end();
578
+ }
579
+ }
580
+ });
581
+
582
+ const expandWorkspacePath = (inputPath) => {
583
+ if (!inputPath) return inputPath;
584
+ if (inputPath === '~') {
585
+ return WORKSPACES_ROOT;
586
+ }
587
+ if (inputPath.startsWith('~/') || inputPath.startsWith('~\\')) {
588
+ return path.join(WORKSPACES_ROOT, inputPath.slice(2));
589
+ }
590
+ return inputPath;
591
+ };
592
+
593
+ // Browse filesystem endpoint for project suggestions - uses existing getFileTree
594
+ app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
595
+ try {
596
+ const { path: dirPath } = req.query;
597
+
598
+ console.log('[API] Browse filesystem request for path:', dirPath);
599
+ console.log('[API] WORKSPACES_ROOT is:', WORKSPACES_ROOT);
600
+ // Default to home directory if no path provided
601
+ const defaultRoot = WORKSPACES_ROOT;
602
+ let targetPath = dirPath ? expandWorkspacePath(dirPath) : defaultRoot;
603
+
604
+ // Resolve and normalize the path
605
+ targetPath = path.resolve(targetPath);
606
+
607
+ // Security check - ensure path is within allowed workspace root
608
+ const validation = await validateWorkspacePath(targetPath);
609
+ if (!validation.valid) {
610
+ return res.status(403).json({ error: validation.error });
611
+ }
612
+ const resolvedPath = validation.resolvedPath || targetPath;
613
+
614
+ // Security check - ensure path is accessible
615
+ try {
616
+ await fs.promises.access(resolvedPath);
617
+ const stats = await fs.promises.stat(resolvedPath);
618
+
619
+ if (!stats.isDirectory()) {
620
+ return res.status(400).json({ error: 'Path is not a directory' });
621
+ }
622
+ } catch (err) {
623
+ return res.status(404).json({ error: 'Directory not accessible' });
624
+ }
625
+
626
+ // Use existing getFileTree function with shallow depth (only direct children)
627
+ const fileTree = await getFileTree(resolvedPath, 1, 0, false); // maxDepth=1, showHidden=false
628
+
629
+ // Filter only directories and format for suggestions
630
+ const directories = fileTree
631
+ .filter(item => item.type === 'directory')
632
+ .map(item => ({
633
+ path: item.path,
634
+ name: item.name,
635
+ type: 'directory'
636
+ }))
637
+ .sort((a, b) => {
638
+ const aHidden = a.name.startsWith('.');
639
+ const bHidden = b.name.startsWith('.');
640
+ if (aHidden && !bHidden) return 1;
641
+ if (!aHidden && bHidden) return -1;
642
+ return a.name.localeCompare(b.name);
643
+ });
644
+
645
+ // Add common directories if browsing home directory
646
+ const suggestions = [];
647
+ let resolvedWorkspaceRoot = defaultRoot;
648
+ try {
649
+ resolvedWorkspaceRoot = await fsPromises.realpath(defaultRoot);
650
+ } catch (error) {
651
+ // Use default root as-is if realpath fails
652
+ }
653
+ if (resolvedPath === resolvedWorkspaceRoot) {
654
+ const commonDirs = ['Desktop', 'Documents', 'Projects', 'Development', 'Dev', 'Code', 'workspace'];
655
+ const existingCommon = directories.filter(dir => commonDirs.includes(dir.name));
656
+ const otherDirs = directories.filter(dir => !commonDirs.includes(dir.name));
657
+
658
+ suggestions.push(...existingCommon, ...otherDirs);
659
+ } else {
660
+ suggestions.push(...directories);
661
+ }
662
+
663
+ res.json({
664
+ path: resolvedPath,
665
+ suggestions: suggestions
666
+ });
667
+
668
+ } catch (error) {
669
+ console.error('Error browsing filesystem:', error);
670
+ res.status(500).json({ error: 'Failed to browse filesystem' });
671
+ }
672
+ });
673
+
674
+ app.post('/api/create-folder', authenticateToken, async (req, res) => {
675
+ try {
676
+ const { path: folderPath } = req.body;
677
+ if (!folderPath) {
678
+ return res.status(400).json({ error: 'Path is required' });
679
+ }
680
+ const expandedPath = expandWorkspacePath(folderPath);
681
+ const resolvedInput = path.resolve(expandedPath);
682
+ const validation = await validateWorkspacePath(resolvedInput);
683
+ if (!validation.valid) {
684
+ return res.status(403).json({ error: validation.error });
685
+ }
686
+ const targetPath = validation.resolvedPath || resolvedInput;
687
+ const parentDir = path.dirname(targetPath);
688
+ try {
689
+ await fs.promises.access(parentDir);
690
+ } catch (err) {
691
+ return res.status(404).json({ error: 'Parent directory does not exist' });
692
+ }
693
+ try {
694
+ await fs.promises.access(targetPath);
695
+ return res.status(409).json({ error: 'Folder already exists' });
696
+ } catch (err) {
697
+ // Folder doesn't exist, which is what we want
698
+ }
699
+ try {
700
+ await fs.promises.mkdir(targetPath, { recursive: false });
701
+ res.json({ success: true, path: targetPath });
702
+ } catch (mkdirError) {
703
+ if (mkdirError.code === 'EEXIST') {
704
+ return res.status(409).json({ error: 'Folder already exists' });
705
+ }
706
+ throw mkdirError;
707
+ }
708
+ } catch (error) {
709
+ console.error('Error creating folder:', error);
710
+ res.status(500).json({ error: 'Failed to create folder' });
711
+ }
712
+ });
713
+
714
+ // Read file content endpoint
715
+ app.get('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
716
+ try {
717
+ const { projectName } = req.params;
718
+ const { filePath } = req.query;
719
+
720
+
721
+ // Security: ensure the requested path is inside the project root
722
+ if (!filePath) {
723
+ return res.status(400).json({ error: 'Invalid file path' });
724
+ }
725
+
726
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
727
+ if (!projectRoot) {
728
+ return res.status(404).json({ error: 'Project not found' });
729
+ }
730
+
731
+ // Handle both absolute and relative paths
732
+ const resolved = path.isAbsolute(filePath)
733
+ ? path.resolve(filePath)
734
+ : path.resolve(projectRoot, filePath);
735
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
736
+ if (!resolved.startsWith(normalizedRoot)) {
737
+ return res.status(403).json({ error: 'Path must be under project root' });
738
+ }
739
+
740
+ const content = await fsPromises.readFile(resolved, 'utf8');
741
+ res.json({ content, path: resolved });
742
+ } catch (error) {
743
+ console.error('Error reading file:', error);
744
+ if (error.code === 'ENOENT') {
745
+ res.status(404).json({ error: 'File not found' });
746
+ } else if (error.code === 'EACCES') {
747
+ res.status(403).json({ error: 'Permission denied' });
748
+ } else {
749
+ res.status(500).json({ error: error.message });
750
+ }
751
+ }
752
+ });
753
+
754
+ // Serve binary file content endpoint (for images, etc.)
755
+ app.get('/api/projects/:projectName/files/content', authenticateToken, async (req, res) => {
756
+ try {
757
+ const { projectName } = req.params;
758
+ const { path: filePath } = req.query;
759
+
760
+
761
+ // Security: ensure the requested path is inside the project root
762
+ if (!filePath) {
763
+ return res.status(400).json({ error: 'Invalid file path' });
764
+ }
765
+
766
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
767
+ if (!projectRoot) {
768
+ return res.status(404).json({ error: 'Project not found' });
769
+ }
770
+
771
+ const resolved = path.resolve(filePath);
772
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
773
+ if (!resolved.startsWith(normalizedRoot)) {
774
+ return res.status(403).json({ error: 'Path must be under project root' });
775
+ }
776
+
777
+ // Check if file exists
778
+ try {
779
+ await fsPromises.access(resolved);
780
+ } catch (error) {
781
+ return res.status(404).json({ error: 'File not found' });
782
+ }
783
+
784
+ // Get file extension and set appropriate content type
785
+ const mimeType = mime.lookup(resolved) || 'application/octet-stream';
786
+ res.setHeader('Content-Type', mimeType);
787
+
788
+ // Stream the file
789
+ const fileStream = fs.createReadStream(resolved);
790
+ fileStream.pipe(res);
791
+
792
+ fileStream.on('error', (error) => {
793
+ console.error('Error streaming file:', error);
794
+ if (!res.headersSent) {
795
+ res.status(500).json({ error: 'Error reading file' });
796
+ }
797
+ });
798
+
799
+ } catch (error) {
800
+ console.error('Error serving binary file:', error);
801
+ if (!res.headersSent) {
802
+ res.status(500).json({ error: error.message });
803
+ }
804
+ }
805
+ });
806
+
807
+ // Save file content endpoint
808
+ app.put('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
809
+ try {
810
+ const { projectName } = req.params;
811
+ const { filePath, content } = req.body;
812
+
813
+
814
+ // Security: ensure the requested path is inside the project root
815
+ if (!filePath) {
816
+ return res.status(400).json({ error: 'Invalid file path' });
817
+ }
818
+
819
+ if (content === undefined) {
820
+ return res.status(400).json({ error: 'Content is required' });
821
+ }
822
+
823
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
824
+ if (!projectRoot) {
825
+ return res.status(404).json({ error: 'Project not found' });
826
+ }
827
+
828
+ // Handle both absolute and relative paths
829
+ const resolved = path.isAbsolute(filePath)
830
+ ? path.resolve(filePath)
831
+ : path.resolve(projectRoot, filePath);
832
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
833
+ if (!resolved.startsWith(normalizedRoot)) {
834
+ return res.status(403).json({ error: 'Path must be under project root' });
835
+ }
836
+
837
+ // Write the new content
838
+ await fsPromises.writeFile(resolved, content, 'utf8');
839
+
840
+ res.json({
841
+ success: true,
842
+ path: resolved,
843
+ message: 'File saved successfully'
844
+ });
845
+ } catch (error) {
846
+ console.error('Error saving file:', error);
847
+ if (error.code === 'ENOENT') {
848
+ res.status(404).json({ error: 'File or directory not found' });
849
+ } else if (error.code === 'EACCES') {
850
+ res.status(403).json({ error: 'Permission denied' });
851
+ } else {
852
+ res.status(500).json({ error: error.message });
853
+ }
854
+ }
855
+ });
856
+
857
+ app.get('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
858
+ try {
859
+
860
+ // Using fsPromises from import
861
+
862
+ // Use extractProjectDirectory to get the actual project path
863
+ let actualPath;
864
+ try {
865
+ actualPath = await extractProjectDirectory(req.params.projectName);
866
+ } catch (error) {
867
+ console.error('Error extracting project directory:', error);
868
+ // Fallback to simple dash replacement
869
+ actualPath = req.params.projectName.replace(/-/g, '/');
870
+ }
871
+
872
+ // Check if path exists
873
+ try {
874
+ await fsPromises.access(actualPath);
875
+ } catch (e) {
876
+ return res.status(404).json({ error: `Project path not found: ${actualPath}` });
877
+ }
878
+
879
+ const files = await getFileTree(actualPath, 10, 0, true);
880
+ res.json(files);
881
+ } catch (error) {
882
+ console.error('[ERROR] File tree error:', error.message);
883
+ res.status(500).json({ error: error.message });
884
+ }
885
+ });
886
+
887
+ // ============================================================================
888
+ // FILE OPERATIONS API ENDPOINTS
889
+ // ============================================================================
890
+
891
+ /**
892
+ * Validate that a path is within the project root
893
+ * @param {string} projectRoot - The project root path
894
+ * @param {string} targetPath - The path to validate
895
+ * @returns {{ valid: boolean, resolved?: string, error?: string }}
896
+ */
897
+ function validatePathInProject(projectRoot, targetPath) {
898
+ const resolved = path.isAbsolute(targetPath)
899
+ ? path.resolve(targetPath)
900
+ : path.resolve(projectRoot, targetPath);
901
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
902
+ if (!resolved.startsWith(normalizedRoot)) {
903
+ return { valid: false, error: 'Path must be under project root' };
904
+ }
905
+ return { valid: true, resolved };
906
+ }
907
+
908
+ /**
909
+ * Validate filename - check for invalid characters
910
+ * @param {string} name - The filename to validate
911
+ * @returns {{ valid: boolean, error?: string }}
912
+ */
913
+ function validateFilename(name) {
914
+ if (!name || !name.trim()) {
915
+ return { valid: false, error: 'Filename cannot be empty' };
916
+ }
917
+ // Check for invalid characters (Windows + Unix)
918
+ const invalidChars = /[<>:"/\\|?*\x00-\x1f]/;
919
+ if (invalidChars.test(name)) {
920
+ return { valid: false, error: 'Filename contains invalid characters' };
921
+ }
922
+ // Check for reserved names (Windows)
923
+ const reserved = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
924
+ if (reserved.test(name)) {
925
+ return { valid: false, error: 'Filename is a reserved name' };
926
+ }
927
+ // Check for dots only
928
+ if (/^\.+$/.test(name)) {
929
+ return { valid: false, error: 'Filename cannot be only dots' };
930
+ }
931
+ return { valid: true };
932
+ }
933
+
934
+ // POST /api/projects/:projectName/files/create - Create new file or directory
935
+ app.post('/api/projects/:projectName/files/create', authenticateToken, async (req, res) => {
936
+ try {
937
+ const { projectName } = req.params;
938
+ const { path: parentPath, type, name } = req.body;
939
+
940
+ // Validate input
941
+ if (!name || !type) {
942
+ return res.status(400).json({ error: 'Name and type are required' });
943
+ }
944
+
945
+ if (!['file', 'directory'].includes(type)) {
946
+ return res.status(400).json({ error: 'Type must be "file" or "directory"' });
947
+ }
948
+
949
+ const nameValidation = validateFilename(name);
950
+ if (!nameValidation.valid) {
951
+ return res.status(400).json({ error: nameValidation.error });
952
+ }
953
+
954
+ // Get project root
955
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
956
+ if (!projectRoot) {
957
+ return res.status(404).json({ error: 'Project not found' });
958
+ }
959
+
960
+ // Build and validate target path
961
+ const targetDir = parentPath || '';
962
+ const targetPath = targetDir ? path.join(targetDir, name) : name;
963
+ const validation = validatePathInProject(projectRoot, targetPath);
964
+ if (!validation.valid) {
965
+ return res.status(403).json({ error: validation.error });
966
+ }
967
+
968
+ const resolvedPath = validation.resolved;
969
+
970
+ // Check if already exists
971
+ try {
972
+ await fsPromises.access(resolvedPath);
973
+ return res.status(409).json({ error: `${type === 'file' ? 'File' : 'Directory'} already exists` });
974
+ } catch {
975
+ // Doesn't exist, which is what we want
976
+ }
977
+
978
+ // Create file or directory
979
+ if (type === 'directory') {
980
+ await fsPromises.mkdir(resolvedPath, { recursive: false });
981
+ } else {
982
+ // Ensure parent directory exists
983
+ const parentDir = path.dirname(resolvedPath);
984
+ try {
985
+ await fsPromises.access(parentDir);
986
+ } catch {
987
+ await fsPromises.mkdir(parentDir, { recursive: true });
988
+ }
989
+ await fsPromises.writeFile(resolvedPath, '', 'utf8');
990
+ }
991
+
992
+ res.json({
993
+ success: true,
994
+ path: resolvedPath,
995
+ name,
996
+ type,
997
+ message: `${type === 'file' ? 'File' : 'Directory'} created successfully`
998
+ });
999
+ } catch (error) {
1000
+ console.error('Error creating file/directory:', error);
1001
+ if (error.code === 'EACCES') {
1002
+ res.status(403).json({ error: 'Permission denied' });
1003
+ } else if (error.code === 'ENOENT') {
1004
+ res.status(404).json({ error: 'Parent directory not found' });
1005
+ } else {
1006
+ res.status(500).json({ error: error.message });
1007
+ }
1008
+ }
1009
+ });
1010
+
1011
+ // PUT /api/projects/:projectName/files/rename - Rename file or directory
1012
+ app.put('/api/projects/:projectName/files/rename', authenticateToken, async (req, res) => {
1013
+ try {
1014
+ const { projectName } = req.params;
1015
+ const { oldPath, newName } = req.body;
1016
+
1017
+ // Validate input
1018
+ if (!oldPath || !newName) {
1019
+ return res.status(400).json({ error: 'oldPath and newName are required' });
1020
+ }
1021
+
1022
+ const nameValidation = validateFilename(newName);
1023
+ if (!nameValidation.valid) {
1024
+ return res.status(400).json({ error: nameValidation.error });
1025
+ }
1026
+
1027
+ // Get project root
1028
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1029
+ if (!projectRoot) {
1030
+ return res.status(404).json({ error: 'Project not found' });
1031
+ }
1032
+
1033
+ // Validate old path
1034
+ const oldValidation = validatePathInProject(projectRoot, oldPath);
1035
+ if (!oldValidation.valid) {
1036
+ return res.status(403).json({ error: oldValidation.error });
1037
+ }
1038
+
1039
+ const resolvedOldPath = oldValidation.resolved;
1040
+
1041
+ // Check if old path exists
1042
+ try {
1043
+ await fsPromises.access(resolvedOldPath);
1044
+ } catch {
1045
+ return res.status(404).json({ error: 'File or directory not found' });
1046
+ }
1047
+
1048
+ // Build and validate new path
1049
+ const parentDir = path.dirname(resolvedOldPath);
1050
+ const resolvedNewPath = path.join(parentDir, newName);
1051
+ const newValidation = validatePathInProject(projectRoot, resolvedNewPath);
1052
+ if (!newValidation.valid) {
1053
+ return res.status(403).json({ error: newValidation.error });
1054
+ }
1055
+
1056
+ // Check if new path already exists
1057
+ try {
1058
+ await fsPromises.access(resolvedNewPath);
1059
+ return res.status(409).json({ error: 'A file or directory with this name already exists' });
1060
+ } catch {
1061
+ // Doesn't exist, which is what we want
1062
+ }
1063
+
1064
+ // Rename
1065
+ await fsPromises.rename(resolvedOldPath, resolvedNewPath);
1066
+
1067
+ res.json({
1068
+ success: true,
1069
+ oldPath: resolvedOldPath,
1070
+ newPath: resolvedNewPath,
1071
+ newName,
1072
+ message: 'Renamed successfully'
1073
+ });
1074
+ } catch (error) {
1075
+ console.error('Error renaming file/directory:', error);
1076
+ if (error.code === 'EACCES') {
1077
+ res.status(403).json({ error: 'Permission denied' });
1078
+ } else if (error.code === 'ENOENT') {
1079
+ res.status(404).json({ error: 'File or directory not found' });
1080
+ } else if (error.code === 'EXDEV') {
1081
+ res.status(400).json({ error: 'Cannot move across different filesystems' });
1082
+ } else {
1083
+ res.status(500).json({ error: error.message });
1084
+ }
1085
+ }
1086
+ });
1087
+
1088
+ // DELETE /api/projects/:projectName/files - Delete file or directory
1089
+ app.delete('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
1090
+ try {
1091
+ const { projectName } = req.params;
1092
+ const { path: targetPath, type } = req.body;
1093
+
1094
+ // Validate input
1095
+ if (!targetPath) {
1096
+ return res.status(400).json({ error: 'Path is required' });
1097
+ }
1098
+
1099
+ // Get project root
1100
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1101
+ if (!projectRoot) {
1102
+ return res.status(404).json({ error: 'Project not found' });
1103
+ }
1104
+
1105
+ // Validate path
1106
+ const validation = validatePathInProject(projectRoot, targetPath);
1107
+ if (!validation.valid) {
1108
+ return res.status(403).json({ error: validation.error });
1109
+ }
1110
+
1111
+ const resolvedPath = validation.resolved;
1112
+
1113
+ // Check if path exists and get stats
1114
+ let stats;
1115
+ try {
1116
+ stats = await fsPromises.stat(resolvedPath);
1117
+ } catch {
1118
+ return res.status(404).json({ error: 'File or directory not found' });
1119
+ }
1120
+
1121
+ // Prevent deleting the project root itself
1122
+ if (resolvedPath === path.resolve(projectRoot)) {
1123
+ return res.status(403).json({ error: 'Cannot delete project root directory' });
1124
+ }
1125
+
1126
+ // Delete based on type
1127
+ if (stats.isDirectory()) {
1128
+ await fsPromises.rm(resolvedPath, { recursive: true, force: true });
1129
+ } else {
1130
+ await fsPromises.unlink(resolvedPath);
1131
+ }
1132
+
1133
+ res.json({
1134
+ success: true,
1135
+ path: resolvedPath,
1136
+ type: stats.isDirectory() ? 'directory' : 'file',
1137
+ message: 'Deleted successfully'
1138
+ });
1139
+ } catch (error) {
1140
+ console.error('Error deleting file/directory:', error);
1141
+ if (error.code === 'EACCES') {
1142
+ res.status(403).json({ error: 'Permission denied' });
1143
+ } else if (error.code === 'ENOENT') {
1144
+ res.status(404).json({ error: 'File or directory not found' });
1145
+ } else if (error.code === 'ENOTEMPTY') {
1146
+ res.status(400).json({ error: 'Directory is not empty' });
1147
+ } else {
1148
+ res.status(500).json({ error: error.message });
1149
+ }
1150
+ }
1151
+ });
1152
+
1153
+ // POST /api/projects/:projectName/files/upload - Upload files
1154
+ // Dynamic import of multer for file uploads
1155
+ const uploadFilesHandler = async (req, res) => {
1156
+ // Dynamic import of multer
1157
+ const multer = (await import('multer')).default;
1158
+
1159
+ const uploadMiddleware = multer({
1160
+ storage: multer.diskStorage({
1161
+ destination: (req, file, cb) => {
1162
+ cb(null, os.tmpdir());
1163
+ },
1164
+ filename: (req, file, cb) => {
1165
+ // Use a unique temp name, but preserve original name in file.originalname
1166
+ // Note: file.originalname may contain path separators for folder uploads
1167
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
1168
+ // For temp file, just use a safe unique name without the path
1169
+ cb(null, `upload-${uniqueSuffix}`);
1170
+ }
1171
+ }),
1172
+ limits: {
1173
+ fileSize: 50 * 1024 * 1024, // 50MB limit
1174
+ files: 20 // Max 20 files at once
1175
+ }
1176
+ });
1177
+
1178
+ // Use multer middleware
1179
+ uploadMiddleware.array('files', 20)(req, res, async (err) => {
1180
+ if (err) {
1181
+ console.error('Multer error:', err);
1182
+ if (err.code === 'LIMIT_FILE_SIZE') {
1183
+ return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' });
1184
+ }
1185
+ if (err.code === 'LIMIT_FILE_COUNT') {
1186
+ return res.status(400).json({ error: 'Too many files. Maximum is 20 files.' });
1187
+ }
1188
+ return res.status(500).json({ error: err.message });
1189
+ }
1190
+
1191
+ try {
1192
+ const { projectName } = req.params;
1193
+ const { targetPath, relativePaths } = req.body;
1194
+
1195
+ // Parse relative paths if provided (for folder uploads)
1196
+ let filePaths = [];
1197
+ if (relativePaths) {
1198
+ try {
1199
+ filePaths = JSON.parse(relativePaths);
1200
+ } catch (e) {
1201
+ console.log('[DEBUG] Failed to parse relativePaths:', relativePaths);
1202
+ }
1203
+ }
1204
+
1205
+ console.log('[DEBUG] File upload request:', {
1206
+ projectName,
1207
+ targetPath: JSON.stringify(targetPath),
1208
+ targetPathType: typeof targetPath,
1209
+ filesCount: req.files?.length,
1210
+ relativePaths: filePaths
1211
+ });
1212
+
1213
+ if (!req.files || req.files.length === 0) {
1214
+ return res.status(400).json({ error: 'No files provided' });
1215
+ }
1216
+
1217
+ // Get project root
1218
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1219
+ if (!projectRoot) {
1220
+ return res.status(404).json({ error: 'Project not found' });
1221
+ }
1222
+
1223
+ console.log('[DEBUG] Project root:', projectRoot);
1224
+
1225
+ // Validate and resolve target path
1226
+ // If targetPath is empty or '.', use project root directly
1227
+ const targetDir = targetPath || '';
1228
+ let resolvedTargetDir;
1229
+
1230
+ console.log('[DEBUG] Target dir:', JSON.stringify(targetDir));
1231
+
1232
+ if (!targetDir || targetDir === '.' || targetDir === './') {
1233
+ // Empty path means upload to project root
1234
+ resolvedTargetDir = path.resolve(projectRoot);
1235
+ console.log('[DEBUG] Using project root as target:', resolvedTargetDir);
1236
+ } else {
1237
+ const validation = validatePathInProject(projectRoot, targetDir);
1238
+ if (!validation.valid) {
1239
+ console.log('[DEBUG] Path validation failed:', validation.error);
1240
+ return res.status(403).json({ error: validation.error });
1241
+ }
1242
+ resolvedTargetDir = validation.resolved;
1243
+ console.log('[DEBUG] Resolved target dir:', resolvedTargetDir);
1244
+ }
1245
+
1246
+ // Ensure target directory exists
1247
+ try {
1248
+ await fsPromises.access(resolvedTargetDir);
1249
+ } catch {
1250
+ await fsPromises.mkdir(resolvedTargetDir, { recursive: true });
1251
+ }
1252
+
1253
+ // Move uploaded files from temp to target directory
1254
+ const uploadedFiles = [];
1255
+ console.log('[DEBUG] Processing files:', req.files.map(f => ({ originalname: f.originalname, path: f.path })));
1256
+ for (let i = 0; i < req.files.length; i++) {
1257
+ const file = req.files[i];
1258
+ // Use relative path if provided (for folder uploads), otherwise use originalname
1259
+ const fileName = (filePaths && filePaths[i]) ? filePaths[i] : file.originalname;
1260
+ console.log('[DEBUG] Processing file:', fileName, '(originalname:', file.originalname + ')');
1261
+ const destPath = path.join(resolvedTargetDir, fileName);
1262
+
1263
+ // Validate destination path
1264
+ const destValidation = validatePathInProject(projectRoot, destPath);
1265
+ if (!destValidation.valid) {
1266
+ console.log('[DEBUG] Destination validation failed for:', destPath);
1267
+ // Clean up temp file
1268
+ await fsPromises.unlink(file.path).catch(() => {});
1269
+ continue;
1270
+ }
1271
+
1272
+ // Ensure parent directory exists (for nested files from folder upload)
1273
+ const parentDir = path.dirname(destPath);
1274
+ try {
1275
+ await fsPromises.access(parentDir);
1276
+ } catch {
1277
+ await fsPromises.mkdir(parentDir, { recursive: true });
1278
+ }
1279
+
1280
+ // Move file (copy + unlink to handle cross-device scenarios)
1281
+ await fsPromises.copyFile(file.path, destPath);
1282
+ await fsPromises.unlink(file.path);
1283
+
1284
+ uploadedFiles.push({
1285
+ name: fileName,
1286
+ path: destPath,
1287
+ size: file.size,
1288
+ mimeType: file.mimetype
1289
+ });
1290
+ }
1291
+
1292
+ res.json({
1293
+ success: true,
1294
+ files: uploadedFiles,
1295
+ targetPath: resolvedTargetDir,
1296
+ message: `Uploaded ${uploadedFiles.length} file(s) successfully`
1297
+ });
1298
+ } catch (error) {
1299
+ console.error('Error uploading files:', error);
1300
+ // Clean up any remaining temp files
1301
+ if (req.files) {
1302
+ for (const file of req.files) {
1303
+ await fsPromises.unlink(file.path).catch(() => {});
1304
+ }
1305
+ }
1306
+ if (error.code === 'EACCES') {
1307
+ res.status(403).json({ error: 'Permission denied' });
1308
+ } else {
1309
+ res.status(500).json({ error: error.message });
1310
+ }
1311
+ }
1312
+ });
1313
+ };
1314
+
1315
+ app.post('/api/projects/:projectName/files/upload', authenticateToken, uploadFilesHandler);
1316
+
1317
+ /**
1318
+ * Proxy an authenticated client WebSocket to a plugin's internal WS server.
1319
+ * Auth is enforced by verifyClient before this function is reached.
1320
+ */
1321
+ function handlePluginWsProxy(clientWs, pathname) {
1322
+ const pluginName = pathname.replace('/plugin-ws/', '');
1323
+ if (!pluginName || /[^a-zA-Z0-9_-]/.test(pluginName)) {
1324
+ clientWs.close(4400, 'Invalid plugin name');
1325
+ return;
1326
+ }
1327
+
1328
+ const port = getPluginPort(pluginName);
1329
+ if (!port) {
1330
+ clientWs.close(4404, 'Plugin not running');
1331
+ return;
1332
+ }
1333
+
1334
+ const upstream = new WebSocket(`ws://127.0.0.1:${port}/ws`);
1335
+
1336
+ upstream.on('open', () => {
1337
+ console.log(`[Plugins] WS proxy connected to "${pluginName}" on port ${port}`);
1338
+ });
1339
+
1340
+ // Relay messages bidirectionally
1341
+ upstream.on('message', (data) => {
1342
+ if (clientWs.readyState === WebSocket.OPEN) clientWs.send(data);
1343
+ });
1344
+ clientWs.on('message', (data) => {
1345
+ if (upstream.readyState === WebSocket.OPEN) upstream.send(data);
1346
+ });
1347
+
1348
+ // Propagate close in both directions
1349
+ upstream.on('close', () => { if (clientWs.readyState === WebSocket.OPEN) clientWs.close(); });
1350
+ clientWs.on('close', () => { if (upstream.readyState === WebSocket.OPEN) upstream.close(); });
1351
+
1352
+ upstream.on('error', (err) => {
1353
+ console.error(`[Plugins] WS proxy error for "${pluginName}":`, err.message);
1354
+ if (clientWs.readyState === WebSocket.OPEN) clientWs.close(4502, 'Upstream error');
1355
+ });
1356
+ clientWs.on('error', () => {
1357
+ if (upstream.readyState === WebSocket.OPEN) upstream.close();
1358
+ });
1359
+ }
1360
+
1361
+ // WebSocket connection handler that routes based on URL path
1362
+ wss.on('connection', (ws, request) => {
1363
+ const url = request.url;
1364
+ console.log('[INFO] Client connected to:', url);
1365
+
1366
+ // Parse URL to get pathname without query parameters
1367
+ const urlObj = new URL(url, 'http://localhost');
1368
+ const pathname = urlObj.pathname;
1369
+
1370
+ if (pathname === '/shell') {
1371
+ handleShellConnection(ws);
1372
+ } else if (pathname === '/ws') {
1373
+ handleChatConnection(ws, request);
1374
+ } else if (pathname.startsWith('/plugin-ws/')) {
1375
+ handlePluginWsProxy(ws, pathname);
1376
+ } else {
1377
+ console.log('[WARN] Unknown WebSocket path:', pathname);
1378
+ ws.close();
1379
+ }
1380
+ });
1381
+
1382
+ /**
1383
+ * WebSocket Writer - Wrapper for WebSocket to match SSEStreamWriter interface
1384
+ *
1385
+ * Provider files use `createNormalizedMessage()` from `providers/types.js` and
1386
+ * adapter `normalizeMessage()` to produce unified NormalizedMessage events.
1387
+ * The writer simply serialises and sends.
1388
+ */
1389
+ class WebSocketWriter {
1390
+ constructor(ws, userId = null) {
1391
+ this.ws = ws;
1392
+ this.sessionId = null;
1393
+ this.userId = userId;
1394
+ this.isWebSocketWriter = true; // Marker for transport detection
1395
+ }
1396
+
1397
+ send(data) {
1398
+ if (this.ws.readyState === 1) { // WebSocket.OPEN
1399
+ this.ws.send(JSON.stringify(data));
1400
+ }
1401
+ }
1402
+
1403
+ updateWebSocket(newRawWs) {
1404
+ this.ws = newRawWs;
1405
+ }
1406
+
1407
+ setSessionId(sessionId) {
1408
+ this.sessionId = sessionId;
1409
+ }
1410
+
1411
+ getSessionId() {
1412
+ return this.sessionId;
1413
+ }
1414
+ }
1415
+
1416
+ // Handle chat WebSocket connections
1417
+ function handleChatConnection(ws, request) {
1418
+ console.log('[INFO] Chat WebSocket connected');
1419
+
1420
+ // Add to connected clients for project updates
1421
+ connectedClients.add(ws);
1422
+
1423
+ // Wrap WebSocket with writer for consistent interface with SSEStreamWriter
1424
+ const writer = new WebSocketWriter(ws, request?.user?.id ?? request?.user?.userId ?? null);
1425
+
1426
+ ws.on('message', async (message) => {
1427
+ try {
1428
+ const data = JSON.parse(message);
1429
+
1430
+ if (data.type === 'claude-command') {
1431
+ console.log('[DEBUG] User message:', data.command || '[Continue/Resume]');
1432
+ console.log('📁 Project:', data.options?.projectPath || 'Unknown');
1433
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1434
+
1435
+ // Use Claude Agents SDK
1436
+ await queryClaudeSDK(data.command, data.options, writer);
1437
+ } else if (data.type === 'cursor-command') {
1438
+ console.log('[DEBUG] Cursor message:', data.command || '[Continue/Resume]');
1439
+ console.log('📁 Project:', data.options?.cwd || 'Unknown');
1440
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1441
+ console.log('🤖 Model:', data.options?.model || 'default');
1442
+ await spawnCursor(data.command, data.options, writer);
1443
+ } else if (data.type === 'codex-command') {
1444
+ console.log('[DEBUG] Codex message:', data.command || '[Continue/Resume]');
1445
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
1446
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1447
+ console.log('🤖 Model:', data.options?.model || 'default');
1448
+ await queryCodex(data.command, data.options, writer);
1449
+ } else if (data.type === 'gemini-command') {
1450
+ console.log('[DEBUG] Gemini message:', data.command || '[Continue/Resume]');
1451
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
1452
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1453
+ console.log('🤖 Model:', data.options?.model || 'default');
1454
+ await spawnGemini(data.command, data.options, writer);
1455
+ } else if (data.type === 'cursor-resume') {
1456
+ // Backward compatibility: treat as cursor-command with resume and no prompt
1457
+ console.log('[DEBUG] Cursor resume session (compat):', data.sessionId);
1458
+ await spawnCursor('', {
1459
+ sessionId: data.sessionId,
1460
+ resume: true,
1461
+ cwd: data.options?.cwd
1462
+ }, writer);
1463
+ } else if (data.type === 'abort-session') {
1464
+ console.log('[DEBUG] Abort session request:', data.sessionId);
1465
+ const provider = data.provider || 'claude';
1466
+ let success;
1467
+
1468
+ if (provider === 'cursor') {
1469
+ success = abortCursorSession(data.sessionId);
1470
+ } else if (provider === 'codex') {
1471
+ success = abortCodexSession(data.sessionId);
1472
+ } else if (provider === 'gemini') {
1473
+ success = abortGeminiSession(data.sessionId);
1474
+ } else {
1475
+ // Use Claude Agents SDK
1476
+ success = await abortClaudeSDKSession(data.sessionId);
1477
+ }
1478
+
1479
+ writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider }));
1480
+ } else if (data.type === 'claude-permission-response') {
1481
+ // Relay UI approval decisions back into the SDK control flow.
1482
+ // This does not persist permissions; it only resolves the in-flight request,
1483
+ // introduced so the SDK can resume once the user clicks Allow/Deny.
1484
+ if (data.requestId) {
1485
+ resolveToolApproval(data.requestId, {
1486
+ allow: Boolean(data.allow),
1487
+ updatedInput: data.updatedInput,
1488
+ message: data.message,
1489
+ rememberEntry: data.rememberEntry
1490
+ });
1491
+ }
1492
+ } else if (data.type === 'cursor-abort') {
1493
+ console.log('[DEBUG] Abort Cursor session:', data.sessionId);
1494
+ const success = abortCursorSession(data.sessionId);
1495
+ writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider: 'cursor' }));
1496
+ } else if (data.type === 'check-session-status') {
1497
+ // Check if a specific session is currently processing
1498
+ const provider = data.provider || 'claude';
1499
+ const sessionId = data.sessionId;
1500
+ let isActive;
1501
+
1502
+ if (provider === 'cursor') {
1503
+ isActive = isCursorSessionActive(sessionId);
1504
+ } else if (provider === 'codex') {
1505
+ isActive = isCodexSessionActive(sessionId);
1506
+ } else if (provider === 'gemini') {
1507
+ isActive = isGeminiSessionActive(sessionId);
1508
+ } else {
1509
+ // Use Claude Agents SDK
1510
+ isActive = isClaudeSDKSessionActive(sessionId);
1511
+ if (isActive) {
1512
+ // Reconnect the session's writer to the new WebSocket so
1513
+ // subsequent SDK output flows to the refreshed client.
1514
+ reconnectSessionWriter(sessionId, ws);
1515
+ }
1516
+ }
1517
+
1518
+ writer.send({
1519
+ type: 'session-status',
1520
+ sessionId,
1521
+ provider,
1522
+ isProcessing: isActive
1523
+ });
1524
+ } else if (data.type === 'get-pending-permissions') {
1525
+ // Return pending permission requests for a session
1526
+ const sessionId = data.sessionId;
1527
+ if (sessionId && isClaudeSDKSessionActive(sessionId)) {
1528
+ const pending = getPendingApprovalsForSession(sessionId);
1529
+ writer.send({
1530
+ type: 'pending-permissions-response',
1531
+ sessionId,
1532
+ data: pending
1533
+ });
1534
+ }
1535
+ } else if (data.type === 'get-active-sessions') {
1536
+ // Get all currently active sessions
1537
+ const activeSessions = {
1538
+ claude: getActiveClaudeSDKSessions(),
1539
+ cursor: getActiveCursorSessions(),
1540
+ codex: getActiveCodexSessions(),
1541
+ gemini: getActiveGeminiSessions()
1542
+ };
1543
+ writer.send({
1544
+ type: 'active-sessions',
1545
+ sessions: activeSessions
1546
+ });
1547
+ }
1548
+ } catch (error) {
1549
+ console.error('[ERROR] Chat WebSocket error:', error.message);
1550
+ writer.send({
1551
+ type: 'error',
1552
+ error: error.message
1553
+ });
1554
+ }
1555
+ });
1556
+
1557
+ ws.on('close', () => {
1558
+ console.log('🔌 Chat client disconnected');
1559
+ // Remove from connected clients
1560
+ connectedClients.delete(ws);
1561
+ });
1562
+ }
1563
+
1564
+ function normalizeShellProfile(profile) {
1565
+ if (!profile || typeof profile !== 'object') {
1566
+ return null;
1567
+ }
1568
+
1569
+ const shellPath = typeof profile.path === 'string' ? profile.path.trim() : '';
1570
+ if (!shellPath) {
1571
+ return null;
1572
+ }
1573
+
1574
+ return {
1575
+ id: typeof profile.id === 'string' ? profile.id.trim().toLowerCase() : '',
1576
+ label: typeof profile.label === 'string' ? profile.label.trim() : '',
1577
+ path: shellPath,
1578
+ args: Array.isArray(profile.args)
1579
+ ? profile.args.filter((value) => typeof value === 'string' && value.trim().length > 0)
1580
+ : []
1581
+ };
1582
+ }
1583
+
1584
+ function buildPlainShellLaunch(shellProfile, shellCommand) {
1585
+ const platform = os.platform();
1586
+ const normalized = normalizeShellProfile(shellProfile);
1587
+
1588
+ if (!normalized) {
1589
+ return {
1590
+ shell: platform === 'win32' ? 'powershell.exe' : 'bash',
1591
+ shellArgs: shellCommand
1592
+ ? (platform === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand])
1593
+ : []
1594
+ };
1595
+ }
1596
+
1597
+ const lowerPath = normalized.path.toLowerCase();
1598
+ const lowerId = normalized.id;
1599
+ const baseArgs = [...normalized.args];
1600
+ const baseName = path.win32.basename(lowerPath);
1601
+ const isCommandPrompt =
1602
+ platform === 'win32' &&
1603
+ (lowerId === 'command-prompt' || baseName === 'cmd.exe' || baseName === 'cmd');
1604
+ const isPowerShell =
1605
+ platform === 'win32' &&
1606
+ (lowerId.includes('powershell') || baseName === 'powershell.exe' || baseName === 'pwsh.exe');
1607
+ const isFish = /(^|[\\/])fish(\.exe)?$/i.test(normalized.path) || lowerId === 'fish';
1608
+ const isBashLike =
1609
+ /(^|[\\/])(bash|sh|zsh|dash|ksh)(\.exe)?$/i.test(normalized.path) ||
1610
+ lowerId === 'git-bash' ||
1611
+ lowerId === 'bash' ||
1612
+ lowerId === 'zsh' ||
1613
+ lowerId === 'system-shell';
1614
+
1615
+ if (!shellCommand) {
1616
+ return {
1617
+ shell: normalized.path,
1618
+ shellArgs: baseArgs
1619
+ };
1620
+ }
1621
+
1622
+ if (isCommandPrompt) {
1623
+ return {
1624
+ shell: normalized.path,
1625
+ shellArgs: [...baseArgs, '/D', '/S', '/C', shellCommand]
1626
+ };
1627
+ }
1628
+
1629
+ if (isPowerShell) {
1630
+ return {
1631
+ shell: normalized.path,
1632
+ shellArgs: [...baseArgs, '-Command', shellCommand]
1633
+ };
1634
+ }
1635
+
1636
+ if (isBashLike) {
1637
+ return {
1638
+ shell: normalized.path,
1639
+ shellArgs: [...baseArgs, '-lc', shellCommand]
1640
+ };
1641
+ }
1642
+
1643
+ return {
1644
+ shell: normalized.path,
1645
+ shellArgs: [...baseArgs, '-c', shellCommand]
1646
+ };
1647
+ }
1648
+
1649
+ // Handle shell WebSocket connections
1650
+ function handleShellConnection(ws) {
1651
+ console.log('🐚 Shell client connected');
1652
+ let shellProcess = null;
1653
+ let ptySessionKey = null;
1654
+
1655
+ ws.on('message', async (message) => {
1656
+ try {
1657
+ const data = JSON.parse(message);
1658
+ console.log('📨 Shell message received:', data.type);
1659
+
1660
+ if (data.type === 'init') {
1661
+ const projectPath = data.projectPath || process.cwd();
1662
+ const sessionId = data.sessionId;
1663
+ const hasSession = data.hasSession;
1664
+ const provider = data.provider || 'claude';
1665
+ const initialCommand = data.initialCommand;
1666
+ const shellProfile = normalizeShellProfile(data.shellProfile);
1667
+ const isPlainShell = data.isPlainShell || (!!initialCommand && !hasSession) || provider === 'plain-shell';
1668
+
1669
+ // Login commands (Claude/Cursor auth) should never reuse cached sessions
1670
+ const isLoginCommand = initialCommand && (
1671
+ initialCommand.includes('setup-token') ||
1672
+ initialCommand.includes('cursor-agent login') ||
1673
+ initialCommand.includes('auth login')
1674
+ );
1675
+
1676
+ // Include command hash in session key so different commands get separate sessions
1677
+ const commandSuffix = isPlainShell && initialCommand
1678
+ ? `_cmd_${Buffer.from(initialCommand).toString('base64').slice(0, 16)}`
1679
+ : '';
1680
+ ptySessionKey = `${projectPath}_${sessionId || 'default'}${commandSuffix}`;
1681
+
1682
+ // Kill any existing login session before starting fresh
1683
+ if (isLoginCommand) {
1684
+ const oldSession = ptySessionsMap.get(ptySessionKey);
1685
+ if (oldSession) {
1686
+ console.log('🧹 Cleaning up existing login session:', ptySessionKey);
1687
+ if (oldSession.timeoutId) clearTimeout(oldSession.timeoutId);
1688
+ if (oldSession.pty && oldSession.pty.kill) oldSession.pty.kill();
1689
+ ptySessionsMap.delete(ptySessionKey);
1690
+ }
1691
+ }
1692
+
1693
+ const existingSession = isLoginCommand ? null : ptySessionsMap.get(ptySessionKey);
1694
+ if (existingSession) {
1695
+ console.log('♻️ Reconnecting to existing PTY session:', ptySessionKey);
1696
+ shellProcess = existingSession.pty;
1697
+
1698
+ clearTimeout(existingSession.timeoutId);
1699
+
1700
+ ws.send(JSON.stringify({
1701
+ type: 'output',
1702
+ data: `\x1b[36m[Reconnected to existing session]\x1b[0m\r\n`
1703
+ }));
1704
+
1705
+ if (existingSession.buffer && existingSession.buffer.length > 0) {
1706
+ console.log(`📜 Sending ${existingSession.buffer.length} buffered messages`);
1707
+ existingSession.buffer.forEach(bufferedData => {
1708
+ ws.send(JSON.stringify({
1709
+ type: 'output',
1710
+ data: bufferedData
1711
+ }));
1712
+ });
1713
+ }
1714
+
1715
+ existingSession.ws = ws;
1716
+
1717
+ return;
1718
+ }
1719
+
1720
+ console.log('[INFO] Starting shell in:', projectPath);
1721
+ console.log('📋 Session info:', hasSession ? `Resume session ${sessionId}` : (isPlainShell ? 'Plain shell mode' : 'New session'));
1722
+ console.log('🤖 Provider:', isPlainShell ? 'plain-shell' : provider);
1723
+ if (initialCommand) {
1724
+ console.log('⚡ Initial command:', initialCommand);
1725
+ }
1726
+ if (isPlainShell && shellProfile) {
1727
+ console.log('🐚 Shell profile:', shellProfile.label || shellProfile.path);
1728
+ }
1729
+
1730
+ // First send a welcome message
1731
+ let welcomeMsg;
1732
+ if (isPlainShell) {
1733
+ welcomeMsg = `\x1b[36mStarting terminal in: ${projectPath}\x1b[0m\r\n`;
1734
+ } else {
1735
+ const providerName = provider === 'cursor' ? 'Cursor' : (provider === 'codex' ? 'Codex' : (provider === 'gemini' ? 'Gemini' : 'Claude'));
1736
+ welcomeMsg = hasSession ?
1737
+ `\x1b[36mResuming ${providerName} session ${sessionId} in: ${projectPath}\x1b[0m\r\n` :
1738
+ `\x1b[36mStarting new ${providerName} session in: ${projectPath}\x1b[0m\r\n`;
1739
+ }
1740
+
1741
+ ws.send(JSON.stringify({
1742
+ type: 'output',
1743
+ data: welcomeMsg
1744
+ }));
1745
+
1746
+ try {
1747
+ // Validate projectPath — resolve to absolute and verify it exists
1748
+ const resolvedProjectPath = path.resolve(projectPath);
1749
+ try {
1750
+ const stats = fs.statSync(resolvedProjectPath);
1751
+ if (!stats.isDirectory()) {
1752
+ throw new Error('Not a directory');
1753
+ }
1754
+ } catch (pathErr) {
1755
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid project path' }));
1756
+ return;
1757
+ }
1758
+
1759
+ // Validate sessionId — only allow safe characters
1760
+ const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
1761
+ if (sessionId && !safeSessionIdPattern.test(sessionId)) {
1762
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid session ID' }));
1763
+ return;
1764
+ }
1765
+
1766
+ // Build shell command — use cwd for project path (never interpolate into shell string)
1767
+ let shellCommand;
1768
+ if (isPlainShell) {
1769
+ // Plain shell mode - run the initial command in the project directory
1770
+ shellCommand = initialCommand;
1771
+ } else if (provider === 'cursor') {
1772
+ if (hasSession && sessionId) {
1773
+ shellCommand = `cursor-agent --resume="${sessionId}"`;
1774
+ } else {
1775
+ shellCommand = 'cursor-agent';
1776
+ }
1777
+ } else if (provider === 'codex') {
1778
+ // Use codex command; attempt to resume and fall back to a new session when the resume fails.
1779
+ if (hasSession && sessionId) {
1780
+ if (os.platform() === 'win32') {
1781
+ // PowerShell syntax for fallback
1782
+ shellCommand = `codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
1783
+ } else {
1784
+ shellCommand = `codex resume "${sessionId}" || codex`;
1785
+ }
1786
+ } else {
1787
+ shellCommand = 'codex';
1788
+ }
1789
+ } else if (provider === 'gemini') {
1790
+ const command = initialCommand || 'gemini';
1791
+ let resumeId = sessionId;
1792
+ if (hasSession && sessionId) {
1793
+ try {
1794
+ // Gemini CLI enforces its own native session IDs, unlike other agents that accept arbitrary string names.
1795
+ // The UI only knows about its internal generated `sessionId` (e.g. gemini_1234).
1796
+ // We must fetch the mapping from the backend session manager to pass the native `cliSessionId` to the shell.
1797
+ const sess = sessionManager.getSession(sessionId);
1798
+ if (sess && sess.cliSessionId) {
1799
+ resumeId = sess.cliSessionId;
1800
+ // Validate the looked-up CLI session ID too
1801
+ if (!safeSessionIdPattern.test(resumeId)) {
1802
+ resumeId = null;
1803
+ }
1804
+ }
1805
+ } catch (err) {
1806
+ console.error('Failed to get Gemini CLI session ID:', err);
1807
+ }
1808
+ }
1809
+
1810
+ if (hasSession && resumeId) {
1811
+ shellCommand = `${command} --resume "${resumeId}"`;
1812
+ } else {
1813
+ shellCommand = command;
1814
+ }
1815
+ } else {
1816
+ // Claude (default provider)
1817
+ const command = initialCommand || 'claude';
1818
+ if (hasSession && sessionId) {
1819
+ if (os.platform() === 'win32') {
1820
+ shellCommand = `claude --resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { claude }`;
1821
+ } else {
1822
+ shellCommand = `claude --resume "${sessionId}" || claude`;
1823
+ }
1824
+ } else {
1825
+ shellCommand = command;
1826
+ }
1827
+ }
1828
+
1829
+ console.log('🔧 Executing shell command:', shellCommand);
1830
+
1831
+ const { shell, shellArgs } = isPlainShell
1832
+ ? buildPlainShellLaunch(shellProfile, shellCommand)
1833
+ : {
1834
+ shell: os.platform() === 'win32' ? 'powershell.exe' : 'bash',
1835
+ shellArgs: shellCommand
1836
+ ? (os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand])
1837
+ : []
1838
+ };
1839
+
1840
+ // Use terminal dimensions from client if provided, otherwise use defaults
1841
+ const termCols = data.cols || 80;
1842
+ const termRows = data.rows || 24;
1843
+ console.log('📐 Using terminal dimensions:', termCols, 'x', termRows);
1844
+
1845
+ shellProcess = pty.spawn(shell, shellArgs, {
1846
+ name: 'xterm-256color',
1847
+ cols: termCols,
1848
+ rows: termRows,
1849
+ cwd: resolvedProjectPath,
1850
+ env: {
1851
+ ...process.env,
1852
+ TERM: 'xterm-256color',
1853
+ COLORTERM: 'truecolor',
1854
+ FORCE_COLOR: '3'
1855
+ }
1856
+ });
1857
+
1858
+ console.log('🟢 Shell process started with PTY, PID:', shellProcess.pid);
1859
+
1860
+ ptySessionsMap.set(ptySessionKey, {
1861
+ pty: shellProcess,
1862
+ ws: ws,
1863
+ buffer: [],
1864
+ timeoutId: null,
1865
+ projectPath,
1866
+ sessionId
1867
+ });
1868
+
1869
+ // Handle data output
1870
+ shellProcess.onData((data) => {
1871
+ const session = ptySessionsMap.get(ptySessionKey);
1872
+ if (!session) return;
1873
+
1874
+ if (session.buffer.length < 5000) {
1875
+ session.buffer.push(data);
1876
+ } else {
1877
+ session.buffer.shift();
1878
+ session.buffer.push(data);
1879
+ }
1880
+
1881
+ if (session.ws && session.ws.readyState === WebSocket.OPEN) {
1882
+ let outputData = data;
1883
+
1884
+ outputData = outputData.replace(
1885
+ /OPEN_URL:\s*(https?:\/\/[^\s\x1b\x07]+)/g,
1886
+ '[INFO] Opening in browser: $1'
1887
+ );
1888
+
1889
+ // Send regular output
1890
+ session.ws.send(JSON.stringify({
1891
+ type: 'output',
1892
+ data: outputData
1893
+ }));
1894
+ }
1895
+ });
1896
+
1897
+ // Handle process exit
1898
+ shellProcess.onExit((exitCode) => {
1899
+ console.log('🔚 Shell process exited with code:', exitCode.exitCode, 'signal:', exitCode.signal);
1900
+ const session = ptySessionsMap.get(ptySessionKey);
1901
+ if (session && session.ws && session.ws.readyState === WebSocket.OPEN) {
1902
+ session.ws.send(JSON.stringify({
1903
+ type: 'output',
1904
+ data: `\r\n\x1b[33mProcess exited with code ${exitCode.exitCode}${exitCode.signal ? ` (${exitCode.signal})` : ''}\x1b[0m\r\n`
1905
+ }));
1906
+ }
1907
+ if (session && session.timeoutId) {
1908
+ clearTimeout(session.timeoutId);
1909
+ }
1910
+ ptySessionsMap.delete(ptySessionKey);
1911
+ shellProcess = null;
1912
+ });
1913
+
1914
+ } catch (spawnError) {
1915
+ console.error('[ERROR] Error spawning process:', spawnError);
1916
+ ws.send(JSON.stringify({
1917
+ type: 'output',
1918
+ data: `\r\n\x1b[31mError: ${spawnError.message}\x1b[0m\r\n`
1919
+ }));
1920
+ }
1921
+
1922
+ } else if (data.type === 'input') {
1923
+ // Send input to shell process
1924
+ if (shellProcess && shellProcess.write) {
1925
+ try {
1926
+ shellProcess.write(data.data);
1927
+ } catch (error) {
1928
+ console.error('Error writing to shell:', error);
1929
+ }
1930
+ } else {
1931
+ console.warn('No active shell process to send input to');
1932
+ }
1933
+ } else if (data.type === 'resize') {
1934
+ // Handle terminal resize
1935
+ if (shellProcess && shellProcess.resize) {
1936
+ console.log('Terminal resize requested:', data.cols, 'x', data.rows);
1937
+ shellProcess.resize(data.cols, data.rows);
1938
+ }
1939
+ }
1940
+ } catch (error) {
1941
+ console.error('[ERROR] Shell WebSocket error:', error.message);
1942
+ if (ws.readyState === WebSocket.OPEN) {
1943
+ ws.send(JSON.stringify({
1944
+ type: 'output',
1945
+ data: `\r\n\x1b[31mError: ${error.message}\x1b[0m\r\n`
1946
+ }));
1947
+ }
1948
+ }
1949
+ });
1950
+
1951
+ ws.on('close', () => {
1952
+ console.log('🔌 Shell client disconnected');
1953
+
1954
+ if (ptySessionKey) {
1955
+ const session = ptySessionsMap.get(ptySessionKey);
1956
+ if (session) {
1957
+ console.log('⏳ PTY session kept alive, will timeout in 30 minutes:', ptySessionKey);
1958
+ session.ws = null;
1959
+
1960
+ session.timeoutId = setTimeout(() => {
1961
+ console.log('⏰ PTY session timeout, killing process:', ptySessionKey);
1962
+ if (session.pty && session.pty.kill) {
1963
+ session.pty.kill();
1964
+ }
1965
+ ptySessionsMap.delete(ptySessionKey);
1966
+ }, PTY_SESSION_TIMEOUT);
1967
+ }
1968
+ }
1969
+ });
1970
+
1971
+ ws.on('error', (error) => {
1972
+ console.error('[ERROR] Shell WebSocket error:', error);
1973
+ });
1974
+ }
1975
+ // Audio transcription endpoint
1976
+ app.post('/api/transcribe', authenticateToken, async (req, res) => {
1977
+ try {
1978
+ const multer = (await import('multer')).default;
1979
+ const upload = multer({ storage: multer.memoryStorage() });
1980
+
1981
+ // Handle multipart form data
1982
+ upload.single('audio')(req, res, async (err) => {
1983
+ if (err) {
1984
+ return res.status(400).json({ error: 'Failed to process audio file' });
1985
+ }
1986
+
1987
+ if (!req.file) {
1988
+ return res.status(400).json({ error: 'No audio file provided' });
1989
+ }
1990
+
1991
+ const apiKey = process.env.OPENAI_API_KEY;
1992
+ if (!apiKey) {
1993
+ return res.status(500).json({ error: 'OpenAI API key not configured. Please set OPENAI_API_KEY in server environment.' });
1994
+ }
1995
+
1996
+ try {
1997
+ // Create form data for OpenAI
1998
+ const FormData = (await import('form-data')).default;
1999
+ const formData = new FormData();
2000
+ formData.append('file', req.file.buffer, {
2001
+ filename: req.file.originalname,
2002
+ contentType: req.file.mimetype
2003
+ });
2004
+ formData.append('model', 'whisper-1');
2005
+ formData.append('response_format', 'json');
2006
+ formData.append('language', 'en');
2007
+
2008
+ // Make request to OpenAI
2009
+ const response = await fetch('https://api.openai.com/v1/audio/transcriptions', {
2010
+ method: 'POST',
2011
+ headers: {
2012
+ 'Authorization': `Bearer ${apiKey}`,
2013
+ ...formData.getHeaders()
2014
+ },
2015
+ body: formData
2016
+ });
2017
+
2018
+ if (!response.ok) {
2019
+ const errorData = await response.json().catch(() => ({}));
2020
+ throw new Error(errorData.error?.message || `Whisper API error: ${response.status}`);
2021
+ }
2022
+
2023
+ const data = await response.json();
2024
+ let transcribedText = data.text || '';
2025
+
2026
+ // Check if enhancement mode is enabled
2027
+ const mode = req.body.mode || 'default';
2028
+
2029
+ // If no transcribed text, return empty
2030
+ if (!transcribedText) {
2031
+ return res.json({ text: '' });
2032
+ }
2033
+
2034
+ // If default mode, return transcribed text without enhancement
2035
+ if (mode === 'default') {
2036
+ return res.json({ text: transcribedText });
2037
+ }
2038
+
2039
+ // Handle different enhancement modes
2040
+ try {
2041
+ const OpenAI = (await import('openai')).default;
2042
+ const openai = new OpenAI({ apiKey });
2043
+
2044
+ let prompt, systemMessage, temperature = 0.7, maxTokens = 800;
2045
+
2046
+ switch (mode) {
2047
+ case 'prompt':
2048
+ systemMessage = 'You are an expert prompt engineer who creates clear, detailed, and effective prompts.';
2049
+ prompt = `You are an expert prompt engineer. Transform the following rough instruction into a clear, detailed, and context-aware AI prompt.
2050
+
2051
+ Your enhanced prompt should:
2052
+ 1. Be specific and unambiguous
2053
+ 2. Include relevant context and constraints
2054
+ 3. Specify the desired output format
2055
+ 4. Use clear, actionable language
2056
+ 5. Include examples where helpful
2057
+ 6. Consider edge cases and potential ambiguities
2058
+
2059
+ Transform this rough instruction into a well-crafted prompt:
2060
+ "${transcribedText}"
2061
+
2062
+ Enhanced prompt:`;
2063
+ break;
2064
+
2065
+ case 'vibe':
2066
+ case 'instructions':
2067
+ case 'architect':
2068
+ systemMessage = 'You are a helpful assistant that formats ideas into clear, actionable instructions for AI agents.';
2069
+ temperature = 0.5; // Lower temperature for more controlled output
2070
+ prompt = `Transform the following idea into clear, well-structured instructions that an AI agent can easily understand and execute.
2071
+
2072
+ IMPORTANT RULES:
2073
+ - Format as clear, step-by-step instructions
2074
+ - Add reasonable implementation details based on common patterns
2075
+ - Only include details directly related to what was asked
2076
+ - Do NOT add features or functionality not mentioned
2077
+ - Keep the original intent and scope intact
2078
+ - Use clear, actionable language an agent can follow
2079
+
2080
+ Transform this idea into agent-friendly instructions:
2081
+ "${transcribedText}"
2082
+
2083
+ Agent instructions:`;
2084
+ break;
2085
+
2086
+ default:
2087
+ // No enhancement needed
2088
+ break;
2089
+ }
2090
+
2091
+ // Only make GPT call if we have a prompt
2092
+ if (prompt) {
2093
+ const completion = await openai.chat.completions.create({
2094
+ model: 'gpt-4o-mini',
2095
+ messages: [
2096
+ { role: 'system', content: systemMessage },
2097
+ { role: 'user', content: prompt }
2098
+ ],
2099
+ temperature: temperature,
2100
+ max_tokens: maxTokens
2101
+ });
2102
+
2103
+ transcribedText = completion.choices[0].message.content || transcribedText;
2104
+ }
2105
+
2106
+ } catch (gptError) {
2107
+ console.error('GPT processing error:', gptError);
2108
+ // Fall back to original transcription if GPT fails
2109
+ }
2110
+
2111
+ res.json({ text: transcribedText });
2112
+
2113
+ } catch (error) {
2114
+ console.error('Transcription error:', error);
2115
+ res.status(500).json({ error: error.message });
2116
+ }
2117
+ });
2118
+ } catch (error) {
2119
+ console.error('Endpoint error:', error);
2120
+ res.status(500).json({ error: 'Internal server error' });
2121
+ }
2122
+ });
2123
+
2124
+ // Image upload endpoint
2125
+ app.post('/api/projects/:projectName/upload-images', authenticateToken, async (req, res) => {
2126
+ try {
2127
+ const multer = (await import('multer')).default;
2128
+ const path = (await import('path')).default;
2129
+ const fs = (await import('fs')).promises;
2130
+ const os = (await import('os')).default;
2131
+
2132
+ // Configure multer for image uploads
2133
+ const storage = multer.diskStorage({
2134
+ destination: async (req, file, cb) => {
2135
+ const uploadDir = path.join(os.tmpdir(), 'claude-ui-uploads', String(req.user.id));
2136
+ await fs.mkdir(uploadDir, { recursive: true });
2137
+ cb(null, uploadDir);
2138
+ },
2139
+ filename: (req, file, cb) => {
2140
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
2141
+ const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
2142
+ cb(null, uniqueSuffix + '-' + sanitizedName);
2143
+ }
2144
+ });
2145
+
2146
+ const fileFilter = (req, file, cb) => {
2147
+ const allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
2148
+ if (allowedMimes.includes(file.mimetype)) {
2149
+ cb(null, true);
2150
+ } else {
2151
+ cb(new Error('Invalid file type. Only JPEG, PNG, GIF, WebP, and SVG are allowed.'));
2152
+ }
2153
+ };
2154
+
2155
+ const upload = multer({
2156
+ storage,
2157
+ fileFilter,
2158
+ limits: {
2159
+ fileSize: 5 * 1024 * 1024, // 5MB
2160
+ files: 5
2161
+ }
2162
+ });
2163
+
2164
+ // Handle multipart form data
2165
+ upload.array('images', 5)(req, res, async (err) => {
2166
+ if (err) {
2167
+ return res.status(400).json({ error: err.message });
2168
+ }
2169
+
2170
+ if (!req.files || req.files.length === 0) {
2171
+ return res.status(400).json({ error: 'No image files provided' });
2172
+ }
2173
+
2174
+ try {
2175
+ // Process uploaded images
2176
+ const processedImages = await Promise.all(
2177
+ req.files.map(async (file) => {
2178
+ // Read file and convert to base64
2179
+ const buffer = await fs.readFile(file.path);
2180
+ const base64 = buffer.toString('base64');
2181
+ const mimeType = file.mimetype;
2182
+
2183
+ // Clean up temp file immediately
2184
+ await fs.unlink(file.path);
2185
+
2186
+ return {
2187
+ name: file.originalname,
2188
+ data: `data:${mimeType};base64,${base64}`,
2189
+ size: file.size,
2190
+ mimeType: mimeType
2191
+ };
2192
+ })
2193
+ );
2194
+
2195
+ res.json({ images: processedImages });
2196
+ } catch (error) {
2197
+ console.error('Error processing images:', error);
2198
+ // Clean up any remaining files
2199
+ await Promise.all(req.files.map(f => fs.unlink(f.path).catch(() => { })));
2200
+ res.status(500).json({ error: 'Failed to process images' });
2201
+ }
2202
+ });
2203
+ } catch (error) {
2204
+ console.error('Error in image upload endpoint:', error);
2205
+ res.status(500).json({ error: 'Internal server error' });
2206
+ }
2207
+ });
2208
+
2209
+ // Get token usage for a specific session
2210
+ app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
2211
+ try {
2212
+ const { projectName, sessionId } = req.params;
2213
+ const { provider = 'claude' } = req.query;
2214
+ const homeDir = os.homedir();
2215
+
2216
+ // Allow only safe characters in sessionId
2217
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
2218
+ if (!safeSessionId || safeSessionId !== String(sessionId)) {
2219
+ return res.status(400).json({ error: 'Invalid sessionId' });
2220
+ }
2221
+
2222
+ // Handle Cursor sessions - they use SQLite and don't have token usage info
2223
+ if (provider === 'cursor') {
2224
+ return res.json({
2225
+ used: 0,
2226
+ total: 0,
2227
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
2228
+ unsupported: true,
2229
+ message: 'Token usage tracking not available for Cursor sessions'
2230
+ });
2231
+ }
2232
+
2233
+ // Handle Gemini sessions - they are raw logs in our current setup
2234
+ if (provider === 'gemini') {
2235
+ return res.json({
2236
+ used: 0,
2237
+ total: 0,
2238
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
2239
+ unsupported: true,
2240
+ message: 'Token usage tracking not available for Gemini sessions'
2241
+ });
2242
+ }
2243
+
2244
+ // Handle Codex sessions
2245
+ if (provider === 'codex') {
2246
+ const codexSessionsDir = path.join(homeDir, '.codex', 'sessions');
2247
+
2248
+ // Find the session file by searching for the session ID
2249
+ const findSessionFile = async (dir) => {
2250
+ try {
2251
+ const entries = await fsPromises.readdir(dir, { withFileTypes: true });
2252
+ for (const entry of entries) {
2253
+ const fullPath = path.join(dir, entry.name);
2254
+ if (entry.isDirectory()) {
2255
+ const found = await findSessionFile(fullPath);
2256
+ if (found) return found;
2257
+ } else if (entry.name.includes(safeSessionId) && entry.name.endsWith('.jsonl')) {
2258
+ return fullPath;
2259
+ }
2260
+ }
2261
+ } catch (error) {
2262
+ // Skip directories we can't read
2263
+ }
2264
+ return null;
2265
+ };
2266
+
2267
+ const sessionFilePath = await findSessionFile(codexSessionsDir);
2268
+
2269
+ if (!sessionFilePath) {
2270
+ return res.status(404).json({ error: 'Codex session file not found', sessionId: safeSessionId });
2271
+ }
2272
+
2273
+ // Read and parse the Codex JSONL file
2274
+ let fileContent;
2275
+ try {
2276
+ fileContent = await fsPromises.readFile(sessionFilePath, 'utf8');
2277
+ } catch (error) {
2278
+ if (error.code === 'ENOENT') {
2279
+ return res.status(404).json({ error: 'Session file not found', path: sessionFilePath });
2280
+ }
2281
+ throw error;
2282
+ }
2283
+ const lines = fileContent.trim().split('\n');
2284
+ let totalTokens = 0;
2285
+ let contextWindow = 200000; // Default for Codex/OpenAI
2286
+
2287
+ // Find the latest token_count event with info (scan from end)
2288
+ for (let i = lines.length - 1; i >= 0; i--) {
2289
+ try {
2290
+ const entry = JSON.parse(lines[i]);
2291
+
2292
+ // Codex stores token info in event_msg with type: "token_count"
2293
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
2294
+ const tokenInfo = entry.payload.info;
2295
+ if (tokenInfo.total_token_usage) {
2296
+ totalTokens = tokenInfo.total_token_usage.total_tokens || 0;
2297
+ }
2298
+ if (tokenInfo.model_context_window) {
2299
+ contextWindow = tokenInfo.model_context_window;
2300
+ }
2301
+ break; // Stop after finding the latest token count
2302
+ }
2303
+ } catch (parseError) {
2304
+ // Skip lines that can't be parsed
2305
+ continue;
2306
+ }
2307
+ }
2308
+
2309
+ return res.json({
2310
+ used: totalTokens,
2311
+ total: contextWindow
2312
+ });
2313
+ }
2314
+
2315
+ // Handle Claude sessions (default)
2316
+ // Extract actual project path
2317
+ let projectPath;
2318
+ try {
2319
+ projectPath = await extractProjectDirectory(projectName);
2320
+ } catch (error) {
2321
+ console.error('Error extracting project directory:', error);
2322
+ return res.status(500).json({ error: 'Failed to determine project path' });
2323
+ }
2324
+
2325
+ // Construct the JSONL file path
2326
+ // Claude stores session files in ~/.claude/projects/[encoded-project-path]/[session-id].jsonl
2327
+ // The encoding replaces any non-alphanumeric character (except -) with -
2328
+ const encodedPath = projectPath.replace(/[^a-zA-Z0-9-]/g, '-');
2329
+ const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
2330
+
2331
+ const jsonlPath = path.join(projectDir, `${safeSessionId}.jsonl`);
2332
+
2333
+ // Constrain to projectDir
2334
+ const rel = path.relative(path.resolve(projectDir), path.resolve(jsonlPath));
2335
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
2336
+ return res.status(400).json({ error: 'Invalid path' });
2337
+ }
2338
+
2339
+ // Read and parse the JSONL file
2340
+ let fileContent;
2341
+ try {
2342
+ fileContent = await fsPromises.readFile(jsonlPath, 'utf8');
2343
+ } catch (error) {
2344
+ if (error.code === 'ENOENT') {
2345
+ return res.status(404).json({ error: 'Session file not found', path: jsonlPath });
2346
+ }
2347
+ throw error; // Re-throw other errors to be caught by outer try-catch
2348
+ }
2349
+ const lines = fileContent.trim().split('\n');
2350
+
2351
+ const parsedContextWindow = parseInt(process.env.CONTEXT_WINDOW, 10);
2352
+ const contextWindow = Number.isFinite(parsedContextWindow) ? parsedContextWindow : 160000;
2353
+ let inputTokens = 0;
2354
+ let cacheCreationTokens = 0;
2355
+ let cacheReadTokens = 0;
2356
+
2357
+ // Find the latest assistant message with usage data (scan from end)
2358
+ for (let i = lines.length - 1; i >= 0; i--) {
2359
+ try {
2360
+ const entry = JSON.parse(lines[i]);
2361
+
2362
+ // Only count assistant messages which have usage data
2363
+ if (entry.type === 'assistant' && entry.message?.usage) {
2364
+ const usage = entry.message.usage;
2365
+
2366
+ // Use token counts from latest assistant message only
2367
+ inputTokens = usage.input_tokens || 0;
2368
+ cacheCreationTokens = usage.cache_creation_input_tokens || 0;
2369
+ cacheReadTokens = usage.cache_read_input_tokens || 0;
2370
+
2371
+ break; // Stop after finding the latest assistant message
2372
+ }
2373
+ } catch (parseError) {
2374
+ // Skip lines that can't be parsed
2375
+ continue;
2376
+ }
2377
+ }
2378
+
2379
+ // Calculate total context usage (excluding output_tokens, as per ccusage)
2380
+ const totalUsed = inputTokens + cacheCreationTokens + cacheReadTokens;
2381
+
2382
+ res.json({
2383
+ used: totalUsed,
2384
+ total: contextWindow,
2385
+ breakdown: {
2386
+ input: inputTokens,
2387
+ cacheCreation: cacheCreationTokens,
2388
+ cacheRead: cacheReadTokens
2389
+ }
2390
+ });
2391
+ } catch (error) {
2392
+ console.error('Error reading session token usage:', error);
2393
+ res.status(500).json({ error: 'Failed to read session token usage' });
2394
+ }
2395
+ });
2396
+
2397
+ // Serve React app for all other routes (excluding static files)
2398
+ app.get('*', (req, res) => {
2399
+ // Skip requests for static assets (files with extensions)
2400
+ if (path.extname(req.path)) {
2401
+ return res.status(404).send('Not found');
2402
+ }
2403
+
2404
+ // Only serve index.html for HTML routes, not for static assets
2405
+ // Static assets should already be handled by express.static middleware above
2406
+ const indexPath = path.join(__dirname, '../dist/index.html');
2407
+
2408
+ // Check if dist/index.html exists (production build available)
2409
+ if (fs.existsSync(indexPath)) {
2410
+ // Set no-cache headers for HTML to prevent service worker issues
2411
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
2412
+ res.setHeader('Pragma', 'no-cache');
2413
+ res.setHeader('Expires', '0');
2414
+ res.sendFile(indexPath);
2415
+ } else {
2416
+ // In development, redirect to Vite dev server only if dist doesn't exist
2417
+ const redirectHost = getConnectableHost(req.hostname);
2418
+ res.redirect(`${req.protocol}://${redirectHost}:${VITE_PORT}`);
2419
+ }
2420
+ });
2421
+
2422
+ // Helper function to convert permissions to rwx format
2423
+ function permToRwx(perm) {
2424
+ const r = perm & 4 ? 'r' : '-';
2425
+ const w = perm & 2 ? 'w' : '-';
2426
+ const x = perm & 1 ? 'x' : '-';
2427
+ return r + w + x;
2428
+ }
2429
+
2430
+ async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden = true) {
2431
+ // Using fsPromises from import
2432
+ const items = [];
2433
+
2434
+ try {
2435
+ const entries = await fsPromises.readdir(dirPath, { withFileTypes: true });
2436
+
2437
+ for (const entry of entries) {
2438
+ // Debug: log all entries including hidden files
2439
+
2440
+
2441
+ // Skip heavy build directories and VCS directories
2442
+ if (entry.name === 'node_modules' ||
2443
+ entry.name === 'dist' ||
2444
+ entry.name === 'build' ||
2445
+ entry.name === '.git' ||
2446
+ entry.name === '.svn' ||
2447
+ entry.name === '.hg') continue;
2448
+
2449
+ const itemPath = path.join(dirPath, entry.name);
2450
+ const item = {
2451
+ name: entry.name,
2452
+ path: itemPath,
2453
+ type: entry.isDirectory() ? 'directory' : 'file'
2454
+ };
2455
+
2456
+ // Get file stats for additional metadata
2457
+ try {
2458
+ const stats = await fsPromises.stat(itemPath);
2459
+ item.size = stats.size;
2460
+ item.modified = stats.mtime.toISOString();
2461
+
2462
+ // Convert permissions to rwx format
2463
+ const mode = stats.mode;
2464
+ const ownerPerm = (mode >> 6) & 7;
2465
+ const groupPerm = (mode >> 3) & 7;
2466
+ const otherPerm = mode & 7;
2467
+ item.permissions = ((mode >> 6) & 7).toString() + ((mode >> 3) & 7).toString() + (mode & 7).toString();
2468
+ item.permissionsRwx = permToRwx(ownerPerm) + permToRwx(groupPerm) + permToRwx(otherPerm);
2469
+ } catch (statError) {
2470
+ // If stat fails, provide default values
2471
+ item.size = 0;
2472
+ item.modified = null;
2473
+ item.permissions = '000';
2474
+ item.permissionsRwx = '---------';
2475
+ }
2476
+
2477
+ if (entry.isDirectory() && currentDepth < maxDepth) {
2478
+ // Recursively get subdirectories but limit depth
2479
+ try {
2480
+ // Check if we can access the directory before trying to read it
2481
+ await fsPromises.access(item.path, fs.constants.R_OK);
2482
+ item.children = await getFileTree(item.path, maxDepth, currentDepth + 1, showHidden);
2483
+ } catch (e) {
2484
+ // Silently skip directories we can't access (permission denied, etc.)
2485
+ item.children = [];
2486
+ }
2487
+ }
2488
+
2489
+ items.push(item);
2490
+ }
2491
+ } catch (error) {
2492
+ // Only log non-permission errors to avoid spam
2493
+ if (error.code !== 'EACCES' && error.code !== 'EPERM') {
2494
+ console.error('Error reading directory:', error);
2495
+ }
2496
+ }
2497
+
2498
+ return items.sort((a, b) => {
2499
+ if (a.type !== b.type) {
2500
+ return a.type === 'directory' ? -1 : 1;
2501
+ }
2502
+ return a.name.localeCompare(b.name);
2503
+ });
2504
+ }
2505
+
2506
+ const SERVER_PORT = process.env.SERVER_PORT || 3001;
2507
+ const HOST = process.env.HOST || '0.0.0.0';
2508
+ const DISPLAY_HOST = getConnectableHost(HOST);
2509
+ const VITE_PORT = process.env.VITE_PORT || 5173;
2510
+
2511
+ // Initialize database and start server
2512
+ async function startServer() {
2513
+ try {
2514
+ // Initialize authentication database
2515
+ await initializeDatabase();
2516
+
2517
+ // Configure Web Push (VAPID keys)
2518
+ configureWebPush();
2519
+
2520
+ // Check if running in production mode (dist folder exists)
2521
+ const distIndexPath = path.join(__dirname, '../dist/index.html');
2522
+ const isProduction = fs.existsSync(distIndexPath);
2523
+
2524
+ // Log Claude implementation mode
2525
+ console.log(`${c.info('[INFO]')} Using Claude Agents SDK for Claude integration`);
2526
+ console.log('');
2527
+
2528
+ if (isProduction) {
2529
+ console.log(`${c.info('[INFO]')} To run in production mode, go to http://${DISPLAY_HOST}:${SERVER_PORT}`);
2530
+ }
2531
+
2532
+ console.log(`${c.info('[INFO]')} To run in development mode with hot-module replacement, go to http://${DISPLAY_HOST}:${VITE_PORT}`);
2533
+
2534
+ server.listen(SERVER_PORT, HOST, async () => {
2535
+ const appInstallPath = path.join(__dirname, '..');
2536
+
2537
+ console.log('');
2538
+ console.log(c.dim('═'.repeat(63)));
2539
+ console.log(` ${c.bright('Claude Code UI Server - Ready')}`);
2540
+ console.log(c.dim('═'.repeat(63)));
2541
+ console.log('');
2542
+ console.log(`${c.info('[INFO]')} Server URL: ${c.bright('http://' + DISPLAY_HOST + ':' + SERVER_PORT)}`);
2543
+ console.log(`${c.info('[INFO]')} Installed at: ${c.dim(appInstallPath)}`);
2544
+ console.log(`${c.tip('[TIP]')} Run "notion-code-agent status" for full configuration details`);
2545
+ console.log('');
2546
+
2547
+ // Start watching the projects folder for changes
2548
+ await setupProjectsWatcher();
2549
+
2550
+ // Start server-side plugin processes for enabled plugins
2551
+ startEnabledPluginServers().catch(err => {
2552
+ console.error('[Plugins] Error during startup:', err.message);
2553
+ });
2554
+ });
2555
+
2556
+ // Clean up plugin processes on shutdown
2557
+ const shutdownPlugins = async () => {
2558
+ await stopAllPlugins();
2559
+ process.exit(0);
2560
+ };
2561
+ process.on('SIGTERM', () => void shutdownPlugins());
2562
+ process.on('SIGINT', () => void shutdownPlugins());
2563
+ } catch (error) {
2564
+ console.error('[ERROR] Failed to start server:', error);
2565
+ process.exit(1);
2566
+ }
2567
+ }
2568
+
2569
+ startServer();