@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
@@ -3,7 +3,7 @@ import { projectCleanupRegistry, runProjectCleanups } from './project-cleanup-re
3
3
 
4
4
  import './project-cleanup';
5
5
 
6
- const DEFAULT_CLEANUP_HANDLERS = ['engine', 'mcp-context', 'file-watcher', 'presence', 'worktrees'] as const;
6
+ const DEFAULT_CLEANUP_HANDLERS = ['engine', 'mcp-context', 'file-watcher', 'worktrees'] as const;
7
7
 
8
8
  describe('project cleanup integration', () => {
9
9
  test('registers default backend handlers when project-cleanup is loaded', () => {
@@ -13,7 +13,7 @@ describe('project cleanup integration', () => {
13
13
  }
14
14
  expect(names.indexOf('engine')).toBeLessThan(names.indexOf('mcp-context'));
15
15
  expect(names.indexOf('mcp-context')).toBeLessThan(names.indexOf('file-watcher'));
16
- expect(names.indexOf('file-watcher')).toBeLessThan(names.indexOf('presence'));
16
+ expect(names.indexOf('file-watcher')).toBeLessThan(names.indexOf('worktrees'));
17
17
  });
18
18
 
19
19
  test('runProjectCleanups runs default handlers without throwing', async () => {
@@ -4,7 +4,6 @@
4
4
  import { disposeProjectEngines } from '../engine';
5
5
  import { projectContextService } from '../mcp';
6
6
  import { fileWatcher } from '../files/file-watcher';
7
- import { clearProjectPresence } from '../project/status-manager';
8
7
  import { registerProjectCleanup } from './project-cleanup-registry';
9
8
  import { removeProjectWorktrees } from '../worktrees';
10
9
  import { removeProjectNotes } from '../notes/storage';
@@ -26,13 +25,6 @@ registerProjectCleanup({
26
25
  }
27
26
  });
28
27
 
29
- registerProjectCleanup({
30
- name: 'presence',
31
- run: (projectId) => {
32
- clearProjectPresence(projectId);
33
- }
34
- });
35
-
36
28
  registerProjectCleanup({
37
29
  name: 'worktrees',
38
30
  run: (projectId) => removeProjectWorktrees(projectId)
@@ -184,9 +184,8 @@ export const skillService = {
184
184
  },
185
185
 
186
186
  /**
187
- * Minimal list of slash-invocable skills for the chat "/" picker. Non-admin
188
- * surface (any user can invoke one), so it exposes only display fields — no
189
- * bodies, no source/disk metadata.
187
+ * Minimal list of slash-invocable skills for the chat "/" picker. It exposes
188
+ * only display fields — no bodies, no source/disk metadata.
190
189
  *
191
190
  * `profileFilter` mirrors the stream-time semantics: when an active profile
192
191
  * references ≥1 skill, the picker shows exactly that set (even if a referenced
@@ -14,6 +14,7 @@ import fs from 'fs/promises';
14
14
  import { gzipSync, gunzipSync } from 'zlib';
15
15
  import { debug } from '$shared/utils/logger';
16
16
  import { getClopenDir } from '../utils/index.js';
17
+ import { blobLineStatsQueries } from '../database/queries/blob-line-stats-queries';
17
18
 
18
19
  const SNAPSHOTS_DIR = join(getClopenDir(), 'snapshots');
19
20
  const BLOBS_DIR = join(SNAPSHOTS_DIR, 'blobs');
@@ -156,7 +157,8 @@ class BlobStore {
156
157
 
157
158
  /**
158
159
  * Delete multiple blobs by hash.
159
- * Also invalidates fileHashCache entries whose hash matches a deleted blob.
160
+ * Also invalidates fileHashCache entries whose hash matches a deleted blob,
161
+ * and the cached line counts of every pair that names one.
160
162
  */
161
163
  async deleteBlobs(hashes: string[]): Promise<number> {
162
164
  const hashSet = new Set(hashes);
@@ -177,6 +179,12 @@ class BlobStore {
177
179
  }
178
180
  }
179
181
 
182
+ try {
183
+ blobLineStatsQueries.deleteByHashes(hashes);
184
+ } catch (error) {
185
+ debug.warn('snapshot', 'Failed to prune cached line stats:', error);
186
+ }
187
+
180
188
  return deleted;
181
189
  }
182
190
 
@@ -3,6 +3,7 @@ import { blobStore } from './blob-store';
3
3
  import { debug } from '$shared/utils/logger';
4
4
  import { loadMessage } from '$shared/utils/message-formatter';
5
5
  import { buildTurnFiles, summariseTurnFiles } from './turn-changes';
6
+ import { blobLineStats } from './line-stats';
6
7
  import type { DatabaseMessage, SessionScopedChanges } from '$shared/types/database/schema';
7
8
  import type { UnifiedMessage, UserMessage } from '$shared/types/unified';
8
9
 
@@ -25,7 +26,6 @@ export interface CheckpointNode {
25
26
  isCurrent: boolean; // this is the current active checkpoint
26
27
  hasSnapshot: boolean;
27
28
  isInitial?: boolean; // true for the "initial state" node
28
- senderName?: string | null;
29
29
  // File change statistics (git-like)
30
30
  filesChanged?: number;
31
31
  insertions?: number;
@@ -349,16 +349,8 @@ export async function getCheckpointFileStats(
349
349
  const changes = JSON.parse(snapshot.session_changes as string) as SessionScopedChanges;
350
350
  if (Object.keys(changes).length === 0) return stored;
351
351
 
352
- let blobMissing = false;
353
- const files = await buildTurnFiles(changes, async (hash) => {
354
- try {
355
- return await blobStore.readBlob(hash);
356
- } catch (err) {
357
- blobMissing = true;
358
- throw err;
359
- }
360
- });
361
- return blobMissing ? stored : summariseTurnFiles(files);
352
+ const files = await buildTurnFiles(changes, blobLineStats);
353
+ return files.some((file) => !file.contentAvailable) ? stored : summariseTurnFiles(files);
362
354
  } catch {
363
355
  return stored;
364
356
  }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Counting each pair of blobs once.
3
+ *
4
+ * A chat open used to re-diff every changed file of every turn, and a single
5
+ * large file made that block the server for minutes. The pair's count is a
6
+ * fact about two content hashes, so it is computed on first use and read back
7
+ * from then on — and dropped when the blobs it describes are deleted.
8
+ */
9
+
10
+ import { describe, it, expect, beforeAll } from 'bun:test';
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ import { initializeDatabase } from '../database';
14
+ import { blobLineStatsQueries } from '../database/queries/blob-line-stats-queries';
15
+ import { blobStore } from './blob-store';
16
+ import { blobLineStats } from './line-stats';
17
+
18
+ /** Fresh content per test, so its hashes are not shared with any other run. */
19
+ async function storePair(oldText: string, newText: string) {
20
+ const salt = randomUUID();
21
+ const oldHash = await blobStore.storeBlob(Buffer.from(`${salt}\n${oldText}`, 'utf8'));
22
+ const newHash = await blobStore.storeBlob(Buffer.from(`${salt}\n${newText}`, 'utf8'));
23
+ return { oldHash, newHash };
24
+ }
25
+
26
+ beforeAll(async () => {
27
+ await initializeDatabase();
28
+ });
29
+
30
+ describe('blobLineStats', () => {
31
+ it('counts a pair on first use and remembers it', async () => {
32
+ const { oldHash, newHash } = await storePair('a\nb\nc\n', 'a\nB\nc\nd\n');
33
+
34
+ expect(blobLineStatsQueries.get(oldHash, newHash)).toBeNull();
35
+
36
+ const first = await blobLineStats(oldHash, newHash);
37
+ expect(first).toEqual({ insertions: 2, deletions: 1, isBinary: false, contentAvailable: true });
38
+ expect(blobLineStatsQueries.get(oldHash, newHash)).toEqual({ insertions: 2, deletions: 1, isBinary: false });
39
+
40
+ expect(await blobLineStats(oldHash, newHash)).toEqual(first);
41
+ });
42
+
43
+ it('counts a created file against an empty side', async () => {
44
+ const { newHash } = await storePair('', 'one\ntwo\n');
45
+
46
+ // The salt line makes it three.
47
+ expect(await blobLineStats('', newHash)).toEqual({
48
+ insertions: 3,
49
+ deletions: 0,
50
+ isBinary: false,
51
+ contentAvailable: true
52
+ });
53
+ });
54
+
55
+ it('shares one computation between concurrent callers', async () => {
56
+ const { oldHash, newHash } = await storePair('x\n', 'y\n');
57
+
58
+ const [a, b] = await Promise.all([blobLineStats(oldHash, newHash), blobLineStats(oldHash, newHash)]);
59
+ expect(a).toBe(b);
60
+ });
61
+
62
+ it('never stores a pair whose blob is missing', async () => {
63
+ const { newHash } = await storePair('', 'x\n');
64
+ const missing = 'f'.repeat(64);
65
+
66
+ const stats = await blobLineStats(missing, newHash);
67
+ expect(stats.contentAvailable).toBe(false);
68
+ expect(blobLineStatsQueries.get(missing, newHash)).toBeNull();
69
+ });
70
+
71
+ it('drops the remembered count when its blobs are deleted', async () => {
72
+ const { oldHash, newHash } = await storePair('a\n', 'b\n');
73
+ await blobLineStats(oldHash, newHash);
74
+
75
+ await blobStore.deleteBlobs([oldHash, newHash]);
76
+
77
+ expect(blobLineStatsQueries.get(oldHash, newHash)).toBeNull();
78
+ expect((await blobLineStats(oldHash, newHash)).contentAvailable).toBe(false);
79
+ });
80
+ });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The production `LineStatsSource`: every pair of blobs is counted once.
3
+ *
4
+ * Blobs are content-addressed, so the +/- count of (oldHash, newHash) is a
5
+ * fact that never changes. It used to be recomputed on every chat open, every
6
+ * reconnect and every pending-changes poll — twice per request, once for the
7
+ * turn list and once for the net total — and a single large file made each of
8
+ * those block the server. Now the first caller computes it and every later
9
+ * one, on any surface, reads the same row (migration 087).
10
+ *
11
+ * The count itself is `countPairFromBlobs`; this module only remembers it.
12
+ */
13
+
14
+ import { blobLineStatsQueries } from '../database/queries/blob-line-stats-queries';
15
+ import { blobStore } from './blob-store';
16
+ import { countPairFromBlobs } from './turn-changes';
17
+ import type { LineStatsSource, PairLineStats } from './turn-changes';
18
+ import { debug } from '$shared/utils/logger';
19
+
20
+ /** Pairs being counted right now, so concurrent callers share one computation. */
21
+ const inFlight = new Map<string, Promise<PairLineStats>>();
22
+
23
+ const readBlob = (hash: string) => blobStore.readBlob(hash);
24
+
25
+ /** Whether both sides of a pair can still be read — the diff view needs them. */
26
+ async function contentAvailable(oldHash: string, newHash: string): Promise<boolean> {
27
+ const [hasOld, hasNew] = await Promise.all([
28
+ oldHash ? blobStore.hasBlob(oldHash) : true,
29
+ newHash ? blobStore.hasBlob(newHash) : true
30
+ ]);
31
+ return hasOld && hasNew;
32
+ }
33
+
34
+ async function computeAndRemember(oldHash: string, newHash: string): Promise<PairLineStats> {
35
+ const stats = await countPairFromBlobs(oldHash, newHash, readBlob);
36
+ // A missing blob yields a non-answer, not a count — never store it.
37
+ if (stats.contentAvailable) {
38
+ try {
39
+ blobLineStatsQueries.save(oldHash, newHash, stats);
40
+ } catch (error) {
41
+ debug.warn('snapshot', 'Failed to cache line stats:', error);
42
+ }
43
+ }
44
+ return stats;
45
+ }
46
+
47
+ export const blobLineStats: LineStatsSource = async (oldHash, newHash) => {
48
+ try {
49
+ const cached = blobLineStatsQueries.get(oldHash, newHash);
50
+ if (cached) {
51
+ return { ...cached, contentAvailable: await contentAvailable(oldHash, newHash) };
52
+ }
53
+ } catch (error) {
54
+ debug.warn('snapshot', 'Failed to read cached line stats:', error);
55
+ }
56
+
57
+ const key = `${oldHash}:${newHash}`;
58
+ const pending = inFlight.get(key);
59
+ if (pending) return pending;
60
+
61
+ const computation = computeAndRemember(oldHash, newHash).finally(() => inFlight.delete(key));
62
+ inFlight.set(key, computation);
63
+ return computation;
64
+ };
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Restore a chat session to a checkpoint — HEAD, engine resume id, checkpoint
3
+ * tree and files, in one call.
4
+ *
5
+ * This used to live inline in the `snapshot:restore` WebSocket handler, which
6
+ * made the web UI the only thing that could branch a conversation. A chat
7
+ * channel replying to an older message, or editing one, needs exactly the
8
+ * same operation without a connection, so the logic lives here and the
9
+ * handler is a thin wrapper. Any change to what "restore" means is made once.
10
+ */
11
+
12
+ import { messageQueries, sessionQueries, checkpointQueries } from '../database/queries';
13
+ import { getDatabase } from '../database';
14
+ import { snapshotService } from './snapshot-service';
15
+ import { streamManager } from '../chat/stream-manager';
16
+ import { debug } from '$shared/utils/logger';
17
+ import type { UnifiedMessage } from '$shared/types/unified';
18
+ import {
19
+ buildCheckpointTree,
20
+ getCheckpointPathToRoot,
21
+ findCheckpointForHead,
22
+ findSessionEnd,
23
+ INITIAL_NODE_ID
24
+ } from './helpers';
25
+ import { ws } from '$backend/utils/ws';
26
+ import { resolveSessionRoot } from '../worktrees';
27
+
28
+ export type ConflictResolutions = Record<string, 'restore' | 'keep'>;
29
+
30
+ export interface RestoreResult {
31
+ restoredTo: { messageId: string; timestamp: string };
32
+ filesRestored: number;
33
+ filesSkipped: number;
34
+ }
35
+
36
+ /** The checkpoint a target resolves to, and the checkpoint path for branch-aware file work. */
37
+ function resolveCheckpoint(sessionId: string, messageId: string): { checkpointId: string | null; path: string[] | undefined } {
38
+ if (messageId === INITIAL_NODE_ID) return { checkpointId: null, path: undefined };
39
+ const allMessages = messageQueries.getAllBySessionId(sessionId);
40
+ const { checkpoints, parentMap } = buildCheckpointTree(allMessages);
41
+ const checkpointIdSet = new Set(checkpoints.map((c) => c.id));
42
+ const resolvedId = checkpointIdSet.has(messageId) ? messageId : findCheckpointForHead(messageId, allMessages, checkpointIdSet);
43
+ return resolvedId
44
+ ? { checkpointId: resolvedId, path: getCheckpointPathToRoot(resolvedId, parentMap) }
45
+ : { checkpointId: messageId, path: undefined };
46
+ }
47
+
48
+ /** Files another session (or the user) changed that restoring to `messageId` would overwrite. */
49
+ export async function checkSessionRestoreConflicts(sessionId: string, messageId: string) {
50
+ const projectPath = resolveSessionRoot(sessionId)?.path || undefined;
51
+ const { checkpointId, path } = resolveCheckpoint(sessionId, messageId);
52
+ return snapshotService.checkRestoreConflicts(sessionId, checkpointId, projectPath, path);
53
+ }
54
+
55
+ /**
56
+ * The message a restore to `messageId` would leave HEAD on — the end of that
57
+ * message's turn. Lets a caller tell "continue from HEAD" (no restore at all)
58
+ * apart from "branch from an older point" before doing anything.
59
+ */
60
+ export function restoreTargetEnd(sessionId: string, messageId: string): string | null {
61
+ if (messageId === INITIAL_NODE_ID) return null;
62
+ const target = messageQueries.getById(messageId);
63
+ if (!target || target.session_id !== sessionId) return null;
64
+ return findSessionEnd(target, messageQueries.getAllBySessionId(sessionId)).id;
65
+ }
66
+
67
+ function broadcastRestored(sessionId: string): void {
68
+ try {
69
+ ws.emit.chatSession(sessionId, 'chat:messages-changed', {
70
+ sessionId,
71
+ reason: 'restore',
72
+ timestamp: new Date().toISOString()
73
+ });
74
+ } catch (err) {
75
+ debug.error('snapshot', 'Failed to broadcast messages-changed:', err);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Move a session back to `messageId` (or to before its first message, with
81
+ * `INITIAL_NODE_ID`) and restore its files to match. Refuses while the
82
+ * session is generating: restore rewrites the working tree and resets the
83
+ * in-memory baseline, and doing that mid-stream would corrupt the end-of-turn
84
+ * snapshot and race the engine's own writes.
85
+ */
86
+ export async function restoreSessionTo(
87
+ sessionId: string,
88
+ messageId: string,
89
+ conflictResolutions?: ConflictResolutions
90
+ ): Promise<RestoreResult> {
91
+ const session = sessionQueries.getById(sessionId);
92
+ if (!session) throw new Error('Session not found');
93
+
94
+ const activeStream = streamManager.getSessionStream(sessionId, session.project_id);
95
+ if (activeStream?.status === 'active') {
96
+ throw new Error('Cannot restore while the chat is still generating. Stop the stream first, then try again.');
97
+ }
98
+
99
+ const isInitialRestore = messageId === INITIAL_NODE_ID;
100
+ debug.log('snapshot', `RESTORE - ${isInitialRestore ? 'Restoring to initial state' : 'Moving HEAD to checkpoint'} (${messageId}) in ${sessionId}`);
101
+
102
+ if (isInitialRestore) {
103
+ sessionQueries.clearHead(sessionId);
104
+ sessionQueries.rederiveHeadSnapshot(sessionId);
105
+ // Clear head_session_id so the next chat starts fresh.
106
+ getDatabase().prepare(`UPDATE chat_sessions SET head_session_id = NULL WHERE id = ?`).run(sessionId);
107
+ checkpointQueries.deleteForSession(sessionId);
108
+
109
+ let filesRestored = 0;
110
+ let filesSkipped = 0;
111
+ const sessionRoot = resolveSessionRoot(sessionId);
112
+ if (sessionRoot?.path) {
113
+ // null = restore to initial (before all snapshots): revert ALL session changes.
114
+ const result = await snapshotService.restoreSessionScoped(sessionRoot.path, sessionId, null, conflictResolutions);
115
+ filesRestored = result.restoredFiles;
116
+ filesSkipped = result.skippedFiles;
117
+ }
118
+ broadcastRestored(sessionId);
119
+ return { restoredTo: { messageId: INITIAL_NODE_ID, timestamp: new Date().toISOString() }, filesRestored, filesSkipped };
120
+ }
121
+
122
+ // 1. The target message.
123
+ const checkpointMessage = messageQueries.getById(messageId);
124
+ if (!checkpointMessage) throw new Error('Checkpoint message not found');
125
+
126
+ // 2-3. Every message, and the checkpoint tree built from them.
127
+ const allMessages = messageQueries.getAllBySessionId(sessionId);
128
+ const { checkpoints, parentMap } = buildCheckpointTree(allMessages);
129
+
130
+ // 3b. The target may be a non-checkpoint (e.g. an assistant response, which
131
+ // is what an edit targets): walk back to the nearest ancestor checkpoint.
132
+ const checkpointIdSet = new Set(checkpoints.map((c) => c.id));
133
+ const resolvedCheckpointId = checkpointIdSet.has(messageId)
134
+ ? messageId
135
+ : findCheckpointForHead(messageId, allMessages, checkpointIdSet);
136
+
137
+ // 4-5. HEAD moves to the end of the target's turn.
138
+ const sessionEnd = findSessionEnd(checkpointMessage, allMessages);
139
+ sessionQueries.updateHead(sessionId, sessionEnd.id);
140
+ sessionQueries.rederiveHeadSnapshot(sessionId);
141
+ debug.log('snapshot', `HEAD updated to: ${sessionEnd.id}`);
142
+
143
+ // 5b. head_session_id, so resume works. Engine is read PER MESSAGE, not from
144
+ // `chat_sessions.engine`: a session can switch engine mid-conversation, so
145
+ // the session column only names the currently selected engine. Restoring
146
+ // into a region driven by another engine must apply that region's
147
+ // semantics, and must not adopt an SDK session id from another store.
148
+ // Claude Code: skip cancelled fork session ids (partial messages from
149
+ // cancelStream). Other engines: any session id on the branch is valid.
150
+ {
151
+ let foundSdkSessionId: string | null = null;
152
+ const msgLookup = new Map(allMessages.map((m) => [m.id, m]));
153
+ const engineOf = (msg: UnifiedMessage): string | null => msg.engine?.type ?? null;
154
+
155
+ let branchEngine: string | null = null;
156
+ {
157
+ let probeId: string | null = sessionEnd.id;
158
+ while (probeId) {
159
+ const probeMsg = msgLookup.get(probeId);
160
+ if (!probeMsg) break;
161
+ try {
162
+ const msg = JSON.parse(probeMsg.data) as UnifiedMessage;
163
+ if (msg.type !== 'user') {
164
+ const type = engineOf(msg);
165
+ if (type) {
166
+ branchEngine = type;
167
+ break;
168
+ }
169
+ }
170
+ } catch {
171
+ /* skip */
172
+ }
173
+ probeId = probeMsg.parent_message_id || null;
174
+ }
175
+ if (!branchEngine) branchEngine = session.engine ?? null;
176
+ }
177
+
178
+ const isClaudeCode = branchEngine === 'claude-code';
179
+
180
+ let cancelledSessionId: string | null = null;
181
+ if (isClaudeCode) {
182
+ try {
183
+ const endMsg = msgLookup.get(sessionEnd.id);
184
+ if (endMsg) {
185
+ const endParsed = JSON.parse(endMsg.data) as UnifiedMessage;
186
+ if (endParsed.type === 'assistant' && endParsed.stopReason === 'interrupted') {
187
+ cancelledSessionId = endParsed.sessionId || null;
188
+ }
189
+ }
190
+ } catch {
191
+ /* skip */
192
+ }
193
+ }
194
+
195
+ let walkId: string | null = sessionEnd.id;
196
+ while (walkId) {
197
+ const walkMsg = msgLookup.get(walkId);
198
+ if (!walkMsg) break;
199
+ try {
200
+ const msg = JSON.parse(walkMsg.data) as UnifiedMessage;
201
+ if (isClaudeCode && msg.type === 'assistant' && msg.stopReason === 'interrupted') {
202
+ walkId = walkMsg.parent_message_id || null;
203
+ continue;
204
+ }
205
+ if (isClaudeCode && cancelledSessionId && msg.sessionId === cancelledSessionId) {
206
+ walkId = walkMsg.parent_message_id || null;
207
+ continue;
208
+ }
209
+ // A message with no engine block is pre-migration: it cannot be proven
210
+ // foreign, so keep the old behaviour and accept it.
211
+ const msgEngine = engineOf(msg);
212
+ if (msg.sessionId && (!branchEngine || !msgEngine || msgEngine === branchEngine)) {
213
+ foundSdkSessionId = msg.sessionId;
214
+ break;
215
+ }
216
+ } catch {
217
+ /* skip */
218
+ }
219
+ walkId = walkMsg.parent_message_id || null;
220
+ }
221
+
222
+ if (foundSdkSessionId) sessionQueries.updateSessionId(sessionId, foundSdkSessionId);
223
+ else sessionQueries.clearSessionId(sessionId);
224
+ }
225
+
226
+ // 6. checkpoint_tree_state along the restored path.
227
+ let checkpointPath: string[] = [];
228
+ if (resolvedCheckpointId) {
229
+ checkpointPath = getCheckpointPathToRoot(resolvedCheckpointId, parentMap);
230
+ if (checkpointPath.length > 1) checkpointQueries.updateActiveChildrenAlongPath(sessionId, checkpointPath);
231
+ }
232
+
233
+ // 7. Files. Snapshots are keyed by checkpoint user message ids, so the
234
+ // resolved checkpoint is what the lookup must use.
235
+ let filesRestored = 0;
236
+ let filesSkipped = 0;
237
+ const sessionRoot = resolveSessionRoot(sessionId);
238
+ if (sessionRoot?.path) {
239
+ const result = await snapshotService.restoreSessionScoped(
240
+ sessionRoot.path,
241
+ sessionId,
242
+ resolvedCheckpointId,
243
+ conflictResolutions,
244
+ checkpointPath.length > 0 ? checkpointPath : undefined
245
+ );
246
+ filesRestored = result.restoredFiles;
247
+ filesSkipped = result.skippedFiles;
248
+ }
249
+
250
+ broadcastRestored(sessionId);
251
+ return { restoredTo: { messageId: sessionEnd.id, timestamp: sessionEnd.created_at }, filesRestored, filesSkipped };
252
+ }
@@ -23,7 +23,8 @@ import { attributeGitChanges, readRepoHeads, type RepoHeads } from './git-attrib
23
23
  import { TurnActivity, type ObservedOutput } from './turn-activity';
24
24
  import { fileWatcher } from '../files/file-watcher';
25
25
  import type { MessageSnapshot, SessionScopedChanges } from '$shared/types/database/schema';
26
- import { calculateFileChangeStats } from '$shared/utils/diff-calculator';
26
+ import { buildTurnFiles, summariseTurnFiles } from './turn-changes';
27
+ import { blobLineStats } from './line-stats';
27
28
  import { makeScopeKey } from '$shared/utils/workspace-scope';
28
29
  import { debug } from '$shared/utils/logger';
29
30
 
@@ -180,14 +181,13 @@ export class SnapshotService {
180
181
  private async scanTree(
181
182
  root: string,
182
183
  previous: TreeMap
183
- ): Promise<{ tree: TreeMap; contents: Map<string, Buffer> }> {
184
+ ): Promise<{ tree: TreeMap }> {
184
185
  const scan = await scanSnapshotFiles(root, { pruneGenerated: true });
185
186
  if (scan.incomplete.includes('')) {
186
187
  throw new Error(`Could not list the files of ${root}`);
187
188
  }
188
189
 
189
190
  const tree: TreeMap = {};
190
- const contents = new Map<string, Buffer>();
191
191
 
192
192
  if (scan.incomplete.length > 0) {
193
193
  for (const [filepath, hash] of Object.entries(previous)) {
@@ -207,16 +207,13 @@ export class SnapshotService {
207
207
 
208
208
  const result = await blobStore.hashFile(filepath);
209
209
  tree[relativePath] = result.hash;
210
- if (result.content !== null && result.hash !== previous[relativePath]) {
211
- contents.set(relativePath, result.content);
212
- }
213
210
  } catch (error) {
214
211
  if (isMissingFile(error)) return;
215
212
  if (previous[relativePath]) tree[relativePath] = previous[relativePath];
216
213
  }
217
214
  });
218
215
 
219
- return { tree, contents };
216
+ return { tree };
220
217
  }
221
218
 
222
219
  // ========================================================================
@@ -556,7 +553,7 @@ export class SnapshotService {
556
553
  // closed. A gitignore-aware scan + hash diff against the baseline is
557
554
  // always correct, and blobStore.hashFile's mtime+size cache keeps it
558
555
  // cheap — only files that actually changed are re-read.
559
- const { tree: currentTree, contents: readContents } = await this.scanTree(projectPath, previousTree);
556
+ const { tree: currentTree } = await this.scanTree(projectPath, previousTree);
560
557
  const sessionChanges = diffTrees(previousTree, currentTree);
561
558
 
562
559
  // A disk diff sees every writer. Take out what is not this turn's.
@@ -589,7 +586,7 @@ export class SnapshotService {
589
586
  }
590
587
 
591
588
  // Calculate line-level file change stats
592
- const fileStats = await this.calculateChangeStats(sessionChanges, readContents);
589
+ const fileStats = await this.calculateChangeStats(sessionChanges);
593
590
 
594
591
  const metadata: SnapshotMetadata = {
595
592
  totalFiles: Object.keys(currentTree).length,
@@ -1069,27 +1066,17 @@ export class SnapshotService {
1069
1066
  }
1070
1067
 
1071
1068
  /**
1072
- * Calculate line-level change stats for changed files.
1069
+ * Line-level change stats for a turn's changed files.
1070
+ *
1071
+ * Counted through the same `buildTurnFiles` + `blobLineStats` every other
1072
+ * surface reads, so the numbers stored on the row are the ones the Changes
1073
+ * tab shows — and counting here, at capture, is what puts each pair in the
1074
+ * cache before anyone opens the chat.
1073
1075
  */
1074
1076
  private async calculateChangeStats(
1075
- sessionChanges: SessionScopedChanges,
1076
- readContents: Map<string, Buffer>
1077
+ sessionChanges: SessionScopedChanges
1077
1078
  ): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
1078
- const previousSnapshot: Record<string, Buffer> = {};
1079
- const currentSnapshot: Record<string, Buffer> = {};
1080
-
1081
- for (const [filepath, change] of Object.entries(sessionChanges)) {
1082
- try {
1083
- if (change.oldHash) {
1084
- previousSnapshot[filepath] = await blobStore.readBlob(change.oldHash);
1085
- }
1086
- if (change.newHash) {
1087
- currentSnapshot[filepath] = readContents.get(filepath) ?? await blobStore.readBlob(change.newHash);
1088
- }
1089
- } catch { /* skip */ }
1090
- }
1091
-
1092
- return calculateFileChangeStats(previousSnapshot, currentSnapshot);
1079
+ return summariseTurnFiles(await buildTurnFiles(sessionChanges, blobLineStats));
1093
1080
  }
1094
1081
 
1095
1082
  /**
@@ -18,16 +18,21 @@ import {
18
18
  summariseTurnFiles,
19
19
  excerptPrompt,
20
20
  netChangeRuns,
21
- summariseNetChanges
21
+ summariseNetChanges,
22
+ statsFromBlobs
22
23
  } from './turn-changes';
24
+ import type { LineStatsSource } from './turn-changes';
23
25
 
24
- /** Blob reader over an in-memory store, so the tests own their failure modes. */
25
- function readerFor(blobs: Record<string, string | Buffer>) {
26
- return async (hash: string): Promise<Buffer> => {
26
+ /**
27
+ * Line stats over an in-memory blob store, so the tests own their failure
28
+ * modes. Uncached on purpose: the hashes here are labels, not content hashes.
29
+ */
30
+ function readerFor(blobs: Record<string, string | Buffer>): LineStatsSource {
31
+ return statsFromBlobs(async (hash: string): Promise<Buffer> => {
27
32
  const value = blobs[hash];
28
33
  if (value === undefined) throw new Error(`missing blob ${hash}`);
29
34
  return Buffer.isBuffer(value) ? value : Buffer.from(value, 'utf8');
30
- };
35
+ });
31
36
  }
32
37
 
33
38
  describe('statusOf', () => {