@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
@@ -24,6 +24,7 @@ import {
24
24
  } from '$shared/constants/notification-messages';
25
25
  import { requireSessionAccess } from '../access';
26
26
  import { resolveSessionPath } from '../../worktrees';
27
+ import { normalizeAttachments } from '../../chat/attachments';
27
28
 
28
29
  /**
29
30
  * Where a notification-worthy event happened, resolved once on the server.
@@ -49,14 +50,25 @@ function resolveNotificationContext(
49
50
  }
50
51
 
51
52
  /**
52
- * Broadcast presence + notify project members when a chat message may flip the
53
+ * Where tapping a notification lands: the session it is about, through the
54
+ * `#session/<project>/<session>` route, instead of whatever was open last.
55
+ */
56
+ function sessionLinkPath(projectId: string, chatSessionId: string): string {
57
+ return `/#session/${encodeURIComponent(projectId)}/${encodeURIComponent(chatSessionId)}`;
58
+ }
59
+
60
+ /**
61
+ * Broadcast presence + notify every device when a chat message may flip the
53
62
  * stream's waiting-for-input state (an AskUserQuestion tool_use arrives, or a
54
63
  * tool_result answers it). `event.data.message` IS the UnifiedMessage, so its
55
64
  * blocks live at `.content` — reading `.message.content` (one level too deep)
56
65
  * silently yields `[]` and the status indicators never update until refresh.
57
66
  *
58
- * Shared by the initial-stream and reconnect message handlers so the two paths
59
- * cannot drift apart again.
67
+ * Driven by the stream manager's global `stream:message`, NOT by the per-room
68
+ * bridge. A bridge lives only as long as the connection that opened it, so a
69
+ * question arriving after the user closed the tab used to reach nobody — no
70
+ * presence, no push — which is exactly when a notification matters. It also
71
+ * fired once per attached tab; the global event fires once per message.
60
72
  */
