@pi-chamber/web 0.7.1 → 0.8.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 (190) hide show
  1. package/README.md +2 -1
  2. package/bin/cli.js +2 -2
  3. package/bin/cli.test.js +98 -1
  4. package/bin/lib/DOCUMENTATION.md +2 -1
  5. package/bin/lib/cli-args.js +8 -5
  6. package/bin/lib/cli-startup.js +10 -7
  7. package/bin/lib/cli-startup.test.js +28 -0
  8. package/bin/lib/commands-startup.js +152 -6
  9. package/dist/assets/{DiagramEditor-C7xe1Brl.js → DiagramEditor-YPSKccgo.js} +1 -1
  10. package/dist/assets/DiagramView-C-PbBHce.js +1 -0
  11. package/dist/assets/DiffView-DfltyfN2.js +18 -0
  12. package/dist/assets/FilesView-BEjbLiK2.js +6 -0
  13. package/dist/assets/GitView-B_zTaXX4.js +8 -0
  14. package/dist/assets/JsonTreeView-9p4txyB_.js +1 -0
  15. package/dist/assets/MarkdownRendererImpl-CbRPLK2x.js +12 -0
  16. package/dist/assets/PatchDiff-rKjeUBRl.js +1 -0
  17. package/dist/assets/SessionSwitcherContent-C_VxKFJy.js +1 -0
  18. package/dist/assets/SessionSwitcherDropdown-_k4P32o9.js +2 -0
  19. package/dist/assets/SessionUnreadDot-bT_0MixU.js +1 -0
  20. package/dist/assets/SettingsView-CqZ1ZAWG.js +2 -0
  21. package/dist/assets/SettingsWindow-C7vVE35-.js +1 -0
  22. package/dist/assets/ToolOutputDialog-GBbzATa6.js +8 -0
  23. package/dist/assets/ToolPartDiffPreview-Bdb9p5uS.js +1 -0
  24. package/dist/assets/{VirtualizedFileDiff-DFx8xsmh.js → VirtualizedFileDiff-CA8hQyz9.js} +4 -4
  25. package/dist/assets/{Virtualizer-BxW2CJGB.js → Virtualizer-BSHVMKgK.js} +1 -1
  26. package/dist/assets/{appThemeRegistry-BK0dHKa6.js → appThemeRegistry-gegrE2dq.js} +1 -1
  27. package/dist/assets/collapsible-uwSKBy-K.js +1 -0
  28. package/dist/assets/computeVirtualFileMetrics-9LNCLvAG.js +3 -0
  29. package/dist/assets/contextFileOpenGuard-CZSqdEHk.js +1 -0
  30. package/dist/assets/gitStatusPredicates-CRmbLl-x.js +134 -0
  31. package/dist/assets/index-BeJEipxi.js +1 -0
  32. package/dist/assets/index-CaP8oFLB.js +8 -0
  33. package/dist/assets/index-Dq8CnRYM.css +1 -0
  34. package/dist/assets/isDiffPlainText-YYyZNTdb.js +1 -0
  35. package/dist/assets/isFilePlainText-C70Z71bG.js +1 -0
  36. package/dist/assets/main-CsdVAKy_.js +135 -0
  37. package/dist/assets/main-GMQIZjuQ.js +2 -0
  38. package/dist/assets/{markdownCore-CzWR_p3k.js → markdownCore-BgVcDt0q.js} +2 -2
  39. package/dist/assets/miniChat-W6YsdiWR.js +2 -0
  40. package/dist/assets/mobile-BFR9CR5w.js +2 -0
  41. package/dist/assets/{permissionStore-BRcQ9Jgt.js → permissionStore-iKN1K2_x.js} +1 -1
  42. package/dist/assets/registerCustomTheme-DmolaWWZ.js +1 -0
  43. package/dist/assets/renderElectronMiniChatApp-B8ZiW-3E.js +2 -0
  44. package/dist/assets/renderMobileApp-C5CdsYP6.js +11 -0
  45. package/dist/assets/runtimeEndpointReset-D3AZYuoF.js +54 -0
  46. package/dist/assets/{runtimeSurface-OhCUGSKg.js → runtimeSurface-B818u-_c.js} +1 -1
  47. package/dist/assets/themeResolver-yJ9XpNMI.js +1 -0
  48. package/dist/assets/{WindowsWindowControls-DIqnZ2uU.js → useAppFontEffects-CYzYRbLp.js} +126 -499
  49. package/dist/assets/useFilesViewSearch-C--GWtn-.js +7 -0
  50. package/dist/assets/usePushVisibilityBeacon-D9lajdAc.js +10 -0
  51. package/dist/assets/useSwitcherItems-DOoi3x_8.js +1 -0
  52. package/dist/assets/vendor-base-ui-vkqQ2P9o.js +1 -0
  53. package/dist/assets/{vendor-beautiful-mermaid-r4GK_usS.js → vendor-beautiful-mermaid-DneUawHp.js} +1 -1
  54. package/dist/assets/{vendor-cmdk-BCEUzcHE.js → vendor-cmdk-zXx6sGnS.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-autocomplete-BS2SpSAZ.js → vendor-codemirror-autocomplete-wd6iRebq.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-commands-RrgJ8H_6.js → vendor-codemirror-commands-DYppkHEk.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-ADhO_TUK.js → vendor-codemirror-lang-angular-DU_4KiiW.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-cpp-BGCWj7Om.js → vendor-codemirror-lang-cpp-CmIT9Z5_.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-css-Ba8JZ6fp.js → vendor-codemirror-lang-css-djiuoTi8.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-go-DyTiHXo4.js → vendor-codemirror-lang-go-COZSwZYW.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-html-DK27qQri.js → vendor-codemirror-lang-html-CKHqhW5R.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-java-CvFfnhPQ.js → vendor-codemirror-lang-java-CNMP5hyC.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-javascript-BUlYhQ3o.js → vendor-codemirror-lang-javascript-DuOEwJ3f.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-jinja-wBMtAEvT.js → vendor-codemirror-lang-jinja-DaKn_b1k.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-json-CqayksDf.js → vendor-codemirror-lang-json-CZ07HmNC.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-less-Ct3-H1PB.js → vendor-codemirror-lang-less-wJdQiDBf.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-liquid-XspREksq.js → vendor-codemirror-lang-liquid-0z48Roi8.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-markdown-CvO36Y1p.js → vendor-codemirror-lang-markdown-DtcZDGqe.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-php-BlUF9cCe.js → vendor-codemirror-lang-php-W8plS-JQ.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-python-_2bIYTiJ.js → vendor-codemirror-lang-python-DzzokVau.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-rust-BdTYih_U.js → vendor-codemirror-lang-rust-C4ulBVpf.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sass-E6MhfOFk.js → vendor-codemirror-lang-sass-BkZJYEwS.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-sql-B1BRhQSF.js → vendor-codemirror-lang-sql-HpQWHJjv.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-vue-BYQJRa1Q.js → vendor-codemirror-lang-vue-DiBPljCc.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-wast-D706yuyC.js → vendor-codemirror-lang-wast-DoABsogh.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-xml--MfWU6Dj.js → vendor-codemirror-lang-xml-BhLJhOCH.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-yaml-CRUFIbRX.js → vendor-codemirror-lang-yaml-D95i1Y5R.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-language-E2vgV9K3.js → vendor-codemirror-language-BByA_dGF.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-language-data-Dv4zaHRN.js → vendor-codemirror-language-data-DS_4W5G4.js} +2 -2
  80. package/dist/assets/{vendor-codemirror-search-8kyQdB3f.js → vendor-codemirror-search-BV44140v.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-view-DSzLbZiS.js → vendor-codemirror-view-Ct4T37Ue.js} +1 -1
  82. package/dist/assets/{vendor-dnd-kit-accessibility-Cv52zwWT.js → vendor-dnd-kit-accessibility-DZKKhs9S.js} +1 -1
  83. package/dist/assets/{vendor-dnd-kit-core-GipZW2tY.js → vendor-dnd-kit-core-CP8ck10N.js} +1 -1
  84. package/dist/assets/{vendor-dnd-kit-sortable-Ct2QxIHb.js → vendor-dnd-kit-sortable-B-Icjoj4.js} +1 -1
  85. package/dist/assets/{vendor-dnd-kit-utilities-CrOcp0Bp.js → vendor-dnd-kit-utilities-DTY1C6ST.js} +1 -1
  86. package/dist/assets/{vendor-elkjs-CRCLNXjf.js → vendor-elkjs-mzfkf0ML.js} +1 -1
  87. package/dist/assets/{vendor-floating-ui-dom-Bkw82kL9.js → vendor-floating-ui-dom-WyXykhNi.js} +1 -1
  88. package/dist/assets/{vendor-floating-ui-react-dom-sVFnuruh.js → vendor-floating-ui-react-dom-BZOGXAGe.js} +1 -1
  89. package/dist/assets/{vendor-framer-motion-DJASDzNt.js → vendor-framer-motion-BUygY0oN.js} +1 -1
  90. package/dist/assets/{vendor-heic2any-L8hyfc24.js → vendor-heic2any-BHsbokcA.js} +1 -1
  91. package/dist/assets/{vendor-lru_map-B-cPXHXW.js → vendor-lru_map-Cy8fTs3_.js} +1 -1
  92. package/dist/assets/{vendor-pierre-theming-C6Z4M5_u.js → vendor-pierre-theming-Dgp7B_O4.js} +1 -1
  93. package/dist/assets/{vendor-qrcode-COsmt6jn.js → vendor-qrcode-B0KNSajT.js} +1 -1
  94. package/dist/assets/{vendor-radix-ui-react-compose-refs-D1GnwnP9.js → vendor-radix-ui-react-compose-refs-8xy6TJML.js} +1 -1
  95. package/dist/assets/{vendor-radix-ui-react-context-CM4yFQ2I.js → vendor-radix-ui-react-context-CFsX-AUC.js} +1 -1
  96. package/dist/assets/{vendor-radix-ui-react-dialog-jX3Dld8c.js → vendor-radix-ui-react-dialog-D2yhEu2p.js} +1 -1
  97. package/dist/assets/{vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js → vendor-radix-ui-react-dismissable-layer-DrorBNg9.js} +1 -1
  98. package/dist/assets/{vendor-radix-ui-react-focus-guards-D5MZ0nQs.js → vendor-radix-ui-react-focus-guards-BfdFmL7c.js} +1 -1
  99. package/dist/assets/{vendor-radix-ui-react-focus-scope-C2K7lNPv.js → vendor-radix-ui-react-focus-scope-D2BkImwt.js} +1 -1
  100. package/dist/assets/{vendor-radix-ui-react-id-BcxRjnbX.js → vendor-radix-ui-react-id-D2kS9K1j.js} +1 -1
  101. package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +1 -0
  102. package/dist/assets/{vendor-radix-ui-react-presence-Btn-Dp7L.js → vendor-radix-ui-react-presence-D432pCMB.js} +1 -1
  103. package/dist/assets/{vendor-radix-ui-react-primitive-CfpW6_IT.js → vendor-radix-ui-react-primitive-DkH8dMOR.js} +1 -1
  104. package/dist/assets/{vendor-radix-ui-react-slot-BxUc3Pvz.js → vendor-radix-ui-react-slot-BIDFZX0-.js} +1 -1
  105. package/dist/assets/{vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js → vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js} +1 -1
  106. package/dist/assets/{vendor-radix-ui-react-use-controllable-state-C_ecoh35.js → vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js} +1 -1
  107. package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +1 -0
  108. package/dist/assets/{vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js → vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js} +1 -1
  109. package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +1 -0
  110. package/dist/assets/{vendor-react-DYyjh7Q0.js → vendor-react-B5Z1Mdn3.js} +1 -1
  111. package/dist/assets/{vendor-react-drawio-Boqanm0j.js → vendor-react-drawio-BYDptOsj.js} +1 -1
  112. package/dist/assets/{vendor-react-remove-scroll-bar-C9YRs2nU.js → vendor-react-remove-scroll-bar-CSAHp1YF.js} +1 -1
  113. package/dist/assets/{vendor-react-remove-scroll-CfeMe0DL.js → vendor-react-remove-scroll-vR1dy1aP.js} +1 -1
  114. package/dist/assets/{vendor-react-style-singleton-B1H4bWSG.js → vendor-react-style-singleton-Ctw6HnYx.js} +1 -1
  115. package/dist/assets/{vendor-replit-codemirror-vim-BJY5fGLS.js → vendor-replit-codemirror-vim-CGHHNQxC.js} +1 -1
  116. package/dist/assets/{vendor-sonner-CW8w438f.js → vendor-sonner-BDtm25td.js} +1 -1
  117. package/dist/assets/{vendor-tanstack-react-virtual-IrbCBGJ4.js → vendor-tanstack-react-virtual-2skouoFw.js} +1 -1
  118. package/dist/assets/{vendor-use-callback-ref-CJB0R85I.js → vendor-use-callback-ref-CVVuCyLj.js} +1 -1
  119. package/dist/assets/{vendor-use-sidecar-C-AuTczP.js → vendor-use-sidecar-Vv4V8Nd1.js} +1 -1
  120. package/dist/assets/{vendor-use-sync-external-store-B7OScDIw.js → vendor-use-sync-external-store-D0AXkdQC.js} +1 -1
  121. package/dist/assets/{vendor-zustand-CnsBKjP5.js → vendor-zustand-GVb4H8HE.js} +1 -1
  122. package/dist/assets/{web-components-BOt08OHk.js → web-components-C2cMNPqE.js} +2 -2
  123. package/dist/index.html +6 -6
  124. package/dist/mini-chat.html +5 -5
  125. package/dist/mobile.html +5 -5
  126. package/package.json +1 -1
  127. package/server/lib/git/DOCUMENTATION.md +3 -2
  128. package/server/lib/git/routes.js +27 -0
  129. package/server/lib/git/routes.test.js +41 -0
  130. package/server/lib/git/service.js +7 -1
  131. package/server/lib/git/service.test.js +23 -0
  132. package/server/lib/package-manager.js +32 -1
  133. package/server/lib/package-manager.test.js +21 -0
  134. package/server/lib/pi/attachment-store.js +95 -22
  135. package/server/lib/pi/attachment-store.test.js +23 -0
  136. package/server/lib/pi/routes.js +383 -49
  137. package/server/lib/pi/routes.test.js +377 -3
  138. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -3
  139. package/server/lib/pi/session-daemon/prompt-operations.test.js +318 -0
  140. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +2 -0
  141. package/server/lib/pi/session-daemon/session-daemon.js +316 -25
  142. package/server/lib/pi/session-daemon/session-daemon.test.js +137 -0
  143. package/server/lib/pi/session-daemon/supervisor.test.js +1 -1
  144. package/server/lib/pi/snippets-store.js +400 -0
  145. package/server/lib/pi/snippets-store.test.js +252 -0
  146. package/server/lib/relay/host-client.test.js +79 -15
  147. package/server/lib/server/cors.js +2 -0
  148. package/server/lib/server/cors.test.js +6 -5
  149. package/dist/assets/CommitSection-DuGkZ_bm.js +0 -1
  150. package/dist/assets/DiagramView-BTqROEWP.js +0 -1
  151. package/dist/assets/DiffView-hcqXTjEc.js +0 -18
  152. package/dist/assets/FilesView-GadyKxta.js +0 -14
  153. package/dist/assets/GitView-BKy-hYUN.js +0 -6
  154. package/dist/assets/JsonTreeView-CGc4eTGI.js +0 -1
  155. package/dist/assets/MarkdownRendererImpl-CqfEAhPM.js +0 -12
  156. package/dist/assets/PatchDiff-P17-Byb8.js +0 -1
  157. package/dist/assets/PierreDiffViewer-BbUCO4IF.js +0 -136
  158. package/dist/assets/SessionSwitcherContent-j6KFBSe0.js +0 -1
  159. package/dist/assets/SessionSwitcherDropdown-DSVeuuVL.js +0 -2
  160. package/dist/assets/SessionUnreadDot-BVBBEBTg.js +0 -1
  161. package/dist/assets/SettingsView-FnmtcWZc.js +0 -4
  162. package/dist/assets/SettingsWindow-Bascj0V3.js +0 -1
  163. package/dist/assets/ToolOutputDialog-CPMzJ27S.js +0 -15
  164. package/dist/assets/ToolPartDiffPreview-BZSRKHHM.js +0 -8
  165. package/dist/assets/collapsible-DlqZyxEY.js +0 -1
  166. package/dist/assets/computeVirtualFileMetrics-elCbdk6U.js +0 -3
  167. package/dist/assets/contextFileOpenGuard-BmQ7Zu-L.js +0 -1
  168. package/dist/assets/index-BerHSX92.js +0 -1
  169. package/dist/assets/index-ChFxkws4.js +0 -8
  170. package/dist/assets/index-DZ-f_hCQ.css +0 -1
  171. package/dist/assets/isDiffPlainText-CvfRfc7h.js +0 -1
  172. package/dist/assets/isFilePlainText-_vq9Ghu3.js +0 -1
  173. package/dist/assets/main-DTCOwPr3.js +0 -2
  174. package/dist/assets/main-DYs-nZO6.js +0 -133
  175. package/dist/assets/miniChat-C2XxEA3N.js +0 -2
  176. package/dist/assets/mobile-BQhAOqV7.js +0 -2
  177. package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
  178. package/dist/assets/renderElectronMiniChatApp-M2bY1WKA.js +0 -2
  179. package/dist/assets/renderMobileApp-BnpHUUhY.js +0 -14
  180. package/dist/assets/themeResolver-BmJyTmjJ.js +0 -1
  181. package/dist/assets/useInlineCommentController-DC0iNSYX.js +0 -2
  182. package/dist/assets/usePanelSlide-aeAIo1cp.js +0 -56
  183. package/dist/assets/usePushVisibilityBeacon-om5Qlrt6.js +0 -10
  184. package/dist/assets/useSwitcherItems-Bln2r_Q2.js +0 -1
  185. package/dist/assets/vendor-base-ui-DL8r2fgQ.js +0 -1
  186. package/dist/assets/vendor-radix-ui-react-portal-xlJWBfDg.js +0 -1
  187. package/dist/assets/vendor-radix-ui-react-use-effect-event-DkJl_Rn_.js +0 -1
  188. package/dist/assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js +0 -1
  189. package/dist/assets/vendor-remixicon-react-CzPq62YO.js +0 -1
  190. /package/dist/assets/{usePanelSlide-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
@@ -0,0 +1,252 @@
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, describe, expect, it } from "vitest";
5
+
6
+ import { createPiSnippetsStore } from "./snippets-store.js";
7
+
8
+ const directories = [];
9
+
10
+ afterEach(async () => {
11
+ await Promise.all(
12
+ directories
13
+ .splice(0)
14
+ .map((directory) => rm(directory, { recursive: true, force: true })),
15
+ );
16
+ });
17
+
18
+ const makeStore = async () => {
19
+ const directory = await mkdtemp(join(tmpdir(), "pichamber-snippets-"));
20
+ directories.push(directory);
21
+ return createPiSnippetsStore({
22
+ file: join(directory, "pi", "snippets.json"),
23
+ });
24
+ };
25
+
26
+ describe("Pi snippets store", () => {
27
+ it("starts empty and round-trips a global snippet", async () => {
28
+ const store = await makeStore();
29
+ await expect(store.list()).resolves.toEqual([]);
30
+ const snippets = await store.create({
31
+ name: "review",
32
+ content: "Review this",
33
+ scope: "global",
34
+ });
35
+ expect(snippets).toHaveLength(1);
36
+ expect(snippets[0]).toMatchObject({
37
+ name: "review",
38
+ content: "Review this",
39
+ scope: "global",
40
+ });
41
+ expect(typeof snippets[0].id).toBe("string");
42
+ await expect(store.list()).resolves.toEqual(snippets);
43
+ });
44
+
45
+ it("scopes project snippets by directory with project-over-global precedence in the caller", async () => {
46
+ const store = await makeStore();
47
+ await store.create({
48
+ name: "review",
49
+ content: "Global review",
50
+ scope: "global",
51
+ });
52
+ await store.create({
53
+ name: "review",
54
+ content: "Project review",
55
+ scope: "project",
56
+ directory: "/workspace",
57
+ });
58
+ await expect(store.list()).resolves.toHaveLength(1);
59
+ const scoped = await store.list("/workspace");
60
+ expect(scoped).toHaveLength(2);
61
+ await expect(store.list("/other")).resolves.toHaveLength(1);
62
+ });
63
+
64
+ it("rejects duplicate names case-insensitively within the same bucket", async () => {
65
+ const store = await makeStore();
66
+ await store.create({ name: "Review", content: "First", scope: "global" });
67
+ await expect(
68
+ store.create({ name: "review", content: "Second", scope: "global" }),
69
+ ).rejects.toMatchObject({
70
+ code: "INVALID_ARGUMENT",
71
+ });
72
+ await expect(store.list()).resolves.toHaveLength(1);
73
+ });
74
+
75
+ it("rejects malformed input without replacing valid data", async () => {
76
+ const store = await makeStore();
77
+ await store.create({ name: "ok", content: "Content", scope: "global" });
78
+ await expect(
79
+ store.create({ name: "bad name!", content: "x", scope: "global" }),
80
+ ).rejects.toMatchObject({
81
+ code: "INVALID_ARGUMENT",
82
+ });
83
+ await expect(
84
+ store.create({ name: "ok2", content: "", scope: "global" }),
85
+ ).rejects.toMatchObject({
86
+ code: "INVALID_ARGUMENT",
87
+ });
88
+ await expect(store.list()).resolves.toHaveLength(1);
89
+ });
90
+
91
+ it("treats malformed files as invalid rather than empty", async () => {
92
+ const directory = await mkdtemp(join(tmpdir(), "pichamber-snippets-"));
93
+ directories.push(directory);
94
+ const file = join(directory, "snippets.json");
95
+ await writeFile(file, "{ not json", "utf8");
96
+ const store = createPiSnippetsStore({ file });
97
+ await expect(store.list()).rejects.toMatchObject({
98
+ code: "SNIPPETS_INVALID",
99
+ });
100
+ expect(await readFile(file, "utf8")).toBe("{ not json");
101
+ });
102
+
103
+ it("updates content and deletes by id", async () => {
104
+ const store = await makeStore();
105
+ const created = await store.create({
106
+ name: "note",
107
+ content: "Before",
108
+ scope: "global",
109
+ });
110
+ const id = created[0].id;
111
+ const updated = await store.update(id, { content: "After" });
112
+ expect(updated[0]).toMatchObject({ id, content: "After" });
113
+ const afterDelete = await store.remove(id);
114
+ expect(afterDelete).toEqual([]);
115
+ });
116
+
117
+ it("returns not-found for unknown ids without clearing state", async () => {
118
+ const store = await makeStore();
119
+ await store.create({ name: "keep", content: "Content", scope: "global" });
120
+ await expect(
121
+ store.update("missing", { content: "x" }),
122
+ ).rejects.toMatchObject({ code: "SNIPPET_NOT_FOUND" });
123
+ await expect(store.remove("missing")).rejects.toMatchObject({
124
+ code: "SNIPPET_NOT_FOUND",
125
+ });
126
+ await expect(store.list()).resolves.toHaveLength(1);
127
+ });
128
+
129
+ it("serializes the full read-modify-write transaction", async () => {
130
+ const store = await makeStore();
131
+ await Promise.all([
132
+ store.create({ name: "first", content: "One", scope: "global" }),
133
+ store.create({ name: "second", content: "Two", scope: "global" }),
134
+ ]);
135
+ await expect(store.list()).resolves.toHaveLength(2);
136
+ });
137
+
138
+ it("canonicalizes project directory keys", async () => {
139
+ const store = await makeStore();
140
+ await store.create({
141
+ name: "project-note",
142
+ content: "Note",
143
+ scope: "project",
144
+ directory: "/workspace/child/..",
145
+ });
146
+ await expect(store.list("/workspace")).resolves.toHaveLength(1);
147
+ await expect(store.list("relative/path")).rejects.toMatchObject({
148
+ code: "INVALID_ARGUMENT",
149
+ });
150
+ });
151
+
152
+ it("does not update or delete a project snippet through another directory", async () => {
153
+ const store = await makeStore();
154
+ const created = await store.create({
155
+ name: "private",
156
+ content: "Before",
157
+ scope: "project",
158
+ directory: "/workspace-a",
159
+ });
160
+ const id = created.find((snippet) => snippet.scope === "project").id;
161
+ await expect(
162
+ store.update(id, { content: "After" }, "/workspace-b"),
163
+ ).rejects.toMatchObject({ code: "SNIPPET_NOT_FOUND" });
164
+ await expect(store.remove(id, "/workspace-b")).rejects.toMatchObject({
165
+ code: "SNIPPET_NOT_FOUND",
166
+ });
167
+ await expect(store.list("/workspace-a")).resolves.toEqual(created);
168
+ });
169
+
170
+ it("distinguishes missing store from authoritative empty store", async () => {
171
+ const directory = await mkdtemp(join(tmpdir(), "pichamber-snippets-"));
172
+ directories.push(directory);
173
+ const file = join(directory, "snippets.json");
174
+ const store = createPiSnippetsStore({ file });
175
+ await expect(store.list()).resolves.toEqual([]);
176
+ const { stat } = await import("node:fs/promises");
177
+ await expect(stat(file)).rejects.toMatchObject({ code: "ENOENT" });
178
+ await store.create({ name: "a", content: "A", scope: "global" });
179
+ await expect(store.list()).resolves.toHaveLength(1);
180
+ await store.remove((await store.list())[0].id);
181
+ await expect(store.list()).resolves.toEqual([]);
182
+ await expect(readFile(file, "utf8")).resolves.toContain('"snippets": []');
183
+ });
184
+
185
+ it("renames by opaque id and rejects collisions without overwriting", async () => {
186
+ const store = await makeStore();
187
+ const created = await store.create({ name: "first", content: "One", scope: "global" });
188
+ const id = created[0].id;
189
+ await store.create({ name: "second", content: "Two", scope: "global" });
190
+ const renamed = await store.update(id, { name: "renamed" });
191
+ expect(renamed.find((s) => s.id === id)).toMatchObject({ name: "renamed" });
192
+ await expect(store.update(id, { name: "SECOND" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
193
+ await expect(store.list()).resolves.toHaveLength(2);
194
+ expect((await store.list()).find((s) => s.id === id)).toMatchObject({ name: "renamed" });
195
+ });
196
+
197
+ it("moves between global and project scopes with destination validation", async () => {
198
+ const store = await makeStore();
199
+ const created = await store.create({ name: "note", content: "Body", scope: "global" });
200
+ const id = created[0].id;
201
+ const moved = await store.update(id, { scope: "project", directory: "/workspace" }, "/workspace");
202
+ expect(moved.find((s) => s.id === id)).toMatchObject({ scope: "project", directory: "/workspace" });
203
+ await expect(store.list()).resolves.toHaveLength(0);
204
+ await expect(store.list("/workspace")).resolves.toHaveLength(1);
205
+ const back = await store.update(id, { scope: "global" }, "/workspace");
206
+ expect(back.find((s) => s.id === id)).toMatchObject({ scope: "global" });
207
+ });
208
+
209
+ it("leaves the original intact when a scope move collides", async () => {
210
+ const store = await makeStore();
211
+ await store.create({ name: "note", content: "Project", scope: "project", directory: "/workspace" });
212
+ const global = await store.create({ name: "other", content: "Global", scope: "global" });
213
+ const id = global.find((s) => s.name === "other").id;
214
+ await expect(store.update(id, { name: "NOTE", scope: "project", directory: "/workspace" }, "/workspace")).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
215
+ const after = await store.list("/workspace");
216
+ expect(after).toHaveLength(2);
217
+ expect(after.find((s) => s.id === id)).toMatchObject({ scope: "global", name: "other" });
218
+ });
219
+
220
+ it("edits aliases with case-insensitive collision checks", async () => {
221
+ const store = await makeStore();
222
+ const created = await store.create({ name: "note", content: "Body", scope: "global" });
223
+ const id = created[0].id;
224
+ const updated = await store.update(id, { aliases: ["shortcut", "alt"] });
225
+ expect(updated[0]).toMatchObject({ aliases: ["shortcut", "alt"] });
226
+ await store.create({ name: "other", content: "Other", scope: "global" });
227
+ const otherId = (await store.list()).find((s) => s.name === "other").id;
228
+ await expect(store.update(otherId, { aliases: ["SHORTCUT"] })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
229
+ await expect(store.update(otherId, { name: "ALT" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
230
+ });
231
+
232
+ it("preserves the previous snapshot when a write fails", async () => {
233
+ const directory = await mkdtemp(join(tmpdir(), "pichamber-snippets-"));
234
+ directories.push(directory);
235
+ const file = join(directory, "snippets.json");
236
+ const store = createPiSnippetsStore({ file });
237
+ await store.create({ name: "keep", content: "Content", scope: "global" });
238
+ const before = await readFile(file, "utf8");
239
+ const failingFs = {
240
+ ...(await import("node:fs/promises")),
241
+ writeFile: async () => {
242
+ const error = new Error("disk full");
243
+ error.code = "ENOSPC";
244
+ throw error;
245
+ },
246
+ };
247
+ const failing = createPiSnippetsStore({ file, fs: failingFs });
248
+ await expect(failing.create({ name: "lost", content: "x", scope: "global" })).rejects.toBeDefined();
249
+ expect(await readFile(file, "utf8")).toBe(before);
250
+ await expect(store.list()).resolves.toHaveLength(1);
251
+ });
252
+ });
@@ -98,7 +98,11 @@ const startFakeRelay = () => {
98
98
  wsUrl: `ws://127.0.0.1:${port}`,
99
99
  state,
100
100
  stop: () => new Promise((r) => {
101
+ for (const client of wss.clients) {
102
+ try { client.terminate(); } catch {}
103
+ }
101
104
  wss.close();
105
+ server.closeAllConnections?.();
102
106
  server.close(() => r());
103
107
  }),
104
108
  });
@@ -129,7 +133,13 @@ const startLoopbackOrigin = () =>
129
133
  res.writeHead(404);
130
134
  res.end();
131
135
  });
132
- server.listen(0, '127.0.0.1', () => resolve({ port: server.address().port, stop: () => new Promise((r) => server.close(() => r())) }));
136
+ server.listen(0, '127.0.0.1', () => resolve({
137
+ port: server.address().port,
138
+ stop: () => new Promise((r) => {
139
+ server.closeAllConnections?.();
140
+ server.close(() => r());
141
+ }),
142
+ }));
133
143
  });
134
144
 
135
145
  // Build the host identity around a fresh keypair (ECDH enc key + ECDSA sign key).
@@ -177,18 +187,46 @@ const runScriptedClient = async ({ relayUrl, serverId, hostEncPubJwk }) => {
177
187
  let channel = null;
178
188
  const responseChunks = [];
179
189
  let responseStatus = null;
190
+ let gotReady = false;
191
+ let settled = false;
192
+ let timeoutTimer = null;
180
193
  let resolveDone;
181
- const done = new Promise((resolve) => {
194
+ let rejectDone;
195
+ const done = new Promise((resolve, reject) => {
182
196
  resolveDone = resolve;
197
+ rejectDone = reject;
183
198
  });
199
+ const fail = (message) => {
200
+ if (settled) return;
201
+ settled = true;
202
+ if (timeoutTimer) clearTimeout(timeoutTimer);
203
+ try { ws.close(); } catch {}
204
+ rejectDone(new Error(message));
205
+ };
206
+ timeoutTimer = setTimeout(() => {
207
+ fail(
208
+ `scripted relay client timed out (gotReady=${gotReady} status=${responseStatus} chunks=${responseChunks.length})`,
209
+ );
210
+ }, 10000);
211
+ if (typeof timeoutTimer.unref === 'function') timeoutTimer.unref();
184
212
 
185
213
  ws.on('open', async () => {
186
- ws.send(JSON.stringify({
187
- t: 'hello',
188
- v: RELAY_PROTOCOL_VERSION,
189
- clientPubJwk: await exportPublicKeyJwk(ephemeral.publicKey),
190
- nonce: bytesToBase64Url(nonce),
191
- }));
214
+ try {
215
+ ws.send(JSON.stringify({
216
+ t: 'hello',
217
+ v: RELAY_PROTOCOL_VERSION,
218
+ clientPubJwk: await exportPublicKeyJwk(ephemeral.publicKey),
219
+ nonce: bytesToBase64Url(nonce),
220
+ }));
221
+ } catch (error) {
222
+ fail(`scripted client hello failed: ${error?.message ?? error}`);
223
+ }
224
+ });
225
+ ws.on('error', (error) => {
226
+ fail(`scripted client socket error: ${error?.message ?? error}`);
227
+ });
228
+ ws.on('close', () => {
229
+ fail(`scripted client socket closed before StreamEnd (gotReady=${gotReady} status=${responseStatus})`);
192
230
  });
193
231
 
194
232
  // Serialize message handling: an async ws handler runs per-message tasks
@@ -196,9 +234,11 @@ const runScriptedClient = async ({ relayUrl, serverId, hostEncPubJwk }) => {
196
234
  // strict counter ordering (the production tunnel client chains decrypts).
197
235
  let processing = Promise.resolve();
198
236
  const handleMessage = async (data, isBinary) => {
237
+ if (settled) return;
199
238
  if (!isBinary) {
200
239
  const msg = JSON.parse(data.toString('utf8'));
201
240
  if (msg.t === 'ready') {
241
+ gotReady = true;
202
242
  const keys = await deriveSessionKeys(ephemeral.privateKey, hostPub, nonce);
203
243
  channel = {
204
244
  encryptor: createFrameEncryptor(keys.clientToHost),
@@ -231,12 +271,19 @@ const runScriptedClient = async ({ relayUrl, serverId, hostEncPubJwk }) => {
231
271
  body.set(c, off);
232
272
  off += c.length;
233
273
  }
234
- resolveDone({ status: responseStatus, body: JSON.parse(new TextDecoder().decode(body)) });
235
- ws.close();
274
+ settled = true;
275
+ if (timeoutTimer) clearTimeout(timeoutTimer);
276
+ const value = { status: responseStatus, body: JSON.parse(new TextDecoder().decode(body)) };
277
+ try { ws.close(); } catch {}
278
+ resolveDone(value);
236
279
  }
237
280
  };
238
281
  ws.on('message', (data, isBinary) => {
239
- processing = processing.then(() => handleMessage(data, isBinary));
282
+ processing = processing
283
+ .then(() => handleMessage(data, isBinary))
284
+ .catch((error) => {
285
+ fail(`scripted client message handling failed: ${error?.message ?? error}`);
286
+ });
240
287
  });
241
288
 
242
289
  return done;
@@ -260,16 +307,33 @@ describe('relay host-client integration', () => {
260
307
 
261
308
  it('tunnels an HTTP GET /health with only binary frames post-handshake', async () => {
262
309
  const identity = await buildIdentity();
310
+ let resolveConnected;
311
+ const connected = new Promise((r) => { resolveConnected = r; });
263
312
  host = startRelayHost({
264
313
  relayUrl: `${relay.wsUrl}/`,
265
314
  identity,
266
315
  getLocalPort: () => origin.port,
267
- onStatus: () => {},
316
+ onStatus: (status) => {
317
+ if (status?.state === 'connected') resolveConnected?.();
318
+ },
268
319
  logger: { warn: () => {} },
269
320
  });
270
321
 
271
- // Give the control socket a moment to connect before the client arrives.
272
- await new Promise((r) => setTimeout(r, 200));
322
+ if (host.getStatus?.()?.state === 'connected') resolveConnected?.();
323
+ let connectedTimer;
324
+ const connectedTimeout = new Promise((_, reject) => {
325
+ connectedTimer = setTimeout(() => {
326
+ reject(new Error(
327
+ `relay host control socket did not connect (state=${host.getStatus?.()?.state ?? 'unknown'} lastError=${host.getStatus?.()?.lastError ?? 'none'})`,
328
+ ));
329
+ }, 5000);
330
+ if (typeof connectedTimer.unref === 'function') connectedTimer.unref();
331
+ });
332
+ try {
333
+ await Promise.race([connected, connectedTimeout]);
334
+ } finally {
335
+ clearTimeout(connectedTimer);
336
+ }
273
337
 
274
338
  const result = await runScriptedClient({
275
339
  relayUrl: relay.wsUrl,
@@ -288,5 +352,5 @@ describe('relay host-client integration', () => {
288
352
  const plaintextForwarded = forwarded.filter((f) => !f.isBinary);
289
353
  expect(plaintextForwarded.length).toBe(2); // hello + ready only
290
354
  expect(forwarded.filter((f) => f.isBinary).length).toBeGreaterThan(0);
291
- });
355
+ }, 15000);
292
356
  });
@@ -10,6 +10,7 @@ const ALLOWED_CORS_HEADER_NAMES = new Set([
10
10
  'cache-control',
11
11
  'content-type',
12
12
  'x-pichamber-directory',
13
+ 'x-pichamber-filename',
13
14
  'x-requested-with',
14
15
  ]);
15
16
 
@@ -20,6 +21,7 @@ const DEFAULT_ALLOWED_CORS_HEADERS = [
20
21
  'X-Requested-With',
21
22
  'Cache-Control',
22
23
  'x-pichamber-directory',
24
+ 'x-pichamber-filename',
23
25
  ].join(',');
24
26
 
25
27
  export const isAllowedUiCorsOrigin = (origin) => (
@@ -12,26 +12,27 @@ describe('packaged UI CORS', () => {
12
12
  expect(isAllowedUiCorsOrigin('https://example.test')).toBe(false);
13
13
  });
14
14
 
15
- it('allows the workspace directory header used by packaged filesystem fetches', () => {
15
+ it('allows the custom headers used by packaged filesystem and attachment fetches', () => {
16
16
  expect(resolveAllowedCorsHeaders('x-pichamber-directory,authorization')).toBe('x-pichamber-directory,authorization');
17
17
  expect(resolveAllowedCorsHeaders('x-pichamber-directory')).toBe('x-pichamber-directory');
18
+ expect(resolveAllowedCorsHeaders('x-pichamber-filename')).toBe('x-pichamber-filename');
18
19
  expect(resolveAllowedCorsHeaders('x-evil')).toBe(
19
- 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,x-pichamber-directory',
20
+ 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,x-pichamber-directory,x-pichamber-filename',
20
21
  );
21
22
  });
22
23
 
23
- it('answers Electron preflight with the requested directory header', () => {
24
+ it('answers Electron preflight with the requested custom headers', () => {
24
25
  const headers = {};
25
26
  const res = { setHeader(name, value) { headers[name] = value; } };
26
27
  const ended = applyUiCorsHeaders({
27
28
  method: 'OPTIONS',
28
29
  headers: {
29
30
  origin: 'pichamber-ui://app',
30
- 'access-control-request-headers': 'x-pichamber-directory,authorization',
31
+ 'access-control-request-headers': 'x-pichamber-directory,x-pichamber-filename,authorization',
31
32
  },
32
33
  }, res);
33
34
  expect(ended).toBe(true);
34
35
  expect(headers['Access-Control-Allow-Origin']).toBe('pichamber-ui://app');
35
- expect(headers['Access-Control-Allow-Headers']).toBe('x-pichamber-directory,authorization');
36
+ expect(headers['Access-Control-Allow-Headers']).toBe('x-pichamber-directory,x-pichamber-filename,authorization');
36
37
  });
37
38
  });
@@ -1 +0,0 @@
1
- import{R as C,j as e}from"./vendor-react-DYyjh7Q0.js";import{T as y,l as _,B as c,I as a,m as v,aJ as z}from"./WindowsWindowControls-DIqnZ2uU.js";import{u as I,m as H}from"./index-ChFxkws4.js";const N=38,h=200,k=({value:t,onChange:o,placeholder:m,disabled:i=!1,hasTouchInput:r=!1,isMobile:u=!1})=>{const n=C.useRef(null),j=I(s=>s.inputSpellcheckEnabled);return C.useLayoutEffect(()=>{const s=n.current;if(!s)return;const l=document.activeElement===s,d=()=>{s.style.height=`${N}px`;const p=s.scrollHeight,x=Math.min(Math.max(p,N),h);s.style.height=`${x}px`,s.style.overflowY=p>h?"auto":"hidden",p>h&&!l&&(s.scrollTop=s.scrollHeight)};d();const f=window.requestAnimationFrame(d);return()=>{window.cancelAnimationFrame(f)}},[t]),e.jsx("textarea",{ref:n,value:t,onChange:s=>o(s.target.value),placeholder:m??"Commit message",rows:1,disabled:i,autoCorrect:r?"on":"off",autoCapitalize:r?"sentences":"off",spellCheck:u||j,className:H("w-full rounded-lg border border-border/60 bg-surface-elevated px-3 py-2 typography-ui-label text-foreground placeholder:text-muted-foreground","resize-none outline-none transition-[border-color,box-shadow] duration-150","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]",i&&"opacity-50"),style:{minHeight:N,maxHeight:h}})},F=({highlights:t,onInsert:o})=>{if(t.length===0)return null;const m=()=>{o(t)};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-transparent px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Highlights"}),e.jsxs(y,{children:[e.jsx(_,{asChild:!0,children:e.jsx(c,{variant:"ghost",size:"icon",className:"size-6",onClick:m,"aria-label":"Insert aria label",children:e.jsx(a,{name:"arrow-down",className:"size-4"})})}),e.jsx(v,{sideOffset:8,children:"Insert tooltip"})]})]}),e.jsx("ul",{className:"space-y-1",children:t.map((i,r)=>e.jsx("li",{className:"typography-meta text-foreground",children:i},`${i}-${r}`))})]})},q=({stagedCount:t,commitMessage:o,onCommitMessageChange:m,generatedHighlights:i,onInsertHighlights:r,onGenerateMessage:u,isGeneratingMessage:n,onCommit:j,onCommitAndPush:s,commitAction:l,hasPendingIndexMutation:d=!1,gitmojiEnabled:f,onOpenGitmojiPicker:p})=>{const x=t>0,b=o.trim()&&x&&l===null&&!d,{isMobile:g,hasTouchInput:w}=z();return e.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[e.jsxs("div",{className:"flex w-full items-baseline gap-2 px-0 pt-2 pb-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),x?null:e.jsx("span",{className:"min-w-0 truncate typography-meta text-muted-foreground",children:"Stage files to enable commit."})]}),e.jsxs("div",{className:"flex flex-col gap-3 px-0 pt-1 pb-3",children:[e.jsx(F,{highlights:i,onInsert:r}),e.jsx(k,{value:o,onChange:m,placeholder:"Commit message",disabled:l!==null,hasTouchInput:w,isMobile:g}),f&&e.jsxs(c,{variant:"outline",size:"sm",onClick:p,className:"w-fit",type:"button",children:[e.jsx(a,{name:"emotion-happy",className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"@container/commit-actions flex items-center gap-2 min-w-0",children:[e.jsxs(c,{variant:"outline",size:"sm",onClick:u,disabled:n||l!==null||d||t===0,type:"button","aria-label":"Generate commit message",className:"commit-actions__btn",children:[n?e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(a,{name:"ai-generate-2",className:"size-4 text-primary"}),e.jsx("span",{className:"commit-actions__label",children:"Generate"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(c,{size:"sm",variant:"outline",onClick:j,disabled:!b||n,className:"commit-actions__btn whitespace-nowrap","aria-label":"Commit aria label",children:l==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label",children:"Committing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"git-commit",className:"size-4"}),e.jsx("span",{className:"commit-actions__label",children:"Commit"})]})}),g?e.jsxs(y,{children:[e.jsx(_,{asChild:!0,children:e.jsx(c,{variant:"default",size:"sm",onClick:()=>s(),disabled:!b||n,className:"h-7 w-7 p-0","aria-label":"Commit and sync",children:l==="commitAndPush"?e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(a,{name:"arrow-up",className:"size-3.5"})})}),e.jsx(v,{side:"top",children:e.jsx("p",{children:"Commit & sync"})})]}):e.jsx(c,{size:"sm",variant:"default",onClick:()=>s(),disabled:!b||n,className:"commit-actions__btn","aria-label":"Commit and sync",children:l==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"loader-4",className:"size-4 animate-spin"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--push",children:"Syncing..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(a,{name:"arrow-up",className:"size-3.5"}),e.jsx("span",{className:"commit-actions__label commit-actions__label--push",children:"Commit & sync"})]})})]})]})]})};export{q as C};
@@ -1 +0,0 @@
1
- import{R as r,j as t}from"./vendor-react-DYyjh7Q0.js";import{u as a}from"./index-ChFxkws4.js";import{w as v,I as m}from"./WindowsWindowControls-DIqnZ2uU.js";import{D as j}from"./DiagramEditor-C7xe1Brl.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-base-ui-DL8r2fgQ.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./runtimeSurface-OhCUGSKg.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-E2vgV9K3.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-DSzLbZiS.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-BUlYhQ3o.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-BS2SpSAZ.js";import"./vendor-codemirror-lang-json-CqayksDf.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-Ba8JZ6fp.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-DK27qQri.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-CvO36Y1p.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-Dv4zaHRN.js";import"./vendor-codemirror-lang-python-_2bIYTiJ.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-RrgJ8H_6.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-CW8w438f.js";import"./vendor-react-drawio-Boqanm0j.js";function Kt(){const{files:o}=v(),[e,d]=r.useState(null),[s,p]=r.useState(""),[x,n]=r.useState(!0),l=r.useRef(null),c=a(i=>i.pendingDiagramFile),u=r.useCallback(async i=>{n(!0),d(i);try{const f=await o?.readFile?.(i);f&&p(f.content)}catch{p("")}finally{n(!1)}},[o]);r.useEffect(()=>{if(!c)return;const i=a.getState().consumePendingDiagramFile();i&&u(i)},[u,c]);const g=r.useCallback(async()=>{const i=l.current?.getXml();e&&o?.writeFile&&i&&i!==s&&(await o.writeFile(e,i),p(i))},[e,o,s]),h=e?e.split("/").pop()||e:"";return e?x?t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx(m,{name:"loader-4",className:"size-4 animate-spin"})}):t.jsxs("div",{className:"flex h-full flex-col",children:[t.jsxs("div",{className:"flex items-center gap-2 border-b border-border/30 px-3 py-1.5",children:[t.jsx(m,{name:"file",className:"size-4 shrink-0 text-muted-foreground"}),t.jsx("span",{className:"typography-ui text-muted-foreground truncate flex-1",children:h}),t.jsx("button",{type:"button",onClick:()=>{g()},className:"size-6 flex items-center justify-center rounded-md text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Save diagram",children:t.jsx(m,{name:"save-3",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>a.getState().setActiveMainTab("chat"),className:"size-6 flex items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:"Close diagram view",children:t.jsx(m,{name:"close",className:"size-4"})})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(j,{ref:l,xml:s,className:"h-full"})})]}):t.jsx("div",{className:"flex h-full items-center justify-center p-3",children:t.jsx("div",{className:"typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}export{Kt as DiagramView};
@@ -1,18 +0,0 @@
1
- import{R as o,j as n}from"./vendor-react-DYyjh7Q0.js";import{u as _,a as ut,m as B}from"./index-ChFxkws4.js";import{cQ as Bt,cR as Wt,cS as Ot,w as dt,x as zt,aJ as Gt,z as Ht,y as Ut,A as Vt,C as Q,g as Kt,av as qt,cT as Xt,cU as Qt,aQ as Jt,N as ve,t as ft,B as Ne,I as A,T as Yt,l as Zt,m as en,cV as mt,cP as tn,am as nn,an as sn,ao as rn,cW as on,cX as je,ar as pt,F as ht,M as an}from"./WindowsWindowControls-DIqnZ2uU.js";import{P as ln}from"./PierreDiffViewer-BbUCO4IF.js";import{v as cn,g as un}from"./contextFileOpenGuard-BmQ7Zu-L.js";import{p as dn}from"./VirtualizedFileDiff-DFx8xsmh.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-base-ui-DL8r2fgQ.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./runtimeSurface-OhCUGSKg.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-E2vgV9K3.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-DSzLbZiS.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-BUlYhQ3o.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-BS2SpSAZ.js";import"./vendor-codemirror-lang-json-CqayksDf.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-Ba8JZ6fp.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-DK27qQri.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-CvO36Y1p.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-Dv4zaHRN.js";import"./vendor-codemirror-lang-python-_2bIYTiJ.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-RrgJ8H_6.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-CW8w438f.js";import"./web-components-BOt08OHk.js";import"./computeVirtualFileMetrics-elCbdk6U.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-BmJyTmjJ.js";import"./vendor-pierre-theming-C6Z4M5_u.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"./usePanelSlide-aeAIo1cp.js";import"./SessionUnreadDot-BVBBEBTg.js";import"./permissionStore-BRcQ9Jgt.js";import"./useInlineCommentController-DC0iNSYX.js";import"./collapsible-DlqZyxEY.js";import"./appThemeRegistry-BK0dHKa6.js";import"./registerCustomTheme-BBXUCRnG.js";import"./isDiffPlainText-CvfRfc7h.js";import"./vendor-diff-C3JhlQdm.js";function fn(t,e=10){const a=[];let i;for(const u of t.split(`
2
- `)){const x=u.match(Bt);if(x!=null){i!=null&&(i.hunkLines.length>0&&(Me(i,e,"trailing"),Ge(i,a)),i=void 0);const b=parseInt(x[3]),N=parseInt(x[1]),v=parseInt(x[4]??"1"),h=parseInt(x[2]??"1");isNaN(b)||isNaN(N)||isNaN(v)||isNaN(h)?a.push(u):i={additionStart:b,deletionStart:N,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(i==null){a.push(u);continue}if(u.startsWith(" "))i.contextLines.push(u);else if(u!==""){if(i.hunkLines.length>0&&i.contextLines.length>e*2){const b=i.contextLines.length-e*2,N=i.contextLines.slice(-e);Me(i,e,"trailing");const{additionCount:v,deletionCount:h}=i;Ge(i,a),i={additionStart:i.additionStart+v+b,deletionStart:i.deletionStart+h+b,deletionCount:0,additionCount:0,contextLines:N,hunkLines:[]}}Me(i,e,i.hunkLines.length===0?"leading":"before-change"),i.hunkLines.push(u),u.startsWith("+")?i.additionCount+=1:u.startsWith("-")&&(i.deletionCount+=1)}}i!=null&&i.hunkLines.length>0&&(Me(i,e,"trailing"),Ge(i,a));const c=a.join(`
3
- `);return t.endsWith(`
4
- `)?`${c}
5
- `:c}function Me(t,e,a){if(a==="leading"&&t.contextLines.length>e){const i=t.contextLines.length-e;t.contextLines.splice(0,i),t.additionStart+=i,t.deletionStart+=i}return a==="trailing"&&t.contextLines.length>e&&(t.contextLines.length=e),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 Ge(t,e){e.push(`@@ -${Ze(t.deletionStart,t.deletionCount)} +${Ze(t.additionStart,t.additionCount)} @@`),e.push(...t.hunkLines)}function Ze(t,e){return e===1?`${t}`:`${t},${e}`}const et=(t,e)=>{if(e.length===0)return null;let a=null,i=null;for(const u of e)u.top<=t?(!a||u.top>a.top)&&(a=u):(!i||u.top<i.top)&&(i=u);const c=a??i;return c?{path:c.path,topOffset:c.top-t}:null},mn=(t,e,a,i)=>Math.min(Math.max(0,i),Math.max(0,t+a-e)),pn=64,hn=3,ne=new Map,gn=(t,e,a=hn)=>{const i=`${t}\0${a}\0${e}`,c=ne.get(i);if(c)return ne.delete(i),ne.set(i,c),c;const u=bn(e),x=u?Wt(fn(e,a),{oldFile:{name:t,contents:u.before},newFile:{name:t,contents:u.after}})??nt(t):Ot(xn(t,e))[0]?.files[0]??nt(t);for(ne.set(i,x);ne.size>pn;){const b=ne.keys().next().value;if(!b)break;ne.delete(b)}return x},xn=(t,e)=>!e.trim()||e.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(e)?e:`Index: ${t}
6
- ===================================================================
7
- --- ${t}
8
- +++ ${t}
9
- ${e}`,bn=t=>{if(!t.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(t))return;const e=[...t.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(e.length!==1)return;const a=e[0],i=Number.parseInt(a[1]??"",10),c=Number.parseInt(a[2]??"",10);if(i>1||c>1||!Number.isFinite(i)||!Number.isFinite(c))return;const u=(a.index??0)+a[0].length,x=t.slice(u),b=[],N=[];let v;for(const h of x.split(/\r?\n/)){if(h.startsWith("diff --git ")||h.startsWith("@@ "))break;if(h.startsWith("\\")){if(v==="-"||v===" "){const S=b.at(-1);S&&(S.newline=!1)}if(v==="+"||v===" "){const S=N.at(-1);S&&(S.newline=!1)}continue}if(h.startsWith("-")){b.push({text:h.slice(1),newline:!0}),v="-";continue}if(h.startsWith("+")){N.push({text:h.slice(1),newline:!0}),v="+";continue}h.startsWith(" ")&&(b.push({text:h.slice(1),newline:!0}),N.push({text:h.slice(1),newline:!0}),v=" ")}return{before:tt(b),after:tt(N)}},tt=t=>t.map(e=>e.text+(e.newline?`
10
- `:"")).join(""),nt=t=>dn({name:t,contents:""},{name:t,contents:""}),st=t=>{if(!t)return null;const e=t.split(`
11
- `);let a=null;for(const i of e){const c=i.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(c){const u=Number.parseInt(c[1]??"",10);a=Number.isFinite(u)&&u>=1?u:null;continue}if(a!==null){if(i.startsWith(" ")){a+=1;continue}if(i.startsWith("+"))return a;if(i.startsWith("-"))return Math.max(1,a)}}return null},yn=1100,wn=15e3,rt=500,it=300,jn=1e6,gt=3,vn=t=>t<=6?t:t<=12?6:t<=25?4:2,Nn=o.memo(()=>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."})})),xt={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},Cn=xt.M,Sn=t=>{const e=t.index?.trim(),a=t.working_dir?.trim();return e&&e!=="?"?e.charAt(0):a?a.charAt(0):e?.charAt(0)||a?.charAt(0)||"M"},bt=t=>{const e=Sn(t);return xt[e]??Cn},Fn=t=>{const{index:e,working_dir:a}=t;return e==="A"||a==="A"||e==="?"||a==="?"},ot=t=>{const e=t.index?.trim();return!!(e&&e!=="?")},at=t=>!!t.working_dir?.trim()||t.index==="?",Ln=(t,e)=>tn(t,e),lt=t=>(t||"").replace(/\\/g,"/").replace(/\/+$/,""),ct=(t,e)=>{const a=t.split(`
12
- `),i=e.split(`
13
- `),c=Math.min(a.length,i.length);for(let u=0;u<c;u+=1)if(a[u]!==i[u])return u+1;return i.length>a.length?a.length+1:a.length>i.length?Math.max(1,i.length):1},Dn=t=>/^Binary files .+ differ$/m.test(t)||/^GIT binary patch$/m.test(t),kn=t=>Array.isArray(t)?t.filter(e=>!e||typeof e!="object"?!1:typeof e.file=="string"):[],Rn=t=>t.split(/^diff --git /m).slice(1).flatMap(a=>{const[i=""]=a.split(`
14
- `,1),c=i.lastIndexOf(" b/");if(c<=2)return[];const u=i.slice(2,c),x=i.slice(c+3).trim(),b=`diff --git ${a}`,N=b.includes(`
15
- new file mode `)?"added":b.includes(`
16
- deleted file mode `)?"deleted":b.includes(`
17
- rename from `)?"renamed":"modified";let v=0,h=0;for(const S of b.split(`
18
- `))S.startsWith("+")&&!S.startsWith("+++")&&(v+=1),S.startsWith("-")&&!S.startsWith("---")&&(h+=1);return[{file:N==="deleted"?u:x,status:N,additions:v,deletions:h,patch:b}]}),En=t=>t==="added"?"A":t==="deleted"?"D":"M",Ue=(t,e,a)=>Dn(e)?{original:"",modified:"",isBinary:!0,patch:e,contextMode:a}:{original:"",modified:"",patch:e,fileDiff:gn(t,e),contextMode:a},yt=(t,e,a)=>{const i=t??0,c=e??0;return!i&&!c?null:n.jsxs("span",{className:B("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",a?.className),children:[i?n.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i]}):null,c?n.jsxs("span",{style:{color:"var(--status-error)"},children:["-",c]}):null]})},An=o.memo(({scope:t,isGitRepo:e,branchAvailable:a,allCount:i,workingCount:c,stagedCount:u,turnCount:x,branchCount:b,onScopeChange:N})=>{const[v,h]=o.useState(!1),S=t==="all"?i:t==="staged"?u:t==="turn"?x:t==="branch"?b:c,g=t==="staged"?"Staged":t==="turn"?"Last turn":t==="branch"?"Branch":t==="all"?"All":"Changed";return n.jsxs(nn,{open:v,onOpenChange:h,children:[n.jsx(sn,{asChild:!0,children:n.jsxs("button",{type:"button",className:"flex h-7 flex-shrink-0 items-center gap-1.5 rounded-md px-2 typography-ui-label font-semibold text-foreground outline-none hover:bg-interactive-hover focus-visible:ring-2 focus-visible:ring-ring","aria-label":"Select change mode",children:[n.jsxs("span",{className:"whitespace-nowrap",children:[g,n.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",S]})]}),n.jsx(A,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"})]})}),n.jsx(rn,{align:"start",className:"w-40",children:n.jsxs(on,{value:t,onValueChange:w=>{(w==="all"||w==="working"||w==="staged"||w==="turn"||w==="branch")&&(N?.(w),h(!1))},children:[e!==!1?n.jsx(je,{value:"all",children:n.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[n.jsx("span",{children:"All"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:i})]})}):null,e!==!1?n.jsx(je,{value:"working",children:n.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[n.jsx("span",{children:"Changed"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:c})]})}):null,e!==!1?n.jsx(je,{value:"staged",children:n.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[n.jsx("span",{children:"Staged"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:u})]})}):null,n.jsx(je,{value:"turn",children:n.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[n.jsx("span",{children:"Last turn"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:x})]})}),a?n.jsx(je,{value:"branch",children:n.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[n.jsx("span",{children:"Branch"}),n.jsx("span",{className:"typography-meta text-muted-foreground",children:b})]})}):null]})})]})}),Mn=o.memo(({changedFiles:t,selectedFile:e,onSelectFile:a})=>t.length===0?null:n.jsx(pt,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:n.jsx("ul",{className:"flex flex-col gap-1",children:t.map(i=>{const c=bt(i),u=e===i.path;return n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:()=>a(i.path),className:B("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",u?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[n.jsx(ht,{filePath:i.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:c.color},title:c.description,"aria-label":c.description,children:c.code}),n.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:i.path,children:i.path}),yt(i.insertions,i.deletions)]})},i.path)})})})),Tn=o.memo(({filePath:t,diff:e,renderSideBySide:a})=>{const i=e.original.length>0,c=e.modified.length>0,u=a?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",x=a?"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:u,children:[i&&n.jsxs("div",{className:x,children:[n.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),n.jsx("img",{src:e.original,alt:`Original: ${t}`,className:a?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),c&&n.jsxs("div",{className:x,children:[n.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:i?"Modified":"New"}),n.jsx("img",{src:e.modified,alt:`Modified: ${t}`,className:a?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),In=o.memo(({filePath:t,diff:e,renderSideBySide:a,wrapLines:i})=>{const c=o.useMemo(()=>an(t)||"text",[t]);return e.isBinary?n.jsx(Nn,{}):ve(t)?n.jsx(Tn,{filePath:t,diff:e,renderSideBySide:a}):n.jsx("div",{className:"w-full",style:{contain:"layout"},children:n.jsx(ln,{original:e.original,modified:e.modified,fileDiff:e.fileDiff,language:c,fileName:t,renderSideBySide:a,wrapLines:i,layout:"inline"})})}),$n=o.memo(({filePath:t,staged:e,busyAction:a,disabled:i,onAction:c})=>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(He,{label:`Unstage ${t}`,icon:"arrow-go-back",loading:a==="unstage",disabled:i,onClick:()=>c("unstage")}):n.jsxs(n.Fragment,{children:[n.jsx(He,{label:`Revert changes in ${t}`,icon:"arrow-go-back",loading:a==="discard",disabled:i,tone:"failure",onClick:()=>c("discard")}),n.jsx(He,{label:`Stage ${t}`,icon:"add",loading:a==="stage",disabled:i,tone:"success",onClick:()=>c("stage")})]})})),He=({label:t,icon:e,loading:a,disabled:i,tone:c,onClick:u})=>n.jsx(Ne,{variant:"ghost",size:"sm",className:B("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",c==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",c==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]"),disabled:i,title:t,"aria-label":t,onClick:x=>{x.stopPropagation(),u()},children:a?n.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):n.jsx(A,{name:e,className:e==="add"?"size-4":"size-3.5"})}),_n=o.memo(({directory:t,file:e,layout:a,wrapLines:i,isSelected:c,isExpanded:u,isMounted:x,onSelect:b,onExpandedChange:N,registerSectionRef:v,showOpenInEditorAction:h=!1,isOpeningInEditor:S=!1,onOpenInEditor:g,staged:w=!1,showFileActions:Te=!0,loadFullFiles:J=!1,initialDiffData:C=null})=>{const{git:I}=dt(),H=Q(o.useCallback(f=>f.directories.get(t)?.diffCache.get(e.path)??null,[t,e.path])),fe=Q(f=>f.setDiff),me=Q(f=>f.fetchStatus),Ce=_(f=>f.setDiffFileLayout),[pe,Y]=o.useState(0),[W,se]=o.useState(null),[re,ie]=o.useState(!1),[U,O]=o.useState(null),[Z,Ie]=o.useState(!1),[V,K]=o.useState(null),[Se,he]=o.useState(null),P=o.useRef(null),Fe=o.useRef(null),oe=o.useMemo(()=>bt(e),[e]),m=a==="side-by-side",q=J?"full":"patch",z=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,M=o.useMemo(()=>C||(w?Se:V||(H?{original:H.original,modified:H.modified,isBinary:H.isBinary,contextMode:"full"}:null)),[H,C,V,w,Se]),ge=M?.contextMode===q,xe=o.useCallback(f=>{Fe.current=f,v(e.path,f)},[e.path,v]),Le=o.useCallback(f=>{N(e.path,f)},[e.path,N]),ee=o.useCallback(()=>{b(e.path)},[e.path,b]);o.useEffect(()=>{w?he(null):K(null),se(null),P.current=null},[z,w]),o.useEffect(()=>{if(!u||!x)return;if(!t||C||M&&ge){P.current=null,ie(!1);return}const f=`${t}::${e.path}::${w?"staged":"unstaged"}::${z}::${q}::${pe}`;if(P.current===f)return;P.current=f,se(null),ie(!0);let F=!1;const G=ut(),ke=J?jn:gt,Re=ve(e.path)?I.getGitFileDiff(t,{path:e.path,staged:w}):I.getGitDiff(t,{path:e.path,staged:w,contextLines:ke}),be=wn,$e=new Promise((R,$)=>{setTimeout(()=>$(new Error(`Timed out after ${be}ms`)),be)});return Promise.race([Re,$e]).then(R=>{if(!F){if("diff"in R){const $=Ue(e.path,R.diff,q);w?he($):K($)}else{const $={original:R.original??"",modified:R.modified??"",isBinary:R.isBinary,contextMode:"full"};w?he($):fe(t,e.path,$,G)}ie(!1)}}).catch(R=>{if(F)return;const $=R instanceof Error?R.message:String(R);se($),ie(!1)}),()=>{F=!0,P.current===f&&(P.current=null)}},[q,M,ge,pe,t,e.path,z,I,C,u,x,J,fe,w]);const X=o.useCallback(()=>{Le(!u),ee()},[Le,ee,u]),De=o.useCallback(async f=>{if(!(!t||U!==null)){O(f);try{f==="stage"?await I.stageGitFile(t,e.path):f==="unstage"?await I.unstageGitFile(t,e.path):await I.revertGitFile(t,e.path,{scope:"working"}),Y(F=>F+1),await me(t,I)}catch(F){const G=f==="unstage"?"Failed to unstage changes":f==="stage"?"Failed to stage changes":"Failed to revert changes";ft.error(F instanceof Error?F.message:G)}finally{O(F=>F===f?null:F)}}},[t,me,e.path,U,I]);return n.jsxs("div",{ref:xe,className:B("scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0"),children:[n.jsx("div",{className:B("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:X,onKeyDown:f=>{f.target===f.currentTarget&&(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),X())},className:B("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",c?"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:u?n.jsx(A,{name:"arrow-down-s",className:"size-4"}):n.jsx(A,{name:"arrow-right-s",className:"size-4"})}),n.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:oe.color},title:oe.description,"aria-label":oe.description,children:oe.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(ht,{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 F=e.path.slice(0,f),G=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:F}),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:G})]})]})})()]})})]}),n.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[yt(e.insertions,e.deletions),h&&g?n.jsx(Ne,{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(),g(e.path,M)},disabled:S,children:S?n.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):n.jsx(A,{name:"edit",className:"size-3.5"})}):null,n.jsx(mt,{mode:m?"side-by-side":"unified",onModeChange:f=>{const F=f==="side-by-side"?"side-by-side":"inline";Ce(e.path,F)},className:"opacity-70"})]})]})}),u&&n.jsxs("div",{className:"relative overflow-hidden bg-background",children:[!x&&!W?n.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,W?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:W}),n.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>Y(f=>f+1),children:"Retry"})]}):null,x&&re&&!M&&!W?n.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[n.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),"Loading diff..."]}):null,x&&M&&!Z&&e.insertions+e.deletions>rt?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:()=>Ie(!0),children:"Render anyway"})]}):null,x&&M&&(Z||e.insertions+e.deletions<=rt)?n.jsxs(n.Fragment,{children:[n.jsx(In,{filePath:e.path,diff:M,renderSideBySide:m,wrapLines:i}),Te?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($n,{filePath:e.path,staged:w,busyAction:U,disabled:U!==null,onAction:De})})}):null]}):null]})]})}),Kr=({hideStackedFileSidebar:t=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:a=!1,showOpenInEditorAction:i=!1,diffScope:c="all",onDiffScopeChange:u,branchBase:x=null,branchHead:b=null,targetFilePath:N=null,flushContent:v=!1})=>{const{git:h,files:S}=dt(),g=zt(),{screenWidth:w,isMobile:Te}=Gt(),J=Ht(g??null),C=Ut(g??null),I=Vt(g??null),H=Q(s=>s.setActiveDirectory),fe=Q(s=>s.ensureStatus),me=Q(s=>s.fetchStatus),Ce=Q(s=>s.clearDiffCache),pe=Q(s=>s.setDiff),[Y,W]=o.useState(null),[se,re]=o.useState(!1),[ie,U]=o.useState(null),[O,Z]=o.useState(()=>new Set),[Ie,V]=o.useState(()=>new Set),[K,Se]=o.useState(!1),[he,P]=o.useState(0),[Fe,oe]=o.useState(()=>new Map),[m,q]=o.useState(c),[z,M]=o.useState([]),[ge,xe]=o.useState(null),[Le,ee]=o.useState(!1);o.useEffect(()=>{q(c)},[c]);const X=_(s=>s.pendingDiffFile),De=_(s=>s.pendingDiffStaged),f=_(s=>s.pendingDiffScope),F=_(s=>s.setPendingDiffFile),G=_(s=>s.diffLayoutPreference),ke=_(s=>s.diffFileLayout),Re=_(s=>s.setDiffFileLayout),be=_(s=>s.diffWrapLines),$e=_(s=>s.setDiffWrapLines),R=_(s=>s.openContextFileAtLine),$=Kt(s=>s.currentSessionId),Ve=qt($??""),_e=be,Pe=m==="staged"?!0:m==="working"?!1:null,Ee=Pe??se,wt=Te||w<=768,jt=!t&&!wt&&w>=1024,ae=o.useRef(null),ye=o.useRef(new Map),te=o.useRef(null),k=o.useRef(null),le=o.useRef(!1),ce=o.useRef(null),Ke=o.useRef(null),Be=o.useRef(null),We=o.useRef(null),qe=o.useCallback(()=>{const s=ae.current;if(!s)return null;const r=s.getBoundingClientRect().top,l=[];for(const[d,p]of ye.current)p&&l.push({path:d,top:p.getBoundingClientRect().top});return et(r,l)},[]),ue=o.useCallback(()=>{te.current=null,le.current=!1,U(null),k.current!==null&&(window.cancelAnimationFrame(k.current),k.current=null)},[]),de=o.useCallback(s=>{Z(r=>{if(r.has(s))return r;const l=new Set(r);return l.add(s),l})},[]),we=o.useMemo(()=>{const s=Xt(Ve,{showTextJustificationActivity:!1,showTurnChangedFiles:!0,mergeHiddenUserTurns:!0});for(let r=s.turns.length-1;r>=0;r-=1){const l=s.turns[r];if(!l)continue;const d=l.activityParts.map(y=>y.part).filter(y=>y.type==="tool"),p=Qt(d);if(p.length>0)return p.map(y=>({file:y.path,status:"modified",additions:y.additions,deletions:y.deletions,patch:y.patch}));const D=kn(l.userMessage.info.summary?.diffs);if(D.length>0)return D}return[]},[Ve]);o.useEffect(()=>{if(m!=="branch"||!g||!x||!b||!h.getGitRangeDiff){M([]),xe(null),ee(!1);return}let s=!1;return ee(!0),xe(null),h.getGitRangeDiff(g,{base:x,head:b,contextLines:gt}).then(r=>{s||(M(Rn(r.diff??"")),ee(!1))}).catch(r=>{s||(M([]),ee(!1),xe(r instanceof Error?r.message:String(r)))}),()=>{s=!0}},[m,x,b,g,h]);const vt=o.useMemo(()=>{const s=new Map;for(const r of we)if(r.file){if(typeof r.patch=="string"){s.set(r.file,Ue(r.file,r.patch,"patch"));continue}s.set(r.file,{original:r.before??"",modified:r.after??"",contextMode:"full"})}return s},[we]),Nt=o.useMemo(()=>{const s=new Map;for(const r of z)!r.file||typeof r.patch!="string"||s.set(r.file,Ue(r.file,r.patch,"patch"));return s},[z]),j=o.useMemo(()=>{if(m==="turn"||m==="branch")return(m==="branch"?z:we).map(d=>({path:d.file??"",index:"",working_dir:En(d.status),insertions:d.additions??0,deletions:d.deletions??0,isNew:d.status==="added"})).filter(d=>d.path).sort((d,p)=>d.path.localeCompare(p.path));if(!C?.files)return[];const s=C.diffStats??{},r=m==="staged"?ot:m==="working"?at:()=>!0;return C.files.filter(r).map(l=>({...l,insertions:s[l.path]?.insertions??0,deletions:s[l.path]?.deletions??0,isNew:Fn(l)})).sort((l,d)=>l.path.localeCompare(d.path))},[m,z,we,C]),Ct=o.useMemo(()=>C?.files?C.files.filter(at).length:0,[C]),St=o.useMemo(()=>C?.files?C.files.filter(ot).length:0,[C]),Ft=we.length,Lt=C?.files?.length??0,Dt=z.length,Oe=o.useMemo(()=>j.map(s=>s.path).join("\0"),[j]);o.useEffect(()=>{const s=Oe?Oe.split("\0"):[],r=new Set(s),l=`${g??""}:${m}:${e?"collapsed":"default"}`,d=Ke.current!==l;Ke.current=l,Z(p=>{if(d){const L=e?0:vn(s.length);return new Set(s.slice(0,L))}let D=!1;const y=new Set;for(const L of p){if(!r.has(L)){D=!0;continue}y.add(L)}return D?y:p}),V(p=>{if(d)return new Set;let D=!1;const y=new Set;for(const L of p){if(!r.has(L)){D=!0;continue}y.add(L)}return D?y:p})},[m,Oe,g,e]);const Xe=o.useCallback(()=>{ce.current=null;const s=ae.current;if(!s)return;const r=s.getBoundingClientRect(),l=r.top-it,d=r.bottom+it,p={},D=[];for(const[y,L]of ye.current){if(!L)continue;const E=L.getBoundingClientRect();D.push({path:y,top:E.top}),O.has(y)&&(E.bottom<l||E.top>d||(p[y]=!0))}Be.current=et(r.top,D),V(y=>{let L=!1;const E=new Set(y);for(const Ye of Object.keys(p))E.has(Ye)||(E.add(Ye),L=!0);return L?E:y})},[O]),T=o.useCallback(()=>{typeof window>"u"||ce.current===null&&(ce.current=window.requestAnimationFrame(Xe))},[Xe]);o.useEffect(()=>{const s=ae.current;if(s)return T(),s.addEventListener("scroll",T,{passive:!0}),window.addEventListener("resize",T),()=>{s.removeEventListener("scroll",T),window.removeEventListener("resize",T),ce.current!==null&&(window.cancelAnimationFrame(ce.current),ce.current=null)}},[j,O,T]);const ze=o.useCallback(s=>{const r=ke[s.path];if(r)return r;if(G==="inline")return"inline";if(G==="side-by-side")return"side-by-side";const l=w<yn;return s.isNew||l?"inline":"side-by-side"},[ke,G,w]),Qe=o.useMemo(()=>j.length===0?null:j.every(s=>ze(s)==="side-by-side")?"side-by-side":"inline",[j,ze]);o.useEffect(()=>{g&&(H(g),fe(g,h))},[g,H,fe,h]),o.useEffect(()=>{if(g)return Jt.onGitRefreshHint(s=>{lt(s.directory)===lt(g)&&(s.paths?.length&&(We.current=qe()??Be.current,Ce(g,s.paths),oe(r=>{const l=new Map(r);for(const d of s.paths??[])l.set(d,(l.get(d)??0)+1);return l})),me(g,h,{silent:!0}))})},[qe,Ce,g,me,h]),o.useLayoutEffect(()=>{const s=We.current;if(!s)return;We.current=null;const r=ae.current,l=ye.current.get(s.path);if(!r||!l)return;const d=r.getBoundingClientRect().top,p=l.getBoundingClientRect().top-d;r.scrollTop=mn(r.scrollTop,s.topOffset,p,r.scrollHeight-r.clientHeight),Be.current=s},[Fe]),o.useEffect(()=>{m!=="all"&&!f||X&&(f&&q(f),W(X),re(f==="staged"||!f&&De),F(null),le.current=!0,te.current=X,de(X),P(s=>s+1))},[m,de,X,f,De,F]),o.useEffect(()=>{if(m==="all")return;const s=N?.trim();s&&(W(s),re(m==="staged"),le.current=!0,te.current=s,de(s),P(r=>r+1))},[m,de,N]),o.useEffect(()=>{if(!Y)return;j.some(r=>r.path===Y)||(W(null),re(!1))},[j,Y]);const kt=o.useCallback((s,r)=>{const l=ye.current;r?l.set(s,r):l.delete(s),T()},[T]),Rt=o.useCallback((s,r)=>{ue(),Z(l=>{const d=l.has(s);if(r===d)return l;const p=new Set(l);return r?p.add(s):p.delete(s),p}),r||V(l=>{if(!l.has(s))return l;const d=new Set(l);return d.delete(s),d}),T()},[ue,T]),Et=o.useCallback(()=>{ue(),Z(s=>s.size>0?new Set:new Set(j.map(r=>r.path))),V(new Set),T()},[ue,j,T]),Ae=o.useCallback(s=>{const r=ye.current.get(s),l=ae.current;if(!r||!l)return!1;const d=r.getBoundingClientRect().top-l.getBoundingClientRect().top;return l.scrollTo({top:l.scrollTop+d,behavior:"auto"}),!0},[]);o.useEffect(()=>{if(!te.current)return;let r=0;const l=20;let d=!1;const p=(y=!0)=>{d||(d=!0,te.current=null,le.current=!1,y&&U(null),k.current!==null&&(window.cancelAnimationFrame(k.current),k.current=null))},D=()=>{if(d){k.current=null;return}const y=te.current;if(!y){p(),k.current=null;return}if(!Ae(y)){r+=1,r<l?k.current=window.requestAnimationFrame(D):(p(),k.current=null);return}if(a&&le.current){U(y),p(!1);return}p()};return k.current=window.requestAnimationFrame(D),()=>{d=!0,k.current!==null&&(window.cancelAnimationFrame(k.current),k.current=null)}},[a,he,Ae]);const At=o.useCallback(s=>{},[]),Mt=o.useCallback(s=>{ue(),W(s),re(!1),le.current=!0,te.current=s,de(s),P(r=>r+1),Ae(s)},[ue,de,Ae]),Tt=o.useCallback(s=>{const r=s==="side-by-side"?"side-by-side":"inline";j.forEach(l=>{Re(l.path,r)})},[j,Re]),[It,Je]=o.useState(null),$t=o.useCallback(async(s,r)=>{if(!g||!s)return;Je(s);const l=ut();try{let d=null;if(r?.patch&&!r.isBinary&&!ve(s)?d=st(r.patch):r&&r.contextMode==="full"&&!r.isBinary&&!ve(s)&&(d=ct(r.original,r.modified)),d===null)try{const E=await h.getGitDiff(g,{path:s,staged:Ee,contextLines:3});d=st(E.diff)}catch{d=null}let p=r;if(d===null||!p){const E=await h.getGitFileDiff(g,{path:s,staged:Ee});p={original:E.original??"",modified:E.modified??"",isBinary:E.isBinary},Ee||pe(g,s,p,l)}const D=d??(p.isBinary||ve(s)?1:ct(p.original,p.modified)),y=Ln(g,s),L=await cn(S,y,{directory:g});if(!L.ok){ft.error(un(L.reason));return}R(g,y,D,1)}finally{Je(d=>d===s?null:d)}},[Ee,g,S,h,R,pe]),_t=()=>{if(!g)return null;const s=r=>Pe!==null?Pe:se&&r===Y;return n.jsxs("div",{className:B("flex min-w-0 flex-1 min-h-0 h-full",v?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[jt&&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:j.length})]}),n.jsx(Mn,{changedFiles:j,selectedFile:null,onSelectFile:Mt})]}),n.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:n.jsx(pt,{ref:ae,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:j.map(r=>n.jsx(_n,{directory:g,file:r,layout:ze(r),wrapLines:_e,isSelected:!1,isExpanded:O.has(r.path),isMounted:Ie.has(r.path)||r.path===ie,onSelect:At,onExpandedChange:Rt,registerSectionRef:kt,showOpenInEditorAction:i&&m!=="turn"&&m!=="branch",isOpeningInEditor:It===r.path,onOpenInEditor:(l,d)=>{$t(l,d)},staged:s(r.path),showFileActions:m!=="turn"&&m!=="branch",loadFullFiles:K,initialDiffData:m==="turn"?vt.get(r.path)??null:m==="branch"?Nt.get(r.path)??null:null},`${r.path}:${Fe.get(r.path)??0}`))})})})]})},Pt=()=>g?m!=="turn"&&I&&!C?n.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[n.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):m!=="turn"&&m!=="branch"&&J===!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."}):m==="branch"&&Le?n.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[n.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):m==="branch"&&ge?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: ${ge}`}):j.length===0?n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:m==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):_t():n.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return n.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[n.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(J!==!1||m==="turn")&&(m==="all"||m==="working"||m==="staged"||m==="turn"||m==="branch")?n.jsx(An,{scope:m,isGitRepo:J,branchAvailable:!!(x&&b),allCount:Lt,workingCount:Ct,stagedCount:St,turnCount:Ft,branchCount:Dt,onScopeChange:s=>{q(s),u?.(s)}}):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-semibold text-foreground",children:I&&!C?"Loading changes...":j.length===1?`${j.length} file changed`:`${j.length} files changed`})}),j.length>0&&n.jsxs(Ne,{variant:"ghost",size:"sm",onClick:Et,className:B("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:O.size>0?"Collapse all":"Expand all",children:[n.jsx(A,{name:"expand-up-down",className:"size-4"}),n.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:O.size>0?"Collapse all":"Expand all"})]}),j.length>0&&m!=="turn"&&m!=="branch"&&n.jsxs(Yt,{children:[n.jsx(Zt,{asChild:!0,children:n.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>Se(s=>!s),"aria-pressed":K,"aria-label":K?"Unload full files":"Load full files",className:B("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",K&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(A,{name:"file-download",className:"size-4"})})}),n.jsx(en,{children:n.jsx("p",{children:K?"Unload full files":"Load full files"})})]}),j.length>0&&n.jsx(Ne,{variant:"ghost",size:"sm",onClick:()=>$e(!be),className:B("h-5 w-5 p-0 transition-opacity",_e?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:_e?"Disable line wrap":"Enable line wrap",children:n.jsx(A,{name:"text-wrap",className:"size-4"})}),Qe&&n.jsx(mt,{mode:Qe==="side-by-side"?"side-by-side":"unified",onModeChange:Tt})]}),Pt()]})};export{Kr as DiffView};