@myrialabs/clopen 0.4.47 → 0.4.49

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 (390) hide show
  1. package/README.md +11 -11
  2. package/backend/artifacts/project/sources.ts +1 -1
  3. package/backend/auth/auth-service.ts +52 -358
  4. package/backend/auth/onboarding.test.ts +2 -3
  5. package/backend/auth/permissions.test.ts +10 -20
  6. package/backend/auth/permissions.ts +4 -290
  7. package/backend/auth/rate-limiter.test.ts +8 -9
  8. package/backend/auth/rate-limiter.ts +0 -2
  9. package/backend/auth/tokens.ts +1 -8
  10. package/backend/bootstrap.ts +7 -0
  11. package/backend/chat/attachments.test.ts +88 -0
  12. package/backend/chat/attachments.ts +159 -0
  13. package/backend/chat/engine-handoff.test.ts +0 -2
  14. package/backend/chat/message-pages.test.ts +163 -0
  15. package/backend/chat/message-pages.ts +233 -0
  16. package/backend/chat/stream-manager.ts +91 -67
  17. package/backend/chat/turn-answer.test.ts +64 -0
  18. package/backend/chat/turn-answer.ts +125 -0
  19. package/backend/chat-apps/awaiting.test.ts +39 -0
  20. package/backend/chat-apps/awaiting.ts +49 -0
  21. package/backend/chat-apps/conversation.ts +746 -0
  22. package/backend/chat-apps/inbound.ts +324 -0
  23. package/backend/chat-apps/index.ts +309 -0
  24. package/backend/chat-apps/link-events.ts +20 -0
  25. package/backend/chat-apps/media.test.ts +62 -0
  26. package/backend/chat-apps/media.ts +208 -0
  27. package/backend/chat-apps/messages.test.ts +229 -0
  28. package/backend/chat-apps/messages.ts +365 -0
  29. package/backend/chat-apps/outbound.ts +243 -0
  30. package/backend/chat-apps/pairing.test.ts +45 -0
  31. package/backend/chat-apps/pairing.ts +74 -0
  32. package/backend/chat-apps/platforms/index.ts +20 -0
  33. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  34. package/backend/chat-apps/platforms/telegram.ts +191 -0
  35. package/backend/chat-apps/platforms/types.ts +114 -0
  36. package/backend/chat-apps/questions.ts +133 -0
  37. package/backend/chat-apps/runtime.ts +572 -0
  38. package/backend/chat-apps/storage.test.ts +201 -0
  39. package/backend/chat-apps/turns.test.ts +45 -0
  40. package/backend/chat-apps/turns.ts +208 -0
  41. package/backend/containers/pty.ts +3 -11
  42. package/backend/control/actions/accounts.ts +89 -0
  43. package/backend/control/actions/files.ts +116 -0
  44. package/backend/control/actions/models.ts +188 -0
  45. package/backend/control/actions/projects.ts +272 -0
  46. package/backend/control/actions/sessions.ts +280 -0
  47. package/backend/control/actions/skills.ts +111 -0
  48. package/backend/control/control.test.ts +169 -0
  49. package/backend/control/define.ts +20 -0
  50. package/backend/control/folders.test.ts +67 -0
  51. package/backend/control/index.ts +213 -0
  52. package/backend/control/invoke.ts +44 -0
  53. package/backend/control/links.ts +35 -0
  54. package/backend/control/paging.ts +26 -0
  55. package/backend/control/types.ts +117 -0
  56. package/backend/control/workspace.ts +127 -0
  57. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  58. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  59. package/backend/database/migrations/086_single_owner.ts +418 -0
  60. package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
  61. package/backend/database/migrations/index.ts +28 -0
  62. package/backend/database/queries/auth-queries.ts +7 -85
  63. package/backend/database/queries/blob-line-stats-queries.ts +48 -0
  64. package/backend/database/queries/channel-queries.ts +270 -0
  65. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  66. package/backend/database/queries/file-share-queries.ts +5 -23
  67. package/backend/database/queries/git-identity-queries.ts +31 -42
  68. package/backend/database/queries/graph-queries.ts +1 -1
  69. package/backend/database/queries/index.ts +15 -1
  70. package/backend/database/queries/message-queries.test.ts +146 -0
  71. package/backend/database/queries/message-queries.ts +42 -1
  72. package/backend/database/queries/permission-set-queries.ts +1 -1
  73. package/backend/database/queries/profile-queries.ts +1 -1
  74. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  75. package/backend/database/queries/project-queries.ts +50 -63
  76. package/backend/database/queries/session-queries.ts +28 -56
  77. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  78. package/backend/db-client/env/diff.ts +9 -33
  79. package/backend/db-client/env/env.test.ts +8 -8
  80. package/backend/db-client/env/service.ts +1 -1
  81. package/backend/db-client/integrations/projector.ts +0 -5
  82. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  83. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  84. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  85. package/backend/engine/adapters/cline/stream.ts +11 -15
  86. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  87. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  88. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  89. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  90. package/backend/engine/adapters/opencode/stream.ts +11 -0
  91. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  92. package/backend/engine/adapters/parent-scope.ts +44 -0
  93. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  94. package/backend/engine/adapters/pi/stream.ts +4 -5
  95. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  96. package/backend/engine/bootstrap-default-engine.ts +2 -2
  97. package/backend/engine/docs/adapter-contract.md +8 -1
  98. package/backend/engine/install-runner.ts +8 -17
  99. package/backend/files/file-shares.ts +20 -44
  100. package/backend/files/file-size-limit.ts +3 -3
  101. package/backend/files/file-watcher.ts +19 -0
  102. package/backend/files/image-processing.ts +1 -1
  103. package/backend/files/os-clipboard.ts +2 -2
  104. package/backend/git/contributors.test.ts +35 -0
  105. package/backend/git/contributors.ts +46 -0
  106. package/backend/git/git-executor.ts +25 -5
  107. package/backend/git/git-service.ts +420 -19
  108. package/backend/git/identity/credential-helper.test.ts +2 -7
  109. package/backend/git/identity/import-local.test.ts +11 -16
  110. package/backend/git/identity/import-local.ts +12 -12
  111. package/backend/git/identity/index.ts +10 -24
  112. package/backend/git/identity/resolve.ts +13 -14
  113. package/backend/git/identity/scope-config.ts +33 -28
  114. package/backend/git/identity/service.ts +44 -47
  115. package/backend/git/op-lock.test.ts +111 -0
  116. package/backend/git/op-lock.ts +180 -0
  117. package/backend/git/remote-sync.test.ts +249 -0
  118. package/backend/host/metrics.ts +1 -1
  119. package/backend/http/bearer-auth.ts +1 -2
  120. package/backend/http/files-download.test.ts +8 -9
  121. package/backend/http/files-download.ts +2 -2
  122. package/backend/http/files-shared.test.ts +62 -89
  123. package/backend/http/files-shared.ts +2 -2
  124. package/backend/http/files-upload.test.ts +3 -7
  125. package/backend/http/files-upload.ts +3 -3
  126. package/backend/http/notes-images.test.ts +15 -38
  127. package/backend/http/notes-images.ts +6 -8
  128. package/backend/http/ssh-sftp.ts +5 -10
  129. package/backend/http/static-assets.test.ts +78 -0
  130. package/backend/http/static-assets.ts +104 -0
  131. package/backend/index.ts +32 -16
  132. package/backend/integrations/accounts.ts +61 -3
  133. package/backend/integrations/index.ts +2 -2
  134. package/backend/integrations/registry/define.ts +15 -0
  135. package/backend/integrations/registry/index.ts +2 -0
  136. package/backend/integrations/registry/providers/telegram.ts +54 -0
  137. package/backend/integrations/registry/types.ts +21 -1
  138. package/backend/integrations/webhooks/gateway.ts +7 -6
  139. package/backend/integrations/webhooks/verify.test.ts +30 -0
  140. package/backend/integrations/webhooks/verify.ts +4 -0
  141. package/backend/mcp/external/project.ts +1 -1
  142. package/backend/mcp/internal/remote-server.test.ts +1 -3
  143. package/backend/mcp/internal/remote-server.ts +4 -4
  144. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  145. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  146. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  147. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  148. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  149. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  150. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  151. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  152. package/backend/memory/redact.ts +1 -1
  153. package/backend/notes/access.test.ts +28 -29
  154. package/backend/notes/access.ts +6 -11
  155. package/backend/permissions/service.ts +1 -1
  156. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  157. package/backend/preview/browser/browser-clipboard.ts +67 -0
  158. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  159. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  160. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  161. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  162. package/backend/preview/browser/browser-pool.ts +67 -6
  163. package/backend/preview/browser/browser-preview-service.ts +383 -29
  164. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  165. package/backend/preview/browser/browser-video-capture.ts +92 -5
  166. package/backend/preview/browser/element-locator.ts +190 -17
  167. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  168. package/backend/preview/browser/keyboard-chords.ts +132 -0
  169. package/backend/preview/browser/paste.ts +81 -0
  170. package/backend/preview/browser/process-usage.ts +142 -0
  171. package/backend/preview/browser/profile-lock.ts +209 -0
  172. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  173. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  174. package/backend/preview/browser/types.ts +40 -2
  175. package/backend/preview/browser/viewport.test.ts +45 -0
  176. package/backend/preview/browser/viewport.ts +96 -0
  177. package/backend/profiles/service.ts +2 -2
  178. package/backend/project/status-manager.ts +43 -172
  179. package/backend/projects/home.ts +61 -0
  180. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  181. package/backend/projects/project-cleanup.ts +0 -8
  182. package/backend/skills/service.ts +2 -3
  183. package/backend/snapshot/blob-store.ts +9 -1
  184. package/backend/snapshot/helpers.ts +3 -11
  185. package/backend/snapshot/line-stats.test.ts +80 -0
  186. package/backend/snapshot/line-stats.ts +64 -0
  187. package/backend/snapshot/restore.ts +252 -0
  188. package/backend/snapshot/snapshot-service.ts +14 -27
  189. package/backend/snapshot/turn-changes.test.ts +10 -5
  190. package/backend/snapshot/turn-changes.ts +78 -40
  191. package/backend/ssh/ptykit.ts +1 -2
  192. package/backend/terminal/ptykit.ts +10 -8
  193. package/backend/tunnel/public-origin.ts +31 -20
  194. package/backend/utils/user-helpers.ts +0 -55
  195. package/backend/utils/ws-wire.test.ts +87 -0
  196. package/backend/utils/ws-wire.ts +189 -0
  197. package/backend/utils/ws.ts +101 -192
  198. package/backend/worktrees/branching/engine.ts +3 -16
  199. package/backend/worktrees/branching/index.ts +1 -1
  200. package/backend/worktrees/branching/projector.ts +1 -1
  201. package/backend/worktrees/branching/service.ts +13 -25
  202. package/backend/ws/access.ts +12 -21
  203. package/backend/ws/artifacts/generate.ts +2 -2
  204. package/backend/ws/auth/device.ts +16 -71
  205. package/backend/ws/auth/index.ts +4 -22
  206. package/backend/ws/auth/login.test.ts +14 -60
  207. package/backend/ws/auth/login.ts +24 -124
  208. package/backend/ws/auth/status.ts +0 -1
  209. package/backend/ws/chat/composer.ts +118 -118
  210. package/backend/ws/chat/stream.ts +105 -57
  211. package/backend/ws/chat-apps/index.ts +117 -0
  212. package/backend/ws/containers/actions.ts +11 -25
  213. package/backend/ws/containers/index.ts +3 -4
  214. package/backend/ws/containers/list.ts +10 -36
  215. package/backend/ws/containers/logs.ts +2 -2
  216. package/backend/ws/containers/tunnel.ts +1 -2
  217. package/backend/ws/db-client/access.ts +2 -16
  218. package/backend/ws/db-client/accounts.ts +5 -15
  219. package/backend/ws/db-client/connections.ts +17 -25
  220. package/backend/ws/db-client/context.ts +1 -1
  221. package/backend/ws/db-client/env.ts +7 -10
  222. package/backend/ws/db-client/index.ts +2 -2
  223. package/backend/ws/db-client/io.ts +5 -5
  224. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  225. package/backend/ws/db-client/query.ts +18 -17
  226. package/backend/ws/db-client/schema.ts +13 -13
  227. package/backend/ws/db-client/structure.ts +35 -35
  228. package/backend/ws/db-client/supabase.ts +4 -21
  229. package/backend/ws/deployments/context.ts +1 -1
  230. package/backend/ws/deployments/crud.ts +0 -5
  231. package/backend/ws/engine/access.ts +7 -20
  232. package/backend/ws/engine/claude/accounts.ts +4 -4
  233. package/backend/ws/engine/cline/accounts.ts +5 -5
  234. package/backend/ws/engine/codex/accounts.ts +3 -3
  235. package/backend/ws/engine/pi/accounts.ts +5 -5
  236. package/backend/ws/files/clipboard.ts +8 -27
  237. package/backend/ws/files/image-edit.ts +6 -6
  238. package/backend/ws/files/index.ts +1 -1
  239. package/backend/ws/files/path-access.test.ts +32 -131
  240. package/backend/ws/files/path-access.ts +8 -87
  241. package/backend/ws/files/read.ts +45 -19
  242. package/backend/ws/files/reveal.ts +3 -3
  243. package/backend/ws/files/search.ts +7 -7
  244. package/backend/ws/files/share.ts +9 -13
  245. package/backend/ws/files/state.ts +9 -12
  246. package/backend/ws/files/watch.ts +3 -3
  247. package/backend/ws/files/write.ts +30 -31
  248. package/backend/ws/git/branch.ts +80 -59
  249. package/backend/ws/git/commit.ts +63 -44
  250. package/backend/ws/git/conflict.ts +16 -18
  251. package/backend/ws/git/identity-context.ts +8 -17
  252. package/backend/ws/git/identity.ts +17 -27
  253. package/backend/ws/git/index.ts +3 -1
  254. package/backend/ws/git/log.ts +52 -0
  255. package/backend/ws/git/op-state.ts +139 -0
  256. package/backend/ws/git/remote.ts +241 -141
  257. package/backend/ws/git/repo-context.ts +67 -0
  258. package/backend/ws/git/staging.ts +18 -28
  259. package/backend/ws/git/status.ts +5 -2
  260. package/backend/ws/index.ts +5 -1
  261. package/backend/ws/instructions/crud.ts +1 -1
  262. package/backend/ws/integrations/crud.ts +1 -3
  263. package/backend/ws/mcp/crud.ts +3 -5
  264. package/backend/ws/mcp/tools.ts +1 -1
  265. package/backend/ws/memory/crud.ts +14 -46
  266. package/backend/ws/memory/index.ts +2 -2
  267. package/backend/ws/messages/crud.ts +78 -8
  268. package/backend/ws/notes/index.ts +33 -39
  269. package/backend/ws/permissions/crud.ts +3 -4
  270. package/backend/ws/ports/index.ts +1 -2
  271. package/backend/ws/ports/kill.ts +5 -10
  272. package/backend/ws/ports/list.ts +4 -10
  273. package/backend/ws/preview/access.ts +1 -1
  274. package/backend/ws/preview/browser/interact.ts +52 -79
  275. package/backend/ws/preview/browser/native-ui.ts +24 -0
  276. package/backend/ws/preview/browser/stats.ts +98 -1
  277. package/backend/ws/preview/browser/tab-info.ts +15 -0
  278. package/backend/ws/preview/browser/tab.ts +19 -4
  279. package/backend/ws/preview/index.ts +29 -0
  280. package/backend/ws/preview/watchers.ts +84 -0
  281. package/backend/ws/profiles/crud.ts +6 -8
  282. package/backend/ws/project-artifacts/index.ts +30 -31
  283. package/backend/ws/projects/crud.ts +33 -35
  284. package/backend/ws/projects/index.ts +3 -8
  285. package/backend/ws/projects/info.ts +3 -3
  286. package/backend/ws/projects/overview.ts +19 -30
  287. package/backend/ws/projects/status.ts +17 -57
  288. package/backend/ws/sessions/crud.ts +42 -57
  289. package/backend/ws/sessions/index.ts +1 -1
  290. package/backend/ws/settings/crud.ts +1 -1
  291. package/backend/ws/skills/crud.ts +3 -4
  292. package/backend/ws/skills/index.ts +1 -1
  293. package/backend/ws/snapshot/changes.ts +12 -13
  294. package/backend/ws/snapshot/restore.ts +11 -295
  295. package/backend/ws/snapshot/timeline.ts +2 -4
  296. package/backend/ws/ssh/access.ts +6 -21
  297. package/backend/ws/ssh/connections.ts +21 -31
  298. package/backend/ws/ssh/forwards.ts +12 -12
  299. package/backend/ws/ssh/sftp.ts +34 -34
  300. package/backend/ws/ssh/tunnel.ts +1 -2
  301. package/backend/ws/stack/install.ts +7 -17
  302. package/backend/ws/subagents/crud.ts +1 -1
  303. package/backend/ws/terminal/tunnel.ts +2 -2
  304. package/backend/ws/tunnel/share.ts +0 -2
  305. package/backend/ws/user/crud.ts +1 -59
  306. package/backend/ws/user/index.ts +1 -1
  307. package/backend/ws/work/context.ts +1 -1
  308. package/backend/ws/work/crud.ts +0 -5
  309. package/backend/ws/workspace/state.ts +10 -13
  310. package/backend/ws/worktrees/branching.ts +7 -36
  311. package/backend/ws/worktrees/crud.ts +2 -2
  312. package/bin/clopen.ts +46 -41
  313. package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
  314. package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
  315. package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
  316. package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
  317. package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
  318. package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
  319. package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
  320. package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
  321. package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
  322. package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
  323. package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
  324. package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
  325. package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
  326. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
  327. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
  328. package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
  329. package/dist/assets/index-CrVWZH_D.js.br +0 -0
  330. package/dist/assets/index-CrVWZH_D.js.gz +0 -0
  331. package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
  332. package/dist/assets/index-DD0-3EWg.js.br +0 -0
  333. package/dist/assets/index-DD0-3EWg.js.gz +0 -0
  334. package/dist/assets/main-D2_TmcwQ.js +1240 -0
  335. package/dist/assets/main-D2_TmcwQ.js.br +0 -0
  336. package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
  337. package/dist/assets/main-Yucigcmf.css +1 -0
  338. package/dist/assets/main-Yucigcmf.css.br +0 -0
  339. package/dist/assets/main-Yucigcmf.css.gz +0 -0
  340. package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
  341. package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
  342. package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
  343. package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
  344. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
  345. package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
  346. package/dist/fonts/dm-sans.css.br +0 -0
  347. package/dist/fonts/dm-sans.css.gz +0 -0
  348. package/dist/index.html +2 -2
  349. package/dist/index.html.br +0 -0
  350. package/dist/index.html.gz +0 -0
  351. package/dist/sw.js.br +0 -0
  352. package/dist/sw.js.gz +0 -0
  353. package/package.json +3 -3
  354. package/shared/constants/attachments.ts +14 -0
  355. package/shared/constants/engine-tools.ts +1 -1
  356. package/shared/constants/preview.test.ts +259 -0
  357. package/shared/constants/preview.ts +1018 -57
  358. package/shared/constants/tool-icons.ts +5 -0
  359. package/shared/types/containers/container.ts +1 -1
  360. package/shared/types/database/schema.ts +9 -6
  361. package/shared/types/git-identity.ts +1 -1
  362. package/shared/types/git.ts +116 -0
  363. package/shared/types/integrations.ts +7 -0
  364. package/shared/types/stores/settings.ts +1 -1
  365. package/shared/types/unified/index.ts +1 -1
  366. package/shared/types/unified/message.ts +0 -7
  367. package/shared/types/unified/stream.ts +13 -5
  368. package/shared/types/unified/tool.ts +15 -1
  369. package/shared/utils/ask-user-question.test.ts +319 -0
  370. package/shared/utils/ask-user-question.ts +154 -0
  371. package/shared/utils/diff-calculator.test.ts +178 -41
  372. package/shared/utils/diff-calculator.ts +383 -100
  373. package/shared/utils/home-project.ts +25 -0
  374. package/shared/utils/logger.ts +2 -0
  375. package/shared/utils/process-supervisor.test.ts +172 -0
  376. package/shared/utils/process-supervisor.ts +251 -0
  377. package/shared/utils/ws-chunk.test.ts +33 -0
  378. package/shared/utils/ws-chunk.ts +73 -0
  379. package/shared/utils/ws-client-chunks.test.ts +45 -0
  380. package/shared/utils/ws-client.ts +43 -0
  381. package/shared/utils/ws-server.ts +49 -21
  382. package/backend/auth/session-invalidation.test.ts +0 -112
  383. package/backend/auth/session-invalidation.ts +0 -77
  384. package/backend/project/status-manager.test.ts +0 -32
  385. package/backend/ws/auth/invites.ts +0 -94
  386. package/backend/ws/auth/users.ts +0 -112
  387. package/backend/ws/projects/presence.ts +0 -46
  388. package/backend/ws/stack/access.ts +0 -31
  389. package/dist/assets/main-BiDNMWb3.css +0 -1
  390. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The account, gateway, storage and Home rules the channel depends on —
