@pixelbyte-software/pixcode 1.35.2 → 1.35.3

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 (173) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-D1-AIL_5.js → index-D8z78r_D.js} +57 -57
  11. package/dist/assets/{index-B8w57E1r.css → index-DmchzORZ.css} +1 -1
  12. package/dist/clear-cache.html +85 -85
  13. package/dist/convert-icons.md +52 -52
  14. package/dist/favicon.svg +8 -8
  15. package/dist/generate-icons.js +48 -48
  16. package/dist/icons/codex-white.svg +3 -3
  17. package/dist/icons/codex.svg +3 -3
  18. package/dist/icons/cursor-white.svg +11 -11
  19. package/dist/icons/icon-128x128.svg +9 -9
  20. package/dist/icons/icon-144x144.svg +9 -9
  21. package/dist/icons/icon-152x152.svg +9 -9
  22. package/dist/icons/icon-192x192.svg +9 -9
  23. package/dist/icons/icon-384x384.svg +9 -9
  24. package/dist/icons/icon-512x512.svg +9 -9
  25. package/dist/icons/icon-72x72.svg +9 -9
  26. package/dist/icons/icon-96x96.svg +9 -9
  27. package/dist/icons/icon-template.svg +9 -9
  28. package/dist/icons/qwen-logo.svg +14 -14
  29. package/dist/index.html +59 -59
  30. package/dist/logo.svg +12 -12
  31. package/dist/manifest.json +60 -60
  32. package/dist/openapi.yaml +1693 -1693
  33. package/dist/sw.js +124 -124
  34. package/dist-server/server/cli.js +96 -96
  35. package/dist-server/server/daemon/manager.js +33 -33
  36. package/dist-server/server/daemon-manager.js +64 -64
  37. package/dist-server/server/routes/commands.js +25 -25
  38. package/dist-server/server/routes/git.js +17 -17
  39. package/dist-server/server/routes/taskmaster.js +419 -419
  40. package/package.json +180 -180
  41. package/scripts/fix-node-pty.js +67 -67
  42. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  43. package/scripts/smoke/orchestration-api.mjs +172 -172
  44. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  45. package/server/claude-sdk.js +898 -898
  46. package/server/cli.js +935 -935
  47. package/server/constants/config.js +4 -4
  48. package/server/cursor-cli.js +342 -342
  49. package/server/daemon/manager.js +564 -564
  50. package/server/daemon-manager.js +959 -959
  51. package/server/database/db.js +794 -794
  52. package/server/database/json-store.js +197 -197
  53. package/server/gemini-cli.js +535 -535
  54. package/server/gemini-response-handler.js +79 -79
  55. package/server/index.js +3135 -3135
  56. package/server/load-env.js +34 -34
  57. package/server/middleware/auth.js +173 -173
  58. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  59. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  60. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  61. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  62. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  63. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  64. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  65. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  66. package/server/modules/orchestration/a2a/routes.ts +577 -577
  67. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  68. package/server/modules/orchestration/a2a/types.ts +125 -125
  69. package/server/modules/orchestration/a2a/validator.ts +113 -113
  70. package/server/modules/orchestration/index.ts +66 -66
  71. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  72. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  73. package/server/modules/orchestration/preview/types.ts +19 -19
  74. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  75. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  76. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  77. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  78. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  79. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  80. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  81. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  82. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  83. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  84. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  85. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  86. package/server/modules/orchestration/workspace/types.ts +52 -52
  87. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  88. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  89. package/server/modules/providers/index.ts +2 -2
  90. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  91. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  92. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  93. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  94. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  95. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  96. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  97. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  98. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  99. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  100. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  101. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  102. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  103. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  104. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  105. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  106. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  107. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  108. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  109. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  110. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  111. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  112. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  113. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  114. package/server/modules/providers/provider.registry.ts +40 -40
  115. package/server/modules/providers/provider.routes.ts +819 -819
  116. package/server/modules/providers/services/mcp.service.ts +86 -86
  117. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  118. package/server/modules/providers/services/sessions.service.ts +45 -45
  119. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  120. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  121. package/server/modules/providers/shared/provider-configs.ts +142 -142
  122. package/server/modules/providers/tests/mcp.test.ts +293 -293
  123. package/server/openai-codex.js +462 -462
  124. package/server/opencode-cli.js +459 -459
  125. package/server/opencode-response-handler.js +107 -107
  126. package/server/projects.js +3105 -3105
  127. package/server/qwen-code-cli.js +395 -395
  128. package/server/qwen-response-handler.js +73 -73
  129. package/server/routes/agent.js +1365 -1365
  130. package/server/routes/auth.js +138 -138
  131. package/server/routes/codex.js +19 -19
  132. package/server/routes/commands.js +554 -554
  133. package/server/routes/cursor.js +52 -52
  134. package/server/routes/gemini.js +24 -24
  135. package/server/routes/git.js +1488 -1488
  136. package/server/routes/mcp-utils.js +31 -31
  137. package/server/routes/messages.js +61 -61
  138. package/server/routes/network.js +120 -120
  139. package/server/routes/plugins.js +318 -318
  140. package/server/routes/projects.js +915 -915
  141. package/server/routes/qwen.js +27 -27
  142. package/server/routes/settings.js +286 -286
  143. package/server/routes/taskmaster.js +1496 -1496
  144. package/server/routes/telegram.js +125 -125
  145. package/server/routes/user.js +123 -123
  146. package/server/services/external-access.js +171 -171
  147. package/server/services/install-jobs.js +571 -571
  148. package/server/services/notification-orchestrator.js +242 -242
  149. package/server/services/provider-credentials.js +189 -189
  150. package/server/services/provider-models.js +381 -381
  151. package/server/services/telegram/bot.js +279 -279
  152. package/server/services/telegram/telegram-http-client.js +130 -130
  153. package/server/services/telegram/translations.js +170 -170
  154. package/server/services/vapid-keys.js +36 -36
  155. package/server/sessionManager.js +225 -225
  156. package/server/shared/interfaces.ts +54 -54
  157. package/server/shared/types.ts +172 -172
  158. package/server/shared/utils.ts +193 -193
  159. package/server/tsconfig.json +36 -36
  160. package/server/utils/colors.js +21 -21
  161. package/server/utils/commandParser.js +303 -303
  162. package/server/utils/frontmatter.js +18 -18
  163. package/server/utils/gitConfig.js +34 -34
  164. package/server/utils/mcp-detector.js +147 -147
  165. package/server/utils/plugin-loader.js +457 -457
  166. package/server/utils/plugin-process-manager.js +184 -184
  167. package/server/utils/port-access.js +209 -209
  168. package/server/utils/runtime-paths.js +37 -37
  169. package/server/utils/taskmaster-websocket.js +128 -128
  170. package/server/utils/url-detection.js +71 -71
  171. package/server/vite-daemon.js +78 -78
  172. package/shared/modelConstants.js +162 -162
  173. package/shared/networkHosts.js +22 -22
