arco-workbench 0.1.7 → 0.1.9

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 (301) hide show
  1. package/CONTRIBUTING.md +63 -12
  2. package/README.md +21 -17
  3. package/client/dist/assets/{PhosphorBackdrop-DVQdBrTw.js → PhosphorBackdrop-DRu16-Is.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-BfSs2tB4.js → ThemedBackgroundShaderImpl-BLdwwQ4D.js} +1 -1
  5. package/client/dist/assets/{XtermView-DaMjC8Ny.js → XtermView-Xk7_9JaH.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-BCQnXj7R.js → galleryEditor-CI8ClzBa.js} +1 -1
  7. package/client/dist/assets/{index-DD9kFGsF.css → index-BEFgrUJJ.css} +1 -1
  8. package/client/dist/assets/{index-COfbHCYv.js → index-C7WzZfsr.js} +257 -255
  9. package/client/dist/index.html +2 -2
  10. package/client/src/App.tsx +2 -0
  11. package/client/src/components/ChatMessage.tsx +33 -8
  12. package/client/src/components/ChatModeView.tsx +2 -0
  13. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +65 -15
  14. package/client/src/components/ClusterRightPanel/SkillsControl.tsx +124 -0
  15. package/client/src/components/ClusterRightPanel/index.tsx +4 -0
  16. package/client/src/components/ClusterTaskBoardTab.tsx +9 -22
  17. package/client/src/components/CodexLateCommand.tsx +34 -0
  18. package/client/src/components/DialogShell.tsx +2 -0
  19. package/client/src/components/MemberCard.tsx +4 -1
  20. package/client/src/components/MemberPane.tsx +3 -1
  21. package/client/src/components/NeedsYouBadge.tsx +3 -3
  22. package/client/src/components/PhoneUpload.tsx +288 -0
  23. package/client/src/components/PrimaryStatus.tsx +14 -6
  24. package/client/src/components/ProviderReleasesModal.tsx +8 -4
  25. package/client/src/components/ProvidersPopover.tsx +28 -23
  26. package/client/src/components/RuntimeStateBanner.tsx +5 -0
  27. package/client/src/components/SettingsPanel.tsx +2 -2
  28. package/client/src/components/SkillEditorDialog.tsx +2 -2
  29. package/client/src/components/SkillsSettings.tsx +21 -4
  30. package/client/src/components/TabBar.tsx +91 -9
  31. package/client/src/components/TerminalInput.tsx +15 -11
  32. package/client/src/components/TranscriptSendDialog.tsx +12 -8
  33. package/client/src/components/TranscriptWorkerDialog.tsx +119 -0
  34. package/client/src/components/WorkflowView.tsx +2 -0
  35. package/client/src/components/clusterNeedsYou.ts +11 -18
  36. package/client/src/explorer/ArtifactsLens.tsx +37 -28
  37. package/client/src/explorer/ExplorerApp.tsx +5 -4
  38. package/client/src/explorer/types.ts +8 -3
  39. package/client/src/help/content/cluster.tsx +48 -17
  40. package/client/src/help/content/composer.tsx +40 -1
  41. package/client/src/help/content/header.tsx +18 -1
  42. package/client/src/help/content/misc.tsx +9 -1
  43. package/client/src/help/content/settings.tsx +18 -4
  44. package/client/src/help/content/tabbar.tsx +5 -0
  45. package/client/src/help/manualSections/actions.tsx +31 -0
  46. package/client/src/help/manualSections/clusters.tsx +44 -20
  47. package/client/src/help/manualSections/configuration.tsx +20 -0
  48. package/client/src/help/manualSections/gettingStarted.tsx +4 -4
  49. package/client/src/help/manualSections/maintenance.tsx +25 -6
  50. package/client/src/help/manualSections/powerFeatures.tsx +3 -2
  51. package/client/src/help/manualSections/providers.tsx +32 -8
  52. package/client/src/help/manualSections/troubleshooting.tsx +2 -1
  53. package/client/src/help/manualSections/workflows.tsx +12 -0
  54. package/client/src/help/manualSections/workspace.tsx +36 -0
  55. package/client/src/stores/appStore.ts +7 -0
  56. package/client/src/stores/appStore.types.ts +4 -0
  57. package/client/src/styles/global.css +109 -0
  58. package/client/src/utils/phoneTheme.ts +38 -0
  59. package/client/src/utils/phoneUploadApi.ts +10 -0
  60. package/client/src/utils/transcriptWorkerRequest.ts +24 -0
  61. package/client/src/ws/handleServerMessage.ts +31 -8
  62. package/docs/ARCHITECTURE.md +1 -1
  63. package/docs/CLIENT.md +16 -9
  64. package/docs/FEATURES.md +13 -7
  65. package/docs/GETTING_STARTED.md +12 -6
  66. package/docs/GOTCHAS.md +2 -1
  67. package/docs/INDEX.md +1 -1
  68. package/docs/OPERATIONS.md +213 -52
  69. package/docs/PERSISTENCE.md +7 -2
  70. package/docs/PRIMITIVES.md +42 -0
  71. package/docs/PROTOCOL_CLUSTER.md +51 -4
  72. package/docs/PROTOCOL_PRIMITIVES.md +39 -0
  73. package/docs/PROVIDERS.md +84 -13
  74. package/docs/SETTINGS.md +29 -3
  75. package/docs/TASK_LEDGER.md +7 -15
  76. package/native/linux-x64/manifest.json +1 -1
  77. package/native/win32-x64/manifest.json +1 -1
  78. package/node_modules/@arco/shared/dist/clusterCoordination.d.ts +2 -0
  79. package/node_modules/@arco/shared/dist/clusterCoordination.js +5 -1
  80. package/node_modules/@arco/shared/dist/protocol/chat.d.ts +1 -0
  81. package/node_modules/@arco/shared/dist/protocol/clientMessages.d.ts +3 -2
  82. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -1
  83. package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
  84. package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
  85. package/node_modules/@arco/shared/dist/protocol/models.d.ts +4 -3
  86. package/node_modules/@arco/shared/dist/protocol/models.js +26 -2
  87. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +13 -1
  88. package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +4 -0
  89. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  90. package/node_modules/@arco/shared/dist/protocol/transcriptWorker.js +2 -0
  91. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  92. package/node_modules/@arco/shared/dist/runtimeVersions.d.ts +1 -0
  93. package/node_modules/@arco/shared/dist/runtimeVersions.js +14 -0
  94. package/node_modules/@arco/shared/package.json +1 -1
  95. package/package.json +2 -2
  96. package/scripts/packaging/arco.mjs +1 -1
  97. package/scripts/packaging/native-repair.mjs +32 -4
  98. package/server/dist/atomicFile.js +1 -2
  99. package/server/dist/capabilities.d.ts +5 -2
  100. package/server/dist/capabilities.js +59 -9
  101. package/server/dist/cliUpdateDecision.d.ts +1 -1
  102. package/server/dist/cliUpdateDecision.js +5 -3
  103. package/server/dist/clusterDirector.js +2 -1
  104. package/server/dist/clusterPeerOps.js +14 -8
  105. package/server/dist/clusterProgress.js +1 -1
  106. package/server/dist/clusterRehydrate.js +2 -0
  107. package/server/dist/clusterSkills.d.ts +13 -0
  108. package/server/dist/clusterSkills.js +81 -0
  109. package/server/dist/clusterSnapshots.js +2 -0
  110. package/server/dist/clusterStore.d.ts +7 -2
  111. package/server/dist/clusterStore.js +42 -1
  112. package/server/dist/diagnostics/codeSkew.js +1 -0
  113. package/server/dist/eventLog.d.ts +7 -0
  114. package/server/dist/eventLog.js +70 -13
  115. package/server/dist/explorerDocs.d.ts +10 -6
  116. package/server/dist/explorerDocs.js +75 -34
  117. package/server/dist/historyLimits.d.ts +1 -0
  118. package/server/dist/historyLimits.js +3 -0
  119. package/server/dist/http/attachmentUpload.d.ts +13 -0
  120. package/server/dist/http/attachmentUpload.js +38 -0
  121. package/server/dist/http/browserWorktrees.d.ts +23 -0
  122. package/server/dist/http/browserWorktrees.js +120 -0
  123. package/server/dist/http/phoneUploadDrafts.d.ts +13 -0
  124. package/server/dist/http/phoneUploadDrafts.js +125 -0
  125. package/server/dist/http/phoneUploadListener.d.ts +17 -0
  126. package/server/dist/http/phoneUploadListener.js +81 -0
  127. package/server/dist/http/phoneUploadNetwork.d.ts +9 -0
  128. package/server/dist/http/phoneUploadNetwork.js +106 -0
  129. package/server/dist/http/phoneUploadPage.d.ts +2 -0
  130. package/server/dist/http/phoneUploadPage.js +136 -0
  131. package/server/dist/http/phoneUploadRouteHistory.d.ts +4 -0
  132. package/server/dist/http/phoneUploadRouteHistory.js +72 -0
  133. package/server/dist/http/phoneUploadRoutes.d.ts +4 -0
  134. package/server/dist/http/phoneUploadRoutes.js +419 -0
  135. package/server/dist/http/phoneUploadTheme.d.ts +17 -0
  136. package/server/dist/http/phoneUploadTheme.js +96 -0
  137. package/server/dist/http/projectBinding.d.ts +1 -0
  138. package/server/dist/http/projectBinding.js +3 -2
  139. package/server/dist/http/readConfinement.js +5 -1
  140. package/server/dist/http/router.js +14 -25
  141. package/server/dist/http/writeConfinement.js +19 -2
  142. package/server/dist/index.js +24 -1
  143. package/server/dist/jsonlLines.d.ts +4 -0
  144. package/server/dist/jsonlLines.js +53 -0
  145. package/server/dist/management/identity.js +1 -0
  146. package/server/dist/mcp/clusterMcpTools.js +4 -4
  147. package/server/dist/primitives/seedWorker.d.ts +1 -0
  148. package/server/dist/primitives/seedWorker.js +2 -1
  149. package/server/dist/project/taskLedger.d.ts +4 -0
  150. package/server/dist/project/taskLedger.js +7 -4
  151. package/server/dist/providerConversation.d.ts +1 -0
  152. package/server/dist/providerConversation.js +17 -0
  153. package/server/dist/providers/claude-native/resumeSummary.d.ts +9 -0
  154. package/server/dist/providers/claude-native/resumeSummary.js +102 -49
  155. package/server/dist/providers/claude-native/worker.js +8 -4
  156. package/server/dist/providers/claude.js +2 -1
  157. package/server/dist/providers/clusterTaskToolDefinitions.js +4 -4
  158. package/server/dist/providers/codex-appserver/catalog.js +16 -1
  159. package/server/dist/providers/codex-appserver/heldCommands.d.ts +14 -0
  160. package/server/dist/providers/codex-appserver/heldCommands.js +54 -0
  161. package/server/dist/providers/codex-appserver/index.d.ts +52 -2
  162. package/server/dist/providers/codex-appserver/index.js +239 -21
  163. package/server/dist/providers/codex-appserver/lateCommands.d.ts +62 -0
  164. package/server/dist/providers/codex-appserver/lateCommands.js +195 -0
  165. package/server/dist/providers/codex-appserver/worker.d.ts +23 -1
  166. package/server/dist/providers/codex-appserver/worker.js +89 -20
  167. package/server/dist/providers/codex.js +2 -1
  168. package/server/dist/providers/codexCodeMode.d.ts +2 -1
  169. package/server/dist/providers/codexCodeMode.js +8 -3
  170. package/server/dist/providers/cursor/print.js +2 -1
  171. package/server/dist/providers/cursor/worker.js +2 -1
  172. package/server/dist/providers/llamacpp.js +17 -8
  173. package/server/dist/providers/ollamaRecovery.js +6 -6
  174. package/server/dist/providers/ollamaResilience.js +3 -3
  175. package/server/dist/providers/ollamaTokens.js +1 -1
  176. package/server/dist/quota.d.ts +0 -18
  177. package/server/dist/quota.js +0 -44
  178. package/server/dist/replacementHistory.d.ts +19 -0
  179. package/server/dist/replacementHistory.js +49 -0
  180. package/server/dist/server/broadcast.d.ts +2 -1
  181. package/server/dist/server/broadcast.js +1 -0
  182. package/server/dist/server/prompts.d.ts +1 -0
  183. package/server/dist/server/prompts.js +6 -1
  184. package/server/dist/sessionJsonl.d.ts +1 -1
  185. package/server/dist/sessionJsonl.js +115 -40
  186. package/server/dist/smartPickupAdapters.js +15 -2
  187. package/server/dist/transcriptWorker.d.ts +34 -0
  188. package/server/dist/transcriptWorker.js +201 -0
  189. package/server/dist/workers/WorkerManager.d.ts +1 -0
  190. package/server/dist/workers/WorkerManager.js +1 -0
  191. package/server/dist/workers/processKill.d.ts +9 -1
  192. package/server/dist/workers/processKill.js +26 -10
  193. package/server/dist/workflowStore.d.ts +1 -0
  194. package/server/dist/workflowStore.js +31 -0
  195. package/server/dist/ws/clusterHandlers.d.ts +1 -0
  196. package/server/dist/ws/clusterHandlers.js +62 -26
  197. package/server/dist/ws/handoffHandlers.js +7 -2
  198. package/server/dist/ws/transcriptWorkerHandlers.d.ts +25 -0
  199. package/server/dist/ws/transcriptWorkerHandlers.js +139 -0
  200. package/server/dist/ws/turnEngine.js +40 -9
  201. package/server/dist/ws/updatePrimaryConfig.js +27 -8
  202. package/server/dist/ws/workflowHandlers.d.ts +4 -1
  203. package/server/dist/ws/workflowHandlers.js +3 -1
  204. package/server/package.json +1 -1
  205. package/server/src/atomicFile.ts +1 -2
  206. package/server/src/capabilities.ts +58 -17
  207. package/server/src/cliUpdateDecision.ts +5 -4
  208. package/server/src/clusterDirector.ts +2 -1
  209. package/server/src/clusterPeerOps.ts +15 -9
  210. package/server/src/clusterProgress.ts +1 -1
  211. package/server/src/clusterRehydrate.ts +2 -0
  212. package/server/src/clusterSkills.ts +79 -0
  213. package/server/src/clusterSnapshots.ts +1 -0
  214. package/server/src/clusterStore.ts +38 -0
  215. package/server/src/diagnostics/codeSkew.ts +1 -0
  216. package/server/src/eventLog.ts +73 -13
  217. package/server/src/explorerDocs.ts +75 -34
  218. package/server/src/historyLimits.ts +2 -0
  219. package/server/src/http/attachmentUpload.ts +49 -0
  220. package/server/src/http/browserWorktrees.ts +124 -0
  221. package/server/src/http/phoneUploadDrafts.ts +118 -0
  222. package/server/src/http/phoneUploadListener.ts +96 -0
  223. package/server/src/http/phoneUploadNetwork.ts +117 -0
  224. package/server/src/http/phoneUploadPage.ts +137 -0
  225. package/server/src/http/phoneUploadRouteHistory.ts +73 -0
  226. package/server/src/http/phoneUploadRoutes.ts +398 -0
  227. package/server/src/http/phoneUploadTheme.ts +97 -0
  228. package/server/src/http/projectBinding.ts +3 -2
  229. package/server/src/http/readConfinement.ts +5 -1
  230. package/server/src/http/router.ts +12 -26
  231. package/server/src/http/writeConfinement.ts +13 -2
  232. package/server/src/index.ts +23 -0
  233. package/server/src/jsonlLines.ts +52 -0
  234. package/server/src/management/identity.ts +1 -0
  235. package/server/src/mcp/clusterMcpTools.ts +4 -4
  236. package/server/src/primitives/seedWorker.ts +3 -1
  237. package/server/src/project/taskLedger.ts +7 -5
  238. package/server/src/providerConversation.ts +15 -0
  239. package/server/src/providers/claude-native/resumeSummary.ts +98 -50
  240. package/server/src/providers/claude-native/worker.ts +8 -4
  241. package/server/src/providers/claude.ts +2 -1
  242. package/server/src/providers/clusterTaskToolDefinitions.ts +4 -4
  243. package/server/src/providers/codex-appserver/catalog.ts +14 -1
  244. package/server/src/providers/codex-appserver/heldCommands.ts +58 -0
  245. package/server/src/providers/codex-appserver/index.ts +222 -20
  246. package/server/src/providers/codex-appserver/lateCommands.ts +225 -0
  247. package/server/src/providers/codex-appserver/worker.ts +85 -21
  248. package/server/src/providers/codex.ts +2 -1
  249. package/server/src/providers/codexCodeMode.ts +9 -4
  250. package/server/src/providers/cursor/print.ts +2 -1
  251. package/server/src/providers/cursor/worker.ts +2 -1
  252. package/server/src/providers/llamacpp.ts +18 -7
  253. package/server/src/providers/llamacppRecovery.ts +2 -0
  254. package/server/src/providers/ollamaRecovery.ts +6 -6
  255. package/server/src/providers/ollamaResilience.ts +3 -3
  256. package/server/src/providers/ollamaTokens.ts +1 -1
  257. package/server/src/providers/ollamaToolSubset.ts +3 -3
  258. package/server/src/quota.ts +0 -50
  259. package/server/src/replacementHistory.ts +44 -0
  260. package/server/src/server/broadcast.ts +2 -0
  261. package/server/src/server/prompts.ts +8 -1
  262. package/server/src/sessionJsonl.ts +92 -32
  263. package/server/src/smartPickupAdapters.ts +17 -3
  264. package/server/src/transcriptWorker.ts +182 -0
  265. package/server/src/workers/WorkerManager.ts +2 -0
  266. package/server/src/workers/processKill.ts +35 -7
  267. package/server/src/workflowStore.ts +21 -0
  268. package/server/src/ws/clusterHandlers.ts +43 -25
  269. package/server/src/ws/handoffHandlers.ts +7 -1
  270. package/server/src/ws/transcriptWorkerHandlers.ts +126 -0
  271. package/server/src/ws/turnEngine.ts +35 -8
  272. package/server/src/ws/updatePrimaryConfig.ts +25 -6
  273. package/server/src/ws/workflowHandlers.ts +3 -1
  274. package/shared/dist/clusterCoordination.d.ts +2 -0
  275. package/shared/dist/clusterCoordination.js +5 -1
  276. package/shared/dist/protocol/chat.d.ts +1 -0
  277. package/shared/dist/protocol/clientMessages.d.ts +3 -2
  278. package/shared/dist/protocol/clusters.d.ts +15 -1
  279. package/shared/dist/protocol/index.d.ts +1 -0
  280. package/shared/dist/protocol/index.js +1 -0
  281. package/shared/dist/protocol/models.d.ts +4 -3
  282. package/shared/dist/protocol/models.js +26 -2
  283. package/shared/dist/protocol/serverMessages.d.ts +13 -1
  284. package/shared/dist/protocol/tasks.d.ts +4 -0
  285. package/shared/dist/protocol/transcriptWorker.d.ts +47 -0
  286. package/shared/dist/protocol/transcriptWorker.js +2 -0
  287. package/shared/dist/protocol/workflows.d.ts +1 -0
  288. package/shared/dist/runtimeVersions.d.ts +1 -0
  289. package/shared/dist/runtimeVersions.js +14 -0
  290. package/shared/src/clusterCoordination.ts +7 -1
  291. package/shared/src/protocol/chat.ts +1 -0
  292. package/shared/src/protocol/clientMessages.ts +5 -0
  293. package/shared/src/protocol/clusters.ts +20 -6
  294. package/shared/src/protocol/index.ts +1 -0
  295. package/shared/src/protocol/models.ts +31 -5
  296. package/shared/src/protocol/serverMessages.ts +13 -0
  297. package/shared/src/protocol/settings.ts +2 -3
  298. package/shared/src/protocol/tasks.ts +4 -7
  299. package/shared/src/protocol/transcriptWorker.ts +49 -0
  300. package/shared/src/protocol/workflows.ts +4 -0
  301. package/shared/src/runtimeVersions.ts +14 -0