61
73
  function handleWaitingInputChange(
62
74
  event: StreamEvent,
@@ -65,6 +77,7 @@ function handleWaitingInputChange(
65
77
  ): void {
66
78
  const message = event.data?.message;
67
79
  const msgContent = Array.isArray(message?.content) ? message.content : [];
80
+ if (!projectId) return;
68
81
 
69
82
  const askToolUse = msgContent.find(
70
83
  (item: any) => item.type === 'tool_use' && item.name === 'AskUserQuestion'
@@ -79,11 +92,11 @@ function handleWaitingInputChange(
79
92
  });
80
93
  }
81
94
 
82
- // Notify all project members when AskUserQuestion arrives (sound + push)
83
- if (askToolUse && projectId) {
95
+ // Notify every device when AskUserQuestion arrives (sound + push)
96
+ if (askToolUse) {
84
97
  const context = resolveNotificationContext(projectId, chatSessionId);
85
98
 
86
- ws.emit.projectMembers(projectId, 'chat:waiting-input', {
99
+ ws.emit.signedIn('chat:waiting-input', {
87
100
  projectId,
88
101
  chatSessionId,
89
102
  toolUseId: askToolUse.id,
@@ -101,7 +114,8 @@ function handleWaitingInputChange(
101
114
  if (requestedByUserId) {
102
115
  void sendPushToUser(requestedByUserId, {
103
116
  ...chatNotificationMessage('waiting-input', context),
104
- tag: waitingInputPushTag(askToolUse.id)
117
+ tag: waitingInputPushTag(askToolUse.id),
118
+ url: sessionLinkPath(projectId, chatSessionId)
105
119
  }).catch((error) => {
106
120
  debug.warn('notification', 'Background waiting-input push failed:', error);
107
121
  });
@@ -109,6 +123,14 @@ function handleWaitingInputChange(
109
123
  }
110
124
  }
111
125
 
126
+ streamManager.on('stream:message', (payload: { event: StreamEvent; chatSessionId: string; projectId?: string }) => {
127
+ try {
128
+ handleWaitingInputChange(payload.event, payload.chatSessionId, payload.projectId);
129
+ } catch (err) {
130
+ debug.error('chat', 'Waiting-input handling failed:', err);
131
+ }
132
+ });
133
+
112
134
  // ============================================================================
113
135
  // Global stream lifecycle handler (module-level, not per-connection)
114
136
  //
@@ -136,8 +158,8 @@ streamManager.on('stream:lifecycle', (event: { status: string; streamId: string;
136
158
  // two copies of one event cannot word themselves differently.
137
159
  const context = resolveNotificationContext(projectId, chatSessionId);
138
160
 
139
- // Notify all project members (cross-project notification for sound + push)
140
- ws.emit.projectMembers(projectId, 'chat:stream-finished', {
161
+ // Notify every device (cross-project notification for sound + push)
162
+ ws.emit.signedIn('chat:stream-finished', {
141
163
  projectId,
142
164
  chatSessionId: chatSessionId || '',
143
165
  streamId,
@@ -158,7 +180,8 @@ streamManager.on('stream:lifecycle', (event: { status: string; streamId: string;
158
180
  status === 'error' ? 'error' : status === 'cancelled' ? 'cancelled' : 'completed';
159
181
  void sendPushToUser(requestedByUserId, {
160
182
  ...chatNotificationMessage(notificationEvent, context),
161
- tag: chatStreamPushTag(streamId)
183
+ tag: chatStreamPushTag(streamId),
184
+ ...(chatSessionId ? { url: sessionLinkPath(projectId, chatSessionId) } : {})
162
185
  }).catch((error) => {
163
186
  debug.warn('notification', 'Background stream-finished push failed:', error);
164
187
  });
@@ -170,12 +193,12 @@ streamManager.on('stream:lifecycle', (event: { status: string; streamId: string;
170
193
  });
171
194
  });
172
195
 
173
- // Notify project members when a snapshot is captured (so the timeline modal can refresh stats)
196
+ // Notify every device when a snapshot is captured (so the timeline modal can refresh stats)
174
197
  streamManager.on('snapshot:captured', (event: { projectId: string; chatSessionId: string }) => {
175
198
  const { projectId, chatSessionId } = event;
176
199
  if (!projectId) return;
177
200
 
178
- ws.emit.projectMembers(projectId, 'snapshot:captured', { projectId, chatSessionId });
201
+ ws.emit.signedIn('snapshot:captured', { projectId, chatSessionId });
179
202
  });
180
203
 
181
204
  // In-memory store for model state per chat session (keyed by chatSessionId)
@@ -184,20 +207,31 @@ const chatSessionModelState = new Map<string, { engine: string; provider: string
184
207
  // In-memory store for account state per chat session (keyed by chatSessionId)
185
208
  const chatSessionAccountState = new Map<string, { accountId: number | null; senderId: string }>();
186
209
 
210
+ /** Streams currently forwarded to their room — at most one bridge each. */
211
+ const roomBridges = new Map<string, () => void>();
212
+
187
213
  /**
188
214
  * Forward one stream's events to its chat session room until the stream ends.
189
215
  *
190
216
  * Every path that attaches a stream to the room goes through here — the
191
217
  * sender's own request, a client re-attaching after a refresh, and a queued
192
218
  * message the server starts on its own — so the event wire format exists once.
193
- * Returns the unsubscribe; a terminal event unsubscribes by itself.
219
+ *
220
+ * Idempotent per stream, and not tied to any connection. A bridge emits to the
221
+ * whole room, so one is all a room ever needs: every client that re-attached
222
+ * used to add its own, and each frame then reached every device once per
223
+ * bridge (the client dropped the copies by `seq`, the bandwidth was spent).
224
+ * Tying a bridge to its connection had the opposite failure: when the sender's
225
+ * tab closed, its bridge went with it and the other devices still in the room
226
+ * stopped receiving the turn. It lives until the stream's terminal event.
194
227
  */
195
228
  export function bridgeStreamToRoom(
196
229
  streamId: string,
197
230
  chatSessionId: string,
198
231
  projectId: string | undefined,
199
232
  options: { presenceOnConnection?: boolean } = {}
200
- ): () => void {
233
+ ): void {
234
+ if (roomBridges.has(streamId)) return;
201
235
  const { presenceOnConnection = true } = options;
202
236
 
203
237
  const handleStreamEvent = (event: StreamEvent) => {
@@ -226,13 +260,11 @@ export function bridgeStreamToRoom(
226
260
  timestamp: event.data.timestamp,
227
261
  message_id: event.data.message_id,
228
262
  parent_message_id: event.data.parent_message_id,
229
- sender_id: event.data.sender_id,
230
- sender_name: event.data.sender_name,
231
263
  engine: event.data.engine,
232
264
  seq: event.seq
233
265
  });
234
- // Broadcast presence + notify when waiting-input state may change
235
- handleWaitingInputChange(event, chatSessionId, projectId);
266
+ // Waiting-input presence and notifications are handled once per
267
+ // message by the global `stream:message` listener above.
236
268
  break;
237
269
  }
238
270
 
@@ -241,7 +273,9 @@ export function bridgeStreamToRoom(
241
273
  chatSessionId,
242
274
  processId: event.processId,
243
275
  eventType: event.data.eventType as any,
244
- partialText: event.data.partialText || '',
276
+ block: event.data.block ?? 0,
277
+ ...(typeof event.data.offset === 'number' && { offset: event.data.offset }),
278
+ ...(typeof event.data.partialText === 'string' && { partialText: event.data.partialText }),
245
279
  deltaText: event.data.deltaText || '',
246
280
  ...(event.data.reasoning && { reasoning: true }),
247
281
  timestamp: event.data.timestamp,
@@ -314,8 +348,17 @@ export function bridgeStreamToRoom(
314
348
  }
315
349
  };
316
350
 
317
- const unsubscribe = streamManager.subscribeToStream(streamId, handleStreamEvent);
318
- return unsubscribe;
351
+ const stopForwarding = streamManager.subscribeToStream(streamId, handleStreamEvent);
352
+ const unsubscribe = () => {
353
+ stopForwarding();
354
+ roomBridges.delete(streamId);
355
+ };
356
+ roomBridges.set(streamId, unsubscribe);
357
+
358
+ // A stream that ended before it was bridged will never send the terminal
359
+ // event that removes the bridge.
360
+ const status = streamManager.getStream(streamId)?.status;
361
+ if (status && status !== 'active') unsubscribe();
319
362
  }
320
363
 
321
364
  /**
@@ -336,12 +379,15 @@ export async function startChatStream(request: StreamRequest): Promise<string |
336
379
  workingRoot
337
380
  });
338
381
 
339
- const streamId = await streamManager.startStream({ ...request, projectPath: workingRoot });
382
+ // One attachment rule for the web and every chat app: what the model
383
+ // reads inline stays inline, anything else is saved and named.
384
+ const prepared = await normalizeAttachments(request, workingRoot);
385
+ const streamId = await streamManager.startStream({ ...prepared, projectPath: workingRoot });
340
386
  debug.log('chat', 'Stream started with ID:', streamId);
341
387
 
342
388
  // The connection event from startStream() fires before anyone subscribes,
343
389
  // so it is announced here. The user message reaches the room through the
344
- // bridge (it carries resume, sender info and the saved message id).
390
+ // bridge (it carries resume and the saved message id).
345
391
  const stream = streamManager.getStream(streamId);
346
392
  if (stream) {
347
393
  ws.emit.chatSession(request.chatSessionId, 'chat:connection', {
@@ -377,7 +423,7 @@ export const streamHandler = createRouter()
377
423
  chatSessionId: t.String()
378
424
  })
379
425
  }, ({ data, conn }) => {
380
- requireSessionAccess(conn, data.chatSessionId);
426
+ requireSessionAccess(data.chatSessionId);
381
427
  // Leave all previous chat sessions first (1 session at a time per connection)
382
428
  ws.leaveAllChatSessions(conn);
383
429
  ws.joinChatSession(conn, data.chatSessionId);
@@ -466,10 +512,6 @@ export const streamHandler = createRouter()
466
512
  name: t.String()
467
513
  })
468
514
  }),
469
- sender: t.Object({
470
- id: t.String(),
471
- name: t.String()
472
- }),
473
515
  // Active Profile for this session (null = explicit none; absent = use
474
516
  // the project default). Persisted like engine/model.
475
517
  profileId: t.Optional(t.Union([t.Number(), t.Null()])),
@@ -478,11 +520,11 @@ export const streamHandler = createRouter()
478
520
  reasoningEffort: t.Optional(t.Union([t.String(), t.Null()]))
479
521
  })
480
522
  }, async ({ data, conn }) => {
481
- requireSessionAccess(conn, data.chatSessionId);
523
+ requireSessionAccess(data.chatSessionId);
482
524
  const projectId = ws.getProjectId(conn);
483
525
 
484
- // The WS user id is server-trusted (unlike the client-supplied sender)
485
- // and routes background Web Push to the requester's devices. Missing
526
+ // The WS user id is server-trusted and routes background Web Push to
527
+ // the requester's devices. Missing
486
528
  // context must not break the stream — push is best-effort.
487
529
  let requestedByUserId: string | undefined;
488
530
  try {
@@ -497,16 +539,14 @@ export const streamHandler = createRouter()
497
539
  chatSessionId: data.chatSessionId,
498
540
  prompt: data.prompt,
499
541
  engine: data.engine,
500
- sender: data.sender,
501
542
  profileId: data.profileId,
502
543
  reasoningEffort: data.reasoningEffort,
503
544
  requestedByUserId
504
545
  });
505
546
  if (!streamId) return;
506
547
 
507
- // Tied to this connection: it closes with the connection, and the
508
- // client's reconnect builds a new one.
509
- ws.addCleanup(conn, bridgeStreamToRoom(streamId, data.chatSessionId, projectId));
548
+ // One bridge per stream, living until the stream ends — see bridgeStreamToRoom.
549
+ bridgeStreamToRoom(streamId, data.chatSessionId, projectId);
510
550
  })
511
551
 
512
552
  // Reconnect to an active stream (after browser refresh / project switch)
@@ -516,7 +556,7 @@ export const streamHandler = createRouter()
516
556
  chatSessionId: t.String()
517
557
  })
518
558
  }, async ({ data, conn }) => {
519
- requireSessionAccess(conn, data.chatSessionId);
559
+ requireSessionAccess(data.chatSessionId);
520
560
  const projectId = ws.getProjectId(conn);
521
561
 
522
562
  try {
@@ -529,7 +569,7 @@ export const streamHandler = createRouter()
529
569
 
530
570
  debug.log('chat', 'Reconnecting to active stream:', streamState.streamId);
531
571
 
532
- ws.addCleanup(conn, bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false }));
572
+ bridgeStreamToRoom(streamState.streamId, chatSessionId, projectId, { presenceOnConnection: false });
533
573
 
534
574
  // Send current state snapshot to chat session room so frontend can catch up
535
575
  ws.emit.chatSession(chatSessionId, 'chat:connection', {
@@ -557,7 +597,7 @@ export const streamHandler = createRouter()
557
597
  answers: t.Record(t.String(), t.String())
558
598
  })
559
599
  }, async ({ data, conn }) => {
560
- requireSessionAccess(conn, data.chatSessionId);
600
+ requireSessionAccess(data.chatSessionId);
561
601
  const projectId = ws.getProjectId(conn);
562
602
 
563
603
  try {
@@ -599,6 +639,9 @@ export const streamHandler = createRouter()
599
639
  messages: t.Array(t.Any()),
600
640
  currentPartialText: t.Optional(t.String()),
601
641
  currentReasoningText: t.Optional(t.String()),
642
+ /** The blocks those two texts belong to (see `chat:partial`). */
643
+ partialBlock: t.Optional(t.Number()),
644
+ reasoningBlock: t.Optional(t.Number()),
602
645
  error: t.Optional(t.String()),
603
646
  startedAt: t.String(),
604
647
  completedAt: t.Optional(t.String())
@@ -607,7 +650,7 @@ export const streamHandler = createRouter()
607
650
  const projectId = ws.getProjectId(conn);
608
651
 
609
652
  if (data.chatSessionId) {
610
- requireSessionAccess(conn, data.chatSessionId);
653
+ requireSessionAccess(data.chatSessionId);
611
654
  }
612
655
 
613
656
  const streamState = data.chatSessionId
@@ -644,6 +687,8 @@ export const streamHandler = createRouter()
644
687
  }),
645
688
  currentPartialText: streamState.currentPartialText,
646
689
  currentReasoningText: streamState.currentReasoningText,
690
+ partialBlock: streamState.partialBlock,
691
+ reasoningBlock: streamState.reasoningBlock,
647
692
  error: streamState.error,
648
693
  startedAt: streamState.startedAt.toISOString(),
649
694
  completedAt: streamState.completedAt?.toISOString()
@@ -657,7 +702,7 @@ export const streamHandler = createRouter()
657
702
  chatSessionId: t.String()
658
703
  })
659
704
  }, async ({ data, conn }) => {
660
- requireSessionAccess(conn, data.chatSessionId);
705
+ requireSessionAccess(data.chatSessionId);
661
706
  const projectId = ws.getProjectId(conn);
662
707
  const chatSessionId = data.chatSessionId;
663
708
 
@@ -703,7 +748,7 @@ export const streamHandler = createRouter()
703
748
  }
704
749
  })
705
750
 
706
- // Collaborative model sync - broadcast model changes to other users in the same chat session
751
+ // Model sync - broadcast model changes to the other devices on the same chat session
707
752
  .on('chat:model-sync', {
708
753
  data: t.Object({
709
754
  senderId: t.String(),
@@ -713,14 +758,14 @@ export const streamHandler = createRouter()
713
758
  modelId: t.String(),
714
759
  modelName: t.String(),
715
760
  // The reasoning level travels with the model pick (it is re-seeded per
716
- // model), so collaborators never end up on a level the model lacks.
761
+ // model), so other devices never end up on a level the model lacks.
717
762
  reasoningEffort: t.Optional(t.Union([t.String(), t.Null()])),
718
763
  // Per-tab id of the sender; lets the sender drop its own echo without
719
764
  // also dropping the same user's other tabs/devices.
720
765
  clientId: t.Optional(t.String())
721
766
  })
722
- }, ({ data, conn }) => {
723
- requireSessionAccess(conn, data.chatSessionId);
767
+ }, ({ data }) => {
768
+ requireSessionAccess(data.chatSessionId);
724
769
  const chatSessionId = data.chatSessionId;
725
770
 
726
771
  // Store latest model state on server for late joiners / refresh
@@ -757,7 +802,7 @@ export const streamHandler = createRouter()
757
802
  });
758
803
  })
759
804
 
760
- // Collaborative account sync - broadcast account changes to other users in the same chat session
805
+ // Account sync - broadcast account changes to the other devices on the same chat session
761
806
  .on('chat:account-sync', {
762
807
  data: t.Object({
763
808
  senderId: t.String(),
@@ -766,8 +811,8 @@ export const streamHandler = createRouter()
766
811
  accountName: t.Optional(t.Union([t.String(), t.Null()])),
767
812
  clientId: t.Optional(t.String())
768
813
  })
769
- }, ({ data, conn }) => {
770
- requireSessionAccess(conn, data.chatSessionId);
814
+ }, ({ data }) => {
815
+ requireSessionAccess(data.chatSessionId);
771
816
  const chatSessionId = data.chatSessionId;
772
817
 
773
818
  // Store latest account state on server for late joiners / refresh
@@ -803,8 +848,8 @@ export const streamHandler = createRouter()
803
848
  reasoningEffort: t.Union([t.String(), t.Null()]),
804
849
  clientId: t.Optional(t.String())
805
850
  })
806
- }, ({ data, conn }) => {
807
- requireSessionAccess(conn, data.chatSessionId);
851
+ }, ({ data }) => {
852
+ requireSessionAccess(data.chatSessionId);
808
853
  const chatSessionId = data.chatSessionId;
809
854
 
810
855
  // Persist to the session record so refreshes and late joiners get it.
@@ -823,9 +868,9 @@ export const streamHandler = createRouter()
823
868
  });
824
869
  })
825
870
 
826
- // Collaborative profile sync — broadcast + persist the per-session active
827
- // profile, mirroring chat:model-sync. Non-admin: choosing a profile is a run
828
- // choice like the model, not an admin mutation of the profile itself.
871
+ // Profile sync — broadcast + persist the per-session active profile,
872
+ // mirroring chat:model-sync: choosing a profile is a run choice like the
873
+ // model, not an edit of the profile itself.
829
874
  .on('chat:profile-sync', {
830
875
  data: t.Object({
831
876
  senderId: t.String(),
@@ -833,8 +878,8 @@ export const streamHandler = createRouter()
833
878
  profileId: t.Union([t.Number(), t.Null()]),
834
879
  clientId: t.Optional(t.String())
835
880
  })
836
- }, ({ data, conn }) => {
837
- requireSessionAccess(conn, data.chatSessionId);
881
+ }, ({ data }) => {
882
+ requireSessionAccess(data.chatSessionId);
838
883
  try {
839
884
  sessionQueries.updateProfile(data.chatSessionId, data.profileId);
840
885
  } catch (err) {
@@ -900,8 +945,6 @@ export const streamHandler = createRouter()
900
945
  timestamp: t.String(),
901
946
  message_id: t.Optional(t.String()),
902
947
  parent_message_id: t.Optional(t.Union([t.String(), t.Null()])),
903
- sender_id: t.Optional(t.String()),
904
- sender_name: t.Optional(t.String()),
905
948
  engine: t.Optional(t.String()),
906
949
  seq: t.Optional(t.Number())
907
950
  }))
@@ -914,7 +957,12 @@ export const streamHandler = createRouter()
914
957
  t.Literal('update'),
915
958
  t.Literal('end')
916
959
  ]),
917
- partialText: t.String(),
960
+ /** Changes on every `start`; deltas only apply within their block. */
961
+ block: t.Number(),
962
+ /** Length of the block's text before `deltaText` (start/update). */
963
+ offset: t.Optional(t.Number()),
964
+ /** The block's full text — on `end` only. */
965
+ partialText: t.Optional(t.String()),
918
966
  deltaText: t.String(),
919
967
  reasoning: t.Optional(t.Boolean()),
920
968
  timestamp: t.String(),
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Chat Apps Router
3
+ *
4
+ * Pairing chats with the connected bots: which bots there are and how they
5
+ * are doing, a pairing link, switching a chat on or off, a test message,
6
+ * unlinking, and the command reference. Connecting or removing the BOT itself
7
+ * is an integration. What a paired chat can DO is the control catalog.
8
+ */
9
+
10
+ import { t } from 'elysia';
11
+ import { createRouter } from '$shared/utils/ws-server';
12
+ import { ws } from '$backend/utils/ws';
13
+ import {
14
+ cancelPairingLink,
15
+ createPairingLink,
16
+ listChannelBots,
17
+ listChatAppCommands,
18
+ onBotsChanged,
19
+ onLinksChanged,
20
+ removeChannelLink,
21
+ sendChannelTest,
22
+ setChannelLinkEnabled
23
+ } from '$backend/chat-apps';
24
+
25
+ const LINK_SCHEMA = t.Object({
26
+ id: t.String(),
27
+ displayName: t.Union([t.String(), t.Null()]),
28
+ isEnabled: t.Boolean(),
29
+ createdAt: t.String(),
30
+ lastUsedAt: t.Union([t.String(), t.Null()])
31
+ });
32
+
33
+ const BOT_SCHEMA = t.Object({
34
+ accountId: t.String(),
35
+ provider: t.String(),
36
+ label: t.String(),
37
+ botName: t.Union([t.String(), t.Null()]),
38
+ projectId: t.Union([t.String(), t.Null()]),
39
+ running: t.Boolean(),
40
+ mode: t.Union([t.Literal('webhook'), t.Literal('polling'), t.Null()]),
41
+ originSource: t.Union([t.Literal('configured'), t.Literal('domain'), t.Literal('tunnel'), t.Null()]),
42
+ connection: t.Union([t.Literal('connecting'), t.Literal('open'), t.Literal('closed'), t.Null()]),
43
+ error: t.Union([t.String(), t.Null()]),
44
+ control: t.Boolean(),
45
+ links: t.Array(LINK_SCHEMA)
46
+ });
47
+
48
+ const OK = t.Object({ ok: t.Boolean() });
49
+
50
+ // A chat pairs or changes itself from the phone, and a bot comes up or goes
51
+ // down, with no request from any tab. Every open Settings page re-reads.
52
+ onLinksChanged(() => ws.emit.global('chat-apps:changed', {}));
53
+ onBotsChanged(() => ws.emit.global('chat-apps:changed', {}));
54
+
55
+ export const chatAppsRouter = createRouter()
56
+ .http('chat-apps:bots', {
57
+ data: t.Object({
58
+ /** The tab's own origin: a non-local one is a better webhook address than a tunnel. */
59
+ requestOrigin: t.Optional(t.String())
60
+ }),
61
+ response: t.Array(BOT_SCHEMA)
62
+ }, async ({ data }) => {
63
+ return listChannelBots(data.requestOrigin);
64
+ })
65
+
66
+ .http('chat-apps:pair', {
67
+ data: t.Object({ accountId: t.String() }),
68
+ response: t.Object({ url: t.String(), expiresAt: t.String(), ttlSeconds: t.Number() })
69
+ }, async ({ data, conn }) => {
70
+ return createPairingLink(ws.getUserId(conn), data.accountId);
71
+ })
72
+
73
+ .http('chat-apps:pair-cancel', {
74
+ data: t.Object({ accountId: t.String() }),
75
+ response: OK
76
+ }, async ({ data, conn }) => {
77
+ cancelPairingLink(ws.getUserId(conn), data.accountId);
78
+ return { ok: true };
79
+ })
80
+
81
+ .http('chat-apps:set-enabled', {
82
+ data: t.Object({ linkId: t.String(), enabled: t.Boolean() }),
83
+ response: OK
84
+ }, async ({ data }) => {
85
+ await setChannelLinkEnabled(data.linkId, data.enabled);
86
+ return { ok: true };
87
+ })
88
+
89
+ .http('chat-apps:unlink', {
90
+ data: t.Object({ linkId: t.String() }),
91
+ response: OK
92
+ }, async ({ data }) => {
93
+ await removeChannelLink(data.linkId);
94
+ return { ok: true };
95
+ })
96
+
97
+ .http('chat-apps:test', {
98
+ data: t.Object({ linkId: t.String() }),
99
+ response: OK
100
+ }, async ({ data }) => {
101
+ await sendChannelTest(data.linkId);
102
+ return { ok: true };
103
+ })
104
+
105
+ .http('chat-apps:commands', {
106
+ data: t.Object({}),
107
+ response: t.Array(t.Object({
108
+ command: t.String(),
109
+ hint: t.Union([t.String(), t.Null()]),
110
+ description: t.String(),
111
+ group: t.String()
112
+ }))
113
+ }, async () => {
114
+ return listChatAppCommands();
115
+ })
116
+
117
+ .emit('chat-apps:changed', t.Object({}));
@@ -1,30 +1,16 @@
1
1
  /**
2
- * Containers — changing something. Admin only, all of it.
3
- *
4
- * The routes are listed in ADMIN_ONLY_ROUTES; these handlers still check host
5
- * access against the caller's real role rather than a hardcoded one, because a
6
- * gate that trusts its caller is no gate at all.
7
- *
8
- * Stopping a container takes down whatever it serves, for everyone — the same
9
- * reason stopping a port is admin-only — and removing an image or a volume
10
- * takes down something nobody can bring back by pressing start.
2
+ * Containers — changing something: start/stop/restart, remove, prune. Every
3
+ * handler first confirms the host is the local machine or a saved SSH host.
11
4
  */
12
5
 
13
6
  import { t } from 'elysia';
14
7
  import { createRouter } from '$shared/utils/ws-server';
15
- import { LOCAL_HOST_ID } from '$shared/types/host';
16
8
  import { removeResource, runContainerAction } from '../../containers/actions';
17
9
  import { dismissPrune, pruneJobFor, startPrune } from '../../containers/prune-job';
18
- import { requireHostAccess } from './list';
10
+ import { requireHost } from './list';
19
11
  import { containerMonitor } from '../../containers/monitor';
20
- import { sshConnectionQueries } from '../../database/queries';
21
12
  import { ws } from '../../utils/ws';
22
13
 
23
- function requireManageAccess(conn: Parameters<typeof ws.getUserId>[0], hostId: string): void {
24
- if (hostId === LOCAL_HOST_ID) return;
25
- sshConnectionQueries.ensureAccess(hostId, ws.getUserId(conn), ws.getRole(conn) === 'admin');
26
- }
27
-
28
14
  const ACTIONS = [
29
15
  t.Literal('start'),
30
16
  t.Literal('stop'),
@@ -55,8 +41,8 @@ export const containersActionHandler = createRouter()
55
41
  }),
56
42
  response: t.Any()
57
43
  },