@@ -1,915 +1,915 @@
1
- import express from 'express';
2
- import { promises as fs } from 'fs';
3
- import path from 'path';
4
- import { spawn } from 'child_process';
5
- import os from 'os';
6
- import { addProjectManually, extractProjectDirectory } from '../projects.js';
7
-
8
- const router = express.Router();
9
-
10
- function sanitizeGitError(message, token) {
11
- if (!message || !token) return message;
12
- return message.replace(new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '***');
13
- }
14
-
15
- // Configure allowed workspace root (defaults to user's home directory)
16
- export const WORKSPACES_ROOT = process.env.WORKSPACES_ROOT || os.homedir();
17
- export const WORKSPACES_BASE = path.resolve(
18
- process.env.WORKSPACES_BASE || path.join(WORKSPACES_ROOT, 'pixcode', 'projects')
19
- );
20
-
21
- // System-critical paths that should never be used as workspace directories.
22
- // `/root` is conditional — included only when the server is NOT running as
23
- // root. On a typical VPS deployment (`sudo` install, root-owned daemon)
24
- // `/root` IS the user's home directory, blocking projects under it locks
25
- // users out of their own filesystem. The carve-out below was meant to
26
- // handle this but only allowed paths under WORKSPACES_BASE — users with
27
- // `/root/foo` from before Pixcode existed couldn't open them.
28
- const RUNNING_AS_ROOT =
29
- process.platform !== 'win32' &&
30
- typeof process.getuid === 'function' &&
31
- process.getuid() === 0;
32
-
33
- export const FORBIDDEN_PATHS = [
34
- // Unix
35
- '/',
36
- '/etc',
37
- '/bin',
38
- '/sbin',
39
- '/usr',
40
- '/dev',
41
- '/proc',
42
- '/sys',
43
- '/var',
44
- '/boot',
45
- ...(RUNNING_AS_ROOT ? [] : ['/root']),
46
- '/lib',
47
- '/lib64',
48
- '/opt',
49
- '/tmp',
50
- '/run',
51
- // Windows
52
- 'C:\\Windows',
53
- 'C:\\Program Files',
54
- 'C:\\Program Files (x86)',
55
- 'C:\\ProgramData',
56
- 'C:\\System Volume Information',
57
- 'C:\\$Recycle.Bin'
58
- ];
59
-
60
- const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
61
-
62
- function isPathWithin(basePath, targetPath) {
63
- const normalizedBase = path.normalize(basePath);
64
- const normalizedTarget = path.normalize(targetPath);
65
- return (
66
- normalizedTarget === normalizedBase ||
67
- normalizedTarget.startsWith(normalizedBase + path.sep)
68
- );
69
- }
70
-
71
- async function realpathOrResolved(targetPath) {
72
- try {
73
- return await fs.realpath(targetPath);
74
- } catch (error) {
75
- if (error.code === 'ENOENT') {
76
- return path.resolve(targetPath);
77
- }
78
- throw error;
79
- }
80
- }
81
-
82
- export function normalizeWorkspacePath(requestedPath) {
83
- if (typeof requestedPath !== 'string') {
84
- return WORKSPACES_BASE;
85
- }
86
-
87
- const trimmedPath = requestedPath.trim();
88
- if (!trimmedPath) {
89
- return WORKSPACES_BASE;
90
- }
91
-
92
- if (trimmedPath === '~') {
93
- return WORKSPACES_BASE;
94
- }
95
-
96
- if (trimmedPath.startsWith('~/') || trimmedPath.startsWith('~\\')) {
97
- return path.join(WORKSPACES_BASE, trimmedPath.slice(2));
98
- }
99
-
100
- const isWindowsAbsolutePath = WINDOWS_ABSOLUTE_PATH_PATTERN.test(trimmedPath);
101
- if (!path.isAbsolute(trimmedPath) && !isWindowsAbsolutePath) {
102
- return path.join(WORKSPACES_BASE, trimmedPath);
103
- }
104
-
105
- return path.resolve(trimmedPath);
106
- }
107
-
108
- /**
109
- * Validates that a path is safe for workspace operations
110
- * @param {string} requestedPath - The path to validate
111
- * @returns {Promise<{valid: boolean, resolvedPath?: string, error?: string}>}
112
- */
113
- export async function validateWorkspacePath(requestedPath) {
114
- try {
115
- if (typeof requestedPath !== 'string' || requestedPath.trim().length === 0) {
116
- return {
117
- valid: false,
118
- error: 'Workspace path is required'
119
- };
120
- }
121
-
122
- // Resolve aliases and relative paths into a safe default base.
123
- // Example: "my-app" -> "<WORKSPACES_BASE>/my-app"
124
- const normalizedInputPath = normalizeWorkspacePath(requestedPath);
125
-
126
- // Resolve to absolute path
127
- let absolutePath = path.resolve(normalizedInputPath);
128
- let resolvedWorkspaceBase = await realpathOrResolved(WORKSPACES_BASE);
129
- resolvedWorkspaceBase = path.normalize(resolvedWorkspaceBase);
130
-
131
- // Check if path is a forbidden system directory
132
- const normalizedPath = path.normalize(absolutePath);
133
- if (FORBIDDEN_PATHS.includes(normalizedPath) || normalizedPath === '/') {
134
- const isRootWorkspaceException =
135
- (normalizedPath === '/root' || normalizedPath.startsWith('/root' + path.sep)) &&
136
- isPathWithin(resolvedWorkspaceBase, normalizedPath);
137
- if (isRootWorkspaceException) {
138
- // Allow /root/<base> carve-out for root installations.
139
- } else {
140
- return {
141
- valid: false,
142
- error: 'Cannot use system-critical directories as workspace locations'
143
- };
144
- }
145
- }
146
-
147
- // Additional check for paths starting with forbidden directories
148
- for (const forbidden of FORBIDDEN_PATHS) {
149
- const isInsideForbidden = normalizedPath === forbidden ||
150
- normalizedPath.startsWith(forbidden + path.sep);
151
-
152
- if (!isInsideForbidden) {
153
- continue;
154
- }
155
-
156
- const isRootWorkspaceException =
157
- (forbidden === '/root') && isPathWithin(resolvedWorkspaceBase, normalizedPath);
158
- if (isRootWorkspaceException) {
159
- continue;
160
- }
161
-
162
- // Exception: /var/tmp and similar user-accessible paths might be allowed
163
- // but /var itself and most /var subdirectories should be blocked
164
- if (forbidden === '/var' &&
165
- (normalizedPath.startsWith('/var/tmp') ||
166
- normalizedPath.startsWith('/var/folders'))) {
167
- continue; // Allow these specific cases
168
- }
169
-
170
- return {
171
- valid: false,
172
- error: `Cannot create workspace in system directory: ${forbidden}`
173
- };
174
- }
175
-
176
- // Try to resolve the real path (following symlinks)
177
- let realPath;
178
- try {
179
- // Check if path exists to resolve real path
180
- await fs.access(absolutePath);
181
- realPath = await fs.realpath(absolutePath);
182
- } catch (error) {
183
- if (error.code === 'ENOENT') {
184
- // Path doesn't exist yet - check parent directory
185
- let parentPath = path.dirname(absolutePath);
186
- try {
187
- const parentRealPath = await fs.realpath(parentPath);
188
-
189
- // Reconstruct the full path with real parent
190
- realPath = path.join(parentRealPath, path.basename(absolutePath));
191
- } catch (parentError) {
192
- if (parentError.code === 'ENOENT') {
193
- // Parent doesn't exist either - use the absolute path as-is
194
- // We'll validate it's within allowed root
195
- realPath = absolutePath;
196
- } else {
197
- throw parentError;
198
- }
199
- }
200
- } else {
201
- throw error;
202
- }
203
- }
204
-
205
- // Symlink safety: if the chosen path is a symlink, make sure its
206
- // target doesn't dive into a forbidden system directory. The plain
207
- // FORBIDDEN_PATHS check above only sees the link path itself.
208
- try {
209
- await fs.access(absolutePath);
210
- const stats = await fs.lstat(absolutePath);
211
-
212
- if (stats.isSymbolicLink()) {
213
- const linkTarget = await fs.readlink(absolutePath);
214
- const resolvedTarget = path.resolve(path.dirname(absolutePath), linkTarget);
215
- const realTarget = path.normalize(await fs.realpath(resolvedTarget));
216
-
217
- for (const forbidden of FORBIDDEN_PATHS) {
218
- if (realTarget === forbidden || realTarget.startsWith(forbidden + path.sep)) {
219
- return {
220
- valid: false,
221
- error: `Symlink target resolves into a system directory: ${forbidden}`
222
- };
223
- }
224
- }
225
- }
226
- } catch (error) {
227
- if (error.code !== 'ENOENT') {
228
- throw error;
229
- }
230
- // Path doesn't exist - that's fine for new workspace creation
231
- }
232
-
233
- return {
234
- valid: true,
235
- resolvedPath: realPath
236
- };
237
-
238
- } catch (error) {
239
- return {
240
- valid: false,
241
- error: `Path validation failed: ${error.message}`
242
- };
243
- }
244
- }
245
-
246
- /**
247
- * Is this `pixcode-project-N` slot already in use? "In use" means the
248
- * user has sent at least one message under any provider — presence of a
249
- * session file under ~/.claude/projects/<encoded>/, ~/.codex/sessions/,
250
- * or ~/.gemini/… is our signal. We keep it best-effort: if we can't
251
- * probe a provider's session dir (no permissions, path missing), we
252
- * treat it as "no sessions for this provider" rather than raise.
253
- *
254
- * Checking the on-disk workspace dir for files is NOT a reliable signal
255
- * — providers store their history outside the workspace, so a project
256
- * that has had 20 messages still has an empty folder.
257
- */
258
- async function projectHasAnySessions(workspacePath) {
259
- const home = os.homedir();
260
- // encodeProjectName strips drive separators (C:\ → -C--…) and dots so
261
- // `extractProjectDirectory` can round-trip. Using the same encoder as
262
- // the rest of projects.js keeps us aligned with however Claude's CLI
263
- // computes its per-project directory name.
264
- const slug = workspacePath.replace(/[\\/:]/g, '-').replace(/\./g, '-');
265
-
266
- const probes = [
267
- // Claude Code: JSONL-per-session files under a per-project subdir.
268
- path.join(home, '.claude', 'projects', slug),
269
- // Codex writes session logs under ~/.codex/sessions — they're cross-project
270
- // so we can't cheaply attribute them to a specific slot; skip.
271
- // Gemini: same layout as Claude.
272
- path.join(home, '.gemini', 'projects', slug),
273
- // Qwen Code (Gemini fork): same layout.
274
- path.join(home, '.qwen', 'projects', slug),
275
- ];
276
-
277
- for (const dir of probes) {
278
- try {
279
- const entries = await fs.readdir(dir);
280
- if (entries.some((name) => name.endsWith('.jsonl') || name.endsWith('.json'))) {
281
- return true;
282
- }
283
- } catch {
284
- // Missing / unreadable dir just means "no sessions here", not fatal.
285
- }
286
- }
287
- return false;
288
- }
289
-
290
- /**
291
- * GET /api/projects/:projectName/dir-status
292
- *
293
- * Lightweight "does the workspace still exist on disk?" check used by
294
- * the chat composer to detect deleted-directory sessions. We decode the
295
- * project name back to an absolute path and stat it — a slug alone isn't
296
- * useful because the user may have deleted the workspace while the
297
- * session metadata still lives under ~/.<provider>/projects/.
298
- *
299
- * Returns `{ exists, path, isDirectory }` so the UI can lock the
300
- * composer and surface a "directory deleted" warning instead of letting
301
- * the user fire prompts into a void.
302
- */
303
- router.get('/:projectName/dir-status', async (req, res) => {
304
- const { projectName } = req.params;
305
- try {
306
- const actualPath = await extractProjectDirectory(projectName);
307
- if (!actualPath) {
308
- return res.json({ exists: false, path: null, isDirectory: false });
309
- }
310
- try {
311
- const stat = await fs.stat(actualPath);
312
- return res.json({
313
- exists: true,
314
- path: actualPath,
315
- isDirectory: stat.isDirectory(),
316
- });
317
- } catch (err) {
318
- // ENOENT is the typical "user rm -rf'd the workspace" path.
319
- if (err.code === 'ENOENT') {
320
- return res.json({ exists: false, path: actualPath, isDirectory: false });
321
- }
322
- throw err;
323
- }
324
- } catch (error) {
325
- console.error(`[projects] dir-status ${projectName}:`, error);
326
- res.status(500).json({ error: error.message || 'Failed to check project directory' });
327
- }
328
- });
329
-
330
- /**
331
- * POST /api/projects/quick-start
332
- *
333
- * Zero-config project creation: **reuses** the first unused
334
- * `pixcode-project-N` slot if one exists, otherwise creates the next
335
- * free index. "Unused" = no session files on disk for any provider.
336
- * Without reuse, clicking "New chat" rapidly stacks up pixcode-project-1
337
- * through pixcode-project-N and litters the workspace — the UX we want
338
- * matches ChatGPT's "New chat" which reuses the empty canvas until the
339
- * user actually commits a message.
340
- */
341
- router.post('/quick-start', async (req, res) => {
342
- try {
343
- await fs.mkdir(WORKSPACES_BASE, { recursive: true });
344
-
345
- let entries = [];
346
- try {
347
- entries = await fs.readdir(WORKSPACES_BASE, { withFileTypes: true });
348
- } catch { /* empty is fine */ }
349
-
350
- // Pixcode-owned slots, sorted by numeric index so reuse is deterministic
351
- // and picks the lowest idle slot (pixcode-project-1 before -3).
352
- const existingSlots = entries
353
- .filter((e) => e.isDirectory() && /^pixcode-project-\d+$/i.test(e.name))
354
- .map((e) => ({
355
- name: e.name,
356
- index: parseInt(e.name.split('-').pop(), 10) || 0,
357
- }))
358
- .sort((a, b) => a.index - b.index);
359
-
360
- // 1. First pass: reuse the lowest-indexed slot that has no sessions.
361
- for (const slot of existingSlots) {
362
- const absolutePath = path.join(WORKSPACES_BASE, slot.name);
363
- const used = await projectHasAnySessions(absolutePath);
364
- if (!used) {
365
- let project;
366
- try {
367
- project = await addProjectManually(absolutePath);
368
- } catch (err) {
369
- // addProjectManually throws when the project is already
370
- // registered. That's fine — look it up via its encoded name
371
- // instead of creating a duplicate.
372
- const msg = err?.message || '';
373
- if (!/already configured/i.test(msg)) throw err;
374
- project = {
375
- name: absolutePath.replace(/[\\/:]/g, '-').replace(/\./g, '-'),
376
- path: absolutePath,
377
- fullPath: absolutePath,
378
- displayName: slot.name,
379
- isManuallyAdded: true,
380
- sessions: [],
381
- cursorSessions: [],
382
- };
383
- }
384
- return res.json({
385
- success: true,
386
- project,
387
- suggestedName: slot.name,
388
- reused: true,
389
- });
390
- }
391
- }
392
-
393
- // 2. No idle slot — create the next free index above what exists.
394
- const takenIndices = new Set(existingSlots.map((s) => s.index));
395
- let nextIndex = 1;
396
- while (takenIndices.has(nextIndex)) {
397
- nextIndex += 1;
398
- if (nextIndex > 9999) {
399
- return res.status(500).json({ error: 'No free pixcode-project slot (exhausted 1..9999)' });
400
- }
401
- }
402
- const name = `pixcode-project-${nextIndex}`;
403
- const absolutePath = path.join(WORKSPACES_BASE, name);
404
- await fs.mkdir(absolutePath, { recursive: true });
405
- const project = await addProjectManually(absolutePath);
406
-
407
- res.json({ success: true, project, suggestedName: name, reused: false });
408
- } catch (error) {
409
- console.error('[projects] quick-start failed:', error);
410
- res.status(500).json({ error: error.message || 'Failed to quick-start project' });
411
- }
412
- });
413
-
414
- /**
415
- * Create a new workspace
416
- * POST /api/projects/create-workspace
417
- *
418
- * Body:
419
- * - workspaceType: 'existing' | 'new'
420
- * - path: string (workspace path)
421
- * - githubUrl?: string (optional, for new workspaces)
422
- * - githubTokenId?: number (optional, ID of stored token)
423
- * - newGithubToken?: string (optional, one-time token)
424
- */
425
- router.post('/create-workspace', async (req, res) => {
426
- try {
427
- const { workspaceType, path: workspacePath, githubUrl, githubTokenId, newGithubToken, subfolderName } = req.body;
428
-
429
- // Validate required fields
430
- if (!workspaceType || !workspacePath) {
431
- return res.status(400).json({ error: 'workspaceType and path are required' });
432
- }
433
-
434
- // 'existing' = open the picked folder as-is
435
- // 'new' = clone a github repo into the picked folder (legacy name kept for client compat)
436
- // 'subfolder'= create a fresh subfolder INSIDE the picked folder and open that
437
- if (!['existing', 'new', 'subfolder'].includes(workspaceType)) {
438
- return res.status(400).json({ error: 'workspaceType must be "existing", "new", or "subfolder"' });
439
- }
440
-
441
- // Validate path safety before any operations
442
- const validation = await validateWorkspacePath(workspacePath);
443
- if (!validation.valid) {
444
- return res.status(400).json({
445
- error: 'Invalid workspace path',
446
- details: validation.error
447
- });
448
- }
449
-
450
- const absolutePath = validation.resolvedPath;
451
-
452
- // Handle existing workspace
453
- if (workspaceType === 'existing') {
454
- // Check if the path exists
455
- try {
456
- await fs.access(absolutePath);
457
- const stats = await fs.stat(absolutePath);
458
-
459
- if (!stats.isDirectory()) {
460
- return res.status(400).json({ error: 'Path exists but is not a directory' });
461
- }
462
- } catch (error) {
463
- if (error.code === 'ENOENT') {
464
- return res.status(404).json({ error: 'Workspace path does not exist' });
465
- }
466
- throw error;
467
- }
468
-
469
- // Add the existing workspace to the project list. If the user picks
470
- // a folder Pixcode has already registered (very common when bouncing
471
- // between sessions or re-opening the wizard on the same project),
472
- // `addProjectManually` throws "Project already configured…" — that
473
- // used to surface as a hard error in the UI even though the right
474
- // outcome is "great, let's just open it." Treat that one specific
475
- // throw as a soft re-open and return a 200 with `alreadyExisted: true`
476
- // so the wizard can show "Opened existing workspace" instead of the
477
- // raw error message.
478
- let project;
479
- let alreadyExisted = false;
480
- try {
481
- project = await addProjectManually(absolutePath);
482
- } catch (error) {
483
- const msg = error?.message || '';
484
- if (!/already configured/i.test(msg)) throw error;
485
- alreadyExisted = true;
486
- project = {
487
- name: absolutePath.replace(/[\\/:]/g, '-').replace(/\./g, '-'),
488
- path: absolutePath,
489
- fullPath: absolutePath,
490
- displayName: path.basename(absolutePath),
491
- isManuallyAdded: true,
492
- sessions: [],
493
- cursorSessions: [],
494
- };
495
- }
496
-
497
- return res.json({
498
- success: true,
499
- project,
500
- alreadyExisted,
501
- message: alreadyExisted
502
- ? 'Workspace was already registered — opening it'
503
- : 'Existing workspace added successfully'
504
- });
505
- }
506
-
507
- // Handle subfolder creation: user picked a parent dir, we mkdir
508
- // <parent>/<subfolderName> and open that.
509
- if (workspaceType === 'subfolder') {
510
- const trimmedName = typeof subfolderName === 'string' ? subfolderName.trim() : '';
511
- if (!trimmedName) {
512
- return res.status(400).json({ error: 'subfolderName is required when workspaceType is "subfolder"' });
513
- }
514
- // Reject path-traversal / nested separators / reserved names. The
515
- // wizard's UI will only ever send a flat folder name; anything else
516
- // is either a bug or someone fishing.
517
- if (/[\\/]/.test(trimmedName) || trimmedName === '.' || trimmedName === '..') {
518
- return res.status(400).json({ error: 'subfolderName must be a single folder name (no path separators)' });
519
- }
520
-
521
- // Verify parent dir exists (we don't auto-create the picked parent —
522
- // user already pointed at a real folder).
523
- try {
524
- const stats = await fs.stat(absolutePath);
525
- if (!stats.isDirectory()) {
526
- return res.status(400).json({ error: 'Parent path is not a directory' });
527
- }
528
- } catch (error) {
529
- if (error.code === 'ENOENT') {
530
- return res.status(404).json({ error: 'Parent directory does not exist' });
531
- }
532
- throw error;
533
- }
534
-
535
- const childPath = path.join(absolutePath, trimmedName);
536
-
537
- // Validate the resulting path too — don't let "subfolder=foo/../../etc"
538
- // bypass the parent-only check above. validateWorkspacePath already
539
- // rejects symlink escapes and FORBIDDEN_PATHS.
540
- const childValidation = await validateWorkspacePath(childPath);
541
- if (!childValidation.valid) {
542
- return res.status(400).json({
543
- error: 'Invalid subfolder path',
544
- details: childValidation.error,
545
- });
546
- }
547
- const childAbsolute = childValidation.resolvedPath;
548
-
549
- // Refuse to clobber an existing folder with content — user can pick
550
- // "existing" instead. Empty/missing → mkdir.
551
- try {
552
- const childEntries = await fs.readdir(childAbsolute);
553
- if (childEntries.length > 0) {
554
- return res.status(409).json({
555
- error: 'Subfolder already exists and is not empty',
556
- details: `Pick a different name or open "${childAbsolute}" as an existing workspace.`,
557
- });
558
- }
559
- } catch (error) {
560
- if (error.code !== 'ENOENT') throw error;
561
- }
562
- await fs.mkdir(childAbsolute, { recursive: true });
563
-
564
- let subProject;
565
- let subAlreadyExisted = false;
566
- try {
567
- subProject = await addProjectManually(childAbsolute);
568
- } catch (error) {
569
- const msg = error?.message || '';
570
- if (!/already configured/i.test(msg)) throw error;
571
- subAlreadyExisted = true;
572
- subProject = {
573
- name: childAbsolute.replace(/[\\/:]/g, '-').replace(/\./g, '-'),
574
- path: childAbsolute,
575
- fullPath: childAbsolute,
576
- displayName: trimmedName,
577
- isManuallyAdded: true,
578
- sessions: [],
579
- cursorSessions: [],
580
- };
581
- }
582
-
583
- return res.json({
584
- success: true,
585
- project: subProject,
586
- alreadyExisted: subAlreadyExisted,
587
- message: subAlreadyExisted
588
- ? 'Subfolder was already registered — opening it'
589
- : 'Subfolder created successfully',
590
- });
591
- }
592
-
593
- // Handle new workspace creation
594
- if (workspaceType === 'new') {
595
- // Create the directory if it doesn't exist
596
- await fs.mkdir(absolutePath, { recursive: true });
597
-
598
- // If GitHub URL is provided, clone the repository
599
- if (githubUrl) {
600
- let githubToken = null;
601
-
602
- // Get GitHub token if needed
603
- if (githubTokenId) {
604
- // Fetch token from database
605
- const token = await getGithubTokenById(githubTokenId, req.user.id);
606
- if (!token) {
607
- // Clean up created directory
608
- await fs.rm(absolutePath, { recursive: true, force: true });
609
- return res.status(404).json({ error: 'GitHub token not found' });
610
- }
611
- githubToken = token.github_token;
612
- } else if (newGithubToken) {
613
- githubToken = newGithubToken;
614
- }
615
-
616
- // Extract repo name from URL for the clone destination
617
- const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
618
- const repoName = normalizedUrl.split('/').pop() || 'repository';
619
- const clonePath = path.join(absolutePath, repoName);
620
-
621
- // Check if clone destination already exists to prevent data loss
622
- try {
623
- await fs.access(clonePath);
624
- return res.status(409).json({
625
- error: 'Directory already exists',
626
- details: `The destination path "${clonePath}" already exists. Please choose a different location or remove the existing directory.`
627
- });
628
- } catch (err) {
629
- // Directory doesn't exist, which is what we want
630
- }
631
-
632
- // Clone the repository into a subfolder
633
- try {
634
- await cloneGitHubRepository(githubUrl, clonePath, githubToken);
635
- } catch (error) {
636
- // Only clean up if clone created partial data (check if dir exists and is empty or partial)
637
- try {
638
- const stats = await fs.stat(clonePath);
639
- if (stats.isDirectory()) {
640
- await fs.rm(clonePath, { recursive: true, force: true });
641
- }
642
- } catch (cleanupError) {
643
- // Directory doesn't exist or cleanup failed - ignore
644
- }
645
- throw new Error(`Failed to clone repository: ${error.message}`);
646
- }
647
-
648
- // Add the cloned repo path to the project list
649
- const project = await addProjectManually(clonePath);
650
-
651
- return res.json({
652
- success: true,
653
- project,
654
- message: 'New workspace created and repository cloned successfully'
655
- });
656
- }
657
-
658
- // Add the new workspace to the project list (no clone)
659
- const project = await addProjectManually(absolutePath);
660
-
661
- return res.json({
662
- success: true,
663
- project,
664
- message: 'New workspace created successfully'
665
- });
666
- }
667
-
668
- } catch (error) {
669
- console.error('Error creating workspace:', error);
670
- res.status(500).json({
671
- error: error.message || 'Failed to create workspace',
672
- details: process.env.NODE_ENV === 'development' ? error.stack : undefined
673
- });
674
- }
675
- });
676
-
677
- /**
678
- * Helper function to get GitHub token from database
679
- */
680
- async function getGithubTokenById(tokenId, userId) {
681
- const { db } = await import('../database/db.js');
682
-
683
- const credential = db.prepare(
684
- 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1'
685
- ).get(tokenId, userId, 'github_token');
686
-
687
- // Return in the expected format (github_token field for compatibility)
688
- if (credential) {
689
- return {
690
- ...credential,
691
- github_token: credential.credential_value
692
- };
693
- }
694
-
695
- return null;
696
- }
697
-
698
- /**
699
- * Clone repository with progress streaming (SSE)
700
- * GET /api/projects/clone-progress
701
- */
702
- router.get('/clone-progress', async (req, res) => {
703
- const { path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.query;
704
-
705
- res.setHeader('Content-Type', 'text/event-stream');
706
- res.setHeader('Cache-Control', 'no-cache');
707
- res.setHeader('Connection', 'keep-alive');
708
- res.flushHeaders();
709
-
710
- const sendEvent = (type, data) => {
711
- res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
712
- };
713
-
714
- try {
715
- if (!workspacePath || !githubUrl) {
716
- sendEvent('error', { message: 'workspacePath and githubUrl are required' });
717
- res.end();
718
- return;
719
- }
720
-
721
- const validation = await validateWorkspacePath(workspacePath);
722
- if (!validation.valid) {
723
- sendEvent('error', { message: validation.error });
724
- res.end();
725
- return;
726
- }
727
-
728
- const absolutePath = validation.resolvedPath;
729
-
730
- await fs.mkdir(absolutePath, { recursive: true });
731
-
732
- let githubToken = null;
733
- if (githubTokenId) {
734
- const token = await getGithubTokenById(parseInt(githubTokenId), req.user.id);
735
- if (!token) {
736
- await fs.rm(absolutePath, { recursive: true, force: true });
737
- sendEvent('error', { message: 'GitHub token not found' });
738
- res.end();
739
- return;
740
- }
741
- githubToken = token.github_token;
742
- } else if (newGithubToken) {
743
- githubToken = newGithubToken;
744
- }
745
-
746
- const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
747
- const repoName = normalizedUrl.split('/').pop() || 'repository';
748
- const clonePath = path.join(absolutePath, repoName);
749
-
750
- // Check if clone destination already exists to prevent data loss
751
- try {
752
- await fs.access(clonePath);
753
- sendEvent('error', { message: `Directory "${repoName}" already exists. Please choose a different location or remove the existing directory.` });
754
- res.end();
755
- return;
756
- } catch (err) {
757
- // Directory doesn't exist, which is what we want
758
- }
759
-
760
- let cloneUrl = githubUrl;
761
- if (githubToken) {
762
- try {
763
- const url = new URL(githubUrl);
764
- url.username = githubToken;
765
- url.password = '';
766
- cloneUrl = url.toString();
767
- } catch (error) {
768
- // SSH URL or invalid - use as-is
769
- }
770
- }
771
-
772
- sendEvent('progress', { message: `Cloning into '${repoName}'...` });
773
-
774
- const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, clonePath], {
775
- stdio: ['ignore', 'pipe', 'pipe'],
776
- env: {
777
- ...process.env,
778
- GIT_TERMINAL_PROMPT: '0'
779
- }
780
- });
781
-
782
- let lastError = '';
783
-
784
- gitProcess.stdout.on('data', (data) => {
785
- const message = data.toString().trim();
786
- if (message) {
787
- sendEvent('progress', { message });
788
- }
789
- });
790
-
791
- gitProcess.stderr.on('data', (data) => {
792
- const message = data.toString().trim();
793
- lastError = message;
794
- if (message) {
795
- sendEvent('progress', { message });
796
- }
797
- });
798
-
799
- gitProcess.on('close', async (code) => {
800
- if (code === 0) {
801
- try {
802
- const project = await addProjectManually(clonePath);
803
- sendEvent('complete', { project, message: 'Repository cloned successfully' });
804
- } catch (error) {
805
- sendEvent('error', { message: `Clone succeeded but failed to add project: ${error.message}` });
806
- }
807
- } else {
808
- const sanitizedError = sanitizeGitError(lastError, githubToken);
809
- let errorMessage = 'Git clone failed';
810
- if (lastError.includes('Authentication failed') || lastError.includes('could not read Username')) {
811
- errorMessage = 'Authentication failed. Please check your credentials.';
812
- } else if (lastError.includes('Repository not found')) {
813
- errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
814
- } else if (lastError.includes('already exists')) {
815
- errorMessage = 'Directory already exists';
816
- } else if (sanitizedError) {
817
- errorMessage = sanitizedError;
818
- }
819
- try {
820
- await fs.rm(clonePath, { recursive: true, force: true });
821
- } catch (cleanupError) {
822
- console.error('Failed to clean up after clone failure:', sanitizeGitError(cleanupError.message, githubToken));
823
- }
824
- sendEvent('error', { message: errorMessage });
825
- }
826
- res.end();
827
- });
828
-
829
- gitProcess.on('error', (error) => {
830
- if (error.code === 'ENOENT') {
831
- sendEvent('error', { message: 'Git is not installed or not in PATH' });
832
- } else {
833
- sendEvent('error', { message: error.message });
834
- }
835
- res.end();
836
- });
837
-
838
- req.on('close', () => {
839
- gitProcess.kill();
840
- });
841
-
842
- } catch (error) {
843
- sendEvent('error', { message: error.message });
844
- res.end();
845
- }
846
- });
847
-
848
- /**
849
- * Helper function to clone a GitHub repository
850
- */
851
- function cloneGitHubRepository(githubUrl, destinationPath, githubToken = null) {
852
- return new Promise((resolve, reject) => {
853
- let cloneUrl = githubUrl;
854
-
855
- if (githubToken) {
856
- try {
857
- const url = new URL(githubUrl);
858
- url.username = githubToken;
859
- url.password = '';
860
- cloneUrl = url.toString();
861
- } catch (error) {
862
- // SSH URL - use as-is
863
- }
864
- }
865
-
866
- const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, destinationPath], {
867
- stdio: ['ignore', 'pipe', 'pipe'],
868
- env: {
869
- ...process.env,
870
- GIT_TERMINAL_PROMPT: '0'
871
- }
872
- });
873
-
874
- let stdout = '';
875
- let stderr = '';
876
-
877
- gitProcess.stdout.on('data', (data) => {
878
- stdout += data.toString();
879
- });
880
-
881
- gitProcess.stderr.on('data', (data) => {
882
- stderr += data.toString();
883
- });
884
-
885
- gitProcess.on('close', (code) => {
886
- if (code === 0) {
887
- resolve({ stdout, stderr });
888
- } else {
889
- let errorMessage = 'Git clone failed';
890
-
891
- if (stderr.includes('Authentication failed') || stderr.includes('could not read Username')) {
892
- errorMessage = 'Authentication failed. Please check your GitHub token.';
893
- } else if (stderr.includes('Repository not found')) {
894
- errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
895
- } else if (stderr.includes('already exists')) {
896
- errorMessage = 'Directory already exists';
897
- } else if (stderr) {
898
- errorMessage = stderr;
899
- }
900
-
901
- reject(new Error(errorMessage));
902
- }
903
- });
904
-
905
- gitProcess.on('error', (error) => {
906
- if (error.code === 'ENOENT') {
907
- reject(new Error('Git is not installed or not in PATH'));
908
- } else {
909
- reject(error);
910
- }
911
- });
912
- });
913
- }
914
-
915
- export default router;
1
+ import express from 'express';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { spawn } from 'child_process';
5
+ import os from 'os';
6
+ import { addProjectManually, extractProjectDirectory } from '../projects.js';
7
+
8
+ const router = express.Router();
9
+
10
+ function sanitizeGitError(message, token) {
11
+ if (!message || !token) return message;
12
+ return message.replace(new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '***');
13
+ }
14
+
15
+ // Configure allowed workspace root (defaults to user's home directory)
16
+ export const WORKSPACES_ROOT = process.env.WORKSPACES_ROOT || os.homedir();
17
+ export const WORKSPACES_BASE = path.resolve(
18
+ process.env.WORKSPACES_BASE || path.join(WORKSPACES_ROOT, 'pixcode', 'projects')
19
+ );
20
+
21
+ // System-critical paths that should never be used as workspace directories.
22
+ // `/root` is conditional — included only when the server is NOT running as
23
+ // root. On a typical VPS deployment (`sudo` install, root-owned daemon)
24
+ // `/root` IS the user's home directory, blocking projects under it locks
25
+ // users out of their own filesystem. The carve-out below was meant to
26
+ // handle this but only allowed paths under WORKSPACES_BASE — users with
27
+ // `/root/foo` from before Pixcode existed couldn't open them.
28
+ const RUNNING_AS_ROOT =
29
+ process.platform !== 'win32' &&
30
+ typeof process.getuid === 'function' &&
31
+ process.getuid() === 0;
32
+
33
+ export const FORBIDDEN_PATHS = [
34
+ // Unix
35
+ '/',
36
+ '/etc',
37
+ '/bin',
38
+ '/sbin',
39
+ '/usr',
40
+ '/dev',
41
+ '/proc',
42
+ '/sys',
43
+ '/var',
44
+ '/boot',
45
+ ...(RUNNING_AS_ROOT ? [] : ['/root']),
46
+ '/lib',
47
+ '/lib64',
48
+ '/opt',
49
+ '/tmp',
50
+ '/run',
51
+ // Windows
52
+ 'C:\\Windows',
53
+ 'C:\\Program Files',
54
+ 'C:\\Program Files (x86)',
55
+ 'C:\\ProgramData',
56
+ 'C:\\System Volume Information',
57
+ 'C:\\$Recycle.Bin'
58
+ ];
59
+
60
+ const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
61
+
62
+ function isPathWithin(basePath, targetPath) {
63
+ const normalizedBase = path.normalize(basePath);
64
+ const normalizedTarget = path.normalize(targetPath);
65
+ return (
66
+ normalizedTarget === normalizedBase ||
67
+ normalizedTarget.startsWith(normalizedBase + path.sep)
68
+ );
69
+ }
70
+
71
+ async function realpathOrResolved(targetPath) {
72
+ try {
73
+ return await fs.realpath(targetPath);
74
+ } catch (error) {
75
+ if (error.code === 'ENOENT') {
76
+ return path.resolve(targetPath);
77
+ }
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ export function normalizeWorkspacePath(requestedPath) {
83
+ if (typeof requestedPath !== 'string') {
84
+ return WORKSPACES_BASE;
85
+ }
86
+
87
+ const trimmedPath = requestedPath.trim();
88
+ if (!trimmedPath) {
89
+ return WORKSPACES_BASE;
90
+ }
91
+
92
+ if (trimmedPath === '~') {
93
+ return WORKSPACES_BASE;
94
+ }
95
+
96
+ if (trimmedPath.startsWith('~/') || trimmedPath.startsWith('~\\')) {
97
+ return path.join(WORKSPACES_BASE, trimmedPath.slice(2));
98
+ }
99
+
100
+ const isWindowsAbsolutePath = WINDOWS_ABSOLUTE_PATH_PATTERN.test(trimmedPath);
101
+ if (!path.isAbsolute(trimmedPath) && !isWindowsAbsolutePath) {
102
+ return path.join(WORKSPACES_BASE, trimmedPath);
103
+ }
104
+
105
+ return path.resolve(trimmedPath);
106
+ }
107
+
108
+ /**
109
+ * Validates that a path is safe for workspace operations
110
+ * @param {string} requestedPath - The path to validate
111
+ * @returns {Promise<{valid: boolean, resolvedPath?: string, error?: string}>}
112
+ */
113
+ export async function validateWorkspacePath(requestedPath) {
114
+ try {
115
+ if (typeof requestedPath !== 'string' || requestedPath.trim().length === 0) {
116
+ return {
117
+ valid: false,
118
+ error: 'Workspace path is required'
119
+ };
120
+ }
121
+
122
+ // Resolve aliases and relative paths into a safe default base.
123
+ // Example: "my-app" -> "<WORKSPACES_BASE>/my-app"
124
+ const normalizedInputPath = normalizeWorkspacePath(requestedPath);
125
+
126
+ // Resolve to absolute path
127
+ let absolutePath = path.resolve(normalizedInputPath);
128
+ let resolvedWorkspaceBase = await realpathOrResolved(WORKSPACES_BASE);
129
+ resolvedWorkspaceBase = path.normalize(resolvedWorkspaceBase);
130
+
131
+ // Check if path is a forbidden system directory
132
+ const normalizedPath = path.normalize(absolutePath);
133
+ if (FORBIDDEN_PATHS.includes(normalizedPath) || normalizedPath === '/') {
134
+ const isRootWorkspaceException =
135
+ (normalizedPath === '/root' || normalizedPath.startsWith('/root' + path.sep)) &&
136
+ isPathWithin(resolvedWorkspaceBase, normalizedPath);
137
+ if (isRootWorkspaceException) {
138
+ // Allow /root/<base> carve-out for root installations.
139
+ } else {
140
+ return {
141
+ valid: false,
142
+ error: 'Cannot use system-critical directories as workspace locations'
143
+ };
144
+ }
145
+ }
146
+
147
+ // Additional check for paths starting with forbidden directories
148
+ for (const forbidden of FORBIDDEN_PATHS) {
149
+ const isInsideForbidden = normalizedPath === forbidden ||
150
+ normalizedPath.startsWith(forbidden + path.sep);
151
+
152
+ if (!isInsideForbidden) {
153
+ continue;
154
+ }
155
+
156
+ const isRootWorkspaceException =
157
+ (forbidden === '/root') && isPathWithin(resolvedWorkspaceBase, normalizedPath);
158
+ if (isRootWorkspaceException) {
159
+ continue;
160
+ }
161
+
162
+ // Exception: /var/tmp and similar user-accessible paths might be allowed
163
+ // but /var itself and most /var subdirectories should be blocked
164
+ if (forbidden === '/var' &&
165
+ (normalizedPath.startsWith('/var/tmp') ||
166
+ normalizedPath.startsWith('/var/folders'))) {
167
+ continue; // Allow these specific cases
168
+ }
169
+
170
+ return {
171
+ valid: false,
172
+ error: `Cannot create workspace in system directory: ${forbidden}`
173
+ };
174
+ }
175
+
176
+ // Try to resolve the real path (following symlinks)
177
+ let realPath;
178
+ try {
179
+ // Check if path exists to resolve real path
180
+ await fs.access(absolutePath);
181
+ realPath = await fs.realpath(absolutePath);
182
+ } catch (error) {
183
+ if (error.code === 'ENOENT') {
184
+ // Path doesn't exist yet - check parent directory
185
+ let parentPath = path.dirname(absolutePath);
186
+ try {
187
+ const parentRealPath = await fs.realpath(parentPath);
188
+
189
+ // Reconstruct the full path with real parent
190
+ realPath = path.join(parentRealPath, path.basename(absolutePath));
191
+ } catch (parentError) {
192
+ if (parentError.code === 'ENOENT') {
193
+ // Parent doesn't exist either - use the absolute path as-is
194
+ // We'll validate it's within allowed root
195
+ realPath = absolutePath;
196
+ } else {
197
+ throw parentError;
198
+ }
199
+ }
200
+ } else {
201
+ throw error;
202
+ }
203
+ }
204
+
205
+ // Symlink safety: if the chosen path is a symlink, make sure its
206
+ // target doesn't dive into a forbidden system directory. The plain
207
+ // FORBIDDEN_PATHS check above only sees the link path itself.
208
+ try {
209
+ await fs.access(absolutePath);
210
+ const stats = await fs.lstat(absolutePath);
211
+
212
+ if (stats.isSymbolicLink()) {
213
+ const linkTarget = await fs.readlink(absolutePath);
214
+ const resolvedTarget = path.resolve(path.dirname(absolutePath), linkTarget);
215
+ const realTarget = path.normalize(await fs.realpath(resolvedTarget));
216
+
217
+ for (const forbidden of FORBIDDEN_PATHS) {
218
+ if (realTarget === forbidden || realTarget.startsWith(forbidden + path.sep)) {
219
+ return {
220
+ valid: false,
221
+ error: `Symlink target resolves into a system directory: ${forbidden}`
222
+ };
223
+ }
224
+ }
225
+ }
226
+ } catch (error) {
227
+ if (error.code !== 'ENOENT') {
228
+ throw error;
229
+ }
230
+ // Path doesn't exist - that's fine for new workspace creation
231
+ }
232
+
233
+ return {
234
+ valid: true,
235
+ resolvedPath: realPath
236
+ };
237
+
238
+ } catch (error) {
239
+ return {
240
+ valid: false,
241
+ error: `Path validation failed: ${error.message}`
242
+ };
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Is this `pixcode-project-N` slot already in use? "In use" means the
248
+ * user has sent at least one message under any provider — presence of a
249
+ * session file under ~/.claude/projects/<encoded>/, ~/.codex/sessions/,
250
+ * or ~/.gemini/… is our signal. We keep it best-effort: if we can't
251
+ * probe a provider's session dir (no permissions, path missing), we
252
+ * treat it as "no sessions for this provider" rather than raise.
253
+ *
254
+ * Checking the on-disk workspace dir for files is NOT a reliable signal
255
+ * — providers store their history outside the workspace, so a project
256
+ * that has had 20 messages still has an empty folder.
257
+ */
258
+ async function projectHasAnySessions(workspacePath) {
259
+ const home = os.homedir();
260
+ // encodeProjectName strips drive separators (C:\ → -C--…) and dots so
261
+ // `extractProjectDirectory` can round-trip. Using the same encoder as
262
+ // the rest of projects.js keeps us aligned with however Claude's CLI
263
+ // computes its per-project directory name.
264
+ const slug = workspacePath.replace(/[\\/:]/g, '-').replace(/\./g, '-');
265
+
266
+ const probes = [
267
+ // Claude Code: JSONL-per-session files under a per-project subdir.
268
+ path.join(home, '.claude', 'projects', slug),
269
+ // Codex writes session logs under ~/.codex/sessions — they're cross-project
270
+ // so we can't cheaply attribute them to a specific slot; skip.
271
+ // Gemini: same layout as Claude.
272
+ path.join(home, '.gemini', 'projects', slug),
273
+ // Qwen Code (Gemini fork): same layout.
274
+ path.join(home, '.qwen', 'projects', slug),
275
+ ];
276
+
277
+ for (const dir of probes) {
278
+ try {
279
+ const entries = await fs.readdir(dir);
280
+ if (entries.some((name) => name.endsWith('.jsonl') || name.endsWith('.json'))) {
281
+ return true;
282
+ }
283
+ } catch {
284
+ // Missing / unreadable dir just means "no sessions here", not fatal.
285
+ }
286
+ }
287
+ return false;
288
+ }
289
+
290
+ /**
291
+ * GET /api/projects/:projectName/dir-status
292
+ *
293
+ * Lightweight "does the workspace still exist on disk?" check used by
294
+ * the chat composer to detect deleted-directory sessions. We decode the
295
+ * project name back to an absolute path and stat it — a slug alone isn't
296
+ * useful because the user may have deleted the workspace while the
297
+ * session metadata still lives under ~/.<provider>/projects/.
298
+ *
299
+ * Returns `{ exists, path, isDirectory }` so the UI can lock the
300
+ * composer and surface a "directory deleted" warning instead of letting
301
+ * the user fire prompts into a void.
302
+ */
303
+ router.get('/:projectName/dir-status', async (req, res) => {
304
+ const { projectName } = req.params;
305
+ try {
306
+ const actualPath = await extractProjectDirectory(projectName);
307
+ if (!actualPath) {
308
+ return res.json({ exists: false, path: null, isDirectory: false });
309
+ }
310
+ try {
311
+ const stat = await fs.stat(actualPath);
312
+ return res.json({
313
+ exists: true,
314
+ path: actualPath,
315
+ isDirectory: stat.isDirectory(),
316
+ });
317
+ } catch (err) {
318
+ // ENOENT is the typical "user rm -rf'd the workspace" path.
319
+ if (err.code === 'ENOENT') {
320
+ return res.json({ exists: false, path: actualPath, isDirectory: false });
321
+ }
322
+ throw err;
323
+ }
324
+ } catch (error) {
325
+ console.error(`[projects] dir-status ${projectName}:`, error);
326
+ res.status(500).json({ error: error.message || 'Failed to check project directory' });
327
+ }
328
+ });
329
+
330
+ /**
331
+ * POST /api/projects/quick-start
332
+ *
333
+ * Zero-config project creation: **reuses** the first unused
334
+ * `pixcode-project-N` slot if one exists, otherwise creates the next
335
+ * free index. "Unused" = no session files on disk for any provider.
336
+ * Without reuse, clicking "New chat" rapidly stacks up pixcode-project-1
337
+ * through pixcode-project-N and litters the workspace — the UX we want
338
+ * matches ChatGPT's "New chat" which reuses the empty canvas until the
339
+ * user actually commits a message.
340
+ */
341
+ router.post('/quick-start', async (req, res) => {
342
+ try {
343
+ await fs.mkdir(WORKSPACES_BASE, { recursive: true });
344
+
345
+ let entries = [];
346
+ try {
347
+ entries = await fs.readdir(WORKSPACES_BASE, { withFileTypes: true });
348
+ } catch { /* empty is fine */ }
349
+
350
+ // Pixcode-owned slots, sorted by numeric index so reuse is deterministic
351
+ // and picks the lowest idle slot (pixcode-project-1 before -3).
352
+ const existingSlots = entries
353
+ .filter((e) => e.isDirectory() && /^pixcode-project-\d+$/i.test(e.name))
354
+ .map((e) => ({
355
+ name: e.name,
356
+ index: parseInt(e.name.split('-').pop(), 10) || 0,
357
+ }))
358
+ .sort((a, b) => a.index - b.index);
359
+
360
+ // 1. First pass: reuse the lowest-indexed slot that has no sessions.
361
+ for (const slot of existingSlots) {
362
+ const absolutePath = path.join(WORKSPACES_BASE, slot.name);
363
+ const used = await projectHasAnySessions(absolutePath);
364
+ if (!used) {
365
+ let project;
366
+ try {
367
+ project = await addProjectManually(absolutePath);
368
+ } catch (err) {
369
+ // addProjectManually throws when the project is already
370
+ // registered. That's fine — look it up via its encoded name
371
+ // instead of creating a duplicate.
372
+ const msg = err?.message || '';
373
+ if (!/already configured/i.test(msg)) throw err;
374
+ project = {
375
+ name: absolutePath.replace(/[\\/:]/g, '-').replace(/\./g, '-'),
376
+ path: absolutePath,
377
+ fullPath: absolutePath,
378
+ displayName: slot.name,
379
+ isManuallyAdded: true,
380
+ sessions: [],
381
+ cursorSessions: [],
382
+ };
383
+ }
384
+ return res.json({
385
+ success: true,
386
+ project,
387
+ suggestedName: slot.name,
388
+ reused: true,
389
+ });
390
+ }
391
+ }
392
+
393
+ // 2. No idle slot — create the next free index above what exists.
394
+ const takenIndices = new Set(existingSlots.map((s) => s.index));
395
+ let nextIndex = 1;
396
+ while (takenIndices.has(nextIndex)) {
397
+ nextIndex += 1;
398
+ if (nextIndex > 9999) {
399
+ return res.status(500).json({ error: 'No free pixcode-project slot (exhausted 1..9999)' });
400
+ }
401
+ }
402
+ const name = `pixcode-project-${nextIndex}`;
403
+ const absolutePath = path.join(WORKSPACES_BASE, name);
404
+ await fs.mkdir(absolutePath, { recursive: true });
405
+ const project = await addProjectManually(absolutePath);
406
+
407
+ res.json({ success: true, project, suggestedName: name, reused: false });
408
+ } catch (error) {
409
+ console.error('[projects] quick-start failed:', error);
410
+ res.status(500).json({ error: error.message || 'Failed to quick-start project' });
411
+ }
412
+ });
413
+
414
+ /**
415
+ * Create a new workspace
416
+ * POST /api/projects/create-workspace
417
+ *
418
+ * Body:
419
+ * - workspaceType: 'existing' | 'new'
420
+ * - path: string (workspace path)
421
+ * - githubUrl?: string (optional, for new workspaces)
422
+ * - githubTokenId?: number (optional, ID of stored token)
423
+ * - newGithubToken?: string (optional, one-time token)
424
+ */
425
+ router.post('/create-workspace', async (req, res) => {
426
+ try {
427
+ const { workspaceType, path: workspacePath, githubUrl, githubTokenId, newGithubToken, subfolderName } = req.body;
428
+
429
+ // Validate required fields
430
+ if (!workspaceType || !workspacePath) {
431
+ return res.status(400).json({ error: 'workspaceType and path are required' });
432
+ }
433
+
434
+ // 'existing' = open the picked folder as-is
435
+ // 'new' = clone a github repo into the picked folder (legacy name kept for client compat)
436
+ // 'subfolder'= create a fresh subfolder INSIDE the picked folder and open that
437
+ if (!['existing', 'new', 'subfolder'].includes(workspaceType)) {
438
+ return res.status(400).json({ error: 'workspaceType must be "existing", "new", or "subfolder"' });
439
+ }
440
+
441
+ // Validate path safety before any operations
442
+ const validation = await validateWorkspacePath(workspacePath);
443
+ if (!validation.valid) {
444
+ return res.status(400).json({
445
+ error: 'Invalid workspace path',
446
+ details: validation.error
447
+ });
448
+ }
449
+
450
+ const absolutePath = validation.resolvedPath;
451
+
452
+ // Handle existing workspace
453
+ if (workspaceType === 'existing') {
454
+ // Check if the path exists
455
+ try {
456
+ await fs.access(absolutePath);
457
+ const stats = await fs.stat(absolutePath);
458
+
459
+ if (!stats.isDirectory()) {
460
+ return res.status(400).json({ error: 'Path exists but is not a directory' });
461
+ }
462
+ } catch (error) {
463
+ if (error.code === 'ENOENT') {
464
+ return res.status(404).json({ error: 'Workspace path does not exist' });
465
+ }
466
+ throw error;
467
+ }
468
+
469
+ // Add the existing workspace to the project list. If the user picks
470
+ // a folder Pixcode has already registered (very common when bouncing
471
+ // between sessions or re-opening the wizard on the same project),
472
+ // `addProjectManually` throws "Project already configured…" — that
473
+ // used to surface as a hard error in the UI even though the right
474
+ // outcome is "great, let's just open it." Treat that one specific
475
+ // throw as a soft re-open and return a 200 with `alreadyExisted: true`
476
+ // so the wizard can show "Opened existing workspace" instead of the
477
+ // raw error message.
478
+ let project;
479
+ let alreadyExisted = false;
480
+ try {
481
+ project = await addProjectManually(absolutePath);
482
+ } catch (error) {
483
+ const msg = error?.message || '';
484
+ if (!/already configured/i.test(msg)) throw error;
485
+ alreadyExisted = true;
486
+ project = {
487
+ name: absolutePath.replace(/[\\/:]/g, '-').replace(/\./g, '-'),
488
+ path: absolutePath,
489
+ fullPath: absolutePath,
490
+ displayName: path.basename(absolutePath),
491
+ isManuallyAdded: true,
492
+ sessions: [],
493
+ cursorSessions: [],
494
+ };
495
+ }
496
+
497
+ return res.json({
498
+ success: true,
499
+ project,
500
+ alreadyExisted,
501
+ message: alreadyExisted
502
+ ? 'Workspace was already registered — opening it'
503
+ : 'Existing workspace added successfully'
504
+ });
505
+ }
506
+
507
+ // Handle subfolder creation: user picked a parent dir, we mkdir
508
+ // <parent>/<subfolderName> and open that.
509
+ if (workspaceType === 'subfolder') {
510
+ const trimmedName = typeof subfolderName === 'string' ? subfolderName.trim() : '';
511
+ if (!trimmedName) {
512
+ return res.status(400).json({ error: 'subfolderName is required when workspaceType is "subfolder"' });
513
+ }
514
+ // Reject path-traversal / nested separators / reserved names. The
515
+ // wizard's UI will only ever send a flat folder name; anything else
516
+ // is either a bug or someone fishing.
517
+ if (/[\\/]/.test(trimmedName) || trimmedName === '.' || trimmedName === '..') {
518
+ return res.status(400).json({ error: 'subfolderName must be a single folder name (no path separators)' });
519
+ }
520
+
521
+ // Verify parent dir exists (we don't auto-create the picked parent —
522
+ // user already pointed at a real folder).
523
+ try {
524
+ const stats = await fs.stat(absolutePath);
525
+ if (!stats.isDirectory()) {
526
+ return res.status(400).json({ error: 'Parent path is not a directory' });
527
+ }
528
+ } catch (error) {
529
+ if (error.code === 'ENOENT') {
530
+ return res.status(404).json({ error: 'Parent directory does not exist' });
531
+ }
532
+ throw error;
533
+ }
534
+
535
+ const childPath = path.join(absolutePath, trimmedName);
536
+
537
+ // Validate the resulting path too — don't let "subfolder=foo/../../etc"
538
+ // bypass the parent-only check above. validateWorkspacePath already
539
+ // rejects symlink escapes and FORBIDDEN_PATHS.
540
+ const childValidation = await validateWorkspacePath(childPath);
541
+ if (!childValidation.valid) {
542
+ return res.status(400).json({
543
+ error: 'Invalid subfolder path',
544
+ details: childValidation.error,
545
+ });
546
+ }
547
+ const childAbsolute = childValidation.resolvedPath;
548
+
549
+ // Refuse to clobber an existing folder with content — user can pick
550
+ // "existing" instead. Empty/missing → mkdir.
551
+ try {
552
+ const childEntries = await fs.readdir(childAbsolute);
553
+ if (childEntries.length > 0) {
554
+ return res.status(409).json({
555
+ error: 'Subfolder already exists and is not empty',
556
+ details: `Pick a different name or open "${childAbsolute}" as an existing workspace.`,
557
+ });
558
+ }
559
+ } catch (error) {
560
+ if (error.code !== 'ENOENT') throw error;
561
+ }
562
+ await fs.mkdir(childAbsolute, { recursive: true });
563
+
564
+ let subProject;
565
+ let subAlreadyExisted = false;
566
+ try {
567
+ subProject = await addProjectManually(childAbsolute);
568
+ } catch (error) {
569
+ const msg = error?.message || '';
570
+ if (!/already configured/i.test(msg)) throw error;
571
+ subAlreadyExisted = true;
572
+ subProject = {
573
+ name: childAbsolute.replace(/[\\/:]/g, '-').replace(/\./g, '-'),
574
+ path: childAbsolute,
575
+ fullPath: childAbsolute,
576
+ displayName: trimmedName,
577
+ isManuallyAdded: true,
578
+ sessions: [],
579
+ cursorSessions: [],
580
+ };
581
+ }
582
+
583
+ return res.json({
584
+ success: true,
585
+ project: subProject,
586
+ alreadyExisted: subAlreadyExisted,
587
+ message: subAlreadyExisted
588
+ ? 'Subfolder was already registered — opening it'
589
+ : 'Subfolder created successfully',
590
+ });
591
+ }
592
+
593
+ // Handle new workspace creation
594
+ if (workspaceType === 'new') {
595
+ // Create the directory if it doesn't exist
596
+ await fs.mkdir(absolutePath, { recursive: true });
597
+
598
+ // If GitHub URL is provided, clone the repository
599
+ if (githubUrl) {
600
+ let githubToken = null;
601
+
602
+ // Get GitHub token if needed
603
+ if (githubTokenId) {
604
+ // Fetch token from database
605
+ const token = await getGithubTokenById(githubTokenId, req.user.id);
606
+ if (!token) {
607
+ // Clean up created directory
608
+ await fs.rm(absolutePath, { recursive: true, force: true });
609
+ return res.status(404).json({ error: 'GitHub token not found' });
610
+ }
611
+ githubToken = token.github_token;
612
+ } else if (newGithubToken) {
613
+ githubToken = newGithubToken;
614
+ }
615
+
616
+ // Extract repo name from URL for the clone destination
617
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
618
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
619
+ const clonePath = path.join(absolutePath, repoName);
620
+
621
+ // Check if clone destination already exists to prevent data loss
622
+ try {
623
+ await fs.access(clonePath);
624
+ return res.status(409).json({
625
+ error: 'Directory already exists',
626
+ details: `The destination path "${clonePath}" already exists. Please choose a different location or remove the existing directory.`
627
+ });
628
+ } catch (err) {
629
+ // Directory doesn't exist, which is what we want
630
+ }
631
+
632
+ // Clone the repository into a subfolder
633
+ try {
634
+ await cloneGitHubRepository(githubUrl, clonePath, githubToken);
635
+ } catch (error) {
636
+ // Only clean up if clone created partial data (check if dir exists and is empty or partial)
637
+ try {
638
+ const stats = await fs.stat(clonePath);
639
+ if (stats.isDirectory()) {
640
+ await fs.rm(clonePath, { recursive: true, force: true });
641
+ }
642
+ } catch (cleanupError) {
643
+ // Directory doesn't exist or cleanup failed - ignore
644
+ }
645
+ throw new Error(`Failed to clone repository: ${error.message}`);
646
+ }
647
+
648
+ // Add the cloned repo path to the project list
649
+ const project = await addProjectManually(clonePath);
650
+
651
+ return res.json({
652
+ success: true,
653
+ project,
654
+ message: 'New workspace created and repository cloned successfully'
655
+ });
656
+ }
657
+
658
+ // Add the new workspace to the project list (no clone)
659
+ const project = await addProjectManually(absolutePath);
660
+
661
+ return res.json({
662
+ success: true,
663
+ project,
664
+ message: 'New workspace created successfully'
665
+ });
666
+ }
667
+
668
+ } catch (error) {
669
+ console.error('Error creating workspace:', error);
670
+ res.status(500).json({
671
+ error: error.message || 'Failed to create workspace',
672
+ details: process.env.NODE_ENV === 'development' ? error.stack : undefined
673
+ });
674
+ }
675
+ });
676
+
677
+ /**
678
+ * Helper function to get GitHub token from database
679
+ */
680
+ async function getGithubTokenById(tokenId, userId) {
681
+ const { db } = await import('../database/db.js');
682
+
683
+ const credential = db.prepare(
684
+ 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1'
685
+ ).get(tokenId, userId, 'github_token');
686
+
687
+ // Return in the expected format (github_token field for compatibility)
688
+ if (credential) {
689
+ return {
690
+ ...credential,
691
+ github_token: credential.credential_value
692
+ };
693
+ }
694
+
695
+ return null;
696
+ }
697
+
698
+ /**
699
+ * Clone repository with progress streaming (SSE)
700
+ * GET /api/projects/clone-progress
701
+ */
702
+ router.get('/clone-progress', async (req, res) => {
703
+ const { path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.query;
704
+
705
+ res.setHeader('Content-Type', 'text/event-stream');
706
+ res.setHeader('Cache-Control', 'no-cache');
707
+ res.setHeader('Connection', 'keep-alive');
708
+ res.flushHeaders();
709
+
710
+ const sendEvent = (type, data) => {
711
+ res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
712
+ };
713
+
714
+ try {
715
+ if (!workspacePath || !githubUrl) {
716
+ sendEvent('error', { message: 'workspacePath and githubUrl are required' });
717
+ res.end();
718
+ return;
719
+ }
720
+
721
+ const validation = await validateWorkspacePath(workspacePath);
722
+ if (!validation.valid) {
723
+ sendEvent('error', { message: validation.error });
724
+ res.end();
725
+ return;
726
+ }
727
+
728
+ const absolutePath = validation.resolvedPath;
729
+
730
+ await fs.mkdir(absolutePath, { recursive: true });
731
+
732
+ let githubToken = null;
733
+ if (githubTokenId) {
734
+ const token = await getGithubTokenById(parseInt(githubTokenId), req.user.id);
735
+ if (!token) {
736
+ await fs.rm(absolutePath, { recursive: true, force: true });
737
+ sendEvent('error', { message: 'GitHub token not found' });
738
+ res.end();
739
+ return;
740
+ }
741
+ githubToken = token.github_token;
742
+ } else if (newGithubToken) {
743
+ githubToken = newGithubToken;
744
+ }
745
+
746
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
747
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
748
+ const clonePath = path.join(absolutePath, repoName);
749
+
750
+ // Check if clone destination already exists to prevent data loss
751
+ try {
752
+ await fs.access(clonePath);
753
+ sendEvent('error', { message: `Directory "${repoName}" already exists. Please choose a different location or remove the existing directory.` });
754
+ res.end();
755
+ return;
756
+ } catch (err) {
757
+ // Directory doesn't exist, which is what we want
758
+ }
759
+
760
+ let cloneUrl = githubUrl;
761
+ if (githubToken) {
762
+ try {
763
+ const url = new URL(githubUrl);
764
+ url.username = githubToken;
765
+ url.password = '';
766
+ cloneUrl = url.toString();
767
+ } catch (error) {
768
+ // SSH URL or invalid - use as-is
769
+ }
770
+ }
771
+
772
+ sendEvent('progress', { message: `Cloning into '${repoName}'...` });
773
+
774
+ const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, clonePath], {
775
+ stdio: ['ignore', 'pipe', 'pipe'],
776
+ env: {
777
+ ...process.env,
778
+ GIT_TERMINAL_PROMPT: '0'
779
+ }
780
+ });
781
+
782
+ let lastError = '';
783
+
784
+ gitProcess.stdout.on('data', (data) => {
785
+ const message = data.toString().trim();
786
+ if (message) {
787
+ sendEvent('progress', { message });
788
+ }
789
+ });
790
+
791
+ gitProcess.stderr.on('data', (data) => {
792
+ const message = data.toString().trim();
793
+ lastError = message;
794
+ if (message) {
795
+ sendEvent('progress', { message });
796
+ }
797
+ });
798
+
799
+ gitProcess.on('close', async (code) => {
800
+ if (code === 0) {
801
+ try {
802
+ const project = await addProjectManually(clonePath);
803
+ sendEvent('complete', { project, message: 'Repository cloned successfully' });
804
+ } catch (error) {
805
+ sendEvent('error', { message: `Clone succeeded but failed to add project: ${error.message}` });
806
+ }
807
+ } else {
808
+ const sanitizedError = sanitizeGitError(lastError, githubToken);
809
+ let errorMessage = 'Git clone failed';
810
+ if (lastError.includes('Authentication failed') || lastError.includes('could not read Username')) {
811
+ errorMessage = 'Authentication failed. Please check your credentials.';
812
+ } else if (lastError.includes('Repository not found')) {
813
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
814
+ } else if (lastError.includes('already exists')) {
815
+ errorMessage = 'Directory already exists';
816
+ } else if (sanitizedError) {
817
+ errorMessage = sanitizedError;
818
+ }
819
+ try {
820
+ await fs.rm(clonePath, { recursive: true, force: true });
821
+ } catch (cleanupError) {
822
+ console.error('Failed to clean up after clone failure:', sanitizeGitError(cleanupError.message, githubToken));
823
+ }
824
+ sendEvent('error', { message: errorMessage });
825
+ }
826
+ res.end();
827
+ });
828
+
829
+ gitProcess.on('error', (error) => {
830
+ if (error.code === 'ENOENT') {
831
+ sendEvent('error', { message: 'Git is not installed or not in PATH' });
832
+ } else {
833
+ sendEvent('error', { message: error.message });
834
+ }
835
+ res.end();
836
+ });
837
+
838
+ req.on('close', () => {
839
+ gitProcess.kill();
840
+ });
841
+
842
+ } catch (error) {
843
+ sendEvent('error', { message: error.message });
844
+ res.end();
845
+ }
846
+ });
847
+
848
+ /**
849
+ * Helper function to clone a GitHub repository
850
+ */
851
+ function cloneGitHubRepository(githubUrl, destinationPath, githubToken = null) {
852
+ return new Promise((resolve, reject) => {
853
+ let cloneUrl = githubUrl;
854
+
855
+ if (githubToken) {
856
+ try {
857
+ const url = new URL(githubUrl);
858
+ url.username = githubToken;
859
+ url.password = '';
860
+ cloneUrl = url.toString();
861
+ } catch (error) {
862
+ // SSH URL - use as-is
863
+ }
864
+ }
865
+
866
+ const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, destinationPath], {
867
+ stdio: ['ignore', 'pipe', 'pipe'],
868
+ env: {
869
+ ...process.env,
870
+ GIT_TERMINAL_PROMPT: '0'
871
+ }
872
+ });
873
+
874
+ let stdout = '';
875
+ let stderr = '';
876
+
877
+ gitProcess.stdout.on('data', (data) => {
878
+ stdout += data.toString();
879
+ });
880
+
881
+ gitProcess.stderr.on('data', (data) => {
882
+ stderr += data.toString();
883
+ });
884
+
885
+ gitProcess.on('close', (code) => {
886
+ if (code === 0) {
887
+ resolve({ stdout, stderr });
888
+ } else {
889
+ let errorMessage = 'Git clone failed';
890
+
891
+ if (stderr.includes('Authentication failed') || stderr.includes('could not read Username')) {
892
+ errorMessage = 'Authentication failed. Please check your GitHub token.';
893
+ } else if (stderr.includes('Repository not found')) {
894
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
895
+ } else if (stderr.includes('already exists')) {
896
+ errorMessage = 'Directory already exists';
897
+ } else if (stderr) {
898
+ errorMessage = stderr;
899
+ }
900
+
901
+ reject(new Error(errorMessage));
902
+ }
903
+ });
904
+
905
+ gitProcess.on('error', (error) => {
906
+ if (error.code === 'ENOENT') {
907
+ reject(new Error('Git is not installed or not in PATH'));
908
+ } else {
909
+ reject(error);
910
+ }
911
+ });
912
+ });
913
+ }
914
+
915
+ export default router;