@pixelbyte-software/pixcode 1.51.2 → 1.51.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 (331) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +155 -155
  3. package/LICENSE +718 -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 +419 -419
  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-B9N-gfOQ.css +32 -0
  15. package/dist/assets/{index-EN9ngyxf.js → index-HfGHXhD6.js} +175 -175
  16. package/dist/clear-cache.html +85 -85
  17. package/dist/convert-icons.md +52 -52
  18. package/dist/docs.html +308 -308
  19. package/dist/favicon.svg +8 -8
  20. package/dist/features.html +133 -133
  21. package/dist/generate-icons.js +48 -48
  22. package/dist/humans.txt +15 -15
  23. package/dist/icons/codex-white.svg +3 -3
  24. package/dist/icons/codex.svg +3 -3
  25. package/dist/icons/cursor-white.svg +11 -11
  26. package/dist/icons/icon-128x128.svg +9 -9
  27. package/dist/icons/icon-144x144.svg +9 -9
  28. package/dist/icons/icon-152x152.svg +9 -9
  29. package/dist/icons/icon-192x192.svg +9 -9
  30. package/dist/icons/icon-384x384.svg +9 -9
  31. package/dist/icons/icon-512x512.svg +9 -9
  32. package/dist/icons/icon-72x72.svg +9 -9
  33. package/dist/icons/icon-96x96.svg +9 -9
  34. package/dist/icons/icon-template.svg +9 -9
  35. package/dist/icons/qwen-logo.svg +14 -14
  36. package/dist/index.html +59 -59
  37. package/dist/landing.html +268 -268
  38. package/dist/llms-full.txt +119 -119
  39. package/dist/llms.txt +53 -53
  40. package/dist/logo.svg +12 -12
  41. package/dist/manifest.json +60 -60
  42. package/dist/openapi.yaml +1696 -1696
  43. package/dist/orchestration.html +125 -125
  44. package/dist/robots.txt +4 -4
  45. package/dist/site.css +692 -692
  46. package/dist/sitemap.xml +51 -51
  47. package/dist/sw.js +132 -132
  48. package/dist-server/server/cli.js +96 -96
  49. package/dist-server/server/daemon/manager.js +33 -33
  50. package/dist-server/server/daemon-manager.js +64 -64
  51. package/dist-server/server/database/db.js +14 -2
  52. package/dist-server/server/database/db.js.map +1 -1
  53. package/dist-server/server/index.js +191 -31
  54. package/dist-server/server/index.js.map +1 -1
  55. package/dist-server/server/middleware/auth.js +16 -5
  56. package/dist-server/server/middleware/auth.js.map +1 -1
  57. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js +84 -0
  58. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.js.map +1 -0
  59. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js +43 -0
  60. package/dist-server/server/modules/orchestration/a2a/adapters/json-event.adapter.test.js.map +1 -0
  61. package/dist-server/server/modules/orchestration/hermes/hermes.routes.js +55 -1
  62. package/dist-server/server/modules/orchestration/hermes/hermes.routes.js.map +1 -1
  63. package/dist-server/server/modules/orchestration/index.js +1 -0
  64. package/dist-server/server/modules/orchestration/index.js.map +1 -1
  65. package/dist-server/server/routes/auth.js +12 -5
  66. package/dist-server/server/routes/auth.js.map +1 -1
  67. package/dist-server/server/routes/commands.js +25 -25
  68. package/dist-server/server/routes/git.js +29 -17
  69. package/dist-server/server/routes/git.js.map +1 -1
  70. package/dist-server/server/routes/live-view.js +46 -46
  71. package/dist-server/server/routes/platformization.js +7 -6
  72. package/dist-server/server/routes/platformization.js.map +1 -1
  73. package/dist-server/server/services/hermes-gateway.js +310 -0
  74. package/dist-server/server/services/hermes-gateway.js.map +1 -1
  75. package/dist-server/server/services/platformization.js +58 -2
  76. package/dist-server/server/services/platformization.js.map +1 -1
  77. package/dist-server/server/services/public-api-manifest.js +59 -51
  78. package/dist-server/server/services/public-api-manifest.js.map +1 -1
  79. package/package.json +222 -222
  80. package/scripts/fix-node-pty.js +67 -67
  81. package/scripts/github/create-v1.38-issues.mjs +351 -351
  82. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  83. package/scripts/hermes/configure-pixcode-mcp.mjs +165 -163
  84. package/scripts/hermes/pixcode-mcp-server.mjs +1009 -958
  85. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  86. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  87. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  88. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  89. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  90. package/scripts/smoke/chat-session-state.mjs +19 -19
  91. package/scripts/smoke/code-editor-theme.mjs +55 -55
  92. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  93. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  94. package/scripts/smoke/command-center-non-git.mjs +46 -46
  95. package/scripts/smoke/context-packet.mjs +43 -43
  96. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  97. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  98. package/scripts/smoke/default-landing-routing.mjs +33 -33
  99. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  100. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  101. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  102. package/scripts/smoke/git-install-update.mjs +255 -255
  103. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  104. package/scripts/smoke/hermes-api-install.mjs +56 -56
  105. package/scripts/smoke/hermes-gateway-persistence.mjs +104 -104
  106. package/scripts/smoke/hermes-mcp-pixcode-roundtrip.mjs +426 -367
  107. package/scripts/smoke/hermes-rest-chat-api.mjs +162 -162
  108. package/scripts/smoke/hermes-rest-chat-live.mjs +45 -45
  109. package/scripts/smoke/hermes-rest-codex-launch.mjs +209 -209
  110. package/scripts/smoke/hermes-rest-gateway.mjs +79 -70
  111. package/scripts/smoke/hermes-rest-live.mjs +42 -42
  112. package/scripts/smoke/hermes-roundtrip.mjs +167 -167
  113. package/scripts/smoke/hermes-settings-commands.mjs +349 -346
  114. package/scripts/smoke/hermes-smoke-launcher-guard.mjs +34 -34
  115. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  116. package/scripts/smoke/live-view-environment.mjs +92 -92
  117. package/scripts/smoke/live-view-integration.mjs +450 -450
  118. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  119. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  120. package/scripts/smoke/model-registry.mjs +36 -36
  121. package/scripts/smoke/multi-project-ui.mjs +45 -45
  122. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  123. package/scripts/smoke/notification-center.mjs +87 -87
  124. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  125. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  126. package/scripts/smoke/orchestration-api.mjs +172 -172
  127. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  128. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  129. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  130. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  131. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  132. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  133. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  134. package/scripts/smoke/permission-policy.mjs +50 -50
  135. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  136. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  137. package/scripts/smoke/provider-rest-api.mjs +124 -124
  138. package/scripts/smoke/provider-selection-status.mjs +52 -52
  139. package/scripts/smoke/run-state-refresh.mjs +52 -52
  140. package/scripts/smoke/runtime-manager.mjs +99 -99
  141. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  142. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  143. package/scripts/smoke/static-root-routing.mjs +21 -21
  144. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  145. package/scripts/smoke/taskmaster-config.mjs +24 -24
  146. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  147. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  148. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  149. package/scripts/smoke/telegram-control.mjs +242 -242
  150. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  151. package/scripts/smoke/update-issue-progress.mjs +69 -69
  152. package/scripts/smoke/update-ux.mjs +55 -55
  153. package/scripts/smoke/v138-completion.mjs +132 -132
  154. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  155. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  156. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  157. package/scripts/smoke/v143-remote-control.mjs +76 -76
  158. package/scripts/smoke/v144-production-loop.mjs +47 -47
  159. package/scripts/smoke/v145-platformization.mjs +46 -46
  160. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  161. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  162. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  163. package/scripts/smoke/vscode-workbench-polish.mjs +461 -436
  164. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  165. package/scripts/smoke/workflow-templates.mjs +43 -43
  166. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  167. package/scripts/update-git-install.mjs +293 -293
  168. package/server/claude-sdk.js +920 -920
  169. package/server/cli.js +1039 -1039
  170. package/server/constants/config.js +4 -4
  171. package/server/cursor-cli.js +344 -344
  172. package/server/daemon/manager.js +563 -563
  173. package/server/daemon-manager.js +964 -964
  174. package/server/database/db.js +908 -895
  175. package/server/database/json-store.js +197 -197
  176. package/server/gemini-cli.js +550 -550
  177. package/server/gemini-response-handler.js +79 -79
  178. package/server/index.js +201 -30
  179. package/server/load-env.js +35 -35
  180. package/server/middleware/auth.js +171 -156
  181. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  182. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  183. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  184. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  185. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  186. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  187. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -0
  188. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -0
  189. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  190. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  191. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  192. package/server/modules/orchestration/a2a/routes.ts +590 -590
  193. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  194. package/server/modules/orchestration/a2a/types.ts +126 -126
  195. package/server/modules/orchestration/a2a/validator.ts +113 -113
  196. package/server/modules/orchestration/hermes/hermes.routes.ts +642 -583
  197. package/server/modules/orchestration/index.ts +101 -100
  198. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  199. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  200. package/server/modules/orchestration/preview/types.ts +19 -19
  201. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  202. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  203. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +64 -64
  204. package/server/modules/orchestration/tasks/orchestration-task.service.ts +209 -209
  205. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  206. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  207. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  208. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  209. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  210. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  211. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  212. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  213. package/server/modules/orchestration/workflows/workflow-runner.ts +2070 -2070
  214. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  215. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  216. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  217. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  218. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  219. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  220. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  221. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  222. package/server/modules/orchestration/workspace/types.ts +52 -52
  223. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  224. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  225. package/server/modules/providers/index.ts +2 -2
  226. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  227. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  228. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  229. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  230. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  231. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  232. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  233. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  234. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  235. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  236. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  237. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  238. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  239. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  240. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  241. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  242. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  243. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  244. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  245. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  246. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  247. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  248. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  249. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  250. package/server/modules/providers/provider.registry.ts +40 -40
  251. package/server/modules/providers/provider.routes.ts +944 -944
  252. package/server/modules/providers/services/mcp.service.ts +86 -86
  253. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  254. package/server/modules/providers/services/sessions.service.ts +45 -45
  255. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  256. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  257. package/server/modules/providers/shared/provider-configs.ts +142 -142
  258. package/server/modules/providers/tests/mcp.test.ts +293 -293
  259. package/server/openai-codex.js +462 -462
  260. package/server/opencode-cli.js +491 -491
  261. package/server/opencode-response-handler.js +111 -111
  262. package/server/projects.js +3008 -3008
  263. package/server/qwen-code-cli.js +410 -410
  264. package/server/qwen-response-handler.js +73 -73
  265. package/server/routes/agent.js +1435 -1435
  266. package/server/routes/auth.js +154 -146
  267. package/server/routes/codex.js +20 -20
  268. package/server/routes/commands.js +570 -570
  269. package/server/routes/cursor.js +61 -61
  270. package/server/routes/diagnostics.js +41 -41
  271. package/server/routes/gemini.js +25 -25
  272. package/server/routes/git.js +1650 -1635
  273. package/server/routes/live-view.js +411 -411
  274. package/server/routes/mcp-utils.js +13 -13
  275. package/server/routes/messages.js +62 -62
  276. package/server/routes/network.js +125 -125
  277. package/server/routes/platformization.js +198 -197
  278. package/server/routes/plugins.js +320 -320
  279. package/server/routes/production-agent-loop.js +90 -90
  280. package/server/routes/projects.js +917 -917
  281. package/server/routes/public-api.js +34 -34
  282. package/server/routes/qwen.js +27 -27
  283. package/server/routes/remote.js +55 -55
  284. package/server/routes/settings.js +321 -321
  285. package/server/routes/telegram.js +140 -140
  286. package/server/routes/user.js +125 -125
  287. package/server/routes/webhooks.js +63 -63
  288. package/server/services/control-room.js +102 -102
  289. package/server/services/diagnostics.js +165 -165
  290. package/server/services/external-access.js +375 -375
  291. package/server/services/hermes-gateway.js +1562 -1247
  292. package/server/services/hermes-install-jobs.js +729 -729
  293. package/server/services/install-jobs.js +715 -715
  294. package/server/services/live-view.js +956 -956
  295. package/server/services/managed-runtimes.js +493 -493
  296. package/server/services/model-registry.js +144 -144
  297. package/server/services/notification-orchestrator.js +365 -365
  298. package/server/services/notification-taxonomy.js +204 -204
  299. package/server/services/platformization.js +844 -779
  300. package/server/services/production-agent-loop.js +248 -248
  301. package/server/services/provider-cli-versions.js +149 -149
  302. package/server/services/provider-credentials.js +189 -189
  303. package/server/services/provider-models.js +396 -396
  304. package/server/services/public-api-manifest.js +190 -182
  305. package/server/services/remote-connection.js +127 -127
  306. package/server/services/runtime-manager.js +323 -323
  307. package/server/services/startup-update.js +234 -234
  308. package/server/services/telegram/bot.js +331 -331
  309. package/server/services/telegram/control-center.js +979 -979
  310. package/server/services/telegram/telegram-http-client.js +151 -151
  311. package/server/services/telegram/translations.js +340 -340
  312. package/server/services/vapid-keys.js +36 -36
  313. package/server/services/webhooks.js +216 -216
  314. package/server/sessionManager.js +225 -225
  315. package/server/shared/interfaces.ts +54 -54
  316. package/server/shared/types.ts +172 -172
  317. package/server/shared/utils.ts +193 -193
  318. package/server/tsconfig.json +36 -36
  319. package/server/utils/colors.js +21 -21
  320. package/server/utils/commandParser.js +305 -305
  321. package/server/utils/frontmatter.js +18 -18
  322. package/server/utils/gitConfig.js +34 -34
  323. package/server/utils/plugin-loader.js +457 -457
  324. package/server/utils/plugin-process-manager.js +185 -185
  325. package/server/utils/port-access.js +209 -209
  326. package/server/utils/runtime-paths.js +37 -37
  327. package/server/utils/url-detection.js +71 -71
  328. package/server/vite-daemon.js +79 -79
  329. package/shared/modelConstants.js +161 -161
  330. package/shared/networkHosts.js +22 -22
  331. package/dist/assets/index-DMz0zv6T.css +0 -32
@@ -1,917 +1,917 @@
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;
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;