@myrialabs/clopen 0.4.47 → 0.4.48

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 (325) 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/stream-manager.ts +62 -62
  15. package/backend/chat/turn-answer.test.ts +64 -0
  16. package/backend/chat/turn-answer.ts +125 -0
  17. package/backend/chat-apps/awaiting.test.ts +39 -0
  18. package/backend/chat-apps/awaiting.ts +49 -0
  19. package/backend/chat-apps/conversation.ts +746 -0
  20. package/backend/chat-apps/inbound.ts +324 -0
  21. package/backend/chat-apps/index.ts +309 -0
  22. package/backend/chat-apps/link-events.ts +20 -0
  23. package/backend/chat-apps/media.test.ts +62 -0
  24. package/backend/chat-apps/media.ts +208 -0
  25. package/backend/chat-apps/messages.test.ts +229 -0
  26. package/backend/chat-apps/messages.ts +365 -0
  27. package/backend/chat-apps/outbound.ts +243 -0
  28. package/backend/chat-apps/pairing.test.ts +45 -0
  29. package/backend/chat-apps/pairing.ts +74 -0
  30. package/backend/chat-apps/platforms/index.ts +20 -0
  31. package/backend/chat-apps/platforms/telegram.test.ts +35 -0
  32. package/backend/chat-apps/platforms/telegram.ts +191 -0
  33. package/backend/chat-apps/platforms/types.ts +114 -0
  34. package/backend/chat-apps/questions.ts +133 -0
  35. package/backend/chat-apps/runtime.ts +572 -0
  36. package/backend/chat-apps/storage.test.ts +201 -0
  37. package/backend/chat-apps/turns.test.ts +45 -0
  38. package/backend/chat-apps/turns.ts +208 -0
  39. package/backend/containers/pty.ts +3 -11
  40. package/backend/control/actions/accounts.ts +89 -0
  41. package/backend/control/actions/files.ts +116 -0
  42. package/backend/control/actions/models.ts +188 -0
  43. package/backend/control/actions/projects.ts +272 -0
  44. package/backend/control/actions/sessions.ts +280 -0
  45. package/backend/control/actions/skills.ts +111 -0
  46. package/backend/control/control.test.ts +169 -0
  47. package/backend/control/define.ts +20 -0
  48. package/backend/control/folders.test.ts +67 -0
  49. package/backend/control/index.ts +213 -0
  50. package/backend/control/invoke.ts +44 -0
  51. package/backend/control/links.ts +35 -0
  52. package/backend/control/paging.ts +26 -0
  53. package/backend/control/types.ts +117 -0
  54. package/backend/control/workspace.ts +127 -0
  55. package/backend/database/migrations/084_create_channel_links.ts +71 -0
  56. package/backend/database/migrations/085_add_home_projects.ts +36 -0
  57. package/backend/database/migrations/086_single_owner.test.ts +170 -0
  58. package/backend/database/migrations/086_single_owner.ts +418 -0
  59. package/backend/database/migrations/index.ts +21 -0
  60. package/backend/database/queries/auth-queries.ts +7 -85
  61. package/backend/database/queries/channel-queries.ts +270 -0
  62. package/backend/database/queries/db-client-connection-queries.ts +18 -56
  63. package/backend/database/queries/file-share-queries.ts +5 -23
  64. package/backend/database/queries/git-identity-queries.ts +31 -42
  65. package/backend/database/queries/graph-queries.ts +1 -1
  66. package/backend/database/queries/index.ts +13 -1
  67. package/backend/database/queries/message-queries.test.ts +146 -0
  68. package/backend/database/queries/message-queries.ts +42 -1
  69. package/backend/database/queries/permission-set-queries.ts +1 -1
  70. package/backend/database/queries/profile-queries.ts +1 -1
  71. package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
  72. package/backend/database/queries/project-queries.ts +50 -63
  73. package/backend/database/queries/session-queries.ts +28 -56
  74. package/backend/database/queries/ssh-connection-queries.ts +18 -41
  75. package/backend/db-client/integrations/projector.ts +0 -5
  76. package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
  77. package/backend/engine/adapters/claude/message-converter.ts +25 -2
  78. package/backend/engine/adapters/cline/message-converter.ts +0 -1
  79. package/backend/engine/adapters/cline/stream.ts +11 -15
  80. package/backend/engine/adapters/codex/message-converter.ts +0 -2
  81. package/backend/engine/adapters/copilot/message-converter.ts +1 -2
  82. package/backend/engine/adapters/cursor/message-converter.ts +0 -1
  83. package/backend/engine/adapters/opencode/message-converter.ts +2 -4
  84. package/backend/engine/adapters/opencode/stream.ts +11 -0
  85. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  86. package/backend/engine/adapters/parent-scope.ts +44 -0
  87. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  88. package/backend/engine/adapters/pi/stream.ts +4 -5
  89. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  90. package/backend/engine/bootstrap-default-engine.ts +2 -2
  91. package/backend/engine/docs/adapter-contract.md +8 -1
  92. package/backend/engine/install-runner.ts +8 -17
  93. package/backend/files/file-shares.ts +20 -44
  94. package/backend/files/file-size-limit.ts +3 -3
  95. package/backend/files/image-processing.ts +1 -1
  96. package/backend/files/os-clipboard.ts +2 -2
  97. package/backend/git/git-executor.ts +25 -5
  98. package/backend/git/git-service.ts +420 -19
  99. package/backend/git/identity/credential-helper.test.ts +2 -7
  100. package/backend/git/identity/import-local.test.ts +11 -16
  101. package/backend/git/identity/import-local.ts +12 -12
  102. package/backend/git/identity/index.ts +10 -24
  103. package/backend/git/identity/resolve.ts +13 -14
  104. package/backend/git/identity/scope-config.ts +33 -28
  105. package/backend/git/identity/service.ts +44 -47
  106. package/backend/git/op-lock.test.ts +111 -0
  107. package/backend/git/op-lock.ts +180 -0
  108. package/backend/git/remote-sync.test.ts +249 -0
  109. package/backend/host/metrics.ts +1 -1
  110. package/backend/http/bearer-auth.ts +1 -2
  111. package/backend/http/files-download.test.ts +8 -9
  112. package/backend/http/files-download.ts +2 -2
  113. package/backend/http/files-shared.test.ts +62 -89
  114. package/backend/http/files-shared.ts +2 -2
  115. package/backend/http/files-upload.test.ts +3 -7
  116. package/backend/http/files-upload.ts +3 -3
  117. package/backend/http/notes-images.test.ts +15 -38
  118. package/backend/http/notes-images.ts +6 -8
  119. package/backend/http/ssh-sftp.ts +5 -10
  120. package/backend/index.ts +21 -7
  121. package/backend/integrations/accounts.ts +61 -3
  122. package/backend/integrations/index.ts +2 -2
  123. package/backend/integrations/registry/define.ts +15 -0
  124. package/backend/integrations/registry/index.ts +2 -0
  125. package/backend/integrations/registry/providers/telegram.ts +54 -0
  126. package/backend/integrations/registry/types.ts +21 -1
  127. package/backend/integrations/webhooks/gateway.ts +7 -6
  128. package/backend/integrations/webhooks/verify.test.ts +30 -0
  129. package/backend/integrations/webhooks/verify.ts +4 -0
  130. package/backend/mcp/external/project.ts +1 -1
  131. package/backend/mcp/internal/remote-server.test.ts +1 -3
  132. package/backend/mcp/internal/remote-server.ts +4 -4
  133. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  134. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  135. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  136. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  137. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  138. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  139. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  140. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  141. package/backend/memory/redact.ts +1 -1
  142. package/backend/notes/access.test.ts +28 -29
  143. package/backend/notes/access.ts +6 -11
  144. package/backend/permissions/service.ts +1 -1
  145. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  146. package/backend/preview/browser/browser-clipboard.ts +67 -0
  147. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  148. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  149. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  150. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  151. package/backend/preview/browser/browser-pool.ts +67 -6
  152. package/backend/preview/browser/browser-preview-service.ts +361 -25
  153. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  154. package/backend/preview/browser/browser-video-capture.ts +92 -5
  155. package/backend/preview/browser/element-locator.ts +190 -17
  156. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  157. package/backend/preview/browser/keyboard-chords.ts +132 -0
  158. package/backend/preview/browser/paste.ts +81 -0
  159. package/backend/preview/browser/process-usage.ts +142 -0
  160. package/backend/preview/browser/profile-lock.ts +209 -0
  161. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  162. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  163. package/backend/preview/browser/types.ts +40 -2
  164. package/backend/preview/browser/viewport.test.ts +45 -0
  165. package/backend/preview/browser/viewport.ts +96 -0
  166. package/backend/profiles/service.ts +2 -2
  167. package/backend/project/status-manager.ts +43 -172
  168. package/backend/projects/home.ts +61 -0
  169. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  170. package/backend/projects/project-cleanup.ts +0 -8
  171. package/backend/skills/service.ts +2 -3
  172. package/backend/snapshot/helpers.ts +0 -1
  173. package/backend/snapshot/restore.ts +252 -0
  174. package/backend/ssh/ptykit.ts +1 -2
  175. package/backend/terminal/ptykit.ts +5 -8
  176. package/backend/tunnel/public-origin.ts +31 -20
  177. package/backend/utils/user-helpers.ts +0 -55
  178. package/backend/utils/ws.ts +61 -154
  179. package/backend/worktrees/branching/engine.ts +3 -16
  180. package/backend/worktrees/branching/index.ts +1 -1
  181. package/backend/worktrees/branching/projector.ts +1 -1
  182. package/backend/worktrees/branching/service.ts +13 -25
  183. package/backend/ws/access.ts +12 -21
  184. package/backend/ws/artifacts/generate.ts +2 -2
  185. package/backend/ws/auth/device.ts +16 -71
  186. package/backend/ws/auth/index.ts +4 -22
  187. package/backend/ws/auth/login.test.ts +14 -60
  188. package/backend/ws/auth/login.ts +24 -124
  189. package/backend/ws/auth/status.ts +0 -1
  190. package/backend/ws/chat/composer.ts +118 -118
  191. package/backend/ws/chat/stream.ts +64 -47
  192. package/backend/ws/chat-apps/index.ts +117 -0
  193. package/backend/ws/containers/actions.ts +11 -25
  194. package/backend/ws/containers/index.ts +3 -4
  195. package/backend/ws/containers/list.ts +10 -36
  196. package/backend/ws/containers/logs.ts +2 -2
  197. package/backend/ws/containers/tunnel.ts +1 -2
  198. package/backend/ws/db-client/access.ts +2 -16
  199. package/backend/ws/db-client/accounts.ts +5 -15
  200. package/backend/ws/db-client/connections.ts +17 -25
  201. package/backend/ws/db-client/context.ts +1 -1
  202. package/backend/ws/db-client/env.ts +7 -10
  203. package/backend/ws/db-client/index.ts +2 -2
  204. package/backend/ws/db-client/io.ts +5 -5
  205. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  206. package/backend/ws/db-client/query.ts +18 -17
  207. package/backend/ws/db-client/schema.ts +13 -13
  208. package/backend/ws/db-client/structure.ts +35 -35
  209. package/backend/ws/db-client/supabase.ts +4 -21
  210. package/backend/ws/deployments/context.ts +1 -1
  211. package/backend/ws/deployments/crud.ts +0 -5
  212. package/backend/ws/engine/access.ts +7 -20
  213. package/backend/ws/engine/claude/accounts.ts +4 -4
  214. package/backend/ws/engine/cline/accounts.ts +5 -5
  215. package/backend/ws/engine/codex/accounts.ts +3 -3
  216. package/backend/ws/engine/pi/accounts.ts +5 -5
  217. package/backend/ws/files/clipboard.ts +8 -27
  218. package/backend/ws/files/image-edit.ts +6 -6
  219. package/backend/ws/files/index.ts +1 -1
  220. package/backend/ws/files/path-access.test.ts +32 -131
  221. package/backend/ws/files/path-access.ts +8 -87
  222. package/backend/ws/files/read.ts +15 -19
  223. package/backend/ws/files/reveal.ts +3 -3
  224. package/backend/ws/files/search.ts +7 -7
  225. package/backend/ws/files/share.ts +9 -13
  226. package/backend/ws/files/state.ts +9 -12
  227. package/backend/ws/files/watch.ts +3 -3
  228. package/backend/ws/files/write.ts +30 -31
  229. package/backend/ws/git/branch.ts +80 -59
  230. package/backend/ws/git/commit.ts +63 -44
  231. package/backend/ws/git/conflict.ts +16 -18
  232. package/backend/ws/git/identity-context.ts +8 -17
  233. package/backend/ws/git/identity.ts +17 -27
  234. package/backend/ws/git/index.ts +3 -1
  235. package/backend/ws/git/op-state.ts +139 -0
  236. package/backend/ws/git/remote.ts +241 -141
  237. package/backend/ws/git/repo-context.ts +67 -0
  238. package/backend/ws/git/staging.ts +18 -28
  239. package/backend/ws/git/status.ts +5 -2
  240. package/backend/ws/index.ts +5 -1
  241. package/backend/ws/instructions/crud.ts +1 -1
  242. package/backend/ws/integrations/crud.ts +1 -3
  243. package/backend/ws/mcp/crud.ts +3 -5
  244. package/backend/ws/mcp/tools.ts +1 -1
  245. package/backend/ws/memory/crud.ts +14 -46
  246. package/backend/ws/memory/index.ts +2 -2
  247. package/backend/ws/messages/crud.ts +29 -8
  248. package/backend/ws/notes/index.ts +33 -39
  249. package/backend/ws/permissions/crud.ts +3 -4
  250. package/backend/ws/ports/index.ts +1 -2
  251. package/backend/ws/ports/kill.ts +5 -10
  252. package/backend/ws/ports/list.ts +4 -10
  253. package/backend/ws/preview/access.ts +1 -1
  254. package/backend/ws/preview/browser/interact.ts +52 -79
  255. package/backend/ws/preview/browser/native-ui.ts +24 -0
  256. package/backend/ws/preview/browser/stats.ts +98 -1
  257. package/backend/ws/preview/browser/tab-info.ts +15 -0
  258. package/backend/ws/preview/browser/tab.ts +19 -4
  259. package/backend/ws/preview/index.ts +27 -0
  260. package/backend/ws/profiles/crud.ts +6 -8
  261. package/backend/ws/project-artifacts/index.ts +30 -31
  262. package/backend/ws/projects/crud.ts +33 -35
  263. package/backend/ws/projects/index.ts +3 -8
  264. package/backend/ws/projects/info.ts +3 -3
  265. package/backend/ws/projects/overview.ts +19 -30
  266. package/backend/ws/projects/status.ts +17 -57
  267. package/backend/ws/sessions/crud.ts +34 -45
  268. package/backend/ws/sessions/index.ts +1 -1
  269. package/backend/ws/settings/crud.ts +1 -1
  270. package/backend/ws/skills/crud.ts +3 -4
  271. package/backend/ws/skills/index.ts +1 -1
  272. package/backend/ws/snapshot/changes.ts +7 -7
  273. package/backend/ws/snapshot/restore.ts +11 -295
  274. package/backend/ws/snapshot/timeline.ts +2 -4
  275. package/backend/ws/ssh/access.ts +6 -21
  276. package/backend/ws/ssh/connections.ts +21 -31
  277. package/backend/ws/ssh/forwards.ts +12 -12
  278. package/backend/ws/ssh/sftp.ts +34 -34
  279. package/backend/ws/ssh/tunnel.ts +1 -2
  280. package/backend/ws/stack/install.ts +7 -17
  281. package/backend/ws/subagents/crud.ts +1 -1
  282. package/backend/ws/tunnel/share.ts +0 -2
  283. package/backend/ws/user/crud.ts +1 -59
  284. package/backend/ws/user/index.ts +1 -1
  285. package/backend/ws/work/context.ts +1 -1
  286. package/backend/ws/work/crud.ts +0 -5
  287. package/backend/ws/workspace/state.ts +10 -13
  288. package/backend/ws/worktrees/branching.ts +7 -36
  289. package/backend/ws/worktrees/crud.ts +2 -2
  290. package/bin/clopen.ts +10 -11
  291. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  292. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  293. package/dist/assets/main-BUiUL3eZ.css +1 -0
  294. package/dist/assets/main-nBOb9YOA.js +1240 -0
  295. package/dist/index.html +2 -2
  296. package/package.json +2 -1
  297. package/shared/constants/attachments.ts +14 -0
  298. package/shared/constants/engine-tools.ts +1 -1
  299. package/shared/constants/preview.test.ts +259 -0
  300. package/shared/constants/preview.ts +1018 -57
  301. package/shared/constants/tool-icons.ts +5 -0
  302. package/shared/types/containers/container.ts +1 -1
  303. package/shared/types/database/schema.ts +9 -6
  304. package/shared/types/git-identity.ts +1 -1
  305. package/shared/types/git.ts +116 -0
  306. package/shared/types/integrations.ts +7 -0
  307. package/shared/types/stores/settings.ts +1 -1
  308. package/shared/types/unified/index.ts +1 -1
  309. package/shared/types/unified/message.ts +0 -7
  310. package/shared/types/unified/stream.ts +2 -4
  311. package/shared/types/unified/tool.ts +15 -1
  312. package/shared/utils/ask-user-question.test.ts +319 -0
  313. package/shared/utils/ask-user-question.ts +154 -0
  314. package/shared/utils/home-project.ts +25 -0
  315. package/shared/utils/logger.ts +2 -0
  316. package/shared/utils/ws-server.ts +32 -7
  317. package/backend/auth/session-invalidation.test.ts +0 -112
  318. package/backend/auth/session-invalidation.ts +0 -77
  319. package/backend/project/status-manager.test.ts +0 -32
  320. package/backend/ws/auth/invites.ts +0 -94
  321. package/backend/ws/auth/users.ts +0 -112
  322. package/backend/ws/projects/presence.ts +0 -46
  323. package/backend/ws/stack/access.ts +0 -31
  324. package/dist/assets/main-BiDNMWb3.css +0 -1
  325. 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
