@pixelbyte-software/pixcode 1.35.2 → 1.35.4

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