58
- async ({ data, conn }) => {
59
- requireManageAccess(conn, data.hostId);
44
+ async ({ data }) => {
45
+ requireHost(data.hostId);
60
46
 
61
47
  // Re-read before acting rather than trusting the row the client clicked:
62
48
  // a listing is a second or two old, and a container can be removed and
@@ -97,8 +83,8 @@ export const containersActionHandler = createRouter()
97
83
  }),
98
84
  response: t.Any()
99
85
  },
100
- async ({ data, conn }) => {
101
- requireManageAccess(conn, data.hostId);
86
+ async ({ data }) => {
87
+ requireHost(data.hostId);
102
88
  return { result: await removeResource(data.hostId, data.kind, data.id, data.force === true) };
103
89
  }
104
90
  )
@@ -124,7 +110,7 @@ export const containersActionHandler = createRouter()
124
110
  response: t.Any()
125
111
  },
126
112
  async ({ data, conn }) => {
127
- requireManageAccess(conn, data.hostId);
113
+ requireHost(data.hostId);
128
114
  return { job: startPrune(data.hostId, data.kinds, ws.getUserId(conn)) };
129
115
  }
130
116
  )
@@ -139,7 +125,7 @@ export const containersActionHandler = createRouter()
139
125
  'containers:prune-status',
