@pi-chamber/web 1.0.4-rc.4 → 1.0.5-rc.1

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 (204) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +21 -2
  3. package/bin/cli.test.js +164 -4
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +96 -13
  6. package/bin/lib/commands-connect-url-tailscale.test.js +136 -0
  7. package/bin/lib/commands-connect-url.js +146 -39
  8. package/bin/lib/commands-connect-url.test.js +126 -0
  9. package/bin/lib/commands-serve.js +45 -2
  10. package/bin/lib/commands-status.js +28 -5
  11. package/bin/lib/commands-status.test.js +107 -0
  12. package/bin/lib/commands-tunnel.js +36 -10
  13. package/dist/assets/{DiagramView--BGR3PRZ.js → DiagramView-D-OSWTbO.js} +1 -1
  14. package/dist/assets/DiffView-BKT-MIH4.js +18 -0
  15. package/dist/assets/{FileSaveConflictDialog-CcrWHRvd.js → FileSaveConflictDialog-DBkVFssC.js} +2 -2
  16. package/dist/assets/FilesView-B7GIuRlh.js +6 -0
  17. package/dist/assets/{GitHubDetailScaffold-BZhP67Va.js → GitHubDetailScaffold-C9rCZMUT.js} +2 -2
  18. package/dist/assets/{GitHubLinkPicker-CJZmDljp.js → GitHubLinkPicker-Bm09hvhJ.js} +1 -1
  19. package/dist/assets/{GitHubListPrimitives-DhF42guB.js → GitHubListPrimitives-DlhAlxI6.js} +1 -1
  20. package/dist/assets/{GitView-JK-QCK9R.js → GitView-BgqdMb0m.js} +4 -4
  21. package/dist/assets/{IssuesSurface-CAqQzrsv.js → IssuesSurface-BZXAvt49.js} +3 -3
  22. package/dist/assets/{JsonTreeView-CKTqB1CD.js → JsonTreeView-BKgCQjh_.js} +1 -1
  23. package/dist/assets/{MarkdownRendererImpl-B5kJy9Nt.js → MarkdownRendererImpl-BdcyMPw-.js} +1 -1
  24. package/dist/assets/{PatchDiff-BQnRFN30.js → PatchDiff-2MmWXcGe.js} +1 -1
  25. package/dist/assets/PierreDiffViewer-D1F2WvD0.js +135 -0
  26. package/dist/assets/PullRequestsSurface-CN2z3DFv.js +2 -0
  27. package/dist/assets/SessionSwitcherContent-CCljxAZb.js +1 -0
  28. package/dist/assets/SessionSwitcherDropdown-DtNt3qw4.js +2 -0
  29. package/dist/assets/SessionUnreadDot-B9bHMy5q.js +1 -0
  30. package/dist/assets/SettingsView-DaZVCInW.js +6 -0
  31. package/dist/assets/{SettingsWindow-CAxKgYOu.js → SettingsWindow-C-ydfopH.js} +1 -1
  32. package/dist/assets/StickyHorizontalScrollbar-BMITjK4e.js +8 -0
  33. package/dist/assets/{ToolOutputDialog-lz5exVQ4.js → ToolOutputDialog-DJUAx_Oj.js} +4 -4
  34. package/dist/assets/{ToolPartDiffPreview-nIUiNLpP.js → ToolPartDiffPreview-DFyuJM4c.js} +1 -1
  35. package/dist/assets/{VirtualizedFileDiff-IWqCJNXu.js → VirtualizedFileDiff-BS-af6rn.js} +4 -4
  36. package/dist/assets/{Virtualizer-Cp_cJWbI.js → Virtualizer-DP6HbEeC.js} +1 -1
  37. package/dist/assets/{collapsible-C7oyikVm.js → collapsible-BOcd0lzY.js} +1 -1
  38. package/dist/assets/{computeVirtualFileMetrics-CyhUKEfv.js → computeVirtualFileMetrics-BI6wORhM.js} +1 -1
  39. package/dist/assets/{contextFileOpenGuard-DkjmJ-NU.js → contextFileOpenGuard-DUMSGR4M.js} +1 -1
  40. package/dist/assets/{gitStatusPredicates-DBmUY3kA.js → gitStatusPredicates-FdKYDZe3.js} +1 -1
  41. package/dist/assets/{githubLink-BdbPMMAK.js → githubLink-B3-BaGpb.js} +5 -5
  42. package/dist/assets/index-DWSrsQWl.js +11 -0
  43. package/dist/assets/{index-CKgYIOis.js → index-Df-vmvzu.js} +1 -1
  44. package/dist/assets/index-DsQIBAWK.css +1 -0
  45. package/dist/assets/main-61_cd7S7.js +2 -0
  46. package/dist/assets/main-q43jqZ2I.js +136 -0
  47. package/dist/assets/{markdownCore-D7V46WY9.js → markdownCore-CqHYlXi_.js} +2 -2
  48. package/dist/assets/{miniChat-PanPmbEK.js → miniChat-vOuWN5pV.js} +2 -2
  49. package/dist/assets/mobile-mrXWV5ky.js +2 -0
  50. package/dist/assets/{nativeFileSave-BzhtrDoD.js → nativeFileSave-CFuugNKV.js} +1 -1
  51. package/dist/assets/pi-session-focus-preference-BEufpwC6.js +9 -0
  52. package/dist/assets/{renderDiffWithHighlighter-ByZtK9za.js → renderDiffWithHighlighter-BD9CAhZU.js} +1 -1
  53. package/dist/assets/renderElectronMiniChatApp-QQFXkY5Y.js +2 -0
  54. package/dist/assets/{renderFileWithHighlighter-CnN0Tv_8.js → renderFileWithHighlighter-KiEWMtzI.js} +1 -1
  55. package/dist/assets/renderMobileApp-DIZYvrhi.js +11 -0
  56. package/dist/assets/runtimeEndpointReset-BA2uP2rj.js +62 -0
  57. package/dist/assets/{runtimeSurface-DBiUWYK2.js → runtimeSurface-Der4qUnI.js} +1 -1
  58. package/dist/assets/useAppFontEffects-Bfw_d5eB.js +212 -0
  59. package/dist/assets/{useFilesViewSearch-BWABG6pS.js → useFilesViewSearch-Budwejnx.js} +3 -3
  60. package/dist/assets/useGitHubRemoteSearch-gUdylYy3.js +1 -0
  61. package/dist/assets/{useSwitcherItems-BSTSev5C.js → useSwitcherItems-yHSMduoo.js} +1 -1
  62. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BYohCVY0.js → vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js} +1 -1
  63. package/dist/assets/{vendor-base-ui-BscvGUFt.js → vendor-base-ui-CKRUCG-f.js} +1 -1
  64. package/dist/assets/{vendor-boot-Dgb9NVFe.js → vendor-boot-EC6IyLt1.js} +13 -13
  65. package/dist/assets/{vendor-capacitor-app-BjdQVib9.js → vendor-capacitor-app-BaupizkW.js} +1 -1
  66. package/dist/assets/{vendor-capacitor-keyboard-eTtI5go3.js → vendor-capacitor-keyboard-9BVxykO7.js} +1 -1
  67. package/dist/assets/{vendor-capacitor-status-bar-9rNIGxlO.js → vendor-capacitor-status-bar-BsrUwiaA.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-autocomplete-DxS3jwvE.js → vendor-codemirror-autocomplete-CGpAsPWp.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-angular-DdjXl9e2.js → vendor-codemirror-lang-angular-CDJoHJSY.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-cpp--aMr7NVt.js → vendor-codemirror-lang-cpp-BmHofQls.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-css-CZ_qxZY9.js → vendor-codemirror-lang-css-RM2HqXZ0.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-go-Ca-y2Alu.js → vendor-codemirror-lang-go-Crwca_X7.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-html-COZ0L5wT.js → vendor-codemirror-lang-html-CHSHUpwq.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-java-D3Rf3QNJ.js → vendor-codemirror-lang-java-lhQXgWu0.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-javascript-DwJ-IvCs.js → vendor-codemirror-lang-javascript-Dw4kFO4e.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-jinja-D_5lod6k.js → vendor-codemirror-lang-jinja-_pAC3UTN.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-json-BG8C7OpC.js → vendor-codemirror-lang-json-B-b1vAv-.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-less-CVEkoaTw.js → vendor-codemirror-lang-less-xIgOi1ze.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-liquid-U9vj0m8w.js → vendor-codemirror-lang-liquid-CP49m5dB.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-markdown-DqlYH9gY.js → vendor-codemirror-lang-markdown-BTht2ATe.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-php-BFEiEVA1.js → vendor-codemirror-lang-php-BguZDhaO.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-python-Cz1dQXQd.js → vendor-codemirror-lang-python-CH6_em9L.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-rust-C_CoD9mj.js → vendor-codemirror-lang-rust-EG_DtGyi.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-lang-sass-BuR0aKh5.js → vendor-codemirror-lang-sass-BknY5Qpo.js} +1 -1
  85. package/dist/assets/{vendor-codemirror-lang-sql-DggNUjdM.js → vendor-codemirror-lang-sql-B0f-qCZo.js} +1 -1
  86. package/dist/assets/{vendor-codemirror-lang-vue-DFZHi2J3.js → vendor-codemirror-lang-vue-CyGn9snv.js} +1 -1
  87. package/dist/assets/{vendor-codemirror-lang-wast-zuTN3SHT.js → vendor-codemirror-lang-wast-CsFfSyyB.js} +1 -1
  88. package/dist/assets/{vendor-codemirror-lang-xml-CrcvhI-k.js → vendor-codemirror-lang-xml-Cdan_Jp1.js} +1 -1
  89. package/dist/assets/{vendor-codemirror-lang-yaml-DcVWsakb.js → vendor-codemirror-lang-yaml-COI5hck8.js} +1 -1
  90. package/dist/assets/{vendor-codemirror-language-data-CCLITgCF.js → vendor-codemirror-language-data-CqU7kHmg.js} +2 -2
  91. package/dist/assets/{vendor-codemirror-search-H7NOEdbX.js → vendor-codemirror-search-DUfSCF9S.js} +1 -1
  92. package/dist/assets/{vendor-lezer-cpp-C8aD2KAr.js → vendor-lezer-cpp-DMZOJzBa.js} +1 -1
  93. package/dist/assets/{vendor-lezer-css-2lbTJF-Y.js → vendor-lezer-css-DUkkbMp7.js} +1 -1
  94. package/dist/assets/{vendor-lezer-go-Bw6LFTrZ.js → vendor-lezer-go-CHIhCNY6.js} +1 -1
  95. package/dist/assets/{vendor-lezer-html-D7ym2z7S.js → vendor-lezer-html-B3h0MOrG.js} +1 -1
  96. package/dist/assets/{vendor-lezer-java-CZhK7w21.js → vendor-lezer-java-tMazV_6X.js} +1 -1
  97. package/dist/assets/{vendor-lezer-javascript-rpKeTHZp.js → vendor-lezer-javascript-ctwLWf4v.js} +1 -1
  98. package/dist/assets/{vendor-lezer-json-C7jwsd2G.js → vendor-lezer-json-BP_UAzLL.js} +1 -1
  99. package/dist/assets/{vendor-lezer-lr-DR-ylqNN.js → vendor-lezer-lr-B8TQctNw.js} +1 -1
  100. package/dist/assets/{vendor-lezer-markdown-Bir0m5nB.js → vendor-lezer-markdown-aGLZf_3h.js} +1 -1
  101. package/dist/assets/{vendor-lezer-php-y0hIEfo1.js → vendor-lezer-php-D5zCNzlt.js} +1 -1
  102. package/dist/assets/{vendor-lezer-python-D64A9lNV.js → vendor-lezer-python-EJ4Im4y2.js} +1 -1
  103. package/dist/assets/{vendor-lezer-rust-E3ZA9T2L.js → vendor-lezer-rust-DO5c7OtA.js} +1 -1
  104. package/dist/assets/{vendor-lezer-sass-C5UFI9SP.js → vendor-lezer-sass-CMi6zfXI.js} +1 -1
  105. package/dist/assets/{vendor-lezer-xml-DOy7FzCR.js → vendor-lezer-xml-0MHMeZDp.js} +1 -1
  106. package/dist/assets/{vendor-lezer-yaml-kEjaSCvZ.js → vendor-lezer-yaml-BE2EFjpA.js} +1 -1
  107. package/dist/assets/{vendor-replit-codemirror-vim-BLfh0LPy.js → vendor-replit-codemirror-vim-AnOuN8yJ.js} +1 -1
  108. package/dist/assets/{web-components-CdMfsnXE.js → web-components-CeHLxvED.js} +3 -3
  109. package/dist/index.html +4 -4
  110. package/dist/mini-chat.html +3 -3
  111. package/dist/mobile.html +3 -3
  112. package/dist/sw.js +1 -1
  113. package/package.json +1 -2
  114. package/server/index.js +69 -30
  115. package/server/lib/client-auth/DOCUMENTATION.md +15 -1
  116. package/server/lib/client-auth/pairing.js +2 -12
  117. package/server/lib/client-auth/remote-clients.js +2 -12
  118. package/server/lib/cloudflare-tunnel.js +0 -132
  119. package/server/lib/fs/DOCUMENTATION.md +8 -0
  120. package/server/lib/fs/atomic-write.js +111 -0
  121. package/server/lib/fs/atomic-write.test.js +133 -0
  122. package/server/lib/notifications/DOCUMENTATION.md +43 -32
  123. package/server/lib/notifications/pi-notification-watcher.js +8 -7
  124. package/server/lib/notifications/pi-notification-watcher.test.js +88 -2
  125. package/server/lib/pi/routes-extension-events.test.js +231 -0
  126. package/server/lib/pi/routes.js +137 -4
  127. package/server/lib/pi/routes.test.js +248 -2
  128. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -4
  129. package/server/lib/pi/session-daemon/daemon-process.js +2 -0
  130. package/server/lib/pi/session-daemon/engines/index.js +6 -0
  131. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +1 -1
  132. package/server/lib/pi/session-daemon/extension-bridge.js +24 -0
  133. package/server/lib/pi/session-daemon/extension-message-render.js +74 -0
  134. package/server/lib/pi/session-daemon/extension-message-render.test.js +164 -0
  135. package/server/lib/pi/session-daemon/extension-tool-render.js +13 -6
  136. package/server/lib/pi/session-daemon/pending-input.js +188 -0
  137. package/server/lib/pi/session-daemon/pending-input.test.js +202 -0
  138. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +828 -0
  139. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +296 -6
  140. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +9 -0
  141. package/server/lib/pi/session-daemon/session-daemon.js +219 -19
  142. package/server/lib/pi/session-daemon/session-daemon.test.js +30 -2
  143. package/server/lib/pi/session-daemon/session-engine-router.js +390 -0
  144. package/server/lib/pi/session-daemon/session-engine-router.test.js +515 -0
  145. package/server/lib/pi/session-daemon/session-engines.js +467 -0
  146. package/server/lib/pi/session-daemon/session-engines.test.js +383 -0
  147. package/server/lib/pi/snippets-store.js +8 -17
  148. package/server/lib/pi/ui-settings-store.js +6 -10
  149. package/server/lib/pi/ui-settings-store.test.js +37 -1
  150. package/server/lib/relay/DOCUMENTATION.md +6 -4
  151. package/server/lib/relay/identity-store.js +116 -0
  152. package/server/lib/relay/identity-store.test.js +169 -0
  153. package/server/lib/relay/identity.js +6 -4
  154. package/server/lib/relay/server-id.js +63 -0
  155. package/server/lib/relay/server-id.test.js +132 -0
  156. package/server/lib/relay/signing-key.js +14 -11
  157. package/server/lib/security/bind-host.js +6 -2
  158. package/server/lib/security/bind-host.test.js +17 -0
  159. package/server/lib/server/core-routes.js +27 -1
  160. package/server/lib/server/lan-addresses.js +18 -6
  161. package/server/lib/server/lan-addresses.test.js +28 -0
  162. package/server/lib/server/tunnel-auth.js +47 -7
  163. package/server/lib/server/tunnel-auth.rate-limit.test.js +164 -0
  164. package/server/lib/server/tunnel-service.DOCUMENTATION.md +3 -4
  165. package/server/lib/server/tunnel-service.js +23 -20
  166. package/server/lib/server/tunnel-service.test.js +19 -2
  167. package/server/lib/stt/config-store.js +5 -15
  168. package/server/lib/tailscale/DOCUMENTATION.md +264 -0
  169. package/server/lib/tailscale/routes.js +45 -0
  170. package/server/lib/tailscale/service.js +959 -0
  171. package/server/lib/tailscale/tailscale.js +302 -0
  172. package/server/lib/tailscale/tailscale.test.js +1861 -0
  173. package/server/lib/tunnels/DOCUMENTATION.md +3 -4
  174. package/server/lib/tunnels/providers/cloudflare.js +1 -22
  175. package/server/lib/tunnels/types.js +0 -2
  176. package/server/lib/ui-auth/DOCUMENTATION.md +31 -0
  177. package/server/lib/ui-auth/ui-auth.js +80 -6
  178. package/server/lib/ui-auth/ui-auth.test.js +136 -0
  179. package/server/lib/ui-auth/ui-passkeys.js +2 -13
  180. package/server/lib/update-job-store.js +4 -6
  181. package/dist/assets/DiffView-hz90_htv.js +0 -18
  182. package/dist/assets/FilesView-DaqkPMqx.js +0 -6
  183. package/dist/assets/PierreDiffViewer-BeGpdI0x.js +0 -134
  184. package/dist/assets/PullRequestsSurface-D9beq2x9.js +0 -2
  185. package/dist/assets/SessionSwitcherContent-DElQ_cjm.js +0 -1
  186. package/dist/assets/SessionSwitcherDropdown-JaIDcDIj.js +0 -2
  187. package/dist/assets/SessionUnreadDot-Czfvjbdi.js +0 -1
  188. package/dist/assets/SettingsView-C_GC1Mx3.js +0 -6
  189. package/dist/assets/index-BnZVqcki.js +0 -11
  190. package/dist/assets/index-BnieExes.css +0 -1
  191. package/dist/assets/main-6YKi4QM2.js +0 -2
  192. package/dist/assets/main-CWdWdhdL.js +0 -136
  193. package/dist/assets/mobile-0LY-2fxw.js +0 -2
  194. package/dist/assets/pi-session-focus-preference-BC-ze1oC.js +0 -10
  195. package/dist/assets/renderElectronMiniChatApp-DETQLjFi.js +0 -2
  196. package/dist/assets/renderMobileApp-DS0FDQLg.js +0 -11
  197. package/dist/assets/runtimeEndpointReset-BqqXMwE9.js +0 -62
  198. package/dist/assets/useAppFontEffects-BisjofNZ.js +0 -212
  199. package/dist/assets/useGitHubRemoteSearch-Bsf2YeQP.js +0 -1
  200. package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +0 -1
  201. package/server/lib/notifications/delivery-runtime.js +0 -314
  202. package/server/lib/notifications/delivery-runtime.test.js +0 -85
  203. package/server/lib/notifications/routes.js +0 -74
  204. package/server/lib/relay/service.js +0 -9
