@openchamber/web 1.22.1 → 1.23.0

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 (205) hide show
  1. package/bin/cli.js +11 -1
  2. package/bin/cli.test.js +92 -0
  3. package/bin/lib/cli-startup.js +49 -0
  4. package/bin/lib/commands-startup.js +41 -6
  5. package/dist/assets/{CodeMirrorCommentWidgets-BO_2OW4E.js → CodeMirrorCommentWidgets-DbcnxAfY.js} +1 -1
  6. package/dist/assets/DiffView-Dp1tomqK.js +4 -0
  7. package/dist/assets/{DirtyBranchSwitchDialog-jADfXQnR.js → DirtyBranchSwitchDialog-DE2sKIYv.js} +1 -1
  8. package/dist/assets/FilesView-C_of2nIT.js +17 -0
  9. package/dist/assets/{GitView-Cv2xH-S6.js → GitView-CKgUkb5Z.js} +4 -4
  10. package/dist/assets/{JsonTreeView-DUiIpERC.js → JsonTreeView-Bce2ettZ.js} +1 -1
  11. package/dist/assets/{LinearIssuesView-CoZ7pQN5.js → LinearIssuesView-BZVWM2zw.js} +1 -1
  12. package/dist/assets/MarkdownImageGallery-DdROVz29.js +1 -0
  13. package/dist/assets/MarkdownRendererImpl-CenrzmMN.js +12 -0
  14. package/dist/assets/OnboardingScreen-DyqYG_NP.js +1 -0
  15. package/dist/assets/{PatchDiff-BymkP9JA.js → PatchDiff-CR3RVO5I.js} +1 -1
  16. package/dist/assets/PierreDiffViewer-KihzO94X.js +161 -0
  17. package/dist/assets/PlanView-jcQAfr2A.js +5 -0
  18. package/dist/assets/SettingsView-Buvom5A2.js +28 -0
  19. package/dist/assets/{SettingsWindow-COzgfFxM.js → SettingsWindow-CV_hzB5v.js} +1 -1
  20. package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
  21. package/dist/assets/{ToolOutputDialog-Dlhh_-oe.js → ToolOutputDialog-llKecK_Z.js} +6 -6
  22. package/dist/assets/{ToolPartDiffPreview-b9joNtXH.js → ToolPartDiffPreview-ZDMTdCGn.js} +2 -2
  23. package/dist/assets/{VirtualizedFileDiff-vqW3KKo5.js → VirtualizedFileDiff-ClvqQ4j0.js} +1 -1
  24. package/dist/assets/WalkthroughView-BgpSnSlU.js +4 -0
  25. package/dist/assets/{computeVirtualFileMetrics-DUnyszhW.js → computeVirtualFileMetrics-Nm5_wabb.js} +2 -2
  26. package/dist/assets/contextPanelEmbeddedChat-CirXEPJq.js +1 -0
  27. package/dist/assets/de-DTQDjaiv.js +10 -0
  28. package/dist/assets/es-SOCFd_r-.js +16 -0
  29. package/dist/assets/fr-CP6jqIzw.js +14 -0
  30. package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
  31. package/dist/assets/index-B68h5S5B.css +1 -0
  32. package/dist/assets/index-CRf2xk51.js +39 -0
  33. package/dist/assets/{index-DLiD86ge.js → index-Du9sZhDb.js} +1 -1
  34. package/dist/assets/{isDiffPlainText-TNageFjy.js → isDiffPlainText-EQERIius.js} +1 -1
  35. package/dist/assets/{isFilePlainText-JPmZOYSp.js → isFilePlainText-BCoVpkQy.js} +1 -1
  36. package/dist/assets/ja-BKfafwsD.js +16 -0
  37. package/dist/assets/ko-BA5xgCYp.js +16 -0
  38. package/dist/assets/main-BNiPEont.js +930 -0
  39. package/dist/assets/{main-DCB4JgVe.js → main-DPf32fO6.js} +2 -2
  40. package/dist/assets/markdownCore-CQ7CAuuV.js +5 -0
  41. package/dist/assets/{miniChat-BtV7N5OF.js → miniChat-CHqVTsgj.js} +2 -2
  42. package/dist/assets/{mobile-DZV_sfX7.js → mobile-BQmgHA57.js} +2 -2
  43. package/dist/assets/patchFileDiff-C4X_trug.js +13 -0
  44. package/dist/assets/pl-B215pG1Y.js +16 -0
  45. package/dist/assets/pt-BR-Bo2pnlEa.js +16 -0
  46. package/dist/assets/renderElectronMiniChatApp-BUcHPOXW.js +2 -0
  47. package/dist/assets/renderMobileApp-BvTmuRE-.js +25 -0
  48. package/dist/assets/runtimeEndpointReset-C8GAA2kS.js +17 -0
  49. package/dist/assets/scheduledTasksApi-BAScWwt3.js +1 -0
  50. package/dist/assets/{shikiHighlight-CRpCl7UT.js → shikiHighlight-BTObuQCR.js} +1 -1
  51. package/dist/assets/surface-BvRzS58U.js +1 -0
  52. package/dist/assets/tr-CUaxHc8X.js +7 -0
  53. package/dist/assets/uk-YTJgyqAZ.js +16 -0
  54. package/dist/assets/{useAppFontEffects-CCgvcQ6u.js → useAppFontEffects-theH_IJL.js} +143 -137
  55. package/dist/assets/useGitComparison-B94I6kOI.js +1 -0
  56. package/dist/assets/useInlineCommentController-Bs3PgeA8.js +2 -0
  57. package/dist/assets/useRootScrollLock-hSYwnxZs.js +1 -0
  58. package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-DdV8vhHn.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-language-data-BxpoC5Fp.js → vendor-codemirror-language-data-Cxgr01md.js} +2 -2
  60. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  61. package/dist/assets/vendor-zod-BPAANqvH.js +39 -0
  62. package/dist/assets/{web-components-B6QgbmTo.js → web-components-CaS0ksnZ.js} +1 -1
  63. package/dist/assets/zh-CN-CZ2BxZS6.js +16 -0
  64. package/dist/assets/zh-TW-BsUrPdXz.js +16 -0
  65. package/dist/index.html +5 -43
  66. package/dist/mini-chat.html +4 -4
  67. package/dist/mobile.html +4 -4
  68. package/package.json +3 -4
  69. package/server/index.d.ts +15 -0
  70. package/server/index.js +52 -10
  71. package/server/lib/changelog/update-notes.js +82 -0
  72. package/server/lib/changelog/update-notes.test.js +59 -0
  73. package/server/lib/data-dir-migration.js +40 -0
  74. package/server/lib/data-dir-migration.test.js +59 -0
  75. package/server/lib/event-stream/runtime.test.js +12 -12
  76. package/server/lib/fs/DOCUMENTATION.md +5 -0
  77. package/server/lib/fs/routes.js +63 -21
  78. package/server/lib/fs/routes.test.js +187 -1
  79. package/server/lib/git/DOCUMENTATION.md +29 -5
  80. package/server/lib/git/routes.js +24 -4
  81. package/server/lib/git/service.js +194 -198
  82. package/server/lib/git/service.test.js +440 -25
  83. package/server/lib/inherited-env.js +16 -9
  84. package/server/lib/inherited-env.test.js +8 -9
  85. package/server/lib/message-queue/DOCUMENTATION.md +20 -7
  86. package/server/lib/message-queue/runtime.js +59 -7
  87. package/server/lib/message-queue/runtime.test.js +59 -3
  88. package/server/lib/network-defaults.js +23 -0
  89. package/server/lib/network-defaults.test.js +52 -0
  90. package/server/lib/opencode/DOCUMENTATION.md +25 -5
  91. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  92. package/server/lib/opencode/config-paths.test.js +116 -0
  93. package/server/lib/opencode/feature-routes-runtime.js +4 -0
  94. package/server/lib/opencode/input-history-scope.js +14 -0
  95. package/server/lib/opencode/openchamber-routes.js +64 -4
  96. package/server/lib/opencode/openchamber-routes.test.js +128 -1
  97. package/server/lib/opencode/plugins.js +2 -2
  98. package/server/lib/opencode/providers.js +44 -2
  99. package/server/lib/opencode/providers.test.js +131 -4
  100. package/server/lib/opencode/routes.js +9 -7
  101. package/server/lib/opencode/server-startup-runtime.js +1 -1
  102. package/server/lib/opencode/settings-files.js +214 -0
  103. package/server/lib/opencode/settings-helpers.js +113 -41
  104. package/server/lib/opencode/settings-helpers.test.js +342 -0
  105. package/server/lib/opencode/settings-registry.json +747 -0
  106. package/server/lib/opencode/settings-runtime.js +139 -18
  107. package/server/lib/opencode/settings-runtime.test.js +163 -5
  108. package/server/lib/opencode/shared.js +4 -1
  109. package/server/lib/opencode/skill-routes.js +2 -1
  110. package/server/lib/opencode/snippets.js +1 -2
  111. package/server/lib/package-manager.js +3 -28
  112. package/server/lib/project-context/DOCUMENTATION.md +25 -1
  113. package/server/lib/project-context/routes.http.test.js +18 -0
  114. package/server/lib/project-context/routes.js +15 -0
  115. package/server/lib/project-context/runtime.js +248 -23
  116. package/server/lib/project-context/runtime.test.js +106 -3
  117. package/server/lib/projects/DOCUMENTATION.md +76 -0
  118. package/server/lib/projects/project-config.js +142 -9
  119. package/server/lib/projects/project-id.js +17 -0
  120. package/server/lib/projects/project-setup.js +409 -0
  121. package/server/lib/projects/project-setup.test.js +557 -0
  122. package/server/lib/projects/routes.js +59 -0
  123. package/server/lib/quota/DOCUMENTATION.md +38 -1
  124. package/server/lib/quota/index.js +1 -0
  125. package/server/lib/quota/providers/cline-pass.js +125 -0
  126. package/server/lib/quota/providers/cline-pass.test.js +103 -0
  127. package/server/lib/quota/providers/hyper.js +118 -0
  128. package/server/lib/quota/providers/hyper.test.js +126 -0
  129. package/server/lib/quota/providers/index.js +15 -0
  130. package/server/lib/quota/providers/neuralwatt.js +3 -6
  131. package/server/lib/quota/providers/neuralwatt.test.js +7 -7
  132. package/server/lib/quota/providers/ollama-cloud.js +31 -0
  133. package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
  134. package/server/lib/quota/providers/opencode-go.js +1 -1
  135. package/server/lib/quota/providers/opencode-go.test.js +26 -1
  136. package/server/lib/quota/providers/openrouter.js +119 -24
  137. package/server/lib/quota/providers/openrouter.test.js +330 -0
  138. package/server/lib/quota/utils/auth.js +1 -1
  139. package/server/lib/relay/DOCUMENTATION.md +55 -0
  140. package/server/lib/relay/cross-compat.test.js +26 -0
  141. package/server/lib/relay/downstream-scheduler.js +154 -0
  142. package/server/lib/relay/downstream-scheduler.test.js +162 -0
  143. package/server/lib/relay/e2ee.js +10 -8
  144. package/server/lib/relay/flow-control.test.js +177 -0
  145. package/server/lib/relay/host-client.js +37 -8
  146. package/server/lib/relay/host-client.test.js +9 -1
  147. package/server/lib/relay/tunnel-codec.js +9 -0
  148. package/server/lib/relay/tunnel-host.js +66 -17
  149. package/server/lib/session-assist/runtime.js +6 -10
  150. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  151. package/server/lib/session-goal/runtime.js +80 -20
  152. package/server/lib/session-goal/runtime.test.js +426 -0
  153. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  154. package/server/lib/skills-catalog/install.js +3 -2
  155. package/server/lib/small-model/DOCUMENTATION.md +3 -2
  156. package/server/lib/small-model/call.js +9 -4
  157. package/server/lib/small-model/call.test.js +29 -0
  158. package/server/lib/small-model/index.js +5 -10
  159. package/server/lib/small-model/runtime-providers.js +15 -7
  160. package/server/lib/small-model/runtime-providers.test.js +7 -1
  161. package/server/lib/terminal/DOCUMENTATION.md +14 -10
  162. package/server/lib/terminal/runtime.js +160 -24
  163. package/server/lib/terminal/runtime.test.js +571 -37
  164. package/server/lib/terminal/shells.js +17 -0
  165. package/server/lib/terminal/shells.test.js +32 -1
  166. package/server/lib/walkthrough/DOCUMENTATION.md +33 -14
  167. package/server/lib/walkthrough/model-settings.js +8 -12
  168. package/server/lib/walkthrough/prompt.js +3 -1
  169. package/server/lib/walkthrough/routes.test.js +26 -5
  170. package/server/lib/walkthrough/sources.js +23 -2
  171. package/dist/assets/DiffView-CNnDxRmO.js +0 -4
  172. package/dist/assets/FilesView-8wdiG2mj.js +0 -17
  173. package/dist/assets/MarkdownImageGallery-DffjmciG.js +0 -1
  174. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +0 -12
  175. package/dist/assets/OnboardingScreen-CTZe6HZn.js +0 -1
  176. package/dist/assets/PierreDiffViewer-BvwtCxW4.js +0 -157
  177. package/dist/assets/PlanView-C1qvAm7m.js +0 -5
  178. package/dist/assets/SettingsView-xGONHFGS.js +0 -28
  179. package/dist/assets/WalkthroughView-D-HFgdmM.js +0 -4
  180. package/dist/assets/contextPanelEmbeddedChat-CV-DwAiX.js +0 -1
  181. package/dist/assets/de-Cv_4FoXm.js +0 -10
  182. package/dist/assets/es-BIWNEbnS.js +0 -16
  183. package/dist/assets/fr-SD3OfMHJ.js +0 -14
  184. package/dist/assets/index-CHUT_bDS.css +0 -1
  185. package/dist/assets/index-DDInLQDd.js +0 -40
  186. package/dist/assets/ja-D7I9HofF.js +0 -16
  187. package/dist/assets/ko-BsVJM_PQ.js +0 -16
  188. package/dist/assets/main-De8Z5w49.js +0 -928
  189. package/dist/assets/markdownCore-BoQVG5-a.js +0 -3
  190. package/dist/assets/patchFileDiff-Chmiz6hq.js +0 -10
  191. package/dist/assets/pl-XR9Bs8Be.js +0 -16
  192. package/dist/assets/pt-BR-Due4be8g.js +0 -16
  193. package/dist/assets/renderElectronMiniChatApp-8tXADjfl.js +0 -2
  194. package/dist/assets/renderMobileApp-Cji7Hma5.js +0 -25
  195. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +0 -16
  196. package/dist/assets/scheduledTasksApi-9e-UX6im.js +0 -1
  197. package/dist/assets/tr-DBJcAv4y.js +0 -7
  198. package/dist/assets/uk-COYh2BaN.js +0 -16
  199. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +0 -2
  200. package/dist/assets/useRootScrollLock-KzOUytpn.js +0 -1
  201. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
  202. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  203. package/dist/assets/vendor-zod-DVWEh-IS.js +0 -39
  204. package/dist/assets/zh-CN-Cjk6lzhc.js +0 -16
  205. package/dist/assets/zh-TW-Dk0dOg03.js +0 -16