@@ -25,7 +25,6 @@ export interface CheckpointNode {
25
25
  isCurrent: boolean; // this is the current active checkpoint
26
26
  hasSnapshot: boolean;
27
27
  isInitial?: boolean; // true for the "initial state" node
28
- senderName?: string | null;
29
28
  // File change statistics (git-like)
30
29
  filesChanged?: number;
31
30
  insertions?: number;
@@ -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
+ }
@@ -45,13 +45,12 @@ export const sshPtyKitServer = createPtyKitServer(sshPtyKitManager, {
45
45
  room: (ctx) => ctx.namespace,
46
46
  authorize: (ctx) => {
47
47
  const userId = ctx.conn.data.userId;
48
- const isAdmin = ctx.conn.data.isAdmin === true;
49
48
  if (typeof userId !== 'string' || !userId) return false;
50
49
 
51
50
  const connectionId = connectionIdFromNamespace(ctx.namespace);
52
51
  if (!connectionId) return false;
53
52
 
54
- return sshConnectionQueries.getForUser(connectionId, userId, isAdmin) !== null;
53
+ return sshConnectionQueries.get(connectionId) !== null;
55
54
  }
56
55
  });
57
56
 
@@ -41,7 +41,7 @@ export const ptyKitManager = new PtyKitManager({
41
41
  /**
42
42
  * Embedded WebSocket server over the manager. No HTTP/Bun mounting — Clopen's
43
43
  * tunnel feeds it frames and supplies per-connection `send`. `authorize` enforces
44
- * project access; the room is the project so output is collaborative.
44
+ * project access; the room is the project so every device sees the same output.
45
45
  */
46
46
  export const ptyKitServer = createPtyKitServer(ptyKitManager, {
47
47
  room: (ctx) => ctx.namespace,
@@ -49,19 +49,18 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
49
49
  const userId = ctx.conn.data.userId;
50
50
  if (typeof userId !== 'string' || !userId) return false;
51
51
  // The namespace separates worktrees; access is still the project's call.
52
- const allowed = projectQueries.userHasProject(userId, scopeProjectId(ctx.namespace));
52
+ const allowed = projectQueries.isListed(scopeProjectId(ctx.namespace));
53
53
  if (allowed) knownNamespaces.add(ctx.namespace);
54
54
  return allowed;
55
55
  },
56
56
  /**
57
- * The shell inherits the git identity of whoever opened it, for the project
58
- * it belongs to. Without this a `git commit` typed into the terminal would
57
+ * The shell inherits the git identity of the project it belongs to. Without this a `git commit` typed into the terminal would
59
58
  * use the machine's identity while the same commit from the Git panel used
60
59
  * the chosen one — the same repository, two different authors.
61
60
  *
62
61
  * Pointed at a FILE rather than given the `GIT_CONFIG_*` block the other
63
62
  * surfaces use. A shell lives for hours and its environment is fixed at
64
- * spawn, so an inlined identity goes stale the moment the user switches
63
+ * spawn, so an inlined identity goes stale the moment the project switches
65
64
  * accounts — silently, since the tab keeps working. Git re-reads a config
66
65
  * file on every invocation, so the switch reaches tabs that are already open.
67
66
  * See `backend/git/identity/scope-config.ts`.
@@ -71,9 +70,7 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
71
70
  * user's own global config away from every git command in the terminal.
72
71
  */
73
72
  env: async (ctx): Promise<Record<string, string>> => {
74
- const userId = ctx.conn.data.userId;
75
- if (typeof userId !== 'string' || !userId) return {};
76
- const path = await writeScopeConfig(userId, scopeProjectId(ctx.namespace));
73
+ const path = await writeScopeConfig(scopeProjectId(ctx.namespace));
77
74
  return path ? { GIT_CONFIG_GLOBAL: path } : {};
78
75
  }
79
76
  });
@@ -5,7 +5,7 @@
5
5
  * build share links against. Where that origin comes from is adaptive, so the
6
6
  * caller never has to think about tunnels vs domains:
7
7
  *
8
- * 1. `configured` — an admin-set public URL (system setting `publicBaseUrl`),
8
+ * 1. `configured` — a set public URL (system setting `publicBaseUrl`),
9
9
  * for VPS/reverse-proxy deployments where the browser can't see the real
10
10
  * hostname.
11
11
  * 2. `domain` — the browser is already hitting Clopen on a non-local origin
@@ -28,7 +28,7 @@ export interface PublicOrigin {
28
28
  }
29
29
 
30
30
  /** Hostnames that are not reachable by another device — force a tunnel. */
31
- function isLocalHostname(hostname: string): boolean {
31
+ export function isLocalHostname(hostname: string): boolean {
32
32
  const h = hostname.toLowerCase();
33
33
  if (h === 'localhost' || h.endsWith('.localhost')) return true;
34
34
  if (h === '127.0.0.1' || h === '::1' || h === '0.0.0.0') return true;
@@ -43,12 +43,12 @@ function isLocalHostname(hostname: string): boolean {
43
43
  return false;
44
44
  }
45
45
 
46
- /** Strip a trailing slash so callers can append `/#invite/...` cleanly. */
46
+ /** Strip a trailing slash so callers can append `/#device/...` cleanly. */
47
47
  function normalizeOrigin(url: string): string {
48
48
  return url.replace(/\/+$/, '');
49
49
  }
50
50
 
51
- /** Read the admin-configured public base URL from system settings, if any. */
51
+ /** Read the configured public base URL from system settings, if any. */
52
52
  function getConfiguredPublicBaseUrl(): string | null {
53
53
  return readSystemSetting((settings) => {
54
54
  const url = settings.publicBaseUrl;
@@ -66,19 +66,22 @@ function findQuickTunnelForPort(port: number): string | null {
66
66
  return null;
67
67
  }
68
68
 
69
+ /** The port another device must reach: Vite's in dev (it proxies to the backend), the server's in production. */
70
+ export function getClopenPublicPort(): number {
71
+ return SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
72
+ }
73
+
69
74
  /**
70
- * Resolve a public origin for Remote Access share links. `requestOrigin` is the
71
- * browser's own `window.location.origin` (passed by the client), used to detect
72
- * the already-public `domain` case.
75
+ * The public origin that already exists, if any — never starts anything.
76
+ *
77
+ * Same order as {@link resolvePublicOrigin}, minus the side effect. A caller
78
+ * reacting to a tunnel going away needs to know whether something is still
79
+ * reachable without restarting the very tunnel the user may just have stopped.
73
80
  */
74
- export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
75
- // 1. Explicitly configured public URL wins.
81
+ export function findPublicOrigin(requestOrigin?: string): PublicOrigin | null {
76
82
  const configured = getConfiguredPublicBaseUrl();
77
- if (configured) {
78
- return { origin: configured, source: 'configured' };
79
- }
83
+ if (configured) return { origin: configured, source: 'configured' };
80
84
 
81
- // 2. Already served on a real (non-local) origin — reuse it.
82
85
  if (requestOrigin) {
83
86
  try {
84
87
  const url = new URL(requestOrigin);
@@ -90,15 +93,23 @@ export async function resolvePublicOrigin(requestOrigin?: string): Promise<Publi
90
93
  }
91
94
  }
92
95
 
93
- // 3. Local install — tunnel Clopen's own port. In dev the app is served by
96
+ const existing = findQuickTunnelForPort(getClopenPublicPort());
97
+ return existing ? { origin: existing, source: 'tunnel' } : null;
98
+ }
99
+
100
+ /**
101
+ * Resolve a public origin for Remote Access share links. `requestOrigin` is the
102
+ * browser's own `window.location.origin` (passed by the client), used to detect
103
+ * the already-public `domain` case.
104
+ */
105
+ export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
106
+ const found = findPublicOrigin(requestOrigin);
107
+ if (found) return found;
108
+
109
+ // Local install — tunnel Clopen's own port. In dev the app is served by
94
110
  // Vite on PORT_FRONTEND (which proxies to the backend), so tunnel that; in
95
111
  // production frontend and backend share PORT.
96
- const port = SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
97
-
98
- const existing = findQuickTunnelForPort(port);
99
- if (existing) {
100
- return { origin: existing, source: 'tunnel' };
101
- }
112
+ const port = getClopenPublicPort();
102
113
 
103
114
  debug.log('tunnel', `[remote-access] Starting quick tunnel for Clopen port ${port}`);
104
115
  await tunnelKit.bin.ensure();
@@ -2,38 +2,6 @@
2
2
  * User domain helper functions
3
3
  */
4
4
 
5
- // List of friendly animal names for anonymous users
6
- export const ANIMAL_NAMES = [
7
- 'Penguin', 'Koala', 'Panda', 'Tiger', 'Lion', 'Eagle', 'Dolphin', 'Elephant',
8
- 'Giraffe', 'Zebra', 'Kangaroo', 'Octopus', 'Butterfly', 'Fox', 'Wolf', 'Bear',
9
- 'Rabbit', 'Deer', 'Owl', 'Hawk', 'Falcon', 'Parrot', 'Peacock', 'Swan',
10
- 'Flamingo', 'Pelican', 'Seal', 'Walrus', 'Otter', 'Beaver', 'Raccoon', 'Squirrel',
11
- 'Hedgehog', 'Hamster', 'Gecko', 'Chameleon', 'Turtle', 'Frog', 'Salamander', 'Newt',
12
- 'Shark', 'Whale', 'Stingray', 'Jellyfish', 'Starfish', 'Crab', 'Lobster', 'Shrimp',
13
- 'Ant', 'Bee', 'Ladybug', 'Dragonfly', 'Cricket', 'Grasshopper', 'Beetle', 'Moth',
14
- 'Cheetah', 'Jaguar', 'Leopard', 'Lynx', 'Cougar', 'Panther', 'Ocelot', 'Serval',
15
- 'Monkey', 'Gorilla', 'Chimpanzee', 'Orangutan', 'Lemur', 'Sloth', 'Armadillo', 'Pangolin',
16
- 'Platypus', 'Echidna', 'Wombat', 'Tasmanian', 'Quokka', 'Wallaby', 'Possum', 'Bandicoot',
17
- 'Meerkat', 'Mongoose', 'Ferret', 'Weasel', 'Badger', 'Skunk', 'Porcupine', 'Chinchilla',
18
- 'Capybara', 'Alpaca', 'Llama', 'Vicuna', 'Camel', 'Yak', 'Bison', 'Buffalo',
19
- 'Moose', 'Elk', 'Reindeer', 'Antelope', 'Gazelle', 'Impala', 'Wildebeest', 'Okapi'
20
- ];
21
-
22
- // Colors for additional uniqueness
23
- export const COLORS = [
24
- 'Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange', 'Pink', 'Brown',
25
- 'Gray', 'Black', 'White', 'Silver', 'Gold', 'Cyan', 'Magenta', 'Lime',
26
- 'Indigo', 'Violet', 'Turquoise', 'Coral', 'Salmon', 'Crimson', 'Navy', 'Teal'
27
- ];
28
-
29
- export interface AnonymousUser {
30
- id: string;
31
- name: string;
32
- color: string;
33
- avatar: string;
34
- createdAt: string;
35
- }
36
-
37
5
  /**
38
6
  * Generate a consistent color from a string
39
7
  */
@@ -62,26 +30,3 @@ export function getInitials(name: string): string {
62
30
  // Fallback to first 2 characters
63
31
  return trimmed.substring(0, 2).toUpperCase();
64
32
  }
65
-
66
- /**
67
- * Generate a unique anonymous user identity
68
- */
69
- export function generateAnonymousUser(): AnonymousUser {
70
- const randomAnimal = ANIMAL_NAMES[Math.floor(Math.random() * ANIMAL_NAMES.length)];
71
- const randomColor = COLORS[Math.floor(Math.random() * COLORS.length)];
72
- const randomNumber = Math.floor(Math.random() * 1000);
73
-
74
- const name = `${randomColor} ${randomAnimal} ${randomNumber}`;
75
- const id = `user-${crypto.randomUUID()}`; // Server-side crypto API
76
-
77
- // Generate a color for the avatar based on the name
78
- const avatarColor = generateColorFromString(name);
79
-
80
- return {
81
- id,
82
- name,
83
- color: avatarColor,
84
- avatar: getInitials(randomAnimal),
85
- createdAt: new Date().toISOString()
86
- };
87
- }