@@ -23,7 +23,7 @@ use `pichamber tunnel start` after the server is running.
23
23
  - `install-help.js` provides provider and platform install guidance for missing
24
24
  dependencies.
25
25
  - `types.js` defines provider, mode, intent, and `TunnelServiceError` values.
26
- - `../cloudflare-tunnel.js` starts Cloudflare Quick, Managed Remote, and Managed
26
+ - `../cloudflare-tunnel.js` starts Cloudflare Managed Remote and Managed
27
27
  Local children and reports their public hostname.
28
28
  - `../server/tunnel-service.js` owns one active child, token storage, public URL
29
29
  state, and tunnel-auth registration.
@@ -34,10 +34,9 @@ use `pichamber tunnel start` after the server is running.
34
34
  - `executable-search.js` → `getExecutableSearchDirectories`,
35
35
  `createExecutableSearchEnv`, `findExecutableOnPath`,
36
36
  `resolveExecutableLaunchTarget`
37
- - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`, `TUNNEL_MODE_QUICK`,
37
+ - `types.js` → `TUNNEL_PROVIDER_CLOUDFLARE`,
38
38
  `TUNNEL_MODE_MANAGED_REMOTE`, `TUNNEL_MODE_MANAGED_LOCAL`,
39
- `TUNNEL_INTENT_EPHEMERAL_PUBLIC`, `TUNNEL_INTENT_PERSISTENT_PUBLIC`,
40
- `TunnelServiceError`
39
+ `TUNNEL_INTENT_PERSISTENT_PUBLIC`, `TunnelServiceError`
41
40
 
42
41
  ## Consumers
43
42
 
@@ -1,39 +1,18 @@
1
1
  import {
2
- checkCloudflareApiReachability,
3
- checkCloudflaredAvailable,
4
- inspectManagedLocalCloudflareConfig,
5
- normalizeCloudflareTunnelHostname,
6
- startCloudflareManagedLocalTunnel,
7
- startCloudflareManagedRemoteTunnel,
8
- startCloudflareQuickTunnel,
9
- } from '../../cloudflare-tunnel.js';
10
-
11
- import {
12
- TUNNEL_INTENT_EPHEMERAL_PUBLIC,
13
2
  TUNNEL_INTENT_PERSISTENT_PUBLIC,
14
3
  TUNNEL_MODE_MANAGED_LOCAL,
15
4
  TUNNEL_MODE_MANAGED_REMOTE,
16
- TUNNEL_MODE_QUICK,
17
5
  TUNNEL_PROVIDER_CLOUDFLARE,
18
- TunnelServiceError,
19
6
  } from '../types.js';
20
7
  import { getTunnelDependencyInstallInfo } from '../install-help.js';
21
8
 
22
9
  export const cloudflareTunnelProviderCapabilities = {
23
10
  provider: TUNNEL_PROVIDER_CLOUDFLARE,
24
11
  defaults: {
25
- mode: TUNNEL_MODE_QUICK,
12
+ mode: TUNNEL_MODE_MANAGED_REMOTE,
26
13
  optionDefaults: {},
27
14
  },
28
15
  modes: [
29
- {
30
- key: TUNNEL_MODE_QUICK,
31
- label: 'Quick Tunnel',
32
- intent: TUNNEL_INTENT_EPHEMERAL_PUBLIC,
33
- requires: [],
34
- supports: ['sessionTTL'],
35
- stability: 'ga',
36
- },
37
16
  {
38
17
  key: TUNNEL_MODE_MANAGED_REMOTE,
39
18
  label: 'Managed Remote Tunnel',
@@ -1,10 +1,8 @@
1
1
  export const TUNNEL_PROVIDER_CLOUDFLARE = 'cloudflare';
2
2
 
3
- export const TUNNEL_MODE_QUICK = 'quick';
4
3
  export const TUNNEL_MODE_MANAGED_REMOTE = 'managed-remote';
5
4
  export const TUNNEL_MODE_MANAGED_LOCAL = 'managed-local';
6
5
 
7
- export const TUNNEL_INTENT_EPHEMERAL_PUBLIC = 'ephemeral-public';
8
6
  export const TUNNEL_INTENT_PERSISTENT_PUBLIC = 'persistent-public';
9
7
 
10
8
  export class TunnelServiceError extends Error {
@@ -41,6 +41,37 @@ Signing-secret topology: the JWT secret is read once at startup (env override or
41
41
  - `ensureSessionToken(req, res)`
42
42
  - `dispose()`
43
43
 
44
+ ## Login rate limiting (dual-bucket)
45
+
46
+ Password (`handleSessionCreate`) and passkey (`handlePasskeyAuthenticationVerify`)
47
+ login attempts share one limiter with two buckets per attempt:
48
+
49
+ - Per-client bucket keyed by `X-Forwarded-For` first (falls back to `req.ip`):
50
+ 10 attempts per 5 minutes (env-overridable via
51
+ `PICHAMBER_RATE_LIMIT_MAX_ATTEMPTS`), then a 15-minute lockout. Preserves
52
+ per-device budgets behind legitimate proxies.
53
+ - Socket bucket keyed by `req.socket.remoteAddress` (never `req.ip`, which
54
+ Express rewrites from XFF under `trust proxy`): 5x the per-client limit in
55
+ the same window, same lockout.
56
+
57
+ An attempt is refused (429) if EITHER bucket is exhausted. The socket
58
+ address is the unspoofable peer of the TCP connection: Tailscale
59
+ Serve/Funnel forwards from loopback while passing attacker-supplied XFF
60
+ through, so XFF alone would let a public attacker rotate headers for a
61
+ fresh bucket per guess. The socket bucket bounds total guesses per socket
62
+ while `trust proxy` stays enabled for real deployments. A successful
63
+ login clears only the requester's per-client bucket, never the shared
64
+ socket bucket (which decays via window/lockout expiry only); otherwise
65
+ any legitimate login would wipe an attacker's accumulated guesses and
66
+ defeat the socket bound.
67
+
68
+ Accepted trade-off: because Serve/Funnel share the loopback socket, an
69
+ attacker exhausting the socket bucket over Funnel locks out every
70
+ Tailscale/loopback login for the lockout window (15 min) — bounded
71
+ guessing is preferred over unlimited guessing. The per-client bucket keeps
72
+ separate tailnet devices' normal budgets while the socket bucket is not
73
+ exhausted.
74
+
44
75
  ## Public exports (ui-passkeys.js)
45
76
  - `createUiPasskeys({ passwordBinding, readSettingsFromDiskMigrated, storeFile, rpName, challengeTtlMs })`: creates passkey runtime with methods:
46
77
  - `enabled`
@@ -43,19 +43,53 @@ const getClientIp = (req) => {
43
43
  return null;
44
44
  };
45
45
 
46
+ const normalizeSocketIp = (value) => {
47
+ if (typeof value !== 'string' || !value) return null;
48
+ const trimmed = value.trim();
49
+ if (!trimmed) return null;
50
+ if (trimmed.startsWith('::ffff:')) return trimmed.substring(7);
51
+ return trimmed;
52
+ };
53
+
54
+ // The socket address is the unspoofable peer of the TCP connection
55
+ // (`trust proxy` rewrites `req.ip` from X-Forwarded-For, and Tailscale
56
+ // Serve/Funnel forwards from loopback while passing attacker-supplied XFF
57
+ // through). A per-client bucket alone lets a public attacker rotate XFF
58
+ // for a fresh bucket per guess, so every login attempt is ALSO counted
59
+ // against the socket bucket below.
60
+ const getSocketIp = (req) => normalizeSocketIp(req.socket?.remoteAddress || req.connection?.remoteAddress);
61
+
46
62
  const getRateLimitKey = (req) => {
47
63
  const ip = getClientIp(req);
48
64
  if (ip) return ip;
49
65
  return 'rate-limit:no-ip';
50
66
  };
51
67
 
68
+ const getSocketRateLimitKey = (req) => {
69
+ const ip = getSocketIp(req);
70
+ if (ip) return `rate-limit:socket:${ip}`;
71
+ return 'rate-limit:no-socket';
72
+ };
73
+
74
+ // Socket bucket: 5x the per-client limit in the same window. One socket
75
+ // (one Tailscale forwarder, one NAT, one reverse proxy) legitimately
76
+ // multiplexes many clients, so it needs headroom — but the total guesses
77
+ // per socket per window stay bounded, which is what stops XFF rotation.
78
+ const RATE_LIMIT_SOCKET_MULTIPLIER = 5;
79
+
52
80
  const getRateLimitConfig = (key) => {
53
- if (key === 'rate-limit:no-ip') {
81
+ if (key === 'rate-limit:no-ip' || key === 'rate-limit:no-socket') {
54
82
  return {
55
83
  maxAttempts: RATE_LIMIT_NO_IP_MAX_ATTEMPTS,
56
84
  windowMs: RATE_LIMIT_WINDOW_MS
57
85
  };
58
86
  }
87
+ if (key.startsWith('rate-limit:socket:')) {
88
+ return {
89
+ maxAttempts: RATE_LIMIT_MAX_ATTEMPTS * RATE_LIMIT_SOCKET_MULTIPLIER,
90
+ windowMs: RATE_LIMIT_WINDOW_MS
91
+ };
92
+ }
59
93
  return {
60
94
  maxAttempts: RATE_LIMIT_MAX_ATTEMPTS,
61
95
  windowMs: RATE_LIMIT_WINDOW_MS
@@ -69,8 +103,7 @@ const acquireRateLimitLock = async (key) => {
69
103
  await curr;
70
104
  };
71
105
 
72
- const checkRateLimit = async (req) => {
73
- const key = getRateLimitKey(req);
106
+ const checkSingleRateLimitBucket = async (key) => {
74
107
  await acquireRateLimitLock(key);
75
108
 
76
109
  const now = Date.now();
@@ -144,12 +177,27 @@ const checkRateLimit = async (req) => {
144
177
  };
145
178
  };
146
179
 
147
- const recordFailedAttempt = async (req) => {
148
- const key = getRateLimitKey(req);
180
+ // Dual-bucket gate: the per-client bucket (XFF-derived, for UX behind legit
181
+ // proxies) AND the socket bucket (unspoofable peer address) are both
182
+ // checked. An attempt is refused if EITHER bucket is exhausted, so rotating
183
+ // X-Forwarded-For from one socket still hits the socket lockout.
184
+ const checkRateLimit = async (req) => {
185
+ const clientResult = await checkSingleRateLimitBucket(getRateLimitKey(req));
186
+ const socketResult = await checkSingleRateLimitBucket(getSocketRateLimitKey(req));
187
+ if (!clientResult.allowed) return clientResult;
188
+ if (!socketResult.allowed) return socketResult;
189
+ return {
190
+ allowed: true,
191
+ limit: clientResult.limit,
192
+ remaining: Math.min(clientResult.remaining, socketResult.remaining),
193
+ reset: Math.max(clientResult.reset, socketResult.reset),
194
+ };
195
+ };
196
+
197
+ const recordSingleFailedAttempt = async (key) => {
149
198
  await acquireRateLimitLock(key);
150
199
 
151
200
  const now = Date.now();
152
- const { maxAttempts } = getRateLimitConfig(key);
153
201
  const record = loginRateLimiter.get(key);
154
202
 
155
203
  if (!record || now - record.lastAttempt > RATE_LIMIT_WINDOW_MS) {
@@ -168,6 +216,15 @@ const recordFailedAttempt = async (req) => {
168
216
  }
169
217
  };
170
218
 
219
+ const recordFailedAttempt = async (req) => {
220
+ await recordSingleFailedAttempt(getRateLimitKey(req));
221
+ await recordSingleFailedAttempt(getSocketRateLimitKey(req));
222
+ };
223
+
224
+ // Success clears only the per-client bucket. The socket bucket is shared
225
+ // (Tailscale Serve/Funnel multiplexes every client onto loopback), so
226
+ // clearing it here would let one legitimate login wipe out an attacker's
227
+ // accumulated guesses. It decays via window/lockout expiry only.
171
228
  const clearRateLimit = async (req) => {
172
229
  const key = getRateLimitKey(req);
173
230
  await acquireRateLimitLock(key);
@@ -974,8 +1031,24 @@ export const createUiAuth = ({
974
1031
  };
975
1032
 
976
1033
  const handlePasskeyAuthenticationVerify = async (req, res) => {
1034
+ // Passkey verification is a login attempt path: gate it with the same
1035
+ // dual-bucket limiter as the password path so XFF rotation cannot
1036
+ // bypass it either.
1037
+ const rateLimitResult = await checkRateLimit(req);
1038
+ res.setHeader('X-RateLimit-Limit', rateLimitResult.limit);
1039
+ res.setHeader('X-RateLimit-Remaining', rateLimitResult.remaining);
1040
+ res.setHeader('X-RateLimit-Reset', rateLimitResult.reset);
1041
+ if (!rateLimitResult.allowed) {
1042
+ res.setHeader('Retry-After', rateLimitResult.retryAfter);
1043
+ res.status(429).json({
1044
+ error: 'Too many login attempts, please try again later',
1045
+ retryAfter: rateLimitResult.retryAfter
1046
+ });
1047
+ return;
1048
+ }
977
1049
  try {
978
1050
  await passkeyController.finishAuthentication(req.body);
1051
+ await clearRateLimit(req);
979
1052
  const trustDevice = isTrustedDeviceRequest(req.body?.trustDevice);
980
1053
  const ttlMs = resolveSessionTtlMs(trustDevice);
981
1054
  await issueSession(req, res, { trustDevice });
@@ -998,6 +1071,7 @@ export const createUiAuth = ({
998
1071
  ...(clientTokenResult?.token ? { clientToken: clientTokenResult.token, client: clientTokenResult.client } : {}),
999
1072
  });
1000
1073
  } catch (error) {
1074
+ await recordFailedAttempt(req);
1001
1075
  respondPasskeyError(res, error);
1002
1076
  }
1003
1077
  };
@@ -549,3 +549,139 @@ describe('ui auth live revocation', () => {
549
549
  }
550
550
  });
551
551
  });
552
+
553
+ describe('login rate limit socket bucket (F1)', () => {
554
+ const perClientMax = Number(process.env.PICHAMBER_RATE_LIMIT_MAX_ATTEMPTS) || 10;
555
+ const socketMax = perClientMax * 5;
556
+
557
+ const loginReq = (xff, socketIp) => ({
558
+ method: 'POST',
559
+ headers: { 'x-forwarded-for': xff },
560
+ socket: { remoteAddress: socketIp },
561
+ body: { password: 'wrong-password' },
562
+ });
563
+
564
+ it('locks out XFF rotation from one socket after the socket threshold', async () => {
565
+ const createUiAuth = await loadCreateUiAuth();
566
+ const auth = createUiAuth({ password: 'correct-horse-battery' });
567
+ try {
568
+ // Every guess uses a fresh XFF (fresh per-client bucket) from the same
569
+ // socket: without the socket bucket this would never lock out.
570
+ for (let i = 0; i < socketMax; i++) {
571
+ const res = createResponse();
572
+ await auth.handleSessionCreate(loginReq(`203.0.113.${i % 250 + 1}`, '198.51.100.71'), res);
573
+ expect(res.statusCode).toBe(401);
574
+ }
575
+ const lockedRes = createResponse();
576
+ await auth.handleSessionCreate(loginReq('203.0.113.250', '198.51.100.71'), lockedRes);
577
+ expect(lockedRes.statusCode).toBe(429);
578
+ expect(lockedRes.body?.retryAfter).toBeGreaterThan(0);
579
+ } finally {
580
+ auth.dispose();
581
+ }
582
+ });
583
+
584
+ it('keeps distinct sockets independent', async () => {
585
+ const createUiAuth = await loadCreateUiAuth();
586
+ const auth = createUiAuth({ password: 'correct-horse-battery' });
587
+ try {
588
+ // Exhaust the per-client bucket for one XFF on socket A.
589
+ for (let i = 0; i < perClientMax; i++) {
590
+ const res = createResponse();
591
+ await auth.handleSessionCreate(loginReq('198.51.100.72', '192.0.2.11'), res);
592
+ expect(res.statusCode).toBe(401);
593
+ }
594
+ const lockedRes = createResponse();
595
+ await auth.handleSessionCreate(loginReq('198.51.100.72', '192.0.2.11'), lockedRes);
596
+ expect(lockedRes.statusCode).toBe(429);
597
+ // A different socket with a fresh XFF is unaffected (401, not 429).
598
+ const otherRes = createResponse();
599
+ await auth.handleSessionCreate(loginReq('198.51.100.73', '192.0.2.12'), otherRes);
600
+ expect(otherRes.statusCode).toBe(401);
601
+ } finally {
602
+ auth.dispose();
603
+ }
604
+ });
605
+
606
+ it('successful login preserves the shared socket bucket', async () => {
607
+ const createUiAuth = await loadCreateUiAuth();
608
+ const auth = createUiAuth({ password: 'correct-horse-battery' });
609
+ try {
610
+ const socketIp = '198.51.100.99';
611
+ // 45 bad guesses with rotating XFF (fresh per-client bucket each)
612
+ // from one socket: only the socket bucket accumulates.
613
+ for (let i = 0; i < 45; i++) {
614
+ const res = createResponse();
615
+ await auth.handleSessionCreate(loginReq(`203.0.113.${i + 1}`, socketIp), res);
616
+ expect(res.statusCode).toBe(401);
617
+ }
618
+ // Owner logs in once from the same socket with a different XFF.
619
+ const okRes = createResponse();
620
+ await auth.handleSessionCreate({
621
+ method: 'POST',
622
+ headers: { 'x-forwarded-for': '198.51.100.200' },
623
+ socket: { remoteAddress: socketIp },
624
+ body: { password: 'correct-horse-battery' },
625
+ }, okRes);
626
+ expect(okRes.statusCode).toBe(200);
627
+ expect(okRes.body?.authenticated).toBe(true);
628
+
629
+ // The socket bucket was NOT wiped: a fresh XFF sees the socket
630
+ // remainder (50 - 45 = 5), not a full per-client bucket of 10.
631
+ const probeRes = createResponse();
632
+ await auth.handleSessionCreate(loginReq('203.0.113.210', socketIp), probeRes);
633
+ expect(probeRes.statusCode).toBe(401);
634
+ expect(probeRes.getHeader('x-ratelimit-remaining')).toBe(socketMax - 45);
635
+
636
+ // Lockout still arrives at the same total (50 failures) as without
637
+ // the success: probe was #46, so 4 more go through, then 429.
638
+ for (let i = 0; i < 4; i++) {
639
+ const res = createResponse();
640
+ await auth.handleSessionCreate(loginReq(`203.0.113.${220 + i}`, socketIp), res);
641
+ expect(res.statusCode).toBe(401);
642
+ }
643
+ const lockedRes = createResponse();
644
+ await auth.handleSessionCreate(loginReq('203.0.113.230', socketIp), lockedRes);
645
+ expect(lockedRes.statusCode).toBe(429);
646
+ } finally {
647
+ auth.dispose();
648
+ }
649
+ });
650
+
651
+ it('successful login resets only the succeeding per-client bucket', async () => {
652
+ const createUiAuth = await loadCreateUiAuth();
653
+ const auth = createUiAuth({ password: 'correct-horse-battery' });
654
+ try {
655
+ const socketIp = '198.51.100.98';
656
+ // 3 failures charged to the succeeding client's own bucket.
657
+ for (let i = 0; i < 3; i++) {
658
+ const res = createResponse();
659
+ await auth.handleSessionCreate(loginReq('198.51.100.201', socketIp), res);
660
+ expect(res.statusCode).toBe(401);
661
+ }
662
+ const okRes = createResponse();
663
+ await auth.handleSessionCreate({
664
+ method: 'POST',
665
+ headers: { 'x-forwarded-for': '198.51.100.201' },
666
+ socket: { remoteAddress: socketIp },
667
+ body: { password: 'correct-horse-battery' },
668
+ }, okRes);
669
+ expect(okRes.body?.authenticated).toBe(true);
670
+
671
+ // Fresh budget for that XFF: 10 more failures are all tolerated
672
+ // (socket total stays far below the socket threshold, so a 429 here
673
+ // could only come from the per-client bucket; without the reset the
674
+ // 3 stale failures would lock it after 7 more).
675
+ for (let i = 0; i < perClientMax; i++) {
676
+ const res = createResponse();
677
+ await auth.handleSessionCreate(loginReq('198.51.100.201', socketIp), res);
678
+ expect(res.statusCode).toBe(401);
679
+ }
680
+ const lockedRes = createResponse();
681
+ await auth.handleSessionCreate(loginReq('198.51.100.201', socketIp), lockedRes);
682
+ expect(lockedRes.statusCode).toBe(429);
683
+ } finally {
684
+ auth.dispose();
685
+ }
686
+ });
687
+ });
@@ -8,6 +8,7 @@ import {
8
8
  verifyRegistrationResponse,
9
9
  } from '@simplewebauthn/server';
10
10
 
11
+ import { writeFileAtomicSync } from '../fs/atomic-write.js';
11
12
  import { resolvePiChamberDataDir, resolvePiChamberDataPath } from '../pichamber-data-dir.js';
12
13
 
13
14
  const DEFAULT_STORE_VERSION = 1;
@@ -120,21 +121,9 @@ export const createUiPasskeys = ({
120
121
  const registrationChallenges = new Map();
121
122
  const authenticationChallenges = new Map();
122
123
 
123
- const ensureStoreDirectory = () => {
124
- fs.mkdirSync(path.dirname(storeFile), { recursive: true });
125
- };
126
-
127
124
  const persistStore = (store) => {
128
- ensureStoreDirectory();
129
125
  // Atomic replace so a concurrent server never reads a torn store.
130
- const temporary = `${storeFile}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
131
- try {
132
- fs.writeFileSync(temporary, JSON.stringify(store, null, 2), { mode: 0o600 });
133
- fs.renameSync(temporary, storeFile);
134
- } catch (error) {
135
- try { fs.rmSync(temporary, { force: true }); } catch {}
136
- throw error;
137
- }
126
+ writeFileAtomicSync(storeFile, JSON.stringify(store, null, 2));
138
127
  };
