@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
@@ -77,10 +77,10 @@ export async function readMachineIdentity(): Promise<MachineIdentity | null> {
77
77
  /**
78
78
  * A label that says where the row came from without pretending to be a choice.
79
79
  *
80
- * Unique per user is enforced by the schema, so a collision with a manual
81
- * identity called "This machine" has to be resolved rather than thrown.
80
+ * Labels are unique, so a collision with a manual identity called "This
81
+ * machine" has to be resolved rather than thrown.
82
82
  */
83
- function machineLabel(userId: string, taken: (label: string) => boolean): string {
83
+ function machineLabel(taken: (label: string) => boolean): string {
84
84
  const base = 'This machine';
85
85
  if (!taken(base)) return base;
86
86
  for (let i = 2; i < 50; i++) {
@@ -88,20 +88,20 @@ function machineLabel(userId: string, taken: (label: string) => boolean): string
88
88
  if (!taken(candidate)) return candidate;
89
89
  }
90
90
  // Practically unreachable; a unique suffix beats failing the whole list read.
91
- return `${base} ${userId.slice(0, 6)}`;
91
+ return `${base} ${randomUUID().slice(0, 6)}`;
92
92
  }
93
93
 
94
94
  /**
95
- * Ensure the user's list reflects the machine's git config.
95
+ * Ensure the identity list reflects the machine's git config.
96
96
  *
97
97
  * Returns the mirrored row, or null when the machine has nothing to mirror.
98
98
  * Never throws: this runs on the read path for Settings, and a failure to mirror
99
99
  * must not take the whole list with it.
100
100
  */
101
- export async function syncLocalMachineIdentity(userId: string): Promise<GitIdentityRow | null> {
101
+ export async function syncLocalMachineIdentity(): Promise<GitIdentityRow | null> {
102
102
  try {
103
103
  const machine = await readMachineIdentity();
104
- const existing = gitIdentityQueries.getLocalMachine(userId);
104
+ const existing = gitIdentityQueries.getLocalMachine();
105
105
 
106
106
  if (!machine) {
107
107
  // Nothing to mirror. An existing row is left alone rather than deleted —
@@ -111,8 +111,8 @@ export async function syncLocalMachineIdentity(userId: string): Promise<GitIdent
111
111
  }
112
112
 
113
113
  if (!existing) {
114
- const label = machineLabel(userId, (l) => gitIdentityQueries.labelTaken(userId, l));
115
- const row = gitIdentityQueries.create(randomUUID(), userId, {
114
+ const label = machineLabel((l) => gitIdentityQueries.labelTaken(l));
115
+ const row = gitIdentityQueries.create(randomUUID(), {
116
116
  label,
117
117
  name: machine.name,
118
118
  email: machine.email,
@@ -124,10 +124,10 @@ export async function syncLocalMachineIdentity(userId: string): Promise<GitIdent
124
124
  });
125
125
  // Becoming the default is the point: a fresh install then commits as the
126
126
  // person the machine already says it is, with nothing to configure.
127
- if (!gitIdentityQueries.getDefaultForUser(userId)) {
128
- gitIdentityQueries.setDefault(userId, row.id);
127
+ if (!gitIdentityQueries.getDefault()) {
128
+ gitIdentityQueries.setDefault(row.id);
129
129
  }
130
- debug.log('git', `Imported the machine's git identity for user ${userId}`);
130
+ debug.log('git', "Imported the machine's git identity");
131
131
  return gitIdentityQueries.getById(row.id);
132
132
  }
133
133
 
@@ -4,13 +4,12 @@
4
4
  * Three seams the rest of Clopen uses:
5
5
  * - `gitIdentityService` — CRUD for the Settings surface.
6
6
  * - `resolveGitEnv` — the one call every git-running surface makes to get the
7
- * environment fragment for a (project, user). Panel, engine, and terminal all
7
+ * environment fragment for a project. Panel, engine, and terminal all
8
8
  * go through it so they cannot drift apart.
9
9
  * - `buildGitIdentityEnv` / `remoteHost` — the primitives, for tests and the
10
10
  * credential helper.
11
11
  */
12
12
 
13
- import { gitIdentityQueries } from '$backend/database/queries';
14
13
  import { buildGitIdentityEnv, remoteHost } from './env';
15
14
  import { helperCommand, pickCredentialIdentity, resolveIdentity, toEnvIdentity } from './resolve';
16
15
  import { toDTO } from './service';
@@ -21,30 +20,26 @@ export { buildGitIdentityEnv, buildGitConfigPairs, remoteHost } from './env';
21
20
  export type { GitEnvIdentity, HelperCommand } from './env';
22
21
  export { resolveIdentity, pickCredentialIdentity, toEnvIdentity, helperCommand } from './resolve';
23
22
  export { identityKeyPath, removeKeyFiles, writeKeyFile } from './keys';
24
- export { writeScopeConfig, removeScopeConfig, refreshScopeConfigsForUser, scopeConfigPath } from './scope-config';
23
+ export { writeScopeConfig, removeScopeConfig, refreshScopeConfigs, scopeConfigPath } from './scope-config';
25
24
  export { readMachineIdentity, syncLocalMachineIdentity } from './import-local';
26
25
 
27
26
  /**
28
- * The environment fragment for a (project, user), optionally scoped to a remote.
27
+ * The environment fragment for a project, optionally scoped to a remote.
29
28
  *
30
29
  * `remoteUrl` is what lets a fork workflow work: the host it points at decides
31
30
  * which identity's credential answers, while attribution always comes from the
32
31
  * project's own identity. Callers that are not talking to a remote (a commit, a
33
32
  * rebase) leave it out and get attribution only.
34
33
  *
35
- * Returns `{}` when the user has no identity, so every call site can merge the
34
+ * Returns `{}` when there is no identity, so every call site can merge the
36
35
  * result unconditionally.
37
36
  */
38
- export function resolveGitEnv(
39
- projectId: string,
40
- userId: string,
41
- remoteUrl?: string | null
42
- ): Record<string, string> {
43
- const { row } = resolveIdentity(projectId, userId);
37
+ export function resolveGitEnv(projectId: string, remoteUrl?: string | null): Record<string, string> {
38
+ const { row } = resolveIdentity(projectId);
44
39
  if (!row) return {};
45
40
 
46
41
  const host = remoteUrl ? remoteHost(remoteUrl) : null;
47
- const credential = pickCredentialIdentity(userId, host, row);
42
+ const credential = pickCredentialIdentity(host, row);
48
43
  return buildGitIdentityEnv(toEnvIdentity(row, credential), helperCommand());
49
44
  }
50
45
 
@@ -52,16 +47,12 @@ export function resolveGitEnv(
52
47
  * What the UI shows above the commit box: who this will be committed as, and
53
48
  * whether that was chosen for this project or inherited.
54
49
  */
55
- export function describeIdentity(
56
- projectId: string,
57
- userId: string,
58
- remoteUrl?: string | null
59
- ): ResolvedGitIdentity {
60
- const { row, source } = resolveIdentity(projectId, userId);
50
+ export function describeIdentity(projectId: string, remoteUrl?: string | null): ResolvedGitIdentity {
51
+ const { row, source } = resolveIdentity(projectId);
61
52
  if (!row) return { identity: null, source: 'none', credentialIdentity: null };
62
53
 
63
54
  const host = remoteUrl ? remoteHost(remoteUrl) : null;
64
- const credential = pickCredentialIdentity(userId, host, row);
55
+ const credential = pickCredentialIdentity(host, row);
65
56
 
66
57
  return {
67
58
  identity: toDTO(row),
@@ -71,8 +62,3 @@ export function describeIdentity(
71
62
  credentialIdentity: credential && credential.id !== row.id ? toDTO(credential) : null
72
63
  };
73
64
  }
74
-
75
- /** Every identity a user owns, as rows — for the credential helper. */
76
- export function identitiesOf(userId: string) {
77
- return gitIdentityQueries.listByUser(userId);
78
- }
@@ -2,13 +2,13 @@
2
2
  * Which identity a git command runs as.
3
3
  *
4
4
  * ── The chain ──
5
- * binding (project, user) → the user's default → nothing
5
+ * binding (project) → the default identity → nothing
6
6
  * "Nothing" is a real answer, not a failure: Clopen then runs git exactly as it
7
7
  * did before this feature existed, deferring to `.git/config` and the machine.
8
8
  * That is what keeps the feature opt-in for people who already have git set up.
9
9
  *
10
10
  * ── Why the credential can come from a different identity ──
11
- * Attribution is a property of the person; a credential is a property of the
11
+ * Attribution is a property of the author; a credential is a property of the
12
12
  * host. A fork workflow has `origin` on a personal account and `upstream` on a
13
13
  * work one, and the commits belong to the same human either way. So the
14
14
  * project's identity always decides `user.name`/`user.email`, while the
@@ -28,7 +28,7 @@ import type { GitEnvIdentity, HelperCommand } from './env';
28
28
  import { identityKeyPath } from './keys';
29
29
 
30
30
  /** Where the identity came from, for the "committing as…" line in the UI. */
31
- export type IdentitySource = 'project' | 'user-default' | 'none';
31
+ export type IdentitySource = 'project' | 'default' | 'none';
32
32
 
33
33
  export interface IdentityResolution {
34
34
  row: GitIdentityRow | null;
@@ -36,22 +36,22 @@ export interface IdentityResolution {
36
36
  }
37
37
 
38
38
  /**
39
- * The identity for a project, for one user.
39
+ * The identity for a project.
40
40
  *
41
- * A binding pointing at a deleted identity resolves to the user's default
42
- * rather than to nothing — `ON DELETE CASCADE` removes such bindings, so this
41
+ * A binding pointing at a deleted identity resolves to the default rather than
42
+ * to nothing — `ON DELETE CASCADE` removes such bindings, so this
43
43
  * only guards against a row that outlived its target.
44
44
  */
45
- export function resolveIdentity(projectId: string, userId: string): IdentityResolution {
46
- const binding = gitIdentityBindingQueries.get(projectId, userId);
45
+ export function resolveIdentity(projectId: string): IdentityResolution {
46
+ const binding = gitIdentityBindingQueries.get(projectId);
47
47
  if (binding) {
48
48
  const row = gitIdentityQueries.getById(binding.identity_id);
49
- if (row && row.owner_user_id === userId) return { row, source: 'project' };
49
+ if (row) return { row, source: 'project' };
50
50
  debug.warn('git', `Identity binding for project ${projectId} points at a missing identity`);
51
51
  }
52
52
 
53
- const fallback = gitIdentityQueries.getDefaultForUser(userId);
54
- return fallback ? { row: fallback, source: 'user-default' } : { row: null, source: 'none' };
53
+ const fallback = gitIdentityQueries.getDefault();
54
+ return fallback ? { row: fallback, source: 'default' } : { row: null, source: 'none' };
55
55
  }
56
56
 
57
57
  /** True when this identity can authenticate to `host`. */
@@ -64,7 +64,7 @@ function claimsHost(row: GitIdentityRow, host: string): boolean {
64
64
  * The identity whose credential should answer for `host`.
65
65
  *
66
66
  * Prefers the one already chosen for the project, so the common case never
67
- * looks past it. Otherwise the user's other identities are searched, and a
67
+ * looks past it. Otherwise the other identities are searched, and a
68
68
  * single match wins. AMBIGUITY IS RESOLVED AS "NO CREDENTIAL": if two
69
69
  * identities claim the same host, picking one arbitrarily would authenticate
70
70
  * as an account the user did not choose, and a push that fails asking for a
@@ -72,7 +72,6 @@ function claimsHost(row: GitIdentityRow, host: string): boolean {
72
72
  * wrong name.
73
73
  */
74
74
  export function pickCredentialIdentity(
75
- userId: string,
76
75
  host: string | null,
77
76
  primary: GitIdentityRow | null
78
77
  ): GitIdentityRow | null {
@@ -80,7 +79,7 @@ export function pickCredentialIdentity(
80
79
  if (primary && claimsHost(primary, host)) return primary;
81
80
 
82
81
  const candidates = gitIdentityQueries
83
- .listByUser(userId)
82
+ .list()
84
83
  .filter((row) => claimsHost(row, host));
85
84
 
86
85
  if (candidates.length === 1) return candidates[0]!;
@@ -1,6 +1,6 @@
1
1
  /**
2
- * A git config file per (user, project), for the one surface that outlives a
3
- * single command: the terminal.
2
+ * A git config file per project, for the one surface that outlives a single
3
+ * command: the terminal.
4
4
  *
5
5
  * ── The problem this solves ──
6
6
  * `GIT_CONFIG_*` is read from the environment, and a process's environment is
@@ -40,19 +40,26 @@ import { debug } from '$shared/utils/logger';
40
40
  import { buildGitConfigPairs } from './env';
41
41
  import { helperCommand, pickCredentialIdentity, resolveIdentity, toEnvIdentity } from './resolve';
42
42
 
43
- /** Where the generated per-scope config files live. */
43
+ /** Where the generated per-project config files live. */
44
44
  function scopeConfigDir(): string {
45
- return join(getClopenDir(), 'git-identities', 'scopes');
45
+ return join(getClopenDir(), 'git-identities', 'projects');
46
46
  }
47
47
 
48
48
  /**
49
- * Path of the config file for one (user, project).
50
- *
51
- * Both ids are in the name because the identity is chosen per pair — two people
52
- * in one project must not share a file.
49
+ * Files from when an identity was chosen per (user, project) lived in a sibling
50
+ * directory under a name no longer read. Dropped once per process, before the
51
+ * first write, so they do not linger next to the files that replaced them.
53
52
  */
54
- export function scopeConfigPath(userId: string, projectId: string): string {
55
- return join(scopeConfigDir(), `${userId}__${projectId}.gitconfig`);
53
+ let legacyScopesRemoved = false;
54
+ async function removeLegacyScopes(): Promise<void> {
55
+ if (legacyScopesRemoved) return;
56
+ legacyScopesRemoved = true;
57
+ await rm(join(getClopenDir(), 'git-identities', 'scopes'), { recursive: true, force: true }).catch(() => {});
58
+ }
59
+
60
+ /** Path of the config file for one project. */
61
+ export function scopeConfigPath(projectId: string): string {
62
+ return join(scopeConfigDir(), `${projectId}.gitconfig`);
56
63
  }
57
64
 
58
65
  /** The config files git would normally read as "global", in the order it does. */
@@ -82,7 +89,7 @@ function configValue(value: string): string {
82
89
  export function renderScopeConfig(pairs: Array<[string, string]>): string {
83
90
  const lines = [
84
91
  '# Generated by Clopen — do not edit.',
85
- '# Identity for one (user, project); regenerated whenever it changes.',
92
+ '# Identity for one project; regenerated whenever it changes.',
86
93
  ''
87
94
  ];
88
95
 
@@ -112,20 +119,18 @@ export function renderScopeConfig(pairs: Array<[string, string]>): string {
112
119
  }
113
120
 
114
121
  /**
115
- * Write (or remove) the config file for one (user, project).
122
+ * Write (or remove) the config file for one project.
116
123
  *
117
124
  * Returns the path when a file now exists, and `null` when there is nothing to
118
125
  * write. The caller must only set `GIT_CONFIG_GLOBAL` on a non-null result:
119
126
  * pointing it at a missing file would make git ignore the user's real global
120
127
  * config entirely, which is a far worse outcome than having no identity.
121
128
  */
122
- export async function writeScopeConfig(
123
- userId: string,
124
- projectId: string
125
- ): Promise<string | null> {
129
+ export async function writeScopeConfig(projectId: string): Promise<string | null> {
126
130
  try {
127
- const { row } = resolveIdentity(projectId, userId);
128
- const path = scopeConfigPath(userId, projectId);
131
+ await removeLegacyScopes();
132
+ const { row } = resolveIdentity(projectId);
133
+ const path = scopeConfigPath(projectId);
129
134
 
130
135
  if (!row) {
131
136
  // No identity — remove any file from a previous one, so a cleared
@@ -136,12 +141,12 @@ export async function writeScopeConfig(
136
141
 
137
142
  // No remote URL here: a terminal is not one command against one remote, so
138
143
  // the credential comes from the identity's own host claims.
139
- const credential = pickCredentialIdentity(userId, null, row);
144
+ const credential = pickCredentialIdentity(null, row);
140
145
  const pairs = buildGitConfigPairs(toEnvIdentity(row, credential), helperCommand());
141
146
 
142
147
  await mkdir(scopeConfigDir(), { recursive: true, mode: 0o700 });
143
148
  await writeFile(path, renderScopeConfig(pairs), { mode: 0o600 });
144
- debug.log('git', `Wrote git scope config for ${userId} in project ${projectId}`);
149
+ debug.log('git', `Wrote git scope config for project ${projectId}`);
145
150
  return path;
146
151
  } catch (error) {
147
152
  // A terminal with the machine's identity is a working terminal; failing to
@@ -151,9 +156,9 @@ export async function writeScopeConfig(
151
156
  }
152
157
  }
153
158
 
154
- /** Drop the file for one (user, project). */
155
- export async function removeScopeConfig(userId: string, projectId: string): Promise<void> {
156
- await rm(scopeConfigPath(userId, projectId), { force: true }).catch(() => {});
159
+ /** Drop the file for one project. */
160
+ export async function removeScopeConfig(projectId: string): Promise<void> {
161
+ await rm(scopeConfigPath(projectId), { force: true }).catch(() => {});
157
162
  }
158
163
 
159
164
  /**
@@ -161,14 +166,14 @@ export async function removeScopeConfig(userId: string, projectId: string): Prom
161
166
  *
162
167
  * Called after a create/update/delete/default change, so a shell that is already
163
168
  * open picks the new identity up on its next git command. Bindings naming the
164
- * identity are refreshed, and so is every project the user's default reaches —
165
- * which is why the project list is consulted rather than only the bindings.
169
+ * identity are refreshed, and so is every project the default reaches — which
170
+ * is why the project list is consulted rather than only the bindings.
166
171
  */
167
- export async function refreshScopeConfigsForUser(userId: string): Promise<void> {
172
+ export async function refreshScopeConfigs(): Promise<void> {
168
173
  try {
169
174
  const { projectQueries } = await import('$backend/database/queries');
170
- const projects = projectQueries.getAllForUser(userId);
171
- await Promise.all(projects.map((project) => writeScopeConfig(userId, project.id)));
175
+ const projects = projectQueries.getListed();
176
+ await Promise.all(projects.map((project) => writeScopeConfig(project.id)));
172
177
  } catch (error) {
173
178
  debug.warn('git', 'Could not refresh git scope configs:', error);
174
179
  }
@@ -26,7 +26,7 @@ import type {
26
26
  } from '$shared/types/git-identity';
27
27
  import { derivePublicKey, generateKeyPair, identityKeyPath, removeKeyFiles, writeKeyFile } from './keys';
28
28
  import { syncLocalMachineIdentity } from './import-local';
29
- import { refreshScopeConfigsForUser, writeScopeConfig } from './scope-config';
29
+ import { refreshScopeConfigs, writeScopeConfig } from './scope-config';
30
30
 
31
31
  /** Strip a row down to what a client may see. */
32
32
  export function toDTO(row: GitIdentityRow): GitIdentityDTO {
@@ -111,31 +111,29 @@ async function syncKeyFile(row: GitIdentityRow): Promise<GitIdentityRow> {
111
111
 
112
112
  export const gitIdentityService = {
113
113
  /**
114
- * Every identity this user owns, mirroring the machine's git config first.
114
+ * Every identity, mirroring the machine's git config first.
115
115
  *
116
- * Done on the read rather than at startup so it also covers a user who joins
117
- * later, and because it is the moment the result is actually about to be
118
- * shown. It is idempotent and only writes on the first call per user.
116
+ * Done on the read rather than at startup because it is the moment the result
117
+ * is actually about to be shown. It is idempotent and only writes once.
119
118
  */
120
- async list(userId: string): Promise<GitIdentityDTO[]> {
121
- await syncLocalMachineIdentity(userId);
122
- return gitIdentityQueries.listByUser(userId).map(toDTO);
119
+ async list(): Promise<GitIdentityDTO[]> {
120
+ await syncLocalMachineIdentity();
121
+ return gitIdentityQueries.list().map(toDTO);
123
122
  },
124
123
 
125
- get(userId: string, id: string): GitIdentityDTO | null {
124
+ get(id: string): GitIdentityDTO | null {
126
125
  const row = gitIdentityQueries.getById(id);
127
- if (!row || row.owner_user_id !== userId) return null;
128
- return toDTO(row);
126
+ return row ? toDTO(row) : null;
129
127
  },
130
128
 
131
- async create(userId: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
129
+ async create(input: GitIdentityInput): Promise<GitIdentityDTO> {
132
130
  assertValid(input);
133
- if (gitIdentityQueries.labelTaken(userId, input.label.trim())) {
131
+ if (gitIdentityQueries.labelTaken(input.label.trim())) {
134
132
  throw new Error(`You already have an identity called "${input.label.trim()}"`);
135
133
  }
136
134
 
137
135
  const id = randomUUID();
138
- let row = gitIdentityQueries.create(id, userId, {
136
+ let row = gitIdentityQueries.create(id, {
139
137
  label: input.label.trim(),
140
138
  name: input.name.trim(),
141
139
  email: input.email.trim(),
@@ -151,28 +149,28 @@ export const gitIdentityService = {
151
149
 
152
150
  row = await syncKeyFile(row);
153
151
 
154
- // The first identity a user creates becomes their default — otherwise it
155
- // would sit there doing nothing until they found the toggle, which reads
156
- // as the feature being broken.
157
- if (input.isDefault || gitIdentityQueries.listByUser(userId).length === 1) {
158
- gitIdentityQueries.setDefault(userId, id);
152
+ // The first identity created becomes the default — otherwise it would sit
153
+ // there doing nothing until someone found the toggle, which reads as the
154
+ // feature being broken.
155
+ if (input.isDefault || gitIdentityQueries.list().length === 1) {
156
+ gitIdentityQueries.setDefault(id);
159
157
  row = gitIdentityQueries.getById(id)!;
160
158
  }
161
159
 
162
160
  // Terminals that are already open read their identity from a file, so it is
163
161
  // rewritten here — otherwise the new account would only reach tabs opened
164
162
  // after this point.
165
- await refreshScopeConfigsForUser(userId);
163
+ await refreshScopeConfigs();
166
164
 
167
- debug.log('git', `Created git identity "${row.label}" for user ${userId}`);
165
+ debug.log('git', `Created git identity "${row.label}"`);
168
166
  return toDTO(row);
169
167
  },
170
168
 
171
- async update(userId: string, id: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
169
+ async update(id: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
172
170
  assertValid(input);
173
171
  const existing = gitIdentityQueries.getById(id);
174
- if (!existing || existing.owner_user_id !== userId) throw new Error('Identity not found');
175
- if (gitIdentityQueries.labelTaken(userId, input.label.trim(), id)) {
172
+ if (!existing) throw new Error('Identity not found');
173
+ if (gitIdentityQueries.labelTaken(input.label.trim(), id)) {
176
174
  throw new Error(`You already have an identity called "${input.label.trim()}"`);
177
175
  }
178
176
 
@@ -199,19 +197,19 @@ export const gitIdentityService = {
199
197
  row = await syncKeyFile(row);
200
198
 
201
199
  if (input.isDefault && row.is_default !== 1) {
202
- gitIdentityQueries.setDefault(userId, id);
200
+ gitIdentityQueries.setDefault(id);
203
201
  row = gitIdentityQueries.getById(id)!;
204
202
  }
205
203
 
206
- await refreshScopeConfigsForUser(userId);
204
+ await refreshScopeConfigs();
207
205
 
208
206
  debug.log('git', `Updated git identity "${row.label}"`);
209
207
  return toDTO(row);
210
208
  },
211
209
 
212
- async remove(userId: string, id: string): Promise<void> {
210
+ async remove(id: string): Promise<void> {
213
211
  const row = gitIdentityQueries.getById(id);
214
- if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
212
+ if (!row) throw new Error('Identity not found');
215
213
  if (row.source === 'local-machine') {
216
214
  throw new Error(
217
215
  "This account mirrors the machine's own git config, so it cannot be deleted. Edit it instead."
@@ -221,24 +219,24 @@ export const gitIdentityService = {
221
219
  gitIdentityQueries.remove(id);
222
220
  await removeKeyFiles(id);
223
221
 
224
- // Deleting the default leaves the user with none, so the next one in the
225
- // list takes over rather than every project silently losing its identity.
222
+ // Deleting the default leaves none, so the next one in the list takes over
223
+ // rather than every project silently losing its identity.
226
224
  if (row.is_default === 1) {
227
- const remaining = gitIdentityQueries.listByUser(userId);
228
- if (remaining.length > 0) gitIdentityQueries.setDefault(userId, remaining[0]!.id);
225
+ const remaining = gitIdentityQueries.list();
226
+ if (remaining.length > 0) gitIdentityQueries.setDefault(remaining[0]!.id);
229
227
  }
230
228
 
231
- await refreshScopeConfigsForUser(userId);
229
+ await refreshScopeConfigs();
232
230
 
233
231
  debug.log('git', `Removed git identity "${row.label}"`);
234
232
  },
235
233
 
236
- async setDefault(userId: string, id: string): Promise<GitIdentityDTO> {
234
+ async setDefault(id: string): Promise<GitIdentityDTO> {
237
235
  const row = gitIdentityQueries.getById(id);
238
- if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
239
- gitIdentityQueries.setDefault(userId, id);
236
+ if (!row) throw new Error('Identity not found');
237
+ gitIdentityQueries.setDefault(id);
240
238
  // Every project that inherits the default is affected, not just one.
241
- await refreshScopeConfigsForUser(userId);
239
+ await refreshScopeConfigs();
242
240
  return toDTO(gitIdentityQueries.getById(id)!);
243
241
  },
244
242
 
@@ -248,9 +246,9 @@ export const gitIdentityService = {
248
246
  * Returns only the public key and its fingerprint; the private key goes
249
247
  * straight into the sealed column and the 0600 file.
250
248
  */
251
- async generateKey(userId: string, id: string): Promise<GeneratedSshKey> {
249
+ async generateKey(id: string): Promise<GeneratedSshKey> {
252
250
  const row = gitIdentityQueries.getById(id);
253
- if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
251
+ if (!row) throw new Error('Identity not found');
254
252
 
255
253
  const { privateKey, publicKey, fingerprint } = await generateKeyPair(
256
254
  id,
@@ -271,23 +269,22 @@ export const gitIdentityService = {
271
269
  integrationAccountId: row.integration_account_id
272
270
  });
273
271
 
274
- await refreshScopeConfigsForUser(userId);
272
+ await refreshScopeConfigs();
275
273
 
276
274
  debug.log('git', `Generated SSH key for identity "${row.label}"`);
277
275
  return { publicKey, fingerprint };
278
276
  },
279
277
 
280
- /** Bind a project to an identity, for this user. */
281
- async bind(userId: string, projectId: string, identityId: string | null): Promise<void> {
278
+ /** Bind a project to an identity. */
279
+ async bind(projectId: string, identityId: string | null): Promise<void> {
282
280
  if (identityId === null) {
283
- gitIdentityBindingQueries.clear(projectId, userId);
281
+ gitIdentityBindingQueries.clear(projectId);
284
282
  } else {
285
- const row = gitIdentityQueries.getById(identityId);
286
- if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
287
- gitIdentityBindingQueries.set(projectId, userId, identityId);
283
+ if (!gitIdentityQueries.getById(identityId)) throw new Error('Identity not found');
284
+ gitIdentityBindingQueries.set(projectId, identityId);
288
285
  }
289
286
  // Only this project's file can have changed, so only it is rewritten.
290
- await writeScopeConfig(userId, projectId);
287
+ await writeScopeConfig(projectId);
291
288
  },
292
289
 
293
290
  /** How many projects would lose their binding if this identity went away. */
@@ -0,0 +1,111 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { GitBusyError, getScopeOpStates, hasProjectOps, onGitOpChange, withGitOpLock } from './op-lock';
3
+ import type { GitRepoOpState } from '$shared/types/git';
4
+
5
+ let counter = 0;
6
+ /** A fresh repository key per test, so tests never share a lock. */
7
+ function key(scope = 'project-a') {
8
+ return { cwd: `/tmp/op-lock-test-${++counter}`, scope };
9
+ }
10
+
11
+ function deferred() {
12
+ let resolve!: () => void;
13
+ const promise = new Promise<void>(r => (resolve = r));
14
+ return { promise, resolve };
15
+ }
16
+
17
+ describe('withGitOpLock', () => {
18
+ test('refuses an exclusive operation while another runs, naming it', async () => {
19
+ const repo = key();
20
+ const gate = deferred();
21
+ const pull = withGitOpLock(repo, { category: 'pull', label: 'Pull', target: 'main' }, () => gate.promise);
22
+
23
+ const push = withGitOpLock(repo, { category: 'push', label: 'Push' }, async () => 'pushed');
24
+ await expect(push).rejects.toBeInstanceOf(GitBusyError);
25
+ await expect(push).rejects.toThrow(/Pull \(main\) is still running/);
26
+
27
+ gate.resolve();
28
+ await pull;
29
+ expect(await withGitOpLock(repo, { category: 'push', label: 'Push' }, async () => 'pushed')).toBe('pushed');
30
+ });
31
+
32
+ test('lets staging run while a network operation is in flight', async () => {
33
+ const repo = key();
34
+ const gate = deferred();
35
+ const push = withGitOpLock(repo, { category: 'push', label: 'Push' }, () => gate.promise);
36
+ expect(await withGitOpLock(repo, { category: 'staging', label: 'Staging' }, async () => 'staged')).toBe('staged');
37
+ gate.resolve();
38
+ await push;
39
+ });
40
+
41
+ test('refuses a second network operation', async () => {
42
+ const repo = key();
43
+ const gate = deferred();
44
+ const push = withGitOpLock(repo, { category: 'push', label: 'Push' }, () => gate.promise);
45
+ await expect(withGitOpLock(repo, { category: 'fetch', label: 'Fetch' }, async () => {})).rejects.toBeInstanceOf(
46
+ GitBusyError
47
+ );
48
+ gate.resolve();
49
+ await push;
50
+ });
51
+
52
+ test('queues index writes behind each other instead of refusing', async () => {
53
+ const repo = key();
54
+ const order: string[] = [];
55
+ const gate = deferred();
56
+ const first = withGitOpLock(repo, { category: 'staging', label: 'Staging', queue: true }, async () => {
57
+ await gate.promise;
58
+ order.push('first');
59
+ });
60
+ const second = withGitOpLock(repo, { category: 'staging', label: 'Staging', queue: true }, async () => {
61
+ order.push('second');
62
+ });
63
+ gate.resolve();
64
+ await Promise.all([first, second]);
65
+ expect(order).toEqual(['first', 'second']);
66
+ });
67
+
68
+ test('a queued index write still refuses an exclusive holder', async () => {
69
+ const repo = key();
70
+ const gate = deferred();
71
+ const commit = withGitOpLock(repo, { category: 'commit', label: 'Commit' }, () => gate.promise);
72
+ await expect(
73
+ withGitOpLock(repo, { category: 'staging', label: 'Staging', queue: true }, async () => {})
74
+ ).rejects.toBeInstanceOf(GitBusyError);
75
+ gate.resolve();
76
+ await commit;
77
+ });
78
+
79
+ test('releases the lock when the operation throws', async () => {
80
+ const repo = key();
81
+ await expect(
82
+ withGitOpLock(repo, { category: 'pull', label: 'Pull' }, async () => {
83
+ throw new Error('boom');
84
+ })
85
+ ).rejects.toThrow('boom');
86
+ expect(await withGitOpLock(repo, { category: 'pull', label: 'Pull' }, async () => 'again')).toBe('again');
87
+ });
88
+
89
+ test('reports state to listeners and snapshots, per scope and project', async () => {
90
+ const repo = { ...key('project-b~wt1'), repoPath: '/nested' };
91
+ const seen: GitRepoOpState[] = [];
92
+ const stop = onGitOpChange(state => {
93
+ if (state.scope === 'project-b~wt1') seen.push(state);
94
+ });
95
+ const gate = deferred();
96
+ const running = withGitOpLock(repo, { category: 'fetch', label: 'Fetch', target: 'origin' }, () => gate.promise);
97
+
98
+ expect(getScopeOpStates('project-b~wt1')).toHaveLength(1);
99
+ expect(getScopeOpStates('project-b~wt1')[0].repoPath).toBe('/nested');
100
+ expect(getScopeOpStates('project-b')).toHaveLength(0);
101
+ expect(hasProjectOps('project-b')).toBe(true);
102
+
103
+ gate.resolve();
104
+ await running;
105
+ stop();
106
+
107
+ expect(seen.map(s => s.ops.length)).toEqual([1, 0]);
108
+ expect(seen[0].ops[0]).toMatchObject({ category: 'fetch', cls: 'network', target: 'origin' });
109
+ expect(hasProjectOps('project-b')).toBe(false);
110
+ });
111
+ });