@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
@@ -18,7 +18,7 @@
18
18
 
19
19
  import type { SessionScopedChanges } from '$shared/types/database/schema';
20
20
  import { naturalCompare } from '$shared/utils/compare';
21
- import { countLineChanges, isBinaryBuffer } from '$shared/utils/diff-calculator';
21
+ import { countLineChangesAsync, isBinaryBuffer } from '$shared/utils/diff-calculator';
22
22
 
23
23
  export { isBinaryBuffer };
24
24
 
@@ -46,54 +46,92 @@ export function statusOf(oldHash: string, newHash: string): TurnFileStatus {
46
46
  return 'modified';
47
47
  }
48
48
 
49
+ /** What one (old, new) pair of blobs amounts to as a +/- badge. */
50
+ export interface PairLineStats {
51
+ insertions: number;
52
+ deletions: number;
53
+ isBinary: boolean;
54
+ /** False when a blob this pair needs is no longer readable. */
55
+ contentAvailable: boolean;
56
+ }
57
+
58
+ /**
59
+ * Where a pair's numbers come from. Production passes `blobLineStats`
60
+ * (backend/snapshot/line-stats.ts), which counts each pair once and remembers
61
+ * it; tests pass `statsFromBlobs` over an in-memory store.
62
+ */
63
+ export type LineStatsSource = (oldHash: string, newHash: string) => Promise<PairLineStats>;
64
+
65
+ /**
66
+ * Count one pair straight from its blobs. This is the single definition of
67
+ * "how many lines did this change" — the cache only stores what it returns.
68
+ */
69
+ export async function countPairFromBlobs(
70
+ oldHash: string,
71
+ newHash: string,
72
+ readBlob: (hash: string) => Promise<Buffer>
73
+ ): Promise<PairLineStats> {
74
+ let oldBuf: Buffer | null = null;
75
+ let newBuf: Buffer | null = null;
76
+ let contentAvailable = true;
77
+
78
+ if (oldHash) {
79
+ try {
80
+ oldBuf = await readBlob(oldHash);
81
+ } catch {
82
+ contentAvailable = false;
83
+ }
84
+ }
85
+ if (newHash) {
86
+ try {
87
+ newBuf = await readBlob(newHash);
88
+ } catch {
89
+ contentAvailable = false;
90
+ }
91
+ }
92
+
93
+ const isBinary =
94
+ (oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
95
+
96
+ let insertions = 0;
97
+ let deletions = 0;
98
+ if (contentAvailable && !isBinary) {
99
+ // Cooperative: a pathological pair takes long, but never holds the
100
+ // server's thread for more than a few milliseconds at a time.
101
+ const counts = await countLineChangesAsync(
102
+ oldBuf ? oldBuf.toString('utf8') : '',
103
+ newBuf ? newBuf.toString('utf8') : ''
104
+ );
105
+ insertions = counts.additions;
106
+ deletions = counts.deletions;
107
+ }
108
+
109
+ return { insertions, deletions, isBinary, contentAvailable };
110
+ }
111
+
112
+ /** An uncached source over any blob reader. */
113
+ export function statsFromBlobs(readBlob: (hash: string) => Promise<Buffer>): LineStatsSource {
114
+ return (oldHash, newHash) => countPairFromBlobs(oldHash, newHash, readBlob);
115
+ }
116
+
49
117
  /**
50
118
  * Turn one checkpoint's `session_changes` into a displayable file list.
51
119
  *
52
- * `readBlob` is injected so this stays a pure function over its inputs — the
53
- * only I/O is the reader the caller hands in.
120
+ * `statsFor` is injected so this stays a pure function over its inputs — the
121
+ * only I/O is the source the caller hands in.
54
122
  */
55
123
  export async function buildTurnFiles(
56
124
  changes: SessionScopedChanges,
57
- readBlob: (hash: string) => Promise<Buffer>
125
+ statsFor: LineStatsSource
58
126
  ): Promise<TurnFileChange[]> {
59
127
  const files: TurnFileChange[] = [];
60
128
 
61
129
  for (const [path, change] of Object.entries(changes)) {
62
130
  const status = statusOf(change.oldHash, change.newHash);
63
-
64
- let oldBuf: Buffer | null = null;
65
- let newBuf: Buffer | null = null;
66
- let contentAvailable = true;
67
-
68
- if (change.oldHash) {
69
- try {
70
- oldBuf = await readBlob(change.oldHash);
71
- } catch {
72
- contentAvailable = false;
73
- }
74
- }
75
- if (change.newHash) {
76
- try {
77
- newBuf = await readBlob(change.newHash);
78
- } catch {
79
- contentAvailable = false;
80
- }
81
- }
82
-
83
- const isBinary =
84
- (oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
85
-
86
- let insertions = 0;
87
- let deletions = 0;
88
- if (contentAvailable && !isBinary) {
89
- const counts = countLineChanges(
90
- oldBuf ? oldBuf.toString('utf8') : '',
91
- newBuf ? newBuf.toString('utf8') : ''
92
- );
93
- insertions = counts.additions;
94
- deletions = counts.deletions;
95
- }
96
-
131
+ const { insertions, deletions, isBinary, contentAvailable } = await statsFor(
132
+ change.oldHash,
133
+ change.newHash
134
+ );
97
135
  files.push({ path, status, insertions, deletions, isBinary, contentAvailable });
98
136
  }
99
137
 
@@ -177,7 +215,7 @@ export function netChangeRuns(turns: SessionScopedChanges[]): Map<string, Change
177
215
  /** The chat-level numbers: net files changed, and net lines in and out. */
178
216
  export async function summariseNetChanges(
179
217
  turns: SessionScopedChanges[],
180
- readBlob: (hash: string) => Promise<Buffer>
218
+ statsFor: LineStatsSource
181
219
  ): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
182
220
  let insertions = 0;
183
221
  let deletions = 0;
@@ -189,7 +227,7 @@ export async function summariseNetChanges(
189
227
  list.forEach((run, index) => {
190
228
  changes[`${index}\0${path}`] = run;
191
229
  });
192
- const summary = summariseTurnFiles(await buildTurnFiles(changes, readBlob));
230
+ const summary = summariseTurnFiles(await buildTurnFiles(changes, statsFor));
193
231
  insertions += summary.insertions;
194
232
  deletions += summary.deletions;
195
233
  }
@@ -45,13 +45,12 @@ export const sshPtyKitServer = createPtyKitServer(sshPtyKitManager, {
45
45
  room: (ctx) => ctx.namespace,
46
46
  authorize: (ctx) => {
47
47
  const userId = ctx.conn.data.userId;
48
- const isAdmin = ctx.conn.data.isAdmin === true;
49
48
  if (typeof userId !== 'string' || !userId) return false;
50
49
 
51
50
  const connectionId = connectionIdFromNamespace(ctx.namespace);
52
51
  if (!connectionId) return false;
53
52
 
54
- return sshConnectionQueries.getForUser(connectionId, userId, isAdmin) !== null;
53
+ return sshConnectionQueries.get(connectionId) !== null;
55
54
  }
56
55
  });
57
56
 
@@ -35,13 +35,18 @@ export const ptyKitManager = new PtyKitManager({
35
35
  // refresh/reconnect can still replay their final screen (matches old 5-min window).
36
36
  idleTtl: null,
37
37
  retainExitedMs: 5 * 60_000,
38
+ // A flood (a build, a dev server's log) is held to one frame per window;
39
+ // the first chunk after a pause still goes out at once, so typing is not.
40
+ outputCoalesceMs: 16,
38
41
  env: { sanitize: true, inject: TERMINAL_ENV }
39
42
  });
40
43
 
41
44
  /**
42
45
  * Embedded WebSocket server over the manager. No HTTP/Bun mounting — Clopen's
43
46
  * tunnel feeds it frames and supplies per-connection `send`. `authorize` enforces
44
- * project access; the room is the project so output is collaborative.
47
+ * project access. The room is the workspace scope, which carries awareness (tabs
48
+ * opened or closed on any device); a session's output goes only to the devices
49
+ * that have that tab mounted (PtyKit 0.1.0).
45
50
  */
46
51
  export const ptyKitServer = createPtyKitServer(ptyKitManager, {
47
52
  room: (ctx) => ctx.namespace,
@@ -49,19 +54,18 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
49
54
  const userId = ctx.conn.data.userId;
50
55
  if (typeof userId !== 'string' || !userId) return false;
51
56
  // The namespace separates worktrees; access is still the project's call.
52
- const allowed = projectQueries.userHasProject(userId, scopeProjectId(ctx.namespace));
57
+ const allowed = projectQueries.isListed(scopeProjectId(ctx.namespace));
53
58
  if (allowed) knownNamespaces.add(ctx.namespace);
54
59
  return allowed;
55
60
  },
56
61
  /**
57
- * The shell inherits the git identity of whoever opened it, for the project
58
- * it belongs to. Without this a `git commit` typed into the terminal would
62
+ * The shell inherits the git identity of the project it belongs to. Without this a `git commit` typed into the terminal would
59
63
  * use the machine's identity while the same commit from the Git panel used
60
64
  * the chosen one — the same repository, two different authors.
61
65
  *
62
66
  * Pointed at a FILE rather than given the `GIT_CONFIG_*` block the other
63
67
  * surfaces use. A shell lives for hours and its environment is fixed at
64
- * spawn, so an inlined identity goes stale the moment the user switches
68
+ * spawn, so an inlined identity goes stale the moment the project switches
65
69
  * accounts — silently, since the tab keeps working. Git re-reads a config
66
70
  * file on every invocation, so the switch reaches tabs that are already open.
67
71
  * See `backend/git/identity/scope-config.ts`.
@@ -71,9 +75,7 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
71
75
  * user's own global config away from every git command in the terminal.
72
76
  */
73
77
  env: async (ctx): Promise<Record<string, string>> => {
74
- const userId = ctx.conn.data.userId;
75
- if (typeof userId !== 'string' || !userId) return {};
76
- const path = await writeScopeConfig(userId, scopeProjectId(ctx.namespace));
78
+ const path = await writeScopeConfig(scopeProjectId(ctx.namespace));
77
79
  return path ? { GIT_CONFIG_GLOBAL: path } : {};
78
80
  }
79
81
  });
@@ -5,7 +5,7 @@
5
5
  * build share links against. Where that origin comes from is adaptive, so the
6
6
  * caller never has to think about tunnels vs domains:
7
7
  *
8
- * 1. `configured` — an admin-set public URL (system setting `publicBaseUrl`),
8
+ * 1. `configured` — a set public URL (system setting `publicBaseUrl`),
9
9
  * for VPS/reverse-proxy deployments where the browser can't see the real
10
10
  * hostname.
11
11
  * 2. `domain` — the browser is already hitting Clopen on a non-local origin
@@ -28,7 +28,7 @@ export interface PublicOrigin {
28
28
  }
29
29
 
30
30
  /** Hostnames that are not reachable by another device — force a tunnel. */
31
- function isLocalHostname(hostname: string): boolean {
31
+ export function isLocalHostname(hostname: string): boolean {
32
32
  const h = hostname.toLowerCase();
33
33
  if (h === 'localhost' || h.endsWith('.localhost')) return true;
34
34
  if (h === '127.0.0.1' || h === '::1' || h === '0.0.0.0') return true;
@@ -43,12 +43,12 @@ function isLocalHostname(hostname: string): boolean {
43
43
  return false;
44
44
  }
45
45
 
46
- /** Strip a trailing slash so callers can append `/#invite/...` cleanly. */
46
+ /** Strip a trailing slash so callers can append `/#device/...` cleanly. */
47
47
  function normalizeOrigin(url: string): string {
48
48
  return url.replace(/\/+$/, '');
49
49
  }
50
50
 
51
- /** Read the admin-configured public base URL from system settings, if any. */
51
+ /** Read the configured public base URL from system settings, if any. */
52
52
  function getConfiguredPublicBaseUrl(): string | null {
53
53
  return readSystemSetting((settings) => {
54
54
  const url = settings.publicBaseUrl;
@@ -66,19 +66,22 @@ function findQuickTunnelForPort(port: number): string | null {
66
66
  return null;
67
67
  }
68
68
 
69
+ /** The port another device must reach: Vite's in dev (it proxies to the backend), the server's in production. */
70
+ export function getClopenPublicPort(): number {
71
+ return SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
72
+ }
73
+
69
74
  /**
70
- * Resolve a public origin for Remote Access share links. `requestOrigin` is the
71
- * browser's own `window.location.origin` (passed by the client), used to detect
72
- * the already-public `domain` case.
75
+ * The public origin that already exists, if any — never starts anything.
76
+ *
77
+ * Same order as {@link resolvePublicOrigin}, minus the side effect. A caller
78
+ * reacting to a tunnel going away needs to know whether something is still
79
+ * reachable without restarting the very tunnel the user may just have stopped.
73
80
  */
74
- export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
75
- // 1. Explicitly configured public URL wins.
81
+ export function findPublicOrigin(requestOrigin?: string): PublicOrigin | null {
76
82
  const configured = getConfiguredPublicBaseUrl();
77
- if (configured) {
78
- return { origin: configured, source: 'configured' };
79
- }
83
+ if (configured) return { origin: configured, source: 'configured' };
80
84
 
81
- // 2. Already served on a real (non-local) origin — reuse it.
82
85
  if (requestOrigin) {
83
86
  try {
84
87
  const url = new URL(requestOrigin);
@@ -90,15 +93,23 @@ export async function resolvePublicOrigin(requestOrigin?: string): Promise<Publi
90
93
  }
91
94
  }
92
95
 
93
- // 3. Local install — tunnel Clopen's own port. In dev the app is served by
96
+ const existing = findQuickTunnelForPort(getClopenPublicPort());
97
+ return existing ? { origin: existing, source: 'tunnel' } : null;
98
+ }
99
+
100
+ /**
101
+ * Resolve a public origin for Remote Access share links. `requestOrigin` is the
102
+ * browser's own `window.location.origin` (passed by the client), used to detect
103
+ * the already-public `domain` case.
104
+ */
105
+ export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
106
+ const found = findPublicOrigin(requestOrigin);
107
+ if (found) return found;
108
+
109
+ // Local install — tunnel Clopen's own port. In dev the app is served by
94
110
  // Vite on PORT_FRONTEND (which proxies to the backend), so tunnel that; in
95
111
  // production frontend and backend share PORT.
96
- const port = SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
97
-
98
- const existing = findQuickTunnelForPort(port);
99
- if (existing) {
100
- return { origin: existing, source: 'tunnel' };
101
- }
112
+ const port = getClopenPublicPort();
102
113
 
103
114
  debug.log('tunnel', `[remote-access] Starting quick tunnel for Clopen port ${port}`);
104
115
  await tunnelKit.bin.ensure();
@@ -2,38 +2,6 @@
2
2
  * User domain helper functions
3
3
  */
4
4
 
5
- // List of friendly animal names for anonymous users
6
- export const ANIMAL_NAMES = [
7
- 'Penguin', 'Koala', 'Panda', 'Tiger', 'Lion', 'Eagle', 'Dolphin', 'Elephant',
8
- 'Giraffe', 'Zebra', 'Kangaroo', 'Octopus', 'Butterfly', 'Fox', 'Wolf', 'Bear',
9
- 'Rabbit', 'Deer', 'Owl', 'Hawk', 'Falcon', 'Parrot', 'Peacock', 'Swan',
10
- 'Flamingo', 'Pelican', 'Seal', 'Walrus', 'Otter', 'Beaver', 'Raccoon', 'Squirrel',
11
- 'Hedgehog', 'Hamster', 'Gecko', 'Chameleon', 'Turtle', 'Frog', 'Salamander', 'Newt',
12
- 'Shark', 'Whale', 'Stingray', 'Jellyfish', 'Starfish', 'Crab', 'Lobster', 'Shrimp',
13
- 'Ant', 'Bee', 'Ladybug', 'Dragonfly', 'Cricket', 'Grasshopper', 'Beetle', 'Moth',
14
- 'Cheetah', 'Jaguar', 'Leopard', 'Lynx', 'Cougar', 'Panther', 'Ocelot', 'Serval',
15
- 'Monkey', 'Gorilla', 'Chimpanzee', 'Orangutan', 'Lemur', 'Sloth', 'Armadillo', 'Pangolin',
16
- 'Platypus', 'Echidna', 'Wombat', 'Tasmanian', 'Quokka', 'Wallaby', 'Possum', 'Bandicoot',
17
- 'Meerkat', 'Mongoose', 'Ferret', 'Weasel', 'Badger', 'Skunk', 'Porcupine', 'Chinchilla',
18
- 'Capybara', 'Alpaca', 'Llama', 'Vicuna', 'Camel', 'Yak', 'Bison', 'Buffalo',
19
- 'Moose', 'Elk', 'Reindeer', 'Antelope', 'Gazelle', 'Impala', 'Wildebeest', 'Okapi'
20
- ];
21
-
22
- // Colors for additional uniqueness
23
- export const COLORS = [
24
- 'Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange', 'Pink', 'Brown',
25
- 'Gray', 'Black', 'White', 'Silver', 'Gold', 'Cyan', 'Magenta', 'Lime',
26
- 'Indigo', 'Violet', 'Turquoise', 'Coral', 'Salmon', 'Crimson', 'Navy', 'Teal'
27
- ];
28
-
29
- export interface AnonymousUser {
30
- id: string;
31
- name: string;
32
- color: string;
33
- avatar: string;
34
- createdAt: string;
35
- }
36
-
37
5
  /**
38
6
  * Generate a consistent color from a string
39
7
  */
@@ -62,26 +30,3 @@ export function getInitials(name: string): string {
62
30
  // Fallback to first 2 characters
63
31
  return trimmed.substring(0, 2).toUpperCase();
64
32
  }
65
-
66
- /**
67
- * Generate a unique anonymous user identity
68
- */
69
- export function generateAnonymousUser(): AnonymousUser {
70
- const randomAnimal = ANIMAL_NAMES[Math.floor(Math.random() * ANIMAL_NAMES.length)];
71
- const randomColor = COLORS[Math.floor(Math.random() * COLORS.length)];
72
- const randomNumber = Math.floor(Math.random() * 1000);
73
-
74
- const name = `${randomColor} ${randomAnimal} ${randomNumber}`;
75
- const id = `user-${crypto.randomUUID()}`; // Server-side crypto API
76
-
77
- // Generate a color for the avatar based on the name
78
- const avatarColor = generateColorFromString(name);
79
-
80
- return {
81
- id,
82
- name,
83
- color: avatarColor,
84
- avatar: getInitials(randomAnimal),
85
- createdAt: new Date().toISOString()
86
- };
87
- }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The send path every frame takes: what gets compressed, and how a large
3
+ * reply leaves in chunks without filling the socket's buffer.
4
+ */
5
+
6
+ import { describe, expect, test } from 'bun:test';
7
+
8
+ import { decodeChunk } from '$shared/utils/ws-chunk';
9
+ import { CHUNK_BYTES, COMPRESS_MIN_BYTES, sendBinary, sendReply, sendText } from './ws-wire';
10
+
11
+ class FakeSocket {
12
+ readyState = 1;
13
+ buffered = 0;
14
+ sent: Array<{ data: string | Buffer; compress?: boolean }> = [];
15
+ raw = { getBufferedAmount: () => this.buffered };
16
+ send(data: string | Buffer, compress?: boolean) {
17
+ this.sent.push({ data, compress });
18
+ }
19
+ }
20
+
21
+ describe('sendText / sendBinary', () => {
22
+ test('compresses text only when it is large enough to gain from it', () => {
23
+ const socket = new FakeSocket();
24
+ sendText(socket, 'small', 'x'.repeat(COMPRESS_MIN_BYTES - 1));
25
+ sendText(socket, 'large', 'x'.repeat(COMPRESS_MIN_BYTES));
26
+ expect(socket.sent.map((frame) => frame.compress)).toEqual([false, true]);
27
+ });
28
+
29
+ test('never compresses binary', () => {
30
+ const socket = new FakeSocket();
31
+ sendBinary(socket, 'file:download', new Uint8Array(100_000));
32
+ expect(socket.sent[0].compress).toBe(false);
33
+ expect(Buffer.isBuffer(socket.sent[0].data)).toBe(true);
34
+ });
35
+ });
36
+
37
+ describe('sendReply', () => {
38
+ test('sends a reply under the threshold as one ordinary frame', async () => {
39
+ const socket = new FakeSocket();
40
+ const text = JSON.stringify({ action: 'x:response', payload: { ok: true } });
41
+ await sendReply(socket, 'x:response', 'req-1', text);
42
+ expect(socket.sent).toEqual([{ data: text, compress: false }]);
43
+ });
44
+
45
+ test('chunks a large reply into pieces that reassemble to the exact text', async () => {
46
+ const socket = new FakeSocket();
47
+ const text = JSON.stringify({ action: 'messages:list:response', payload: { data: 'é😀'.repeat(CHUNK_BYTES) } });
48
+ await sendReply(socket, 'messages:list:response', 'req-2', text);
49
+
50
+ const chunks = socket.sent.map((frame) => decodeChunk(frame.data as string)!);
51
+ expect(chunks.length).toBeGreaterThan(1);
52
+ expect(new Set(chunks.map((chunk) => chunk.streamId)).size).toBe(1);
53
+ expect(chunks.every((chunk) => chunk.requestId === 'req-2' && chunk.count === chunks.length)).toBe(true);
54
+ expect(chunks.map((chunk) => chunk.slice).join('')).toBe(text);
55
+ });
56
+
57
+ test('two replies get distinct streams', async () => {
58
+ const socket = new FakeSocket();
59
+ const text = 'x'.repeat(CHUNK_BYTES * 2);
60
+ await sendReply(socket, 'a', 'req', text);
61
+ await sendReply(socket, 'a', 'req', text);
62
+ const streams = new Set(socket.sent.map((frame) => decodeChunk(frame.data as string)!.streamId));
63
+ expect(streams.size).toBe(2);
64
+ });
65
+
66
+ test('waits for the socket to drain between chunks', async () => {
67
+ const socket = new FakeSocket();
68
+ socket.buffered = 10 * 1024 * 1024;
69
+ const sending = sendReply(socket, 'a', 'req', 'x'.repeat(CHUNK_BYTES * 3));
70
+ await new Promise((resolve) => setTimeout(resolve, 40));
71
+ expect(socket.sent).toHaveLength(1); // first chunk only, then held
72
+
73
+ socket.buffered = 0;
74
+ await sending;
75
+ expect(socket.sent).toHaveLength(3);
76
+ });
77
+
78
+ test('stops when the socket closes mid-reply', async () => {
79
+ const socket = new FakeSocket();
80
+ socket.buffered = 10 * 1024 * 1024;
81
+ const sending = sendReply(socket, 'a', 'req', 'x'.repeat(CHUNK_BYTES * 3));
82
+ await new Promise((resolve) => setTimeout(resolve, 20));
83
+ socket.readyState = 3;
84
+ await sending;
85
+ expect(socket.sent).toHaveLength(1);
86
+ });
87
+ });
@@ -0,0 +1,189 @@
1
+ /**
2
+ * The last step before a frame leaves the server — the one place that decides
3
+ * how it travels.
4
+ *
5
+ * Every event (`backend/utils/ws.ts`) and every request-response reply
6
+ * (`shared/utils/ws-server.ts`) is sent through here, so three concerns live
7
+ * once instead of at every call site:
8
+ *
9
+ * 1. Compression. The socket negotiates permessage-deflate (see
10
+ * `WS_PER_MESSAGE_DEFLATE`), but Bun only compresses a frame when asked to.
11
+ * JSON shrinks 4–12× under deflate; a frame under ~1 KB grows instead, and
12
+ * binary frames (uploads, downloads, media) are already dense — so only text
13
+ * of at least `COMPRESS_MIN_BYTES` is compressed.
14
+ *
15
+ * 2. Large replies are chunked. A request-response reply above `CHUNK_BYTES`
16
+ * used to leave as one frame. The browser only reports a frame once all of it
17
+ * has arrived, so on a slow link a multi-megabyte reply looked like silence:
18
+ * the client's 30 s request timer fired mid-download and re-sent the read —
19
+ * queueing a second copy — or tore the socket down and started over. Chunks
20
+ * are proof of progress (each one re-arms the request's timer), they let
21
+ * events slip in between instead of waiting behind the whole reply, and
22
+ * sending waits for the socket to drain so a slow client never makes the
23
+ * server buffer an entire reply in memory. Events are never chunked: they
24
+ * must arrive in the order they were emitted.
25
+ *
26
+ * 3. A traffic meter (development, or `CLOPEN_WS_TRAFFIC=1`) that adds up bytes
27
+ * per action, so a bandwidth claim can be checked against real traffic
28
+ * instead of an estimate.
29
+ */
30
+
31
+ import type { WebSocketCompressor } from 'bun';
32
+ import { debug } from '$shared/utils/logger';
33
+ import { SERVER_ENV } from './env';
34
+ import { encodeChunk, sliceText } from '$shared/utils/ws-chunk';
35
+
36
+ /** Text frames shorter than this are sent uncompressed — deflate would grow them. */
37
+ export const COMPRESS_MIN_BYTES = 1024;
38
+
39
+ /** Request-response replies longer than this (in characters) are chunked. */
40
+ export const CHUNK_BYTES = 256 * 1024;
41
+
42
+ /** Stop sending chunks while the socket has more than this queued. */
43
+ const DRAIN_HIGH_WATER = 1024 * 1024;
44
+
45
+ /** How often to re-check a full socket. */
46
+ const DRAIN_POLL_MS = 10;
47
+
48
+ /**
49
+ * Compression the server offers. A per-socket compressor keeps context across
50
+ * messages, which is what makes the stream of small, similar JSON events
51
+ * (stream deltas, file changes, terminal output) compress well; 32 KB per
52
+ * connection is the price. Client → server frames are small and use the shared
53
+ * decompressor.
54
+ */
55
+ export const WS_PER_MESSAGE_DEFLATE: { compress: WebSocketCompressor; decompress: WebSocketCompressor } = {
56
+ compress: '32KB',
57
+ decompress: 'shared'
58
+ };
59
+
60
+ /**
61
+ * Server-wide socket options, handed to `new Elysia({ websocket })`.
62
+ *
63
+ * They must be set there. Elysia drops the same keys on a `.ws()` route, which
64
+ * is where they used to live — so for as long as that was the case Bun's
65
+ * defaults applied instead: a 16 MB frame limit that closed the socket on any
66
+ * larger upload (1006), and a 120 s idle timeout.
67
+ */
68
+ export const WS_SERVER_OPTIONS = {
69
+ // Allow large binary frames (file uploads, zip extracts); the per-file
70
+ // limits are enforced by the handlers, not by the transport.
71
+ maxPayloadLength: 1024 * 1024 * 1024, // 1 GiB
72
+ // Don't drop a connection that is busy with one long binary transfer.
73
+ idleTimeout: 960, // seconds (max allowed by uWS)
74
+ perMessageDeflate: WS_PER_MESSAGE_DEFLATE
75
+ };
76
+
77
+ /** Numbers each chunked reply, so two replies to one re-sent request stay apart. */
78
+ let replyStreams = 0;
79
+
80
+ /** The part of a socket this module needs: Elysia's wrapper or Bun's own. */
81
+ interface WireSocket {
82
+ readyState: number;
83
+ send(data: string | Buffer, compress?: boolean): unknown;
84
+ raw?: { getBufferedAmount?: () => number };
85
+ getBufferedAmount?: () => number;
86
+ }
87
+
88
+ /** Send one text frame, compressed when it is big enough to gain from it. */
89
+ export function sendText(conn: WireSocket, action: string, text: string): void {
90
+ conn.send(text, text.length >= COMPRESS_MIN_BYTES);
91
+ recordTraffic(action, text.length);
92
+ }
93
+
94
+ /** Send one binary frame. Never compressed: it is already dense. */
95
+ export function sendBinary(conn: WireSocket, action: string, data: ArrayBuffer | Uint8Array | Buffer): void {
96
+ const buffer = Buffer.isBuffer(data)
97
+ ? data
98
+ : data instanceof ArrayBuffer
99
+ ? Buffer.from(data)
100
+ : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
101
+ conn.send(buffer, false);
102
+ recordTraffic(action, buffer.byteLength);
103
+ }
104
+
105
+ /**
106
+ * Send a serialized request-response reply, chunked when it is large.
107
+ * Resolves once the last chunk is handed to the socket (or the socket closed).
108
+ */
109
+ export async function sendReply(conn: WireSocket, action: string, requestId: string, text: string): Promise<void> {
110
+ if (text.length <= CHUNK_BYTES || !requestId) {
111
+ sendText(conn, action, text);
112
+ return;
113
+ }
114
+
115
+ const slices = sliceText(text, CHUNK_BYTES);
116
+ const streamId = String(++replyStreams);
117
+ for (let index = 0; index < slices.length; index++) {
118
+ if (index > 0) {
119
+ await waitForDrain(conn);
120
+ if (conn.readyState !== 1) return; // The client is gone; it will re-request.
121
+ }
122
+ const frame = encodeChunk(streamId, requestId, index, slices.length, slices[index]);
123
+ conn.send(frame, true);
124
+ recordTraffic(action, frame.length);
125
+ }
126
+ }
127
+
128
+ function bufferedAmount(conn: WireSocket): number {
129
+ try {
130
+ if (typeof conn.raw?.getBufferedAmount === 'function') return conn.raw.getBufferedAmount();
131
+ if (typeof conn.getBufferedAmount === 'function') return conn.getBufferedAmount();
132
+ } catch {
133
+ // A closed socket throws; the caller checks readyState next.
134
+ }
135
+ return 0;
136
+ }
137
+
138
+ async function waitForDrain(conn: WireSocket): Promise<void> {
139
+ while (conn.readyState === 1 && bufferedAmount(conn) > DRAIN_HIGH_WATER) {
140
+ await new Promise((resolve) => setTimeout(resolve, DRAIN_POLL_MS));
141
+ }
142
+ }
143
+
144
+ // ============================================================================
145
+ // Traffic meter
146
+ // ============================================================================
147
+
148
+ const TRAFFIC_ENABLED = SERVER_ENV.isDevelopment || process.env.CLOPEN_WS_TRAFFIC === '1';
149
+ const TRAFFIC_REPORT_MS = 30_000;
150
+
151
+ const traffic = new Map<string, { frames: number; bytes: number }>();
152
+ let reportTimer: ReturnType<typeof setInterval> | null = null;
153
+
154
+ function recordTraffic(action: string, bytes: number): void {
155
+ if (!TRAFFIC_ENABLED) return;
156
+ const entry = traffic.get(action);
157
+ if (entry) {
158
+ entry.frames++;
159
+ entry.bytes += bytes;
160
+ } else {
161
+ traffic.set(action, { frames: 1, bytes });
162
+ }
163
+ if (!reportTimer) {
164
+ reportTimer = setInterval(reportTraffic, TRAFFIC_REPORT_MS);
165
+ reportTimer.unref?.();
166
+ }
167
+ }
168
+
169
+ /** Bytes sent per action since the last report (before compression), largest first. */
170
+ export function takeTrafficReport(): Array<{ action: string; frames: number; bytes: number }> {
171
+ const rows = [...traffic.entries()]
172
+ .map(([action, entry]) => ({ action, ...entry }))
173
+ .sort((a, b) => b.bytes - a.bytes);
174
+ traffic.clear();
175
+ return rows;
176
+ }
177
+
178
+ function reportTraffic(): void {
179
+ const rows = takeTrafficReport();
180
+ if (rows.length === 0) return;
181
+ const total = rows.reduce((sum, row) => sum + row.bytes, 0);
182
+ const lines = rows
183
+ .slice(0, 15)
184
+ .map((row) => ` ${(row.bytes / 1024).toFixed(1).padStart(10)} KB ${String(row.frames).padStart(6)}× ${row.action}`);
185
+ debug.log(
186
+ 'websocket',
187
+ `WS traffic, last ${TRAFFIC_REPORT_MS / 1000}s: ${(total / 1024).toFixed(1)} KB before compression\n${lines.join('\n')}`
188
+ );
189
+ }