@@ -352,16 +352,17 @@ const buildGitEnv = async () => {
352
352
  return env;
353
353
  };
354
354
 
355
- const createGit = async (directory, { allowUnsafeSshCommand = false } = {}) => {
355
+ const createGit = async (directory, { allowUnsafeSshCommand = false, allowUnsafeCredentialHelper = false } = {}) => {
356
356
  const env = await buildGitEnv();
357
357
  const spawnOptions = { windowsHide: true };
358
358
  const binary = getGitBinary();
359
359
  const hasCustomBinary = typeof binary === 'string' && binary.trim() && binary !== 'git' && binary !== 'git.exe';
360
- const unsafe = hasCustomBinary || allowUnsafeSshCommand
360
+ const unsafe = hasCustomBinary || allowUnsafeSshCommand || allowUnsafeCredentialHelper
361
361
  ? {
362
- ...(hasCustomBinary && { allowUnsafeCustomBinary: true }),
363
- ...(allowUnsafeSshCommand && { allowUnsafeSshCommand: true }),
364
- }
362
+ ...(hasCustomBinary && { allowUnsafeCustomBinary: true }),
363
+ ...(allowUnsafeSshCommand && { allowUnsafeSshCommand: true }),
364
+ ...(allowUnsafeCredentialHelper && { allowUnsafeCredentialHelper: true }),
365
+ }
365
366
  : undefined;
366
367
  // Always pin simple-git to an explicit working directory. Omitting baseDir
367
368
  // makes simple-git use process.cwd(), which breaks when the OpenChamber
@@ -684,6 +685,15 @@ const parseWorktreePorcelain = (raw) => {
684
685
  const branchRef = line.substring('branch '.length).trim();
685
686
  current.branchRef = branchRef;
686
687
  current.branch = cleanBranchName(branchRef);
688
+ continue;
689
+ }
690
+
691
+ // git marks a worktree whose directory is gone (deleted outside git) as
692
+ // prunable; it stays registered until `git worktree prune`. The sidebar
693
+ // needs that distinction: the directory is missing, but the sessions that
694
+ // lived there are not.
695
+ if (line === 'prunable' || line.startsWith('prunable ')) {
696
+ current.prunable = true;
687
697
  }
688
698
  }