139
128
 
140
129
  const createEmptyStore = () => ({
@@ -1,7 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
3
- import { dirname, join } from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
4
 
5
+ import { writeFileAtomic } from './fs/atomic-write.js';
5
6
  import { resolvePiChamberDataDir } from './pichamber-data-dir.js';
6
7
  import { withCrossProcessLock } from './server/cross-process-lock.js';
7
8
 
@@ -58,10 +59,7 @@ export const createUpdateJobStore = ({
58
59
  };
59
60
 
60
61
  const writeFileValue = async (job) => {
61
- await mkdir(dirname(file), { recursive: true, mode: 0o700 });
62
- const temporary = `${file}.${process.pid}.tmp`;
63
- await writeFile(temporary, JSON.stringify(job), { mode: 0o600 });
64
- await rename(temporary, file);
62
+ await writeFileAtomic(file, JSON.stringify(job));
65
63
  return job;
66
64
  };
67
65
 
@@ -1,18 +0,0 @@
1
- import{k as n,aL as St}from"./vendor-boot-Dgb9NVFe.js";import{R as r}from"./vendor-react-DASdDPIk.js";import{o as se,t as Q,a as Ze,C as ze}from"./index-BnZVqcki.js";import{dN as vt,dv as Ct,dL as Nt,aj as et,a7 as tt,ck as jt,cl as je,B as Le,I as J,q as nt,aD as oe,t as st,dD as it,ce as Lt,dO as Dt,dP as kt,p as Rt,a4 as Et,ay as At,ah as Tt,cF as Mt,h as It,at as $t,aM as Pt,a9 as _t,aa as Wt,ac as Bt}from"./useAppFontEffects-BisjofNZ.js";import{d as rt,i as Ge,a as He,b as Ot,C as zt}from"./gitStatusPredicates-DBmUY3kA.js";import{p as Gt}from"./VirtualizedFileDiff-IWqCJNXu.js";import{P as Ht}from"./PierreDiffViewer-BeGpdI0x.js";import{v as Ut,g as Vt}from"./contextFileOpenGuard-DkjmJ-NU.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-zustand-CUi8eEds.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./runtimeSurface-DBiUWYK2.js";import"./nativeFileSave-BzhtrDoD.js";import"./web-components-CdMfsnXE.js";import"./computeVirtualFileMetrics-CyhUKEfv.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-yJ9XpNMI.js";import"./vendor-pierre-theming-Dgp7B_O4.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./renderDiffWithHighlighter-ByZtK9za.js";import"./vendor-diff-C3JhlQdm.js";import"./runtimeEndpointReset-BqqXMwE9.js";import"./SessionUnreadDot-Czfvjbdi.js";/* empty css */import"./permissionStore-B9Hkrqny.js";import"./appThemeRegistry-gegrE2dq.js";import"./registerCustomTheme-DmolaWWZ.js";function Kt(t,s=10){const e=[];let i;for(const l of t.split(`
2
- `)){const p=l.match(vt);if(p!=null){i!=null&&(i.hunkLines.length>0&&(Re(i,s,"trailing"),Ie(i,e)),i=void 0);const u=parseInt(p[3]),b=parseInt(p[1]),g=parseInt(p[4]??"1"),c=parseInt(p[2]??"1");isNaN(u)||isNaN(b)||isNaN(g)||isNaN(c)?e.push(l):i={additionStart:u,deletionStart:b,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(i==null){e.push(l);continue}if(l.startsWith(" "))i.contextLines.push(l);else if(l!==""){if(i.hunkLines.length>0&&i.contextLines.length>s*2){const u=i.contextLines.length-s*2,b=i.contextLines.slice(-s);Re(i,s,"trailing");const{additionCount:g,deletionCount:c}=i;Ie(i,e),i={additionStart:i.additionStart+g+u,deletionStart:i.deletionStart+c+u,deletionCount:0,additionCount:0,contextLines:b,hunkLines:[]}}Re(i,s,i.hunkLines.length===0?"leading":"before-change"),i.hunkLines.push(l),l.startsWith("+")?i.additionCount+=1:l.startsWith("-")&&(i.deletionCount+=1)}}i!=null&&i.hunkLines.length>0&&(Re(i,s,"trailing"),Ie(i,e));const a=e.join(`
3
- `);return t.endsWith(`
4
- `)?`${a}
5
- `:a}function Re(t,s,e){if(e==="leading"&&t.contextLines.length>s){const i=t.contextLines.length-s;t.contextLines.splice(0,i),t.additionStart+=i,t.deletionStart+=i}return e==="trailing"&&t.contextLines.length>s&&(t.contextLines.length=s),t.contextLines.length>0&&(t.hunkLines.push(...t.contextLines),t.additionCount+=t.contextLines.length,t.deletionCount+=t.contextLines.length,t.contextLines.length=0),t}function Ie(t,s){s.push(`@@ -${Ue(t.deletionStart,t.deletionCount)} +${Ue(t.additionStart,t.additionCount)} @@`),s.push(...t.hunkLines)}function Ue(t,s){return s===1?`${t}`:`${t},${s}`}const qt=64,Xt=3,de=new Map,Yt=(t,s,e=Xt)=>{const i=`${t}\0${e}\0${s}`,a=de.get(i);if(a)return de.delete(i),de.set(i,a),a;const l=Qt(s),p=l?Ct(Kt(s,e),{oldFile:{name:t,contents:l.before},newFile:{name:t,contents:l.after}})??Ke(t):Nt(Jt(t,s))[0]?.files[0]??Ke(t);for(de.set(i,p);de.size>qt;){const u=de.keys().next().value;if(!u)break;de.delete(u)}return p},Jt=(t,s)=>!s.trim()||s.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(s)?s:`Index: ${t}
6
- ===================================================================
7
- --- ${t}
8
- +++ ${t}
9
- ${s}`,Qt=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(t))return;const s=[...t.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(s.length!==1)return;const e=s[0],i=Number.parseInt(e[1]??"",10),a=Number.parseInt(e[2]??"",10);if(i>1||a>1||!Number.isFinite(i)||!Number.isFinite(a))return;const l=(e.index??0)+e[0].length,p=t.slice(l),u=[],b=[];let g;for(const c of p.split(/\r?\n/)){if(c.startsWith("diff --git ")||c.startsWith("@@ "))break;if(c.startsWith("\\")){if(g==="-"||g===" "){const h=u.at(-1);h&&(h.newline=!1)}if(g==="+"||g===" "){const h=b.at(-1);h&&(h.newline=!1)}continue}if(c.startsWith("-")){u.push({text:c.slice(1),newline:!0}),g="-";continue}if(c.startsWith("+")){b.push({text:c.slice(1),newline:!0}),g="+";continue}c.startsWith(" ")&&(u.push({text:c.slice(1),newline:!0}),b.push({text:c.slice(1),newline:!0}),g=" ")}return{before:Ve(u),after:Ve(b)}},Ve=t=>t.map(s=>s.text+(s.newline?`
10
- `:"")).join(""),Ke=t=>Gt({name:t,contents:""},{name:t,contents:""}),Zt=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),Pe=(t,s,e)=>Zt(s)?{original:"",modified:"",isBinary:!0,patch:s,contextMode:e}:{original:"",modified:"",patch:s,fileDiff:Yt(t,s),contextMode:e},ot=(t,s,e)=>{const i=t??0,a=s??0;return!i&&!a?null:n.jsxs("span",{className:se("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",e?.className),children:[i?n.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i]}):null,a?n.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a]}):null]})},en=r.memo(function({changedFiles:s,selectedFile:e,onSelectFile:i}){return s.length===0?null:n.jsx(et,{outerClassName:"flex-1 min-h-0",className:"px-1 py-2",children:n.jsx("ul",{className:"flex flex-col gap-1",children:s.map(a=>{const l=rt(a),p=e===a.path;return n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:()=>i(a.path),className:se("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",p?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[n.jsx(tt,{filePath:a.path,className:"h-3.5 w-3.5 flex-shrink-0"}),n.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:l.color},title:l.description,"aria-label":l.description,children:l.code}),n.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:a.path,children:a.path}),ot(a.insertions,a.deletions)]})},a.path)})})})}),tn=r.memo(function(){return n.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:n.jsx("div",{className:"typography-meta text-muted-foreground",children:"Content of this file cannot be viewed."})})}),nn=r.memo(function({filePath:s,diff:e,renderSideBySide:i}){const a=e.original.length>0,l=e.modified.length>0,p=i?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",u=i?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return n.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:n.jsxs("div",{className:p,children:[a&&n.jsxs("div",{className:u,children:[n.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),n.jsx("img",{src:e.original,alt:`Original: ${s}`,className:i?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),l&&n.jsxs("div",{className:u,children:[n.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a?"Modified":"New"}),n.jsx("img",{src:e.modified,alt:`Modified: ${s}`,className:i?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),sn=r.memo(function({filePath:s,diff:e,renderSideBySide:i,wrapLines:a}){const l=r.useMemo(()=>jt(s)||"text",[s]);return e.isBinary?n.jsx(tn,{}):je(s)?n.jsx(nn,{filePath:s,diff:e,renderSideBySide:i}):n.jsx("div",{className:"w-full",style:{contain:"layout"},children:n.jsx(Ht,{original:e.original,modified:e.modified,fileDiff:e.fileDiff,language:l,fileName:s,renderSideBySide:i,wrapLines:a,layout:"inline"})})}),$e=({label:t,icon:s,loading:e,disabled:i,tone:a,onClick:l})=>n.jsx(Le,{variant:"ghost",size:"sm",className:se("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",a==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",a==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]"),disabled:i,title:t,"aria-label":t,onClick:p=>{p.stopPropagation(),l()},children:e?n.jsx(J,{name:"loader-4",className:"size-3.5 animate-spin"}):n.jsx(J,{name:s,className:s==="add"?"size-4":"size-3.5"})}),rn=r.memo(function({filePath:s,staged:e,busyAction:i,disabled:a,onAction:l}){return n.jsx("div",{className:"flex items-center gap-0.5 rounded-full border border-[var(--interactive-border)]/45 bg-[var(--surface-background)]/95 px-1 py-0.5 shadow-sm backdrop-blur-md",children:e?n.jsx($e,{label:`Unstage ${s}`,icon:"arrow-go-back",loading:i==="unstage",disabled:a,onClick:()=>l("unstage")}):n.jsxs(n.Fragment,{children:[n.jsx($e,{label:`Revert changes in ${s}`,icon:"arrow-go-back",loading:i==="discard",disabled:a,tone:"failure",onClick:()=>l("discard")}),n.jsx($e,{label:`Stage ${s}`,icon:"add",loading:i==="stage",disabled:a,tone:"success",onClick:()=>l("stage")})]})})}),at=3,on=1e6,an=15e3,qe=500,ln=r.memo(function({directory:s,file:e,layout:i,wrapLines:a,isSelected:l,isExpanded:p,isMounted:u,onSelect:b,onExpandedChange:g,registerSectionRef:c,showOpenInEditorAction:h=!1,isOpeningInEditor:w=!1,onOpenInEditor:k,staged:x=!1,showFileActions:C=!0,loadFullFiles:m=!1,initialDiffData:d=null}){const{git:_}=nt(),W=oe(r.useCallback(f=>f.directories.get(s)?.diffCache.get(e.path)??null,[s,e.path])),$=oe(f=>f.setDiff),N=oe(f=>f.fetchStatus),H=Q(f=>f.setDiffFileLayout),[F,y]=r.useState(0),[j,R]=r.useState(null),[A,M]=r.useState(!1),[L,B]=r.useState(null),[U,Z]=r.useState(!1),[ie,fe]=r.useState(null),[E,I]=r.useState(null),V=r.useRef(null),pe=r.useRef(null),O=r.useMemo(()=>rt(e),[e]),ae=i==="side-by-side",Y=m?"full":"patch",q=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,X=r.useMemo(()=>d||(x?E:ie||(W?{original:W.original,modified:W.modified,isBinary:W.isBinary,contextMode:"full"}:null)),[W,d,ie,x,E]),he=X?.contextMode===Y,ve=r.useCallback(f=>{pe.current=f,c(e.path,f)},[e.path,c]),re=r.useCallback(f=>{g(e.path,f)},[e.path,g]),me=r.useCallback(()=>{b(e.path)},[e.path,b]);r.useEffect(()=>{x?I(null):fe(null),R(null),V.current=null},[q,x]),r.useEffect(()=>{if(!p||!u)return;if(!s||d||X&&he){V.current=null,M(!1);return}const f=`${s}::${e.path}::${x?"staged":"unstaged"}::${q}::${Y}::${F}`;if(V.current===f)return;V.current=f,R(null),M(!0);let P=!1;const ee=Ze(),xe=m?on:at,ce=je(e.path)?_.getGitFileDiff(s,{path:e.path,staged:x}):_.getGitDiff(s,{path:e.path,staged:x,contextLines:xe}),te=an,be=new Promise((K,z)=>{setTimeout(()=>z(new Error(`Timed out after ${te}ms`)),te)});return Promise.race([ce,be]).then(K=>{if(!P){if("diff"in K){const z=Pe(e.path,K.diff,Y);x?I(z):fe(z)}else{const z={original:K.original??"",modified:K.modified??"",isBinary:K.isBinary,contextMode:"full"};x?I(z):$(s,e.path,z,ee)}M(!1)}}).catch(K=>{if(P)return;const z=K instanceof Error?K.message:String(K);R(z),M(!1)}),()=>{P=!0,V.current===f&&(V.current=null)}},[Y,X,he,F,s,e.path,q,_,d,p,u,m,$,x]);const ge=r.useCallback(()=>{re(!p),me()},[re,me,p]),le=r.useCallback(async f=>{if(!(!s||L!==null)){B(f);try{f==="stage"?await _.stageGitFile(s,e.path):f==="unstage"?await _.unstageGitFile(s,e.path):await _.revertGitFile(s,e.path,{scope:"working"}),y(P=>P+1),await N(s,_)}catch(P){const ee=f==="unstage"?"Failed to unstage changes":f==="stage"?"Failed to stage changes":"Failed to revert changes";st.error(P instanceof Error?P.message:ee)}finally{B(P=>P===f?null:P)}}},[s,N,e.path,L,_]);return n.jsxs("div",{ref:ve,className:se("scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0"),children:[n.jsx("div",{className:se("z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80","sticky top-0"),children:n.jsxs("div",{role:"button",tabIndex:0,onClick:ge,onKeyDown:f=>{f.target===f.currentTarget&&(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),ge())},className:se("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",l?"bg-[var(--interactive-selection)]/35":null),children:[n.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),n.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[n.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:p?n.jsx(J,{name:"arrow-down-s",className:"size-4"}):n.jsx(J,{name:"arrow-right-s",className:"size-4"})}),n.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:O.color},title:O.description,"aria-label":O.description,children:O.code}),n.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:e.path,children:n.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[n.jsx(tt,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const f=e.path.lastIndexOf("/");if(f===-1)return n.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:e.path});const P=e.path.slice(0,f),ee=e.path.slice(f+1);return n.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[n.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:P}),n.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[n.jsx("span",{className:"text-muted-foreground",children:"/"}),n.jsx("span",{className:"text-foreground",children:ee})]})]})})()]})})]}),n.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[ot(e.insertions,e.deletions),h&&k?n.jsx(Le,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:"Open this file in editor at change",onClick:f=>{f.stopPropagation(),k(e.path,X)},disabled:w,children:w?n.jsx(J,{name:"loader-4",className:"size-3.5 animate-spin"}):n.jsx(J,{name:"edit",className:"size-3.5"})}):null,n.jsx(it,{mode:ae?"side-by-side":"unified",onModeChange:f=>{const P=f==="side-by-side"?"side-by-side":"inline";H(e.path,P)},className:"opacity-70"})]})]})}),p&&n.jsxs("div",{className:"relative overflow-hidden bg-background",children:[!u&&!j?n.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,j?n.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[n.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),n.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:j}),n.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>y(f=>f+1),children:"Retry"})]}):null,u&&A&&!X&&!j?n.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[n.jsx(J,{name:"loader-4",className:"size-4 animate-spin"}),"Loading diff..."]}):null,u&&X&&!U&&e.insertions+e.deletions>qe?n.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[n.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:`Large diff (${e.insertions+e.deletions} changed lines)`}),n.jsx("div",{className:"typography-meta text-muted-foreground",children:"Rendering may be slow. You can still view the diff by clicking below."}),n.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>Z(!0),children:"Render anyway"})]}):null,u&&X&&(U||e.insertions+e.deletions<=qe)?n.jsxs(n.Fragment,{children:[n.jsx(sn,{filePath:e.path,diff:X,renderSideBySide:ae,wrapLines:a}),C?n.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:n.jsx("div",{className:"pointer-events-auto",children:n.jsx(rn,{filePath:e.path,staged:x,busyAction:L,disabled:L!==null,onAction:le})})}):null]}):null]})]})}),cn=1100,Xe=300,un=t=>t<=6?t:t<=12?6:t<=25?4:2,dn=(t,s)=>Lt(t,s),Ye=(t,s)=>{const e=t.split(`
11
- `),i=s.split(`
12
- `),a=Math.min(e.length,i.length);for(let l=0;l<a;l+=1)if(e[l]!==i[l])return l+1;return i.length>e.length?e.length+1:e.length>i.length?Math.max(1,i.length):1},fn=t=>Array.isArray(t)?t.filter(s=>!s||typeof s!="object"?!1:typeof s.file=="string"):[],pn=t=>t.split(/^diff --git /m).slice(1).flatMap(e=>{const[i=""]=e.split(`
13
- `,1),a=i.lastIndexOf(" b/");if(a<=2)return[];const l=i.slice(2,a),p=i.slice(a+3).trim(),u=`diff --git ${e}`,b=u.includes(`
14
- new file mode `)?"added":u.includes(`
15
- deleted file mode `)?"deleted":u.includes(`
16
- rename from `)?"renamed":"modified";let g=0,c=0;for(const h of u.split(`
17
- `))h.startsWith("+")&&!h.startsWith("+++")&&(g+=1),h.startsWith("-")&&!h.startsWith("---")&&(c+=1);return[{file:b==="deleted"?l:p,status:b,additions:g,deletions:c,patch:u}]}),hn=t=>t==="added"?"A":t==="deleted"?"D":"M";function mn({activeDiffScope:t,effectiveDirectory:s,branchBase:e,branchHead:i,git:a,sessionMessageRecords:l}){const[p,u]=r.useState([]),[b,g]=r.useState(null),[c,h]=r.useState(!1),w=r.useMemo(()=>{const C=Dt(l,{showTextJustificationActivity:!1,mergeHiddenUserTurns:!0});for(let m=C.turns.length-1;m>=0;m-=1){const d=C.turns[m];if(!d)continue;const _=d.activityParts.map(N=>N.part).filter(N=>N.type==="tool"),W=kt(_);if(W.length>0)return W.map(N=>({file:N.path,status:"modified",additions:N.additions,deletions:N.deletions,patch:N.patch}));const $=fn(d.userMessage.info?.summary?.diffs);if($.length>0)return $}return[]},[l]);r.useEffect(()=>{if(t!=="branch"||!s||!e||!i||!a.getGitRangeDiff){u([]),g(null),h(!1);return}let C=!1;return h(!0),g(null),a.getGitRangeDiff(s,{base:e,head:i,contextLines:at}).then(m=>{C||(u(pn(m.diff??"")),h(!1))}).catch(m=>{C||(u([]),h(!1),g(m instanceof Error?m.message:String(m)))}),()=>{C=!0}},[t,e,i,s,a]);const k=r.useMemo(()=>{const C=new Map;for(const m of w)if(m.file){if(typeof m.patch=="string"){C.set(m.file,Pe(m.file,m.patch,"patch"));continue}typeof m.before!="string"&&typeof m.after!="string"||C.set(m.file,{original:m.before??"",modified:m.after??"",contextMode:"full"})}return C},[w]),x=r.useMemo(()=>{const C=new Map;for(const m of p)!m.file||typeof m.patch!="string"||C.set(m.file,Pe(m.file,m.patch,"patch"));return C},[p]);return{branchDiffs:p,branchDiffError:b,branchDiffLoading:c,lastTurnDiffs:w,lastTurnDiffData:k,branchDiffData:x}}const Je=(t,s)=>{if(s.length===0)return null;let e=null,i=null;for(const l of s)l.top<=t?(!e||l.top>e.top)&&(e=l):(!i||l.top<i.top)&&(i=l);const a=e??i;return a?{path:a.path,topOffset:a.top-t}:null},gn=(t,s,e,i)=>Math.min(Math.max(0,i),Math.max(0,t+e-s));function xn({pinSelectedFileHeaderToTopOnNavigate:t,scrollRequestNonce:s,changedFiles:e,expandedFiles:i,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const p=r.useRef(null),u=r.useRef(new Map),[b,g]=r.useState(null),c=r.useRef(null),h=r.useRef(null),w=r.useRef(!1),k=r.useRef(null),x=r.useRef(i),C=r.useRef(null);r.useLayoutEffect(()=>{x.current=i},[i]);const m=r.useRef(null),d=r.useCallback(()=>{const F=p.current;if(!F)return null;const y=F.getBoundingClientRect().top,j=[];for(const[R,A]of u.current)A&&j.push({path:R,top:A.getBoundingClientRect().top});return Je(y,j)},[]),_=r.useCallback(()=>{c.current=null,w.current=!1,g(null),h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null)},[]),W=r.useCallback(()=>{k.current=null;const F=p.current;if(!F)return;const y=F.getBoundingClientRect(),j=y.top-Xe,R=y.bottom+Xe,A={},M=[];for(const[L,B]of u.current){if(!B)continue;const U=B.getBoundingClientRect();M.push({path:L,top:U.top}),x.current.has(L)&&(U.bottom<j||U.top>R||(A[L]=!0))}C.current=Je(y.top,M),a(L=>{let B=!1;const U=new Set(L);for(const Z of Object.keys(A))U.has(Z)||(U.add(Z),B=!0);return B?U:L})},[a]),$=r.useCallback(()=>{typeof window>"u"||k.current===null&&(k.current=window.requestAnimationFrame(W))},[W]);r.useEffect(()=>{const F=p.current;if(F)return $(),F.addEventListener("scroll",$,{passive:!0}),window.addEventListener("resize",$),()=>{F.removeEventListener("scroll",$),window.removeEventListener("resize",$),k.current!==null&&(window.cancelAnimationFrame(k.current),k.current=null)}},[e,i,$]),r.useLayoutEffect(()=>{const F=m.current;if(!F)return;m.current=null;const y=p.current,j=u.current.get(F.path);if(!y||!j)return;const R=y.getBoundingClientRect().top,A=j.getBoundingClientRect().top-R;y.scrollTop=gn(y.scrollTop,F.topOffset,A,y.scrollHeight-y.clientHeight),C.current=F},[l]);const N=r.useCallback((F,y)=>{const j=u.current;y?j.set(F,y):j.delete(F),$()},[$]),H=r.useCallback(F=>{const y=u.current.get(F),j=p.current;if(!y||!j)return!1;const R=y.getBoundingClientRect().top-j.getBoundingClientRect().top;return j.scrollTo({top:j.scrollTop+R,behavior:"auto"}),!0},[]);return r.useEffect(()=>{if(!c.current)return;let y=0;const j=20;let R=!1;const A=(L=!0)=>{R||(R=!0,c.current=null,w.current=!1,L&&g(null),h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null))},M=()=>{if(R){h.current=null;return}const L=c.current;if(!L){A(),h.current=null;return}if(!H(L)){y+=1,y<j?h.current=window.requestAnimationFrame(M):(A(),h.current=null);return}if(t&&w.current){g(L),A(!1);return}A()};return h.current=window.requestAnimationFrame(M),()=>{R=!0,h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null)}},[t,s,H]),{diffScrollRef:p,fileSectionRefs:u,pinnedStackedTarget:b,pendingScrollTargetRef:c,shouldPinAfterAlignRef:w,pendingScrollAnchorRestoreRef:m,lastScrollAnchorRef:C,captureScrollAnchor:d,cancelPendingScrollAlignment:_,queueVisibleStackedFilesSync:$,registerSectionRef:N,scrollToFile:H}}const Qe=t=>{if(!t)return null;const s=t.split(`
18
- `);let e=null;for(const i of s){const a=i.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(a){const l=Number.parseInt(a[1]??"",10);e=Number.isFinite(l)&&l>=1?l:null;continue}if(e!==null){if(i.startsWith(" ")){e+=1;continue}if(i.startsWith("+"))return e;if(i.startsWith("-"))return Math.max(1,e)}}return null};function bn({effectiveDirectory:t,activeDiffStaged:s,git:e,files:i,setDiff:a,openContextFileAtLine:l}){const[p,u]=r.useState(null),b=r.useCallback(async(g,c)=>{if(!t||!g)return;u(g);const h=Ze();try{let w=null;if(c?.patch&&!c.isBinary&&!je(g)?w=Qe(c.patch):c&&c.contextMode==="full"&&!c.isBinary&&!je(g)&&(w=Ye(c.original,c.modified)),w===null)try{const d=await e.getGitDiff(t,{path:g,staged:s,contextLines:3});w=Qe(d.diff)}catch{w=null}let k=c;if(w===null||!k){const d=await e.getGitFileDiff(t,{path:g,staged:s});k={original:d.original??"",modified:d.modified??"",isBinary:d.isBinary},s||a(t,g,k,h??void 0)}const x=w??(k.isBinary||je(g)?1:Ye(k.original,k.modified)),C=dn(t,g),m=await Ut(i,C,{directory:t});if(!m.ok){st.error(Vt(m.reason));return}l(t,C,x,1)}finally{u(w=>w===g?null:w)}},[s,t,i,e,l,a]);return{openingEditorFilePath:p,openFileInEditorAtChange:b}}function yn(t){const{hideStackedFileSidebar:s=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:i=!1,diffScope:a="all",branchBase:l=null,branchHead:p=null,targetFilePath:u=null}=t,{git:b,files:g}=nt(),c=Rt(),{screenWidth:h,isMobile:w}=Et(),k=At(c??null),x=Tt(c??null),C=Mt(c??null),m=oe(o=>o.setActiveDirectory),d=oe(o=>o.ensureStatus),_=oe(o=>o.fetchStatus),W=oe(o=>o.clearDiffCache),$=oe(o=>o.setDiff),[N,H]=r.useState(null),[F,y]=r.useState(!1),[j,R]=r.useState(()=>new Set),[A,M]=r.useState(()=>new Set),[L,B]=r.useState(!1),[U,Z]=r.useState(0),[ie,fe]=r.useState(()=>new Map),[E,I]=r.useState(a);r.useEffect(()=>{I(a)},[a]);const V=Q(o=>o.pendingDiffFile),pe=Q(o=>o.pendingDiffStaged),O=Q(o=>o.pendingDiffScope),ae=Q(o=>o.setPendingDiffFile),Y=Q(o=>o.diffLayoutPreference),q=Q(o=>o.diffFileLayout),X=Q(o=>o.setDiffFileLayout),he=Q(o=>o.diffWrapLines),ve=Q(o=>o.setDiffWrapLines),re=Q(o=>o.openContextFileAtLine),me=It(o=>o.currentSessionId),ge=$t(me??""),le=he,f=E==="staged"?!0:E==="working"?!1:null,P=f??F,ee=w||h<=768,xe=!s&&!ee&&h>=1024,ce=r.useRef(null),{branchDiffs:te,branchDiffError:be,branchDiffLoading:K,lastTurnDiffs:z,lastTurnDiffData:De,branchDiffData:ne}=mn({activeDiffScope:E,effectiveDirectory:c,branchBase:l,branchHead:p,git:b,sessionMessageRecords:ge}),D=r.useMemo(()=>{if(E==="turn"||E==="branch")return(E==="branch"?te:z).map(T=>({path:T.file??"",index:"",working_dir:hn(T.status),insertions:T.additions??0,deletions:T.deletions??0,isNew:T.status==="added"})).filter(T=>T.path).sort((T,G)=>T.path.localeCompare(G.path));if(!x?.files)return[];const o=x.diffStats??{},v=E==="staged"?Ge:E==="working"?He:()=>!0;return x.files.filter(v).map(S=>({...S,insertions:o[S.path]?.insertions??0,deletions:o[S.path]?.deletions??0,isNew:Ot(S)})).sort((S,T)=>S.path.localeCompare(T.path))},[E,te,z,x]),Ee=r.useMemo(()=>x?.files?x.files.filter(He).length:0,[x]),Ae=r.useMemo(()=>x?.files?x.files.filter(Ge).length:0,[x]),lt=z.length,ct=x?.files?.length??0,ut=te.length,{diffScrollRef:dt,pinnedStackedTarget:ft,pendingScrollTargetRef:ye,shouldPinAfterAlignRef:we,pendingScrollAnchorRestoreRef:_e,lastScrollAnchorRef:We,captureScrollAnchor:Be,cancelPendingScrollAlignment:Fe,queueVisibleStackedFilesSync:ke,registerSectionRef:pt,scrollToFile:Oe}=xn({pinSelectedFileHeaderToTopOnNavigate:i,scrollRequestNonce:U,changedFiles:D,expandedFiles:j,setMountedStackedFiles:M,fileDiffRefreshNonce:ie}),Se=r.useCallback(o=>{R(v=>{if(v.has(o))return v;const S=new Set(v);return S.add(o),S})},[]),Te=r.useMemo(()=>D.map(o=>o.path).join("\0"),[D]);r.useEffect(()=>{const o=Te?Te.split("\0"):[],v=new Set(o),S=`${c??""}:${E}:${e?"collapsed":"default"}`,T=ce.current!==S;ce.current=S,R(G=>{if(T){const ue=e?0:un(o.length);return new Set(o.slice(0,ue))}let Ce=!1;const Ne=new Set;for(const ue of G){if(!v.has(ue)){Ce=!0;continue}Ne.add(ue)}return Ce?Ne:G}),M(G=>{if(T)return new Set;let Ce=!1;const Ne=new Set;for(const ue of G){if(!v.has(ue)){Ce=!0;continue}Ne.add(ue)}return Ce?Ne:G})},[E,Te,c,M,e]);const Me=r.useCallback(o=>{const v=q[o.path];if(v)return v;if(Y==="inline")return"inline";if(Y==="side-by-side")return"side-by-side";const S=h<cn;return o.isNew||S?"inline":"side-by-side"},[q,Y,h]),ht=r.useMemo(()=>D.length===0?null:D.every(o=>Me(o)==="side-by-side")?"side-by-side":"inline",[D,Me]);r.useEffect(()=>{c&&(m(c),d(c,b))},[c,m,d,b]),r.useEffect(()=>{if(c)return Pt.onGitRefreshHint(o=>{ze(o.directory)===ze(c)&&(o.paths?.length&&(_e.current=Be()??We.current,W(c,o.paths),fe(v=>{const S=new Map(v);for(const T of o.paths??[])S.set(T,(S.get(T)??0)+1);return S})),_(c,b,{silent:!0}))})},[Be,W,c,_,b,We,_e]),r.useEffect(()=>{E!=="all"&&!O||V&&(O&&I(O),H(V),y(O==="staged"||!O&&pe),ae(null),we.current=!0,ye.current=V,Se(V),Z(o=>o+1))},[E,Se,V,O,pe,ye,ae,we]),r.useEffect(()=>{if(E==="all")return;const o=u?.trim();o&&(H(o),y(E==="staged"),we.current=!0,ye.current=o,Se(o),Z(v=>v+1))},[E,Se,ye,we,u]),r.useEffect(()=>{if(!N)return;D.some(v=>v.path===N)||(H(null),y(!1))},[D,N]);const mt=r.useCallback((o,v)=>{Fe(),R(S=>{const T=S.has(o);if(v===T)return S;const G=new Set(S);return v?G.add(o):G.delete(o),G}),M(S=>{const T=S.has(o);if(v===T)return S;const G=new Set(S);return v?G.add(o):G.delete(o),G}),ke()},[Fe,ke,M]),gt=r.useCallback(()=>{Fe(),R(o=>o.size>0?new Set:new Set(D.map(v=>v.path))),M(new Set),ke()},[Fe,D,ke,M]),xt=r.useCallback(o=>{},[]),bt=r.useCallback(o=>{Fe(),H(o),y(!1),we.current=!0,ye.current=o,Se(o),Z(v=>v+1),Oe(o)},[Fe,Se,ye,Oe,we]),yt=r.useCallback(o=>{const v=o==="side-by-side"?"side-by-side":"inline";D.forEach(S=>{X(S.path,v)})},[D,X]),{openingEditorFilePath:wt,openFileInEditorAtChange:Ft}=bn({effectiveDirectory:c,activeDiffStaged:P,git:b,files:g,setDiff:$,openContextFileAtLine:re});return{git:b,files:g,effectiveDirectory:c,screenWidth:h,isMobile:w,isGitRepo:k,status:x,isLoadingStatus:C,activeDiffScope:E,setActiveDiffScope:I,branchDiffs:te,branchDiffError:be,branchDiffLoading:K,diffWrapLines:le,setDiffWrapLines:ve,forcedStaged:f,displayFileStaged:F,displayFile:N,pinnedStackedTarget:ft,expandedFiles:j,mountedStackedFiles:A,loadFullFiles:L,setLoadFullFiles:B,fileDiffRefreshNonce:ie,showFileSidebar:xe,diffScrollRef:dt,lastTurnDiffData:De,branchDiffData:ne,changedFiles:D,workingFileCount:Ee,stagedFileCount:Ae,turnFileCount:lt,allFileCount:ct,branchFileCount:ut,currentLayoutForAllFiles:ht,openingEditorFilePath:wt,registerSectionRef:pt,handleStackedEntryExpandedChange:mt,handleExpandOrCollapseAll:gt,handleSelectFile:xt,handleSelectFileAndScroll:bt,handleHeaderLayoutChange:yt,openFileInEditorAtChange:Ft,getLayoutForFile:Me}}const gs=({hideStackedFileSidebar:t=!1,stackedDefaultCollapsedAll:s=!1,pinSelectedFileHeaderToTopOnNavigate:e=!1,showOpenInEditorAction:i=!1,diffScope:a="all",onDiffScopeChange:l,branchBase:p=null,branchHead:u=null,targetFilePath:b=null,flushContent:g=!1,hideToolbar:c=!1,onHeaderControlsStateChange:h,toolbarSlot:w=null})=>{const{effectiveDirectory:k,isGitRepo:x,status:C,isLoadingStatus:m,activeDiffScope:d,setActiveDiffScope:_,branchDiffError:W,branchDiffLoading:$,diffWrapLines:N,setDiffWrapLines:H,forcedStaged:F,displayFileStaged:y,displayFile:j,pinnedStackedTarget:R,expandedFiles:A,mountedStackedFiles:M,loadFullFiles:L,setLoadFullFiles:B,fileDiffRefreshNonce:U,showFileSidebar:Z,diffScrollRef:ie,lastTurnDiffData:fe,branchDiffData:E,changedFiles:I,workingFileCount:V,stagedFileCount:pe,turnFileCount:O,allFileCount:ae,branchFileCount:Y,currentLayoutForAllFiles:q,openingEditorFilePath:X,registerSectionRef:he,handleStackedEntryExpandedChange:ve,handleExpandOrCollapseAll:re,handleSelectFile:me,handleSelectFileAndScroll:ge,handleHeaderLayoutChange:le,openFileInEditorAtChange:f,getLayoutForFile:P}=yn({hideStackedFileSidebar:t,stackedDefaultCollapsedAll:s,pinSelectedFileHeaderToTopOnNavigate:e,diffScope:a,branchBase:p,branchHead:u,targetFilePath:b});r.useEffect(()=>{c&&l?.(d)},[d,c,l]);const ee=r.useCallback(()=>{B(ne=>!ne)},[B]),xe=r.useCallback(()=>{H(!N)},[N,H]),ce=r.useCallback(()=>{le(q==="side-by-side"?"unified":"side-by-side")},[q,le]),te=A.size,be=r.useMemo(()=>({turnCount:O,branchCount:Y,expandedCount:te,totalCount:I.length,loadFullFiles:L,wrapLines:N,layoutMode:q,onExpandOrCollapseAll:re,onToggleLoadFullFiles:ee,onToggleWrapLines:xe,onToggleLayout:ce}),[O,Y,te,I.length,L,N,q,re,ee,xe,ce]);r.useEffect(()=>{c&&h?.(be)},[c,be,h]);const K=()=>{if(!k)return null;const ne=D=>F!==null?F:y&&D===j;return n.jsxs("div",{className:se("flex min-w-0 flex-1 min-h-0 h-full",g?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[Z&&n.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[n.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:I.length})]}),n.jsx(en,{changedFiles:I,selectedFile:null,onSelectFile:ge})]}),n.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:n.jsx(et,{ref:ie,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:n.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:I.map(D=>n.jsx(ln,{directory:k,file:D,layout:P(D),wrapLines:N,isSelected:!1,isExpanded:A.has(D.path),isMounted:M.has(D.path)||D.path===R,onSelect:me,onExpandedChange:ve,registerSectionRef:he,showOpenInEditorAction:i&&d!=="turn"&&d!=="branch",isOpeningInEditor:X===D.path,onOpenInEditor:(Ee,Ae)=>{f(Ee,Ae)},staged:ne(D.path),showFileActions:d!=="turn"&&d!=="branch",loadFullFiles:L,initialDiffData:d==="turn"?fe.get(D.path)??null:d==="branch"?E.get(D.path)??null:null},`${D.path}:${U.get(D.path)??0}`))})})})]})},z=()=>k?d!=="turn"&&m&&!C?n.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[n.jsx(J,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):d!=="turn"&&d!=="branch"&&x===!1?n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):d==="branch"&&$?n.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[n.jsx(J,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):d==="branch"&&W?n.jsx("div",{className:"flex flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground",children:`Failed to load branch changes: ${W}`}):I.length===0?n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:d==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):K():n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"}),De=n.jsxs("div",{className:w?"flex min-w-0 flex-1 items-center gap-1.5":"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(x!==!1||d==="turn")&&(d==="all"||d==="working"||d==="staged"||d==="turn"||d==="branch")?n.jsx(zt,{scope:d,isGitRepo:x,branchAvailable:!!(p&&u),allCount:ae,workingCount:V,stagedCount:pe,turnCount:O,branchCount:Y,onScopeChange:ne=>{_(ne),l?.(ne)}}):n.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:n.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:m&&!C?"Loading changes...":I.length===1?`${I.length} file changed`:`${I.length} files changed`})}),I.length>0&&n.jsxs(Le,{variant:"ghost",size:"sm",onClick:re,className:se("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:A.size>0?"Collapse all":"Expand all",children:[n.jsx(J,{name:"expand-up-down",className:"size-4"}),n.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:A.size>0?"Collapse all":"Expand all"})]}),I.length>0&&d!=="turn"&&d!=="branch"&&n.jsxs(_t,{children:[n.jsx(Wt,{asChild:!0,children:n.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>B(ne=>!ne),"aria-pressed":L,"aria-label":L?"Unload full files":"Load full files",className:se("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",L&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(J,{name:"file-download",className:"size-4"})})}),n.jsx(Bt,{children:n.jsx("p",{children:L?"Unload full files":"Load full files"})})]}),I.length>0&&n.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>H(!N),className:se("h-5 w-5 p-0 transition-opacity",N?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:N?"Disable line wrap":"Enable line wrap",children:n.jsx(J,{name:"text-wrap",className:"size-4"})}),q&&n.jsx(it,{mode:q==="side-by-side"?"side-by-side":"unified",onModeChange:le})]});return n.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[w?St.createPortal(De,w):c?null:De,z()]})};export{gs as DiffView};