@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
@@ -1134,6 +1134,65 @@ export function hostBridgeScript(bindingName: string) {
1134
1134
  );
1135
1135
  }
1136
1136
 
1137
+ // A copy that never touches `navigator.clipboard` — Ctrl/⌘+C, a "Copy"
1138
+ // button built on `execCommand('copy')` — only ever reached the headless
1139
+ // clipboard. The copy event is the one place all of them pass through, so
1140
+ // what it copies is reported to the workspace clipboard from here.
1141
+ //
1142
+ // What a copy puts on the clipboard is decided by the page's own handlers:
1143
+ // `clipboardData.setData` if one calls it, the selection otherwise, nothing
1144
+ // if one cancels without setting data. Those handlers run after this
1145
+ // capture listener, so the selection is read now, `setData` is recorded as
1146
+ // it happens, and the outcome is settled once the event has finished.
1147
+ let pendingCopy: { selection: string; data: string | null; event: Event } | null = null;
1148
+
1149
+ const readSelection = (): string => {
1150
+ let active: Element | null = document.activeElement;
1151
+ while (active && (active as HTMLElement).shadowRoot?.activeElement) {
1152
+ active = (active as HTMLElement).shadowRoot!.activeElement;
1153
+ }
1154
+ const field = active as HTMLInputElement | HTMLTextAreaElement | null;
1155
+ if (field && (field.tagName === 'INPUT' || field.tagName === 'TEXTAREA')) {
1156
+ try {
1157
+ const start = field.selectionStart ?? 0;
1158
+ const end = field.selectionEnd ?? 0;
1159
+ if (end > start) return field.value.slice(start, end);
1160
+ } catch {
1161
+ // Input types without selection (email, number) — fall through.
1162
+ }
1163
+ }
1164
+ return window.getSelection()?.toString() ?? '';
1165
+ };
1166
+
1167
+ const onCopy = (event: Event) => {
1168
+ pendingCopy = { selection: readSelection(), data: null, event };
1169
+ setTimeout(() => {
1170
+ const copy = pendingCopy;
1171
+ pendingCopy = null;
1172
+ if (!copy) return;
1173
+ const text = copy.data ?? (copy.event.defaultPrevented ? null : copy.selection);
1174
+ if (text) void call('clipboard-copied', { text }).catch(() => {});
1175
+ }, 0);
1176
+ };
1177
+ window.addEventListener('copy', onCopy, true);
1178
+ window.addEventListener('cut', onCopy, true);
1179
+
1180
+ const DataTransferProto = (scope.DataTransfer as typeof DataTransfer | undefined)?.prototype;
1181
+ if (DataTransferProto) {
1182
+ const originalSetData = DataTransferProto.setData;
1183
+ define(
1184
+ DataTransferProto,
1185
+ 'setData',
1186
+ nativeLike(function setData(this: DataTransfer, format: string, data: string) {
1187
+ const kind = String(format).toLowerCase();
1188
+ if (pendingCopy && (kind === 'text/plain' || kind === 'text')) {
1189
+ pendingCopy.data = String(data);
1190
+ }
1191
+ return originalSetData.call(this, format, data);
1192
+ } as never, 'setData')
1193
+ );
1194
+ }
1195
+
1137
1196
  // ── Notifications ───────────────────────────────────────────────────────
1138
1197
  const NativeNotification = scope.Notification as (typeof Notification) | undefined;
1139
1198
  if (NativeNotification) {
@@ -814,6 +814,61 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
814
814
  }, NATIVE_TOP_OFF_DELAY_MS);
815
815
  }
816
816
 
