@myrialabs/clopen 0.4.46 → 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 (328) 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/presets.ts +27 -2
  85. package/backend/engine/adapters/opencode/server.ts +6 -4
  86. package/backend/engine/adapters/opencode/stream.ts +11 -0
  87. package/backend/engine/adapters/parent-scope.test.ts +38 -0
  88. package/backend/engine/adapters/parent-scope.ts +44 -0
  89. package/backend/engine/adapters/pi/message-converter.ts +0 -1
  90. package/backend/engine/adapters/pi/stream.ts +4 -5
  91. package/backend/engine/adapters/qwen/message-converter.ts +0 -2
  92. package/backend/engine/bootstrap-default-engine.ts +2 -2
  93. package/backend/engine/docs/adapter-contract.md +8 -1
  94. package/backend/engine/install-runner.ts +8 -17
  95. package/backend/files/file-shares.ts +20 -44
  96. package/backend/files/file-size-limit.ts +3 -3
  97. package/backend/files/image-processing.ts +1 -1
  98. package/backend/files/os-clipboard.ts +2 -2
  99. package/backend/git/git-executor.ts +25 -5
  100. package/backend/git/git-service.ts +420 -19
  101. package/backend/git/identity/credential-helper.test.ts +2 -7
  102. package/backend/git/identity/import-local.test.ts +11 -16
  103. package/backend/git/identity/import-local.ts +12 -12
  104. package/backend/git/identity/index.ts +10 -24
  105. package/backend/git/identity/resolve.ts +13 -14
  106. package/backend/git/identity/scope-config.ts +33 -28
  107. package/backend/git/identity/service.ts +44 -47
  108. package/backend/git/op-lock.test.ts +111 -0
  109. package/backend/git/op-lock.ts +180 -0
  110. package/backend/git/remote-sync.test.ts +249 -0
  111. package/backend/host/metrics.ts +1 -1
  112. package/backend/http/bearer-auth.ts +1 -2
  113. package/backend/http/files-download.test.ts +8 -9
  114. package/backend/http/files-download.ts +2 -2
  115. package/backend/http/files-shared.test.ts +62 -89
  116. package/backend/http/files-shared.ts +2 -2
  117. package/backend/http/files-upload.test.ts +3 -7
  118. package/backend/http/files-upload.ts +3 -3
  119. package/backend/http/notes-images.test.ts +15 -38
  120. package/backend/http/notes-images.ts +6 -8
  121. package/backend/http/ssh-sftp.ts +5 -10
  122. package/backend/index.ts +21 -7
  123. package/backend/integrations/accounts.ts +61 -3
  124. package/backend/integrations/index.ts +2 -2
  125. package/backend/integrations/registry/define.ts +15 -0
  126. package/backend/integrations/registry/index.ts +2 -0
  127. package/backend/integrations/registry/providers/telegram.ts +54 -0
  128. package/backend/integrations/registry/types.ts +21 -1
  129. package/backend/integrations/webhooks/gateway.ts +7 -6
  130. package/backend/integrations/webhooks/verify.test.ts +30 -0
  131. package/backend/integrations/webhooks/verify.ts +4 -0
  132. package/backend/mcp/external/project.ts +1 -1
  133. package/backend/mcp/internal/remote-server.test.ts +1 -3
  134. package/backend/mcp/internal/remote-server.ts +4 -4
  135. package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
  136. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
  137. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
  138. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
  139. package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
  140. package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
  141. package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
  142. package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
  143. package/backend/memory/redact.ts +1 -1
  144. package/backend/notes/access.test.ts +28 -29
  145. package/backend/notes/access.ts +6 -11
  146. package/backend/permissions/service.ts +1 -1
  147. package/backend/preview/browser/browser-clipboard.test.ts +46 -0
  148. package/backend/preview/browser/browser-clipboard.ts +67 -0
  149. package/backend/preview/browser/browser-dialog-handler.ts +95 -6
  150. package/backend/preview/browser/browser-host-bridge.ts +9 -0
  151. package/backend/preview/browser/browser-interaction-handler.ts +316 -86
  152. package/backend/preview/browser/browser-mcp-control.ts +34 -0
  153. package/backend/preview/browser/browser-pool.ts +67 -6
  154. package/backend/preview/browser/browser-preview-service.ts +361 -25
  155. package/backend/preview/browser/browser-tab-manager.ts +66 -23
  156. package/backend/preview/browser/browser-video-capture.ts +92 -5
  157. package/backend/preview/browser/element-locator.ts +190 -17
  158. package/backend/preview/browser/keyboard-chords.test.ts +68 -0
  159. package/backend/preview/browser/keyboard-chords.ts +132 -0
  160. package/backend/preview/browser/paste.ts +81 -0
  161. package/backend/preview/browser/process-usage.ts +142 -0
  162. package/backend/preview/browser/profile-lock.ts +209 -0
  163. package/backend/preview/browser/scripts/host-bridge.ts +59 -0
  164. package/backend/preview/browser/scripts/video-stream.ts +58 -0
  165. package/backend/preview/browser/types.ts +40 -2
  166. package/backend/preview/browser/viewport.test.ts +45 -0
  167. package/backend/preview/browser/viewport.ts +96 -0
  168. package/backend/profiles/service.ts +2 -2
  169. package/backend/project/status-manager.ts +43 -172
  170. package/backend/projects/home.ts +61 -0
  171. package/backend/projects/project-cleanup.integration.test.ts +2 -2
  172. package/backend/projects/project-cleanup.ts +0 -8
  173. package/backend/skills/service.ts +2 -3
  174. package/backend/snapshot/helpers.ts +0 -1
  175. package/backend/snapshot/restore.ts +252 -0
  176. package/backend/ssh/ptykit.ts +1 -2
  177. package/backend/terminal/ptykit.ts +5 -8
  178. package/backend/tunnel/public-origin.ts +31 -20
  179. package/backend/utils/user-helpers.ts +0 -55
  180. package/backend/utils/ws.ts +61 -154
  181. package/backend/worktrees/branching/engine.ts +3 -16
  182. package/backend/worktrees/branching/index.ts +1 -1
  183. package/backend/worktrees/branching/projector.ts +1 -1
  184. package/backend/worktrees/branching/service.ts +13 -25
  185. package/backend/ws/access.ts +12 -21
  186. package/backend/ws/artifacts/generate.ts +2 -2
  187. package/backend/ws/auth/device.ts +16 -71
  188. package/backend/ws/auth/index.ts +4 -22
  189. package/backend/ws/auth/login.test.ts +14 -60
  190. package/backend/ws/auth/login.ts +24 -124
  191. package/backend/ws/auth/status.ts +0 -1
  192. package/backend/ws/chat/composer.ts +118 -118
  193. package/backend/ws/chat/stream.ts +64 -47
  194. package/backend/ws/chat-apps/index.ts +117 -0
  195. package/backend/ws/containers/actions.ts +11 -25
  196. package/backend/ws/containers/index.ts +3 -4
  197. package/backend/ws/containers/list.ts +10 -36
  198. package/backend/ws/containers/logs.ts +2 -2
  199. package/backend/ws/containers/tunnel.ts +1 -2
  200. package/backend/ws/db-client/access.ts +2 -16
  201. package/backend/ws/db-client/accounts.ts +5 -15
  202. package/backend/ws/db-client/connections.ts +17 -25
  203. package/backend/ws/db-client/context.ts +1 -1
  204. package/backend/ws/db-client/env.ts +7 -10
  205. package/backend/ws/db-client/index.ts +2 -2
  206. package/backend/ws/db-client/io.ts +5 -5
  207. package/backend/ws/db-client/query-history-retention.test.ts +8 -8
  208. package/backend/ws/db-client/query.ts +18 -17
  209. package/backend/ws/db-client/schema.ts +13 -13
  210. package/backend/ws/db-client/structure.ts +35 -35
  211. package/backend/ws/db-client/supabase.ts +4 -21
  212. package/backend/ws/deployments/context.ts +1 -1
  213. package/backend/ws/deployments/crud.ts +0 -5
  214. package/backend/ws/engine/access.ts +7 -20
  215. package/backend/ws/engine/claude/accounts.ts +4 -4
  216. package/backend/ws/engine/cline/accounts.ts +5 -5
  217. package/backend/ws/engine/codex/accounts.ts +3 -3
  218. package/backend/ws/engine/opencode/providers.ts +2 -1
  219. package/backend/ws/engine/pi/accounts.ts +5 -5
  220. package/backend/ws/files/clipboard.ts +8 -27
  221. package/backend/ws/files/image-edit.ts +6 -6
  222. package/backend/ws/files/index.ts +1 -1
  223. package/backend/ws/files/path-access.test.ts +32 -131
  224. package/backend/ws/files/path-access.ts +8 -87
  225. package/backend/ws/files/read.ts +15 -19
  226. package/backend/ws/files/reveal.ts +3 -3
  227. package/backend/ws/files/search.ts +7 -7
  228. package/backend/ws/files/share.ts +9 -13
  229. package/backend/ws/files/state.ts +9 -12
  230. package/backend/ws/files/watch.ts +3 -3
  231. package/backend/ws/files/write.ts +30 -31
  232. package/backend/ws/git/branch.ts +80 -59
  233. package/backend/ws/git/commit.ts +63 -44
  234. package/backend/ws/git/conflict.ts +16 -18
  235. package/backend/ws/git/identity-context.ts +8 -17
  236. package/backend/ws/git/identity.ts +17 -27
  237. package/backend/ws/git/index.ts +3 -1
  238. package/backend/ws/git/op-state.ts +139 -0
  239. package/backend/ws/git/remote.ts +241 -141
  240. package/backend/ws/git/repo-context.ts +67 -0
  241. package/backend/ws/git/staging.ts +18 -28
  242. package/backend/ws/git/status.ts +5 -2
  243. package/backend/ws/index.ts +5 -1
  244. package/backend/ws/instructions/crud.ts +1 -1
  245. package/backend/ws/integrations/crud.ts +1 -3
  246. package/backend/ws/mcp/crud.ts +3 -5
  247. package/backend/ws/mcp/tools.ts +1 -1
  248. package/backend/ws/memory/crud.ts +14 -46
  249. package/backend/ws/memory/index.ts +2 -2
  250. package/backend/ws/messages/crud.ts +29 -8
  251. package/backend/ws/notes/index.ts +33 -39
  252. package/backend/ws/permissions/crud.ts +3 -4
  253. package/backend/ws/ports/index.ts +1 -2
  254. package/backend/ws/ports/kill.ts +5 -10
  255. package/backend/ws/ports/list.ts +4 -10
  256. package/backend/ws/preview/access.ts +1 -1
  257. package/backend/ws/preview/browser/interact.ts +52 -79
  258. package/backend/ws/preview/browser/native-ui.ts +24 -0
  259. package/backend/ws/preview/browser/stats.ts +98 -1
  260. package/backend/ws/preview/browser/tab-info.ts +15 -0
  261. package/backend/ws/preview/browser/tab.ts +19 -4
  262. package/backend/ws/preview/index.ts +27 -0
  263. package/backend/ws/profiles/crud.ts +6 -8
  264. package/backend/ws/project-artifacts/index.ts +30 -31
  265. package/backend/ws/projects/crud.ts +33 -35
  266. package/backend/ws/projects/index.ts +3 -8
  267. package/backend/ws/projects/info.ts +3 -3
  268. package/backend/ws/projects/overview.ts +19 -30
  269. package/backend/ws/projects/status.ts +17 -57
  270. package/backend/ws/sessions/crud.ts +34 -45
  271. package/backend/ws/sessions/index.ts +1 -1
  272. package/backend/ws/settings/crud.ts +1 -1
  273. package/backend/ws/skills/crud.ts +3 -4
  274. package/backend/ws/skills/index.ts +1 -1
  275. package/backend/ws/snapshot/changes.ts +7 -7
  276. package/backend/ws/snapshot/restore.ts +11 -295
  277. package/backend/ws/snapshot/timeline.ts +2 -4
  278. package/backend/ws/ssh/access.ts +6 -21
  279. package/backend/ws/ssh/connections.ts +21 -31
  280. package/backend/ws/ssh/forwards.ts +12 -12
  281. package/backend/ws/ssh/sftp.ts +34 -34
  282. package/backend/ws/ssh/tunnel.ts +1 -2
  283. package/backend/ws/stack/install.ts +7 -17
  284. package/backend/ws/subagents/crud.ts +1 -1
  285. package/backend/ws/tunnel/share.ts +0 -2
  286. package/backend/ws/user/crud.ts +1 -59
  287. package/backend/ws/user/index.ts +1 -1
  288. package/backend/ws/work/context.ts +1 -1
  289. package/backend/ws/work/crud.ts +0 -5
  290. package/backend/ws/workspace/state.ts +10 -13
  291. package/backend/ws/worktrees/branching.ts +7 -36
  292. package/backend/ws/worktrees/crud.ts +2 -2
  293. package/bin/clopen.ts +10 -11
  294. package/dist/assets/{index-CwuKQelV.js → index-CONlwAXZ.js} +1 -1
  295. package/dist/assets/{index-BTcR1byF.js → index-DJzwt-hq.js} +1 -1
  296. package/dist/assets/main-BUiUL3eZ.css +1 -0
  297. package/dist/assets/main-nBOb9YOA.js +1240 -0
  298. package/dist/index.html +2 -2
  299. package/package.json +2 -1
  300. package/shared/constants/attachments.ts +14 -0
  301. package/shared/constants/engine-tools.ts +1 -1
  302. package/shared/constants/preview.test.ts +259 -0
  303. package/shared/constants/preview.ts +1018 -57
  304. package/shared/constants/tool-icons.ts +5 -0
  305. package/shared/types/containers/container.ts +1 -1
  306. package/shared/types/database/schema.ts +9 -6
  307. package/shared/types/git-identity.ts +1 -1
  308. package/shared/types/git.ts +116 -0
  309. package/shared/types/integrations.ts +7 -0
  310. package/shared/types/stores/settings.ts +1 -1
  311. package/shared/types/unified/index.ts +1 -1
  312. package/shared/types/unified/message.ts +0 -7
  313. package/shared/types/unified/stream.ts +2 -4
  314. package/shared/types/unified/tool.ts +15 -1
  315. package/shared/utils/ask-user-question.test.ts +319 -0
  316. package/shared/utils/ask-user-question.ts +154 -0
  317. package/shared/utils/home-project.ts +25 -0
  318. package/shared/utils/logger.ts +2 -0
  319. package/shared/utils/ws-server.ts +32 -7
  320. package/backend/auth/session-invalidation.test.ts +0 -112
  321. package/backend/auth/session-invalidation.ts +0 -77
  322. package/backend/project/status-manager.test.ts +0 -32
  323. package/backend/ws/auth/invites.ts +0 -94
  324. package/backend/ws/auth/users.ts +0 -112
  325. package/backend/ws/projects/presence.ts +0 -46
  326. package/backend/ws/stack/access.ts +0 -31
  327. package/dist/assets/main-BiDNMWb3.css +0 -1
  328. package/dist/assets/main-BlhKWz2B.js +0 -1241