689
699
 
@@ -932,7 +942,7 @@ const runGitCommand = async (cwd, args) => {
932
942
  } catch (error) {
933
943
  return {
934
944
  success: false,
935
- exitCode: typeof error?.code === 'number' ? error.code : 1,
945
+ exitCode: Number.isInteger(error?.code) ? error.code : null,
936
946
  stdout: String(error?.stdout || ''),
937
947
  stderr: String(error?.stderr || ''),
938
948
  message: parseGitErrorText(error),
@@ -2137,7 +2147,7 @@ export async function hasLocalIdentity(directory) {
2137
2147
  }
2138
2148
 
2139
2149
  export async function setLocalIdentity(directory, profile) {
2140
- const git = await createGit(directory, { allowUnsafeSshCommand: true });
2150
+ const git = await createGit(directory, { allowUnsafeSshCommand: true, allowUnsafeCredentialHelper: true });
2141
2151
 
2142
2152
  try {
2143
2153
 
@@ -2455,11 +2465,26 @@ export async function getStatus(directory, options = {}) {
2455
2465
  }
2456
2466
  }
2457
2467
 
2468
+ const getNoIndexDiff = async (repoRoot, repoPath, contextLines) => {
2469
+ const args = ['diff', '--no-color', '--full-index'];
2470
+ if (Number.isFinite(contextLines)) {
2471
+ args.push(`-U${Math.max(0, contextLines)}`);
2472
+ }
2473
+ args.push('--no-index', '--', '/dev/null', repoPath);
2474
+ const result = await runGitCommand(repoRoot, args);
2475
+ // Exit 1 means differences, even when Git also writes warnings to stderr.
2476
+ // Spawn and buffer errors have no numeric exit code and must still fail.
2477
+ if (result.exitCode === 0 || result.exitCode === 1) {
2478
+ return result.stdout;
2479
+ }
2480
+ throw new Error(result.stderr || result.message || 'Failed to get untracked Git diff');
2481
+ };
2482
+
2458
2483
  export async function getDiff(directory, { path: filePath, staged = false, contextLines = 3 } = {}) {
2459
2484
  const { directoryPath, directoryGit, repoRoot, git } = await createRepositoryGitContext(directory);
2460
2485
 
2461
2486
  try {
2462
- const args = ['diff', '--no-color'];
2487
+ const args = ['diff', '--no-color', '--full-index'];
2463
2488
  const fileContext = filePath ? await resolveGitFileContext(directoryPath, directoryGit, filePath, repoRoot) : null;
2464
2489
 
2465
2490
  if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
@@ -2505,21 +2530,7 @@ export async function getDiff(directory, { path: filePath, staged = false, conte
2505
2530
  ].join('\n');
2506
2531
  }
2507
2532
 
2508
- const noIndexArgs = ['diff', '--no-color'];
2509
- if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
2510
- noIndexArgs.push(`-U${Math.max(0, contextLines)}`);
2511
- }
2512
- noIndexArgs.push('--no-index', '--', '/dev/null', fileContext.repoPath);
2513
- try {
2514
- const noIndexDiff = await git.raw(noIndexArgs);
2515
- return noIndexDiff;
2516
- } catch (noIndexError) {
2517
- // git diff --no-index returns exit code 1 when differences exist (not a real error)
2518
- if (noIndexError.exitCode === 1 && noIndexError.message) {
2519
- return noIndexError.message;
2520
- }
2521
- throw noIndexError;
2522
- }
2533
+ return await getNoIndexDiff(repoRoot, fileContext.repoPath, contextLines);
2523
2534
  }
2524
2535
  } catch (error) {
2525
2536
  console.error('Failed to get Git diff:', error);
@@ -2568,7 +2579,7 @@ export async function getUntrackedDiffs(directory, filePaths = [], { concurrency
2568
2579
  const paths = (Array.isArray(filePaths) ? filePaths : []).filter((value) => typeof value === 'string' && value);
2569
2580
  if (paths.length === 0) return [];
2570
2581
 
2571
- const { directoryPath, directoryGit, repoRoot, git } = await createRepositoryGitContext(directory);
2582
+ const { directoryPath, directoryGit, repoRoot } = await createRepositoryGitContext(directory);
2572
2583
  const results = new Array(paths.length).fill('');
2573
2584
  let cursor = 0;
2574
2585
 
@@ -2577,18 +2588,7 @@ export async function getUntrackedDiffs(directory, filePaths = [], { concurrency
2577
2588
  const index = cursor++;
2578
2589
  try {
2579
2590
  const fileContext = await resolveGitFileContext(directoryPath, directoryGit, paths[index], repoRoot);
2580
- const args = ['diff', '--no-color'];
2581
- if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
2582
- args.push(`-U${Math.max(0, contextLines)}`);
2583
- }
2584
- args.push('--no-index', '--', '/dev/null', fileContext.repoPath);
2585
- try {
2586
- results[index] = await git.raw(args);
2587
- } catch (error) {
2588
- // `git diff --no-index` exits 1 whenever there are differences, which
2589
- // for a new file is always.
2590
- results[index] = error?.exitCode === 1 && error?.message ? error.message : '';
2591
- }
2591
+ results[index] = await getNoIndexDiff(repoRoot, fileContext.repoPath, contextLines);
2592
2592
  } catch {
2593
2593
  results[index] = '';
2594
2594
  }
@@ -2618,7 +2618,51 @@ async function assertRangeRefsResolve(git, refs) {
2618
2618
  }
2619
2619
  }
2620
2620
 
2621
- export async function getRangeDiff(directory, { base, head, path: filePath, contextLines = 3 } = {}) {
2621
+ // A private index lets git include untracked paths in the same tree comparison
2622
+ // as tracked files, including a staged deletion recreated at the same path.
2623
+ // Intent-to-add records only their existence; diff reads current file contents.
2624
+ async function runWorkingTreeRangeDiff(context, baseRef, headRef, args, paths = []) {
2625
+ const { git, repoRoot } = context;
2626
+ const readHead = async () => {
2627
+ const commit = (await git.raw(['rev-parse', '--verify', 'HEAD'])).trim();
2628
+ const ref = (await git.raw(['symbolic-ref', '--quiet', 'HEAD'])).trim();
2629
+ return `${commit}\n${ref}`;
2630
+ };
2631
+ const startingHead = await readHead();
2632
+ const [headCommit, currentRef] = startingHead.split('\n');
2633
+ const requestedRef = (await git.raw(['rev-parse', '--verify', '--symbolic-full-name', '--end-of-options', headRef])).trim();
2634
+ if (requestedRef !== currentRef) {
2635
+ throw new Error('Working-tree comparisons require the checked-out branch. Refresh and try again.');
2636
+ }
2637
+ const mergeBase = (await git.raw(['merge-base', baseRef, headCommit])).trim();
2638
+ const readDiff = async (comparisonGit) => {
2639
+ const diff = await comparisonGit.raw([...args, mergeBase, '--', ...paths]);
2640
+ if (await readHead() !== startingHead) {
2641
+ throw new Error('The checked-out branch changed during comparison. Refresh and try again.');
2642
+ }
2643
+ return diff;
2644
+ };
2645
+ const untracked = await git.raw(['ls-files', '--others', '--exclude-standard', '-z', '--', ...paths]);
2646
+ if (!untracked) return readDiff(git);
2647
+
2648
+ const temporaryDirectory = await fsp.mkdtemp(path.join(os.tmpdir(), 'openchamber-branch-diff-'));
2649
+ try {
2650
+ const indexPath = (await git.raw(['rev-parse', '--git-path', 'index'])).trim();
2651
+ const temporaryIndex = path.join(temporaryDirectory, 'index');
2652
+ await fsp.copyFile(path.resolve(repoRoot, indexPath), temporaryIndex);
2653
+ const pathspecFile = path.join(temporaryDirectory, 'paths');
2654
+ await fsp.writeFile(pathspecFile, untracked);
2655
+ const comparisonGit = await createGit(repoRoot);
2656
+ comparisonGit.env('GIT_INDEX_FILE', temporaryIndex);
2657
+ comparisonGit.env('GIT_LITERAL_PATHSPECS', '1');
2658
+ await comparisonGit.raw(['add', '--intent-to-add', '--pathspec-from-file=' + pathspecFile, '--pathspec-file-nul']);
2659
+ return await readDiff(comparisonGit);
2660
+ } finally {
2661
+ await fsp.rm(temporaryDirectory, { recursive: true, force: true });
2662
+ }
2663
+ }
2664
+
2665
+ export async function getRangeDiff(directory, { base, head, path: filePath, contextLines = 3, includeWorkingTree = false } = {}) {
2622
2666
  const { directoryPath, directoryGit, repoRoot, git } = await createRepositoryGitContext(directory);
2623
2667
  const baseRef = typeof base === 'string' ? base.trim() : '';
2624
2668
  const headRef = typeof head === 'string' ? head.trim() : '';
@@ -2626,51 +2670,39 @@ export async function getRangeDiff(directory, { base, head, path: filePath, cont
2626
2670
  throw new Error('base and head are required');
2627
2671
  }
2628
2672
 
2629
- // Prefer remote-tracking base ref so merged commits don't reappear
2630
- // when local base branch is stale (common when user stays on feature branch).
2631
- let resolvedBase = baseRef;
2632
- const originCandidate = `refs/remotes/origin/${baseRef}`;
2633
- try {
2634
- const verified = await git.raw(['rev-parse', '--verify', originCandidate]);
2635
- if (verified && verified.trim()) {
2636
- resolvedBase = `origin/${baseRef}`;
2637
- }
2638
- } catch {
2639
- // ignore
2640
- }
2641
-
2642
- // Not every repository has an `origin`. When the base names a branch that
2643
- // exists only on another remote, a bare name does not resolve — git looks in
2644
- // refs/heads, not across remotes — and the diff fails with "ambiguous
2645
- // argument". Fall back to whichever remote actually carries it.
2646
- if (resolvedBase === baseRef && !/[*?[\]^~:\\]/.test(baseRef)) {
2647
- const resolvesLocally = await git
2648
- .raw(['rev-parse', '--verify', `refs/heads/${baseRef}`])
2649
- .then((value) => Boolean(String(value || '').trim()))
2650
- .catch(() => false);
2651
-
2652
- if (!resolvesLocally) {
2653
- const remoteMatch = await git
2654
- .raw(['for-each-ref', '--count=1', '--format=%(refname:short)', `refs/remotes/*/${baseRef}`])
2655
- .then((value) => String(value || '').trim())
2656
- .catch(() => '');
2657
- if (remoteMatch) {
2658
- resolvedBase = remoteMatch;
2659
- }
2660
- }
2661
- }
2662
-
2663
- await assertRangeRefsResolve(git, [resolvedBase, headRef]);
2673
+ await assertRangeRefsResolve(git, [baseRef, headRef]);
2664
2674
 
2665
2675
  const args = ['diff', '--no-color'];
2666
2676
  if (typeof contextLines === 'number' && !Number.isNaN(contextLines)) {
2667
2677
  args.push(`-U${Math.max(0, contextLines)}`);
2668
2678
  }
2669
- args.push(`${resolvedBase}...${headRef}`);
2679
+ const paths = [];
2670
2680
  if (filePath) {
2671
- const fileContext = await resolveGitFileContext(directoryPath, directoryGit, filePath, repoRoot);
2672
- args.push('--', fileContext.repoPath);
2681
+ try {
2682
+ const fileContext = await resolveGitFileContext(directoryPath, directoryGit, filePath, repoRoot);
2683
+ paths.push(fileContext.repoPath);
2684
+ } catch (error) {
2685
+ if (error.message !== 'Invalid file path') throw error;
2686
+ // A committed deletion is absent from HEAD, the index, and the working
2687
+ // tree. It is still a valid range path when it exists at the merge base.
2688
+ const mergeBase = (await git.raw(['merge-base', baseRef, headRef])).trim();
2689
+ for (const root of new Set([repoRoot, directoryPath])) {
2690
+ const target = path.resolve(root, filePath);
2691
+ if (!isInsideOrSameDirectory(repoRoot, target)) continue;
2692
+ const repoPath = toGitPath(path.relative(repoRoot, target));
2693
+ const exists = await git.raw(['cat-file', '-e', `${mergeBase}:${repoPath}`]).then(() => true).catch(() => false);
2694
+ if (exists) {
2695
+ paths.push(repoPath);
2696
+ break;
2697
+ }
2698
+ }
2699
+ if (paths.length === 0) throw error;
2700
+ }
2701
+ }
2702
+ if (includeWorkingTree) {
2703
+ return runWorkingTreeRangeDiff({ git, repoRoot }, baseRef, headRef, args, paths);
2673
2704
  }
2705
+ args.push(`${baseRef}...${headRef}`, '--', ...paths);
2674
2706
  const diff = await git.raw(args);
2675
2707
  return diff;
2676
2708
  }
@@ -2692,6 +2724,9 @@ export function parseBranchCreationSource(reflogText) {
2692
2724
  .split('\n')
2693
2725
  .map((line) => line.trim())
2694
2726
  .filter(Boolean);
2727
+ // Rebase records its destination as a commit, not a parent branch. The
2728
+ // creation ref is no longer evidence of the current base after restacking.
2729
+ if (lines.some((line) => /^rebase(?:\s|\()/.test(line))) return null;
2695
2730
  // Reflog lists newest entries first; the creation entry is the oldest one.
2696
2731
  for (let index = lines.length - 1; index >= 0; index -= 1) {
2697
2732
  const match = lines[index].match(BRANCH_CREATION_SOURCE_RE);
@@ -2743,31 +2778,23 @@ export async function getBranchBase(directory, branch) {
2743
2778
  return { base: source };
2744
2779
  }
2745
2780
 
2746
- export async function getRangeFiles(directory, { base, head } = {}) {
2747
- const { git } = await createRepositoryGitContext(directory);
2781
+ export async function getRangeFiles(directory, { base, head, includeWorkingTree = false } = {}) {
2782
+ const { git, repoRoot } = await createRepositoryGitContext(directory);
2748
2783
  const baseRef = typeof base === 'string' ? base.trim() : '';
2749
2784
  const headRef = typeof head === 'string' ? head.trim() : '';
2750
2785
  if (!baseRef || !headRef) {
2751
2786
  throw new Error('base and head are required');
2752
2787
  }
2753
2788
 
2754
- let resolvedBase = baseRef;
2755
- const originCandidate = `refs/remotes/origin/${baseRef}`;
2756
- try {
2757
- const verified = await git.raw(['rev-parse', '--verify', originCandidate]);
2758
- if (verified && verified.trim()) {
2759
- resolvedBase = `origin/${baseRef}`;
2760
- }
2761
- } catch {
2762
- // ignore
2763
- }
2764
-
2765
- await assertRangeRefsResolve(git, [resolvedBase, headRef]);
2789
+ await assertRangeRefsResolve(git, [baseRef, headRef]);
2766
2790
 
2767
2791
  // `-C` (copy detection among changed files only, so cheap) makes copies
2768
2792
  // surface as C entries instead of plain additions; rename detection is on
2769
2793
  // by default.
2770
- const raw = await git.raw(['diff', '--name-status', '-z', '-C', `${resolvedBase}...${headRef}`]);
2794
+ const args = ['diff', '--name-status', '-z', '-C'];
2795
+ const raw = includeWorkingTree
2796
+ ? await runWorkingTreeRangeDiff({ git, repoRoot }, baseRef, headRef, args)
2797
+ : await git.raw([...args, `${baseRef}...${headRef}`, '--']);
2771
2798
  // -z format: STATUS\0PATH\0[ORIG\0] repeated. For rename/copy entries
2772
2799
  // (`R100`, `C75`) the first path token is the ORIGINAL path and the second
2773
2800
  // is the DESTINATION — the diff (and the UI) must address the destination.
@@ -2777,7 +2804,7 @@ export async function getRangeFiles(directory, { base, head } = {}) {
2777
2804
  const status = (tokens[index] || '').trim();
2778
2805
  if (!status) continue;
2779
2806
  const isRenameOrCopy = status.startsWith('R') || status.startsWith('C');
2780
- const path = isRenameOrCopy ? (tokens[index + 2] || '').trim() : (tokens[index + 1] || '').trim();
2807
+ const path = isRenameOrCopy ? (tokens[index + 2] || '') : (tokens[index + 1] || '');
2781
2808
  index += isRenameOrCopy ? 2 : 1;
2782
2809
  if (path) {
2783
2810
  files.push({ path, status: status.charAt(0) });
@@ -2823,27 +2850,6 @@ const parseIsBinaryFromNumstat = (raw) => {
2823
2850
  return added === '-' || deleted === '-';
2824
2851
  };
2825
2852
 
2826
- const extractGitStatusPath = (status, pathPart) => {
2827
- if ((status === 'R' || status === 'C') && pathPart.includes('\t')) {
2828
- return pathPart.split('\t').pop() || pathPart;
2829
- }
2830
- return pathPart;
2831
- };
2832
-
2833
- const extractGitNumstatDestinationPath = (filePath) => {
2834
- if (!filePath.includes(' => ')) {
2835
- return filePath;
2836
- }
2837
-
2838
- const braceMatch = filePath.match(/^(.*)\{([^{}]*)\s=>\s([^{}]*)\}(.*)$/);
2839
- if (braceMatch) {
2840
- const [, prefix, , destination, suffix] = braceMatch;
2841
- return `${prefix}${destination}${suffix}`.replace(/\/+/g, '/');
2842
- }
2843
-
2844
- return filePath.split(' => ').pop()?.trim() || filePath;
2845
- };
2846
-
2847
2853
  const looksBinaryBySniff = async (absolutePath) => {
2848
2854
  try {
2849
2855
  const handle = await fsp.open(absolutePath, 'r');
@@ -3093,11 +3099,13 @@ const normalizePatchTargetPath = (value) => {
3093
3099
  };
3094
3100
 
3095
3101
  const extractPatchTargetPath = (patch) => {
3096
- const matches = [...patch.matchAll(/^(?:-{3}|\+{3})\s+.+$/gm)];
3102
+ const firstHunk = patch.search(/^@@\s/m);
3103
+ const header = firstHunk < 0 ? patch : patch.slice(0, firstHunk);
3104
+ const matches = [...header.matchAll(/^(?:-{3}|\+{3})\s+.+$/gm)];
3097
3105
  const realTargets = matches
3098
3106
  .map((match) => normalizePatchTargetPath(parsePatchPathToken(match[0])))
3099
3107
  .filter(Boolean);
3100
- return realTargets[0] || null;
3108
+ return realTargets.at(-1) || null;
3101
3109
  };
3102
3110
 
3103
3111
  const writeTempPatchFile = async (patch) => {
@@ -3125,9 +3133,21 @@ export async function applyHunk(directory, filePath, options = {}) {
3125
3133
  const fileContext = await resolveGitFileContext(directoryPath, directoryGit, filePath, repoRoot);
3126
3134
  validateRepositoryFilePaths(repoRoot, [fileContext.repoPath]);
3127
3135
 
3128
- const targetPath = extractPatchTargetPath(patch);
3129
- if (targetPath && targetPath !== fileContext.repoPath && targetPath !== filePath) {
3130
- throw new Error('patch target path does not match the requested file');
3136
+ // Applicability alone is insufficient: a previously staged or committed
3137
+ // hunk may still reverse cleanly against the working tree. Accept only a
3138
+ // canonical hunk from this file's current working/index diff.
3139
+ const current = await getDiff(directory, { path: filePath, staged: action === 'unstage', contextLines: 3 });
3140
+ const starts = [...current.matchAll(/^@@\s/gm)].map((match) => match.index);
3141
+ const header = current.slice(0, starts[0] ?? 0);
3142
+ const isCurrentHunk = starts.some((start, index) => (
3143
+ header + current.slice(start, starts[index + 1] ?? current.length) === patch
3144
+ ));
3145
+ if (!isCurrentHunk) {
3146
+ const targetPath = extractPatchTargetPath(patch);
3147
+ if (targetPath && targetPath !== fileContext.repoPath && targetPath !== filePath) {
3148
+ throw new Error('patch target path does not match the requested file');
3149
+ }
3150
+ throw new Error('Hunk no longer applies — refresh and try again.');
3131
3151
  }
3132
3152
 
3133
3153
  const flags = HUNK_ACTION_FLAGS[action];
@@ -4036,6 +4056,7 @@ export async function getWorktrees(directory) {
4036
4056
  name: path.basename(entry.worktree || ''),
4037
4057
  branch: entry.branch || '',
4038
4058
  path: entry.worktree,
4059
+ prunable: entry.prunable === true,
4039
4060
  }));
4040
4061
  } catch (error) {
4041
4062
  // Worktrees are an optional feature. When the caller passes a directory
@@ -4668,12 +4689,11 @@ export async function getLog(directory, options = {}) {
4668
4689
  };
4669
4690
  const resolvedFrom = await resolveBaseRefForLog(options.from, checkRef);
4670
4691
 
4671
- const baseLog = await git.log({
4672
- maxCount,
4673
- from: resolvedFrom,
4674
- to: options.to,
4675
- file: filePath
4676
- });
4692
+ // simple-git's `to` alone means HEAD..to, which is empty for the current
4693
+ // branch. A single requested ref means its reachable history instead.
4694
+ const baseLog = options.to && !resolvedFrom
4695
+ ? await git.log([`--max-count=${maxCount}`, options.to, ...(filePath ? ['--', filePath] : [])])
4696
+ : await git.log({ maxCount, from: resolvedFrom, to: options.to, file: filePath });
4677
4697
 
4678
4698
  const logArgs = [
4679
4699
  'log',
@@ -4917,85 +4937,61 @@ export async function canonicalizeWorktreeState(directory) {
4917
4937
  };
4918
4938
  }
4919
4939
 
4920
- export async function getCommitFiles(directory, commitHash) {
4921
- const { git } = await createRepositoryGitContext(directory);
4922
-
4923
- try {
4924
-
4925
- const numstatRaw = await git.raw([
4926
- 'show',
4927
- '--numstat',
4928
- '--format=',
4929
- commitHash
4930
- ]);
4931
-
4932
- const files = [];
4933
- const lines = numstatRaw.trim().split('\n').filter(Boolean);
4934
-
4935
- for (const line of lines) {
4936
- const parts = line.split('\t');
4937
- if (parts.length < 3) continue;
4938
-
4939
- const [insertionsRaw, deletionsRaw, ...pathParts] = parts;
4940
- const filePath = pathParts.join('\t');
4941
- if (!filePath) continue;
4942
-
4943
- const insertions = insertionsRaw === '-' ? 0 : parseInt(insertionsRaw, 10) || 0;
4944
- const deletions = deletionsRaw === '-' ? 0 : parseInt(deletionsRaw, 10) || 0;
4945
- const isBinary = insertionsRaw === '-' && deletionsRaw === '-';
4946
-
4947
- let changeType = 'M';
4948
- let displayPath = filePath;
4949
-
4950
- if (filePath.includes(' => ')) {
4951
- changeType = 'R';
4952
-
4953
- const match = filePath.match(/(?:\{[^}]*\s=>\s[^}]*\}|.*\s=>\s.*)/);
4954
- if (match) {
4955
- displayPath = filePath;
4956
- }
4957
- }
4958
-
4959
- files.push({
4960
- path: displayPath,
4961
- insertions,
4962
- deletions,
4963
- isBinary,
4964
- changeType
4965
- });
4966
- }
4967
-
4968
- const nameStatusRaw = await git.raw([
4969
- 'show',
4970
- '--name-status',
4971
- '--format=',
4972
- commitHash
4973
- ]).catch(() => '');
4974
-
4975
- const statusMap = new Map();
4976
- const statusLines = nameStatusRaw.trim().split('\n').filter(Boolean);
4977
- for (const line of statusLines) {
4978
- const match = line.match(/^([AMDRC])\d*\t(.+)$/);
4979
- if (match) {
4980
- const [, status, pathPart] = match;
4981
- statusMap.set(extractGitStatusPath(status, pathPart), status);
4982
- }
4983
- }
4940
+ async function resolveCommitHash(git, hash) {
4941
+ if (!/^[0-9a-f]{7,64}$/i.test(hash)) throw new Error('A commit hash is required');
4942
+ return (await git.raw(['rev-parse', '--verify', '--end-of-options', `${hash}^{commit}`])).trim();
4943
+ }
4984
4944
 
4985
- for (const file of files) {
4986
- const basePath = extractGitNumstatDestinationPath(file.path);
4945
+ const commitShowArgs = (hash) => ['show', '--format=', '--root', '--diff-merges=first-parent', '--find-renames', hash];
4987
4946
 
4988
- const status = statusMap.get(basePath) || statusMap.get(file.path);
4989
- if (status) {
4990
- file.changeType = status;
4991
- }
4992
- }
4947
+ export async function getCommitDiff(directory, { hash, path: filePath, previousPath, contextLines = 3 } = {}) {
4948
+ const { git } = await createRepositoryGitContext(directory);
4949
+ const commit = await resolveCommitHash(git, hash);
4950
+ const paths = [filePath, previousPath].filter(Boolean).map((value) => `:(literal)${value}`);
4951
+ return git.raw([
4952
+ ...commitShowArgs(commit), '--no-color', '--no-ext-diff', `-U${Math.max(0, contextLines)}`,
4953
+ '--', ...paths,
4954
+ ]);
4955
+ }
4993
4956
 
4994
- return { files };
4995
- } catch (error) {
4996
- console.error('Failed to get commit files:', error);
4997
- throw error;
4957
+ export async function getCommitFiles(directory, commitHash) {
4958
+ const { git } = await createRepositoryGitContext(directory);
4959
+ const hash = await resolveCommitHash(git, commitHash);
4960
+ const [numstat, nameStatus] = await Promise.all([
4961
+ git.raw([...commitShowArgs(hash), '--numstat', '-z', '--']),
4962
+ git.raw([...commitShowArgs(hash), '--name-status', '-z', '--']),
4963
+ ]);
4964
+ const stats = new Map();
4965
+ const tokens = numstat.split('\0');
4966
+ for (let index = 0; index < tokens.length; index += 1) {
4967
+ const match = /^(\d+|-)\t(\d+|-)\t([\s\S]*)$/.exec(tokens[index]);
4968
+ if (!match) continue;
4969
+ let destination = match[3];
4970
+ if (!destination) {
4971
+ destination = tokens[index + 2];
4972
+ index += 2;
4973
+ }
4974
+ stats.set(destination, {
4975
+ insertions: Number.parseInt(match[1], 10) || 0,
4976
+ deletions: Number.parseInt(match[2], 10) || 0,
4977
+ isBinary: match[1] === '-',
4978
+ });
4998
4979
  }
4980
+ const files = [];
4981
+ const names = nameStatus.split('\0');
4982
+ for (let index = 0; index < names.length; index += 1) {
4983
+ const changeType = names[index].charAt(0);
4984
+ if (!changeType) continue;
4985
+ const renamed = changeType === 'R' || changeType === 'C';
4986
+ const previousPath = renamed ? names[++index] : undefined;
4987
+ const filePath = names[++index];
4988
+ const fileStats = stats.get(filePath);
4989
+ if (!filePath || !fileStats) throw new Error('Incomplete commit file statistics');
4990
+ const entry = { path: filePath, ...fileStats, changeType };
4991
+ if (previousPath) entry.previousPath = previousPath;
4992
+ files.push(entry);
4993
+ }
4994
+ return { files };
4999
4995
  }
5000
4996
 
5001
4997
  export async function renameBranch(directory, oldName, newName) {