140
126
  { data: t.Object({ hostId: t.String({ minLength: 1 }) }), response: t.Any() },
141
127
  async ({ data, conn }) => {
142
- requireHostAccess(conn, data.hostId);
128
+ requireHost(data.hostId);
143
129
  return { job: pruneJobFor(data.hostId, ws.getUserId(conn)) };
144
130
  }
145
131
  )
@@ -148,8 +134,8 @@ export const containersActionHandler = createRouter()
148
134
  .http(
149
135
  'containers:prune-dismiss',
150
136
  { data: t.Object({ hostId: t.String({ minLength: 1 }) }), response: t.Any() },
151
- async ({ data, conn }) => {
152
- requireManageAccess(conn, data.hostId);
137
+ async ({ data }) => {
138
+ requireHost(data.hostId);
153
139
  dismissPrune(data.hostId);
154
140
  return { ok: true };
155
141
  }
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * Container manager WebSocket router.
3
3
  *
4
- * Reading the list, the detail and the logs is open to any signed-in user who
5
- * can already reach the host; `containers:action` is registered in
6
- * ADMIN_ONLY_ROUTES, and opening a shell is gated inside the PtyKit server's
7
- * own `authorize`.
4
+ * Reading the list, the detail and the logs of a host that still exists;
5
+ * changing containers; and a shell, authorized inside the PtyKit server's own
6
+ * `authorize`.
8
7
  */
9
8
 
10
9
  import { t } from 'elysia';