@@ -33,7 +33,12 @@ import type {
33
33
  GitConflictKind,
34
34
  GitConflictResolution,
35
35
  GitOperationState,
36
- GitReflogEntry
36
+ GitReflogEntry,
37
+ GitPullMode,
38
+ GitPullResult,
39
+ GitForcePullPreview,
40
+ GitForcePullResult,
41
+ GitPruneCandidate
37
42
  } from '$shared/types/git';
38
43
  import { naturalCompare } from '$shared/utils/compare';
39
44
  import { debug } from '$shared/utils/logger';
@@ -47,6 +52,14 @@ import {
47
52
  } from './git-spawn-validation';
48
53
  import { findNestedRepoPaths, findSubmodulePaths } from './nested-repos';
49
54
  import path from 'node:path';
55
+ import { existsSync } from 'node:fs';
56
+
57
+ /**
58
+ * Ceiling for anything that talks to a remote. A large fetch over a slow link
59
+ * routinely needs more than a minute, and the old 60s cut-off killed it midway
60
+ * with an empty error.
61
+ */
62
+ export const NETWORK_TIMEOUT_MS = 5 * 60 * 1000;
50
63
 
51
64
  export class GitService {
52
65
  /**
@@ -384,11 +397,12 @@ export class GitService {
384
397
  // Try to get the initial branch name from HEAD
385
398
  const headResult = await execGit(['symbolic-ref', '--short', 'HEAD'], cwd);
386
399
  const initialBranch = headResult.exitCode === 0 ? headResult.stdout.trim() : 'main';
387
- return { current: initialBranch, local: [], remote: [], ahead: 0, behind: 0 };
400
+ return { current: initialBranch, local: [], remote: [], ahead: 0, behind: 0, ...this.repoCapabilities(cwd) };
388
401
  }
389
402
 
390
403
  const branchInfo = parseBranches(localResult.stdout, remoteResult.stdout);
391
404
  branchInfo.operation = await this.detectGitOperation(cwd);
405
+ Object.assign(branchInfo, this.repoCapabilities(cwd));
392
406
 
393
407
  // Resolve the current branch authoritatively instead of trusting the parsed
394
408
  // `git branch -v` text: while HEAD is detached (rebase, bisect, or a detached
@@ -548,7 +562,7 @@ export class GitService {
548
562
  async deleteRemoteBranch(cwd: string, remote: string, branch: string, identityEnv: GitIdentityEnv = {}): Promise<void> {
549
563
  assertSafeGitRevish(remote, 'remote name');
550
564
  assertSafeGitRevish(branch, 'branch name');
551
- const result = await execGit(['push', remote, '--delete', branch], cwd, { env: identityEnv });
565
+ const result = await execGit(['push', remote, '--delete', branch], cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv });
552
566
  if (result.exitCode !== 0) {
553
567
  throw new Error(`git push --delete failed: ${result.stderr}`);
554
568
  }
@@ -633,6 +647,17 @@ export class GitService {
633
647
  // Remote Operations
634
648
  // ============================================
635
649
 
650
+ /**
651
+ * What the repo root offers beyond git itself. The More menu only lists
652
+ * `npm version` and submodule updates where they can actually run.
653
+ */
654
+ private repoCapabilities(cwd: string): { hasSubmodules: boolean; hasPackageJson: boolean } {
655
+ return {
656
+ hasSubmodules: existsSync(path.join(cwd, '.gitmodules')),
657
+ hasPackageJson: existsSync(path.join(cwd, 'package.json'))
658
+ };
659
+ }
660
+
636
661
  async getRemotes(cwd: string): Promise<GitRemote[]> {
637
662
  const result = await execGit(['remote', '-v'], cwd);
638
663
  return parseRemotes(result.stdout);
@@ -641,7 +666,7 @@ export class GitService {
641
666
  async fetch(cwd: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<string> {
642
667
  assertSafeGitRemoteName(remote);
643
668
  // Use explicit refspec to ensure all branches are fetched regardless of clone config
644
- const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, { timeout: 60000, env: identityEnv });
669
+ const result = await execGit(['fetch', remote, `+refs/heads/*:refs/remotes/${remote}/*`, '--prune'], cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv });
645
670
  if (result.exitCode !== 0) {
646
671
  throw new Error(`git fetch failed: ${result.stderr}`);
647
672
  }
@@ -656,9 +681,23 @@ export class GitService {
656
681
  * differently-named branch, which is the normal state of a fork PR under
657
682
  * review. A tracked branch pulls from its own upstream.
658
683
  */
659
- async pull(cwd: string, remote = 'origin', branch?: string, rebase = false, identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
684
+ async pull(
685
+ cwd: string,
686
+ remote = 'origin',
687
+ branch?: string,
688
+ mode: GitPullMode = 'default',
689
+ autostash = false,
690
+ identityEnv: GitIdentityEnv = {}
691
+ ): Promise<GitPullResult> {
660
692
  const args = ['pull'];
661
- if (rebase) args.push('--rebase');
693
+ // `default` leaves the strategy to the user's own git config — the panel
694
+ // only names one when the user picked it.
695
+ if (mode === 'merge') args.push('--no-rebase');
696
+ else if (mode === 'rebase') args.push('--rebase');
697
+ else if (mode === 'ff-only') args.push('--ff-only');
698
+ // Rebase refuses a dirty tree outright, so it always carries its own
699
+ // stash, the same as Rebase onto Branch does.
700
+ if (autostash || mode === 'rebase') args.push('--autostash');
662
701
 
663
702
  const target = await this.getPushTarget(cwd, branch);
664
703
  if (!target.hasUpstream) {
@@ -670,15 +709,348 @@ export class GitService {
670
709
  }
671
710
  }
672
711
 
712
+ const before = await this.headHash(cwd);
673
713
  // A pull can create a merge commit, so it needs both halves of the
674
714
  // identity: the credential to fetch, the name to author the merge.
675
- const result = await execGit(args, cwd, { timeout: 60000, env: identityEnv });
715
+ const result = await execGit(args, cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv });
716
+ if (result.exitCode === 0) {
717
+ const after = await this.headHash(cwd);
718
+ const pulledCount =
719
+ before && after && before !== after ? await this.countCommits(cwd, `${before}..${after}`) : 0;
720
+ return { success: true, message: result.stdout || result.stderr, pulledCount };
721
+ }
722
+
723
+ const message = (result.stderr || result.stdout).trim();
724
+ const output = `${result.stderr}\n${result.stdout}`;
725
+ // Decide from the repository, not the wording: a merge or rebase that
726
+ // stopped on conflicts leaves unmerged paths behind.
727
+ if ((await this.getUnmergedPaths(cwd)).length > 0) {
728
+ return { success: false, message, reason: 'conflict' };
729
+ }
730
+ if (/divergent branches|Not possible to fast-forward/i.test(output)) {
731
+ const counts = await this.aheadBehindUpstream(cwd);
732
+ return { success: false, message, reason: 'diverged', ...counts };
733
+ }
734
+ if (/would be overwritten by|commit or stash them|You have unstaged changes|Your index contains uncommitted changes/i.test(output)) {
735
+ return { success: false, message, reason: 'local-changes' };
736
+ }
737
+ return { success: false, message };
738
+ }
739
+
740
+ /** Full hash of HEAD, or null on an unborn branch. */
741
+ private async headHash(cwd: string): Promise<string | null> {
742
+ const result = await execGit(['rev-parse', '--verify', '--quiet', 'HEAD'], cwd, { okExitCodes: [1] });
743
+ return result.exitCode === 0 ? result.stdout.trim() || null : null;
744
+ }
745
+
746
+ private async countCommits(cwd: string, range: string): Promise<number> {
747
+ const result = await execGit(['rev-list', '--count', range], cwd);
748
+ return result.exitCode === 0 ? Number.parseInt(result.stdout.trim(), 10) || 0 : 0;
749
+ }
750
+
751
+ /**
752
+ * Ahead/behind of HEAD against what the last fetch brought in. `@{upstream}`
753
+ * when it resolves; `FETCH_HEAD` covers the URL-tracked branch that has no
754
+ * remote-tracking ref.
755
+ */
756
+ private async aheadBehindUpstream(cwd: string): Promise<{ ahead: number; behind: number }> {
757
+ const other = (await this.hasRef(cwd, '@{upstream}')) ? '@{upstream}' : 'FETCH_HEAD';
758
+ const result = await execGit(['rev-list', '--left-right', '--count', `HEAD...${other}`], cwd);
759
+ return result.exitCode === 0 ? parseAheadBehind(result.stdout) : { ahead: 0, behind: 0 };
760
+ }
761
+
762
+ // ============================================
763
+ // Force pull
764
+ // ============================================
765
+
766
+ /**
767
+ * Where a force pull resets to: the branch's own upstream when it tracks one
768
+ * (a remote name or the URL `gh pr checkout` records), otherwise the
769
+ * same-named branch on `remote`.
770
+ */
771
+ private async resolvePullSource(
772
+ cwd: string,
773
+ remote: string,
774
+ branch?: string
775
+ ): Promise<{ from: string; ref: string; label: string; branch: string }> {
776
+ const current = branch ?? (await execGit(['branch', '--show-current'], cwd)).stdout.trim();
777
+ if (!current) {
778
+ throw new Error('HEAD is detached — check out a branch before force pulling.');
779
+ }
780
+ assertSafeGitRevish(current, 'branch name');
781
+ const tracking = await this.readBranchTracking(cwd, current);
782
+ if (tracking) {
783
+ if (tracking.remote !== '.') {
784
+ if (await this.isConfiguredRemote(cwd, tracking.remote)) assertSafeGitRemoteName(tracking.remote);
785
+ else assertSafeGitRemoteUrl(tracking.remote);
786
+ }
787
+ assertSafeGitRevish(tracking.remoteBranch, 'upstream branch');
788
+ return {
789
+ from: tracking.remote,
790
+ ref: tracking.remoteBranch,
791
+ label: `${tracking.remote}/${tracking.remoteBranch}`,
792
+ branch: current
793
+ };
794
+ }
795
+ assertSafeGitRemoteName(remote);
796
+ return { from: remote, ref: current, label: `${remote}/${current}`, branch: current };
797
+ }
798
+
799
+ /** Fetch the force-pull source and return the exact commit it points at. */
800
+ private async fetchPullSource(
801
+ cwd: string,
802
+ source: { from: string; ref: string; label: string },
803
+ identityEnv: GitIdentityEnv
804
+ ): Promise<string> {
805
+ const result = await execGit(['fetch', source.from, `refs/heads/${source.ref}`], cwd, {
806
+ timeout: NETWORK_TIMEOUT_MS,
807
+ env: identityEnv
808
+ });
809
+ if (result.exitCode !== 0) {
810
+ if (/couldn't find remote ref/i.test(result.stderr)) {
811
+ throw new Error(`${source.label} does not exist on the remote, so there is nothing to pull.`);
812
+ }
813
+ throw new Error(`git fetch failed: ${result.stderr.trim()}`);
814
+ }
815
+ // Pin the commit now: FETCH_HEAD is rewritten by the next fetch anyone runs.
816
+ const hash = await execGit(['rev-parse', '--verify', 'FETCH_HEAD^{commit}'], cwd);
817
+ if (hash.exitCode !== 0) throw new Error('Could not read the fetched commit.');
818
+ return hash.stdout.trim();
819
+ }
820
+
821
+ /** Refuse to force pull mid-operation: resetting under a rebase strands it. */
822
+ private async assertNoOperation(cwd: string, action: string): Promise<void> {
823
+ const operation = await this.detectGitOperation(cwd);
824
+ if (operation) {
825
+ throw new Error(`A ${operation} is in progress — finish or abort it before you ${action}.`);
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Untracked files the target tree contains. `reset --hard` overwrites them
831
+ * without a word, so a force pull stashes them along with tracked changes.
832
+ */
833
+ private async collidingUntracked(cwd: string, target: string): Promise<string[]> {
834
+ const [untracked, tree] = await Promise.all([
835
+ execGit(['ls-files', '--others', '--exclude-standard', '-z'], cwd),
836
+ execGit(['ls-tree', '-r', '--name-only', '-z', target], cwd)
837
+ ]);
838
+ if (untracked.exitCode !== 0 || tree.exitCode !== 0) return [];
839
+ const incoming = new Set(tree.stdout.split('\0').filter(Boolean));
840
+ return untracked.stdout.split('\0').filter(file => file && incoming.has(file));
841
+ }
842
+
843
+ /** Tracked paths that differ from HEAD (staged or not), renames split in two. */
844
+ private async changedTrackedPaths(cwd: string): Promise<string[]> {
845
+ const result = await execGit(['diff', '--name-only', '--no-renames', '-z', 'HEAD'], cwd);
846
+ if (result.exitCode !== 0) return [];
847
+ return result.stdout.split('\0').filter(Boolean);
848
+ }
849
+
850
+ async forcePullPreview(
851
+ cwd: string,
852
+ remote = 'origin',
853
+ branch?: string,
854
+ identityEnv: GitIdentityEnv = {}
855
+ ): Promise<GitForcePullPreview> {
856
+ await this.assertNoOperation(cwd, 'force pull');
857
+ const source = await this.resolvePullSource(cwd, remote, branch);
858
+ const target = await this.fetchPullSource(cwd, source, identityEnv);
859
+ const head = await this.headHash(cwd);
860
+ const [localCommits, incomingCommits, changed, colliding] = await Promise.all([
861
+ head ? this.countCommits(cwd, `${target}..HEAD`) : Promise.resolve(0),
862
+ head ? this.countCommits(cwd, `HEAD..${target}`) : this.countCommits(cwd, target),
863
+ head ? this.changedTrackedPaths(cwd) : Promise.resolve([]),
864
+ this.collidingUntracked(cwd, target)
865
+ ]);
676
866
  return {
677
- success: result.exitCode === 0,
678
- message: result.exitCode === 0 ? result.stdout : result.stderr
867
+ target: source.label,
868
+ localCommits,
869
+ incomingCommits,
870
+ changedFiles: changed.length,
871
+ collidingUntracked: colliding
679
872
  };
680
873
  }
681
874
 
875
+ /**
876
+ * Make the current branch exactly match its remote: fetch, stash what the
877
+ * reset would destroy, `reset --hard`.
878
+ *
879
+ * Local commits are left to the reflog (the result names the old HEAD).
880
+ * Uncommitted work has no reflog, so it goes into a stash first — tracked
881
+ * changes plus only those untracked files the remote tree would overwrite;
882
+ * every other untracked file stays where it is.
883
+ */
884
+ async forcePull(
885
+ cwd: string,
886
+ remote = 'origin',
887
+ branch?: string,
888
+ identityEnv: GitIdentityEnv = {}
889
+ ): Promise<GitForcePullResult> {
890
+ await this.assertNoOperation(cwd, 'force pull');
891
+ const source = await this.resolvePullSource(cwd, remote, branch);
892
+ const target = await this.fetchPullSource(cwd, source, identityEnv);
893
+ const head = await this.headHash(cwd);
894
+
895
+ let stashMessage: string | undefined;
896
+ if (head) {
897
+ const [changed, colliding] = await Promise.all([
898
+ this.changedTrackedPaths(cwd),
899
+ this.collidingUntracked(cwd, target)
900
+ ]);
901
+ if (changed.length > 0 || colliding.length > 0) {
902
+ stashMessage = `clopen: before force pull of ${source.branch} (${new Date().toISOString()})`;
903
+ const args = ['stash', 'push', '-m', stashMessage];
904
+ let stdin: string | undefined;
905
+ if (colliding.length > 0) {
906
+ // A pathspec limits BOTH halves of the stash, so it has to name every
907
+ // tracked change as well, or those would be left to the reset.
908
+ args.push('--include-untracked', '--pathspec-from-file=-', '--pathspec-file-nul');
909
+ stdin = [...changed, ...colliding].join('\0');
910
+ }
911
+ const stash = await execGit(args, cwd, { stdin, env: identityEnv });
912
+ if (stash.exitCode !== 0) {
913
+ throw new Error(`Could not stash local changes, nothing was reset: ${stash.stderr.trim()}`);
914
+ }
915
+ }
916
+ } else {
917
+ const status = await execGit(['status', '--porcelain'], cwd);
918
+ if (status.stdout.trim()) {
919
+ throw new Error('This branch has no commits yet, so local changes cannot be stashed. Commit or remove them first.');
920
+ }
921
+ }
922
+
923
+ const discardedCommits = head ? await this.countCommits(cwd, `${target}..${head}`) : 0;
924
+ const reset = await execGit(['reset', '--hard', target], cwd);
925
+ if (reset.exitCode !== 0) {
926
+ throw new Error(
927
+ `git reset --hard failed: ${reset.stderr.trim()}${stashMessage ? ' — your changes are safe in the stash.' : ''}`
928
+ );
929
+ }
930
+ return {
931
+ previousHead: head ? head.slice(0, 7) : '',
932
+ newHead: target.slice(0, 7),
933
+ discardedCommits,
934
+ ...(stashMessage && { stashMessage })
935
+ };
936
+ }
937
+
938
+ // ============================================
939
+ // Branch pruning
940
+ // ============================================
941
+
942
+ /** The branch a repo integrates into: `<remote>/HEAD`, else main/master. */
943
+ async getDefaultBranch(cwd: string, remote = 'origin'): Promise<string | null> {
944
+ assertSafeGitRemoteName(remote);
945
+ const symbolic = await execGit(['symbolic-ref', '--quiet', '--short', `refs/remotes/${remote}/HEAD`], cwd, {
946
+ okExitCodes: [1, 128]
947
+ });
948
+ if (symbolic.exitCode === 0) {
949
+ const name = symbolic.stdout.trim().replace(new RegExp(`^${remote}/`), '');
950
+ if (name) return name;
951
+ }
952
+ for (const candidate of ['main', 'master', 'trunk', 'develop']) {
953
+ if ((await this.hasRef(cwd, `refs/heads/${candidate}`)) || (await this.hasRef(cwd, `refs/remotes/${remote}/${candidate}`))) {
954
+ return candidate;
955
+ }
956
+ }
957
+ return null;
958
+ }
959
+
960
+ /**
961
+ * Local branches that can go.
962
+ *
963
+ * `merged` — fully merged into the default branch. Squash merges are not
964
+ * detectable this way (the commits differ), which is what `gone` is for.
965
+ * `gone` — the upstream was deleted on the remote, the usual trace of a
966
+ * merged pull request once a fetch has pruned it.
967
+ *
968
+ * Never offers the current branch or the default branch.
969
+ */
970
+ async getPruneCandidates(
971
+ cwd: string,
972
+ mode: 'merged' | 'gone',
973
+ remote = 'origin'
974
+ ): Promise<{ defaultBranch: string | null; candidates: GitPruneCandidate[] }> {
975
+ const defaultBranch = await this.getDefaultBranch(cwd, remote);
976
+ if (mode === 'merged' && !defaultBranch) {
977
+ throw new Error('Could not tell which branch is the default one, so merged branches cannot be determined.');
978
+ }
979
+ // Prefer the remote's copy of the default branch: a stale local `main` would
980
+ // hide branches that were merged on the remote.
981
+ const mergedBase = defaultBranch
982
+ ? (await this.hasRef(cwd, `refs/remotes/${remote}/${defaultBranch}`))
983
+ ? `${remote}/${defaultBranch}`
984
+ : (await this.hasRef(cwd, `refs/heads/${defaultBranch}`))
985
+ ? defaultBranch
986
+ : null
987
+ : null;
988
+
989
+ const [refs, current, merged] = await Promise.all([
990
+ execGit(['for-each-ref', '--format=%(refname:short)%09%(upstream:track)', 'refs/heads/'], cwd),
991
+ execGit(['branch', '--show-current'], cwd),
992
+ mergedBase
993
+ ? execGit(['branch', '--merged', mergedBase, '--format=%(refname:short)'], cwd)
994
+ : Promise.resolve(null)
995
+ ]);
996
+ const currentName = current.stdout.trim();
997
+ const mergedSet = new Set(
998
+ (merged?.exitCode === 0 ? merged.stdout : '').split('\n').map(l => l.trim()).filter(Boolean)
999
+ );
1000
+
1001
+ const candidates: GitPruneCandidate[] = [];
1002
+ for (const line of refs.stdout.split('\n')) {
1003
+ if (!line.trim()) continue;
1004
+ const [name, track = ''] = line.split('\t');
1005
+ if (!name || name === currentName || name === defaultBranch) continue;
1006
+ const isMerged = mergedSet.has(name);
1007
+ if (mode === 'merged' ? isMerged : track.trim() === '[gone]') {
1008
+ candidates.push({ name, merged: isMerged });
1009
+ }
1010
+ }
1011
+ candidates.sort((a, b) => naturalCompare(a.name, b.name));
1012
+ return { defaultBranch, candidates };
1013
+ }
1014
+
1015
+ /** Delete local branches one by one, reporting each outcome. */
1016
+ async deleteBranches(
1017
+ cwd: string,
1018
+ names: string[]
1019
+ ): Promise<{ deleted: string[]; failed: { name: string; message: string }[] }> {
1020
+ const deleted: string[] = [];
1021
+ const failed: { name: string; message: string }[] = [];
1022
+ const current = (await execGit(['branch', '--show-current'], cwd)).stdout.trim();
1023
+ for (const name of names) {
1024
+ try {
1025
+ assertSafeGitRevish(name, 'branch name');
1026
+ if (name === current) throw new Error('This is the checked-out branch.');
1027
+ // `-D`: the list was confirmed with each branch's merge state shown, and
1028
+ // `-d` judges "merged" against HEAD rather than the default branch.
1029
+ const result = await execGit(['branch', '-D', name], cwd);
1030
+ if (result.exitCode !== 0) throw new Error(result.stderr.trim());
1031
+ deleted.push(name);
1032
+ } catch (err) {
1033
+ failed.push({ name, message: err instanceof Error ? err.message : String(err) });
1034
+ }
1035
+ }
1036
+ return { deleted, failed };
1037
+ }
1038
+
1039
+ // ============================================
1040
+ // Submodules
1041
+ // ============================================
1042
+
1043
+ async updateSubmodules(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
1044
+ const result = await execGit(['submodule', 'update', '--init', '--recursive'], cwd, {
1045
+ timeout: NETWORK_TIMEOUT_MS,
1046
+ env: identityEnv
1047
+ });
1048
+ if (result.exitCode !== 0) {
1049
+ throw new Error(`git submodule update failed: ${result.stderr.trim()}`);
1050
+ }
1051
+ return (result.stdout || result.stderr).trim() || 'Submodules are up to date.';
1052
+ }
1053
+
682
1054
  /**
683
1055
  * Shape a `git push` outcome. On an unborn HEAD git only reports
684
1056
  * `src refspec <branch> does not match any`, which reads like a broken remote
@@ -816,7 +1188,7 @@ export class GitService {
816
1188
  if (useUpstream && target.hasUpstream) {
817
1189
  const args = ['push'];
818
1190
  if (force) args.push('--force-with-lease');
819
- return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
1191
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv }));
820
1192
  }
821
1193
 
822
1194
  assertSafeGitRemoteName(remote);
@@ -829,7 +1201,7 @@ export class GitService {
829
1201
  // Only safe here: the branch tracks nothing, so there is no upstream to
830
1202
  // overwrite and recording one is the point of a first push.
831
1203
  args.push('-u');
832
- return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
1204
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv }));
833
1205
  }
834
1206
 
835
1207
  /** Point a branch at a different upstream — the way back from a wrong push. */
@@ -880,7 +1252,7 @@ export class GitService {
880
1252
  assertSafeGitRemoteName(remote);
881
1253
  return this.describePushResult(
882
1254
  cwd,
883
- await execGit(['push', remote, '--tags'], cwd, { timeout: 60000, env: identityEnv })
1255
+ await execGit(['push', remote, '--tags'], cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv })
884
1256
  );
885
1257
  }
886
1258
 
@@ -894,7 +1266,7 @@ export class GitService {
894
1266
  // Same rule as `push`: a tracked branch goes where git says it goes.
895
1267
  const target = await this.getPushTarget(cwd, branch);
896
1268
  if (target.hasUpstream) {
897
- return this.describePushResult(cwd, await execGit(['push', flag], cwd, { timeout: 60000, env: identityEnv }));
1269
+ return this.describePushResult(cwd, await execGit(['push', flag], cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv }));
898
1270
  }
899
1271
 
900
1272
  assertSafeGitRemoteName(remote);
@@ -904,12 +1276,12 @@ export class GitService {
904
1276
  args.push(branch);
905
1277
  }
906
1278
  args.push(flag, '-u');
907
- return this.describePushResult(cwd, await execGit(args, cwd, { timeout: 60000, env: identityEnv }));
1279
+ return this.describePushResult(cwd, await execGit(args, cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv }));
908
1280
  }
909
1281
 
910
1282
  /** Fetch every configured remote and prune deleted remote-tracking refs. */
911
1283
  async fetchAll(cwd: string, identityEnv: GitIdentityEnv = {}): Promise<string> {
912
- const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, { timeout: 60000, env: identityEnv });
1284
+ const result = await execGit(['fetch', '--all', '--prune', '--tags'], cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv });
913
1285
  if (result.exitCode !== 0) {
914
1286
  throw new Error(`git fetch --all failed: ${result.stderr}`);
915
1287
  }
@@ -965,11 +1337,21 @@ export class GitService {
965
1337
  return parseStashList(result.stdout);
966
1338
  }
967
1339
 
968
- async stashSave(cwd: string, message?: string, stagedOnly = false, identityEnv: GitIdentityEnv = {}): Promise<void> {
1340
+ async stashSave(
1341
+ cwd: string,
1342
+ message?: string,
1343
+ stagedOnly = false,
1344
+ identityEnv: GitIdentityEnv = {},
1345
+ includeUntracked = false
1346
+ ): Promise<void> {
1347
+ if (stagedOnly && includeUntracked) {
1348
+ throw new Error('A stash can hold staged changes only, or everything including untracked files — not both.');
1349
+ }
969
1350
  const args = ['stash', 'push'];
970
1351
  // `--staged` stashes exactly the index (works at hunk level, so partially
971
1352
  // staged files are handled precisely). Requires Git >= 2.35.
972
1353
  if (stagedOnly) args.push('--staged');
1354
+ if (includeUntracked) args.push('--include-untracked');
973
1355
  if (message) {
974
1356
  assertSafeGitCommitMessage(message);
975
1357
  args.push('-m', message);
@@ -1118,7 +1500,7 @@ export class GitService {
1118
1500
  async pushTag(cwd: string, name: string, remote = 'origin', identityEnv: GitIdentityEnv = {}): Promise<{ success: boolean; message: string }> {
1119
1501
  assertSafeGitRemoteName(remote);
1120
1502
  assertSafeGitRevish(name, 'tag name');
1121
- const result = await execGit(['push', remote, name], cwd, { timeout: 60000, env: identityEnv });
1503
+ const result = await execGit(['push', remote, name], cwd, { timeout: NETWORK_TIMEOUT_MS, env: identityEnv });
1122
1504
  return {
1123
1505
  success: result.exitCode === 0,
1124
1506
  message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
@@ -1667,6 +2049,13 @@ export class GitService {
1667
2049
  // Unborn HEAD — git only reports `bad revision 'HEAD'`.
1668
2050
  return { success: false, message: 'This repository has no commits yet, so there is nothing to revert.' };
1669
2051
  }
2052
+ if (result.exitCode !== 0 && /is a merge but no -m option/i.test(result.stderr)) {
2053
+ return {
2054
+ success: false,
2055
+ message:
2056
+ 'This commit is a merge. Reverting a merge means choosing which parent to keep, and re-merging that branch later will not bring the changes back — run `git revert -m 1 <commit>` in the terminal if that is what you want, or use Undo instead if it is not pushed yet.'
2057
+ };
2058
+ }
1670
2059
  return {
1671
2060
  success: result.exitCode === 0,
1672
2061
  message: result.exitCode === 0 ? (result.stdout || result.stderr) : result.stderr
@@ -1693,8 +2082,20 @@ export class GitService {
1693
2082
  // ============================================
1694
2083
 
1695
2084
  /** Remove untracked files and directories (`git clean -fd`). */
1696
- async cleanUntracked(cwd: string): Promise<string> {
1697
- const result = await execGit(['clean', '-fd'], cwd);
2085
+ /** What `cleanUntracked` would delete, without deleting it. */
2086
+ async cleanPreview(cwd: string, includeIgnored = false): Promise<string[]> {
2087
+ const result = await execGit(['clean', '-n', '-d', ...(includeIgnored ? ['-x'] : [])], cwd);
2088
+ if (result.exitCode !== 0) {
2089
+ throw new Error(`git clean failed: ${result.stderr}`);
2090
+ }
2091
+ return result.stdout
2092
+ .split('\n')
2093
+ .map(line => line.replace(/^Would remove /, '').trim())
2094
+ .filter(Boolean);
2095
+ }
2096
+
2097
+ async cleanUntracked(cwd: string, includeIgnored = false): Promise<string> {
2098
+ const result = await execGit(['clean', '-fd', ...(includeIgnored ? ['-x'] : [])], cwd);
1698
2099
  if (result.exitCode !== 0) {
1699
2100
  throw new Error(`git clean failed: ${result.stderr}`);
1700
2101
  }
@@ -72,15 +72,10 @@ beforeAll(async () => {
72
72
  // Seed an identity in the isolated data directory, through the real query
73
73
  // layer so the token is sealed exactly as it is in production.
74
74
  const seed = `
75
- import { initializeDatabase, getDatabase } from '$backend/database';
75
+ import { initializeDatabase } from '$backend/database';
76
76
  import { gitIdentityQueries } from '$backend/database/queries';
77
77
  await initializeDatabase();
78
- const now = new Date().toISOString();
79
- getDatabase().prepare(
80
- \`INSERT INTO users (id, name, color, avatar, role, created_at, updated_at)
81
- VALUES ('u-test', 'Ada', '#fff', 'a', 'admin', ?, ?)\`
82
- ).run(now, now);
83
- gitIdentityQueries.create('id-test', 'u-test', {
78
+ gitIdentityQueries.create('id-test', {
84
79
  label: 'Work',
85
80
  name: 'Ada Lovelace',
86
81
  email: 'ada@example.com',
@@ -64,14 +64,9 @@ async function runInSandbox(
64
64
  }
65
65
 
66
66
  const PRELUDE = `
67
- import { initializeDatabase, getDatabase } from '$backend/database';
67
+ import { initializeDatabase } from '$backend/database';
68
68
  import { gitIdentityService } from '$backend/git/identity';
69
69
  await initializeDatabase();
70
- const now = new Date().toISOString();
71
- getDatabase().prepare(
72
- \`INSERT INTO users (id, name, color, avatar, role, created_at, updated_at)
73
- VALUES ('u1', 'User', '#fff', 'a', 'admin', ?, ?)\`
74
- ).run(now, now);
75
70
  `;
76
71
 
77
72
  describe('mirroring the machine git identity', () => {
@@ -85,7 +80,7 @@ describe('mirroring the machine git identity', () => {
85
80
 
86
81
  const result = await runInSandbox(
87
82
  `${PRELUDE}
88
- const list = await gitIdentityService.list('u1');
83
+ const list = await gitIdentityService.list();
89
84
  console.log(JSON.stringify(list.map((i) => ({
90
85
  label: i.label, name: i.name, email: i.email,
91
86
  isDefault: i.isDefault, source: i.source, canDelete: i.canDelete
@@ -117,9 +112,9 @@ describe('mirroring the machine git identity', () => {
117
112
 
118
113
  const result = await runInSandbox(
119
114
  `${PRELUDE}
120
- await gitIdentityService.list('u1');
121
- await gitIdentityService.list('u1');
122
- const list = await gitIdentityService.list('u1');
115
+ await gitIdentityService.list();
116
+ await gitIdentityService.list();
117
+ const list = await gitIdentityService.list();
123
118
  console.log(JSON.stringify({ count: list.length }));`,
124
119
  { home, dataDir }
125
120
  );
@@ -137,11 +132,11 @@ describe('mirroring the machine git identity', () => {
137
132
 
138
133
  const result = await runInSandbox(
139
134
  `${PRELUDE}
140
- const [mirrored] = await gitIdentityService.list('u1');
135
+ const [mirrored] = await gitIdentityService.list();
141
136
  let error = null;
142
- try { await gitIdentityService.remove('u1', mirrored.id); }
137
+ try { await gitIdentityService.remove(mirrored.id); }
143
138
  catch (e) { error = e instanceof Error ? e.message : String(e); }
144
- const after = await gitIdentityService.list('u1');
139
+ const after = await gitIdentityService.list();
145
140
  console.log(JSON.stringify({ error, stillThere: after.length }));`,
146
141
  { home, dataDir }
147
142
  );
@@ -162,8 +157,8 @@ describe('mirroring the machine git identity', () => {
162
157
 
163
158
  const result = await runInSandbox(
164
159
  `${PRELUDE}
165
- const [mirrored] = await gitIdentityService.list('u1');
166
- const updated = await gitIdentityService.update('u1', mirrored.id, {
160
+ const [mirrored] = await gitIdentityService.list();
161
+ const updated = await gitIdentityService.update(mirrored.id, {
167
162
  label: 'Renamed', name: 'Edited Name', email: 'edited@example.com',
168
163
  authMethod: 'none', hosts: []
169
164
  });
@@ -189,7 +184,7 @@ describe('mirroring the machine git identity', () => {
189
184
 
190
185
  const result = await runInSandbox(
191
186
  `${PRELUDE}
192
- const list = await gitIdentityService.list('u1');
187
+ const list = await gitIdentityService.list();
193
188
  console.log(JSON.stringify({ count: list.length }));`,
194
189
  { home, dataDir }
195
190
  );