3
+ * everything that decides WHICH chat a message is from and WHERE an answer may go,
4
+ * exercised against the real schema rather than a fake.
5
+ */
6
+
7
+ import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'bun:test';
8
+ import { randomUUID } from 'crypto';
9
+ import { existsSync } from 'fs';
10
+
11
+ import { initializeDatabase, closeDatabase, getDatabase } from '$backend/database';
12
+ import {
13
+ authQueries,
14
+ channelMessageQueries,
15
+ integrationAccountQueries,
16
+ channelLinkQueries,
17
+ projectQueries
18
+ } from '$backend/database/queries';
19
+ import { integrationAccounts } from '$backend/integrations/accounts';
20
+ import { handleInboundDelivery, onWebhook, type WebhookEvent } from '$backend/integrations/webhooks/gateway';
21
+ import { ensureHomeProject } from '$backend/projects/home';
22
+
23
+ const owner = `channel-test-${randomUUID()}`;
24
+ const delivered: WebhookEvent[] = [];
25
+
26
+ function createUser(id: string): void {
27
+ authQueries.createUser({
28
+ id,
29
+ name: id,
30
+ color: '#000000',
31
+ avatar: 'CT',
32
+ personal_access_token_hash: `hash-${randomUUID()}`,
33
+ created_at: new Date().toISOString()
34
+ });
35
+ }
36
+
37
+ function clearAccounts(): void {
38
+ for (const account of integrationAccountQueries.getAll()) integrationAccountQueries.remove(account.id);
39
+ }
40
+
41
+ function connectBot(label: string) {
42
+ return integrationAccounts.connect({ provider: 'telegram', label, credentials: { botToken: `123:${label}` } });
43
+ }
44
+
45
+ function secretOf(accountId: string): string {
46
+ return integrationAccountQueries.credentialsOf(integrationAccountQueries.getById(accountId)!).webhookSecret ?? '';
47
+ }
48
+
49
+ function linkFor(accountId: string, conversationId: string, platformUserId = conversationId) {
50
+ return channelLinkQueries.upsert({ accountId, userId: owner, conversationId, platformUserId, displayName: null });
51
+ }
52
+
53
+ function questionRow(linkId: string) {
54
+ return channelMessageQueries.create({
55
+ linkId,
56
+ kind: 'question',
57
+ projectId: 'p',
58
+ chatSessionId: 's',
59
+ toolUseId: 't',
60
+ questionIndex: 0,
61
+ platformMessageId: '10',
62
+ payload: {}
63
+ });
64
+ }
65
+
66
+ beforeAll(async () => {
67
+ await initializeDatabase();
68
+ createUser(owner);
69
+ onWebhook('telegram', (event) => void delivered.push(event));
70
+ });
71
+
72
+ beforeEach(() => {
73
+ clearAccounts();
74
+ delivered.length = 0;
75
+ });
76
+
77
+ afterAll(() => {
78
+ clearAccounts();
79
+ getDatabase().prepare('DELETE FROM users WHERE id = ?').run(owner);
80
+ closeDatabase();
81
+ });
82
+
83
+ describe('a Telegram account', () => {
84
+ it('offers the single control capability, and gets a generated webhook secret the hub never reports', () => {
85
+ const account = connectBot('Bot');
86
+ expect(account.capabilities).toEqual(['control']);
87
+ expect(secretOf(account.id)).toMatch(/^[A-Za-z0-9_-]{40,}$/);
88
+ expect(account.configuredFields).toEqual(['botToken']);
89
+ });
90
+
91
+ it('keeps its secret when the token changes, and ignores a client trying to set it', () => {
92
+ const account = connectBot('Bot');
93
+ const before = secretOf(account.id);
94
+ integrationAccounts.updateCredentials(account.id, { botToken: '123:new', webhookSecret: 'chosen-by-client' });
95
+ expect(secretOf(account.id)).toBe(before);
96
+ });
97
+
98
+ it('ignores a secret supplied at connect time', () => {
99
+ const account = integrationAccounts.connect({ provider: 'telegram', label: 'Bot', credentials: { botToken: '1:a', webhookSecret: 'mine' } });
100
+ expect(secretOf(account.id)).not.toBe('mine');
101
+ });
102
+ });
103
+
104
+ describe('the webhook gateway', () => {
105
+ const withSecret = (secret: string) => new Headers({ 'x-telegram-bot-api-secret-token': secret });
106
+ const body = (updateId: number) => new TextEncoder().encode(`{"update_id":${updateId}}`);
107
+
108
+ it('routes a delivery to the bot whose secret it carries', async () => {
109
+ connectBot('First');
110
+ const second = connectBot('Second');
111
+ const response = await handleInboundDelivery('telegram', body(Date.now()), withSecret(secretOf(second.id)));
112
+ expect(response.status).toBe(200);
113
+ await new Promise((resolve) => setTimeout(resolve, 10));
114
+ expect(delivered.map((event) => event.accountId)).toEqual([second.id]);
115
+ });
116
+
117
+ it('answers 404 for a wrong secret, and for a bot with control switched off', async () => {
118
+ const account = connectBot('On');
119
+ expect((await handleInboundDelivery('telegram', body(Date.now() + 1), withSecret('nope'))).status).toBe(404);
120
+ expect((await handleInboundDelivery('telegram', body(Date.now() + 2), withSecret(secretOf(account.id)))).status).toBe(200);
121
+
122
+ integrationAccounts.setCapabilities(account.id, []);
123
+ expect((await handleInboundDelivery('telegram', body(Date.now() + 3), withSecret(secretOf(account.id)))).status).toBe(404);
124
+ });
125
+ });
126
+
127
+ describe('links and channel messages', () => {
128
+ it('a chat taken over by another platform account closes what the old one could still act on, and forgets where it was', () => {
129
+ const account = connectBot('Bot');
130
+ const link = linkFor(account.id, '777');
131
+ channelLinkQueries.setActive(link.id, 'some-project', 'some-session');
132
+ const row = questionRow(link.id);
133
+
134
+ const moved = linkFor(account.id, '777', 'someone-else');
135
+ expect(moved.id).toBe(link.id);
136
+ expect(moved.platform_user_id).toBe('someone-else');
137
+ expect(moved.active_project_id).toBeNull();
138
+ expect(moved.active_session_id).toBeNull();
139
+ expect(channelMessageQueries.getById(row.id)?.state).toBe('closed');
140
+ });
141
+
142
+ it('can be switched off, and re-pairing switches it back on', () => {
143
+ const account = connectBot('Bot');
144
+ const link = linkFor(account.id, '42');
145
+ expect(channelLinkQueries.isActive(link)).toBe(true);
146
+
147
+ channelLinkQueries.setEnabled(link.id, false);
148
+ expect(channelLinkQueries.isActive(channelLinkQueries.getById(link.id)!)).toBe(false);
149
+
150
+ const again = linkFor(account.id, '42');
151
+ expect(again.id).toBe(link.id);
152
+ expect(again.is_enabled).toBe(1);
153
+ });
154
+
155
+ it('a question settles exactly once', () => {
156
+ const account = connectBot('Bot');
157
+ const link = linkFor(account.id, '1');
158
+ const row = questionRow(link.id);
159
+ expect(channelMessageQueries.settle(row.id, 'answered')).toBe(true);
160
+ expect(channelMessageQueries.settle(row.id, 'closed')).toBe(false);
161
+ expect(channelMessageQueries.openQuestionsForLink(link.id)).toEqual([]);
162
+ });
163
+
164
+ it('a reply finds the newest row for a message, and an edit finds the user message it maps to', () => {
165
+ const account = connectBot('Bot');
166
+ const link = linkFor(account.id, '1');
167
+ channelMessageQueries.create({ linkId: link.id, kind: 'answer', chatSessionId: 's', clopenMessageId: 'old', platformMessageId: '50' });
168
+ channelMessageQueries.create({ linkId: link.id, kind: 'user', chatSessionId: 's', clopenMessageId: 'u1', platformMessageId: '50' });
169
+ expect(channelMessageQueries.getByMessage(link.id, '50')?.kind).toBe('user');
170
+ expect(channelMessageQueries.getUserMessage(link.id, 'u1')?.platform_message_id).toBe('50');
171
+ });
172
+
173
+ it('forgetting a session clears it as the active one everywhere', () => {
174
+ const account = connectBot('Bot');
175
+ const link = linkFor(account.id, '1');
176
+ channelLinkQueries.setActive(link.id, 'p', 'gone');
177
+ channelLinkQueries.clearActiveSession('gone');
178
+ expect(channelLinkQueries.getById(link.id)?.active_session_id).toBeNull();
179
+ expect(channelLinkQueries.getById(link.id)?.active_project_id).toBe('p');
180
+ });
181
+
182
+ it('disconnecting the bot removes its links and their messages', () => {
183
+ const account = connectBot('Bot');
184
+ const link = linkFor(account.id, '1');
185
+ const row = questionRow(link.id);
186
+ integrationAccounts.disconnect(account.id);
187
+ expect(channelLinkQueries.getById(link.id)).toBeNull();
188
+ expect(channelMessageQueries.getById(row.id)).toBeNull();
189
+ });
190
+ });
191
+
192
+ describe('Home', () => {
193
+ it('is one per install, on disk, and in the project list', () => {
194
+ const first = ensureHomeProject();
195
+ const again = ensureHomeProject();
196
+ expect(again.id).toBe(first.id);
197
+ expect(first.kind).toBe('home');
198
+ expect(existsSync(first.path)).toBe(true);
199
+ expect(projectQueries.isListed(first.id)).toBe(true);
200
+ });
201
+ });
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A prompt a chat sent is followed by its own id — a photo with no caption is
3
+ * matched as surely as text, and a message still in the queue can be found
4
+ * again by the chat message that sent it.
5
+ */
6
+
7
+ import { describe, it, expect, afterEach } from 'bun:test';
8
+ import { expectTurn, forgetExpectedTurn, liveTurn, onUserMessage, queuedPromptFor, resetTurns, setExpectedQueueId, takeStoppedByChat, markStoppedByChat } from './turns';
9
+
10
+ const prompt = (promptMessageId: string, platformMessageId: string | null = '100') => ({
11
+ linkId: 'link-1',
12
+ accountId: 'acc',
13
+ conversationId: 'chat',
14
+ projectId: 'p',
15
+ platformMessageId,
16
+ promptMessageId
17
+ });
18
+
19
+ afterEach(() => resetTurns());
20
+
21
+ describe('turns a chat started', () => {
22
+ it('match the saved user message by the prompt id, not its text', () => {
23
+ // No chat message to map (like /retry), so no row is written.
24
+ expectTurn('s1', prompt('prompt-a', null));
25
+ expect(onUserMessage('s1', 'saved-x', 'someone-else')).toBeNull();
26
+ const turn = onUserMessage('s1', 'saved-a', 'prompt-a');
27
+ expect(turn?.promptMessageId).toBe('prompt-a');
28
+ expect(liveTurn('s1')).toBe(turn);
29
+ });
30
+
31
+ it('can be found while queued, and forgotten when sending failed', () => {
32
+ expectTurn('s1', prompt('prompt-b', '200'));
33
+ expect(queuedPromptFor('link-1', '200')).toBeNull();
34
+ setExpectedQueueId('s1', 'prompt-b', 'queue-1');
35
+ expect(queuedPromptFor('link-1', '200')?.prompt.queueId).toBe('queue-1');
36
+ forgetExpectedTurn('s1', 'prompt-b');
37
+ expect(queuedPromptFor('link-1', '200')).toBeNull();
38
+ });
39
+
40
+ it('remember once that this chat stopped the turn', () => {
41
+ markStoppedByChat('s2');
42
+ expect(takeStoppedByChat('s2')).toBe(true);
43
+ expect(takeStoppedByChat('s2')).toBe(false);
44
+ });
45
+ });
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Turns a chat started — the live half of a conversation in a chat app.
3
+ *
4
+ * When a message from a chat becomes a turn, three things must follow it that
5
+ * a turn started in the web UI does not need:
6
+ *
7
+ * - its Clopen user message must be mapped back to the chat message that
8
+ * sent it, so editing that message later can act like Edit Message;
9
+ * - the chat must see that something is happening: "typing…" for as long as
10
+ * the turn runs, and once it has taken a while, one progress line —
11
+ * edited in place, at most every 10 seconds — naming what it is doing;
12
+ * - when it ends, the answer goes back to THAT chat as a reply: it asked.
13
+ *
14
+ * A turn may wait in the composer queue behind another, so a prompt is first
15
+ * EXPECTED and only becomes live when its user message is actually saved —
16
+ * matched by the prompt's own message id, so a message typed in the web UI in
17
+ * between is never mistaken for it, and a photo with no caption is matched as
18
+ * surely as text. In memory: a restart drops the mapping for turns in flight,
19
+ * and their end is then announced like any other run.
20
+ */
21
+
22
+ import { channelMessageQueries } from '$backend/database/queries';
23
+ import { debug } from '$shared/utils/logger';
24
+ import { channelRuntime } from './runtime';
25
+ import { progressCard } from './messages';
26
+
27
+ export interface ExpectedPrompt {
28
+ linkId: string;
29
+ accountId: string;
30
+ conversationId: string;
31
+ projectId: string;
32
+ /** The chat message that sent it — null for /retry, which has no new message. */
33
+ platformMessageId: string | null;
34
+ /** The prompt's message id — what its saved user message carries. */
35
+ promptMessageId: string;
36
+ /** Its place in the composer queue, while it waits there. */
37
+ queueId?: string;
38
+ }
39
+
40
+ export interface LiveTurn extends ExpectedPrompt {
41
+ startedAt: number;
42
+ steps: number;
43
+ activity: string | null;
44
+ progressMessageId: string | null;
45
+ lastProgressAt: number;
46
+ timer: ReturnType<typeof setInterval>;
47
+ }
48
+
49
+ /** Typing lasts about 5 seconds on Telegram; refresh a little sooner. */
50
+ const TICK_MS = 4500;
51
+ /** A turn this short needs no progress line — the answer is the progress. */
52
+ const PROGRESS_AFTER_MS = 15_000;
53
+ /** The progress line is edited at most this often, to stay inside rate limits. */
54
+ const PROGRESS_EVERY_MS = 10_000;
55
+ /** An expected prompt that never started (a queue that was cleared) is forgotten. */
56
+ const EXPECT_TTL_MS = 6 * 60 * 60 * 1000;
57
+
58
+ const expected = new Map<string, Array<ExpectedPrompt & { at: number }>>();
59
+ const live = new Map<string, LiveTurn>();
60
+
61
+ /** Sessions whose running turn this chat asked to stop — its "Stopped" was already said. */
62
+ const stopped = new Set<string>();
63
+
64
+ /** A prompt from a chat is about to run (or queue) in `chatSessionId`. */
65
+ export function expectTurn(chatSessionId: string, prompt: ExpectedPrompt): void {
66
+ const now = Date.now();
67
+ const list = (expected.get(chatSessionId) ?? []).filter((entry) => now - entry.at < EXPECT_TTL_MS);
68
+ list.push({ ...prompt, at: now });
69
+ expected.set(chatSessionId, list);
70
+ }
71
+
72
+ /** Forget an expectation that will not run (submitting it failed). */
73
+ export function forgetExpectedTurn(chatSessionId: string, promptMessageId: string): void {
74
+ const list = expected.get(chatSessionId);
75
+ if (!list) return;
76
+ const index = list.findIndex((entry) => entry.promptMessageId === promptMessageId);
77
+ if (index !== -1) list.splice(index, 1);
78
+ if (list.length === 0) expected.delete(chatSessionId);
79
+ }
80
+
81
+ /** Remember where an expected prompt sits in the queue, so editing it can change it there. */
82
+ export function setExpectedQueueId(chatSessionId: string, promptMessageId: string, queueId: string): void {
83
+ const entry = expected.get(chatSessionId)?.find((item) => item.promptMessageId === promptMessageId);
84
+ if (entry) entry.queueId = queueId;
85
+ }
86
+
87
+ /** A prompt this chat sent that is still waiting in the queue, by the chat message that sent it. */
88
+ export function queuedPromptFor(linkId: string, platformMessageId: string): { chatSessionId: string; prompt: ExpectedPrompt } | null {
89
+ for (const [chatSessionId, list] of expected) {
90
+ const prompt = list.find((entry) => entry.linkId === linkId && entry.platformMessageId === platformMessageId && entry.queueId);
91
+ if (prompt) return { chatSessionId, prompt };
92
+ }
93
+ return null;
94
+ }
95
+
96
+ /**
97
+ * A user message was saved. If a chat expected it, map it and start the
98
+ * turn's live feedback. Returns the turn, or null for a message typed in Clopen.
99
+ */
100
+ export function onUserMessage(chatSessionId: string, clopenMessageId: string, promptMessageId: string): LiveTurn | null {
101
+ const list = expected.get(chatSessionId);
102
+ if (!list?.length) return null;
103
+ const index = list.findIndex((entry) => entry.promptMessageId === promptMessageId);
104
+ if (index === -1) return null;
105
+ const [prompt] = list.splice(index, 1);
106
+ if (list.length === 0) expected.delete(chatSessionId);
107
+
108
+ if (prompt.platformMessageId) {
109
+ try {
110
+ channelMessageQueries.create({
111
+ linkId: prompt.linkId,
112
+ kind: 'user',
113
+ projectId: prompt.projectId,
114
+ chatSessionId,
115
+ clopenMessageId,
116
+ platformMessageId: prompt.platformMessageId,
117
+ state: 'closed'
118
+ });
119
+ } catch (error) {
120
+ debug.warn('chat-apps', 'Mapping a chat message to its Clopen message failed:', error);
121
+ }
122
+ }
123
+
124
+ endLiveTurn(chatSessionId);
125
+ const turn: LiveTurn = {
126
+ ...prompt,
127
+ startedAt: Date.now(),
128
+ steps: 0,
129
+ activity: null,
130
+ progressMessageId: null,
131
+ lastProgressAt: 0,
132
+ timer: setInterval(() => void tick(chatSessionId), TICK_MS)
133
+ };
134
+ turn.timer.unref?.();
135
+ live.set(chatSessionId, turn);
136
+ void channelRuntime.setTyping(turn.accountId, turn.conversationId).catch(() => {});
137
+ return turn;
138
+ }
139
+
140
+ /** The turn is calling a tool — what the progress line names. */
141
+ export function onToolActivity(chatSessionId: string, activity: string): void {
142
+ const turn = live.get(chatSessionId);
143
+ if (!turn) return;
144
+ turn.steps += 1;
145
+ turn.activity = activity;
146
+ }
147
+
148
+ async function tick(chatSessionId: string): Promise<void> {
149
+ const turn = live.get(chatSessionId);
150
+ if (!turn) return;
151
+ // Waiting on the user's answer is not "typing…": the bot is not busy, the user is.
152
+ if (channelMessageQueries.openQuestionsForSession(chatSessionId).length > 0) return;
153
+ await channelRuntime.setTyping(turn.accountId, turn.conversationId).catch(() => {});
154
+
155
+ const now = Date.now();
156
+ const elapsed = now - turn.startedAt;
157
+ if (elapsed < PROGRESS_AFTER_MS || now - turn.lastProgressAt < PROGRESS_EVERY_MS) return;
158
+ turn.lastProgressAt = now;
159
+ const card = progressCard({ elapsedMs: elapsed, activity: turn.activity, steps: turn.steps });
160
+ try {
161
+ if (turn.progressMessageId) {
162
+ await channelRuntime.edit(turn.accountId, turn.conversationId, turn.progressMessageId, card);
163
+ } else {
164
+ const sent = await channelRuntime.send(turn.accountId, turn.conversationId, card);
165
+ // The turn may have ended while this was in flight; its line must not linger.
166
+ if (live.get(chatSessionId) !== turn && sent.platform_message_id) {
167
+ await channelRuntime.deleteMessage(turn.accountId, turn.conversationId, sent.platform_message_id);
168
+ return;
169
+ }
170
+ turn.progressMessageId = sent.platform_message_id;
171
+ }
172
+ } catch (error) {
173
+ debug.log('chat-apps', 'Progress update skipped:', error);
174
+ }
175
+ }
176
+
177
+ /** Stop a turn's feedback. Returns it so the caller can deliver its answer. */
178
+ export function endLiveTurn(chatSessionId: string): LiveTurn | null {
179
+ const turn = live.get(chatSessionId);
180
+ if (!turn) return null;
181
+ clearInterval(turn.timer);
182
+ live.delete(chatSessionId);
183
+ if (turn.progressMessageId) void channelRuntime.deleteMessage(turn.accountId, turn.conversationId, turn.progressMessageId);
184
+ return turn;
185
+ }
186
+
187
+ export function liveTurn(chatSessionId: string): LiveTurn | null {
188
+ return live.get(chatSessionId) ?? null;
189
+ }
190
+
191
+ /** This chat stopped the session's turn itself and has already said so. */
192
+ export function markStoppedByChat(chatSessionId: string): void {
193
+ stopped.add(chatSessionId);
194
+ setTimeout(() => stopped.delete(chatSessionId), 60_000).unref?.();
195
+ }
196
+
197
+ /** Did this chat stop the turn? Asking forgets it. */
198
+ export function takeStoppedByChat(chatSessionId: string): boolean {
199
+ return stopped.delete(chatSessionId);
200
+ }
201
+
202
+ /** Tests and shutdown. */
203
+ export function resetTurns(): void {
204
+ for (const turn of live.values()) clearInterval(turn.timer);
205
+ live.clear();
206
+ expected.clear();
207
+ stopped.clear();
208
+ }
@@ -10,12 +10,8 @@
10
10
  * security design: it is the only statement of intent the client makes,