817
+ // ------------------------------------------------------------------
818
+ // Surface drift
819
+ // ------------------------------------------------------------------
820
+ //
821
+ // The captured surface is not guaranteed to stay the shape of the page.
822
+ // Chrome's own fullscreen (a <video> control, a fullscreen granted from
823
+ // C++, an embed the shim cannot reach) resizes the surface it composites
824
+ // to the browser window and leaves it there afterwards: a 1440×900 page
825
+ // came back captured at 1366×681. The layout viewport never changes, so the
826
+ // page is cropped and zoomed, and the frames — the wrong shape — reached
827
+ // the viewer letterboxed, then snapped back when something re-asserted the
828
+ // viewport. That alternation was the flicker.
829
+ //
830
+ // The page's own viewport is the authority: it stays at the emulated size
831
+ // throughout. A frame whose aspect disagrees with it is never encoded (the
832
+ // viewer keeps the last good frame, and the encoder and the viewer's
833
+ // canvas are never resized to a shape that is about to go away), and once
834
+ // the disagreement has lasted past a short grace the host is asked to
835
+ // re-assert the viewport. Should that keep failing, frames are let through
836
+ // rather than freezing the preview on a surface nobody can fix.
837
+ const DRIFT_TOLERANCE = 0.03;
838
+ const DRIFT_GRACE_MS = 250;
839
+ const DRIFT_RESTORE_COOLDOWN_MS = 1500;
840
+ const DRIFT_MAX_RESTORES = 3;
841
+ let driftSince = 0;
842
+ let lastDriftReport = 0;
843
+ let driftReports = 0;
844
+
845
+ function surfaceDrifted(width: number, height: number): boolean {
846
+ const viewportWidth = window.innerWidth;
847
+ const viewportHeight = window.innerHeight;
848
+ if (!width || !height || !viewportWidth || !viewportHeight) return false;
849
+
850
+ const expected = viewportWidth / viewportHeight;
851
+ const drifted = Math.abs(width / height - expected) / expected > DRIFT_TOLERANCE;
852
+ if (!drifted) {
853
+ driftSince = 0;
854
+ driftReports = 0;
855
+ return false;
856
+ }
857
+
858
+ const now = performance.now();
859
+ if (!driftSince) driftSince = now;
860
+ if (driftReports >= DRIFT_MAX_RESTORES) return false;
861
+
862
+ if (now - driftSince >= DRIFT_GRACE_MS && now - lastDriftReport >= DRIFT_RESTORE_COOLDOWN_MS) {
863
+ lastDriftReport = now;
864
+ driftReports++;
865
+ try {
866
+ (window as any).__reportSurfaceDrift?.(width, height);
867
+ } catch (e) {}
868
+ }
869
+ return true;
870
+ }
871
+
817
872
  async function readNativeFrames() {
818
873
  if (!nativeReader) return;
819
874
 
@@ -847,6 +902,9 @@ export function videoEncoderScript(config: StreamingConfig['video']) {
847
902
 
848
903
  if (shouldSkipMotionFrame()) continue;
849
904
 
905
+ // Wrong shape: stranded by a Chrome fullscreen. Not encoded.
906
+ if (surfaceDrifted(frame.displayWidth, frame.displayHeight)) continue;
907
+
850
908
  if (!(await ensureEncoderSize(frame.displayWidth, frame.displayHeight))) continue;
851
909
 
852
910
  const costStart = performance.now();
@@ -1,8 +1,14 @@
1
1
  import type { Browser, BrowserContext, Page } from 'puppeteer';
2
- import type { DeviceSize, Rotation } from '$shared/constants/preview.js';
2
+ import type {
3
+ DeviceEmulationOverrides,
4
+ DeviceSize,
5
+ PageColors,
6
+ Rotation,
7
+ ViewportSize
8
+ } from '$shared/constants/preview.js';
3
9
 
4
10
  // Re-export types from preview config
5
- export type { DeviceSize, Rotation };
11
+ export type { DeviceEmulationOverrides, DeviceSize, PageColors, Rotation, ViewportSize };
6
12
 
7
13
  /**
8
14
  * A console argument rendered for display.
@@ -87,6 +93,26 @@ export interface BrowserTab {
87
93
  // Device
88
94
  deviceSize: DeviceSize;
89
95
  rotation: Rotation;
96
+ /**
97
+ * The size the page is laid out at, already facing `rotation`.
98
+ *
99
+ * The one source for it: a preset, a typed size and a drag all land here,
100
+ * and everything that sets the browser's viewport reads it back from here
101
+ * rather than recomputing it from the device class.
102
+ */
103
+ viewport: ViewportSize;
104
+ /**
105
+ * The device model the tab is shown on — which mockup the viewer draws.
106
+ * Null for `responsive`, which has none.
107
+ */
108
+ deviceModel: string | null;
109
+ /** Device settings set on top of the model; empty means the device's own. */
110
+ emulation: DeviceEmulationOverrides;
111
+ /**
112
+ * The colours the page asks to be framed in, last read from its DOM.
113
+ * Painted into the system bands around it by the viewer.
114
+ */
115
+ pageColors?: PageColors;
90
116
 
91
117
  // Console
92
118
  consoleLogs: BrowserConsoleMessage[];
@@ -121,6 +147,14 @@ export interface BrowserTab {
121
147
  createdAt: number;
122
148
  lastAccessedAt: number;
123
149
 
150
+ /**
151
+ * Who opened the tab. An agent is expected to close the tabs it opens once
152
+ * it is done with them, so the tabs it still has open are listed back to it
153
+ * in every report; a tab the user opened is never its to close unasked.
154
+ * Absent means the user (or a tab from before this was recorded).
155
+ */
156
+ openedBy?: { kind: 'agent'; chatSessionId: string } | { kind: 'user' };
157
+
124
158
  // Internal
125
159
  isDestroyed?: boolean;
126
160
  /**
@@ -207,6 +241,10 @@ export interface BrowserTabInfo {
207
241
  isStreaming: boolean;
208
242
  deviceSize: DeviceSize;
209
243
  rotation: Rotation;
244
+ width: number;
245
+ height: number;
246
+ deviceModel: string | null;
247
+ emulation: DeviceEmulationOverrides;
210
248
  isActive: boolean;
211
249
  canGoBack: boolean;
212
250
  canGoForward: boolean;
@@ -0,0 +1,45 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { mergeEmulation, viewportFor } from './viewport';
3
+
4
+ describe('mergeEmulation', () => {
5
+ test('left-out fields keep their value, null hands them back to the device', () => {
6
+ const current = { touch: false, colorScheme: 'dark' as const };
7
+ expect(mergeEmulation(current, { reducedMotion: 'reduce', colorScheme: null })).toEqual({
8
+ touch: false,
9
+ reducedMotion: 'reduce'
10
+ });
11
+ expect(mergeEmulation(current, null)).toBe(current);
12
+ });
13
+ });
14
+
15
+ describe('viewportFor', () => {
16
+ test('handheld classes are touch and mobile by default', () => {
17
+ expect(viewportFor({ deviceSize: 'mobile', viewport: { width: 402, height: 874 } })).toEqual({
18
+ width: 402,
19
+ height: 874,
20
+ deviceScaleFactor: 1,
21
+ isMobile: true,
22
+ hasTouch: true,
23
+ isLandscape: false
24
+ });
25
+ });
26
+
27
+ test('overrides win over the class', () => {
28
+ const touchLaptop = viewportFor({
29
+ deviceSize: 'laptop',
30
+ viewport: { width: 1440, height: 900 },
31
+ emulation: { touch: true }
32
+ });
33
+ expect(touchLaptop.hasTouch).toBe(true);
34
+ expect(touchLaptop.isMobile).toBe(false);
35
+ expect(touchLaptop.isLandscape).toBe(true);
36
+
37
+ const desktopModePhone = viewportFor({
38
+ deviceSize: 'mobile',
39
+ viewport: { width: 402, height: 874 },
40
+ emulation: { mobile: false }
41
+ });
42
+ expect(desktopModePhone.isMobile).toBe(false);
43
+ expect(desktopModePhone.hasTouch).toBe(true);
44
+ });
45
+ });
@@ -0,0 +1,96 @@
1
+ import type { Page, Viewport } from 'puppeteer';
2
+ import {
3
+ getDeviceEmulation,
4
+ type DeviceEmulationOverrides,
5
+ type DeviceSize,
6
+ type ViewportSize
7
+ } from '$shared/constants/preview.js';
8
+ import { debug } from '$shared/utils/logger';
9
+
10
+ /** What a tab's page is emulated as: its class, its size and any device settings on top. */
11
+ export interface EmulatedDevice {
12
+ deviceSize: DeviceSize;
13
+ viewport: ViewportSize;
14
+ emulation?: DeviceEmulationOverrides;
15
+ }
16
+
17
+ /**
18
+ * A change to a tab's device settings. A field left out keeps its value;
19
+ * `null` puts it back to what the device would do.
20
+ */
21
+ export type EmulationPatch = {
22
+ [K in keyof DeviceEmulationOverrides]?: DeviceEmulationOverrides[K] | null;
23
+ };
24
+
25
+ export function mergeEmulation(
26
+ current: DeviceEmulationOverrides,
27
+ patch: EmulationPatch | null | undefined
28
+ ): DeviceEmulationOverrides {
29
+ if (!patch) return current;
30
+ const next: DeviceEmulationOverrides = { ...current };
31
+ for (const key of Object.keys(patch) as Array<keyof DeviceEmulationOverrides>) {
32
+ const value = patch[key];
33
+ if (value === undefined) continue;
34
+ if (value === null) delete next[key];
35
+ else (next as Record<string, unknown>)[key] = value;
36
+ }
37
+ return next;
38
+ }
39
+
40
+ /**
41
+ * The full viewport override a tab's page runs under.
42
+ *
43
+ * Every `setViewport` goes through here. Puppeteer replaces the whole override
44
+ * on each call, so a caller that passed only a width and a height — a hot-swap,
45
+ * a restore after fullscreen — silently turned a phone back into a desktop.
46
+ */
47
+ export function viewportFor(device: EmulatedDevice): Viewport {
48
+ const { isMobile, hasTouch } = getDeviceEmulation(device.deviceSize, device.emulation);
49
+ return {
50
+ width: device.viewport.width,
51
+ height: device.viewport.height,
52
+ deviceScaleFactor: 1,
53
+ isMobile,
54
+ hasTouch,
55
+ isLandscape: device.viewport.width > device.viewport.height
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Apply a tab's emulation to its page.
61
+ *
62
+ * Turning touch or the mobile viewport on or off makes Puppeteer reload the
63
+ * page: both are fixed when a document is created, so a page that has already
64
+ * run its feature detection would carry on with the old answers. That reload
65
+ * waits for `load`, and a slow page can outlast the navigation timeout — by
66
+ * which point the override has already been applied, so the timeout is not a
67
+ * failure of this call.
68
+ */
69
+ export async function applyViewport(page: Page, device: EmulatedDevice): Promise<void> {
70
+ try {
71
+ await page.setViewport(viewportFor(device));
72
+ } catch (error) {
73
+ if (error instanceof Error && error.name === 'TimeoutError') {
74
+ debug.warn('preview', `⏱️ Reload after an emulation change outlasted its timeout; the viewport is applied`);
75
+ return;
76
+ }
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Apply the media-query side of a tab's device settings. An empty value hands
83
+ * the feature back to the browser, so clearing an override is the same call.
84
+ */
85
+ export async function applyMediaEmulation(page: Page, emulation: DeviceEmulationOverrides | undefined): Promise<void> {
86
+ await page.emulateMediaFeatures([
87
+ { name: 'prefers-color-scheme', value: emulation?.colorScheme ?? '' },
88
+ { name: 'prefers-reduced-motion', value: emulation?.reducedMotion ?? '' }
89
+ ]);
90
+ }
91
+
92
+ /** Everything a page needs to look like its tab's device. */
93
+ export async function applyDevice(page: Page, device: EmulatedDevice): Promise<void> {
94
+ await applyViewport(page, device);
95
+ await applyMediaEmulation(page, device.emulation);
96
+ }
@@ -100,7 +100,7 @@ export function artifactFilter(profileId: number | null | undefined, type: Profi
100
100
  }
101
101
 
102
102
  export const profileService = {
103
- /** All profiles (metadata + grouped items) for the admin listing. */
103
+ /** All profiles (metadata + grouped items) for the Settings listing. */
104
104
  list(): ProfileDTO[] {
105
105
  return profileQueries.getAll().map(r => toDTO(r.id)!).filter(Boolean);
106
106
  },
@@ -146,7 +146,7 @@ export const profileService = {
146
146
  return inv;
147
147
  },
148
148
 
149
- /** Lightweight list for the non-admin per-session picker (id + name only). */
149
+ /** Lightweight list for the per-session picker (id + name only). */
150
150
  available(): { id: number; slug: string; name: string; description: string }[] {
151
151
  return profileQueries.getAll().map(r => ({ id: r.id, slug: r.slug, name: r.name, description: r.description }));
152
152
  }
@@ -4,7 +4,6 @@
4
4
  */
5
5
 
6
6
  import { streamManager, type StreamState } from '../chat/stream-manager.js';
7
- import { ws } from '../utils/ws.js';
8
7
  import { sessionQueries } from '../database/queries/session-queries.js';
9
8
  import type { UnifiedMessage } from '$shared/types/unified';
10
9
  import { isWaitingForInteractiveInput } from '$shared/utils/interactive-input';
@@ -41,190 +40,62 @@ function resolveStreamWorktreeId(chatSessionId: string, memo: Map<string, string
41
40
  return worktreeId;
42
41
  }
43
42
 
44
- // Store active users per project (shared with main endpoint)
45
- const projectUsers = new Map<string, Set<{ userId: string; userName: string; lastSeen: number }>>();
46
-
47
- // Cleanup inactive users after 5 minutes
48
- const USER_TIMEOUT = 5 * 60 * 1000;
43
+ function toStreamStatus(stream: StreamState, worktreeMemo: Map<string, string | null>) {
44
+ return {
45
+ streamId: stream.streamId,
46
+ chatSessionId: stream.chatSessionId,
47
+ worktreeId: resolveStreamWorktreeId(stream.chatSessionId, worktreeMemo),
48
+ status: stream.status,
49
+ startedAt: stream.startedAt,
50
+ messagesCount: stream.messages.length,
51
+ isWaitingInput: detectStreamWaitingInput(stream)
52
+ };
53
+ }
49
54
 
50
- function cleanupInactiveUsers() {
51
- const now = Date.now();
52
- projectUsers.forEach((users, projectId) => {
53
- const activeUsers = new Set([...users].filter(user => now - user.lastSeen < USER_TIMEOUT));
54
- if (activeUsers.size === 0) {
55
- projectUsers.delete(projectId);
56
- } else {
57
- projectUsers.set(projectId, activeUsers);
58
- }
59
- });
55
+ export interface ProjectStatusData {
56
+ projectId: string;
57
+ hasActiveStreams: boolean;
58
+ activeStreamCount: number;
59
+ streams: ReturnType<typeof toStreamStatus>[];
60
60
  }
61
61
 
62
- // Get project status data
63
- export async function getProjectStatusData(projectId?: string) {
64
- cleanupInactiveUsers();
65
-
62
+ // Get project status data: the chat streams running in a project (or in every
63
+ // project), which every device mirrors to show busy/waiting indicators.
64
+ export async function getProjectStatusData(projectId: string): Promise<ProjectStatusData>;
65
+ export async function getProjectStatusData(): Promise<ProjectStatusData[]>;
66
+ export async function getProjectStatusData(projectId?: string): Promise<ProjectStatusData | ProjectStatusData[]> {
67
+ const worktreeMemo = new Map<string, string | null>();
68
+
66
69
  if (projectId) {
67
- // Get status for specific project
68
70
  const allProjectStreams = streamManager.getProjectStreams(projectId);
69
- const users = projectUsers.get(projectId);
70
-
71
- // Filter to only count active streams
72
71
  const activeStreams = allProjectStreams.filter(s => s.status === 'active');
73
-
74
- // Get per-chat-session user presence from WS rooms
75
- const chatSessionUsers = ws.getProjectChatSessions(projectId);
76
- const worktreeMemo = new Map<string, string | null>();
77
-
78
72
  return {
79
73
  projectId,
80
74
  hasActiveStreams: activeStreams.length > 0,
81
75
  activeStreamCount: activeStreams.length,
82
- activeUsers: users ? [...users].map(u => ({
83
- userId: u.userId,
84
- userName: u.userName
85
- })) : [],
86
- streams: allProjectStreams.map(s => ({
87
- streamId: s.streamId,
88
- chatSessionId: s.chatSessionId,
89
- worktreeId: resolveStreamWorktreeId(s.chatSessionId, worktreeMemo),
90
- status: s.status,
91
- startedAt: s.startedAt,
92
- messagesCount: s.messages.length,
93
- isWaitingInput: detectStreamWaitingInput(s)
94
- })),
95
- chatSessionUsers: Object.fromEntries(
96
- Array.from(chatSessionUsers.entries()).map(([csId, csUsers]) => [
97
- csId,
98
- csUsers.map(u => {
99
- // Resolve userName from projectUsers
100
- const projectUser = users ? [...users].find(pu => pu.userId === u.userId) : undefined;
101
- return { userId: u.userId, userName: projectUser?.userName || u.userId };
102
- })
103
- ])
104
- )
76
+ streams: allProjectStreams.map(s => toStreamStatus(s, worktreeMemo))
105
77
  };
106
- } else {
107
- // Get status for all projects
108
- const allProjects = new Map<string, any>();
109
-
110
- // Get all active streams grouped by project
111
- const allStreams = streamManager.getAllStreams();
112
- const worktreeMemo = new Map<string, string | null>();
113
- allStreams.forEach(stream => {
114
- if (stream.projectId) {
115
- if (!allProjects.has(stream.projectId)) {
116
- allProjects.set(stream.projectId, {
117
- projectId: stream.projectId,
118
- hasActiveStreams: false,
119
- activeStreamCount: 0,
120
- activeUsers: [],
121
- streams: []
122
- });
123
- }
124
-
125
- const projectData = allProjects.get(stream.projectId);
126
- if (stream.status === 'active') {
127
- projectData.hasActiveStreams = true;
128
- projectData.activeStreamCount++;
129
- }
130
- projectData.streams.push({
131
- streamId: stream.streamId,
132
- chatSessionId: stream.chatSessionId,
133
- worktreeId: resolveStreamWorktreeId(stream.chatSessionId, worktreeMemo),
134
- status: stream.status,
135
- startedAt: stream.startedAt,
136
- messagesCount: stream.messages.length,
137
- isWaitingInput: detectStreamWaitingInput(stream)
138
- });
139
- }
140
- });
141
-
142
- // Add active users to each project
143
- projectUsers.forEach((users, projectId) => {
144
- if (!allProjects.has(projectId)) {
145
- allProjects.set(projectId, {
146
- projectId,
147
- hasActiveStreams: false,
148
- activeStreamCount: 0,
149
- activeUsers: [],
150
- streams: [],
151
- chatSessionUsers: {}
152
- });
153
- }
154
-
155
- const projectData = allProjects.get(projectId);
156
- projectData.activeUsers = [...users].map(u => ({
157
- userId: u.userId,
158
- userName: u.userName
159
- }));
160
- });
161
-
162
- // Add per-chat-session user presence to each project
163
- for (const [projectId, projectData] of allProjects) {
164
- const chatSessionUsers = ws.getProjectChatSessions(projectId);
165
- const users = projectUsers.get(projectId);
166
- projectData.chatSessionUsers = Object.fromEntries(
167
- Array.from(chatSessionUsers.entries()).map(([csId, csUsers]) => [
168
- csId,
169
- csUsers.map(u => {
170
- const projectUser = users ? [...users].find(pu => pu.userId === u.userId) : undefined;
171
- return { userId: u.userId, userName: projectUser?.userName || u.userId };
172
- })
173
- ])
174
- );
175
- }
176
-
177
- return [...allProjects.values()];
178
78
  }
179
- }
180
79
 
181
- /**
182
- * Drop in-memory presence for a project (e.g. after full project delete).
183
- */
184
- export function clearProjectPresence(projectId: string): void {
185
- projectUsers.delete(projectId);
186
- }
187
-
188
- // Update user presence
189
- export function updateUserPresence(projectId: string, userId: string, userName: string, action: string) {
190
- cleanupInactiveUsers();
191
-
192
- if (action === 'leave') {
193
- // Remove user from project
194
- const users = projectUsers.get(projectId);
195
- if (users) {
196
- const updatedUsers = new Set([...users].filter(u => u.userId !== userId));
197
- if (updatedUsers.size === 0) {
198
- projectUsers.delete(projectId);
199
- } else {
200
- projectUsers.set(projectId, updatedUsers);
201
- }
80
+ const allProjects = new Map<string, ProjectStatusData>();
81
+ for (const stream of streamManager.getAllStreams()) {
82
+ if (!stream.projectId) continue;
83
+ let projectData = allProjects.get(stream.projectId);
84
+ if (!projectData) {
85
+ projectData = {
86
+ projectId: stream.projectId,
87
+ hasActiveStreams: false,
88
+ activeStreamCount: 0,
89
+ streams: []
90
+ };
91
+ allProjects.set(stream.projectId, projectData);
202
92
  }
203
- } else {
204
- // Add or update user presence
205
- if (!projectUsers.has(projectId)) {
206
- projectUsers.set(projectId, new Set());
93
+ if (stream.status === 'active') {
94
+ projectData.hasActiveStreams = true;
95
+ projectData.activeStreamCount++;
207
96
  }
208
-
209
- const users = projectUsers.get(projectId)!;
210
- // Remove old entry if exists
211
- const updatedUsers = new Set([...users].filter(u => u.userId !== userId));
212
- // Add new entry with updated timestamp
213
- updatedUsers.add({
214
- userId,
215
- userName,
216
- lastSeen: Date.now()
217
- });
218
- projectUsers.set(projectId, updatedUsers);
97
+ projectData.streams.push(toStreamStatus(stream, worktreeMemo));
219
98
  }
220
-
221
- // Return current users for the project
222
- const currentUsers = projectUsers.get(projectId);
223
- return {
224
- projectId,
225
- activeUsers: currentUsers ? [...currentUsers].map(u => ({
226
- userId: u.userId,
227
- userName: u.userName
228
- })) : []
229
- };
230
- }
99
+
100
+ return [...allProjects.values()];
101
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Home workspace — one per install, for chatting with no project selected.
3
+ *
4
+ * Home is a real project row pointing at a real directory, because every
5
+ * engine needs a working directory and every chat path needs a project: the
6
+ * cheapest correct "no project" is a project nobody had to pick. The directory
7
+ * lives under Clopen's data dir (`home/`), so it is a scratch space and never
8
+ * somebody's repository.
9
+ *
10
+ * Created on demand and idempotent: the project list, a chat channel's `/home`
11
+ * and a first sign-in with no project all call `ensureHomeProject()`. The
12
+ * unique index on `(kind) WHERE kind = 'home'` makes two racing calls end with
13
+ * one Home.
14
+ */
15
+
16
+ import { mkdirSync } from 'fs';
17
+ import { join } from 'path';
18
+ import { projectQueries } from '$backend/database/queries';
19
+ import { getClopenDir } from '$backend/utils/paths';
20
+ import { HOME_PROJECT_NAME } from '$shared/utils/home-project';
21
+ import type { Project } from '$shared/types/database/schema';
22
+ import { debug } from '$shared/utils/logger';
23
+
24
+ export function getHomeDirectory(): string {
25
+ return join(getClopenDir(), 'home');
26
+ }
27
+
28
+ export function ensureHomeProject(): Project {
29
+ const existing = projectQueries.getHome();
30
+ const path = existing?.path ?? getHomeDirectory();
31
+ // Re-created every time: a "Clear All Data" or a hand-deleted folder must
32
+ // not leave the engine starting in a directory that is not there.
33
+ mkdirSync(path, { recursive: true });
34
+
35
+ if (existing) {
36
+ projectQueries.list(existing.id);
37
+ return existing;
38
+ }
39
+
40
+ const now = new Date().toISOString();
41
+ try {
42
+ const project = projectQueries.create({
43
+ name: HOME_PROJECT_NAME,
44
+ path,
45
+ created_at: now,
46
+ last_opened_at: now,
47
+ kind: 'home'
48
+ });
49
+ projectQueries.list(project.id);
50
+ debug.log('project', 'Created Home workspace');
51
+ return project;
52
+ } catch (error) {
53
+ // Lost a race with another tab: the other call's row is the Home.
54
+ const raced = projectQueries.getHome();
55
+ if (raced) {
56
+ projectQueries.list(raced.id);
57
+ return raced;
58
+ }
59
+ throw error;
60
+ }
61
+ }