@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
@@ -5,7 +5,7 @@
5
5
  * - Event-driven push model (no polling)
6
6
  * - Background processing that continues even when browser is closed
7
7
  * - Reconnection to active streams after browser refresh
8
- * - Multiple concurrent streams per user/session
8
+ * - Multiple concurrent streams per session
9
9
  */
10
10
 
11
11
  import { EventEmitter } from 'events';
@@ -48,6 +48,7 @@ import { buildMemoryContext, withMemoryContext } from '../memory/context';
48
48
  import { buildEngineHandoff, resolveBranchEngine, withHandoff } from './engine-handoff';
49
49
  import { resolveGitEnv } from '$backend/git/identity';
50
50
  import { debug } from '$shared/utils/logger';
51
+ import { attachSubmittedAnswers } from '$shared/utils/ask-user-question';
51
52
  import { DEFAULT_MODEL_ID, DEFAULT_MODEL_NAME } from '$shared/constants/engines';
52
53
 
53
54
  // ============================================================================
@@ -77,6 +78,13 @@ export interface StreamState {
77
78
  currentMessage?: UnifiedMessage;
78
79
  currentPartialText?: string;
79
80
  currentReasoningText?: string;
81
+ /**
82
+ * Which streamed block `currentPartialText` / `currentReasoningText` belong
83
+ * to. Bumped on every `start`, so a catch-up snapshot of one block can never
84
+ * be mistaken for the text of the next.
85
+ */
86
+ partialBlock?: number;
87
+ reasoningBlock?: number;
80
88
  error?: string;
81
89
  abortController?: AbortController;
82
90
  streamPromise?: Promise<void>;
@@ -95,6 +103,12 @@ export interface StreamState {
95
103
  preStreamSessionId?: string | null;
96
104
  hasCompactBoundary?: boolean;
97
105
  eventSeq: number;
106
+ /**
107
+ * AskUserQuestion answers the user submitted, keyed by tool_use id, held
108
+ * until the engine's tool_result for that id arrives and they are attached
109
+ * to it (see attachSubmittedAnswers).
110
+ */
111
+ submittedAnswers: Map<string, Record<string, string>>;
98
112
  }
99
113
 
100
114
  // ============================================================================
@@ -102,11 +116,7 @@ export interface StreamState {
102
116
  // ============================================================================
103
117
 
104
118
  /** Normalize raw UserMessage prompt from WS handler into a validated UserMessage */
105
- function convertRawPromptToUserMessage(
106
- rawPrompt: any,
107
- senderId?: string,
108
- senderName?: string,
109
- ): UserMessage {
119
+ function convertRawPromptToUserMessage(rawPrompt: any): UserMessage {
110
120
  const content: UserContentBlock[] = Array.isArray(rawPrompt?.content) && rawPrompt.content.length > 0
111
121
  ? rawPrompt.content as UserContentBlock[]
112
122
  : [{ type: 'text', text: '' }];
@@ -136,10 +146,6 @@ function convertRawPromptToUserMessage(
136
146
  toolUseId: rawPrompt?.parent?.toolUseId ?? rawPrompt?.parentToolUseId ?? null,
137
147
  },
138
148
  engine: engineObj,
139
- sender: {
140
- id: senderId || rawPrompt?.sender?.id || '',
141
- name: senderName || rawPrompt?.sender?.name || '',
142
- },
143
149
  content,
144
150
  synthetic: rawPrompt?.synthetic ?? false,
145
151
  };
@@ -412,7 +418,8 @@ class StreamManager extends EventEmitter {
412
418
  startedAt: new Date(),
413
419
  messages: [],
414
420
  abortController: new AbortController(),
415
- eventSeq: 0 // Initialize sequence for deduplication
421
+ eventSeq: 0, // Initialize sequence for deduplication
422
+ submittedAnswers: new Map()
416
423
  };
417
424
 
418
425
  this.activeStreams.set(streamId, streamState);
@@ -519,6 +526,22 @@ class StreamManager extends EventEmitter {
519
526
  // Emit to stream-specific channel only
520
527
  // (session channel removed to prevent duplicate dispatches)
521
528
  this.emit(`stream:${streamState.streamId}`, event);
529
+
530
+ // Messages also go out on one GLOBAL channel, exactly once per message.
531
+ // The per-stream channel above is only heard while some connection has
532
+ // bridged the stream into a room — and a bridge closes with its
533
+ // connection — so anything that must react to a message whether or not
534
+ // a tab is open (a question arriving after the user closed the browser
535
+ // is the whole point of a notification) listens here instead.
536
+ if (type === 'message') {
537
+ this.emit('stream:message', {
538
+ event,
539
+ streamId: streamState.streamId,
540
+ projectId: streamState.projectId,
541
+ chatSessionId: streamState.chatSessionId,
542
+ requestedByUserId: streamState.requestedByUserId
543
+ });
544
+ }
522
545
  }
523
546
 
524
547
  /**
@@ -569,7 +592,7 @@ class StreamManager extends EventEmitter {
569
592
  }
570
593
 
571
594
  try {
572
- const { projectPath, prompt: rawPrompt, chatSessionId, engine: requestEngine, sender: requestSender } = requestData;
595
+ const { projectPath, prompt: rawPrompt, chatSessionId, engine: requestEngine } = requestData;
573
596
 
574
597
  // Engine context that stream-manager injects into every SDK-emitted message.
575
598
  // (SDK adapters cannot know these values; only the request layer can.)
@@ -632,25 +655,26 @@ class StreamManager extends EventEmitter {
632
655
  streamState.preStreamSessionId = resumeSessionId ?? null;
633
656
 
634
657
  // Convert raw SDK prompt → UserMessage (unified)
635
- const userMessage = convertRawPromptToUserMessage(rawPrompt, requestSender.id, requestSender.name);
658
+ const userMessage = convertRawPromptToUserMessage(rawPrompt);
636
659
 
637
- // Save user message to DB
660
+ // Save user message to DB under the id the composer already shows it
661
+ // with, so its optimistic bubble names a real row from the start.
638
662
  const userMessageTimestamp = new Date().toISOString();
639
663
  const savedMessage = await this.saveMessage(
640
664
  userMessage,
641
665
  chatSessionId,
642
- userMessageTimestamp
666
+ userMessageTimestamp,
667
+ userMessage.messageId
643
668
  );
644
669
  userMessageId = savedMessage?.id;
670
+ if (savedMessage) this.emit('session:turn-started', chatSessionId);
645
671
 
646
672
  streamState.messages.push({
647
673
  processId: streamState.processId,
648
674
  message: userMessage as any,
649
675
  timestamp: userMessageTimestamp,
650
676
  message_id: savedMessage?.id,
651
- parent_message_id: savedMessage?.parent_message_id || null,
652
- sender_id: requestSender.id,
653
- sender_name: requestSender.name
677
+ parent_message_id: savedMessage?.parent_message_id || null
654
678
  });
655
679
 
656
680
  this.emitStreamEvent(streamState, 'message', {
@@ -658,9 +682,7 @@ class StreamManager extends EventEmitter {
658
682
  message: userMessage,
659
683
  timestamp: userMessageTimestamp,
660
684
  message_id: savedMessage?.id,
661
- parent_message_id: savedMessage?.parent_message_id || null,
662
- sender_id: requestSender.id,
663
- sender_name: requestSender.name
685
+ parent_message_id: savedMessage?.parent_message_id || null
664
686
  });
665
687
 
666
688
  if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
@@ -894,13 +916,10 @@ class StreamManager extends EventEmitter {
894
916
  ...(projectId && chatSessionId && {
895
917
  mcpContext: { projectId, chatSessionId, streamId: streamState.streamId, ...(activeProfileId != null && { profileId: activeProfileId }) }
896
918
  }),
897
- // The agent commits as the person who asked it to. Resolved here
898
- // because this is the only layer that knows both the project and
899
- // the requester; omitted when either is missing, which leaves git
900
- // behaving exactly as it did before identities existed.
901
- ...(projectId && streamState.requestedByUserId && {
902
- gitIdentityEnv: resolveGitEnv(projectId, streamState.requestedByUserId)
903
- }),
919
+ // The agent commits as the project's git identity; with none chosen
920
+ // the fragment is empty and git behaves exactly as it did before
921
+ // identities existed.
922
+ ...(projectId && { gitIdentityEnv: resolveGitEnv(projectId) }),
904
923
  });
905
924
 
906
925
  await projectContextService.runWithContextAsync(
@@ -1000,9 +1019,7 @@ class StreamManager extends EventEmitter {
1000
1019
  message: boundary,
1001
1020
  timestamp: compactTimestamp,
1002
1021
  message_id: savedCompactId,
1003
- parent_message_id: savedCompactParentId,
1004
- sender_id: requestSender.id,
1005
- sender_name: requestSender.name
1022
+ parent_message_id: savedCompactParentId
1006
1023
  });
1007
1024
  continue;
1008
1025
  }
@@ -1072,9 +1089,7 @@ class StreamManager extends EventEmitter {
1072
1089
  message: patched,
1073
1090
  timestamp: patched.createdAt,
1074
1091
  message_id: lastEntry?.message_id ?? undefined,
1075
- parent_message_id: lastEntry?.parent_message_id ?? null,
1076
- sender_id: requestSender.id,
1077
- sender_name: requestSender.name
1092
+ parent_message_id: lastEntry?.parent_message_id ?? null
1078
1093
  });
1079
1094
  }
1080
1095
  }
@@ -1083,7 +1098,7 @@ class StreamManager extends EventEmitter {
1083
1098
  // usage:null. Backfill the turn's aggregate to every saved
1084
1099
  // assistant without usage so it survives a refresh.
1085
1100
  if (successResult.usage && (streamState.engine === 'codex' || streamState.engine === 'cursor')) {
1086
- this.backfillUsageForStream(streamState, successResult.usage, requestSender);
1101
+ this.backfillUsageForStream(streamState, successResult.usage);
1087
1102
  }
1088
1103
  } else {
1089
1104
  const errResult = output as ErrorResultEvent;
@@ -1098,17 +1113,28 @@ class StreamManager extends EventEmitter {
1098
1113
  case 'stream_event': {
1099
1114
  const streamEvt = output as UnifiedStreamEvent;
1100
1115
 
1116
+ // Partials carry the DELTA, not the text so far. Re-sending the
1117
+ // whole accumulated text on every token made a turn cost the sum
1118
+ // of all its prefixes — quadratic in its length, ~115× the text
1119
+ // itself on real chats. `offset` (the length before this delta)
1120
+ // and `block` let a client that joins mid-block or misses a frame
1121
+ // tell exactly what it has and resync instead of guessing; `end`
1122
+ // still carries the full text once, as the reconciliation point.
1101
1123
  if (streamEvt.event === 'start') {
1102
1124
  const lifecycle = streamEvt as StreamLifecycleEvent;
1125
+ let block: number;
1103
1126
  if (lifecycle.reasoning) {
1104
1127
  streamState.currentReasoningText = '';
1128
+ block = streamState.reasoningBlock = (streamState.reasoningBlock ?? 0) + 1;
1105
1129
  } else {
1106
1130
  streamState.currentPartialText = '';
1131
+ block = streamState.partialBlock = (streamState.partialBlock ?? 0) + 1;
1107
1132
  }
1108
1133
  this.emitStreamEvent(streamState, 'partial', {
1109
1134
  processId: streamState.processId,
1110
1135
  eventType: 'start',
1111
- partialText: '',
1136
+ block,
1137
+ offset: 0,
1112
1138
  deltaText: '',
1113
1139
  ...(lifecycle.reasoning && { reasoning: true }),
1114
1140
  timestamp: new Date().toISOString()
@@ -1116,21 +1142,25 @@ class StreamManager extends EventEmitter {
1116
1142
  } else if (streamEvt.event === 'delta') {
1117
1143
  const delta = streamEvt as TextDeltaEvent;
1118
1144
  if (delta.reasoning) {
1119
- streamState.currentReasoningText = (streamState.currentReasoningText || '') + delta.text;
1145
+ const before = streamState.currentReasoningText || '';
1146
+ streamState.currentReasoningText = before + delta.text;
1120
1147
  this.emitStreamEvent(streamState, 'partial', {
1121
1148
  processId: streamState.processId,
1122
1149
  eventType: 'update',
1123
- partialText: streamState.currentReasoningText,
1150
+ block: streamState.reasoningBlock ?? 0,
1151
+ offset: before.length,
1124
1152
  deltaText: delta.text,
1125
1153
  reasoning: true,
1126
1154
  timestamp: new Date().toISOString()
1127
1155
  });
1128
1156
  } else {
1129
- streamState.currentPartialText = (streamState.currentPartialText || '') + delta.text;
1157
+ const before = streamState.currentPartialText || '';
1158
+ streamState.currentPartialText = before + delta.text;
1130
1159
  this.emitStreamEvent(streamState, 'partial', {
1131
1160
  processId: streamState.processId,
1132
1161
  eventType: 'update',
1133
- partialText: streamState.currentPartialText,
1162
+ block: streamState.partialBlock ?? 0,
1163
+ offset: before.length,
1134
1164
  deltaText: delta.text,
1135
1165
  timestamp: new Date().toISOString()
1136
1166
  });
@@ -1141,6 +1171,7 @@ class StreamManager extends EventEmitter {
1141
1171
  this.emitStreamEvent(streamState, 'partial', {
1142
1172
  processId: streamState.processId,
1143
1173
  eventType: 'end',
1174
+ block: streamState.reasoningBlock ?? 0,
1144
1175
  partialText: streamState.currentReasoningText,
1145
1176
  deltaText: '',
1146
1177
  reasoning: true,
@@ -1151,6 +1182,7 @@ class StreamManager extends EventEmitter {
1151
1182
  this.emitStreamEvent(streamState, 'partial', {
1152
1183
  processId: streamState.processId,
1153
1184
  eventType: 'end',
1185
+ block: streamState.partialBlock ?? 0,
1154
1186
  partialText: streamState.currentPartialText || '',
1155
1187
  deltaText: '',
1156
1188
  timestamp: new Date().toISOString()
@@ -1163,7 +1195,9 @@ class StreamManager extends EventEmitter {
1163
1195
  // ── Reasoning Message ──────────────────────────────────
1164
1196
  case 'reasoning': {
1165
1197
  const reasoning = enrichMessageEngine(output, engineCtx) as ReasoningMessage;
1166
- streamState.currentReasoningText = undefined;
1198
+ // Only a root message settles the root's live text — a sub-agent's
1199
+ // (parent-tagged) one finishing must not wipe the main turn's partial.
1200
+ if (!reasoning.parent.toolUseId) streamState.currentReasoningText = undefined;
1167
1201
 
1168
1202
  const reasoningTimestamp = reasoning.createdAt;
1169
1203
  let savedReasoningId: string | undefined;
@@ -1183,9 +1217,7 @@ class StreamManager extends EventEmitter {
1183
1217
  message: reasoning,
1184
1218
  timestamp: reasoningTimestamp,
1185
1219
  message_id: savedReasoningId,
1186
- parent_message_id: savedReasoningParentId,
1187
- sender_id: requestSender.id,
1188
- sender_name: requestSender.name
1220
+ parent_message_id: savedReasoningParentId
1189
1221
  });
1190
1222
  continue;
1191
1223
  }
@@ -1220,7 +1252,7 @@ class StreamManager extends EventEmitter {
1220
1252
  savedParentId = saved?.parent_message_id || null;
1221
1253
  }
1222
1254
 
1223
- streamState.currentPartialText = undefined;
1255
+ if (!assistantMsg.parent.toolUseId) streamState.currentPartialText = undefined;
1224
1256
 
1225
1257
  streamState.messages.push({
1226
1258
  processId: streamState.processId,
@@ -1228,9 +1260,7 @@ class StreamManager extends EventEmitter {
1228
1260
  usage: usage as any,
1229
1261
  timestamp: messageTimestamp,
1230
1262
  message_id: savedMsgId,
1231
- parent_message_id: savedParentId,
1232
- sender_id: requestSender.id,
1233
- sender_name: requestSender.name
1263
+ parent_message_id: savedParentId
1234
1264
  });
1235
1265
 
1236
1266
  streamState.currentMessage = assistantMsg;
@@ -1241,9 +1271,7 @@ class StreamManager extends EventEmitter {
1241
1271
  usage,
1242
1272
  timestamp: messageTimestamp,
1243
1273
  message_id: savedMsgId,
1244
- parent_message_id: savedParentId,
1245
- sender_id: requestSender.id,
1246
- sender_name: requestSender.name
1274
+ parent_message_id: savedParentId
1247
1275
  });
1248
1276
  continue;
1249
1277
  }
@@ -1252,6 +1280,7 @@ class StreamManager extends EventEmitter {
1252
1280
  case 'user': {
1253
1281
  const userMsg = enrichMessageEngine(output, engineCtx) as UserMessage;
1254
1282
  lastAssistantTextContent = null; // Reset dedup tracker
1283
+ attachSubmittedAnswers(userMsg, streamState.submittedAnswers);
1255
1284
 
1256
1285
  const messageTimestamp = userMsg.createdAt;
1257
1286
  let savedMsgId: string | undefined;
@@ -1271,9 +1300,7 @@ class StreamManager extends EventEmitter {
1271
1300
  message: userMsg as any,
1272
1301
  timestamp: messageTimestamp,
1273
1302
  message_id: savedMsgId,
1274
- parent_message_id: savedParentId,
1275
- sender_id: requestSender.id,
1276
- sender_name: requestSender.name
1303
+ parent_message_id: savedParentId
1277
1304
  });
1278
1305
 
1279
1306
  streamState.currentMessage = userMsg;
@@ -1283,9 +1310,7 @@ class StreamManager extends EventEmitter {
1283
1310
  message: userMsg,
1284
1311
  timestamp: messageTimestamp,
1285
1312
  message_id: savedMsgId,
1286
- parent_message_id: savedParentId,
1287
- sender_id: requestSender.id,
1288
- sender_name: requestSender.name
1313
+ parent_message_id: savedParentId
1289
1314
  });
1290
1315
  continue;
1291
1316
  }
@@ -1351,8 +1376,6 @@ class StreamManager extends EventEmitter {
1351
1376
  timestamp: errorTimestamp,
1352
1377
  message_id: savedErrorMsgId,
1353
1378
  parent_message_id: savedErrorParentId,
1354
- sender_id: requestData.sender.id,
1355
- sender_name: requestData.sender.name,
1356
1379
  });
1357
1380
 
1358
1381
  this.emitStreamEvent(streamState, 'error', {
@@ -1481,7 +1504,11 @@ class StreamManager extends EventEmitter {
1481
1504
  }
1482
1505
 
1483
1506
  debug.log('chat', 'Resolving AskUserQuestion answer:', { toolUseId, answers });
1484
- return engine.resolveUserAnswer(toolUseId, answers);
1507
+ // Recorded first: an engine may emit the tool_result before this returns.
1508
+ streamState.submittedAnswers.set(toolUseId, answers);
1509
+ const handled = engine.resolveUserAnswer(toolUseId, answers);
1510
+ if (!handled) streamState.submittedAnswers.delete(toolUseId);
1511
+ return handled;
1485
1512
  }
1486
1513
 
1487
1514
  async cancelStream(streamId: string, reason?: string): Promise<boolean> {
@@ -1681,7 +1708,8 @@ class StreamManager extends EventEmitter {
1681
1708
  private async saveMessage(
1682
1709
  message: UnifiedMessage,
1683
1710
  sessionId: string,
1684
- timestamp: string
1711
+ timestamp: string,
1712
+ preferredId?: string
1685
1713
  ): Promise<DatabaseMessage | null> {
1686
1714
  try {
1687
1715
  const currentHead = sessionQueries.getHead(sessionId);
@@ -1690,7 +1718,8 @@ class StreamManager extends EventEmitter {
1690
1718
  session_id: sessionId,
1691
1719
  message: message,
1692
1720
  timestamp,
1693
- parent_message_id: currentHead || undefined
1721
+ parent_message_id: currentHead || undefined,
1722
+ preferred_id: preferredId
1694
1723
  });
1695
1724
 
1696
1725
  sessionQueries.updateHead(sessionId, savedMessage.id);
@@ -1700,8 +1729,6 @@ class StreamManager extends EventEmitter {
1700
1729
  const text = extractMessageText(message);
1701
1730
  const updateOpts: Parameters<typeof sessionQueries.updateOnMessage>[1] = {
1702
1731
  messageType: message.type,
1703
- senderId: message.type === 'user' ? message.sender?.id : undefined,
1704
- senderName: message.type === 'user' ? message.sender?.name : undefined,
1705
1732
  timestamp,
1706
1733
  };
1707
1734
 
@@ -1804,7 +1831,6 @@ class StreamManager extends EventEmitter {
1804
1831
  private backfillUsageForStream(
1805
1832
  streamState: StreamState,
1806
1833
  usage: TokenUsage,
1807
- requestSender: StreamRequest['sender'],
1808
1834
  ): void {
1809
1835
  try {
1810
1836
  const { getDatabase } = require('../database');
@@ -1835,8 +1861,6 @@ class StreamManager extends EventEmitter {
1835
1861
  timestamp: patched.createdAt,
1836
1862
  message_id: entry.message_id,
1837
1863
  parent_message_id: entry.parent_message_id ?? null,
1838
- sender_id: requestSender.id,
1839
- sender_name: requestSender.name,
1840
1864
  });
1841
1865
  }
1842
1866
  } catch (err) {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * What a turn's "answer" is, read back from the stored chain: the last text,
3
+ * the failure apart from it, and a turn that opened with only a photo.
4
+ */
5
+
6
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
7
+ import { initializeDatabase, closeDatabase } from '$backend/database';
8
+ import { messageQueries, projectQueries, sessionQueries } from '$backend/database/queries';
9
+ import type { UnifiedMessage } from '$shared/types/unified';
10
+ import { lastTurnAnswer } from './turn-answer';
11
+
12
+ let projectId: string;
13
+
14
+ function chain(sessionId: string, messages: UnifiedMessage[]): string[] {
15
+ const ids: string[] = [];
16
+ let parent: string | undefined;
17
+ for (const message of messages) {
18
+ const row = messageQueries.create({ session_id: sessionId, message, parent_message_id: parent });
19
+ parent = row.id;
20
+ ids.push(row.id);
21
+ sessionQueries.updateHead(sessionId, row.id);
22
+ }
23
+ return ids;
24
+ }
25
+
26
+ const base = { createdAt: '', messageId: '', sessionId: null, parent: { messageId: null, sessionId: null, toolUseId: null } };
27
+ const engine = { type: 'claude-code', provider: '', model: { id: '', name: '' }, account: { id: 0, name: '' } };
28
+ const user = (content: unknown[]) => ({ ...base, type: 'user', engine, content }) as unknown as UnifiedMessage;
29
+ const assistant = (text: string) => ({ ...base, type: 'assistant', engine, content: [{ type: 'text', text }], stopReason: null, usage: null }) as unknown as UnifiedMessage;
30
+
31
+ function newSession(): string {
32
+ return sessionQueries.create({ project_id: projectId, engine: 'claude-code', started_at: new Date().toISOString() } as never).id;
33
+ }
34
+
35
+ beforeAll(async () => {
36
+ await initializeDatabase();
37
+ projectId = projectQueries.create({ name: 'turn-answer', path: `/tmp/turn-answer-${crypto.randomUUID()}`, created_at: new Date().toISOString(), last_opened_at: new Date().toISOString() } as never).id;
38
+ });
39
+
40
+ afterAll(() => {
41
+ sessionQueries.deleteAllByProjectId(projectId);
42
+ projectQueries.deleteProject(projectId);
43
+ closeDatabase();
44
+ });
45
+
46
+ describe('lastTurnAnswer', () => {
47
+ it('is the last text of the turn, with the turn’s own user message', () => {
48
+ const session = newSession();
49
+ const [, , ask] = chain(session, [user([{ type: 'text', text: 'one' }]), assistant('first'), user([{ type: 'text', text: 'two' }]), assistant('looking…'), assistant('second')]);
50
+ expect(lastTurnAnswer(session)).toMatchObject({ text: 'second', error: null, userMessageId: ask });
51
+ });
52
+
53
+ it('keeps a failure apart from what the turn said before it', () => {
54
+ const session = newSession();
55
+ chain(session, [user([{ type: 'text', text: 'do it' }]), assistant('half done'), assistant('**Error:** rate limited')]);
56
+ expect(lastTurnAnswer(session)).toMatchObject({ text: 'half done', error: 'rate limited' });
57
+ });
58
+
59
+ it('stops at a turn that opened with only a photo, never reaching the turn before', () => {
60
+ const session = newSession();
61
+ const ids = chain(session, [user([{ type: 'text', text: 'one' }]), assistant('first'), user([{ type: 'image', mediaType: 'image/png', data: 'AAAA' }])]);
62
+ expect(lastTurnAnswer(session)).toMatchObject({ text: '', userMessageId: ids[2] });
63
+ });
64
+ });
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The answer a turn ended with — what a chat app shows as "the reply".
3
+ *
4
+ * A turn is a user message followed by assistant messages, tool calls and tool
5
+ * results; what reads as the answer is the text of the LAST assistant message
6
+ * that has any (the earlier ones are the "let me look at…" between tools).
7
+ * `head_summary` is not this: it is cut to 200 characters with code removed,
8
+ * fit for a session list, not for a conversation.
9
+ *
10
+ * Walks back from HEAD only as far as the turn's own user message, one row at
11
+ * a time, so a long session is not loaded whole to read its last reply.
12
+ */
13
+
14
+ import { messageQueries, sessionQueries } from '$backend/database/queries';
15
+ import { isInternalToolMessage } from '$backend/snapshot/helpers';
16
+ import type { UnifiedMessage } from '$shared/types/unified';
17
+
18
+ /** A turn is never this long; the bound only protects against a corrupt parent chain. */
19
+ const MAX_WALK = 2000;
20
+
21
+ export interface TurnAnswer {
22
+ /** The answer's Markdown, or '' when the turn produced no text. */
23
+ text: string;
24
+ /** The error the turn ended with, when it failed — never part of `text`. */
25
+ error: string | null;
26
+ /** HEAD when read — the message a reply to this answer continues from. */
27
+ endMessageId: string | null;
28
+ /** The turn's own user message. */
29
+ userMessageId: string | null;
30
+ }
31
+
32
+ /**
33
+ * Where a turn starts: any message the user sent — including one that is only
34
+ * a photo, which a snapshot checkpoint (text required) would not count.
35
+ */
36
+ function isTurnStart(row: { data: string }): boolean {
37
+ try {
38
+ const message = JSON.parse(row.data) as UnifiedMessage;
39
+ return message.type === 'user' && !isInternalToolMessage(message);
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ /** The stream records a failure as an assistant message with this prefix. */
46
+ const ERROR_PREFIX = '**Error:** ';
47
+
48
+ function textOf(message: UnifiedMessage): string {
49
+ if (message.type !== 'assistant' || !Array.isArray(message.content)) return '';
50
+ return message.content
51
+ .filter((block) => block.type === 'text' && typeof block.text === 'string')
52
+ .map((block) => (block as { text: string }).text)
53
+ .join('\n\n')
54
+ .trim();
55
+ }
56
+
57
+ export function lastTurnAnswer(chatSessionId: string): TurnAnswer {
58
+ const head = sessionQueries.getHead(chatSessionId);
59
+ if (!head) return { text: '', error: null, endMessageId: null, userMessageId: null };
60
+
61
+ let error: string | null = null;
62
+ let currentId: string | null = head;
63
+ for (let steps = 0; currentId && steps < MAX_WALK; steps++) {
64
+ const row = messageQueries.getById(currentId);
65
+ if (!row) break;
66
+ if (isTurnStart(row)) return { text: '', error, endMessageId: head, userMessageId: row.id };
67
+ try {
68
+ const message = JSON.parse(row.data) as UnifiedMessage;
69
+ // Sub-agent output carries the tool call it answers; it is not the reply.
70
+ const isSubAgent = message.type === 'assistant' && message.parent?.toolUseId != null;
71
+ const text = isSubAgent ? '' : textOf(message);
72
+ // The failure the turn ended with is reported apart; what the turn said
73
+ // before it is still the answer so far.
74
+ if (text.startsWith(ERROR_PREFIX) && error === null && steps === 0) {
75
+ error = text.slice(ERROR_PREFIX.length).trim();
76
+ } else if (text) {
77
+ return { text, error, endMessageId: head, userMessageId: findTurnStart(row.parent_message_id ?? null) };
78
+ }
79
+ } catch {
80
+ // Unparseable row — skip it like any message without text.
81
+ }
82
+ currentId = row.parent_message_id ?? null;
83
+ }
84
+ return { text: '', error, endMessageId: head, userMessageId: null };
85
+ }
86
+
87
+ function findTurnStart(fromId: string | null): string | null {
88
+ let currentId = fromId;
89
+ for (let steps = 0; currentId && steps < MAX_WALK; steps++) {
90
+ const row = messageQueries.getById(currentId);
91
+ if (!row) return null;
92
+ if (isTurnStart(row)) return row.id;
93
+ currentId = row.parent_message_id ?? null;
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /** The text of a user message as the user wrote it — what /retry and an edit resend. */
99
+ export function userMessageText(messageId: string): string | null {
100
+ const row = messageQueries.getById(messageId);
101
+ if (!row) return null;
102
+ try {
103
+ const message = JSON.parse(row.data) as UnifiedMessage;
104
+ if (message.type !== 'user' || !Array.isArray(message.content)) return null;
105
+ return message.content
106
+ .filter((block) => block.type === 'text' && typeof (block as { text?: string }).text === 'string')
107
+ .map((block) => (block as { text: string }).text)
108
+ .join('\n')
109
+ .trim() || null;
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ /** Cut Markdown at a paragraph boundary near `max`, so a quoted excerpt never ends mid-fence. */
116
+ export function excerptMarkdown(markdown: string, max: number): string {
117
+ const trimmed = markdown.trim();
118
+ if (trimmed.length <= max) return trimmed;
119
+ const window = trimmed.slice(0, max);
120
+ const cut = window.lastIndexOf('\n\n');
121
+ let excerpt = cut > max / 2 ? window.slice(0, cut) : window;
122
+ // An odd number of fences means the cut landed inside a code block — close it.
123
+ if ((excerpt.match(/^\s*```/gm) ?? []).length % 2 === 1) excerpt += '\n```';
124
+ return `${excerpt.trimEnd()}\n\n…`;
125
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * "The next thing you type is for this": one per chat, newest wins, used
3
+ * once, and it lapses.
4
+ */
5
+
6
+ import { describe, it, expect, afterEach, setSystemTime } from 'bun:test';
7
+ import { clearAwaiting, hasAwaiting, isAwaiting, resetAwaiting, setAwaiting, takeAwaiting } from './awaiting';
8
+
9
+ afterEach(() => {
10
+ resetAwaiting();
11
+ setSystemTime();
12
+ });
13
+
14
+ describe('awaiting typed words', () => {
15
+ it('is taken once, and the newest ask wins', () => {
16
+ setAwaiting('link', { kind: 'question', rowId: 'q1' });
17
+ setAwaiting('link', { kind: 'ask', rowId: 'a1' });
18
+ expect(isAwaiting('link', 'q1')).toBe(false);
19
+ expect(takeAwaiting('link')).toEqual({ kind: 'ask', rowId: 'a1' });
20
+ expect(takeAwaiting('link')).toBeNull();
21
+ });
22
+
23
+ it('knows whether the chat is waiting at all', () => {
24
+ expect(hasAwaiting('link')).toBe(false);
25
+ setAwaiting('link', { kind: 'ask', rowId: 'a1' });
26
+ expect(hasAwaiting('link')).toBe(true);
27
+ expect(hasAwaiting('other-link')).toBe(false);
28
+ });
29
+
30
+ it('lapses, and a command clears it', () => {
31
+ setAwaiting('link', { kind: 'question', rowId: 'q1' });
32
+ setSystemTime(new Date(Date.now() + 11 * 60 * 1000));
33
+ expect(takeAwaiting('link')).toBeNull();
34
+ setSystemTime();
35
+ setAwaiting('link', { kind: 'question', rowId: 'q1' });
36
+ clearAwaiting('link');
37
+ expect(takeAwaiting('link')).toBeNull();
38
+ });
39
+ });