@pixelbyte-software/pixcode 1.54.10 → 1.54.11

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