11
11
  * `authorize` checks it, and the spawn target is derived from it rather than
12
12
  * from anything else in the frame — so a client cannot ask for a container on a
13
- * host it may not reach. It also scopes the collaborative room to one
14
- * container, which is what a second admin opening the same shell should join.
15
- *
16
- * A shell inside a container is usually root inside it and can reach every
17
- * volume that container mounts, so `authorize` requires an admin. Reading the
18
- * list, the detail and the logs stays open to any member.
13
+ * host it may not reach. It also scopes the shared room to one container, which
14
+ * is what a second device opening the same shell should join.
19
15
  */
20
16
 
21
17
  import { PtyKitManager } from '@myrialabs/ptykit/core';
@@ -63,17 +59,13 @@ export const containerPtyKitServer = createPtyKitServer(containerPtyKitManager,
63
59
  room: (ctx) => ctx.namespace,
64
60
  authorize: (ctx) => {
65
61
  const userId = ctx.conn.data.userId;
66
- const isAdmin = ctx.conn.data.isAdmin === true;
67
62
  if (typeof userId !== 'string' || !userId) return false;
68
- // A container shell can do anything the container can, so it is gated the
69
- // same way stopping a port is.
70
- if (!isAdmin) return false;
71
63
 
72
64
  const target = targetFromNamespace(ctx.namespace);
73
65
  if (!target) return false;
74
66
  if (target.hostId === LOCAL_HOST_ID) return true;
75
67
 
76
- return sshConnectionQueries.getForUser(target.hostId, userId, isAdmin) !== null;
68
+ return sshConnectionQueries.get(target.hostId) !== null;
77
69
  }
78
70
  });
