@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
package/README.md CHANGED
@@ -22,7 +22,8 @@ Use `--api-only` for a host intended to be paired from a PiChamber desktop or mo
22
22
  ## Runtime contract
23
23
 
24
24
  - Pi session state and actions are served only through `/api/pi/*`.
25
- - PiChamber-owned UI settings, custom themes, and update metadata use `/api/pi/ui-settings`, `/api/pi/themes`, and `/api/pi/update-check`; removed `/api/config/*` and `/api/pichamber/*` aliases are not required.
25
+ - `POST /api/pi/attachments` accepts raw `application/octet-stream` bodies with bounded `X-PiChamber-Filename` and `X-PiChamber-Mime` metadata. It returns opaque attachment metadata plus `expiresAt`; filesystem paths remain private. The legacy base64 JSON body remains available for persisted clients. `DELETE /api/pi/attachments/:id` removes an unused upload. Prompt routes accept at most 20 attachment IDs and retire accepted uploads from the active 32-upload map while retaining their files until the one-hour expiry.
26
+ - PiChamber-owned UI settings, snippets, custom themes, and updates use `/api/pi/ui-settings`, `/api/pi/snippets`, `/api/pi/themes`, `/api/pi/update-check`, and `/api/pi/update-install`; removed `/api/config/*` and `/api/pichamber/*` aliases are not required. Snippets persist in the PiChamber data root (`snippets.json`) and expand through literal `#name` replacement; Pi prompt templates remain Pi-owned `/name` commands in Pi's global and trusted-project prompt directories, discovered through the active runtime's resource loader and exposed through `/api/pi/resources`, `/api/pi/resources/prompts`, and `/api/pi/commands`. Pi skills invoke as `/skill:name` (bare `/name` never invokes a skill) and extension commands use their registered `/name` (including Pi-generated suffixes); `/api/pi/commands` exposes prompts as `name`, skills as `skill:name`, and extensions under their invocation names, executed via Pi's `session.prompt()` with extension-first precedence. Snippet, prompt-template, skill, and extension-command concepts stay distinct with separate Settings pages, stores, persistence, and caches; they share only `/` autocomplete presentation. New-session starters are pinned Pi prompt templates that insert `/name ` for editing (never submit or expand in PiChamber); legacy skill starters are removed without conversion.
26
27
  - Final-only speech-to-text uses authenticated `/api/stt/*` routes and `/api/stt/ws`. Local model inference runs in a forked worker, while remote provider credentials remain in server configuration.
27
28
  - Browser and paired clients authenticate with UI sessions or scoped client credentials.
28
29
  - `connect-url` creates a one-time pairing link; credentials are not written to URLs or logs.