@@ -0,0 +1,398 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
3
+ import { extname } from 'node:path';
4
+ import { unzipSync } from 'fflate';
5
+ import * as clusterStore from '../clusterStore.js';
6
+ import { fileHeaderKind } from '../fileContent/detect.js';
7
+ import { awaitModelImage } from '../providers/attachments.js';
8
+ import { PORT, UUID_PATTERN } from '../server/constants.js';
9
+ import { workflows } from '../server/state.js';
10
+ import type { WorkflowState } from '../workflows/types.js';
11
+ import { managedUploadPath } from '../uploadImages.js';
12
+ import { readAttachmentBody, storeAttachment, UploadTooLarge } from './attachmentUpload.js';
13
+ import { readFileForExplorer } from './fileRead.js';
14
+ import { discardPhoneDraft, phoneDraftForOwner, phoneFilename, rememberPhoneDraft, PHONE_DRAFT_TTL_MS, type PhoneDraft } from './phoneUploadDrafts.js';
15
+ import { phoneListenerAddresses, phoneUploadOrigins, privatePhoneOrigin } from './phoneUploadNetwork.js';
16
+ import { startPhoneListener, type PhoneListener } from './phoneUploadListener.js';
17
+ import { recordRouteSuccess, routeSuccesses } from './phoneUploadRouteHistory.js';
18
+ import { checkRequestOrigin } from './originGuard.js';
19
+ import { PHONE_PAGE, PHONE_PAGE_CSP } from './phoneUploadPage.js';
20
+ import { bundledPhoneFont, checkedPhoneTheme, type PhoneTheme } from './phoneUploadTheme.js';
21
+ import { readCookie, SESSION_COOKIE, verifyToken } from './wsAuth.js';
22
+
23
+ const PHONE_PATH = '/phone-upload';
24
+ const API_PATH = '/api/phone-upload';
25
+ const UNAVAILABLE = 'Phone upload is unavailable. Open Arco on your private network first.';
26
+ const NO_PRIVATE_ADDRESS = 'Phone upload is unavailable. This computer has no private network or tailnet address a phone can reach. Connect it to Wi-Fi, a wired network or Tailscale, then try again.';
27
+ const NOT_LISTENING = 'Phone upload is unavailable. Arco could not accept connections on this computer\'s private network address. Try again; if it keeps failing, the Arco log has a line with the error code.';
28
+ const CLOSED = 'This link is closed or expired. Open a new code in Arco.';
29
+ const MIB = 1024 * 1024;
30
+ const FILE_LIMIT = 20 * MIB;
31
+ const LINK_LIMIT = 100 * MIB;
32
+ const COUNT_LIMIT = 10;
33
+ const LINK_TTL_MS = 5 * 60_000;
34
+ const MAX_OPEN_LINKS = 8;
35
+ const MAX_TRANSFERS = 2;
36
+ // The temporary phone listener stays open this long after the last request
37
+ // for a code, so a choice between several addresses finds it still there.
38
+ const LISTENER_GRACE_MS = 60_000;
39
+
40
+ interface UploadLink {
41
+ id: string;
42
+ key: string;
43
+ owner: string;
44
+ workflowId: string;
45
+ workflow: WorkflowState;
46
+ cwd: string;
47
+ origin: string;
48
+ expiresAt: number;
49
+ files: PhoneDraft[];
50
+ receivedBytes: number;
51
+ closed: boolean;
52
+ transferring: boolean;
53
+ theme?: PhoneTheme;
54
+ }
55
+
56
+ const links = new Map<string, UploadLink>();
57
+ const tokens = new Map<string, UploadLink>();
58
+ let transfers = 0;
59
+ let phoneListener: Promise<PhoneListener> | null = null;
60
+ let openingCodes = 0;
61
+ let listenerGraceUntil = 0;
62
+ const digest = (s: string) => createHash('sha256').update(s).digest('hex');
63
+
64
+ function json(res: ServerResponse, status: number, body: object): void {
65
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
66
+ res.end(JSON.stringify(body));
67
+ }
68
+
69
+ function error(res: ServerResponse, status: number, message: string): void {
70
+ json(res, status, { error: message });
71
+ }
72
+
73
+ function targetAvailable(id: string, wf: WorkflowState | undefined): wf is WorkflowState {
74
+ if (!wf?.config.workingDirectory || wf.config.incognito) return false;
75
+ const cluster = clusterStore.getClusterIdForWorkflow(id);
76
+ return !cluster || clusterStore.getMemberAccessMode(cluster, id) !== 'isolated';
77
+ }
78
+
79
+ function closeLink(link: UploadLink): void {
80
+ link.closed = true;
81
+ tokens.delete(link.key);
82
+ }
83
+
84
+ function active(link: UploadLink): boolean {
85
+ const wf = workflows.get(link.workflowId);
86
+ if (link.closed || link.expiresAt <= Date.now() || wf !== link.workflow
87
+ || !targetAvailable(link.workflowId, wf) || wf.config.workingDirectory !== link.cwd) {
88
+ closeLink(link);
89
+ return false;
90
+ }
91
+ return true;
92
+ }
93
+
94
+ function purgeLinks(): void {
95
+ const now = Date.now();
96
+ for (const [id, link] of links) {
97
+ active(link);
98
+ if (!link.transferring && link.expiresAt + 60_000 <= now) links.delete(id);
99
+ }
100
+ }
101
+
102
+ // The temporary listener closes only when no code is being opened, no upload
103
+ // is in progress, no link is still open and the grace time has passed.
104
+ function releasePhoneListener(): void {
105
+ if (!phoneListener || openingCodes > 0 || transfers > 0 || Date.now() < listenerGraceUntil) return;
106
+ if ([...tokens.values()].some(link => active(link))) return;
107
+ const closing = phoneListener;
108
+ phoneListener = null;
109
+ void closing.then(listener => listener.close());
110
+ }
111
+
112
+ setInterval(() => { purgeLinks(); releasePhoneListener(); }, 30_000).unref();
113
+
114
+ export async function _closePhoneListenerForTest(): Promise<void> {
115
+ const closing = phoneListener;
116
+ phoneListener = null;
117
+ (await closing)?.close();
118
+ }
119
+
120
+ // The temporary listener's only route: the same Host and Origin precheck as
121
+ // the main router, then the phone page and its upload endpoint.
122
+ async function phoneOnly(req: IncomingMessage, res: ServerResponse): Promise<void> {
123
+ if (!checkRequestOrigin(req).ok) return error(res, 403, 'Forbidden origin');
124
+ await tryHandlePhonePage(req, res);
125
+ }
126
+
127
+ // When the main server serves no private address (the default loopback
128
+ // bind), open the temporary phone listener on this machine's private network
129
+ // and tailnet addresses, or reuse the one already open.
130
+ async function temporaryOrigins(port: number): Promise<{ origins: string[]; error?: string }> {
131
+ listenerGraceUntil = Date.now() + LISTENER_GRACE_MS;
132
+ if (!phoneListener) {
133
+ const addresses = phoneListenerAddresses();
134
+ if (!addresses.length) return { origins: [], error: NO_PRIVATE_ADDRESS };
135
+ phoneListener = startPhoneListener(addresses, port, phoneOnly);
136
+ }
137
+ const current = phoneListener;
138
+ const { origins } = await current;
139
+ if (origins.length) return { origins };
140
+ if (phoneListener === current) phoneListener = null;
141
+ return { origins, error: NOT_LISTENING };
142
+ }
143
+
144
+ const imageExtensions: Record<string, string> = {
145
+ 'image/jpeg': '.jpg', 'image/png': '.png', 'image/gif': '.gif', 'image/webp': '.webp',
146
+ 'image/avif': '.avif', 'image/heic': '.heic', 'image/tiff': '.tiff', 'image/bmp': '.bmp', 'image/x-icon': '.ico',
147
+ };
148
+
149
+ function officeDocument(ext: string, bytes: Buffer): boolean {
150
+ const required: Record<string, string> = {
151
+ '.docx': 'word/document.xml', '.xlsx': 'xl/workbook.xml', '.pptx': 'ppt/presentation.xml',
152
+ '.odt': 'content.xml', '.ods': 'content.xml', '.odp': 'content.xml',
153
+ };
154
+ if (!required[ext]) return false;
155
+ let containsDocument = false;
156
+ let containsActivePart = false;
157
+ try {
158
+ const parts = unzipSync(bytes, { filter: (file) => {
159
+ if (file.name === required[ext]) containsDocument = true;
160
+ if (/vbaProject|^Scripts\/|^Basic\//i.test(file.name)) containsActivePart = true;
161
+ return file.name === 'mimetype' && file.originalSize <= 128 && /^\.od/.test(ext);
162
+ } });
163
+ if (!containsDocument || containsActivePart) return false;
164
+ if (!/^\.od/.test(ext)) return true;
165
+ const kind: Record<string, string> = { '.odt': 'text', '.ods': 'spreadsheet', '.odp': 'presentation' };
166
+ return !!parts.mimetype && Buffer.from(parts.mimetype).toString() === 'application/vnd.oasis.opendocument.' + kind[ext];
167
+ } catch {
168
+ return false;
169
+ }
170
+ }
171
+
172
+ function checkedFilename(req: IncomingMessage, bytes: Buffer): string | null {
173
+ const supplied = req.headers['x-filename'];
174
+ if (typeof supplied !== 'string' || supplied.length > 1024) return null;
175
+ let filename: string;
176
+ try { filename = phoneFilename(decodeURIComponent(supplied)); }
177
+ catch { return null; }
178
+ if (!filename) return null;
179
+ const ext = extname(filename).toLowerCase();
180
+ const content = fileHeaderKind(bytes);
181
+ const detectedExtension = imageExtensions[content];
182
+ if (detectedExtension) {
183
+ const alternates = detectedExtension === '.jpg' ? ['.jpeg'] : detectedExtension === '.heic' ? ['.heif']
184
+ : detectedExtension === '.tiff' ? ['.tif'] : [];
185
+ if (!ext) filename += detectedExtension;
186
+ else if (ext !== detectedExtension && !alternates.includes(ext)) return null;
187
+ return phoneFilename(filename) || null;
188
+ }
189
+ if ((ext === '.pdf' && content === 'application/pdf') || (ext === '.rtf' && content === 'application/rtf')
190
+ || (['.txt', '.md', '.csv'].includes(ext) && content === 'text/plain')
191
+ || (content === 'application/zip' && officeDocument(ext, bytes))) {
192
+ return filename;
193
+ }
194
+ return null;
195
+ }
196
+
197
+ async function uploadFromPhone(req: IncomingMessage, res: ServerResponse, origin: string): Promise<void> {
198
+ const token = req.headers['x-arco-phone-upload'];
199
+ if (req.headers.origin !== origin || typeof token !== 'string' || !/^[\w-]{43}$/.test(token)) {
200
+ return error(res, 403, 'Open the upload page from the QR code.');
201
+ }
202
+ const link = tokens.get(digest(token));
203
+ if (!link || !active(link)) return error(res, 410, CLOSED);
204
+ if (link.origin !== origin) return error(res, 403, UNAVAILABLE);
205
+ if (link.transferring || transfers >= MAX_TRANSFERS) return error(res, 429, 'Another upload is in progress. Try again shortly.');
206
+ if (link.files.length >= COUNT_LIMIT || link.receivedBytes >= LINK_LIMIT) {
207
+ return error(res, 413, 'This link has reached its file limit. Open a new code for more files.');
208
+ }
209
+ const limit = Math.min(FILE_LIMIT, LINK_LIMIT - link.receivedBytes);
210
+ const remaining = link.expiresAt - Date.now();
211
+ const timer = setTimeout(() => req.destroy(), remaining);
212
+ timer.unref();
213
+ link.transferring = true;
214
+ transfers++;
215
+ let draft: PhoneDraft | undefined;
216
+ try {
217
+ if (Number(req.headers['content-length']) > limit) throw new UploadTooLarge();
218
+ const body = await readAttachmentBody(req, limit);
219
+ if (!active(link)) return error(res, 410, CLOSED);
220
+ if (!body.length) return error(res, 400, 'The file is empty.');
221
+ link.receivedBytes += body.length;
222
+ const checked = checkedFilename(req, body);
223
+ if (!checked) return error(res, 415, 'Choose a supported photo, PDF, text or office document.');
224
+ const fileId = randomUUID();
225
+ await storeAttachment(body, checked, '', {
226
+ fileId,
227
+ beforeWrite: async (file) => {
228
+ draft = { ...file, workflowId: link.workflowId, owner: link.owner, expiresAt: Date.now() + PHONE_DRAFT_TTL_MS };
229
+ await rememberPhoneDraft(draft);
230
+ },
231
+ });
232
+ if (!draft) throw new Error('Missing draft receipt');
233
+ if (!active(link)) {
234
+ await discardPhoneDraft(draft);
235
+ return error(res, 410, CLOSED);
236
+ }
237
+ link.files.push(draft);
238
+ // The route worked: remember it. Saving happens in the background and a
239
+ // failure there never turns this successful upload into an error.
240
+ void recordRouteSuccess(link.origin);
241
+ json(res, 201, { ok: true });
242
+ } catch (e) {
243
+ if (draft) await discardPhoneDraft(draft).catch(() => {});
244
+ if (res.destroyed) return;
245
+ if (e instanceof UploadTooLarge) {
246
+ res.setHeader('Connection', 'close');
247
+ error(res, 413, 'This file is too large for the remaining upload allowance.');
248
+ } else {
249
+ error(res, 500, 'Upload failed. Try again from the phone.');
250
+ }
251
+ } finally {
252
+ clearTimeout(timer);
253
+ link.transferring = false;
254
+ transfers--;
255
+ }
256
+ }
257
+
258
+ // Opens one upload link on a chosen address, or lists the addresses to
259
+ // choose from when there are several. Synchronous, so a temporary listener
260
+ // cannot close between its origins being read and the link being recorded.
261
+ function createLink(res: ServerResponse, body: { workflowId: string; origin?: string; theme?: unknown }, workflow: WorkflowState,
262
+ owner: string, origins: string[]): true {
263
+ const origin = body.origin ?? (origins.length === 1 ? origins[0] : undefined);
264
+ if (!origin) {
265
+ json(res, 200, { origins, verified: routeSuccesses(origins) });
266
+ return true;
267
+ }
268
+ if (!origins.includes(origin)) {
269
+ error(res, 403, UNAVAILABLE);
270
+ return true;
271
+ }
272
+ if (tokens.size >= MAX_OPEN_LINKS || links.size >= 4 * MAX_OPEN_LINKS) {
273
+ error(res, 429, 'Too many phone upload links. Wait for one to expire.');
274
+ return true;
275
+ }
276
+ const token = randomBytes(32).toString('base64url');
277
+ const link: UploadLink = {
278
+ id: randomUUID(), key: digest(token), owner, workflowId: body.workflowId, workflow,
279
+ cwd: workflow.config.workingDirectory!, origin, expiresAt: Date.now() + LINK_TTL_MS,
280
+ files: [], receivedBytes: 0, closed: false, transferring: false, theme: checkedPhoneTheme(body.theme),
281
+ };
282
+ links.set(link.id, link);
283
+ tokens.set(link.key, link);
284
+ json(res, 201, {
285
+ id: link.id, url: origin + PHONE_PATH + '#' + token, expiresAt: link.expiresAt,
286
+ verifiedAt: routeSuccesses([origin])[origin],
287
+ });
288
+ return true;
289
+ }
290
+
291
+ // What the phone page reads with its token: the theme snapshot taken when
292
+ // the code was opened, or one bundled font that theme names. Nothing else.
293
+ async function phoneResource(req: IncomingMessage, res: ServerResponse, origin: string): Promise<void> {
294
+ const token = req.headers['x-arco-phone-upload'];
295
+ if (typeof token !== 'string' || !/^[\w-]{43}$/.test(token)) return error(res, 403, 'Open the upload page from the QR code.');
296
+ const link = tokens.get(digest(token));
297
+ if (!link || !active(link)) return error(res, 410, CLOSED);
298
+ if (link.origin !== origin) return error(res, 403, UNAVAILABLE);
299
+ const fontId = req.headers['x-arco-phone-font'];
300
+ if (fontId === undefined) return json(res, 200, { theme: link.theme ?? null });
301
+ const font = typeof fontId === 'string' ? await bundledPhoneFont(link.theme, fontId) : null;
302
+ if (!font) return error(res, 404, 'Not found.');
303
+ res.writeHead(200, { 'Content-Type': font.type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
304
+ res.end(font.bytes);
305
+ }
306
+
307
+ // This exact path has upload authority only. It is deliberately handled
308
+ // before operator session auth, with the same router Host/Origin precheck.
309
+ export async function tryHandlePhonePage(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
310
+ if (req.url !== PHONE_PATH) return false;
311
+ const origin = privatePhoneOrigin(req);
312
+ if (!origin) error(res, 403, UNAVAILABLE);
313
+ else if (req.method === 'POST') await uploadFromPhone(req, res, origin);
314
+ else if (req.method === 'GET' && req.headers['x-arco-phone-upload'] !== undefined) await phoneResource(req, res, origin);
315
+ else if (req.method === 'GET') {
316
+ res.writeHead(200, {
317
+ 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': PHONE_PAGE_CSP,
318
+ 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Content-Type-Options': 'nosniff',
319
+ });
320
+ res.end(PHONE_PAGE);
321
+ } else error(res, 405, 'Method not allowed.');
322
+ return true;
323
+ }
324
+
325
+ export async function tryHandlePhoneOperator(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
326
+ const path = req.url ?? '';
327
+ if (path !== API_PATH && !path.startsWith(API_PATH + '/')) return false;
328
+ const cookie = readCookie(req, SESSION_COOKIE);
329
+ if (!cookie || !verifyToken(cookie)) {
330
+ error(res, 401, 'Session required.');
331
+ return true;
332
+ }
333
+ const ownerKey = req.headers['x-arco-phone-owner'];
334
+ if (typeof ownerKey !== 'string' || !/^[0-9a-f]{64}$/.test(ownerKey)) {
335
+ error(res, 403, 'Phone upload must be opened from the message box.');
336
+ return true;
337
+ }
338
+ const owner = digest(ownerKey);
339
+ try {
340
+ if (path === API_PATH && req.method === 'POST') {
341
+ purgeLinks();
342
+ const body = JSON.parse((await readAttachmentBody(req, 8192)).toString()) as { workflowId?: string; origin?: string; theme?: unknown };
343
+ const workflow = typeof body?.workflowId === 'string' ? workflows.get(body.workflowId) : undefined;
344
+ if (!body?.workflowId || !targetAvailable(body.workflowId, workflow)) {
345
+ error(res, 409, 'This conversation does not accept attachments.');
346
+ return true;
347
+ }
348
+ let origins = phoneUploadOrigins(req);
349
+ if (!origins.length) {
350
+ openingCodes++;
351
+ try {
352
+ const opened = await temporaryOrigins(req.socket.localPort || PORT);
353
+ if (opened.error) {
354
+ error(res, 503, opened.error);
355
+ return true;
356
+ }
357
+ origins = opened.origins;
358
+ return createLink(res, { workflowId: body.workflowId, origin: body.origin, theme: body.theme }, workflow, owner, origins);
359
+ } finally {
360
+ openingCodes--;
361
+ }
362
+ }
363
+ return createLink(res, { workflowId: body.workflowId, origin: body.origin, theme: body.theme }, workflow, owner, origins);
364
+ }
365
+ const id = path.slice(path.lastIndexOf('/') + 1);
366
+ if (!UUID_PATTERN.test(id)) {
367
+ error(res, 404, 'Phone upload not found.');
368
+ return true;
369
+ }
370
+ if (path === API_PATH + '/draft/' + id) {
371
+ const draft = phoneDraftForOwner(id, owner);
372
+ if (!draft) error(res, 404, 'Phone attachment has expired.');
373
+ else if (req.method === 'DELETE') {
374
+ await discardPhoneDraft(draft);
375
+ json(res, 200, { ok: true });
376
+ } else if (req.method === 'GET') {
377
+ const image = managedUploadPath(await awaitModelImage(draft.path));
378
+ const preview = image ? await readFileForExplorer(image) : null;
379
+ json(res, 200, { preview: preview?.type === 'image' ? preview.dataUrl : undefined });
380
+ } else error(res, 405, 'Method not allowed.');
381
+ return true;
382
+ }
383
+ const link = path === API_PATH + '/' + id ? links.get(id) : undefined;
384
+ if (!link || link.owner !== owner) error(res, 404, 'Phone upload link not found.');
385
+ else if (req.method === 'GET' || req.method === 'DELETE') {
386
+ if (req.method === 'DELETE') closeLink(link);
387
+ const closed = !active(link);
388
+ const files = link.files.filter(file => phoneDraftForOwner(file.fileId, owner))
389
+ .map(({ fileId, filename, path, expiresAt }) => ({ fileId, filename, path, expiresAt }));
390
+ if (req.method === 'DELETE') links.delete(id);
391
+ json(res, 200, { files, closed, verifiedAt: routeSuccesses([link.origin])[link.origin] });
392
+ } else error(res, 405, 'Method not allowed.');
393
+ } catch (e) {
394
+ if (e instanceof UploadTooLarge || e instanceof SyntaxError) error(res, 400, 'Invalid phone upload request.');
395
+ else error(res, 500, 'Phone upload failed.');
396
+ }
397
+ return true;
398
+ }
@@ -0,0 +1,97 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { PROJECT_ROOT } from '../server/constants.js';
4
+
5
+ // The look of the phone upload page: a snapshot of the Arco theme that was
6
+ // active on the computer when the code was opened. Only these fixed values
7
+ // are accepted, each checked against a strict form, so the phone page never
8
+ // receives CSS, HTML or a URL from the browser that sent them. A value that
9
+ // fails its check is dropped and the page keeps its plain default for it.
10
+
11
+ export const PHONE_THEME_COLORS = [
12
+ 'color-bg', 'color-bg-dialog', 'color-fg', 'color-fg-muted', 'color-border',
13
+ 'color-accent-primary', 'color-control-fg', 'color-success', 'color-error',
14
+ ] as const;
15
+ const LENGTHS = ['border-width', 'radius-sm'] as const;
16
+ const FONTS = ['font-display', 'font-body'] as const;
17
+ const GENERIC_FONTS = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-monospace', 'ui-sans-serif', 'ui-serif']);
18
+
19
+ // Fonts that ship inside Arco itself. The phone page may fetch these, and
20
+ // only these, through its own token-checked path. A theme font that the
21
+ // computer loads from the internet falls back to the phone's own fonts.
22
+ const BUNDLED_FONTS: Record<string, { family: string; weight: string; type: string; file: string }> = {
23
+ 'victor-mono-400': { family: 'Victor Mono', weight: '400', type: 'font/otf', file: 'themes/victor-mono/VictorMono-Regular.otf' },
24
+ 'victor-mono-700': { family: 'Victor Mono', weight: '700', type: 'font/otf', file: 'themes/victor-mono/VictorMono-Bold.otf' },
25
+ 'excalifont-400': { family: 'Excalifont', weight: '400', type: 'font/woff2', file: 'themes/excalifont/Excalifont-Regular.woff2' },
26
+ };
27
+
28
+ export interface PhoneTheme {
29
+ vars: Record<string, string>;
30
+ scheme?: 'light' | 'dark';
31
+ fonts: { id: string; family: string; weight: string }[];
32
+ }
33
+
34
+ function color(value: unknown): string | undefined {
35
+ if (typeof value !== 'string') return undefined;
36
+ const m = /^rgba?\((\d{1,3}), (\d{1,3}), (\d{1,3})(?:, (0|1|0?\.\d{1,6}))?\)$/.exec(value);
37
+ return m && [m[1], m[2], m[3]].every(n => Number(n) <= 255) ? value : undefined;
38
+ }
39
+
40
+ function length(value: unknown): string | undefined {
41
+ if (typeof value !== 'string') return undefined;
42
+ const m = /^(\d{1,2}(?:\.\d{1,3})?)px$/.exec(value);
43
+ return m && Number(m[1]) <= 24 ? value : undefined;
44
+ }
45
+
46
+ function families(value: unknown): string[] | undefined {
47
+ if (typeof value !== 'string' || value.length > 240) return undefined;
48
+ const names: string[] = [];
49
+ for (const part of value.split(',').slice(0, 6)) {
50
+ const name = part.trim().replace(/^(['"])(.*)\1$/, '$2');
51
+ if (GENERIC_FONTS.has(name) || /^[A-Za-z0-9][A-Za-z0-9 _-]{0,47}$/.test(name)) names.push(name);
52
+ else return undefined;
53
+ }
54
+ return names.length ? names : undefined;
55
+ }
56
+
57
+ const stack = (names: string[]) => names.map(n => GENERIC_FONTS.has(n) ? n : `"${n}"`).join(', ');
58
+
59
+ /** Keep only the values that pass their checks; undefined when none do. */
60
+ export function checkedPhoneTheme(input: unknown): PhoneTheme | undefined {
61
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return undefined;
62
+ const raw = input as Record<string, unknown>;
63
+ const vars: Record<string, string> = {};
64
+ for (const key of PHONE_THEME_COLORS) {
65
+ const value = color(raw[key]);
66
+ if (value) vars[key] = value;
67
+ }
68
+ for (const key of LENGTHS) {
69
+ const value = length(raw[key]);
70
+ if (value) vars[key] = value;
71
+ }
72
+ const fonts = new Map<string, { id: string; family: string; weight: string }>();
73
+ for (const key of FONTS) {
74
+ const names = families(raw[key]);
75
+ if (!names) continue;
76
+ vars[key] = stack(names);
77
+ // The first family is the one the theme shows; bring it along when it
78
+ // is bundled with Arco.
79
+ for (const [id, font] of Object.entries(BUNDLED_FONTS)) {
80
+ if (font.family === names[0]) fonts.set(id, { id, family: font.family, weight: font.weight });
81
+ }
82
+ }
83
+ const scheme = raw.scheme === 'light' || raw.scheme === 'dark' ? raw.scheme : undefined;
84
+ if (!Object.keys(vars).length && !scheme) return undefined;
85
+ return { vars, ...(scheme ? { scheme } : {}), fonts: [...fonts.values()] };
86
+ }
87
+
88
+ /** The bytes of one bundled font that the theme names, or null. */
89
+ export async function bundledPhoneFont(theme: PhoneTheme | undefined, id: string): Promise<{ type: string; bytes: Buffer } | null> {
90
+ const font = Object.hasOwn(BUNDLED_FONTS, id) ? BUNDLED_FONTS[id] : undefined;
91
+ if (!font || !theme?.fonts.some(f => f.id === id)) return null;
92
+ try {
93
+ return { type: font.type, bytes: await readFile(join(PROJECT_ROOT, 'client', 'dist', font.file)) };
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { promisify } from 'node:util';
5
5
  import { confinedPath, isPathWithin, FileAccessError, safeDirectory } from '../fileAccessPolicy.js';
6
6
  import { worktreesRoot } from '../project/taskWorktree.js';
7
+ import { projectGitEnv } from '../publicProject.js';
7
8
  import { resolveBoundCwd } from './writeConfinement.js';
8
9
 
9
10
  const execFileAsync = promisify(execFile);
@@ -14,8 +15,8 @@ class SelectedWorktreeError extends Error {
14
15
  constructor() { super('The selected worktree is unavailable or is not registered with this tab\'s project. Select a worktree again.'); }
15
16
  }
16
17
 
17
- async function gitOutput(cwd: string, args: string[]): Promise<string> {
18
- const { stdout } = await execFileAsync('git', args, { cwd, encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024 });
18
+ export async function gitOutput(cwd: string, args: string[], signal?: AbortSignal): Promise<string> {
19
+ const { stdout } = await execFileAsync('git', args, { cwd, encoding: 'utf8', timeout: 5000, maxBuffer: 1024 * 1024, env: projectGitEnv(), signal });
19
20
  return stdout;
20
21
  }
21
22
 
@@ -2,11 +2,12 @@ import { readListingSettings } from '../settings.js';
2
2
  import path from 'node:path';
3
3
  import { explorerRoot } from './explorerRoot.js';
4
4
  import { readdir } from 'node:fs/promises';
5
- import { FileAccessError, assertSafePath, confinedPath, createReadAccessContext, type ReadAccessContext } from '../fileAccessPolicy.js';
5
+ import { FileAccessError, assertSafePath, confinedPath, createReadAccessContext, isPathWithin, type ReadAccessContext } from '../fileAccessPolicy.js';
6
6
  import { knownRoots, resolveBoundCwd } from './writeConfinement.js';
7
7
  import { UPLOADS_DIR } from '../server/constants.js';
8
8
  import { SCRATCH_ROOT } from '../media/scratch.js';
9
9
  import { artifactsDir } from '../workers/limits.js';
10
+ import { resolveWorktreeFile } from './browserWorktrees.js';
10
11
 
11
12
  export async function readRoots(cwd?: string | null, workflowId?: string | null): Promise<string[]> {
12
13
  const bound = await resolveBoundCwd(cwd, workflowId);
@@ -31,6 +32,9 @@ export async function resolveBrowserRead(p: string, cwd?: string | null, workflo
31
32
  if (tracked) return tracked;
32
33
  }
33
34
  try { return confinedPath(target, roots, kind); } catch (err) {
35
+ if (kind === 'file' && bound.ok && !roots.some(root => isPathWithin(root, target))) {
36
+ return resolveWorktreeFile(target, bound.cwd, await createReadAccessContext());
37
+ }
34
38
  // Only a missing bare filename can fall back to this bound workflow's
35
39
  // artifacts. Traversal, denied paths and unknown bindings never fall back.
36
40
  if ((err as NodeJS.ErrnoException).code !== 'ENOENT' || kind !== 'file' || !bound.ok || !workflowId
@@ -1,7 +1,8 @@
1
1
  import { localRuntimeStatusService } from '../localRuntimeStatus.js';
2
2
  import { tryHandleHandoffHistoryRoute } from './handoffHistoryRoutes.js';
3
- import { shrinkUploadedImage } from '../uploadImages.js';
4
- import { ensureStorageRoot, UnsafeStorageRootError } from '../storageRoot.js';
3
+ import { UnsafeStorageRootError } from '../storageRoot.js';
4
+ import { readAttachmentBody, storeAttachment } from './attachmentUpload.js';
5
+ import { tryHandlePhoneOperator, tryHandlePhonePage } from './phoneUploadRoutes.js';
5
6
  import { requireProjectBinding } from './projectBinding.js';
6
7
  import { tryHandleStorageRoutes } from './storageRoutes.js';
7
8
  import { tryHandleArchitectureReviewRoutes } from './architectureReviewRoutes.js';
@@ -30,10 +31,10 @@ ClusterPresetMember,ProviderName
30
31
  import { type LlamacppModelDef } from '@arco/shared';
31
32
  import { spawn } from 'child_process';
32
33
  import { chmodSync,writeFileSync } from 'fs';
33
- import { mkdir,readdir,readFile,writeFile } from 'fs/promises';
34
+ import { mkdir,readdir,readFile } from 'fs/promises';
34
35
  import { IncomingMessage,ServerResponse } from 'http';
35
36
  import { homedir,tmpdir } from 'os';
36
- import { basename,extname,join,resolve,sep } from 'path';
37
+ import { extname,join,resolve,sep } from 'path';
37
38
  import { unloadLocalModels } from '../localModels.js';
38
39
  import { getAuthStatus,triggerAuthLogin } from '../auth.js';
39
40
  import { cliSnapshotDir,runCliUpdate,refreshRuntimeVersions,type CliProvider } from '../capabilities.js';
@@ -101,11 +102,8 @@ send
101
102
  import {
102
103
  compareDirectoryNames,
103
104
  PORT,
104
- PROJECT_ROOT,
105
- UPLOAD_IMAGE_EXT,
106
- UPLOADS_DIR
105
+ PROJECT_ROOT
107
106
  } from '../server/constants.js';
108
- import { queueModelImage } from '../providers/attachments.js';
109
107
  import {
110
108
  sessions,
111
109
  workflows
@@ -235,6 +233,7 @@ export async function handleHttpRequest(
235
233
  res.end(JSON.stringify({ error: 'Forbidden origin' }));
236
234
  return;
237
235
  }
236
+ if (await tryHandlePhonePage(req, res)) return;
238
237
  if (guard.origin) {
239
238
  res.setHeader('Access-Control-Allow-Origin', guard.origin);
240
239
  res.setHeader('Vary', 'Origin');
@@ -312,6 +311,7 @@ export async function handleHttpRequest(
312
311
 
313
312
  // Operator routes in their own modules: behind the session gate like every
314
313
  // other /api route (they read or change settings and can call providers).
314
+ if (await tryHandlePhoneOperator(req, res)) return;
315
315
  if (await tryHandleProviderThrottleRoutes(req, res)) return;
316
316
  if (await tryHandleSmartPickupRoutes(req, res)) return;
317
317
  if (await tryHandleTidyRoutes(req, res)) return;
@@ -384,9 +384,7 @@ export async function handleHttpRequest(
384
384
 
385
385
  if (req.url === '/upload' && req.method === 'POST') {
386
386
  try {
387
- const chunks: Buffer[] = [];
388
- for await (const chunk of req) chunks.push(chunk as Buffer);
389
- const body = Buffer.concat(chunks);
387
+ const body = await readAttachmentBody(req);
390
388
  // Reject empty uploads so they cannot produce invalid image blocks in
391
389
  // a worker's persistent history.
392
390
  if (body.length === 0) {
@@ -398,21 +396,9 @@ export async function handleHttpRequest(
398
396
  ? req.headers['x-filename'].trim()
399
397
  : `upload-${Date.now()}`;
400
398
  const contentType = typeof req.headers['content-type'] === 'string' ? req.headers['content-type'].split(';')[0].trim().toLowerCase() : '';
401
- const ext = extname(rawFilename);
402
- const inferredExt = !ext && contentType ? UPLOAD_IMAGE_EXT[contentType] : undefined;
403
- const filename = basename(rawFilename) + (inferredExt ?? '');
404
- const fileId = crypto.randomUUID().slice(0, 8);
405
- const uploadRoot = await ensureStorageRoot(UPLOADS_DIR);
406
- const savePath = join(uploadRoot, `${fileId}-${filename}`);
407
- await writeFile(savePath, body, { flag: 'wx' });
408
- console.log(`[arco] File uploaded: ${filename} -> ${savePath}`);
409
- // Finish upload-only replacement before publishing the stable path.
410
- // Failure retains the original; project files never enter this path.
411
- await shrinkUploadedImage(savePath);
412
- // Other formats still use a separate model-compatible copy.
413
- queueModelImage(savePath);
399
+ const stored = await storeAttachment(body, rawFilename, contentType);
414
400
  res.writeHead(200, { 'Content-Type': 'application/json' });
415
- res.end(JSON.stringify({ fileId, filename, path: savePath }));
401
+ res.end(JSON.stringify(stored));
416
402
  } catch (error) {
417
403
  res.writeHead(500, { 'Content-Type': 'application/json' });
418
404
  const message = error instanceof UnsafeStorageRootError ? error.message : 'Upload failed';
@@ -1893,7 +1879,7 @@ export async function handleHttpRequest(
1893
1879
  res.end(JSON.stringify({ error: retired }));
1894
1880
  return;
1895
1881
  }
1896
- const provider: CliProvider = providerParam === 'codex'
1882
+ const provider: CliProvider = providerParam === 'codex' || providerParam === 'cursor'
1897
1883
  ? providerParam
1898
1884
  : 'claude';
1899
1885
  const result = await runCliUpdate(deps.getCapabilities(), provider);
@@ -100,15 +100,26 @@ export async function resolveBoundCwd(
100
100
  const live = [...workflowCwds.values(), ...[...workflows.values()].map(wf => wf.config.workingDirectory),
101
101
  ...clusterStore.listKnownClusterIds().map(id => clusterStore.getClusterCached(id)?.cwd)];
102
102
  for (const root of live) {
103
- try { if (root && safeDirectory(root) === canonical) return { ok: true, cwd: callerCwd }; } catch { /* protected or stale root */ }
103
+ try { if (root && sameDirectory(canonical, root)) return { ok: true, cwd: callerCwd }; } catch { /* protected or stale root */ }
104
104
  }
105
105
  const roots = await knownRoots();
106
106
  for (const root of roots) {
107
- try { if (safeDirectory(root) === canonical) return { ok: true, cwd: callerCwd }; } catch { /* protected or stale root */ }
107
+ try { if (sameDirectory(canonical, root)) return { ok: true, cwd: callerCwd }; } catch { /* protected or stale root */ }
108
108
  }
109
109
  return { ok: false, reason: 'unknown-cwd' };
110
110
  }
111
111
 
112
+ // Node's JavaScript realpath keeps a Windows 8.3 short name and the letter
113
+ // case as written, while the native resolver (used by the document list)
114
+ // expands both. A known root and a caller cwd that name the same directory in
115
+ // different spellings still match; both sides pass safeDirectory first.
116
+ function sameDirectory(canonical: string, root: string): boolean {
117
+ const other = safeDirectory(root);
118
+ if (other === canonical) return true;
119
+ if (process.platform !== 'win32') return false;
120
+ try { return realpathSync.native(other) === realpathSync.native(canonical); } catch { return false; }
121
+ }
122
+
112
123
  export function boundCwdError(reason: 'none' | 'unknown-workflow' | 'unknown-cwd'): string {
113
124
  switch (reason) {
114
125
  case 'none': return 'cwd or a workflow id with a bound cwd is required';