79
71
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Engine accounts — which account each engine signs in with.
3
+ *
4
+ * Every call goes through the engine's own account routes, so switching here
5
+ * does exactly what switching in Settings → Engines does (credential files,
6
+ * hot reload, the lot). Accounts are ADDED in Clopen only: a key or a sign-in
7
+ * never goes through a chat.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import type { EngineType } from '$shared/types/unified';
12
+ import { ENGINES } from '$shared/constants/engines';
13
+ import { sessionQueries } from '$backend/database/queries';
14
+ import { defineAction } from '../define';
15
+ import { accessibleSession } from '../workspace';
16
+ import { engineName, parseEngine } from './models';
17
+ import { escapeMd } from './projects';
18
+
19
+ interface AccountRow {
20
+ id: number;
21
+ name: string;
22
+ isActive: boolean;
23
+ }
24
+
25
+ /** The route-name slug an engine's account routes use. */
26
+ function accountSlug(engine: EngineType): string {
27
+ return engine === 'claude-code' ? 'claude' : engine;
28
+ }
29
+
30
+ async function accountsOf(call: <T>(action: string, data?: Record<string, unknown>) => Promise<T>, engine: EngineType): Promise<Array<AccountRow & { provider?: string }>> {
31
+ if (engine === 'opencode') {
32
+ const { providers } = await call<{ providers: Array<{ name: string; isEnabled: boolean; accounts: AccountRow[] }> }>('engine:opencode-providers-list');
33
+ return providers.filter((provider) => provider.isEnabled).flatMap((provider) => provider.accounts.map((account) => ({ ...account, provider: provider.name })));
34
+ }
35
+ const { accounts } = await call<{ accounts: AccountRow[] }>(`engine:${accountSlug(engine)}-accounts-list`);
36
+ return accounts;
37
+ }
38
+
39
+ export const listAccounts = defineAction({
40
+ id: 'accounts.list',
41
+ group: 'accounts',
42
+ title: 'Engine accounts',
43
+ description: 'Switch an engine account',
44
+ args: t.Object({ engine: t.Optional(t.String()) }),
45
+ command: { name: 'accounts', argument: { keys: ['engine'], hint: '[engine]' } },
46
+ async run(ctx, args) {
47
+ const engine = parseEngine(args.engine);
48
+ if (!engine) {
49
+ return {
50
+ text: '**🔑 Accounts for which engine?**',
51
+ choices: ENGINES.map((info) => ({ label: info.name, action: 'accounts.list', args: { engine: info.type } }))
52
+ };
53
+ }
54
+ const accounts = await accountsOf(ctx.call, engine);
55
+ const hint = '\n\nAdd accounts in Clopen → Settings → Engines.';
56
+ if (accounts.length === 0) return { text: `No ${engineName(engine)} accounts yet.${hint}` };
57
+ return {
58
+ text: `**🔑 ${engineName(engine)} accounts**${hint}`,
59
+ choices: accounts.map((account) => ({
60
+ label: account.name,
61
+ detail: account.provider,
62
+ current: account.isActive,
63
+ action: 'accounts.switch',
64
+ args: { engine, accountId: account.id }
65
+ }))
66
+ };
67
+ }
68
+ });
69
+
70
+ export const switchAccount = defineAction({
71
+ id: 'accounts.switch',
72
+ group: 'accounts',
73
+ title: 'Switch account',
74
+ description: 'Make an account the one an engine signs in with, for the current session too.',
75
+ args: t.Object({ engine: t.String({ minLength: 1 }), accountId: t.Number() }),
76
+ async run(ctx, args) {
77
+ const engine = parseEngine(args.engine);
78
+ if (!engine) throw new Error(`No engine called "${args.engine}".`);
79
+ const accounts = await accountsOf(ctx.call, engine);
80
+ const account = accounts.find((row) => row.id === args.accountId);
81
+ if (!account) throw new Error('That account no longer exists.');
82
+ if (engine === 'opencode') await ctx.call('engine:opencode-account-switch', { accountId: account.id });
83
+ else await ctx.call(`engine:${accountSlug(engine)}-accounts-switch`, { id: account.id });
84
+ // The session pins an account of its own; follow the switch when it runs on this engine.
85
+ const found = accessibleSession(ctx.target.sessionId);
86
+ if (found?.session.engine === engine) sessionQueries.updateAccount(found.session.id, account.id, account.name);
87
+ return { text: `🔑 ${engineName(engine)} now signs in as **${escapeMd(account.name)}**.` };
88
+ }
89
+ });