package/bin/cli.js CHANGED
@@ -195,7 +195,7 @@ async function main() {
195
195
  const { command, subcommand, tunnelAction, startupAction, options, removedFlagErrors, helpRequested, versionRequested } = parsed;
196
196
  activeCommandOptions = options;
197
197
 
198
- if (versionRequested) {
198
+ if (versionRequested || command === 'version') {
199
199
  if (isJsonMode(options)) {
200
200
  printJson({ version: PACKAGE_JSON.version });
201
201
  } else {
@@ -245,7 +245,7 @@ async function main() {
245
245
  }
246
246
 
247
247
  if (!commands[command]) {
248
- const knownCommands = ['serve', 'stop', 'restart', 'status', 'tunnel', 'startup', 'logs', 'update'];
248
+ const knownCommands = ['serve', 'stop', 'restart', 'status', 'tunnel', 'startup', 'logs', 'update', 'version'];
249
249
  const suggestion = findClosestMatch(command, knownCommands);
250
250
  const hint = suggestion ? ` Did you mean '${suggestion}'?` : '';
251
251
  if (isJsonMode(options)) {
package/bin/cli.test.js CHANGED
@@ -4,7 +4,7 @@ import os from 'os';
4
4
  import path from 'path';
5
5
  import { createServer } from 'http';
6
6
  import net from 'net';
7
- import { spawn } from 'child_process';
7
+ import { spawn, spawnSync } from 'child_process';
8
8
  import { pathToFileURL } from 'url';
9
9
 
10
10
  import { isModuleCliExecution, normalizeCliEntryPath } from './cli-entry.js';
@@ -331,6 +331,79 @@ describe('cli args', () => {
331
331
  });
332
332
 
333
333
  describe('startup enable command helper', () => {
334
+ it('collects LAN, port, and generated-password choices interactively', async () => {
335
+ const { collectInteractiveStartupOptions } = await import('./lib/commands-startup.js');
336
+ const answers = ['lan', '8080', 'generate', true];
337
+ const prompts = {
338
+ select: async () => answers.shift(),
339
+ text: async () => answers.shift(),
340
+ password: async () => answers.shift(),
341
+ confirm: async () => answers.shift(),
342
+ isCancel: () => false,
343
+ cancel: () => {},
344
+ };
345
+
346
+ const result = await collectInteractiveStartupOptions({ port: 3000 }, prompts);
347
+
348
+ expect(result).toMatchObject({
349
+ host: '0.0.0.0',
350
+ lan: true,
351
+ port: 8080,
352
+ explicitPort: true,
353
+ uiPassword: '',
354
+ explicitUiPassword: true,
355
+ });
356
+ });
357
+
358
+ it('collects and confirms a user-entered password', async () => {
359
+ const { collectInteractiveStartupOptions } = await import('./lib/commands-startup.js');
360
+ const answers = ['local', '3000', 'enter', 'secret', 'secret', true];
361
+ const prompts = {
362
+ select: async () => answers.shift(),
363
+ text: async () => answers.shift(),
364
+ password: async () => answers.shift(),
365
+ confirm: async () => answers.shift(),
366
+ isCancel: () => false,
367
+ cancel: () => {},
368
+ };
369
+
370
+ const result = await collectInteractiveStartupOptions({ port: 3000 }, prompts);
371
+
372
+ expect(result).toMatchObject({
373
+ port: 3000,
374
+ uiPassword: 'secret',
375
+ explicitUiPassword: true,
376
+ });
377
+ expect(result.host).toBe('127.0.0.1');
378
+ expect(result.lan).toBe(false);
379
+ });
380
+
381
+ it('cancels interactive setup without returning service options', async () => {
382
+ const { collectInteractiveStartupOptions } = await import('./lib/commands-startup.js');
383
+ const cancelled = Symbol('cancelled');
384
+ let cancellationMessage = '';
385
+ const prompts = {
386
+ select: async () => cancelled,
387
+ text: async () => '',
388
+ password: async () => '',
389
+ confirm: async () => false,
390
+ isCancel: (value) => value === cancelled,
391
+ cancel: (message) => { cancellationMessage = message; },
392
+ };
393
+
394
+ await expect(collectInteractiveStartupOptions({ port: 3000 }, prompts)).resolves.toBeNull();
395
+ expect(cancellationMessage).toBe('Startup setup cancelled.');
396
+ });
397
+
398
+ it('keeps flag-driven startup enable non-interactive', async () => {
399
+ const { hasExplicitStartupConfiguration } = await import('./lib/commands-startup.js');
400
+
401
+ expect(hasExplicitStartupConfiguration({ explicitPort: true })).toBe(true);
402
+ expect(hasExplicitStartupConfiguration({ lan: true })).toBe(true);
403
+ expect(hasExplicitStartupConfiguration({ explicitUiPassword: true })).toBe(true);
404
+ expect(hasExplicitStartupConfiguration({ port: 3000 })).toBe(false);
405
+ });
406
+
334
407
  it('formats stored serve flags for a local port', async () => {
335
408
  const { formatStartupServeCommand } = await import('./lib/cli-startup.js');
336
409
  expect(formatStartupServeCommand({ port: 8080 })).toBe('pichamber serve --foreground --port 8080');
@@ -367,6 +440,30 @@ describe('startup enable command helper', () => {
367
440
  });
368
441
  });
369
442
 
443
+ describe('version command', () => {
444
+ it('prints the installed package version', () => {
445
+ const packageJson = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
446
+ const result = spawnSync(process.execPath, [new URL('./cli.js', import.meta.url).pathname, 'version'], {
447
+ encoding: 'utf8',
448
+ });
449
+
450
+ expect(result.status).toBe(0);
451
+ expect(result.stdout.trim()).toBe(packageJson.version);
452
+ expect(result.stderr).toBe('');
453
+ });
454
+
455
+ it('prints the installed package version as JSON', () => {
456
+ const packageJson = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
457
+ const result = spawnSync(process.execPath, [new URL('./cli.js', import.meta.url).pathname, 'version', '--json'], {
458
+ encoding: 'utf8',
459
+ });
460
+
461
+ expect(result.status).toBe(0);
462
+ expect(JSON.parse(result.stdout)).toMatchObject({ status: 'ok', version: packageJson.version });
463
+ expect(result.stderr).toBe('');
464
+ });
465
+ });
466
+
370
467
  describe('cli API target resolution', () => {
371
468
  it('uses an explicit port without discovery', async () => {
372
469
  await expect(resolveTargetPort(
@@ -8,8 +8,9 @@ This directory contains non-entrypoint PiChamber CLI implementation. `../cli.js`
8
8
  - `commands-lifecycle.js`: stop and restart behavior.
9
9
  - `commands-status.js`: running-instance and tunnel status presentation.
10
10
  - `commands-logs.js`: log discovery, tailing, and follow behavior.
11
- - `commands-startup.js`: native startup service management. `startup enable` stores serve flags (`--port`, `--lan`/`--host`, `--ui-password`, `--api-only`) in the login service. `pichamber startup --help` documents those flags. LAN binds require a UI password, matching `pichamber serve`.
11
+ - `commands-startup.js`: native startup service management. Interactive `startup enable` walks through access, port, authentication, and confirmation when no setup flags are supplied. Flag-driven, non-TTY, `--quiet`, and `--json` runs remain non-interactive. The command stores serve flags (`--port`, `--lan`/`--host`, `--ui-password`, `--api-only`) in the native service. Re-running enable rewrites and restarts a systemd unit so the new settings take effect immediately. LAN binds require a UI password, matching `pichamber serve`.
12
12
  - `commands-connect-url.js`: authenticated direct/relay pairing links.
13
+ - `pichamber version` and `pichamber --version`: print the installed package version; `--json` returns the same value as JSON.
13
14
  - `commands-update.js`: package update and restart coordination. Updates only a global install owned by the running CLI. A Linux user systemd unit is restarted in place; the command does not spawn a replacement server on the same port.
14
15
  - `commands-tunnel.js`: tunnel lifecycle and profile management.
15
16
 
@@ -492,6 +492,7 @@ COMMANDS:
492
492
  logs Tail PiChamber logs
493
493
  connect-url Generate URL/QR for connecting another client
494
494
  update Check for and install updates
495
+ version Show the installed PiChamber version
495
496
 
496
497
  OPTIONS:
497
498
  -p, --port Web server port (default: ${DEFAULT_PORT})
@@ -526,6 +527,7 @@ EXAMPLES:
526
527
  # Login service on LAN at 0.0.0.0:3002
527
528
  pichamber tunnel help # Show tunnel lifecycle help
528
529
  pichamber logs # Follow logs for latest running instance
530
+ pichamber version # Show the installed version
529
531
  `);
530
532
  }
531
533
 
@@ -537,14 +539,15 @@ USAGE:
537
539
  pichamber startup <SUBCOMMAND> [OPTIONS]
538
540
 
539
541
  DESCRIPTION:
540
- Installs a user-login service that runs pichamber serve --foreground.
541
- Flags passed to startup enable are stored in that service. Re-run enable
542
- to replace the stored command.
542
+ Installs a native startup service that runs pichamber serve --foreground.
543
+ In an interactive terminal, enable walks through access, port, and password
544
+ setup. Supplied flags keep the command non-interactive. Re-run enable to
545
+ replace the stored command.
543
546
 
544
547
  SUBCOMMANDS:
545
548
  status Show startup integration status
546
- enable Install and start native user startup integration
547
- disable Stop and remove native user startup integration
549
+ enable Configure, install, and start native startup integration
550
+ disable Stop and remove native startup integration
548
551
 
549
552
  ENABLE FLAGS:
550
553
  These become the serve command the login service runs.
@@ -317,6 +317,14 @@ function runStartupCommand(command, args, options = {}) {
317
317
  return result;
318
318
  }
319
319
 
320
+ function activateSystemdStartupService(isRoot, run = runStartupCommand) {
321
+ const userArgs = isRoot ? [] : ['--user'];
322
+ run('systemctl', [...userArgs, 'daemon-reload']);
323
+ run('systemctl', [...userArgs, 'enable', 'pichamber.service']);
324
+ // restart also starts an inactive unit and guarantees rewritten settings take effect.
325
+ run('systemctl', [...userArgs, 'restart', 'pichamber.service']);
326
+ }
327
+
320
328
  function getStartupStatus() {
321
329
  const paths = getStartupServicePaths();
322
330
  if (!paths.servicePath) {
@@ -389,13 +397,7 @@ function enableStartupService(options = {}) {
389
397
  writeStartupEnvFile(serveOptions, { quoteValue: systemdEnvFileQuote });
390
398
  fs.mkdirSync(path.dirname(paths.servicePath), { recursive: true, mode: 0o700 });
391
399
  fs.writeFileSync(paths.servicePath, buildSystemdUserService(serveOptions), { mode: 0o600 });
392
- if (isRoot) {
393
- runStartupCommand('systemctl', ['daemon-reload']);
394
- runStartupCommand('systemctl', ['enable', '--now', 'pichamber.service']);
395
- } else {
396
- runStartupCommand('systemctl', ['--user', 'daemon-reload']);
397
- runStartupCommand('systemctl', ['--user', 'enable', '--now', 'pichamber.service']);
398
- }
400
+ activateSystemdStartupService(isRoot);
399
401
  return finish(getStartupStatus());
400
402
  }
401
403
 
@@ -453,6 +455,7 @@ function disableStartupService() {
453
455
 
454
456
  export {
455
457
  getStartupServicePaths,
458
+ activateSystemdStartupService,
456
459
  getStartupStatus,
457
460
  enableStartupService,
458
461
  disableStartupService,
@@ -4,6 +4,34 @@ import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { mkdtempSync, rmSync } from 'node:fs';
6
6
 
7
+ describe('systemd startup activation', () => {
8
+ it('enables and restarts a system service so updated settings take effect', async () => {
9
+ const { activateSystemdStartupService } = await import('./cli-startup.js');
10
+ const calls = [];
11
+
12
+ activateSystemdStartupService(true, (command, args) => calls.push([command, args]));
13
+
14
+ expect(calls).toEqual([
15
+ ['systemctl', ['daemon-reload']],
16
+ ['systemctl', ['enable', 'pichamber.service']],
17
+ ['systemctl', ['restart', 'pichamber.service']],
18
+ ]);
19
+ });
20
+
21
+ it('enables and restarts a user service so updated settings take effect', async () => {
22
+ const { activateSystemdStartupService } = await import('./cli-startup.js');
23
+ const calls = [];
24
+
25
+ activateSystemdStartupService(false, (command, args) => calls.push([command, args]));
26
+
27
+ expect(calls).toEqual([
28
+ ['systemctl', ['--user', 'daemon-reload']],
29
+ ['systemctl', ['--user', 'enable', 'pichamber.service']],
30
+ ['systemctl', ['--user', 'restart', 'pichamber.service']],
31
+ ]);
32
+ });
33
+ });
34
+
7
35
  describe('startup service paths', () => {
8
36
  const originalPlatform = process.platform;
9
37
  const originalGetuid = process.getuid;
@@ -1,14 +1,150 @@
1
1
  import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
2
- import { getStartupStatus, enableStartupService, disableStartupService, formatStartupServeCommand } from './cli-startup.js';
2
+ import { getStartupStatus, enableStartupService, disableStartupService, formatStartupServeCommand, getStartupServicePaths } from './cli-startup.js';
3
+ import { hasUiPasswordConfigured } from './cli-network.js';
3
4
  import {
4
5
  intro as clackIntro,
5
6
  outro as clackOutro,
7
+ cancel as clackCancel,
8
+ isCancel,
9
+ select,
10
+ text,
11
+ password as passwordPrompt,
12
+ confirm,
13
+ canPrompt,
6
14
  isJsonMode,
7
15
  isQuietMode,
8
16
  printJson,
9
17
  logStatus,
10
18
  } from '../cli-output.js';
11
19
 
20
+ const promptApi = { select, text, password: passwordPrompt, confirm, isCancel, cancel: clackCancel };
21
+
22
+ function validatePort(value) {
23
+ const normalized = String(value ?? '').trim();
24
+ if (!/^\d+$/.test(normalized)) return 'Enter a port between 1 and 65535.';
25
+ const port = Number(normalized);
26
+ return port >= 1 && port <= 65535 ? undefined : 'Enter a port between 1 and 65535.';
27
+ }
28
+
29
+ function hasExplicitStartupConfiguration(options) {
30
+ return options.explicitPort === true
31
+ || options.lan === true
32
+ || typeof options.host === 'string'
33
+ || options.explicitUiPassword === true
34
+ || options.apiOnly === true;
35
+ }
36
+
37
+ async function collectInteractiveStartupOptions(options, prompts = promptApi) {
38
+ const ask = async (method, config) => {
39
+ const answer = await prompts[method](config);
40
+ if (prompts.isCancel(answer)) {
41
+ prompts.cancel('Startup setup cancelled.');
42
+ return { cancelled: true };
43
+ }
44
+ return { answer };
45
+ };
46
+
47
+ const accessResult = await ask('select', {
48
+ message: 'Where should PiChamber be accessible?',
49
+ options: [
50
+ { value: 'local', label: 'This machine only', hint: 'recommended' },
51
+ { value: 'lan', label: 'Local network', hint: 'other devices on your LAN or Wi-Fi' },
52
+ { value: 'custom', label: 'Custom bind address' },
53
+ ],
54
+ initialValue: 'local',
55
+ });
56
+ if (accessResult.cancelled) return null;
57
+
58
+ let host = '127.0.0.1';
59
+ let lan = false;
60
+ if (accessResult.answer === 'lan') {
61
+ host = '0.0.0.0';
62
+ lan = true;
63
+ } else if (accessResult.answer === 'custom') {
64
+ const hostResult = await ask('text', {
65
+ message: 'Bind address',
66
+ placeholder: '127.0.0.1',
67
+ initialValue: '127.0.0.1',
68
+ validate: (value) => String(value ?? '').trim().length > 0 ? undefined : 'Enter a bind address.',
69
+ });
70
+ if (hostResult.cancelled) return null;
71
+ host = String(hostResult.answer).trim();
72
+ }
73
+
74
+ const portResult = await ask('text', {
75
+ message: 'Port',
76
+ initialValue: String(options.port),
77
+ validate: validatePort,
78
+ });
79
+ if (portResult.cancelled) return null;
80
+ const port = Number(String(portResult.answer).trim());
81
+
82
+ const networkExposed = accessResult.answer !== 'local';
83
+ const configuredPassword = hasUiPasswordConfigured(options.uiPassword);
84
+ const authOptions = [
85
+ ...(configuredPassword ? [{ value: 'configured', label: 'Use the configured password' }] : []),
86
+ { value: 'enter', label: 'Enter a password' },
87
+ { value: 'generate', label: 'Generate a secure password' },
88
+ ...(!networkExposed && !configuredPassword ? [{ value: 'none', label: 'No password', hint: 'local access only' }] : []),
89
+ ];
90
+ const authResult = await ask('select', {
91
+ message: networkExposed ? 'Choose a required UI password' : 'Protect the UI with a password?',
92
+ options: authOptions,
93
+ initialValue: configuredPassword ? 'configured' : (networkExposed ? 'generate' : 'none'),
94
+ });
95
+ if (authResult.cancelled) return null;
96
+
97
+ let uiPassword = configuredPassword ? options.uiPassword : undefined;
98
+ let explicitUiPassword = false;
99
+ if (authResult.answer === 'enter') {
100
+ const passwordResult = await ask('password', {
101
+ message: 'UI password',
102
+ validate: (value) => String(value ?? '').length > 0 ? undefined : 'Enter a password.',
103
+ });
104
+ if (passwordResult.cancelled) return null;
105
+ uiPassword = String(passwordResult.answer);
106
+ const confirmationResult = await ask('password', {
107
+ message: 'Confirm UI password',
108
+ validate: (value) => value === uiPassword ? undefined : 'Passwords do not match.',
109
+ });
110
+ if (confirmationResult.cancelled) return null;
111
+ explicitUiPassword = true;
112
+ } else if (authResult.answer === 'generate') {
113
+ uiPassword = '';
114
+ explicitUiPassword = true;
115
+ } else if (authResult.answer === 'none') {
116
+ uiPassword = undefined;
117
+ }
118
+
119
+ const paths = getStartupServicePaths();
120
+ logStatus('info', 'Review startup service', [
121
+ `Access: ${accessResult.answer === 'local' ? 'this machine only' : host}`,
122
+ `Port: ${port}`,
123
+ `Authentication: ${authResult.answer === 'none' ? 'disabled' : authResult.answer === 'generate' ? 'generated password' : 'enabled'}`,
124
+ `Service: ${paths.scope === 'system' ? 'system' : paths.scope === 'user' ? 'user' : paths.platform}`,
125
+ ].join('\n'));
126
+
127
+ const confirmResult = await ask('confirm', {
128
+ message: 'Install and start this service?',
129
+ initialValue: true,
130
+ });
131
+ if (confirmResult.cancelled) return null;
132
+ if (confirmResult.answer !== true) {
133
+ prompts.cancel('Startup setup cancelled.');
134
+ return null;
135
+ }
136
+
137
+ return {
138
+ ...options,
139
+ port,
140
+ explicitPort: true,
141
+ host,
142
+ lan,
143
+ uiPassword,
144
+ explicitUiPassword,
145
+ };
146
+ }
147
+
12
148
  async function startupCommand(options, action = 'status') {
13
149
  const normalized = typeof action === 'string' ? action.trim().toLowerCase() : 'status';
14
150
  if (!['status', 'enable', 'disable'].includes(normalized)) {
@@ -18,9 +154,16 @@ async function startupCommand(options, action = 'status') {
18
154
  );
19
155
  }
20
156
 
157
+ let resolvedOptions = options;
158
+ if (normalized === 'enable' && canPrompt(options) && !hasExplicitStartupConfiguration(options)) {
159
+ clackIntro('PiChamber Startup Setup');
160
+ resolvedOptions = await collectInteractiveStartupOptions(options);
161
+ if (!resolvedOptions) return;
162
+ }
163
+
21
164
  let status;
22
165
  if (normalized === 'enable') {
23
- status = enableStartupService(options);
166
+ status = enableStartupService(resolvedOptions);
24
167
  } else if (normalized === 'disable') {
25
168
  status = disableStartupService();
26
169
  } else {
@@ -32,7 +175,7 @@ async function startupCommand(options, action = 'status') {
32
175
  : undefined;
33
176
  const { generatedUiPassword: _generatedUiPassword, ...publicStatus } = status;
34
177
  void _generatedUiPassword;
35
- const serveCommand = normalized === 'enable' ? formatStartupServeCommand(options) : undefined;
178
+ const serveCommand = normalized === 'enable' ? formatStartupServeCommand(resolvedOptions) : undefined;
36
179
  const result = {
37
180
  action: normalized,
38
181
  ...publicStatus,
@@ -46,8 +189,11 @@ async function startupCommand(options, action = 'status') {
46
189
  );
47
190
  }
48
191
  if (normalized === 'enable' && result.activeState === 'failed') {
192
+ const journalCommand = result.scope === 'system'
193
+ ? 'journalctl -u pichamber.service -n 80 --no-pager'
194
+ : 'journalctl --user -u pichamber.service -n 80 --no-pager';
49
195
  throw new TunnelCliError(
50
- 'Startup service was installed but failed to start. Run `journalctl --user -u pichamber.service -n 80 --no-pager` for details.',
196
+ `Startup service was installed but failed to start. Run \`${journalCommand}\` for details.`,
51
197
  EXIT_CODE.GENERAL_ERROR
52
198
  );
53
199
  }
@@ -61,7 +207,7 @@ async function startupCommand(options, action = 'status') {
61
207
  return;
62
208
  }
63
209
 
64
- clackIntro('PiChamber Startup');
210
+ if (resolvedOptions === options) clackIntro('PiChamber Startup');
65
211
  logStatus(result.enabled ? 'success' : 'info', `startup ${result.enabled ? 'enabled' : 'disabled'}`, result.servicePath || undefined);
66
212
  if (typeof result.activeState === 'string') {
67
213
  logStatus(result.active ? 'success' : result.activeState === 'failed' ? 'error' : 'warning', `service ${result.activeState}`);
@@ -76,4 +222,4 @@ async function startupCommand(options, action = 'status') {
76
222
  clackOutro(normalized === 'status' ? 'status complete' : `${normalized} complete`);
77
223
  }
78
224
 
79
- export { startupCommand };
225
+ export { startupCommand, collectInteractiveStartupOptions, hasExplicitStartupConfiguration, validatePort };
@@ -1 +1 @@
1
- import{R as e,j as h}from"./vendor-react-DYyjh7Q0.js";import{D as E}from"./vendor-react-drawio-Boqanm0j.js";import{m as x}from"./index-ChFxkws4.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
1
+ import{R as e,j as h}from"./vendor-react-B5Z1Mdn3.js";import{D as E}from"./vendor-react-drawio-BYDptOsj.js";import{c as x}from"./index-CaP8oFLB.js";const D='<mxfile><diagram id="new" name="Page-1"><mxGraphModel dx="0" dy="0" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0"><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>';function g(){if(typeof document>"u")return!1;const o=document.documentElement.getAttribute("data-theme");return o==="dark"||!o&&window.matchMedia("(prefers-color-scheme: dark)").matches}const X=e.forwardRef(function({xml:t,readOnly:a,className:R,onChange:c},v){const s=e.useRef(t),i=e.useRef(null),m=e.useRef(!1),[n,k]=e.useState(g),u=e.useRef(t),d=e.useRef(t);d.current!==t&&(d.current=t,u.current=t,s.current=t);const f=e.useRef(n);f.current!==n&&(f.current=n,u.current=s.current);const l=e.useRef(null);e.useEffect(()=>{const r=()=>k(g());r();const p=new MutationObserver(r);return p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>p.disconnect()},[]),e.useEffect(()=>{const r=setTimeout(()=>{l.current?.querySelector(".diagrams-iframe")?.focus()},600);return()=>clearTimeout(r)},[]),e.useImperativeHandle(v,()=>({getXml:()=>s.current}));const b=e.useCallback(()=>{!t&&!m.current&&(m.current=!0,setTimeout(()=>{i.current?.template({})},500))},[t]),w=e.useCallback(r=>{s.current=r.xml,c?.(r.xml)},[c]);return h.jsx("div",{ref:l,className:x("h-full w-full",R),children:h.jsx(E,{ref:i,xml:u.current||D,autosave:!0,urlParameters:{ui:a?"simple":n?"dark":"kennedy",spin:!0,libraries:!a,chrome:a,nav:a,layers:a,noSaveBtn:!0,noExitBtn:!0,saveAndExit:!1},onLoad:b,onAutoSave:w},n?"dark":"light")})});export{X as D};
@@ -0,0 +1 @@
1
+ import{R as r,j as t}from"./vendor-react-B5Z1Mdn3.js";import{u as a}from"./index-CaP8oFLB.js";import{j as v,I as m}from"./useAppFontEffects-CYzYRbLp.js";import{D as j}from"./DiagramEditor-YPSKccgo.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-B818u-_c.js";import"./vendor-dnd-kit-core-CP8ck10N.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-B-Icjoj4.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-DS_4W5G4.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-BUygY0oN.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-react-drawio-BYDptOsj.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};
@@ -0,0 +1,18 @@
1
+ import{R as i,j as e}from"./vendor-react-B5Z1Mdn3.js";import{c as J,u as Q,w as Qe,n as Be}from"./index-CaP8oFLB.js";import{b3 as Ft,D as Nt,a as vt,I as U,b as Ct,b4 as Lt,b5 as Ne,a$ as Dt,aa as kt,ao as Ye,b6 as Je,aP as Rt,p as ve,U as Ce,j as Ze,Q as ne,t as et,aS as tt,aA as Et,b7 as At,b8 as Tt,aB as Mt,b9 as It,ba as $t,bb as Pt,bc as _t,k as Bt,bd as Wt,be as Ot,E as zt,F as Gt,G as Ht}from"./useAppFontEffects-CYzYRbLp.js";import{d as nt,P as Ut,i as We,a as Oe,b as Vt}from"./gitStatusPredicates-CRmbLl-x.js";import{p as Kt}from"./VirtualizedFileDiff-CA8hQyz9.js";import{v as qt,g as Xt}from"./contextFileOpenGuard-CZSqdEHk.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-vkqQ2P9o.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-B818u-_c.js";import"./vendor-dnd-kit-core-CP8ck10N.js";import"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-dnd-kit-sortable-B-Icjoj4.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-DS_4W5G4.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-DYppkHEk.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-BUygY0oN.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./web-components-C2cMNPqE.js";import"./computeVirtualFileMetrics-9LNCLvAG.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"./runtimeEndpointReset-D3AZYuoF.js";import"./SessionUnreadDot-bT_0MixU.js";import"./permissionStore-iKN1K2_x.js";import"./appThemeRegistry-gegrE2dq.js";import"./registerCustomTheme-DmolaWWZ.js";import"./isDiffPlainText-YYyZNTdb.js";import"./vendor-diff-C3JhlQdm.js";function Qt(s,n=10){const t=[];let r;for(const l of s.split(`
2
+ `)){const p=l.match(Ft);if(p!=null){r!=null&&(r.hunkLines.length>0&&(De(r,n,"trailing"),Ae(r,t)),r=void 0);const d=parseInt(p[3]),x=parseInt(p[1]),h=parseInt(p[4]??"1"),c=parseInt(p[2]??"1");isNaN(d)||isNaN(x)||isNaN(h)||isNaN(c)?t.push(l):r={additionStart:d,deletionStart:x,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(r==null){t.push(l);continue}if(l.startsWith(" "))r.contextLines.push(l);else if(l!==""){if(r.hunkLines.length>0&&r.contextLines.length>n*2){const d=r.contextLines.length-n*2,x=r.contextLines.slice(-n);De(r,n,"trailing");const{additionCount:h,deletionCount:c}=r;Ae(r,t),r={additionStart:r.additionStart+h+d,deletionStart:r.deletionStart+c+d,deletionCount:0,additionCount:0,contextLines:x,hunkLines:[]}}De(r,n,r.hunkLines.length===0?"leading":"before-change"),r.hunkLines.push(l),l.startsWith("+")?r.additionCount+=1:l.startsWith("-")&&(r.deletionCount+=1)}}r!=null&&r.hunkLines.length>0&&(De(r,n,"trailing"),Ae(r,t));const a=t.join(`
3
+ `);return s.endsWith(`
4
+ `)?`${a}
5
+ `:a}function De(s,n,t){if(t==="leading"&&s.contextLines.length>n){const r=s.contextLines.length-n;s.contextLines.splice(0,r),s.additionStart+=r,s.deletionStart+=r}return t==="trailing"&&s.contextLines.length>n&&(s.contextLines.length=n),s.contextLines.length>0&&(s.hunkLines.push(...s.contextLines),s.additionCount+=s.contextLines.length,s.deletionCount+=s.contextLines.length,s.contextLines.length=0),s}function Ae(s,n){n.push(`@@ -${ze(s.deletionStart,s.deletionCount)} +${ze(s.additionStart,s.additionCount)} @@`),n.push(...s.hunkLines)}function ze(s,n){return n===1?`${s}`:`${s},${n}`}const Yt=i.memo(function({scope:n,isGitRepo:t,branchAvailable:r,allCount:a,workingCount:l,stagedCount:p,turnCount:d,branchCount:x,onScopeChange:h}){const[c,f]=i.useState(!1),b=n==="all"?a:n==="staged"?p:n==="turn"?d:n==="branch"?x:l,L=n==="staged"?"Staged":n==="turn"?"Last turn":n==="branch"?"Branch":n==="all"?"All":"Changed";return e.jsxs(Nt,{open:c,onOpenChange:f,children:[e.jsx(vt,{asChild:!0,children:e.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:[e.jsxs("span",{className:"whitespace-nowrap",children:[L,e.jsxs("span",{className:"diff-toolbar__scope-count",children:[": ",b]})]}),e.jsx(U,{name:"arrow-down-s",className:"size-4 flex-shrink-0 opacity-60"})]})}),e.jsx(Ct,{align:"start",className:"w-40",children:e.jsxs(Lt,{value:n,onValueChange:u=>{(u==="all"||u==="working"||u==="staged"||u==="turn"||u==="branch")&&(h?.(u),f(!1))},children:[t!==!1?e.jsx(Ne,{value:"all",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"All"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:a})]})}):null,t!==!1?e.jsx(Ne,{value:"working",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Changed"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:l})]})}):null,t!==!1?e.jsx(Ne,{value:"staged",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Staged"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:p})]})}):null,e.jsx(Ne,{value:"turn",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Last turn"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:d})]})}),r?e.jsx(Ne,{value:"branch",children:e.jsxs("span",{className:"flex min-w-0 flex-1 items-center justify-between gap-3",children:[e.jsx("span",{children:"Branch"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:x})]})}):null]})})]})}),Jt=64,Zt=3,ae=new Map,en=(s,n,t=Zt)=>{const r=`${s}\0${t}\0${n}`,a=ae.get(r);if(a)return ae.delete(r),ae.set(r,a),a;const l=nn(n),p=l?Dt(Qt(n,t),{oldFile:{name:s,contents:l.before},newFile:{name:s,contents:l.after}})??He(s):kt(tn(s,n))[0]?.files[0]??He(s);for(ae.set(r,p);ae.size>Jt;){const d=ae.keys().next().value;if(!d)break;ae.delete(d)}return p},tn=(s,n)=>!n.trim()||n.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(n)?n:`Index: ${s}
6
+ ===================================================================
7
+ --- ${s}
8
+ +++ ${s}
9
+ ${n}`,nn=s=>{if(!s.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(s))return;const n=[...s.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(n.length!==1)return;const t=n[0],r=Number.parseInt(t[1]??"",10),a=Number.parseInt(t[2]??"",10);if(r>1||a>1||!Number.isFinite(r)||!Number.isFinite(a))return;const l=(t.index??0)+t[0].length,p=s.slice(l),d=[],x=[];let h;for(const c of p.split(/\r?\n/)){if(c.startsWith("diff --git ")||c.startsWith("@@ "))break;if(c.startsWith("\\")){if(h==="-"||h===" "){const f=d.at(-1);f&&(f.newline=!1)}if(h==="+"||h===" "){const f=x.at(-1);f&&(f.newline=!1)}continue}if(c.startsWith("-")){d.push({text:c.slice(1),newline:!0}),h="-";continue}if(c.startsWith("+")){x.push({text:c.slice(1),newline:!0}),h="+";continue}c.startsWith(" ")&&(d.push({text:c.slice(1),newline:!0}),x.push({text:c.slice(1),newline:!0}),h=" ")}return{before:Ge(d),after:Ge(x)}},Ge=s=>s.map(n=>n.text+(n.newline?`
10
+ `:"")).join(""),He=s=>Kt({name:s,contents:""},{name:s,contents:""}),sn=s=>/^Binary files .+ differ$/m.test(s)||/^GIT binary patch$/m.test(s),Me=(s,n,t)=>sn(n)?{original:"",modified:"",isBinary:!0,patch:n,contextMode:t}:{original:"",modified:"",patch:n,fileDiff:en(s,n),contextMode:t},st=(s,n,t)=>{const r=s??0,a=n??0;return!r&&!a?null:e.jsxs("span",{className:J("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",t?.className),children:[r?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",r]}):null,a?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a]}):null]})},rn=i.memo(function({changedFiles:n,selectedFile:t,onSelectFile:r}){return n.length===0?null:e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:n.map(a=>{const l=nt(a),p=t===a.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>r(a.path),className:J("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:[e.jsx(Je,{filePath:a.path,className:"h-3.5 w-3.5 flex-shrink-0"}),e.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}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:a.path,children:a.path}),st(a.insertions,a.deletions)]})},a.path)})})})}),on=i.memo(function(){return e.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Content of this file cannot be viewed."})})}),an=i.memo(function({filePath:n,diff:t,renderSideBySide:r}){const a=t.original.length>0,l=t.modified.length>0,p=r?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",d=r?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:p,children:[a&&e.jsxs("div",{className:d,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:t.original,alt:`Original: ${n}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),l&&e.jsxs("div",{className:d,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a?"Modified":"New"}),e.jsx("img",{src:t.modified,alt:`Modified: ${n}`,className:r?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),ln=i.memo(function({filePath:n,diff:t,renderSideBySide:r,wrapLines:a}){const l=i.useMemo(()=>Rt(n)||"text",[n]);return t.isBinary?e.jsx(on,{}):ve(n)?e.jsx(an,{filePath:n,diff:t,renderSideBySide:r}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(Ut,{original:t.original,modified:t.modified,fileDiff:t.fileDiff,language:l,fileName:n,renderSideBySide:r,wrapLines:a,layout:"inline"})})}),Te=({label:s,icon:n,loading:t,disabled:r,tone:a,onClick:l})=>e.jsx(Ce,{variant:"ghost",size:"sm",className:J("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:r,title:s,"aria-label":s,onClick:p=>{p.stopPropagation(),l()},children:t?e.jsx(U,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(U,{name:n,className:n==="add"?"size-4":"size-3.5"})}),cn=i.memo(function({filePath:n,staged:t,busyAction:r,disabled:a,onAction:l}){return e.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:t?e.jsx(Te,{label:`Unstage ${n}`,icon:"arrow-go-back",loading:r==="unstage",disabled:a,onClick:()=>l("unstage")}):e.jsxs(e.Fragment,{children:[e.jsx(Te,{label:`Revert changes in ${n}`,icon:"arrow-go-back",loading:r==="discard",disabled:a,tone:"failure",onClick:()=>l("discard")}),e.jsx(Te,{label:`Stage ${n}`,icon:"add",loading:r==="stage",disabled:a,tone:"success",onClick:()=>l("stage")})]})})}),rt=3,un=1e6,dn=15e3,Ue=500,fn=i.memo(function({directory:n,file:t,layout:r,wrapLines:a,isSelected:l,isExpanded:p,isMounted:d,onSelect:x,onExpandedChange:h,registerSectionRef:c,showOpenInEditorAction:f=!1,isOpeningInEditor:b=!1,onOpenInEditor:L,staged:u=!1,showFileActions:C=!0,loadFullFiles:g=!1,initialDiffData:R=null}){const{git:I}=Ze(),k=ne(i.useCallback(m=>m.directories.get(n)?.diffCache.get(t.path)??null,[n,t.path])),V=ne(m=>m.setDiff),E=ne(m=>m.fetchStatus),y=Q(m=>m.setDiffFileLayout),[w,j]=i.useState(0),[A,F]=i.useState(null),[q,N]=i.useState(!1),[_,B]=i.useState(null),[Z,se]=i.useState(!1),[P,le]=i.useState(null),[T,ee]=i.useState(null),W=i.useRef(null),ce=i.useRef(null),O=i.useMemo(()=>nt(t),[t]),re=r==="side-by-side",Y=g?"full":"patch",te=`${t.index}:${t.working_dir}:${t.insertions}:${t.deletions}`,z=i.useMemo(()=>R||(u?T:P||(k?{original:k.original,modified:k.modified,isBinary:k.isBinary,contextMode:"full"}:null)),[k,R,P,u,T]),ue=z?.contextMode===Y,ye=i.useCallback(m=>{ce.current=m,c(t.path,m)},[t.path,c]),de=i.useCallback(m=>{h(t.path,m)},[t.path,h]),fe=i.useCallback(()=>{x(t.path)},[t.path,x]);i.useEffect(()=>{u?ee(null):le(null),F(null),W.current=null},[te,u]),i.useEffect(()=>{if(!p||!d)return;if(!n||R||z&&ue){W.current=null,N(!1);return}const m=`${n}::${t.path}::${u?"staged":"unstaged"}::${te}::${Y}::${w}`;if(W.current===m)return;W.current=m,F(null),N(!0);let D=!1;const $=Qe(),je=g?un:rt,me=ve(t.path)?I.getGitFileDiff(n,{path:t.path,staged:u}):I.getGitDiff(n,{path:t.path,staged:u,contextLines:je}),ie=dn,ke=new Promise((K,G)=>{setTimeout(()=>G(new Error(`Timed out after ${ie}ms`)),ie)});return Promise.race([me,ke]).then(K=>{if(!D){if("diff"in K){const G=Me(t.path,K.diff,Y);u?ee(G):le(G)}else{const G={original:K.original??"",modified:K.modified??"",isBinary:K.isBinary,contextMode:"full"};u?ee(G):V(n,t.path,G,$)}N(!1)}}).catch(K=>{if(D)return;const G=K instanceof Error?K.message:String(K);F(G),N(!1)}),()=>{D=!0,W.current===m&&(W.current=null)}},[Y,z,ue,w,n,t.path,te,I,R,p,d,g,V,u]);const pe=i.useCallback(()=>{de(!p),fe()},[de,fe,p]),we=i.useCallback(async m=>{if(!(!n||_!==null)){B(m);try{m==="stage"?await I.stageGitFile(n,t.path):m==="unstage"?await I.unstageGitFile(n,t.path):await I.revertGitFile(n,t.path,{scope:"working"}),j(D=>D+1),await E(n,I)}catch(D){const $=m==="unstage"?"Failed to unstage changes":m==="stage"?"Failed to stage changes":"Failed to revert changes";et.error(D instanceof Error?D.message:$)}finally{B(D=>D===m?null:D)}}},[n,E,t.path,_,I]);return e.jsxs("div",{ref:ye,className:J("scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0"),children:[e.jsx("div",{className:J("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:e.jsxs("div",{role:"button",tabIndex:0,onClick:pe,onKeyDown:m=>{m.target===m.currentTarget&&(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),pe())},className:J("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:[e.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:p?e.jsx(U,{name:"arrow-down-s",className:"size-4"}):e.jsx(U,{name:"arrow-right-s",className:"size-4"})}),e.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}),e.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:t.path,children:e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Je,{filePath:t.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const m=t.path.lastIndexOf("/");if(m===-1)return e.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:t.path});const D=t.path.slice(0,m),$=t.path.slice(m+1);return e.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[e.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:D}),e.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("span",{className:"text-foreground",children:$})]})]})})()]})})]}),e.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[st(t.insertions,t.deletions),f&&L?e.jsx(Ce,{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:m=>{m.stopPropagation(),L(t.path,z)},disabled:b,children:b?e.jsx(U,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(U,{name:"edit",className:"size-3.5"})}):null,e.jsx(tt,{mode:re?"side-by-side":"unified",onModeChange:m=>{const D=m==="side-by-side"?"side-by-side":"inline";y(t.path,D)},className:"opacity-70"})]})]})}),p&&e.jsxs("div",{className:"relative overflow-hidden bg-background",children:[!d&&!A?e.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,A?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:A}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>j(m=>m+1),children:"Retry"})]}):null,d&&q&&!z&&!A?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading diff..."]}):null,d&&z&&!Z&&t.insertions+t.deletions>Ue?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:`Large diff (${t.insertions+t.deletions} changed lines)`}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Rendering may be slow. You can still view the diff by clicking below."}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>se(!0),children:"Render anyway"})]}):null,d&&z&&(Z||t.insertions+t.deletions<=Ue)?e.jsxs(e.Fragment,{children:[e.jsx(ln,{filePath:t.path,diff:z,renderSideBySide:re,wrapLines:a}),C?e.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:e.jsx("div",{className:"pointer-events-auto",children:e.jsx(cn,{filePath:t.path,staged:u,busyAction:_,disabled:_!==null,onAction:we})})}):null]}):null]})]})}),pn=1100,Ve=300,mn=s=>s<=6?s:s<=12?6:s<=25?4:2,hn=(s,n)=>Et(s,n),Ke=(s,n)=>{const t=s.split(`
11
+ `),r=n.split(`
12
+ `),a=Math.min(t.length,r.length);for(let l=0;l<a;l+=1)if(t[l]!==r[l])return l+1;return r.length>t.length?t.length+1:t.length>r.length?Math.max(1,r.length):1},gn=s=>Array.isArray(s)?s.filter(n=>!n||typeof n!="object"?!1:typeof n.file=="string"):[],xn=s=>s.split(/^diff --git /m).slice(1).flatMap(t=>{const[r=""]=t.split(`
13
+ `,1),a=r.lastIndexOf(" b/");if(a<=2)return[];const l=r.slice(2,a),p=r.slice(a+3).trim(),d=`diff --git ${t}`,x=d.includes(`
14
+ new file mode `)?"added":d.includes(`
15
+ deleted file mode `)?"deleted":d.includes(`
16
+ rename from `)?"renamed":"modified";let h=0,c=0;for(const f of d.split(`
17
+ `))f.startsWith("+")&&!f.startsWith("+++")&&(h+=1),f.startsWith("-")&&!f.startsWith("---")&&(c+=1);return[{file:x==="deleted"?l:p,status:x,additions:h,deletions:c,patch:d}]}),bn=s=>s==="added"?"A":s==="deleted"?"D":"M";function yn({activeDiffScope:s,effectiveDirectory:n,branchBase:t,branchHead:r,git:a,sessionMessageRecords:l}){const[p,d]=i.useState([]),[x,h]=i.useState(null),[c,f]=i.useState(!1),b=i.useMemo(()=>{const C=At(l,{showTextJustificationActivity:!1,showTurnChangedFiles:!0,mergeHiddenUserTurns:!0});for(let g=C.turns.length-1;g>=0;g-=1){const R=C.turns[g];if(!R)continue;const I=R.activityParts.map(E=>E.part).filter(E=>E.type==="tool"),k=Tt(I);if(k.length>0)return k.map(E=>({file:E.path,status:"modified",additions:E.additions,deletions:E.deletions,patch:E.patch}));const V=gn(R.userMessage.info?.summary?.diffs);if(V.length>0)return V}return[]},[l]);i.useEffect(()=>{if(s!=="branch"||!n||!t||!r||!a.getGitRangeDiff){d([]),h(null),f(!1);return}let C=!1;return f(!0),h(null),a.getGitRangeDiff(n,{base:t,head:r,contextLines:rt}).then(g=>{C||(d(xn(g.diff??"")),f(!1))}).catch(g=>{C||(d([]),f(!1),h(g instanceof Error?g.message:String(g)))}),()=>{C=!0}},[s,t,r,n,a]);const L=i.useMemo(()=>{const C=new Map;for(const g of b)if(g.file){if(typeof g.patch=="string"){C.set(g.file,Me(g.file,g.patch,"patch"));continue}C.set(g.file,{original:g.before??"",modified:g.after??"",contextMode:"full"})}return C},[b]),u=i.useMemo(()=>{const C=new Map;for(const g of p)!g.file||typeof g.patch!="string"||C.set(g.file,Me(g.file,g.patch,"patch"));return C},[p]);return{branchDiffs:p,branchDiffError:x,branchDiffLoading:c,lastTurnDiffs:b,lastTurnDiffData:L,branchDiffData:u}}const qe=(s,n)=>{if(n.length===0)return null;let t=null,r=null;for(const l of n)l.top<=s?(!t||l.top>t.top)&&(t=l):(!r||l.top<r.top)&&(r=l);const a=t??r;return a?{path:a.path,topOffset:a.top-s}:null},wn=(s,n,t,r)=>Math.min(Math.max(0,r),Math.max(0,s+t-n));function jn({pinSelectedFileHeaderToTopOnNavigate:s,scrollRequestNonce:n,changedFiles:t,expandedFiles:r,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const p=i.useRef(null),d=i.useRef(new Map),[x,h]=i.useState(null),c=i.useRef(null),f=i.useRef(null),b=i.useRef(!1),L=i.useRef(null),u=i.useRef(null),C=i.useRef(null),g=i.useCallback(()=>{const y=p.current;if(!y)return null;const w=y.getBoundingClientRect().top,j=[];for(const[A,F]of d.current)F&&j.push({path:A,top:F.getBoundingClientRect().top});return qe(w,j)},[]),R=i.useCallback(()=>{c.current=null,b.current=!1,h(null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null)},[]),I=i.useCallback(()=>{L.current=null;const y=p.current;if(!y)return;const w=y.getBoundingClientRect(),j=w.top-Ve,A=w.bottom+Ve,F={},q=[];for(const[N,_]of d.current){if(!_)continue;const B=_.getBoundingClientRect();q.push({path:N,top:B.top}),r.has(N)&&(B.bottom<j||B.top>A||(F[N]=!0))}u.current=qe(w.top,q),a(N=>{let _=!1;const B=new Set(N);for(const Z of Object.keys(F))B.has(Z)||(B.add(Z),_=!0);return _?B:N})},[r,a]),k=i.useCallback(()=>{typeof window>"u"||L.current===null&&(L.current=window.requestAnimationFrame(I))},[I]);i.useEffect(()=>{const y=p.current;if(y)return k(),y.addEventListener("scroll",k,{passive:!0}),window.addEventListener("resize",k),()=>{y.removeEventListener("scroll",k),window.removeEventListener("resize",k),L.current!==null&&(window.cancelAnimationFrame(L.current),L.current=null)}},[t,r,k]),i.useLayoutEffect(()=>{const y=C.current;if(!y)return;C.current=null;const w=p.current,j=d.current.get(y.path);if(!w||!j)return;const A=w.getBoundingClientRect().top,F=j.getBoundingClientRect().top-A;w.scrollTop=wn(w.scrollTop,y.topOffset,F,w.scrollHeight-w.clientHeight),u.current=y},[l]);const V=i.useCallback((y,w)=>{const j=d.current;w?j.set(y,w):j.delete(y),k()},[k]),E=i.useCallback(y=>{const w=d.current.get(y),j=p.current;if(!w||!j)return!1;const A=w.getBoundingClientRect().top-j.getBoundingClientRect().top;return j.scrollTo({top:j.scrollTop+A,behavior:"auto"}),!0},[]);return i.useEffect(()=>{if(!c.current)return;let w=0;const j=20;let A=!1;const F=(N=!0)=>{A||(A=!0,c.current=null,b.current=!1,N&&h(null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null))},q=()=>{if(A){f.current=null;return}const N=c.current;if(!N){F(),f.current=null;return}if(!E(N)){w+=1,w<j?f.current=window.requestAnimationFrame(q):(F(),f.current=null);return}if(s&&b.current){h(N),F(!1);return}F()};return f.current=window.requestAnimationFrame(q),()=>{A=!0,f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null)}},[s,n,E]),{diffScrollRef:p,fileSectionRefs:d,pinnedStackedTarget:x,pendingScrollTargetRef:c,shouldPinAfterAlignRef:b,pendingScrollAnchorRestoreRef:C,lastScrollAnchorRef:u,captureScrollAnchor:g,cancelPendingScrollAlignment:R,queueVisibleStackedFilesSync:k,registerSectionRef:V,scrollToFile:E}}const Xe=s=>{if(!s)return null;const n=s.split(`
18
+ `);let t=null;for(const r of n){const a=r.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(a){const l=Number.parseInt(a[1]??"",10);t=Number.isFinite(l)&&l>=1?l:null;continue}if(t!==null){if(r.startsWith(" ")){t+=1;continue}if(r.startsWith("+"))return t;if(r.startsWith("-"))return Math.max(1,t)}}return null};function Sn({effectiveDirectory:s,activeDiffStaged:n,git:t,files:r,setDiff:a,openContextFileAtLine:l}){const[p,d]=i.useState(null),x=i.useCallback(async(h,c)=>{if(!s||!h)return;d(h);const f=Qe();try{let b=null;if(c?.patch&&!c.isBinary&&!ve(h)?b=Xe(c.patch):c&&c.contextMode==="full"&&!c.isBinary&&!ve(h)&&(b=Ke(c.original,c.modified)),b===null)try{const R=await t.getGitDiff(s,{path:h,staged:n,contextLines:3});b=Xe(R.diff)}catch{b=null}let L=c;if(b===null||!L){const R=await t.getGitFileDiff(s,{path:h,staged:n});L={original:R.original??"",modified:R.modified??"",isBinary:R.isBinary},n||a(s,h,L,f??void 0)}const u=b??(L.isBinary||ve(h)?1:Ke(L.original,L.modified)),C=hn(s,h),g=await qt(r,C,{directory:s});if(!g.ok){et.error(Xt(g.reason));return}l(s,C,u,1)}finally{d(b=>b===h?null:b)}},[n,s,r,t,l,a]);return{openingEditorFilePath:p,openFileInEditorAtChange:x}}function Fn(s){const{hideStackedFileSidebar:n=!1,stackedDefaultCollapsedAll:t=!1,pinSelectedFileHeaderToTopOnNavigate:r=!1,diffScope:a="all",branchBase:l=null,branchHead:p=null,targetFilePath:d=null}=s,{git:x,files:h}=Ze(),c=Mt(),{screenWidth:f,isMobile:b}=It(),L=$t(c??null),u=Pt(c??null),C=_t(c??null),g=ne(o=>o.setActiveDirectory),R=ne(o=>o.ensureStatus),I=ne(o=>o.fetchStatus),k=ne(o=>o.clearDiffCache),V=ne(o=>o.setDiff),[E,y]=i.useState(null),[w,j]=i.useState(!1),[A,F]=i.useState(()=>new Set),[q,N]=i.useState(()=>new Set),[_,B]=i.useState(!1),[Z,se]=i.useState(0),[P,le]=i.useState(()=>new Map),[T,ee]=i.useState(a);i.useEffect(()=>{ee(a)},[a]);const W=Q(o=>o.pendingDiffFile),ce=Q(o=>o.pendingDiffStaged),O=Q(o=>o.pendingDiffScope),re=Q(o=>o.setPendingDiffFile),Y=Q(o=>o.diffLayoutPreference),te=Q(o=>o.diffFileLayout),z=Q(o=>o.setDiffFileLayout),ue=Q(o=>o.diffWrapLines),ye=Q(o=>o.setDiffWrapLines),de=Q(o=>o.openContextFileAtLine),fe=Bt(o=>o.currentSessionId),pe=Wt(fe??""),we=ue,m=T==="staged"?!0:T==="working"?!1:null,D=m??w,$=b||f<=768,je=!n&&!$&&f>=1024,me=i.useRef(null),{branchDiffs:ie,branchDiffError:ke,branchDiffLoading:K,lastTurnDiffs:G,lastTurnDiffData:it,branchDiffData:ot}=yn({activeDiffScope:T,effectiveDirectory:c,branchBase:l,branchHead:p,git:x,sessionMessageRecords:pe}),H=i.useMemo(()=>{if(T==="turn"||T==="branch")return(T==="branch"?ie:G).map(M=>({path:M.file??"",index:"",working_dir:bn(M.status),insertions:M.additions??0,deletions:M.deletions??0,isNew:M.status==="added"})).filter(M=>M.path).sort((M,X)=>M.path.localeCompare(X.path));if(!u?.files)return[];const o=u.diffStats??{},v=T==="staged"?We:T==="working"?Oe:()=>!0;return u.files.filter(v).map(S=>({...S,insertions:o[S.path]?.insertions??0,deletions:o[S.path]?.deletions??0,isNew:Vt(S)})).sort((S,M)=>S.path.localeCompare(M.path))},[T,ie,G,u]),at=i.useMemo(()=>u?.files?u.files.filter(Oe).length:0,[u]),lt=i.useMemo(()=>u?.files?u.files.filter(We).length:0,[u]),ct=G.length,ut=u?.files?.length??0,dt=ie.length,{diffScrollRef:ft,pinnedStackedTarget:pt,pendingScrollTargetRef:he,shouldPinAfterAlignRef:ge,pendingScrollAnchorRestoreRef:Ie,lastScrollAnchorRef:$e,captureScrollAnchor:Pe,cancelPendingScrollAlignment:xe,queueVisibleStackedFilesSync:Le,registerSectionRef:mt,scrollToFile:_e}=jn({pinSelectedFileHeaderToTopOnNavigate:r,scrollRequestNonce:Z,changedFiles:H,expandedFiles:A,setMountedStackedFiles:N,fileDiffRefreshNonce:P}),be=i.useCallback(o=>{F(v=>{if(v.has(o))return v;const S=new Set(v);return S.add(o),S})},[]),Re=i.useMemo(()=>H.map(o=>o.path).join("\0"),[H]);i.useEffect(()=>{const o=Re?Re.split("\0"):[],v=new Set(o),S=`${c??""}:${T}:${t?"collapsed":"default"}`,M=me.current!==S;me.current=S,F(X=>{if(M){const oe=t?0:mn(o.length);return new Set(o.slice(0,oe))}let Se=!1;const Fe=new Set;for(const oe of X){if(!v.has(oe)){Se=!0;continue}Fe.add(oe)}return Se?Fe:X}),N(X=>{if(M)return new Set;let Se=!1;const Fe=new Set;for(const oe of X){if(!v.has(oe)){Se=!0;continue}Fe.add(oe)}return Se?Fe:X})},[T,Re,c,N,t]);const Ee=i.useCallback(o=>{const v=te[o.path];if(v)return v;if(Y==="inline")return"inline";if(Y==="side-by-side")return"side-by-side";const S=f<pn;return o.isNew||S?"inline":"side-by-side"},[te,Y,f]),ht=i.useMemo(()=>H.length===0?null:H.every(o=>Ee(o)==="side-by-side")?"side-by-side":"inline",[H,Ee]);i.useEffect(()=>{c&&(g(c),R(c,x))},[c,g,R,x]),i.useEffect(()=>{if(c)return Ot.onGitRefreshHint(o=>{Be(o.directory)===Be(c)&&(o.paths?.length&&(Ie.current=Pe()??$e.current,k(c,o.paths),le(v=>{const S=new Map(v);for(const M of o.paths??[])S.set(M,(S.get(M)??0)+1);return S})),I(c,x,{silent:!0}))})},[Pe,k,c,I,x,$e,Ie]),i.useEffect(()=>{T!=="all"&&!O||W&&(O&&ee(O),y(W),j(O==="staged"||!O&&ce),re(null),ge.current=!0,he.current=W,be(W),se(o=>o+1))},[T,be,W,O,ce,he,re,ge]),i.useEffect(()=>{if(T==="all")return;const o=d?.trim();o&&(y(o),j(T==="staged"),ge.current=!0,he.current=o,be(o),se(v=>v+1))},[T,be,he,ge,d]),i.useEffect(()=>{if(!E)return;H.some(v=>v.path===E)||(y(null),j(!1))},[H,E]);const gt=i.useCallback((o,v)=>{xe(),F(S=>{const M=S.has(o);if(v===M)return S;const X=new Set(S);return v?X.add(o):X.delete(o),X}),v||N(S=>{if(!S.has(o))return S;const M=new Set(S);return M.delete(o),M}),Le()},[xe,Le,N]),xt=i.useCallback(()=>{xe(),F(o=>o.size>0?new Set:new Set(H.map(v=>v.path))),N(new Set),Le()},[xe,H,Le,N]),bt=i.useCallback(o=>{},[]),yt=i.useCallback(o=>{xe(),y(o),j(!1),ge.current=!0,he.current=o,be(o),se(v=>v+1),_e(o)},[xe,be,he,_e,ge]),wt=i.useCallback(o=>{const v=o==="side-by-side"?"side-by-side":"inline";H.forEach(S=>{z(S.path,v)})},[H,z]),{openingEditorFilePath:jt,openFileInEditorAtChange:St}=Sn({effectiveDirectory:c,activeDiffStaged:D,git:x,files:h,setDiff:V,openContextFileAtLine:de});return{git:x,files:h,effectiveDirectory:c,screenWidth:f,isMobile:b,isGitRepo:L,status:u,isLoadingStatus:C,activeDiffScope:T,setActiveDiffScope:ee,branchDiffs:ie,branchDiffError:ke,branchDiffLoading:K,diffWrapLines:we,setDiffWrapLines:ye,forcedStaged:m,displayFileStaged:w,displayFile:E,pinnedStackedTarget:pt,expandedFiles:A,mountedStackedFiles:q,loadFullFiles:_,setLoadFullFiles:B,fileDiffRefreshNonce:P,showFileSidebar:je,diffScrollRef:ft,lastTurnDiffData:it,branchDiffData:ot,changedFiles:H,workingFileCount:at,stagedFileCount:lt,turnFileCount:ct,allFileCount:ut,branchFileCount:dt,currentLayoutForAllFiles:ht,openingEditorFilePath:jt,registerSectionRef:mt,handleStackedEntryExpandedChange:gt,handleExpandOrCollapseAll:xt,handleSelectFile:bt,handleSelectFileAndScroll:yt,handleHeaderLayoutChange:wt,openFileInEditorAtChange:St,getLayoutForFile:Ee}}const Er=({hideStackedFileSidebar:s=!1,stackedDefaultCollapsedAll:n=!1,pinSelectedFileHeaderToTopOnNavigate:t=!1,showOpenInEditorAction:r=!1,diffScope:a="all",onDiffScopeChange:l,branchBase:p=null,branchHead:d=null,targetFilePath:x=null,flushContent:h=!1})=>{const{effectiveDirectory:c,isGitRepo:f,status:b,isLoadingStatus:L,activeDiffScope:u,setActiveDiffScope:C,branchDiffError:g,branchDiffLoading:R,diffWrapLines:I,setDiffWrapLines:k,forcedStaged:V,displayFileStaged:E,displayFile:y,pinnedStackedTarget:w,expandedFiles:j,mountedStackedFiles:A,loadFullFiles:F,setLoadFullFiles:q,fileDiffRefreshNonce:N,showFileSidebar:_,diffScrollRef:B,lastTurnDiffData:Z,branchDiffData:se,changedFiles:P,workingFileCount:le,stagedFileCount:T,turnFileCount:ee,allFileCount:W,branchFileCount:ce,currentLayoutForAllFiles:O,openingEditorFilePath:re,registerSectionRef:Y,handleStackedEntryExpandedChange:te,handleExpandOrCollapseAll:z,handleSelectFile:ue,handleSelectFileAndScroll:ye,handleHeaderLayoutChange:de,openFileInEditorAtChange:fe,getLayoutForFile:pe}=Fn({hideStackedFileSidebar:s,stackedDefaultCollapsedAll:n,pinSelectedFileHeaderToTopOnNavigate:t,diffScope:a,branchBase:p,branchHead:d,targetFilePath:x}),we=()=>{if(!c)return null;const D=$=>V!==null?V:E&&$===y;return e.jsxs("div",{className:J("flex min-w-0 flex-1 min-h-0 h-full",h?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[_&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:P.length})]}),e.jsx(rn,{changedFiles:P,selectedFile:null,onSelectFile:ye})]}),e.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:e.jsx(Ye,{ref:B,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none] pb-16",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:e.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:P.map($=>e.jsx(fn,{directory:c,file:$,layout:pe($),wrapLines:I,isSelected:!1,isExpanded:j.has($.path),isMounted:A.has($.path)||$.path===w,onSelect:ue,onExpandedChange:te,registerSectionRef:Y,showOpenInEditorAction:r&&u!=="turn"&&u!=="branch",isOpeningInEditor:re===$.path,onOpenInEditor:(je,me)=>{fe(je,me)},staged:D($.path),showFileActions:u!=="turn"&&u!=="branch",loadFullFiles:F,initialDiffData:u==="turn"?Z.get($.path)??null:u==="branch"?se.get($.path)??null:null},`${$.path}:${N.get($.path)??0}`))})})})]})},m=()=>c?u!=="turn"&&L&&!b?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):u!=="turn"&&u!=="branch"&&f===!1?e.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."}):u==="branch"&&R?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):u==="branch"&&g?e.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: ${g}`}):P.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:u==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):we():e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(f!==!1||u==="turn")&&(u==="all"||u==="working"||u==="staged"||u==="turn"||u==="branch")?e.jsx(Yt,{scope:u,isGitRepo:f,branchAvailable:!!(p&&d),allCount:W,workingCount:le,stagedCount:T,turnCount:ee,branchCount:ce,onScopeChange:D=>{C(D),l?.(D)}}):e.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:L&&!b?"Loading changes...":P.length===1?`${P.length} file changed`:`${P.length} files changed`})}),P.length>0&&e.jsxs(Ce,{variant:"ghost",size:"sm",onClick:z,className:J("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:j.size>0?"Collapse all":"Expand all",children:[e.jsx(U,{name:"expand-up-down",className:"size-4"}),e.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:j.size>0?"Collapse all":"Expand all"})]}),P.length>0&&u!=="turn"&&u!=="branch"&&e.jsxs(zt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>q(D=>!D),"aria-pressed":F,"aria-label":F?"Unload full files":"Load full files",className:J("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",F&&"bg-interactive-selection text-interactive-selection-foreground"),children:e.jsx(U,{name:"file-download",className:"size-4"})})}),e.jsx(Ht,{children:e.jsx("p",{children:F?"Unload full files":"Load full files"})})]}),P.length>0&&e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>k(!I),className:J("h-5 w-5 p-0 transition-opacity",I?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:I?"Disable line wrap":"Enable line wrap",children:e.jsx(U,{name:"text-wrap",className:"size-4"})}),O&&e.jsx(tt,{mode:O==="side-by-side"?"side-by-side":"unified",onModeChange:de})]}),m()]})};export{Er as DiffView};