@pi-chamber/web 1.0.7 → 1.0.8-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
  2. package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
  3. package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
  4. package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-C70pbgk-.js} +6 -6
  5. package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
  6. package/dist/assets/FilesView-nFJYEdRw.js +6 -0
  7. package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
  8. package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
  9. package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
  10. package/dist/assets/{GitView-DD33ngnM.js → GitView-MIDG5RYW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-uNlozeu0.js} +2 -2
  12. package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-CSLsTriz.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
  14. package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
  15. package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
  16. package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
  17. package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
  18. package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
  19. package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
  20. package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
  21. package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-Cb4st5y5.js} +1 -1
  22. package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
  23. package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
  24. package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
  25. package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
  26. package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
  27. package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
  28. package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
  29. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
  30. package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
  31. package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
  32. package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
  33. package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CnzR7kxA.js} +2 -2
  34. package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
  35. package/dist/assets/githubLink-QvaLfNNT.js +10 -0
  36. package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
  37. package/dist/assets/index-D3F4JrPN.css +1 -0
  38. package/dist/assets/{index-ComwtfT4.js → index-DMX9wT1Z.js} +1 -1
  39. package/dist/assets/{main-DoiadX0a.js → main-BW9J3Y72.js} +2 -2
  40. package/dist/assets/main-BirYxac2.js +137 -0
  41. package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-CxmcPur8.js} +2 -2
  42. package/dist/assets/miniChat-BRB11eEs.js +2 -0
  43. package/dist/assets/{mobile-BucKVm1P.js → mobile-DJZYYCuB.js} +2 -2
  44. package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
  45. package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
  46. package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
  47. package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
  48. package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
  49. package/dist/assets/{renderMobileApp-Bp74b_Lo.js → renderMobileApp-B7cT7m5b.js} +3 -3
  50. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
  51. package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
  52. package/dist/assets/selection-BTEdLRVK.js +1 -0
  53. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
  54. package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
  55. package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
  56. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
  57. package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
  58. package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
  59. package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
  60. package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
  61. package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
  86. package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
  87. package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
  88. package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
  89. package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
  90. package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
  91. package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
  93. package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
  94. package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
  95. package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
  96. package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
  97. package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
  98. package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
  99. package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
  100. package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
  101. package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
  102. package/dist/assets/{web-components-CGDpzixf.js → web-components-C_DsTJis.js} +4 -4
  103. package/dist/index.html +4 -4
  104. package/dist/mini-chat.html +3 -3
  105. package/dist/mobile.html +3 -3
  106. package/package.json +2 -1
  107. package/plugins/registry.json +7 -0
  108. package/plugins/subagents/LICENSE +25 -0
  109. package/plugins/subagents/agents/planner.md +36 -0
  110. package/plugins/subagents/agents/reviewer.md +34 -0
  111. package/plugins/subagents/agents/scout.md +49 -0
  112. package/plugins/subagents/agents/worker.md +23 -0
  113. package/plugins/subagents/extension.js +631 -0
  114. package/plugins/subagents/extension.test.js +295 -0
  115. package/plugins/subagents/package.json +41 -0
  116. package/plugins/visuals/choices.js +168 -0
  117. package/plugins/visuals/extension.js +87 -0
  118. package/plugins/visuals/files.js +74 -0
  119. package/plugins/visuals/package.json +32 -0
  120. package/server/index.js +20 -0
  121. package/server/lib/github/DOCUMENTATION.md +4 -2
  122. package/server/lib/github/gh-cli.js +35 -9
  123. package/server/lib/github/gh-cli.test.js +122 -0
  124. package/server/lib/notifications/pi-notification-watcher.js +3 -0
  125. package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
  126. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  127. package/server/lib/pi/extension-protocol.js +54 -0
  128. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
  129. package/server/lib/pi/routes-extension-events.test.js +115 -0
  130. package/server/lib/pi/routes.js +307 -5
  131. package/server/lib/pi/routes.test.js +296 -1
  132. package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
  133. package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
  134. package/server/lib/pi/session-daemon/extension-config.js +719 -0
  135. package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
  136. package/server/lib/pi/session-daemon/extension-controls.js +177 -0
  137. package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
  138. package/server/lib/pi/session-daemon/extension-name.js +6 -0
  139. package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
  140. package/server/lib/pi/session-daemon/extension-palette.js +146 -0
  141. package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
  142. package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
  143. package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
  144. package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
  145. package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
  146. package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
  147. package/server/lib/pi/session-daemon/plugin-host.js +245 -0
  148. package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
  149. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
  150. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
  151. package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
  152. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
  153. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
  154. package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
  155. package/server/lib/pi/session-daemon/session-daemon.js +568 -61
  156. package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
  157. package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
  158. package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
  159. package/server/lib/pi/session-daemon/supervisor.js +22 -3
  160. package/server/lib/pi/settings-store.js +14 -0
  161. package/server/lib/pi/settings-store.test.js +11 -0
  162. package/server/lib/plugins/DOCUMENTATION.md +186 -0
  163. package/server/lib/plugins/daemon-sync.js +78 -0
  164. package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
  165. package/server/lib/plugins/daemon-sync.test.js +96 -0
  166. package/server/lib/plugins/impact.js +139 -0
  167. package/server/lib/plugins/impact.test.js +82 -0
  168. package/server/lib/plugins/manifest.js +195 -0
  169. package/server/lib/plugins/manifest.test.js +118 -0
  170. package/server/lib/plugins/registry.js +59 -0
  171. package/server/lib/plugins/routes.js +92 -0
  172. package/server/lib/plugins/routes.test.js +219 -0
  173. package/server/lib/plugins/service.js +161 -0
  174. package/server/lib/plugins/store.js +261 -0
  175. package/server/lib/plugins/store.test.js +188 -0
  176. package/server/lib/plugins/visuals-extension.test.js +237 -0
  177. package/server/lib/server-browser/DOCUMENTATION.md +32 -7
  178. package/server/lib/server-browser/browser-tab.js +4 -1
  179. package/server/lib/server-browser/downloads.js +261 -34
  180. package/server/lib/server-browser/downloads.test.js +171 -0
  181. package/server/lib/server-browser/runtime.integration.test.js +47 -0
  182. package/server/lib/server-browser/runtime.js +16 -0
  183. package/server/lib/server-browser/server-browser.js +25 -6
  184. package/server/lib/tunnels/executable-search.js +5 -1
  185. package/server/lib/tunnels/executable-search.test.js +26 -0
  186. package/dist/assets/DiagramView-BB-aZobi.js +0 -1
  187. package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
  188. package/dist/assets/FilesView-DECxN8Z0.js +0 -6
  189. package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
  190. package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
  191. package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
  192. package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
  193. package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
  194. package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
  195. package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
  196. package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
  197. package/dist/assets/SettingsView-DcF-At5E.js +0 -6
  198. package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
  199. package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
  200. package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
  201. package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
  202. package/dist/assets/githubLink-ByPAyFjh.js +0 -10
  203. package/dist/assets/index-BaLCg7tL.css +0 -1
  204. package/dist/assets/main-DyFfbllq.js +0 -137
  205. package/dist/assets/miniChat-Ck6MEZ9Q.js +0 -2
  206. package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
  207. package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
  209. package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
  210. package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
  211. package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
  212. package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
@@ -0,0 +1,137 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentsSurface-BmHImX8m.js","assets/vendor-boot-D-KEJjsM.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-clsx-B-dksMZM.js","assets/useAppFontEffects-EcTZ_I_I.js","assets/index-B2v0_mez.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-D3F4JrPN.css","assets/runtimeSurface-kIEoYsPP.js","assets/nativeFileSave-B6QpoPRn.js","assets/selection-BTEdLRVK.js","assets/DiffView-C70pbgk-.js","assets/gitStatusPredicates-4kPg2t6j.js","assets/VirtualizedFileDiff-CLgDONEQ.js","assets/web-components-C_DsTJis.js","assets/computeVirtualFileMetrics-DmO6H8u6.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/renderDiffWithHighlighter-C48T6YFJ.js","assets/vendor-diff-C3JhlQdm.js","assets/PierreDiffViewer-lwn6w_5w.js","assets/StickyHorizontalScrollbar-CMbTn5WQ.js","assets/runtimeEndpointReset-BC6yGnxN.js","assets/SessionUnreadDot-DyeIrsro.js","assets/permissionStore-zIpxq9Pq.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/vendor-xterm-xterm-css-DDGTF8rc.css","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/contextFileOpenGuard-DOK251YW.js","assets/FilesView-nFJYEdRw.js","assets/vendor-codemirror-lang-javascript-DF3GDYje.js","assets/vendor-lezer-javascript-CUdJ0VGA.js","assets/vendor-lezer-lr-DluApmOX.js","assets/vendor-codemirror-autocomplete-BKvJ8PfM.js","assets/vendor-codemirror-lang-json-DCqvG1nE.js","assets/vendor-lezer-json-BKYAA8Hu.js","assets/vendor-codemirror-lang-css-DoEEdEpW.js","assets/vendor-lezer-css-DRxDmhcy.js","assets/vendor-codemirror-lang-html-h25V-Hp5.js","assets/vendor-lezer-html-qr9pUPmM.js","assets/vendor-codemirror-lang-markdown-6BNbCEPe.js","assets/vendor-lezer-markdown-B-uzYzYT.js","assets/vendor-codemirror-language-data-BUZIlm3G.js","assets/vendor-codemirror-lang-python-DQym-8Tx.js","assets/vendor-lezer-python-Bj232yb5.js","assets/shell-CjFT_Tl9.js","assets/FileSaveConflictDialog-Cu8c3gBV.js","assets/vendor-react-drawio-IYnLUY5N.js","assets/fileTreeStatus-CnzR7kxA.js","assets/JsonTreeView-CSLsTriz.js","assets/Virtualizer-PxblpQn6.js","assets/renderFileWithHighlighter-8Kt2MyTN.js","assets/vendor-codemirror-search-BlDCaCMK.js","assets/vendor-replit-codemirror-vim-Cvk64got.js","assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js","assets/GitView-MIDG5RYW.js","assets/GitHubDetailScaffold-Jvv_tgbl.js","assets/vendor-dompurify-BGCr_sdL.js","assets/collapsible-BeyKtQGB.js","assets/vendor-base-ui-DE6jnTiC.js","assets/PullRequestsSurface-o_AXDjbO.js","assets/useGitHubRemoteSearch-DIBHNu8r.js","assets/GitHubListPrimitives-BWI706F0.js","assets/IssuesSurface-uNlozeu0.js","assets/githubLink-QvaLfNNT.js","assets/DiagramView-BZQxoiZu.js","assets/SettingsView-BHBpt2Um.js","assets/vendor-qrcode-gzL9QFkg.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js","assets/SettingsWindow-Cb4st5y5.js"])))=>i.map(i=>d[i]);
2
+ import{bi as $s,bj as Bt,bk as Pn,j as e,bl as Fs,bm as Ws,bn as zs,bo as Rn,bp as En,bq as Hs,br as Us,bs as Tn,bt as Dn,bu as An,bv as _n,bw as rs,bx as wt,b3 as os,aX as Mn}from"./vendor-boot-D-KEJjsM.js";import{R as n,a as Fe}from"./vendor-react-Bz1tRBxM.js";/* empty css */import{u as K,c as fe,r as Ot,a0 as In,q as Vs,a1 as Ln,b as Bn,f as Ks,B as On,N as $n,R as Ue,V as Fn,A as Be,W as Wn,T as zn,P as Hn,I as Xs,Z as Un,a2 as Vn,a3 as Kn,a4 as as,a5 as ft,k as is,z as Xn,v as qn,a6 as Yn,a7 as qs,w as Ys,a8 as Gn,a9 as Jn,aa as Qn,s as Zn,ab as er,y as tr,l as Gs,x as sr}from"./index-B2v0_mez.js";import{_ as Oe}from"./vendor-vite-runtime-DD1OZmLC.js";import{X as nr,ak as ls,al as rr,am as or,an as ar,ao as ir,ap as lr,aq as cr,ar as dr,as as ur,at as hr,au as fr,av as dt,aw as pr,ax as mr,ay as gr,az as xr,aA as br,aB as wr,aC as yr,aD as vr,aE as Js,aF as jr,aa as Sr,ab as kr,ac as Cr,ad as Nr,ae as Pr,aG as Qs,aH as Zs,aI as $t,Q as en,aJ as Rr,aK as Er,aL as Tr,Y as Dr,a9 as Ar,a6 as _r,a7 as Mr,_ as cs,a0 as ds,$ as us,S as hs,Z as Ir,a2 as Lr,a3 as Br,a5 as Or,a4 as $r,a8 as Fr}from"./runtimeEndpointReset-BC6yGnxN.js";import{ai as kt,I as W,aE as ze,N as xt,B as Q,aW as Ct,a0 as ct,t as xe,bY as Xt,x as Me,af as at,cS as Et,cT as Wr,D as Ft,ap as et,aq as tt,h as Wt,ar as st,i as zt,a1 as Qe,aY as tn,j as Nt,aZ as bt,bP as qt,f as fs,aj as zr,m as Yt,n as Gt,o as Jt,p as Qt,q as Zt,U as Hr,$ as Ur,cu as Vr,av as Kr,bR as sn,ak as Ze,cU as pt,C as nn,bn as Xr,cK as qr,cN as Ke,bO as rn,cV as Yr,cW as Gr,cM as es,cX as Jr,ax as on,k as ps,cY as Qr,w as ms,cZ as Zr,c_ as eo,c$ as to,d0 as gs,u as so,b as no,c as ro,d1 as oo,a as xs,aV as ao,r as Tt,bS as io,d2 as lo,d as co,cB as uo,cC as ho,cD as fo,cE as po,cF as ut,cG as ht,d3 as mo,g as go,d4 as xo,cA as bo,d5 as wo,d6 as yo,aP as vo,aQ as jo,aR as So,aG as ko,aF as Co,aI as No,aD as Po,cm as Ro,aH as Eo,cj as To,ck as Do,cl as Ao,aJ as _o,aK as Mo,aN as Io,aO as Lo}from"./useAppFontEffects-EcTZ_I_I.js";import{g as an,F as Bo,a as Oo,q as $o,f as Fo,h as Wo,j as zo,k as Ho,u as Uo,w as bs,m as ln,y as Vo}from"./fileTreeStatus-CnzR7kxA.js";import{v as cn,g as dn}from"./contextFileOpenGuard-DOK251YW.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-zustand-CXhN0IMY.js";import"./vendor-tailwind-merge-BKkUfl9q.js";import"./vendor-fuse.js-t_7AcMTv.js";import"./nativeFileSave-B6QpoPRn.js";import"./SessionUnreadDot-DyeIrsro.js";/* empty css */import"./permissionStore-zIpxq9Pq.js";import"./runtimeSurface-kIEoYsPP.js";const Ko=280,ws=4,Xo=({transform:t})=>({...t,y:0}),qo=({id:t,children:s,className:r})=>{const{attributes:a,listeners:i,setNodeRef:o,transform:u,transition:l,isDragging:c}=Hs({id:t});return e.jsx("div",{ref:o,"data-sortable-tab-id":t,style:{transform:Us.Transform.toString(u),transition:l},className:fe("h-full rounded-md",r,c&&"opacity-50"),...a,...i,children:s})},Yo=({id:t,children:s,className:r})=>e.jsx("div",{className:fe("h-full",r),"data-sortable-tab-id":t,children:s}),un=({items:t,activeId:s,onSelect:r,onClose:a,onReorder:i,layoutMode:o="scrollable",variant:u="default",activePillInsetClassName:l,activePillButtonClassName:c,inactiveTabsIconOnly:h=!1,animateActivePill:f,activePillLowercase:y=!0,nonCompositedIndicator:d=!1,className:b})=>{const p=K(B=>B.isMobile),{isTablet:C}=kt(),x=p||C,P=n.useRef(null),[_,U]=n.useState({left:!1,right:!1}),w=n.useMemo(()=>t.map(B=>B.id),[t]),E=o==="scrollable",S=u==="default",M=u==="active-pill",T=M||u==="animated",Y=S,X=T||Y,z=M&&E,Z=T,le=f??T,H=typeof i=="function",ne=H?qo:Yo,N=n.useRef(new Map),[F,oe]=n.useState(null),[D,O]=n.useState(!1),[G,ue]=n.useState(null),ge=n.useRef(!1),he=n.useRef(0),be=n.useRef(s),je=n.useRef(null),Ce=n.useMemo(()=>{if(!X||!G||!s||G===s)return 0;const B=t.findIndex(re=>re.id===G),J=t.findIndex(re=>re.id===s);return B<0||J<0?0:B>J?ws:-ws},[s,t,G,X]),ve=$s(Bt(Pn,{activationConstraint:{distance:8}})),ye=n.useCallback((B,J)=>!B||!J?B===J:Math.abs(B.left-J.left)<.5&&Math.abs(B.top-J.top)<.5&&Math.abs(B.width-J.width)<.5&&Math.abs(B.height-J.height)<.5,[]),Re=n.useCallback((B,J)=>{if(J){N.current.set(B,J);return}N.current.delete(B)},[]),Te=n.useCallback(()=>{if(!X||!s){oe(g=>g===null?g:null);return}const B=P.current,J=N.current.get(s);if(!B||!J){oe(g=>g===null?g:null);return}let re=0,L=0,ee=J;for(;ee&&ee!==B;)re+=ee.offsetLeft,L+=ee.offsetTop,ee=ee.offsetParent;const ae={left:re,top:L,width:J.offsetWidth,height:J.offsetHeight};oe(g=>ye(g,ae)?g:ae)},[s,ye,X]),Se=n.useCallback(()=>{if(!E){U({left:!1,right:!1});return}const B=P.current;if(!B){U({left:!1,right:!1});return}U({left:B.scrollLeft>2,right:B.scrollLeft+B.clientWidth<B.scrollWidth-2})},[E]);n.useEffect(()=>{if(!E){U({left:!1,right:!1});return}const B=P.current;if(!B)return;Se(),B.addEventListener("scroll",Se,{passive:!0});const J=new ResizeObserver(Se);return J.observe(B),()=>{B.removeEventListener("scroll",Se),J.disconnect()}},[E,t.length,Se]),n.useEffect(()=>{if(!E)return;const B=P.current;if(!B)return;const J=re=>{if(re.ctrlKey||Math.abs(re.deltaY)<=Math.abs(re.deltaX))return;const L=B.scrollWidth-B.clientWidth;if(L<=0)return;const ee=re.deltaMode===WheelEvent.DOM_DELTA_LINE?re.deltaY*16:re.deltaMode===WheelEvent.DOM_DELTA_PAGE?re.deltaY*B.clientWidth:re.deltaY;re.preventDefault(),B.scrollLeft=Math.min(L,Math.max(0,B.scrollLeft+ee))};return B.addEventListener("wheel",J,{passive:!1}),()=>{B.removeEventListener("wheel",J)}},[E]),n.useEffect(()=>{if(!X){oe(null);return}Te();const B=P.current;if(!B)return;const J=new ResizeObserver(()=>{performance.now()-he.current>Ko&&O(!1),Te()});if(J.observe(B),s){const re=N.current.get(s);re&&J.observe(re)}return()=>{J.disconnect()}},[s,t.length,Te,X]),n.useLayoutEffect(()=>{Te()});const ke=w.join("\0");n.useLayoutEffect(()=>{if(!X){ge.current=!1,O(!1);return}const B=je.current!==ke;if(je.current=ke,!ge.current){ge.current=!0,be.current=s;return}const J=be.current!==s;if(be.current=s,!J||B){O(!1);return}he.current=performance.now(),O(!0)},[s,ke,X]),n.useEffect(()=>{if(!E||!s)return;const B=P.current;if(!B)return;const J=window.requestAnimationFrame(()=>{const re=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),L=B.querySelector(`[data-sortable-tab-id="${re}"]`);L&&(L.scrollIntoView({block:"nearest",inline:"nearest"}),Se())});return()=>{window.cancelAnimationFrame(J)}},[s,E,t.length,Se]);const Ne=n.useCallback(B=>{if(!i)return;const{active:J,over:re}=B;!re||J.id===re.id||i(String(J.id),String(re.id))},[i]),De=e.jsxs("div",{className:fe("relative flex h-full min-w-0 flex-1",b),children:[E&&_.left?e.jsx("div",{className:fe("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",T?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,E&&_.right?e.jsx("div",{className:fe("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",T?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e.jsxs("div",{ref:P,className:fe("relative flex h-full min-w-0 flex-1",T?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",T&&"@container/pill-tabs",T&&"pill-tabs__track",T&&(l??"gap-0.5 py-0.5"),Y&&"items-center overflow-y-hidden",Z&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",E?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:E?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[T&&F?e.jsx("div",{className:fe("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",le&&D&&(d?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:d?{left:`${F.left+Ce}px`,top:`${F.top}px`,width:`${F.width}px`,height:`${F.height}px`}:{transform:`translate3d(${F.left+Ce}px, ${F.top}px, 0)`,width:`${F.width}px`,height:`${F.height}px`}}):null,Y&&F?e.jsx("div",{className:fe("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",D&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${F.left+Ce}px, 0, 0)`,width:`${F.width}px`},"aria-hidden":!0}):null,t.map(B=>{const J=B.id===s,re=h&&T&&!J&&!!B.icon,L=!re,ee=!!B.icon,ae=h&&T&&J&&!E&&!z,g=B.closable!==!1&&!!a,A=g&&!!B.icon,te=E||z?void 0:T?ae?"flex-none basis-auto":p?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",de=g?V=>{V.button===1&&(V.preventDefault(),V.stopPropagation(),a?.(B.id))}:void 0,m=g?V=>{V.button===1&&V.preventDefault()}:void 0,I=V=>ee?e.jsxs("span",{className:V,children:[e.jsx("span",{className:fe("flex items-center justify-center transition-opacity",A&&(x?"opacity-0":"group-hover:opacity-0")),children:B.icon}),A?e.jsx("span",{role:"button",tabIndex:-1,className:fe("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",x?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:pe=>pe.stopPropagation(),onClick:pe=>{pe.stopPropagation(),a?.(B.id)},"aria-label":B.closeLabel??`Close ${B.label} tab`,title:B.closeLabel??`Close ${B.label} tab`,children:e.jsx(W,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return e.jsx(ne,{id:B.id,className:te,children:e.jsxs("div",{ref:V=>Re(B.id,V),onAuxClick:de,onMouseDown:m,className:fe("group flex h-full min-w-0 flex-nowrap items-center",E||z?"shrink-0":T?"w-full":"w-full min-w-0",T?"relative z-10 bg-transparent":J?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":J,"aria-label":re?B.title??B.label:void 0,onClick:()=>r(B.id),onPointerDown:X?()=>{O(!0),ue(B.id)}:void 0,onPointerUp:X?()=>ue(null):void 0,onPointerLeave:X?()=>ue(null):void 0,onPointerCancel:X?()=>ue(null):void 0,className:fe(T?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",T&&y?"lowercase":null,T&&(re?"gap-0":"gap-1.5"),T?z?"shrink-0 whitespace-nowrap px-3 text-center":E?"max-w-56 shrink-0 px-3 text-center":re?"px-2 !min-w-0 text-center":ae?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":E?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",T?c??(M?p?"h-[38px]":"h-[31px]":"h-7"):null,T?J?"text-foreground":"text-muted-foreground hover:text-foreground":null,T?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:B.title??B.label,children:T?e.jsxs(e.Fragment,{children:[I("relative flex h-4 w-4 shrink-0 items-center justify-center"),L?e.jsx("span",{className:"animated-tabs__label truncate",children:B.label}):null]}):e.jsxs("span",{className:fe("flex min-w-0 flex-nowrap items-center gap-1.5",!E&&"justify-center"),children:[I(fe("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",J?"text-[var(--primary-base)]":"text-muted-foreground")),e.jsx("span",{className:"truncate leading-[1.2]",children:B.label})]})}),g&&!A?e.jsx("button",{type:"button",onPointerDown:V=>{V.stopPropagation()},onClick:V=>{V.stopPropagation(),a?.(B.id)},className:fe("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",T?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",T?J?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":J?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":B.closeLabel??`Close ${B.label} tab`,title:B.closeLabel??`Close ${B.label} tab`,children:e.jsx(W,{name:"close",className:"h-3 w-3"})}):null]})},B.id)})]})]});return H?e.jsxs(Fs,{sensors:ve,collisionDetection:Ws,onDragEnd:Ne,modifiers:[Xo],children:[e.jsx(zs,{items:w,strategy:Rn,children:De}),e.jsx(En,{dropAnimation:null})]}):De},ys=280,vs=280,js=500,Go=({isOpen:t,isMobile:s,children:r,className:a,topBar:i})=>{const o=K(j=>j.sidebarWidth),u=K(j=>j.setSidebarWidth),[l,c]=n.useState(!1),h=n.useRef(0),f=n.useRef(o||ys),y=n.useRef(null),d=n.useRef(null),b=n.useRef(null),p=n.useCallback(j=>Math.min(js,Math.max(vs,j)),[]),C=n.useCallback(j=>{const T=b.current;T&&(T.style.width=`${j}px`,T.style.minWidth=`${j}px`,T.style.maxWidth=`${j}px`,T.style.setProperty("--oc-left-sidebar-width",`${j}px`))},[]);n.useEffect(()=>{s&&l&&c(!1)},[s,l]),n.useEffect(()=>{l||(y.current=null,d.current=null)},[l]);const x=nr(t);if(s)return null;const P=Math.min(js,Math.max(vs,o||ys)),_=x.layoutVisible?P:0,U=j=>{if(t){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}d.current=j.pointerId,c(!0),h.current=j.clientX,f.current=_,y.current=_,C(_),j.preventDefault()}},w=j=>{if(s||!l||d.current!==j.pointerId)return;const T=j.clientX-h.current,Y=p(f.current+T);y.current!==Y&&(y.current=Y,C(Y))},E=j=>{if(d.current!==j.pointerId||s)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const T=p(y.current??_);d.current=null,y.current=null,c(!1),u(T)},S=l?y.current??_:_,M=l?S:_;return e.jsxs("aside",{ref:b,className:fe("relative flex h-full overflow-hidden motion-reduce:transition-none","bg-sidebar",a),style:{width:`${M}px`,minWidth:`${M}px`,maxWidth:`${M}px`,"--oc-left-sidebar-width":`${l?S:P}px`,overflowX:"clip",transform:l||x.slidIn?"translateX(0)":"translateX(-100%)",transition:l?"none":x.transition},"aria-hidden":!t||M===0,children:[t&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-30 shadow-[inset_-2px_0_10px_-2px_rgb(0_0_0_/_0.06)]","aria-hidden":"true"}),t&&e.jsx("div",{className:fe("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",l&&"bg-[var(--interactive-border)]"),onPointerDown:U,onPointerMove:w,onPointerUp:E,onPointerCancel:E,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:fe("relative z-10 flex h-full shrink-0 flex-col",l&&"pointer-events-none",!t&&"pointer-events-none select-none"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[i,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(ze,{children:r})})]})]})},Jo=t=>{if(!t||typeof t!="object")return!1;const s=t;return typeof s.x=="number"&&typeof s.y=="number"},Ss=t=>!t||typeof t!="object"?!1:Object.values(t).every(s=>typeof s=="string"),it=t=>{if(!t||typeof t!="object")return!1;const s=t,r=s.bounds;return typeof s.tag=="string"&&typeof s.text=="string"&&typeof s.selector=="string"&&typeof s.path=="string"&&!!r&&typeof r?.x=="number"&&typeof r?.y=="number"&&typeof r?.width=="number"&&typeof r?.height=="number"&&Jo(s.center)&&Ss(s.attributes)&&Ss(s.computedStyle)&&Array.isArray(s.ancestry)},Pt=({pageUrl:t,viewport:s,devicePixelRatio:r,target:a,screenshotAttached:i,intro:o})=>{const u=a.text.trim(),l=Object.entries(a.attributes).map(([b,p])=>`${b}="${p}"`).join(" "),c=a.computedStyle,h=a.bounds,f=a.center,y=o.replace(/[.:]+$/g,""),d=a.ancestry.map(b=>b.selectorPart).join(" > ");return[`${y}:`,`Page: ${t||"preview"}`,`Viewport: ${s.width}x${s.height}, DPR ${r}`,`Screenshot: ${i?"attached":"not attached"}`,`Element: ${a.tag}`,u?`Text: ${u}`:null,`- Selector: ${a.selector}`,`- Path: ${a.path}`,d?`- Ancestry: ${d}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(h.x)}, y=${Math.round(h.y)}, width=${Math.round(h.width)}, height=${Math.round(h.height)}`,`- Center: x=${Math.round(f.x)}, y=${Math.round(f.y)}`,`Styles: display=${c.display}; position=${c.position}; font=${c.fontWeight} ${c.fontSize} / ${c.lineHeight} ${c.fontFamily}; color=${c.color}; background=${c.backgroundColor}; z-index=${c.zIndex}`].filter(b=>typeof b=="string").join(`
3
+ `)},Ve=new Map,Qo=3e4,hn=t=>{const s=Ve.get(t);return s?s.expiresAt-Date.now()<=Qo?(Ve.delete(t),null):s:null},ot="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Dt=new Map;function fn(t){const s="#ffffff",r=t.defaultView??window;try{const a=t.body?r.getComputedStyle(t.body).backgroundColor:"";if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a;const i=r.getComputedStyle(t.documentElement).backgroundColor;if(i&&i!=="rgba(0, 0, 0, 0)"&&i!=="transparent")return i}catch{}return s}const pn=t=>new Promise((s,r)=>{const a=new FileReader;a.onloadend=()=>s(typeof a.result=="string"?a.result:ot),a.onerror=()=>r(a.error??new Error("Failed to read image blob")),a.readAsDataURL(t)}),Zo=async(t,s=.82)=>{const r=await new Promise(a=>t.toBlob(a,"image/jpeg",s));return r&&(await pn(r)).split(",",2)[1]||""},At=async(t,s)=>{try{const r=await fetch(t,{credentials:s});return r.ok?await pn(await r.blob()):null}catch{return null}},ea=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const s=t.origin,r=hn(s);if(r)return`${r.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const a=Dt.get(s),i=a??(async()=>{try{const u=await Ot("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!u.ok)return Ve.delete(s),null;const l=await u.json(),c=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",h=typeof l.expiresAt=="number"?l.expiresAt:0;if(!c)return Ve.delete(s),null;const f={proxyBasePath:c,expiresAt:h};return Ve.set(s,f),f}catch{return Ve.delete(s),null}finally{Dt.delete(s)}})();a||Dt.set(s,i);const o=await i;return o?`${o.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},mn=async(t,s)=>{if(!t||t.startsWith("data:"))return t;try{const r=new URL(t,s.baseURI);if(r.origin===window.location.origin||r.protocol!=="http:"&&r.protocol!=="https:")return await At(r.toString(),"include")??ot;const a=await ea(r),i=a?await At(a,"include"):null;return i||(await At(r.toString(),"omit")??ot)}catch{return ot}},ta=async(t,s)=>{if(!t||t==="none"||!t.includes("url("))return t;const r=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let a=t;for(const i of r){const o=i[2]||"";if(!o||o.startsWith("data:"))continue;const u=await mn(o,s);a=a.replace(i[0],`url("${u}")`)}return a},ks=t=>t.complete?Promise.resolve():new Promise(s=>{t.addEventListener("load",()=>s(),{once:!0}),t.addEventListener("error",()=>s(),{once:!0})}),gn=t=>{const s=t.style.cssText;return()=>{t.style.cssText=s}},sa=t=>{const s=Number.parseFloat(t.lineHeight);if(Number.isFinite(s)&&s>0)return s;const r=Number.parseFloat(t.fontSize);return Number.isFinite(r)&&r>0?r*1.2:16},na=(t,s,r)=>{const a=[],i=t.defaultView??window,u=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of u){const c=l.textContent?.replace(/\s+/g," ").trim()??"";if(!c||!c.includes(" "))continue;const h=l.getBoundingClientRect();if(h.width<=0||h.height<=0||h.right<0||h.bottom<0||h.left>s||h.top>r)continue;const f=i.getComputedStyle(l);if(f.display==="none"||f.visibility==="hidden"||Number(f.opacity)===0)continue;const y=f.getPropertyValue("text-wrap"),d=f.getPropertyValue("text-wrap-mode"),b=f.whiteSpace.includes("nowrap")||y==="nowrap"||d==="nowrap",p=h.height<=sa(f)*1.7;!b&&(!p||h.width>s*.72)||(a.push(gn(l)),l.style.whiteSpace="nowrap",l.style.overflowWrap="normal",l.style.wordBreak="normal",l.style.setProperty("text-wrap","nowrap"),l.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let l=a.length-1;l>=0;l-=1)a[l]?.()}},ra=(t,s,r,a)=>{const i=[],o=t.defaultView??window,u=o.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=o.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,c=Array.from(t.querySelectorAll("*")).filter(h=>{const f=o.getComputedStyle(h);if(f.position!=="fixed"||f.display==="none"||f.visibility==="hidden"||Number(f.opacity)===0)return!1;const y=h.getBoundingClientRect();return y.width>0&&y.height>0&&y.right>=0&&y.bottom>=0&&y.left<=s&&y.top<=r}).filter((h,f,y)=>!y.some((d,b)=>b<f&&d.contains(h)));for(const h of c){const f=h.getBoundingClientRect(),y=o.getComputedStyle(h),d=Math.ceil(f.width)+8,b=Math.ceil(f.height)+2;a?.add(h),i.push(gn(h)),h.style.position="absolute",h.style.top=`${f.top+l}px`,h.style.left=`${f.left+u}px`,h.style.right="auto",h.style.bottom="auto",h.style.width=`${d}px`,h.style.minWidth=`${d}px`,h.style.height=`${b}px`,h.style.minHeight=`${b}px`,h.style.margin="0",h.style.boxSizing="border-box",h.style.transform="none",y.zIndex!=="auto"&&(h.style.zIndex=y.zIndex)}return()=>{for(let h=i.length-1;h>=0;h-=1)i[h]?.()}},xn=async(t,s,r,a={})=>{const i=[],o=t.defaultView??window,u=y=>{if(y===t.documentElement||y===t.body)return!0;try{const d=y.getBoundingClientRect();return d.width>0&&d.height>0&&d.right>=0&&d.bottom>=0&&d.left<=s&&d.top<=r}catch{return!1}};if(a.applyLayoutWorkarounds){const y=new WeakSet;i.push(ra(t,s,r,y)),i.push(na(t,s,r))}const l=new Map;for(const y of Array.from(t.images))l.set(y,y.currentSrc||y.src||y.getAttribute("src")||"");const c=Array.from(t.querySelectorAll("picture"));for(const y of c){const d=Array.from(y.querySelectorAll("source"));if(d.length===0)continue;const b=d.map(p=>({source:p,srcset:p.getAttribute("srcset"),sizes:p.getAttribute("sizes")}));i.push(()=>{for(const p of b)p.srcset===null?p.source.removeAttribute("srcset"):p.source.setAttribute("srcset",p.srcset),p.sizes===null?p.source.removeAttribute("sizes"):p.source.setAttribute("sizes",p.sizes)});for(const p of d)p.removeAttribute("srcset"),p.removeAttribute("sizes")}const h=Array.from(t.images).filter(y=>u(y));await Promise.all(h.map(async y=>{const d=l.get(y)||y.currentSrc||y.src||y.getAttribute("src")||"";if(!d)return;await ks(y);const b=await mn(d,t),p={src:y.getAttribute("src"),srcset:y.getAttribute("srcset"),sizes:y.getAttribute("sizes")};i.push(()=>{p.src===null?y.removeAttribute("src"):y.setAttribute("src",p.src),p.srcset===null?y.removeAttribute("srcset"):y.setAttribute("srcset",p.srcset),p.sizes===null?y.removeAttribute("sizes"):y.setAttribute("sizes",p.sizes)}),y.removeAttribute("srcset"),y.removeAttribute("sizes"),y.setAttribute("src",b||ot),await ks(y)}));const f=Array.from(t.querySelectorAll("*")).filter(u);return await Promise.all(f.map(async y=>{const d=o.getComputedStyle(y).backgroundImage;if(!d||d==="none"||!d.includes("url("))return;const b=await ta(d,t);if(b===d)return;const p=y.style.backgroundImage;i.push(()=>{y.style.backgroundImage=p}),y.style.backgroundImage=b})),()=>{for(let y=i.length-1;y>=0;y-=1)try{i[y]?.()}catch{}}},oa=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},vt=(...t)=>{oa()&&console.info("[preview-capture]",...t)},bn=(t,s=8)=>{const r=[];try{const a=t.querySelectorAll("*");for(const i of a){const o=i.scrollTop||0,u=i.scrollLeft||0;if(o<=0&&u<=0)continue;const l=i.tagName.toLowerCase(),c=i.id?`#${i.id}`:"",h=typeof i.className=="string"&&i.className?`.${i.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(r.push({selector:`${l}${c}${h}`,scrollTop:o,scrollLeft:u,clientWidth:i.clientWidth,clientHeight:i.clientHeight,scrollWidth:i.scrollWidth,scrollHeight:i.scrollHeight}),r.length>=s)break}}catch{}return r},mt="data-oc-fixed-pin",aa=(t,s,r)=>{if(s<=0&&r<=0)return()=>{};const a=t.defaultView;if(!a)return()=>{};const i=[],o=[];try{for(const u of t.querySelectorAll("*")){if(a.getComputedStyle(u).position!=="fixed")continue;const l=u.getBoundingClientRect();if(!(l.width>0&&l.height>0))continue;u.setAttribute(mt,JSON.stringify({top:l.top+r,left:l.left+s,width:l.width,height:l.height})),i.push(u);const c=u.tagName.toLowerCase(),h=typeof u.className=="string"&&u.className?`.${u.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";o.push({selector:`${c}${h}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return vt("tagged fixed elements",o),()=>{for(const u of i)try{u.removeAttribute(mt)}catch{}}},ia={name:"oc-fixed-pin",afterClone(t){const s=t?.clone;if(!(!s||typeof s.querySelectorAll!="function"))for(const r of s.querySelectorAll(`[${mt}]`)){let a;try{a=JSON.parse(r.getAttribute(mt)||"")}catch{continue}r.style.setProperty("position","absolute","important"),r.style.setProperty("top",`${a.top}px`,"important"),r.style.setProperty("left",`${a.left}px`,"important"),r.style.setProperty("right","auto","important"),r.style.setProperty("bottom","auto","important"),r.style.setProperty("width",`${a.width}px`,"important"),r.style.setProperty("height",`${a.height}px`,"important"),r.removeAttribute(mt)}}},nt="data-oc-scroll-pin",la=t=>{const s=[],r=bn(t,64);try{const o=t.documentElement,u=t.body;for(const l of t.querySelectorAll("*")){const c=l.scrollTop||0,h=l.scrollLeft||0;if(c<=0&&h<=0)continue;const f=l!==o&&l!==u;f&&l.setAttribute(nt,JSON.stringify({top:c,left:h})),s.push({el:l,top:c,left:h,tagged:f})}}catch{}return{reapply:()=>{for(const o of s)try{o.el.scrollHeight,o.el.scrollTop!==o.top&&(o.el.scrollTop=o.top),o.el.scrollLeft!==o.left&&(o.el.scrollLeft=o.left)}catch{}},cleanup:()=>{for(const o of s)if(o.tagged)try{o.el.removeAttribute(nt)}catch{}},snapshot:r}},ca={name:"oc-nested-scroll",afterClone(t){const s=t?.clone;if(!s||typeof s.querySelectorAll!="function")return;const r=s.ownerDocument;if(r)for(const a of s.querySelectorAll(`[${nt}]`)){let i;try{i=JSON.parse(a.getAttribute(nt)||"")}catch{a.removeAttribute(nt);continue}const o=`translate(${-i.left}px, ${-i.top}px)`,u=a.children.length===1&&a.firstElementChild instanceof HTMLElement&&a.firstElementChild.style.willChange==="transform"?a.firstElementChild:null;if(u)u.style.transform=o;else{a.style.overflow="hidden";const l=r.createElement("div");for(l.style.transform=o,l.style.willChange="transform",l.style.display="inline-block",l.style.width="100%";a.firstChild;)l.appendChild(a.firstChild);a.appendChild(l)}a.removeAttribute(nt)}}},wn=async(t,s)=>{if(In())try{const r=t.getBoundingClientRect(),a=await Vs("desktop_capture_page_rect",{x:r.left,y:r.top,width:r.width,height:r.height});if(!a)throw new Error("Desktop screenshot capture is not available");const i=new Image;await new Promise((p,C)=>{i.onload=()=>p(),i.onerror=()=>C(new Error("Failed to load desktop preview screenshot")),i.src=`data:${a.mime};base64,${a.base64}`});const o=Math.max(1,i.naturalWidth||a.width||Math.floor(r.width)),u=Math.max(1,i.naturalHeight||a.height||Math.floor(r.height)),c=Math.min(1,1200/o),h=document.createElement("canvas");h.width=Math.floor(o*c),h.height=Math.floor(u*c);const f=h.getContext("2d");if(!f)return null;f.scale(c,c),f.drawImage(i,0,0,o,u);const y=o/Math.max(1,r.width),d=u/Math.max(1,r.height);f.fillStyle="rgba(37, 99, 235, 0.28)",f.strokeStyle="rgb(37, 99, 235)",f.lineWidth=Math.max(2,2*y),f.fillRect(s.bounds.x*y,s.bounds.y*d,s.bounds.width*y,s.bounds.height*d),f.strokeRect(s.bounds.x*y,s.bounds.y*d,s.bounds.width*y,s.bounds.height*d);const b=await new Promise(p=>h.toBlob(p,"image/jpeg",.82));return b?new File([b],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(r){console.warn("[preview] failed to capture annotation screenshot:",r)}return await ua(t,s)},Rt=async(t,s,r,a,i,o)=>{if(!t)return null;try{const u=new Image;await new Promise((x,P)=>{u.onload=()=>x(),u.onerror=()=>P(new Error("Failed to load desktop browser screenshot")),u.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,u.naturalWidth||s),c=Math.max(1,u.naturalHeight||r),f=Math.min(1,1200/l),y=document.createElement("canvas");y.width=Math.floor(l*f),y.height=Math.floor(c*f);const d=y.getContext("2d");if(!d)return null;d.scale(f,f),d.drawImage(u,0,0,l,c);const b=l/Math.max(1,a||l),p=c/Math.max(1,i||c);d.fillStyle="rgba(37, 99, 235, 0.14)",d.strokeStyle="rgb(37, 99, 235)",d.lineWidth=Math.max(2,2*b),d.fillRect(o.bounds.x*b,o.bounds.y*p,o.bounds.width*b,o.bounds.height*p),d.strokeRect(o.bounds.x*b,o.bounds.y*p,o.bounds.width*b,o.bounds.height*p);const C=await new Promise(x=>y.toBlob(x,"image/jpeg",.82));return C?new File([C],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}};async function da(t,s){try{const r=t.contentWindow,a=t.contentDocument??r?.document,i=a?.documentElement;if(!r||!a||!i)return null;const o=t.getBoundingClientRect(),u=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||o.width)),l=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||o.height)),c=a.body,h=a.scrollingElement instanceof HTMLElement?a.scrollingElement:null,f=r.scrollX||0,y=r.scrollY||0,d=r.pageXOffset||0,b=r.pageYOffset||0,p=r.visualViewport?.pageLeft||r.visualViewport?.offsetLeft||0,C=r.visualViewport?.pageTop||r.visualViewport?.offsetTop||0,x=i.scrollLeft||0,P=i.scrollTop||0,_=c?.scrollLeft||0,U=c?.scrollTop||0,w=h?.scrollLeft||0,E=h?.scrollTop||0,S=Math.max(f,d,p,x,_,w),M=Math.max(y,b,C,P,U,E);vt("scroll sources",{windowScrollX:f,windowScrollY:y,pageScrollX:d,pageScrollY:b,visualViewportScrollX:p,visualViewportScrollY:C,rootScrollX:x,rootScrollY:P,bodyScrollX:_,bodyScrollY:U,scrollingElementScrollX:w,scrollingElementScrollY:E,scrollingElementTag:h?.tagName?.toLowerCase()??null,resolvedScrollX:S,resolvedScrollY:M,nestedScrolledElements:bn(a)});const j=Math.max(u,i.scrollWidth||0,c?.scrollWidth||0,Math.ceil(i.getBoundingClientRect().width||0)),T=Math.max(l,i.scrollHeight||0,c?.scrollHeight||0,Math.ceil(i.getBoundingClientRect().height||0)),Y=Math.min(2,Math.max(1,window.devicePixelRatio||1)),X=i.style.scrollBehavior,z=c?.style.scrollBehavior??"";i.style.scrollBehavior="auto",c&&(c.style.scrollBehavior="auto");const Z=la(a);vt("nested scroll snapshot",Z.snapshot);let le=()=>{},H=()=>{};try{await a.fonts?.ready.catch(()=>{}),le=await xn(a,u,l,{applyLayoutWorkarounds:!1}),r.scrollTo(S,M),H=aa(a,S,M),Z.reapply();const{snapdom:ne}=await Oe(async()=>{const{snapdom:Re}=await import("./vendor-zumer-snapdom-SJzqoCHV.js");return{snapdom:Re}},[]),N={backgroundColor:fn(a),cache:"disabled",dpr:Y,embedFonts:!0,fast:!1,height:T,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[ia,ca],quality:.82,width:j},oe=await(await ne(i,N)).toCanvas();if(!oe.width||!oe.height)return null;const D=oe.width/Math.max(1,j),O=oe.height/Math.max(1,T),G=Math.min(oe.width,Math.max(1,Math.round(u*D))),ue=Math.min(oe.height,Math.max(1,Math.round(l*O))),ge=Math.max(0,oe.width-G),he=Math.max(0,oe.height-ue),be=Math.min(ge,Math.max(0,Math.round(S*D))),je=Math.min(he,Math.max(0,Math.round(M*O)));vt("capture geometry",{viewportWidth:u,viewportHeight:l,captureWidth:j,captureHeight:T,canvasWidth:oe.width,canvasHeight:oe.height,xScale:D,yScale:O,sourceX:be,sourceY:je,sourceWidth:G,sourceHeight:ue});const Ce=a.createElement("canvas");Ce.width=G,Ce.height=ue;const ve=Ce.getContext("2d");if(!ve)return null;ve.drawImage(oe,be,je,G,ue,0,0,G,ue);const ye=await Zo(Ce,.82);return ye?await Rt(ye,u,l,u,l,s):null}finally{H(),Z.cleanup(),le(),r.scrollTo(S,M),Z.reapply(),i.style.scrollBehavior=X,c&&(c.style.scrollBehavior=z)}}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",r),null}}async function ua(t,s){const r=await da(t,s);if(r)return r;try{const a=t.contentWindow,i=t.contentDocument??a?.document,o=i?.documentElement;if(!a||!i||!o)return null;const u=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(a.innerWidth||t.clientWidth||u.width)),c=Math.max(1,Math.ceil(a.innerHeight||t.clientHeight||u.height)),h=a.scrollX||i.documentElement.scrollLeft||i.body?.scrollLeft||0,f=a.scrollY||i.documentElement.scrollTop||i.body?.scrollTop||0,y=i.body,d=Math.max(c,o.scrollHeight||0,y?.scrollHeight||0),b=Math.min(2,Math.max(1,window.devicePixelRatio||1)),p=o.style.scrollBehavior,C=y?.style.scrollBehavior??"";o.style.scrollBehavior="auto",y&&(y.style.scrollBehavior="auto");let x="",P=()=>{};try{await i.fonts?.ready.catch(()=>{}),P=await xn(i,l,c,{applyLayoutWorkarounds:!0}),a.scrollTo(h,f);const{getFontEmbedCSS:U,toJpeg:w}=await Oe(async()=>{const{getFontEmbedCSS:S,toJpeg:M}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:S,toJpeg:M}},[]),E=await U(o).catch(()=>"");x=await w(o,{quality:.82,pixelRatio:b,width:l,height:c,backgroundColor:fn(i),imagePlaceholder:ot,fontEmbedCSS:E||void 0,style:{transform:`translate(${-h}px, ${-f}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${d}px`},cacheBust:!0})}finally{P(),a.scrollTo(h,f),o.style.scrollBehavior=p,y&&(y.style.scrollBehavior=C)}const _=x.split(",",2)[1]||"";return _?await Rt(_,l,c,l,c,s):null}catch(a){return console.warn("[preview] failed to capture iframe DOM screenshot:",a),null}}const Cs=200,ha=(t,s)=>s==="all"?!0:s==="errors"?t.level==="error"||t.level==="runtime"||t.level==="resource":s==="warnings"?t.level==="warn":t.level==="log"||t.level==="info"||t.level==="debug",gt=t=>{const s=xt.getState();s.setPendingSyntheticParts([...s.pendingSyntheticParts??[],{text:t,synthetic:!0}])},fa=async t=>{const s=await t.json().catch(()=>({}));if(!t.ok)return{ok:!1,message:typeof s.error=="string"?s.error:`HTTP ${t.status}`};const r=typeof s.proxyBasePath=="string"?s.proxyBasePath:"",a=typeof s.previewToken=="string"?s.previewToken:"";return!r||!a?{ok:!1,message:"Could not start preview proxy."}:{ok:!0,target:{proxyBasePath:r,previewToken:a,expiresAt:typeof s.expiresAt=="number"?s.expiresAt:0}}},yn=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Ns=(t,s,r)=>{t.postMessage(r,yn(s))},pa=t=>{if(!t)return t;try{const s=new URL(t);return s.searchParams.delete("oc_preview_token"),s.searchParams.delete("oc_client_token"),s.searchParams.delete("oc_url_token"),s.toString()}catch{return t}},vn=`new Promise((resolve) => {
4
+ const existing = document.getElementById('__pichamber_desktop_browser_overlay');
5
+ if (existing) existing.remove();
6
+ if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
7
+ try { window.__pichamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
8
+ }
9
+ const overlay = document.createElement('div');
10
+ overlay.id = '__pichamber_desktop_browser_overlay';
11
+ overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
12
+ document.documentElement.appendChild(overlay);
13
+ const cssEscape = (value) => {
14
+ try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
15
+ };
16
+ const selectorPart = (element) => {
17
+ const tag = element.tagName.toLowerCase();
18
+ if (element.id) return tag + '#' + cssEscape(element.id);
19
+ const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
20
+ return tag + className;
21
+ };
22
+ const metadata = (element) => {
23
+ const rect = element.getBoundingClientRect();
24
+ const style = getComputedStyle(element);
25
+ const ancestry = [];
26
+ let current = element;
27
+ while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
28
+ ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
29
+ current = current.parentElement;
30
+ }
31
+ const attrs = {};
32
+ for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
33
+ const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
34
+ return {
35
+ frame: 'top',
36
+ tag: element.tagName.toLowerCase(),
37
+ text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
38
+ selector: element.id ? '#' + cssEscape(element.id) : path,
39
+ path,
40
+ bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
41
+ center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
42
+ attributes: attrs,
43
+ computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
44
+ ancestry,
45
+ };
46
+ };
47
+ const move = (event) => {
48
+ const element = document.elementFromPoint(event.clientX, event.clientY);
49
+ if (!element || element === overlay || element === document.documentElement || element === document.body) return;
50
+ const rect = element.getBoundingClientRect();
51
+ overlay.style.display = 'block';
52
+ overlay.style.left = rect.left + 'px';
53
+ overlay.style.top = rect.top + 'px';
54
+ overlay.style.width = rect.width + 'px';
55
+ overlay.style.height = rect.height + 'px';
56
+ };
57
+ const cleanup = () => {
58
+ window.removeEventListener('mousemove', move, true);
59
+ window.removeEventListener('click', click, true);
60
+ window.removeEventListener('keydown', keydown, true);
61
+ if (window.__pichamberDesktopBrowserCancelInspect === cancel) {
62
+ delete window.__pichamberDesktopBrowserCancelInspect;
63
+ }
64
+ };
65
+ const cancel = () => {
66
+ cleanup();
67
+ overlay.remove();
68
+ resolve(null);
69
+ };
70
+ const click = (event) => {
71
+ event.preventDefault();
72
+ event.stopPropagation();
73
+ const element = document.elementFromPoint(event.clientX, event.clientY);
74
+ const result = element ? metadata(element) : null;
75
+ cleanup();
76
+ overlay.remove();
77
+ resolve(result);
78
+ };
79
+ const keydown = (event) => {
80
+ if (event.key !== 'Escape') return;
81
+ cancel();
82
+ };
83
+ window.__pichamberDesktopBrowserCancelInspect = cancel;
84
+ window.addEventListener('mousemove', move, true);
85
+ window.addEventListener('click', click, true);
86
+ window.addEventListener('keydown', keydown, true);
87
+ });`,jt=`(() => {
88
+ if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
89
+ window.__pichamberDesktopBrowserCancelInspect();
90
+ return;
91
+ }
92
+ const overlay = document.getElementById('__pichamber_desktop_browser_overlay');
93
+ if (overlay) overlay.remove();
94
+ })()`,ma=`(() => {
95
+ if (window.__pichamberSameWebviewNavigationInstalled) return;
96
+ window.__pichamberSameWebviewNavigationInstalled = true;
97
+
98
+ const navigate = (rawUrl) => {
99
+ if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
100
+ try {
101
+ const url = new URL(rawUrl, window.location.href);
102
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
103
+ window.location.assign(url.href);
104
+ return true;
105
+ } catch (_error) {
106
+ return false;
107
+ }
108
+ };
109
+
110
+ const originalOpen = window.open.bind(window);
111
+ window.open = (url, target, features) => {
112
+ if (navigate(url)) return null;
113
+ return originalOpen(url, target, features);
114
+ };
115
+
116
+ document.addEventListener('click', (event) => {
117
+ if (event.defaultPrevented) return;
118
+ const target = event.target;
119
+ if (!(target instanceof Element)) return;
120
+ const anchor = target.closest('a[target="_blank"][href]');
121
+ if (!(anchor instanceof HTMLAnchorElement)) return;
122
+ if (!navigate(anchor.href)) return;
123
+ event.preventDefault();
124
+ event.stopPropagation();
125
+ }, true);
126
+ })()`,ga=/^(localhost|127(\.\d{1,3}){1,3}|0\.0\.0\.0|\[::1?\]|10(\.\d{1,3}){3}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|192\.168(\.\d{1,3}){2}|[^/:?#]+\.(local|localhost))(?=[:/?#]|$)/i,Ht=t=>{try{return new URL(t).host||t}catch{return t}},lt=t=>{const s=t.trim();if(!s)return"about:blank";try{const r=ga.test(s)?"http":"https",a=new URL(s.includes("://")?s:`${r}://${s}`);return a.protocol!=="http:"&&a.protocol!=="https:"?"about:blank":a.toString()}catch{return"about:blank"}},Ps=async(t,s)=>{const r=t.contentWindow;if(!r)throw new Error("Iframe window is not available");const i=r.eval.call(r,s);return await Promise.resolve(i)},Rs=["B","KB","MB","GB","TB"],rt=t=>{let s=Math.max(0,t),r=0;for(;s>=1024&&r<Rs.length-1;)s/=1024,r+=1;return`${r===0||s>=10?Math.round(s):s.toFixed(1)} ${Rs[r]}`},xa=t=>{try{return new URL(t).host}catch{return""}},ba=t=>{const s=t.url?xa(t.url):"",r=a=>s?`${a} · ${s}`:a;switch(t.state){case"inProgress":return t.totalBytes>0?`${rt(t.receivedBytes)} of ${rt(t.totalBytes)}`:`${rt(t.receivedBytes)} so far`;case"completed":return r(rt(t.totalBytes));case"canceled":return r("Canceled");default:return r("Failed")}},wa=t=>({id:t.id,filename:t.filename,url:t.url??"",state:t.state,receivedBytes:t.receivedBytes,totalBytes:t.totalBytes,path:t.path??null,savedPath:t.savedPath??null,startedAt:t.startedAt}),ya=(t,s)=>{const r=t.findIndex(i=>i.id===s.id);if(r===-1)return[...t,s];const a=t.slice();return a[r]=s,a};class va{constructor(s,r,a,i){this.tab=s,this.start=r,this.listener=a,this.deps=i}tab;start;listener;deps;socket=null;active=!1;disposed=!1;failures=0;retryTimer=null;generation=0;claimed=!1;setActive(s){if(!(this.disposed||s===this.active)){if(this.active=s,s){this.failures=0,this.connect();return}this.clearRetry(),this.closeSocket(),this.listener.onPhase("idle")}}retry(){this.disposed||!this.active||(this.clearRetry(),this.closeSocket(),this.failures=0,this.connect())}send(s){return this.socket?.readyState!==1?!1:(this.socket.send(JSON.stringify(s)),!0)}ack(){this.send({type:"ack"})}dispose(){this.disposed=!0,this.active=!1,this.clearRetry(),this.closeSocket()}clearRetry(){this.retryTimer!==null&&this.deps.clearTimeout(this.retryTimer),this.retryTimer=null}closeSocket(){this.generation+=1;const s=this.socket;if(this.socket=null,!!s){s.onopen=null,s.onmessage=null,s.onerror=null,s.onclose=null;try{s.close(1e3)}catch{}}}scheduleReconnect(){if(this.disposed||!this.active||this.retryTimer!==null)return;const s=ls[Math.min(this.failures,ls.length-1)];this.failures+=1,this.listener.onPhase("reconnecting"),this.retryTimer=this.deps.setTimeout(()=>{this.retryTimer=null,this.connect()},s)}async connect(){if(this.disposed||!this.active)return;const s=++this.generation;this.listener.onPhase(this.failures>0?"reconnecting":"connecting");let r;try{const{url:u,popup:l}=this.start();r=await this.deps.open(this.tab,u,this.claimed?null:l??null)}catch{s===this.generation&&this.scheduleReconnect();return}const{socket:a,urlAuthToken:i}=r;if(s!==this.generation||this.disposed||!this.active){try{a.close(1e3)}catch{}return}this.socket=a,a.binaryType="arraybuffer";let o=!1;a.onopen=()=>{o=!0,this.claimed=!0,this.failures=0,this.listener.onPhase("open"),this.listener.onOpen()},a.onmessage=u=>{if(typeof u.data=="string"){const c=rr(u.data);c&&this.listener.onMessage(c);return}const l=or(u.data);l?this.listener.onFrame(l.header,l.jpeg):this.ack()},a.onerror=()=>{},a.onclose=u=>{if(this.socket!==a)return;this.socket=null,o||this.deps.forgetToken(i);const l=o?ar(u.code):"reconnect";if(l==="unavailable"){this.listener.onPhase("unavailable");return}if(l==="stop"){this.listener.onPhase("failed");return}if(l==="closed"){this.listener.onPhase("closed");return}this.scheduleReconnect()}}}const Es=({fraction:t,label:s})=>{const r=t===null?null:Math.min(1,Math.max(0,t));return e.jsx("div",{role:"progressbar","aria-label":s,"aria-valuemin":0,"aria-valuemax":100,...r!==null?{"aria-valuenow":Math.round(r*100)}:{},className:"h-1 w-full overflow-hidden rounded-full bg-[var(--interactive-border)]",children:e.jsx("div",{className:"h-full w-full origin-left rounded-full bg-[var(--primary-base)] transition-transform duration-200",style:{transform:`scaleX(${r??0})`}})})},ja=({download:t,deviceSave:s,savingToServer:r,onCancel:a,onSaveToDevice:i,onSaveToServer:o,onCopyPath:u})=>{const l=t.state==="completed",c=t.state==="canceled"||t.state==="failed",h=s?.state==="saving";let f=ba(t);return h?f=s.totalBytes>0?`Copying to this device: ${rt(s.receivedBytes)} of ${rt(s.totalBytes)}`:"Copying to this device":l&&t.savedPath?f=`Saved on the server: ${t.savedPath}`:l&&s?.state==="ready"?f="Copied to this device. Tap Share to save it.":l&&s?.state==="saved"&&(f=`${f} · Saved to this device`),e.jsxs("li",{className:"flex items-start gap-2.5 px-3 py-2",children:[e.jsx(Ct,{filePath:t.filename,className:c?"mt-0.5 size-5 shrink-0 opacity-50":"mt-0.5 size-5 shrink-0"}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("span",{className:c?"truncate typography-meta text-muted-foreground line-through":"truncate typography-meta text-foreground",title:t.filename,children:t.filename}),e.jsx("span",{className:t.state==="failed"?"truncate typography-micro text-[var(--status-error)]":"truncate typography-micro text-muted-foreground",title:f,children:f})]}),t.state==="inProgress"?e.jsx(Q,{type:"button",variant:"ghost",size:"xs",onClick:a,children:"Cancel"}):null]}),t.state==="inProgress"?e.jsx(Es,{fraction:t.totalBytes>0?t.receivedBytes/t.totalBytes:null,label:`Downloading ${t.filename} on the server`}):null,h?e.jsx(Es,{fraction:s.totalBytes>0?s.receivedBytes/s.totalBytes:null,label:`Copying ${t.filename} to this device`}):null,l?e.jsxs("div",{className:"-ml-1.5 flex flex-wrap items-center gap-1",children:[e.jsxs(Q,{type:"button",variant:"ghost",size:"xs",disabled:h,onClick:i,children:[e.jsx(W,{name:"download",className:"size-3.5"}),s?.state==="ready"?"Share":"Save to this device"]}),e.jsxs(Q,{type:"button",variant:"ghost",size:"xs",disabled:r,onClick:o,title:"Copy it into the Downloads folder on the server",children:[e.jsx(W,{name:"server",className:"size-3.5"}),r?"Saving...":"Save to server"]}),e.jsxs(Q,{type:"button",variant:"ghost",size:"xs",onClick:u,title:t.savedPath?"Copy where the file is on the server":"Copy where the file waits on the server (temporary)",children:[e.jsx(W,{name:"file-copy",className:"size-3.5"}),"Copy path"]})]}):null]})]})},Sa=({downloads:t,open:s,onClose:r,onCancel:a})=>{const[i,o]=n.useState({}),[u,l]=n.useState({}),c=(C,x)=>o(P=>({...P,[C]:x})),h=async(C,x)=>{try{const P=await cr(x,C.filename);c(C.id,P==="cancelled"?{state:"ready",blob:x}:{state:"saved"})}catch(P){if(dr(P)){c(C.id,{state:"ready",blob:x});return}c(C.id,{state:"failed"}),xe.error(P instanceof Error?P.message:`Could not save ${C.filename} to this device`)}},f=async C=>{const x=i[C.id];if(x?.state==="ready"){await h(C,x.blob);return}c(C.id,{state:"saving",receivedBytes:0,totalBytes:C.totalBytes});let P;try{P=await lr(C.id,C.filename,{onProgress:(_,U)=>c(C.id,{state:"saving",receivedBytes:_,totalBytes:U})})}catch(_){c(C.id,{state:"failed"}),xe.error(_ instanceof Error?_.message:`Could not save ${C.filename} to this device`);return}await h(C,P)},y=async C=>{l(x=>({...x,[C.id]:!0}));try{const x=await ir(C.id);xe.success(`Saved ${C.filename} on the server`,{description:x,action:{label:"Copy path",onClick:()=>{d(x)}}})}catch(x){xe.error(x instanceof Error?x.message:`Could not save ${C.filename} on the server`)}finally{l(x=>({...x,[C.id]:!1}))}},d=async C=>{(await ct(C)).ok?xe.success("Path copied",{description:C}):xe.error("Could not copy the path",{description:C})};if(!s||t.length===0)return null;const b=[...t].reverse(),p=t.filter(C=>C.state==="inProgress").length;return e.jsxs("section",{"aria-label":"Downloads",className:"flex max-h-[40%] min-h-0 shrink-0 flex-col border-t border-border bg-[var(--surface-elevated)]",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/60 px-3 py-1",children:[e.jsx("span",{className:"min-w-0 flex-1 typography-micro text-muted-foreground",children:p>0?`Downloading on the server (${p})`:"Downloaded on the server"}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:r,title:"Hide downloads","aria-label":"Hide downloads",children:e.jsx(W,{name:"close",className:"h-3.5 w-3.5"})})]}),e.jsx("ul",{className:"min-h-0 flex-1 divide-y divide-border/60 overflow-y-auto",children:b.map(C=>e.jsx(ja,{download:C,deviceSave:i[C.id],savingToServer:u[C.id]===!0,onCancel:()=>a(C.id),onSaveToDevice:()=>{f(C)},onSaveToServer:()=>{y(C)},onCopyPath:()=>{const x=C.savedPath??C.path;x&&d(x)}},C.id))})]})},ka=5e3,Ca=5,Na=t=>({project:t.filter(s=>s.inProject),others:t.filter(s=>!s.inProject&&s.title).slice(0,Ca)}),Ts=({label:t,servers:s,onOpen:r})=>e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"px-1 typography-micro text-muted-foreground",children:t}),e.jsx("div",{className:"flex flex-col overflow-hidden rounded-md border border-border/60",children:s.map(a=>{const i=`localhost:${a.port}`;return e.jsxs("button",{type:"button",className:"flex min-w-0 flex-col gap-0.5 border-b border-border/60 px-3 py-2 text-left last:border-b-0 hover:bg-interactive-hover focus-visible:bg-interactive-hover focus-visible:outline-none",onClick:()=>r(a.url),children:[e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:a.title||i}),e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:[a.title?i:null,a.process].filter(Boolean).join(" · ")})]},a.port)})})]}),Pa=({directory:t,onOpen:s})=>{const[r,a]=n.useState(null);return n.useEffect(()=>{let i=!1,o=null,u=null;const l=async()=>{if(document.visibilityState==="visible"){u=new AbortController;try{const c=await ur(t,u.signal);i||a(Na(c))}catch{}}i||(o=setTimeout(()=>{l()},ka))};return l(),()=>{i=!0,u?.abort(),o&&clearTimeout(o)}},[t]),!r||r.project.length===0&&r.others.length===0?null:e.jsxs("div",{className:"pointer-events-auto flex w-full max-w-sm flex-col gap-4 text-left",children:[r.project.length>0?e.jsx(Ts,{label:"Running in this project",servers:r.project,onOpen:s}):null,r.others.length>0?e.jsx(Ts,{label:r.project.length>0?"Other servers":"Running on the server",servers:r.others,onOpen:s}):null]})},Ra=({command:t})=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-[var(--surface-elevated)] py-1 pl-3 pr-1",children:[e.jsx("code",{className:"min-w-0 flex-1 overflow-x-auto whitespace-nowrap typography-code text-foreground",children:t}),e.jsx(Q,{type:"button",variant:"ghost",size:"xs",onClick:()=>{ct(t).then(s=>{s.ok?xe.success("Command copied"):xe.error("Could not copy the command")})},children:"Copy"})]}),Ea=t=>{const s=t.problem,r=t.installCommands;return!s||s.kind==="missing"?{title:"Install Chrome on the server",body:"The server browser runs Google Chrome or Chromium on the machine running PiChamber. Install one there, then check again. To use a browser installed somewhere else, set PICHAMBER_BROWSER_CHROME to its executable and restart PiChamber.",commands:r}:s.kind==="missing-env"?{title:`${s.envKey} does not point to a browser`,body:`PiChamber was started with ${s.envKey} set, but no file exists at that path. Fix the path or unset it, then restart PiChamber.`,commands:[]}:s.kind==="sandbox-root"||s.kind==="launch-failed"&&s.reason==="sandbox-root"?{title:"Chrome will not run as root with its sandbox",body:"PiChamber runs as root on this server, and Chrome refuses to start its sandbox as root. Run PiChamber as a regular user, or allow Chrome to run without its sandbox below.",commands:[]}:s.reason==="missing-library"?{title:"Chrome is missing system libraries",body:`Chrome could not start because ${s.library??"a library"} is not installed on the server. Installing Chrome with its dependencies adds what it needs.`,commands:r,detail:s.detail}:s.reason==="sandbox-namespaces"?{title:"Chrome's sandbox is not available",body:"This server does not allow the user namespaces Chrome uses for its sandbox, which is common in containers. Enable unprivileged user namespaces, or allow Chrome to run without its sandbox below.",commands:[],detail:s.detail}:{title:"Chrome did not start",body:"The server browser could not start Chrome. The output below may explain why.",commands:[],detail:s.detail}},Ta=t=>{const s=t.problem;return!s||t.allowNoSandbox?!1:s.kind==="sandbox-root"?!0:s.kind==="launch-failed"&&(s.reason==="sandbox-root"||s.reason==="sandbox-namespaces")},Da=({status:t,onRetry:s,onUseDevice:r})=>{const[a,i]=n.useState(!1),o=Ea(t),u=async()=>{i(!0);try{await hr({allowNoSandbox:!0}),s()}catch(l){xe.error(l instanceof Error?l.message:"Could not save the setting")}finally{i(!1)}};return e.jsx("div",{className:"absolute inset-0 overflow-y-auto bg-background",children:e.jsxs("div",{className:"mx-auto flex max-w-xl flex-col gap-4 px-6 py-10",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-ui-header text-foreground [text-wrap:balance]",children:o.title}),e.jsx("p",{className:"typography-meta text-muted-foreground [text-wrap:pretty]",children:o.body})]}),o.commands.length>0?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:o.commands.length===1?"Run this on the server:":"Run one of these on the server:"}),o.commands.map(l=>e.jsx(Ra,{command:l},l))]}):null,Ta(t)?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground [text-wrap:pretty]",children:"Without its sandbox, a page that exploits a bug in Chrome can reach the server with the permissions PiChamber runs with. Only do this on a machine you are comfortable exposing to the sites you open."}),e.jsx("div",{children:e.jsx(Q,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{u()},children:"Allow without sandbox"})})]}):null,o.detail?e.jsx("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap rounded-md border border-border/60 bg-[var(--surface-elevated)] p-3 typography-code text-muted-foreground",children:o.detail}):null,e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Q,{type:"button",size:"sm",onClick:s,children:"Check again"}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:r,children:"Load on this device instead"})]})]})})},Aa=t=>t.kind==="beforeunload"?{message:"Leave this page? Changes you made may not be saved.",accept:"Leave",dismiss:"Stay"}:t.kind==="alert"?{message:t.message,accept:"OK",dismiss:null}:{message:t.message,accept:"OK",dismiss:"Cancel"},_a=({multiple:t,uploading:s,onChoose:r,onCancel:a})=>e.jsxs("div",{className:"absolute inset-x-0 top-0 flex flex-wrap items-center gap-2 border-b border-border bg-[var(--surface-elevated)] px-3 py-2",children:[e.jsx("span",{className:"min-w-0 flex-1 typography-micro text-foreground",children:t?"This page asks for files.":"This page asks for a file."}),e.jsx(Q,{type:"button",size:"xs",disabled:s,onClick:r,children:s?"Uploading...":t?"Choose files":"Choose file"}),e.jsx(Q,{type:"button",variant:"ghost",size:"xs",disabled:s,onClick:a,children:"Cancel"})]}),Ma=({dialog:t,promptText:s,onPromptTextChange:r,onRespond:a})=>{const i=Aa(t);return e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 p-4",children:e.jsxs("form",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-[var(--surface-elevated)] p-4 shadow-lg",onSubmit:o=>{o.preventDefault(),a(!0)},children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:`${Ht(t.url)} says`}),e.jsx("p",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap typography-meta text-foreground [text-wrap:pretty]",children:i.message}),t.kind==="prompt"?e.jsx("input",{autoFocus:!0,value:s,onChange:o=>r(o.target.value),className:"h-8 rounded-md border border-border/50 bg-background px-2 typography-meta text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Answer"}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[i.dismiss?e.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:()=>a(!1),children:i.dismiss}):null,e.jsx(Q,{type:"submit",size:"sm",autoFocus:t.kind!=="prompt",children:i.accept})]})]})})},Ia=({onReload:t})=>e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center",children:[e.jsx("span",{className:"typography-ui-header text-foreground",children:"This page crashed"}),e.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:t,children:"Reload"})]}),La=({phase:t,status:s,failure:r,hasFrame:a,showBlank:i,directory:o,onRetry:u,onSetupRetry:l,onUseDevice:c,onOpenAddress:h})=>t==="unavailable"?s?e.jsx(Da,{status:s,onRetry:l,onUseDevice:c}):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center",children:[e.jsx("span",{className:"typography-ui-header text-foreground",children:"The server browser is not available"}),r?e.jsx("span",{className:"max-w-md typography-micro text-muted-foreground [text-wrap:pretty]",children:r}):null,e.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:u,children:"Try again"})]}):t==="failed"?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center",children:[e.jsx("span",{className:"typography-ui-header text-foreground",children:"Could not open this tab"}),e.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:u,children:"Try again"})]}):(t==="connecting"||t==="reconnecting")&&!a?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background typography-micro text-muted-foreground",children:t==="connecting"?"Starting the server browser...":"Reconnecting to the server browser..."}):t==="reconnecting"?e.jsx("div",{className:"absolute inset-x-0 top-0 border-b border-border bg-[var(--surface-elevated)] px-3 py-1.5 typography-micro text-muted-foreground",children:"Reconnecting to the server browser..."}):i?e.jsxs("div",{className:"pointer-events-none absolute inset-0 flex flex-col items-center justify-center-safe gap-6 overflow-y-auto bg-background p-6 text-center",children:[e.jsx(Xt,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground [text-wrap:pretty]",children:"Pages run in a browser on the PiChamber server, so localhost addresses reach the server."}),e.jsx(Pa,{directory:o,onOpen:h})]}):null,Ba=({decode:t,paint:s,ack:r})=>{let a={busy:!1,pending:null};const i=async(o,u)=>{const l=a;l.busy=!0;let c=null;try{c=await t(u)}catch{}if(a!==l){c?.close();return}try{c&&s(c,o)}finally{c?.close(),r(),l.busy=!1;const h=l.pending;l.pending=null,h&&i(h.header,h.jpeg)}};return{onFrame(o,u){if(a.busy){a.pending&&r(),a.pending={header:o,jpeg:u};return}i(o,u)},reset(){a={busy:!1,pending:null}}}},Oa=t=>{const s=n.useRef(null),r=n.useRef(null),[a,i]=n.useState(null),o=n.useRef(t);o.current=t;const[u]=n.useState(()=>Ba({decode:h=>createImageBitmap(new Blob([h],{type:"image/jpeg"})),paint:(h,f)=>{const y=s.current,d=y?.getContext("2d");y&&d&&(y.width!==h.width&&(y.width=h.width),y.height!==h.height&&(y.height=h.height),d.drawImage(h,0,0));const b=r.current;r.current=f,(!b||b.width!==f.width||b.height!==f.height)&&i({width:f.width,height:f.height})},ack:()=>o.current()})),l=n.useCallback((h,f)=>u.onFrame(h,f),[u]),c=n.useCallback(()=>u.reset(),[u]);return{canvasRef:s,headerRef:r,frameSize:a,onFrame:l,reset:c}},$a=500,Ds=6,As=["left","middle","right"],Fa=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),Wa=({send:t,canvasRef:s,headerRef:r,areaHeight:a,inspecting:i,onInspectHover:o,onInspectPick:u})=>{const l=n.useRef(null),c=n.useRef({at:0,x:0,y:0,count:0}),h=n.useRef(null),f=n.useRef(null),y=n.useRef(a);y.current=a;const d=n.useCallback((w,E)=>{const S=s.current,M=r.current;return!S||!M?null:fr(w,E,S.getBoundingClientRect(),M)},[s,r]),b=n.useCallback(()=>l.current?.focus({preventScroll:!0}),[]);n.useEffect(()=>{const w=s.current;if(!w)return;const E=S=>{S.preventDefault();const M=d(S.clientX,S.clientY);if(!M)return;const j=S.deltaMode===1?40:S.deltaMode===2?y.current():1;t({type:"mouse",action:"wheel",...M,deltaX:S.deltaX*j,deltaY:S.deltaY*j,modifiers:dt(S)})};return w.addEventListener("wheel",E,{passive:!1}),()=>w.removeEventListener("wheel",E)},[s,d,t]);const p=w=>{w.preventDefault(),b();const E=d(w.clientX,w.clientY);if(!E)return;if(w.pointerType==="touch"){h.current={id:w.pointerId,startX:w.clientX,startY:w.clientY,lastX:w.clientX,lastY:w.clientY,moved:!1},w.currentTarget.setPointerCapture(w.pointerId);return}if(w.button===3||w.button===4){w.preventDefault(),t({type:w.button===3?"back":"forward"});return}if(i){w.button===0&&u(E);return}const S=As[w.button]??"left",M=c.current,j=performance.now(),T=Math.abs(w.clientX-M.x)<5&&Math.abs(w.clientY-M.y)<5;M.count=j-M.at<$a&&T?Math.min(3,M.count+1):1,M.at=j,M.x=w.clientX,M.y=w.clientY,w.currentTarget.setPointerCapture(w.pointerId),f.current={id:w.pointerId,button:S,point:E},t({type:"mouse",action:"down",...E,button:S,buttons:w.buttons,clickCount:M.count,modifiers:dt(w)})},C=w=>{const E=d(w.clientX,w.clientY);if(!E)return;const S=h.current;if(w.pointerType==="touch"){if(!S||S.id!==w.pointerId||((Math.abs(w.clientX-S.startX)>Ds||Math.abs(w.clientY-S.startY)>Ds)&&(S.moved=!0),!S.moved))return;const M=r.current,j=w.currentTarget.getBoundingClientRect(),T=M&&j.width>0?M.width/j.width:1;t({type:"mouse",action:"wheel",...E,deltaX:(S.lastX-w.clientX)*T,deltaY:(S.lastY-w.clientY)*T}),S.lastX=w.clientX,S.lastY=w.clientY;return}if(i){o(E);return}f.current?.id===w.pointerId&&(f.current.point=E),t({type:"mouse",action:"move",...E,buttons:w.buttons,modifiers:dt(w)})},x=w=>{const E=d(w.clientX,w.clientY);if(!E)return;if(w.pointerType==="touch"){const M=h.current;if(h.current=null,!M||M.id!==w.pointerId||M.moved)return;if(i){u(E);return}t({type:"mouse",action:"down",...E,button:"left",buttons:1,clickCount:1}),t({type:"mouse",action:"up",...E,button:"left",buttons:0,clickCount:1});return}if(w.button===3||w.button===4){w.preventDefault();return}if(i)return;f.current?.id===w.pointerId&&(f.current=null);const S=As[w.button]??"left";t({type:"mouse",action:"up",...E,button:S,buttons:w.buttons,clickCount:c.current.count||1,modifiers:dt(w)})},P=(w,E)=>({type:"key",action:w,key:E.key,code:E.code,keyCode:E.keyCode,location:E.nativeEvent.location,repeat:E.repeat,modifiers:dt(E)});return{keyboardRef:l,focusKeyboard:b,canvasHandlers:{onPointerDown:p,onPointerMove:C,onPointerUp:x,onPointerCancel:w=>{h.current=null;const E=f.current;!E||E.id!==w.pointerId||(f.current=null,t({type:"mouse",action:"up",...E.point,button:E.button,buttons:0,clickCount:1}))},onMouseDown:w=>w.preventDefault(),onContextMenu:w=>w.preventDefault()},keyboardHandlers:{onKeyDown:w=>{w.nativeEvent.isComposing||w.keyCode===229||pr(w,Fa())||(w.preventDefault(),w.stopPropagation(),t(P("down",w)))},onKeyUp:w=>{w.nativeEvent.isComposing||w.keyCode===229||(w.stopPropagation(),t(P("up",w)))},onPaste:w=>{w.preventDefault();const E=w.clipboardData.getData("text/plain");E&&t({type:"text",text:E})},onCompositionEnd:w=>{w.data&&t({type:"text",text:w.data}),w.currentTarget.value=""},onInput:w=>{w.nativeEvent.isComposing||(w.currentTarget.value="")}}}},za={url:"about:blank",title:"",loading:!1,canGoBack:!1,canGoForward:!1,crashed:!1},Ha=1500,Ua=({initialUrl:t,directory:s,pageId:r,popupId:a,onScreen:i,routeToggle:o,onRouteChange:u})=>{const l=n.useMemo(()=>mr(s,r),[s,r]),c=K(R=>R.updateBrowserPage),h=K(R=>R.openBrowserPopup),f=K(R=>R.closeBrowserPage),y=Me(R=>R.currentSessionId),d=Me(R=>R.newSessionDraft?.open),b=xt(R=>R.addAttachedFile),p=lt(t),C=p!=="about:blank"?p:"",[x,P]=n.useState(za),[_,U]=n.useState("idle"),[w,E]=n.useState(null),[S,M]=n.useState(""),[j,T]=n.useState(C),[Y,X]=n.useState("default"),[z,Z]=n.useState(null),[le,H]=n.useState(""),[ne,N]=n.useState(null),[F,oe]=n.useState(!1),[D,O]=n.useState(!1),[G,ue]=n.useState(null),[ge,he]=n.useState({width:0,height:0}),[be,je]=n.useState([]),[Ce,ve]=n.useState(!1),ye=n.useRef(Ce);ye.current=Ce;const[Re,Te]=n.useState(()=>typeof document>"u"||document.visibilityState==="visible"),Se=n.useRef(null),ke=n.useRef(null),Ne=n.useRef(null),De=n.useRef(C),B=n.useRef(a);B.current=a;const J=n.useRef(null),re=n.useRef(!1),L=n.useRef(new Map),ee=n.useRef({seq:0,inFlight:!1,queued:null}),ae=n.useRef(ge);ae.current=ge;const g=n.useCallback(R=>Ne.current?.send(R)??!1,[]),{canvasRef:A,headerRef:te,frameSize:de,onFrame:m,reset:I}=Oa(()=>Ne.current?.ack()),V=n.useCallback((R,$)=>{!R||R==="about:blank"||!s||!r||c(s,r,{url:R,title:$})},[s,r,c]),pe=n.useCallback(R=>{const $=lt(R);if($==="about:blank"){xe.warning("Enter an http or https address");return}De.current=$,T($),g({type:"navigate",url:$})||(J.current=$)},[g]),Ee=n.useCallback(()=>{const{width:R,height:$}=ae.current;R<=0||$<=0||g({type:"viewport",width:Math.round(R),height:Math.round($),dpr:window.devicePixelRatio||1})},[g]),Ie=n.useCallback(async(R,$)=>{if(!(y??(d?"draft":null))){xe.error("Open a chat session before attaching preview annotations");return}const me=$?await Rt($.base64,$.width,$.height,$.cssWidth,$.cssHeight,R):null;me&&await b(me);const Ae=$?.cssWidth??te.current?.width??0,$e=$?.cssHeight??te.current?.height??0;gt(Pt({pageUrl:De.current,viewport:{width:Ae,height:$e},devicePixelRatio:$&&$.cssWidth>0?$.width/$.cssWidth:1,target:R,screenshotAttached:!!me,intro:me?"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached.":"This is a selected DOM element from the in-app preview."})),xe.success("Preview annotation attached to chat")},[b,y,te,d]),Le=R=>{switch(R.type){case"state":{const $={url:R.url,title:R.title,loading:R.loading,canGoBack:R.canGoBack,canGoForward:R.canGoForward,crashed:R.crashed};P($),$.url&&$.url!=="about:blank"&&(De.current=$.url,V($.url,$.title)),re.current||T($.url==="about:blank"?"":$.url);return}case"cursor":X(R.cursor||"default");return;case"dialog":Z(R),H(R.defaultPrompt||"");return;case"dialog-closed":Z(null);return;case"file-chooser":N({id:R.id,multiple:R.multiple});return;case"file-chooser-closed":N($=>$?.id===R.id?null:$);return;case"clipboard":ct(R.text);return;case"notice":R.kind==="blocked-server-network"?xe.warning(`Blocked a page from opening ${Ht(R.url)}`,{description:"Sites on the internet cannot send the server browser to addresses on the server or its network. Type the address to open it yourself."}):R.kind==="unsupported-address"?xe.warning("The server browser opens http and https addresses only"):R.kind==="upload-failed"?xe.error("Upload failed",{description:R.message}):xe.error(`Could not load ${Ht(R.url)}`,{description:R.message});return;case"popup":h(s,r,R.id)||xe.warning("A page opened a popup, but too many tabs are open",{description:"Close a tab, then try again."});return;case"download":{const $=wa(R);je(Ae=>ya(Ae,$));const v=L.current,me=v.get($.id);if(v.set($.id,$.state),me===$.state)return;if(me===void 0&&$.state==="inProgress"){ye.current=!0,ve(!0);return}if(me!=="inProgress"||ye.current)return;$.state==="completed"?xe.success(`Downloaded ${$.filename} on the server`,{action:{label:"Show",onClick:()=>ve(!0)}}):$.state==="failed"&&xe.error(`Download of ${$.filename} failed`);return}case"download-removed":if(typeof R.id!="string")return;L.current.delete(R.id),je($=>$.filter(v=>v.id!==R.id));return;case"inspect-hover":{const $=ee.current;if(R.requestId!==$.seq)return;$.inFlight=!1,ue(it(R.target)?R.target:null);const v=$.queued;$.queued=null,v&&Ye(v.x,v.y);return}case"inspect-pick":ue(null),it(R.target)&&Ie(R.target,R.screenshot);return;case"unavailable":R.status&&E(R.status),M(R.message||"");return}},Xe=n.useRef(Le);Xe.current=Le;const Ye=(R,$)=>{const v=ee.current;if(v.inFlight){v.queued={x:R,y:$};return}v.seq+=1,v.inFlight=g({type:"inspect",x:R,y:$,requestId:v.seq})},k=Wa({send:g,canvasRef:A,headerRef:te,areaHeight:()=>ae.current.height,inspecting:D,onInspectHover:R=>Ye(R.x,R.y),onInspectPick:R=>{ee.current.seq+=1,g({type:"inspect",...R,pick:!0,requestId:ee.current.seq}),O(!1)}}),{focusKeyboard:q}=k;n.useEffect(()=>{const R=new va(l,()=>({url:J.current||De.current,popup:B.current}),{onPhase:$=>{U($),$==="open"&&E(null)},onOpen:()=>{B.current&&K.getState().updateBrowserPage(s,r,{popupId:null}),I(),ee.current.inFlight=!1,Ee();const $=J.current;J.current=null,$&&R.send({type:"navigate",url:$})},onMessage:$=>Xe.current($),onFrame:m},{open:wr,forgetToken:br,setTimeout:($,v)=>window.setTimeout($,v),clearTimeout:$=>window.clearTimeout($)});return Ne.current=R,()=>{R.dispose(),Ne.current===R&&(Ne.current=null)}},[s,m,r,I,Ee,l]),n.useEffect(()=>{_==="closed"&&f(s,r)},[f,s,r,_]);const ce=i&&ge.width>0&&ge.height>0&&Re;n.useEffect(()=>{if(ce){Ne.current?.setActive(!0);return}const R=window.setTimeout(()=>Ne.current?.setActive(!1),Ha);return()=>window.clearTimeout(R)},[ce]),n.useEffect(()=>{const R=()=>Te(document.visibilityState==="visible");return document.addEventListener("visibilitychange",R),()=>document.removeEventListener("visibilitychange",R)},[]),n.useEffect(()=>{const R=Se.current;if(!R)return;const $=new ResizeObserver(([v])=>{const{width:me,height:Ae}=v.contentRect;he($e=>$e.width===me&&$e.height===Ae?$e:{width:me,height:Ae})});return $.observe(R),()=>$.disconnect()},[]),n.useEffect(()=>{if(_!=="open")return;const R=window.setTimeout(Ee,80);return()=>window.clearTimeout(R)},[ge,_,Ee]),n.useEffect(()=>{if(_!=="unavailable"||w)return;let R=!1;return gr().then($=>{R||E($)}).catch($=>{R||M($ instanceof Error?$.message:"Could not check the server browser")}),()=>{R=!0}},[_,w]),n.useEffect(()=>{!C||C===De.current||pe(C)},[t]),n.useEffect(()=>{if(!D)return;const R=$=>{$.key==="Escape"&&($.preventDefault(),$.stopImmediatePropagation(),O(!1),ue(null))};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[D]);const ie=R=>{g({type:"dialog",accept:R,text:z?.kind==="prompt"?le:void 0}),Z(null),q()},we=async R=>{const $=ne;if(!$||!R||R.length===0)return;const v=$.multiple?Array.from(R):[R[0]];if(v.reduce((me,Ae)=>me+Ae.size,0)>yr){xe.warning(v.length===1?"The file is too large":"The files are too large together",{description:"The server browser uploads under 50 MB at a time."}),ke.current&&(ke.current.value="");return}oe(!0);try{const me=await Promise.all(v.map(Ae=>vr(Ae)));g({type:"file-chooser",id:$.id,uploadIds:me})}catch(me){xe.error(me instanceof Error?me.message:"Upload failed")}finally{oe(!1),ke.current&&(ke.current.value="")}},se=de?xr(de,ge):null,Pe=x.url!=="about:blank",_e=_==="open"&&!Pe&&!x.loading,He=be.filter(R=>R.state==="inProgress").length;return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!x.canGoBack,onClick:()=>g({type:"back"}),"aria-label":"Back",title:"Back",children:e.jsx(W,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!x.canGoForward,onClick:()=>g({type:"forward"}),"aria-label":"Forward",title:"Forward",children:e.jsx(W,{name:"arrow-right",className:"h-3.5 w-3.5"})}),x.loading?e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>g({type:"stop"}),"aria-label":"Stop loading",title:"Stop loading",children:e.jsx(W,{name:"close",className:"h-3.5 w-3.5"})}):e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!Pe,onClick:()=>g({type:"reload"}),"aria-label":"Reload",title:"Reload",children:e.jsx(W,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:R=>{R.preventDefault(),re.current=!1,pe(j),q()},children:e.jsx("input",{value:j,onChange:R=>T(R.target.value),onFocus:R=>{re.current=!0,R.currentTarget.select()},onBlur:()=>{re.current=!1},placeholder:"Enter an address",className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),o,e.jsx(Q,{type:"button",variant:D?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!Pe||_!=="open","aria-pressed":D,onClick:()=>{O(R=>!R),ue(null)},title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(W,{name:"cursor",className:"h-3.5 w-3.5"})}),be.length>0?e.jsx(Q,{type:"button",variant:Ce?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0","aria-pressed":Ce,onClick:()=>ve(R=>!R),title:He>0?`Downloads (${He} in progress)`:"Downloads","aria-label":He>0?`Downloads, ${He} in progress`:"Downloads",children:e.jsx(W,{name:"download",className:"h-3.5 w-3.5"})}):null,e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!Pe,onClick:()=>{at(x.url)},title:"Open in system browser","aria-label":"Open in system browser",children:e.jsx(W,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{ref:Se,className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[e.jsx("div",{className:"absolute inset-0 flex items-start justify-start",children:e.jsxs("div",{className:"relative",style:se?{width:se.width,height:se.height}:{width:"100%",height:"100%"},children:[e.jsx("canvas",{ref:A,className:"block h-full w-full touch-none select-none outline-none",style:{cursor:D?"crosshair":Y},...k.canvasHandlers,"aria-label":x.title?`Web page: ${x.title}`:"Web page",role:"img"}),D&&G&&de&&se?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:G.bounds.x*se.scale,top:G.bounds.y*se.scale,width:G.bounds.width*se.scale,height:G.bounds.height*se.scale},children:e.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[G.tag,G.text?` · ${G.text}`:""]})}):null]})}),e.jsx("textarea",{ref:k.keyboardRef,className:"pointer-events-none absolute left-0 top-0 h-px w-px resize-none opacity-0","aria-label":"Keyboard input for the web page",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,...k.keyboardHandlers}),e.jsx("input",{ref:ke,type:"file",className:"hidden",multiple:ne?.multiple===!0,onChange:R=>{we(R.target.files)}}),ne?e.jsx(_a,{multiple:ne.multiple,uploading:F,onChoose:()=>ke.current?.click(),onCancel:()=>g({type:"file-chooser",id:ne.id,uploadIds:[]})}):null,z?e.jsx(Ma,{dialog:z,promptText:le,onPromptTextChange:H,onRespond:ie}):null,x.crashed?e.jsx(Ia,{onReload:()=>g({type:"reload"})}):null,e.jsx(La,{phase:_,status:w,failure:S,hasFrame:de!==null,showBlank:_e,directory:s,onRetry:()=>Ne.current?.retry(),onSetupRetry:()=>{E(null),M(""),Ne.current?.retry()},onUseDevice:()=>u("device"),onOpenAddress:pe})]}),e.jsx(Sa,{downloads:be,open:Ce,onClose:()=>ve(!1),onCancel:R=>g({type:"download-cancel",id:R})})]})},Va=t=>{try{return new URL(t).host||t}catch{return t}},Ka=({route:t,onRouteChange:s})=>{const r=t==="server",a=r?"Pages run in a browser on the PiChamber server, so localhost means the server. Switch to load them on this device.":"Pages load on this device, so localhost means this device. Switch to run them on the PiChamber server.";return e.jsx(Q,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 typography-micro",onClick:()=>s(r?"device":"server"),title:a,"aria-label":r?"Running on the server. Switch to this device":"Loading on this device. Switch to server",children:r?"Server":"This device"})},Ut=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,Xa=({initialUrl:t,directory:s,pageId:r,routeToggle:a,onRouteChange:i})=>{const o=n.useRef(null),u=K(D=>D.updateBrowserPage),[l,c]=n.useState(null),h=lt(t),f=h!=="about:blank"?h:"",[y,d]=n.useState(f),[b,p]=n.useState(f),[C,x]=n.useState(()=>f?[f]:[]),[P,_]=n.useState(()=>f?0:-1),[U,w]=n.useReducer(D=>D+1,0),[E,S]=n.useState(!!f),[M,j]=n.useState(!1),T=Me(D=>D.currentSessionId),Y=Me(D=>D.newSessionDraft?.open),X=xt(D=>D.addAttachedFile),z=n.useCallback(D=>{!D||D==="about:blank"||!s||!r||u(s,r,{url:D})},[s,r,u]),Z=n.useCallback(D=>{const O=lt(D),G=O!=="about:blank"?O:"";p(G),d(G),S(!!G),z(G),x(ue=>{if(!G)return _(-1),[];const ge=P>=0?ue.slice(0,P+1):[];if(ge[ge.length-1]===G)return _(ge.length-1),ge;const he=[...ge,G];return _(he.length-1),he})},[P,z]),le=n.useCallback(D=>{const O=C[D];O&&(_(D),p(O),d(O),S(!0),z(O))},[C,z]),H=n.useCallback(()=>{if(b){S(!0);try{o.current?.contentWindow?.location.reload()}catch{w()}}},[b]);n.useEffect(()=>{if(!b)return;const D=new AbortController;return jr(b,window.location.origin,D.signal).then(O=>{O.framing==="refused"&&c(b)}).catch(()=>{}),()=>D.abort()},[b]);const ne=l&&l===b?Va(b):null;n.useEffect(()=>{!f||f===b||Z(f)},[t]);const N=n.useCallback(async D=>{if(!(T??(Y?"draft":null))){xe.error("Open a chat session before attaching preview annotations");return}const G=o.current,ue=G?.contentWindow,ge=G?.getBoundingClientRect(),he={width:Number.isFinite(ue?.innerWidth)?ue?.innerWidth??ge?.width??0:ge?.width??0,height:Number.isFinite(ue?.innerHeight)?ue?.innerHeight??ge?.height??0:ge?.height??0},be=G?await wn(G,D):null,je=!!be;be&&await X(be),gt(Pt({pageUrl:b,viewport:he,devicePixelRatio:window.devicePixelRatio||1,target:D,screenshotAttached:je,intro:je?"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached.":"This is a selected DOM element from the in-app preview."})),xe.success("Preview annotation attached to chat")},[X,T,b,Y]),F=n.useCallback(()=>{const D=o.current;D&&Ps(D,jt).catch(()=>{})},[]);n.useEffect(()=>{if(!M)return;const D=O=>{O.key==="Escape"&&(O.preventDefault(),O.stopImmediatePropagation(),j(!1),F())};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[F,M]),n.useEffect(()=>()=>F(),[F]);const oe=n.useCallback(()=>{const D=o.current;if(!(!D||!b)){if(M){j(!1),F();return}j(!0),(async()=>{try{const O=await Ps(D,vn);if(j(!1),!O||!it(O))return;await N(O)}catch{j(!1),xe.error("This page cannot be inspected on this device. Switch to Server to inspect it.")}})()}},[N,F,b,M]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:P<=0,onClick:()=>le(P-1),"aria-label":"Back",title:"Back",children:e.jsx(W,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:P<0||P>=C.length-1,onClick:()=>le(P+1),"aria-label":"Forward",title:"Forward",children:e.jsx(W,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!b,onClick:H,"aria-label":"Reload",title:"Reload",children:e.jsx(W,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:D=>{D.preventDefault(),Z(y)},children:e.jsx("input",{value:y,onChange:D=>d(D.target.value),placeholder:"Enter an address",className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),a,e.jsx(Q,{type:"button",variant:M?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!b,onClick:oe,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(W,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!b,onClick:()=>{at(b)},title:"Open in system browser","aria-label":"Open in system browser",children:e.jsx(W,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[b?e.jsx("iframe",{ref:o,src:b,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:()=>S(!1)},`${r}:${U}`):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[e.jsx(Xt,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground [text-wrap:pretty]",children:"Pages load on this device, so localhost addresses reach this device. Many sites refuse to load inside other pages here; Server opens them."})]}),E&&!ne?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null,ne?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-4 bg-background p-6 text-center",children:[e.jsx("span",{className:"max-w-sm typography-ui-header text-foreground [text-wrap:balance]",children:`${ne} can't be shown here`}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground [text-wrap:pretty]",children:"This site doesn't allow being shown inside other pages. Use Server to open it in PiChamber, or open it in your system browser."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[e.jsx(Q,{type:"button",size:"sm",onClick:()=>i("server"),children:"Use server"}),e.jsx(Q,{type:"button",size:"sm",variant:"outline",onClick:()=>{at(b)},children:"Open in system browser"})]})]}):null]})]})},qa=({initialUrl:t,directory:s,pageId:r,routeToggle:a})=>{const i=n.useRef(null),o=K(j=>j.updateBrowserPage),u=lt(t),l=u!=="about:blank"?u:"",[c,h]=n.useState(l),[f,y]=n.useState(l),[d]=n.useState(u),[b,p]=n.useState(!1),[C,x]=n.useState(!0),P=n.useRef(null),_=n.useCallback(j=>{!j||j==="about:blank"||!s||!r||o(s,r,{url:j})},[s,r,o]),U=Me(j=>j.currentSessionId),w=Me(j=>j.newSessionDraft?.open),E=xt(j=>j.addAttachedFile),S=n.useCallback(j=>{const T=i.current;if(typeof T?.loadURL=="function")try{T.loadURL(lt(j))}catch{}},[]);n.useEffect(()=>{const j=i.current;if(!j)return;const T=N=>{!N||N==="about:blank"||(y(N),h(N),_(N))},Y=()=>{try{T(j.getURL())}catch{}},X=N=>{const F=N.url;T(typeof F=="string"?F:"")},z=()=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>x(!0),200)},Z=()=>{P.current&&clearTimeout(P.current),x(!1),Y()},le=N=>{const F=N.detail;(F?.disposition==="new-window"||F?.disposition==="foreground-tab"||F?.disposition==="background-tab")&&(N.preventDefault(),F.url&&S(F.url))},H=N=>{const F=N.title;typeof F=="string"&&s&&r&&o(s,r,{title:F})},ne=()=>{try{j.executeJavaScript?.(ma,!0).catch(()=>{})}catch{}};j.addEventListener("did-navigate",X),j.addEventListener("did-navigate-in-page",X),j.addEventListener("did-start-loading",z),j.addEventListener("did-stop-loading",Z),j.addEventListener("new-window",le),j.addEventListener("page-title-updated",H),j.addEventListener("dom-ready",ne);try{j.isLoading()||(x(!1),Y())}catch{}return ne(),()=>{P.current&&clearTimeout(P.current),j.removeEventListener("did-navigate",X),j.removeEventListener("did-navigate-in-page",X),j.removeEventListener("did-start-loading",z),j.removeEventListener("did-stop-loading",Z),j.removeEventListener("new-window",le),j.removeEventListener("page-title-updated",H),j.removeEventListener("dom-ready",ne)}},[s,S,r,_,o]),n.useEffect(()=>{const j=setTimeout(()=>x(!1),3e4);return()=>clearTimeout(j)},[]),n.useEffect(()=>{if(!b)return;const j=T=>{if(T.key!=="Escape")return;T.preventDefault(),T.stopImmediatePropagation(),p(!1);const Y=i.current;try{Y?.executeJavaScript?.(jt).catch(()=>{})}catch{}};return window.addEventListener("keydown",j,!0),()=>window.removeEventListener("keydown",j,!0)},[b]),n.useEffect(()=>{const j=i.current;return()=>{try{const T=j?.getURL?.();T&&T!=="about:blank"&&o(s,r,{url:T})}catch{}try{j?.executeJavaScript?.(jt).catch(()=>{})}catch{}}},[s,r,o]),n.useEffect(()=>{!l||l===f||S(l)},[t]);const M=n.useCallback(()=>{const j=i.current;if(j){if(b){p(!1);try{j.executeJavaScript?.(jt).catch(()=>{})}catch{}return}p(!0),j.executeJavaScript?.(vn,!0).then(async T=>{if(p(!1),!T||!it(T))return;if(!(U??(w?"draft":null))){xe.error("Open a chat session before attaching preview annotations");return}const X=typeof j.getWebContentsId=="function"?j.getWebContentsId():null;if(X==null)return;const z=await Wr("desktop_browser_capture_page",{webContentsId:X}),Z=await j.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),le=Number.isFinite(Z?.width)?Z.width:z.width,H=Number.isFinite(Z?.height)?Z.height:z.height,ne=await Rt(z.base64,z.width,z.height,le,H,T),N=!!ne;ne&&await E(ne),gt(Pt({pageUrl:f,viewport:{width:le,height:H},devicePixelRatio:window.devicePixelRatio||1,target:T,screenshotAttached:N,intro:"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached."})),xe.success("Preview annotation attached to chat")}).catch(()=>p(!1))}},[E,U,f,b,w]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goBack?.()}catch{}},children:e.jsx(W,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goForward?.()}catch{}},children:e.jsx(W,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.reload?.()}catch{}},children:e.jsx(W,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:j=>{j.preventDefault(),S(c)},children:e.jsx("input",{value:c,onChange:j=>h(j.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),a,e.jsx(Q,{type:"button",variant:b?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:M,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(W,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{at(f)},children:e.jsx(W,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[e.jsx("webview",{ref:i,src:d,partition:"persist:pichamber-browser",allowpopups:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",border:"none"}}),!f&&!C?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[e.jsx(Xt,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,C?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},_s=28,Ya=t=>t.length>_s?`${t.slice(0,_s-1)}…`:t,Ga=({page:t,directory:s,route:r,onScreen:a})=>{const i=K(f=>f.updateBrowserPage),o=K(f=>f.setBrowserRoutePreference),u=n.useCallback(f=>{i(s,t.id,{route:f}),Ut()&&o(f)},[s,t.id,o,i]),l=e.jsx(Ka,{route:r,onRouteChange:u}),c={initialUrl:t.url??"",directory:s,pageId:t.id,onScreen:a,routeToggle:l,onRouteChange:u};if(r==="server")return e.jsx(Ua,{...c,popupId:t.popupId??null},r);const h=Ut()?qa:Xa;return e.jsx(h,{...c},r)},Ja=({directory:t,browser:s,onScreen:r})=>{const a=K(b=>b.browserRoutePreference),i=K(b=>b.openContextBrowser),o=K(b=>b.activateBrowserPage),u=K(b=>b.closeBrowserPage),l=K(b=>b.updateBrowserPage),c=n.useMemo(()=>s?.pages??[],[s]),h=s?.activePageId??null;n.useEffect(()=>{for(const b of c)b.route||l(t,b.id,{defaultRoute:Et(null,a)})},[t,c,a,l]);const f=n.useMemo(()=>c.map(b=>{const p=Ln(b);return{id:b.id,label:Ya(p),title:b.url&&b.url!==p?`${p}
127
+ ${b.url}`:p,closeLabel:`Close ${p}`}}),[c]),y=()=>{i(t,"",{target:"new",route:Et(null,a)})},d=b=>{Js(t,b),u(t,b)};return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex h-9 shrink-0 items-stretch border-b border-border bg-[var(--surface-background)]",children:[e.jsx(un,{items:f,activeId:h,onSelect:b=>o(t,b),onClose:d,layoutMode:"scrollable",variant:"default"}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"mx-1 my-auto h-7 w-7 shrink-0 p-0",onClick:y,title:"New browser tab","aria-label":"New browser tab",children:e.jsx(W,{name:"add",className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"relative min-h-0 flex-1",children:c.map(b=>{const p=Et(b.route,a),C=b.id===h,x=p==="device"&&Ut();return e.jsx("div",{className:fe("absolute inset-0",!C&&(x?"invisible pointer-events-none":"hidden")),"aria-hidden":C?void 0:!0,children:e.jsx(Ga,{page:b,directory:t,route:p,onScreen:r&&C})},b.id)})})]})},Qa=8,qe=new Map,ts=t=>JSON.stringify([Bn(),t]),Ms=t=>{const s=ts(t),r=qe.get(s);return r?(r.touchedAt=Date.now(),qe.delete(s),qe.set(s,r),r):null},_t=t=>{const s=ts(t),r=qe.get(s);if(r)return r.touchedAt=Date.now(),r;if(qe.size>=Qa){const i=qe.keys().next().value;i!==void 0&&qe.delete(i)}const a={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return qe.set(s,a),a},Za=t=>{qe.delete(ts(t))},ei=(t,s)=>e.jsx(Ct,{filePath:t,extension:s}),ti=({node:t,root:s,isExpanded:r,isActive:a,isBrowserClient:i,status:o,badge:u,permissions:l,downloadFile:c,onSelect:h,onToggle:f,onRevealPath:y,onOpenDialog:d})=>{const b=t.type==="directory",{canRename:p,canCreateFile:C,canCreateFolder:x,canDelete:P,canReveal:_}=l,U=!b&&!!c,w=_&&!i&&Ks()&&On(),E=p||C||x||P||U||w,[S,M]=n.useState(!1),[j,T]=n.useState(!1),Y=n.useCallback(H=>{E&&(H?.preventDefault(),T(!0))},[E]),X=n.useCallback(()=>{b?f(t.path):h(t)},[b,t,h,f]),z=n.useCallback(H=>{H.stopPropagation(),T(!1),M(!0)},[]),Z=({Item:H,Separator:ne})=>e.jsxs(e.Fragment,{children:[p&&e.jsxs(H,{onClick:N=>{N.stopPropagation(),d("rename",t)},children:[e.jsx(W,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(H,{onClick:N=>{N.stopPropagation(),ct(t.path).then(F=>{if(F.ok){xe.success("Path copied");return}xe.error("Copy failed")})},children:[e.jsx(W,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy path"]}),!b&&c&&e.jsxs(H,{onClick:N=>{N.stopPropagation(),c(t.path).catch(F=>{console.error("Download failed:",F),xe.error("Operation failed")})},children:[e.jsx(W,{name:"download",className:"mr-2 h-4 w-4"})," ",i?"Download":"Save"]}),w&&e.jsxs(H,{onClick:N=>{N.stopPropagation(),y(t.path)},children:[e.jsx(W,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",$n()]}),b&&(C||x)&&e.jsxs(e.Fragment,{children:[e.jsx(ne,{}),C&&e.jsxs(H,{onClick:N=>{N.stopPropagation(),d("createFile",t)},children:[e.jsx(W,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New file"]}),x&&e.jsxs(H,{onClick:N=>{N.stopPropagation(),d("createFolder",t)},children:[e.jsx(W,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New folder"]})]}),P&&e.jsxs(e.Fragment,{children:[e.jsx(ne,{}),e.jsxs(H,{onClick:N=>{N.stopPropagation(),d("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(W,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),le=n.useCallback(H=>{const ne=an(s,t.path);ne&&(H.dataTransfer.setData("application/x-pichamber-file-path",ne),H.dataTransfer.effectAllowed="copy")},[t.path,s]);return e.jsxs(Sr,{open:j,onOpenChange:T,children:[e.jsxs(kr,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:Y}),children:[e.jsxs("button",{type:"button",onClick:X,onContextMenu:Y,draggable:!0,onDragStart:le,className:fe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors select-none",E&&"group-hover:pr-8 group-focus-within:pr-8",a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[b?r?e.jsx(W,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(W,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):ei(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!b&&o&&e.jsx(Bo,{status:o,className:E?"group-hover:invisible group-focus-within:invisible":void 0}),b&&u&&e.jsx(Oo,{badge:u,className:E?"group-hover:invisible group-focus-within:invisible":void 0})]}),E&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:e.jsxs(Ft,{open:S,onOpenChange:M,children:[e.jsxs(et,{children:[e.jsx(tt,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(Wt,{asChild:!0,children:e.jsx(Q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:z,title:"File menu","aria-label":"File menu",children:e.jsx(W,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(st,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(zt,{align:"end",side:"bottom",onCloseAutoFocus:()=>M(!1),children:Z({Item:Qe,Separator:tn})})]})})]}),e.jsx(Cr,{className:"min-w-[180px]",children:Z({Item:Nr,Separator:Pr})})]})},si=(t,s)=>t.node===s.node&&t.root===s.root&&t.isExpanded===s.isExpanded&&t.isActive===s.isActive&&t.isBrowserClient===s.isBrowserClient&&t.status===s.status&&t.badge===s.badge&&t.permissions===s.permissions&&t.downloadFile===s.downloadFile&&t.onSelect===s.onSelect&&t.onToggle===s.onToggle&&t.onRevealPath===s.onRevealPath&&t.onOpenDialog===s.onOpenDialog,ni=n.memo(ti,si),jn=t=>{const{files:s}=Nt(),r=K(o=>o.openContextFile),a=Ue(o=>o.setSelectedPath),i=Ue(o=>o.addOpenPath);return n.useCallback(async o=>{if(!t)return;const u=await cn(s,o,{directory:t});if(!u.ok){xe.error(dn(u.reason));return}a(t,o),i(t,o),r(t,o)},[i,s,r,t,a])},ri=280,oi=({onBackToFile:t})=>{const{files:s,runtime:r}=Nt(),a=Fn(r.platform),i=bt()??"",o=Be(i.trim()),u=Wn(),l=qt(i),[c,h]=n.useState(""),f=n.useRef(null),y=n.useRef(null),[d,b]=n.useState(!1);n.useLayoutEffect(()=>{const k=y.current;if(!k||typeof ResizeObserver>"u")return;const q=()=>b(k.clientWidth<ri);q();const ce=new ResizeObserver(q);return ce.observe(k),()=>ce.disconnect()},[]);const p=c.trim().length>0,{results:C,searching:x,failed:P}=$o({directory:i,query:c,chrome:"desktop",showGitignored:u}),[_,U]=n.useState({}),[w,E]=n.useState({}),S=n.useRef(new Set),M=n.useRef(new Set),j=n.useRef(null);n.useEffect(()=>{if(!o){U({}),E({}),S.current=new Set;return}const k=Ms(o);k?(U({...k.childrenByDir}),E({...k.loadErrorsByDir}),S.current=new Set(k.loadedDirs)):(U({}),E({}),S.current=new Set)},[o]),n.useEffect(()=>{if(!o)return;const k=_t(o);k.childrenByDir=_},[o,_]),n.useEffect(()=>{if(!o)return;const k=_t(o);k.loadErrorsByDir=w},[o,w]),n.useEffect(()=>{if(!o)return;const k=_t(o);k.loadedDirs=new Set(S.current)},[o,_,w]),n.useEffect(()=>()=>{if(!o)return;const k=Ms(o);k&&k.loadedDirs.size===0&&Object.keys(k.childrenByDir).length===0&&Za(o)},[o]);const T=n.useMemo(()=>[],[]),Y=n.useMemo(()=>[],[]),X=Ue(k=>o?k.byRoot[o]?.expandedPaths??T:T),z=Ue(k=>o?k.byRoot[o]?.selectedPath??null:null),Z=Ue(k=>k.setSelectedPath),le=Ue(k=>k.removeOpenPathsByPrefix),H=Ue(k=>k.toggleExpandedPath),ne=Ue(k=>k.collapseAllExpandedPaths),N=K(k=>o?k.contextPanelByDirectory[o]?.tabs??Y:Y),F=n.useMemo(()=>new Set(N.map(k=>k.mode==="file"?k.targetPath:null).filter(k=>typeof k=="string"&&k.length>0).map(k=>Be(k))),[N]),oe=n.useCallback(k=>{s.revealPath&&s.revealPath(k).catch(()=>{xe.error("Failed to reveal path")})},[s]),D=n.useCallback((k,q)=>{const ce=q.filter(ie=>ie&&typeof ie.name=="string"&&ie.name.length>0).filter(ie=>!Fo(ie.name)&&(u||!Wo(ie.name))).map(ie=>{const we=ie.name,se=Be(ie.path||""),Pe=se?zo(se)?se:Be(`${k}/${se}`):Be(`${k}/${we}`),_e=ie.isDirectory?"directory":"file",He=_e==="file"&&we.includes(".")?we.split(".").pop()?.toLowerCase():void 0;return{name:we,path:Pe,type:_e,extension:He}});return Ho(ce)},[u]),O=n.useCallback(async(k,q)=>{const ce=Be(k.trim());if(!ce||S.current.has(ce)||M.current.has(ce))return;M.current=new Set(M.current),M.current.add(ce);const ie=s.listDirectory?s.listDirectory(ce).then(we=>we.entries.map(se=>({name:se.name,path:se.path,isDirectory:se.isDirectory}))):zn(ce).then(we=>we.map(se=>({name:se.name,path:se.path,isDirectory:se.isDirectory})));try{const we=await ie;if(q?.())return;const se=D(ce,we);S.current=new Set(S.current),S.current.add(ce),E(Pe=>{if(!Pe[ce])return Pe;const _e={...Pe};return delete _e[ce],_e}),U(Pe=>({...Pe,[ce]:se}))}catch(we){if(q?.())return;const se=we instanceof Error?we.message:String(we??"");console.error("Failed to load sidebar directory:",we),E(Pe=>({...Pe,[ce]:se}))}finally{M.current=new Set(M.current),M.current.delete(ce)}},[s,D]),G=n.useCallback(async()=>{if(!o)return;j.current?.abort();const k=new AbortController;j.current=k;try{const ce=(Ue.getState().byRoot[o]?.expandedPaths??[]).map(se=>Be(se)).filter(se=>!!se&&se!==o&&se.startsWith(`${o}/`)),ie=[o,...ce];S.current=new Set(S.current);for(const se of ie)S.current.delete(se);E(se=>{if(Object.keys(se).length===0)return se;const Pe={...se};let _e=!1;for(const He of ie)He in Pe&&(delete Pe[He],_e=!0);return _e?Pe:se});const we=()=>k.signal.aborted;await O(o,we);for(let se=0;se<ce.length&&!k.signal.aborted;se+=3){const Pe=ce.slice(se,se+3);await Promise.all(Pe.map(_e=>O(_e,we)))}}catch(q){if(k.signal.aborted)return;console.error("Failed to refresh sidebar tree:",q)}finally{j.current===k&&(j.current=null)}},[O,o]),ue=n.useCallback(async k=>{if(!k){await G();return}const q=Be(k);S.current=new Set(S.current),S.current.delete(q),M.current=new Set(M.current),M.current.delete(q),await O(q)},[O,G]),ge=n.useCallback(()=>{o&&Z(o,null)},[o,Z]),{operation:he,target:be,inputValue:je,setInputValue:Ce,submitting:ve,inputRef:ye,open:Re,close:Te,submit:Se,capabilities:{canCreateFile:ke,canCreateFolder:Ne,canRename:De,canDelete:B}}=Uo({files:s,root:o,selectedPath:z??"",refreshDirectory:ue,removeOpenPathsByPrefix:le,clearSelectedPath:ge}),J=!!s.revealPath,re=n.useMemo(()=>({canRename:De,canCreateFile:ke,canCreateFolder:Ne,canDelete:B,canReveal:J}),[De,ke,Ne,B,J]);n.useEffect(()=>{o&&(j.current?.abort(),S.current=new Set,M.current=new Set,E({}),U(k=>Object.keys(k).length===0?k:{}),O(o))},[O,o,u]),n.useEffect(()=>{if(!o||X.length===0)return;const k=X.map(ie=>Be(ie)).filter(ie=>!!ie&&ie!==o&&ie.startsWith(`${o}/`)&&!S.current.has(ie)&&!M.current.has(ie)).sort((ie,we)=>ie.split("/").length-we.split("/").length);if(k.length===0)return;let q=!1;const ce=()=>q;return(async()=>{for(let ie=0;ie<k.length&&!q;ie+=3){const we=k.slice(ie,ie+3);await Promise.all(we.map(se=>O(se,ce)))}})(),()=>{q=!0}},[X,O,o]);const L=n.useMemo(()=>{const k=new Map;if(!l?.files)return k;for(const q of l.files)q.index==="A"||q.working_dir==="?"?k.set(q.path,"git-added"):q.index==="D"?k.set(q.path,"git-deleted"):(q.index==="M"||q.working_dir==="M")&&k.set(q.path,"git-modified");return k},[l]),ee=n.useMemo(()=>{const k=new Map;if(!l?.files||!o)return k;for(const q of l.files){const ce=q.index==="M"||q.working_dir==="M",ie=q.index==="A"||q.working_dir==="?";if(!ce&&!ie)continue;const we=q.path.split("/");if(we.length<=1)continue;let se=o;for(let Pe=0;Pe<we.length-1;Pe++){se=`${se}/${we[Pe]}`;let _e=k.get(se);_e||(_e={modified:0,added:0},k.set(se,_e)),ce&&_e.modified++,ie&&_e.added++}}return k},[l,o]),ae=n.useCallback(k=>{const q=k.startsWith(o+"/")?k.slice(o.length+1):k,ce=L.get(q);return ce||(F.has(k)&&k!==z?"open":null)},[F,L,o,z]),g=n.useCallback(k=>{if(ee.size===0)return null;const q=ee.get(k);return q&&q.modified+q.added>0?q:null},[ee]),A=jn(o),te=n.useCallback(k=>A(k.path),[A]),de=Ue(k=>k.expandPaths),m=n.useRef(null),I=n.useRef(null);n.useEffect(()=>{if(!o||!z)return;I.current=z;const k=bs(z,o);if(k.length!==0){de(o,k);for(const q of k)O(q)}},[de,o,z]);const V=K(k=>k.fileTreeReveal),pe=K(k=>k.clearFileTreeReveal),Ee=n.useRef("nearest");n.useEffect(()=>{if(!o||!V)return;const k=V.path;if(pe(),h(""),Be(k)===Be(o)){m.current?.firstElementChild?.scrollIntoView({block:"start"});return}const q=bs(`${k}/_`,o);if(q.length!==0){I.current=k,Ee.current="start",de(o,q);for(const ce of q)O(ce)}},[pe,de,V,o]),n.useEffect(()=>{const k=I.current,q=m.current;if(!k||!q)return;const ce=q.querySelector(`[data-tree-path="${CSS.escape(k)}"]`);ce&&(I.current=null,ce.scrollIntoView({block:Ee.current}),Ee.current="nearest")},[_,X,p]);const Ie=n.useCallback(async k=>{const q=Be(k);o&&(H(o,q),S.current.has(q)||await O(q))},[O,o,H]);function Le(k,q){return(_[k]??[]).map(ie=>{const we=ie.type==="directory",se=we&&X.includes(ie.path),Pe=z===ie.path;return e.jsxs("li",{className:"relative","data-tree-path":ie.path,children:[e.jsx(ni,{node:ie,root:o,isExpanded:se,isActive:Pe,isBrowserClient:a,status:we?void 0:ae(ie.path),badge:we?g(ie.path):void 0,permissions:re,downloadFile:s.downloadFile,onSelect:te,onToggle:Ie,onRevealPath:oe,onOpenDialog:Re}),we&&se&&e.jsxs("ul",{className:"relative ml-[15px] flex flex-col border-l border-border/50 pl-1.5",children:[w[ie.path]?e.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:w[ie.path],children:w[ie.path]}),e.jsxs(Q,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{ue(ie.path)},children:[e.jsx(W,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,Le(ie.path)]})]},ie.path)})}const Xe=!!(o&&_[o]),Ye=o?w[o]:null;return e.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs("div",{ref:y,className:"flex h-9 shrink-0 items-center gap-0.5 border-b border-border/60 pl-1.5 pr-1",children:[t?e.jsxs(Q,{variant:"ghost",size:"xs",onClick:t,className:"mr-1 shrink-0 text-muted-foreground hover:text-foreground",children:[e.jsx(W,{name:"arrow-left",className:"size-3.5"}),"Back to file"]}):null,e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(W,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-subtle-foreground"}),e.jsx(fs,{ref:f,value:c,onChange:k=>h(k.target.value),onKeyDown:k=>{k.key!=="Escape"||!c||(k.preventDefault(),h(""))},placeholder:"Search","aria-label":"Search files",className:"h-7 rounded-md bg-transparent pl-7 pr-7 typography-meta ring-0 md:typography-meta placeholder:text-subtle-foreground focus:ring-1"}),c.trim().length>0?e.jsx("button",{type:"button","aria-label":"Clear search",title:"Clear search",className:"absolute right-1.5 top-1/2 inline-flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{h(""),f.current?.focus()},children:e.jsx(W,{name:"close",className:"size-3.5"})}):null]}),d?e.jsxs(Ft,{children:[e.jsxs(et,{children:[e.jsx(tt,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(Wt,{asChild:!0,children:e.jsx(Q,{variant:"ghost",size:"sm",className:"size-7 p-0","aria-label":"File actions",children:e.jsx(W,{name:"more-fill",className:"size-4"})})})})}),e.jsx(st,{side:"bottom",sideOffset:6,children:"File actions"})]}),e.jsxs(zt,{align:"end",side:"bottom",children:[ke?e.jsxs(Qe,{onClick:()=>Re("createFile",{path:i,type:"directory"}),children:[e.jsx(W,{name:"file-add",className:"mr-2 size-4"})," ","New file"]}):null,Ne?e.jsxs(Qe,{onClick:()=>Re("createFolder",{path:i,type:"directory"}),children:[e.jsx(W,{name:"folder-add",className:"mr-2 size-4"})," ","New folder"]}):null,ke||Ne?e.jsx(tn,{}):null,e.jsxs(Qe,{onClick:()=>{G()},children:[e.jsx(W,{name:"refresh",className:"mr-2 size-4"})," ","Refresh"]}),e.jsxs(Qe,{onClick:()=>{o&&ne(o)},children:[e.jsx(W,{name:"collapse-vertical",className:"mr-2 size-4"})," ","Collapse all folders"]})]})]}):e.jsxs(e.Fragment,{children:[ke||Ne?e.jsxs(Ft,{children:[e.jsxs(et,{children:[e.jsx(tt,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(Wt,{asChild:!0,children:e.jsx(Q,{variant:"ghost",size:"sm",className:"size-7 p-0","aria-label":"New file or folder",children:e.jsx(W,{name:"add",className:"size-4"})})})})}),e.jsx(st,{side:"bottom",sideOffset:6,children:"New file or folder"})]}),e.jsxs(zt,{align:"end",side:"bottom",children:[ke?e.jsxs(Qe,{onClick:()=>Re("createFile",{path:i,type:"directory"}),children:[e.jsx(W,{name:"file-add",className:"mr-2 size-4"})," ","New file"]}):null,Ne?e.jsxs(Qe,{onClick:()=>Re("createFolder",{path:i,type:"directory"}),children:[e.jsx(W,{name:"folder-add",className:"mr-2 size-4"})," ","New folder"]}):null]})]}):null,e.jsxs(et,{children:[e.jsx(tt,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{G()},className:"size-7 p-0","aria-label":"Refresh",children:e.jsx(W,{name:"refresh",className:"size-4"})})})}),e.jsx(st,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(et,{children:[e.jsx(tt,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(Q,{variant:"ghost",size:"sm",onClick:()=>{o&&ne(o)},className:"size-7 p-0","aria-label":"Collapse all folders",children:e.jsx(W,{name:"collapse-vertical",className:"size-4"})})})}),e.jsx(st,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]})]}),e.jsx(zr,{outerClassName:"flex-1 min-h-0",className:"px-1 py-2",children:e.jsx("ul",{ref:m,className:"flex flex-col",children:p&&x?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(W,{name:"loader-4",className:"size-4 animate-spin"}),"Searching..."]}):p&&P?e.jsx("li",{className:"px-2 py-1 typography-meta text-[var(--status-error)]",children:"Search failed. Edit the search to try again."}):p&&C.length===0?e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground text-pretty",children:`No files match “${c.trim()}”.`}):p?C.map(k=>{const q=k.relativePath||an(o??"",k.path);return e.jsx("li",{children:e.jsx(ln,{path:q||k.path,status:ae(k.path),active:z===k.path,match:c,onClick:()=>{te(k)},onDragStart:ce=>{!q||q==="."||(ce.dataTransfer.setData("application/x-pichamber-file-path",q),ce.dataTransfer.effectAllowed="copy")}})},k.path)}):Ye?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:Ye}),e.jsxs(Q,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{G()},children:[e.jsx(W,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):Xe&&o?Le(o):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(Yt,{open:!!he,onOpenChange:k=>!k&&Te(),children:e.jsxs(Gt,{children:[e.jsxs(Jt,{children:[e.jsxs(Qt,{children:[he==="createFile"&&"Create file",he==="createFolder"&&"Create folder",he==="rename"&&"Rename",he==="delete"&&"Delete"]}),e.jsxs(Zt,{children:[he==="createFile"&&`Create a new file in ${be?.path??"root"}`,he==="createFolder"&&`Create a new folder in ${be?.path??"root"}`,he==="rename"&&`Rename ${be?.name??""}`,he==="delete"&&`Are you sure you want to delete ${be?.name??""}? This action cannot be undone.`]})]}),he!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(fs,{ref:ye,value:je,onChange:k=>Ce(k.target.value),placeholder:he==="rename"?"New name":"Name",onKeyDown:k=>{k.key==="Enter"&&Se()},autoFocus:!0})}),e.jsxs(Hr,{children:[e.jsx(Q,{variant:"outline",onClick:Te,disabled:ve,children:"Cancel"}),e.jsx(Q,{variant:he==="delete"?"destructive":"default",onClick:()=>{Se()},disabled:ve||he!=="delete"&&!je.trim(),children:ve?e.jsx(W,{name:"loader-4",className:"size-4 animate-spin"}):he==="delete"?"Delete":"Confirm"})]})]})})]})},ai=200,ii=480,li=280,ci=160,di=({visible:t,overlay:s=!1,onDismissOverlay:r})=>{const a=K(S=>S.contextEditorTreeWidth),i=K(S=>S.setContextEditorTreeWidth),[o,u]=n.useState(!1),l=n.useRef(0),c=n.useRef(a),h=n.useRef(null),f=n.useRef(null),y=n.useRef(null),d=n.useCallback(S=>Math.min(ii,Math.max(ai,Math.round(S))),[]),[b,p]=n.useState(null);n.useLayoutEffect(()=>{const S=y.current?.parentElement;if(!S)return;const M=new ResizeObserver(([j])=>{const T=j?.contentRect.width??0;p(T>0?Math.round(T):null)});return M.observe(S),()=>M.disconnect()},[]);const C=n.useCallback(S=>s?b??S:b===null?S:Math.max(ci,Math.min(S,b-li)),[s,b]),x=C(a),P=n.useCallback(S=>{const M=y.current;M&&(M.style.width=`${S}px`,M.style.setProperty("--oc-editor-tree-width",`${S}px`))},[]),_=S=>{if(t){try{S.currentTarget.setPointerCapture(S.pointerId)}catch{}f.current=S.pointerId,u(!0),l.current=S.clientX,c.current=x,h.current=x,S.preventDefault()}},U=S=>{if(!o||f.current!==S.pointerId)return;const M=l.current-S.clientX,j=C(d(c.current+M));h.current!==j&&(h.current=j,P(j))},w=S=>{if(f.current!==S.pointerId)return;try{S.currentTarget.releasePointerCapture(S.pointerId)}catch{}const M=d(h.current??a);f.current=null,h.current=null,u(!1),i(M)},E=t?x:0;return e.jsxs("div",{ref:y,className:fe("h-full flex-shrink-0 overflow-hidden bg-background will-change-[width] motion-reduce:transition-none",s?"absolute inset-y-0 right-0 z-20":"relative border-l border-border",!t&&"border-l-0"),style:{width:`${o?h.current??E:E}px`,"--oc-editor-tree-width":`${o?h.current??x:x}px`,overflowX:"clip",transitionProperty:o?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&!s&&e.jsx("div",{className:fe("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",o&&"bg-[var(--interactive-border)]"),onPointerDown:_,onPointerMove:U,onPointerUp:w,onPointerCancel:w,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:fe("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",o&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,onKeyDown:s&&r?S=>{S.key==="Escape"&&!S.defaultPrevented&&r()}:void 0,children:e.jsx(oi,{onBackToFile:s?r:void 0})})]})},ui=({directory:t})=>{const s=Be(t.trim()),r=qt(t),a=jn(s),i=n.useMemo(()=>{const o=new Set,u=[];for(const l of r?.files??[]){if(o.has(l.path))continue;o.add(l.path);const c=Vo(l);!c||c==="git-deleted"||u.push({path:l.path,status:c})}return u},[r?.files]);return e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx("div",{className:"flex min-h-full flex-col justify-center px-5 py-8",children:e.jsxs("div",{className:"mx-auto w-full max-w-sm",children:[e.jsx("h2",{className:"typography-ui-label font-medium text-foreground",children:"No file open"}),e.jsx("p",{className:"mt-1 typography-meta text-muted-foreground text-pretty",children:i.length>0?"Pick a file from the tree, or open one the session changed.":"Pick a file from the tree to view or edit it."}),i.length>0?e.jsxs("section",{className:"mt-4","aria-label":"Changed files",children:[e.jsx("h3",{className:"px-2 typography-micro font-medium text-subtle-foreground",children:i.length===1?"1 changed file":`${i.length} changed files`}),e.jsx("ul",{className:"mt-1 flex flex-col",children:i.map(({path:o,status:u})=>e.jsx("li",{children:e.jsx(ln,{path:o,status:u,onClick:()=>{a(`${s}/${o}`)}})},o))})]}):null]})})})},hi="x-pichamber-preview-target-error",fi=t=>{const s=t.get(hi);return s==="missing"||s==="expired"||s==="invalid-token"?s:null},pi=(t,s)=>fi(t)?s?"stop-retrying":"retry-registration":"none";function mi(t){const[s,r]=n.useState("");return n.useEffect(()=>{if(!t){r("");return}let a=!1;return r(""),Hn(Xs()).then(i=>{!a&&i&&r(t)}).catch(()=>{}),()=>{a=!0}},[t]),s}const gi=({rawUrl:t,onNavigate:s})=>{const{currentTheme:r}=Ur(),[a,i]=n.useReducer(L=>L+1,0),[o,u]=n.useReducer(L=>L+1,0),[l,c]=n.useState({status:"idle"}),h=n.useRef(null),f=n.useRef(1),[y,d]=n.useState(!1),[b,p]=n.useState(!1),[C,x]=n.useState("all"),[P,_]=n.useState([]),[U,w]=n.useState(!1),[E,S]=n.useState(null),M=Me(L=>L.currentSessionId),j=Me(L=>L.newSessionDraft?.open),T=bt(),Y=xt(L=>L.addAttachedFile);let X=null;try{X=t?new URL(t):null}catch{X=null}const z=X?X.hostname==="localhost"||X.hostname==="127.0.0.1"||X.hostname==="::1"||X.hostname==="[::1]"||X.hostname==="0.0.0.0":!1,Z=X?X.hostname==="0.0.0.0"?new URL(X.toString().replace("0.0.0.0","127.0.0.1")):X:null,le=Z?Z.toString():"",H=le?`${Xs()||"same-origin"}|${le}`:"",ne=r.metadata.variant;n.useEffect(()=>{if(!le||!z){c({status:"idle"});return}const L=hn(H);if(L?.previewToken){c({status:"ready",proxyBasePath:L.proxyBasePath,previewToken:L.previewToken,expiresAt:L.expiresAt});return}L&&Ve.delete(H);let ee=!1;return c({status:"loading"}),(async()=>{try{const ae=await Ot("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:le})}),g=await fa(ae);if(!g.ok){Ve.delete(H),ee||c({status:"error",message:g.message});return}Ve.set(H,g.target),ee||c({status:"ready",...g.target})}catch(ae){if(Ve.delete(H),!ee){const g=ae instanceof Error?ae.message:String(ae);c({status:"error",message:g})}}})(),()=>{ee=!0}},[z,H,o,le]);const N=Z&&(Z.protocol==="http:"||Z.protocol==="https:")?Z.toString():"",F=z&&l.status==="ready"?`${l.proxyBasePath}|${l.previewToken||""}|${a}`:"",oe=mi(F),D=z&&l.status==="ready"&&Z&&oe===F?(()=>{const L=Z.pathname||"/",ee=new URLSearchParams(Z.search);ee.delete("oc_url_token"),ee.delete("oc_client_token"),ee.set("ocPreview",String(a)),ee.set("oc_preview_token",l.previewToken||"");const ae=ee.toString(),g=Z.hash||"";return Un().authenticatedAsset(`${l.proxyBasePath}${L}${ae?`?${ae}`:""}${g}`)})():"",O=z?D:N,G=z?pa(D):N,ue=z&&(l.status==="loading"||l.status==="idle"||oe!==F),ge=z&&l.status==="error",he=n.useCallback(L=>{if(!(M??(j?"draft":null))||!T){xe.error("Open a chat session before attaching preview annotations");return}const ae=t||O||"",g=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},A=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let te=!1;try{const de=h.current,m=de?await wn(de,L):null;m&&(await Y(m),te=!0)}catch{te=!1}gt(Pt({pageUrl:ae,viewport:g,devicePixelRatio:A,target:L,screenshotAttached:te,intro:"This is a selected DOM element from the in-app preview."})),xe.success("Preview annotation attached to chat")})()},[Y,M,T,O,j,t]);n.useEffect(()=>{d(!1),_([]),p(!1),x("all"),w(!1),S(null),f.current=1},[O]),n.useEffect(()=>{const L=h.current?.contentWindow;!y||!L||Ns(L,D,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:U})},[y,U,D]),n.useEffect(()=>{const L=h.current?.contentWindow;!y||!L||Ns(L,D,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:ne})},[y,ne,D]),n.useEffect(()=>{if(!U||typeof window>"u")return;const L=ee=>{ee.key==="Escape"&&(ee.preventDefault(),ee.stopImmediatePropagation(),w(!1))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[U]),n.useEffect(()=>{if(!z||typeof window>"u")return;const L=g=>{if(typeof g=="string")return g;if(g==null)return"";try{return JSON.stringify(g)}catch{return String(g)}},ee=g=>{const A=f.current;f.current+=1,_(te=>{const de=[...te,{...g,id:A}];return de.length>Cs?de.slice(de.length-Cs):de})},ae=g=>{if(g.source!==h.current?.contentWindow)return;const A=g.data;if(!(!A||A.source!=="pichamber-preview-bridge"||A.version!==1)){if(A.type==="ready"){d(!0);return}if(A.type==="console"){const te=A.level==="error"||A.level==="warn"||A.level==="info"||A.level==="debug"?A.level:"log",de=Array.isArray(A.args)?A.args.map(L).filter(Boolean):[];ee({level:te,message:de.join(" "),ts:typeof A.ts=="number"?A.ts:Date.now()});return}if(A.type==="runtime-error"){const te=L(A.filename),de=typeof A.line=="number"?A.line:null,m=typeof A.column=="number"?A.column:null,I=te?`${te}${de!==null?`:${de}${m!==null?`:${m}`:""}`:""}`:"",V=L(A.stack);ee({level:"runtime",message:L(A.message)||"Runtime error",details:[I,V].filter(Boolean).join(`
128
+ `),ts:typeof A.ts=="number"?A.ts:Date.now()});return}if(A.type==="resource-error"){const te=L(A.tag)||"resource",de=L(A.url);ee({level:"resource",message:de?`${te}: ${de}`:te,details:L(A.outerHTML),ts:typeof A.ts=="number"?A.ts:Date.now()});return}if(A.type==="hover"){S(it(A.target)?A.target:null);return}if(A.type==="select"&&it(A.target)){S(A.target),w(!1),he(A.target);return}if(A.type==="navigate-preview"){const te=typeof A.url=="string"?A.url:"",de=A.navigation==="external"?"external":"proxy";if(te&&de==="external"){at(te);return}te&&s(te)}}};return window.addEventListener("message",ae),()=>{window.removeEventListener("message",ae)}},[he,z,s]);const be=P.filter(L=>L.level==="error"||L.level==="runtime"||L.level==="resource").length,je=P.filter(L=>ha(L,C)),Ce=n.useCallback(()=>{const L=[`Preview URL: ${t||O||""}`,`Events: ${P.length}`,""].join(`
129
+ `),ee=P.map(ae=>{const g=new Date(ae.ts).toISOString(),A=ae.details?`
130
+ ${ae.details}`:"";return`[${g}] [${ae.level}] ${ae.message}${A}`}).join(`
131
+ `);ct(`${L}${ee}`).then(ae=>{ae.ok?xe.success("Preview console copied"):xe.error("Failed to copy preview console")})},[P,O,t]),ve=n.useCallback(()=>{if(!(M??(j?"draft":null))||!T){xe.error("Open a chat session before attaching preview logs");return}const ee=[`Preview URL: ${t||O||""}`,`Events: ${P.length}`,""].join(`
132
+ `),ae=P.map(g=>{const A=new Date(g.ts).toISOString(),te=g.details?`
133
+ ${g.details}`:"";return`[${A}] [${g.level}] ${g.message}${te}`}).join(`
134
+ `);gt(`These are browser console logs from the dev server running for this project.
135
+
136
+ ${ee}${ae}`),xe.success("Preview console attached to chat")},[P,M,T,O,j,t]),[ye,Re]=n.useState("unknown"),Te=n.useRef(0),Se=n.useRef(0),ke=n.useRef(""),Ne=n.useRef(""),De=15e3;n.useEffect(()=>{if(!D){Re("unknown"),ke.current="",Te.current=0,Se.current=0;return}let L=!1,ee=null;ke.current!==H&&(ke.current=H,Te.current=Date.now(),Se.current=0);const ae=g=>{ee=setTimeout(()=>{L||i()},g)};return Re("unknown"),(async()=>{const A=await(async()=>{try{return await Ot(D,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(L)return;if(!A){Re("unreachable"),ae(5e3);return}const te=pi(A.headers,Ne.current===H);if(te!=="none"){if(Ve.delete(H),te==="retry-registration")Ne.current=H,c({status:"loading"}),u();else{const I=await A.json().catch(()=>({}));if(L)return;const V=typeof I?.error=="string"?I.error:`HTTP ${A.status}`;c({status:"error",message:V})}return}if(A.status!==502){Ne.current="",Re("reachable");return}const de=Te.current||Date.now();if(Date.now()-de<De){Re("starting"),Se.current+=1;const I=Se.current,V=Math.min(2e3,250*Math.pow(2,Math.min(4,I)));ae(V);return}Re("unreachable"),ae(5e3)})(),()=>{L=!0,ee&&clearTimeout(ee)}},[H,D,a]);const B=z&&l.status==="ready"&&(ye==="unknown"||ye==="starting"),J=z&&l.status==="ready"&&ye==="unreachable",re=n.useCallback(L=>{if(!z||l.status!=="ready"||typeof window>"u")return;const ee=L.currentTarget.contentWindow;if(ee)try{const ae=ee.location,g=yn(D);if(ae.origin!==g||ae.pathname.startsWith(l.proxyBasePath))return;const A=`${l.proxyBasePath}${ae.pathname}${ae.search}${ae.hash}`;ee.location.replace(A)}catch{}},[z,D,l]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:G||t,children:G||t||"No preview URL"}),e.jsx(Q,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>i(),title:"Reload preview","aria-label":"Reload preview",disabled:!O,children:e.jsx(W,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(Q,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{N&&at(N)},title:"Open in browser","aria-label":"Open in browser",disabled:!N,children:e.jsx(W,{name:"external-link",className:"h-3.5 w-3.5"})}),z?e.jsx(Q,{type:"button",size:"sm",variant:U?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>w(L=>!L),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!y,children:e.jsx(W,{name:"cursor",className:"h-3.5 w-3.5"})}):null,z?e.jsxs(Q,{type:"button",size:"sm",variant:b?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>p(L=>!L),title:y?"Open preview console":"Waiting for preview console","aria-label":y?"Open preview console":"Waiting for preview console",disabled:!y&&P.length===0,children:[e.jsx(W,{name:"terminal-box",className:"h-3.5 w-3.5"}),be>0?e.jsx("span",{className:"typography-micro text-status-error",children:be}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[B?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[e.jsx("div",{children:"Starting dev server..."}),e.jsx("div",{className:"text-xs opacity-70",children:"Waiting for the server to accept connections."})]}):J?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[e.jsx("div",{children:"Dev server is not responding."}),e.jsx("div",{className:"text-xs opacity-70",children:"Make sure your dev server is still running, then retry."}),e.jsx(Q,{type:"button",size:"sm",variant:"outline",onClick:()=>i(),children:"Retry"})]}):O&&(!z||ye==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:h,src:O,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:ne},onLoad:re,sandbox:z?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${O}:${a}`),U&&E?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:E.bounds.x,top:E.bounds.y,width:E.bounds.width,height:E.bounds.height},children:e.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[E.tag,E.text?` · ${E.text}`:""]})}):null]}):ue?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):ge?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[e.jsx("div",{children:"Could not start preview proxy."}),l.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:l.message}):null]}):e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Preview needs a valid http(s) URL."}),b?e.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Preview console"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Q,{type:"button",size:"xs",variant:"ghost",onClick:ve,disabled:P.length===0,children:"Attach"}),e.jsx(Q,{type:"button",size:"xs",variant:"ghost",onClick:Ce,disabled:P.length===0,children:"Copy"}),e.jsx(Q,{type:"button",size:"xs",variant:"ghost",onClick:()=>_([]),disabled:P.length===0,children:"Clear"})]})]}),e.jsx("div",{className:"flex items-center gap-1 border-b border-border/30 px-3 py-1.5",children:["all","errors","warnings","logs"].map(L=>e.jsx(Q,{type:"button",size:"xs",variant:C===L?"secondary":"ghost",onClick:()=>x(L),children:L==="all"?"All":L==="errors"?"Errors":L==="warnings"?"Warnings":"Logs"},L))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:P.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):je.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):je.map(L=>e.jsx("div",{className:"border-b border-border/30 px-2 py-1 last:border-b-0",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:fe("shrink-0 uppercase",L.level==="error"||L.level==="runtime"||L.level==="resource"?"text-status-error":L.level==="warn"?"text-status-warning":"text-muted-foreground"),children:L.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:L.message})]})},L.id))})]}):null]})]})},ss=t=>t,Vt=t=>{const s=ss(t).type;return typeof s=="string"?s:""},xi=t=>{const s=ss(t).tool;return typeof s=="string"?s:""},bi=t=>{const s=ss(t).text;return typeof s=="string"?s:""},wi=t=>{const s=Vt(t);return s==="tool"?xi(t).trim().toLowerCase()||"tool":s||"unknown"},yi=t=>{if(t.length===0)return"";const s=[];for(const r of t){const a=wi(r);s.includes(a)||s.push(a)}return s.join(" + ")},vi=t=>t.replace(/\s+/g," ").trim(),ji=t=>{for(const r of t)if(Vt(r)==="text"){const a=vi(bi(r));if(a.length===0)continue;return a}const s=t.filter(r=>Vt(r)!=="text").length;return s===0?"":`${s} attachment${s===1?"":"s"}`},Si=(t,s,r)=>`${r(t)} / ${r(s)}`,ki=t=>{if(t==="12h")return!0;if(t==="24h")return!1},Ci=(t,s)=>{if(!t||!Number.isFinite(t))return"-";const r=ki(s);return new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:r===!1?"2-digit":"numeric",minute:"2-digit",...r===void 0?{}:{hour12:r}})},Ni={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},St={user:0,assistant:0,tool:0,other:0},Pi=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Mt=t=>$t(t),Ri=(...t)=>{for(const s of t)if(typeof s=="string"&&s.trim().length>0)return s;return""},We=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((s,r)=>s+We(r),0):t&&typeof t=="object"?Object.values(t).reduce((s,r)=>s+We(r),0):0,Ei=(t,s)=>{const r=t,a=typeof r.type=="string"?r.type:"";if(a==="reasoning")return{...St,assistant:We(r.text)+We(r.content)};const i=Ri(r.text,r.content,r.value,r.source?.value,r.source?.text?.value);return a==="tool"||s==="tool"?{user:0,assistant:0,tool:We(r.input)+We(r.output)+We(r.error)+We(r.call?.input)+We(r.call?.output)+We(r.call?.error)+We(r.raw)+Math.round(We(r.metadata)*.25)+Math.round(We(r.state)*.1),other:0}:s==="user"?{user:i.length,assistant:0,tool:0,other:0}:s==="assistant"?{user:0,assistant:i.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:i.length}},Is=(t,s)=>({user:t.user+s.user,assistant:t.assistant+s.assistant,tool:t.tool+s.tool,other:t.other+s.other}),Ti=t=>{const s=pt(t.info);return s.isUser?"user":s.role==="assistant"?"assistant":s.role==="tool"?"tool":"other"},Di=(t,s)=>{if(t.length===0)return{...St};const r=t.reduce((a,i)=>{const o=Ti(i);let u={...St};for(const l of i.parts)u=Is(u,Ei(l,o));return Is(a,u)},{...St});return r.user+=s.length,{user:Math.ceil(r.user/4),assistant:Math.ceil(r.assistant/4),tool:Math.ceil(r.tool/4),other:Math.ceil(r.other/4)}},Ge=t=>t.toLocaleString("en-US"),Ai=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),_i=(t,s)=>!t||!Number.isFinite(t)?"-":qr(t,s,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),Mi=(t,s,r)=>{const a=t.find(o=>o.id===s),i=a?.models?.find(o=>o.id===r);return{providerName:a?.name||s||"-",modelName:i?.name||r||"-",contextLimit:typeof i?.limit?.context=="number"?i.limit.context:null}},Ii=()=>{const t=K(p=>p.timeFormatPreference),[s,r]=n.useState({}),{value:a,show:i,clear:o}=Vr(null,2e3),u=Me(p=>p.currentSessionId),l=Me(p=>p.currentSessionDirectory),c=Kr(),h=sn(u??""),f=Ze(p=>p.providers);n.useEffect(()=>{r(p=>Object.keys(p).length>0?{}:p),o()},[o,l,u]);const y=n.useCallback(async(p,C)=>{(await ct(C)).ok?i(p):o()},[o,i]),d=n.useMemo(()=>{const p=u?c.find(D=>D.id===u)??null:null,C=h.filter(D=>pt(D.info).role==="assistant"),x=h.filter(D=>pt(D.info).isUser);let P=null;for(let D=C.length-1;D>=0;D-=1){const O=C[D];if(Mt(O).total>0){P=O;break}}const _=P?Mt(P):Ni,U=P?.info?.usage,w=Qs({input:_.input,cache:{read:_.cacheRead,write:_.cacheWrite}}),E=C.reduce((D,O)=>{const G=Pi(O.info.cost);return D+G},0),S=P?.info?.model??null,M=Mi(f,S?.providerID||"",S?.modelID||""),j=M.contextLimit,T=U?Zs(U):_.total,Y=j&&j>0?Math.min(999,T/j*100):0,X=[...h].reverse().find(D=>pt(D.info).isUser&&typeof D.info.system=="string")?.info?.system||"",z=Di(h,X),Z=z.user,le=z.assistant,H=z.tool,ne=U?0:Math.max(0,_.input-Z-le-H),N=Z+le+H+ne,F=h[0]?.info?.time?.created,oe=h.length>0?h[h.length-1]?.info?.time?.created:null;return{sessionTitle:nn(p),messagesCount:h.length,userMessagesCount:x.length,assistantMessagesCount:C.length,createdAt:p?.time?.created??F??null,lastActivityAt:oe??p?.time?.created??null,providerModel:M,tokenBreakdown:_,usagePercent:Y,cacheHitRate:w,totalAssistantCost:E,contextLimit:j,contextWindowTokens:T,hasUsage:U!==void 0,breakdown:{user:Z,assistant:le,tool:H,other:ne},breakdownTotal:N}},[u,f,h,c]);if(!u)return e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:"Open a session to inspect context."});const b=[{key:"user",label:"User",value:d.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:d.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool calls",value:d.breakdown.tool,color:"var(--status-warning)"},...d.hasUsage?[]:[{key:"other",label:"Other",value:d.breakdown.other,color:"var(--surface-muted-foreground)"}]];return e.jsx("div",{className:"h-full overflow-y-auto bg-background",children:e.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:d.sessionTitle}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 typography-micro text-subtle-foreground",children:[e.jsxs("span",{children:[d.providerModel.providerName," / ",d.providerModel.modelName]}),d.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:_i(d.createdAt,t)})]})]})]}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Context"}),e.jsxs("span",{className:"typography-micro tabular-nums text-subtle-foreground",children:[Ge(d.contextWindowTokens),d.contextLimit?` / ${Ge(d.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:d.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,d.usagePercent)}%`,backgroundColor:d.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}})}),e.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:`${d.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:Ge(d.messagesCount)},{label:"User",value:Ge(d.userMessagesCount)},{label:"Assistant",value:Ge(d.assistantMessagesCount)},{label:"Cost",value:Ai(d.totalAssistantCost)}].map(p=>e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[e.jsx("div",{className:"typography-micro text-subtle-foreground",children:p.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:p.value})]},p.label))}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:"Last assistant message"}),e.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:"Input",value:d.tokenBreakdown.input,format:"count"},{label:"Output",value:d.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:d.tokenBreakdown.reasoning,format:"count"},{label:"Cache read",value:d.tokenBreakdown.cacheRead,format:"count"},{label:"Cache write",value:d.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache hit",value:d.cacheHitRate.hasInput?d.cacheHitRate.percent:null,format:"percent"}].map(p=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-subtle-foreground",children:p.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:p.value!==null&&p.value!==void 0?p.format==="percent"?`${p.value.toFixed(1)}%`:Ge(p.value):"—"})]},p.label))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:b.map(p=>p.value<=0||d.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${p.value/d.breakdownTotal*100}%`,backgroundColor:p.color}},p.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:b.map(p=>{const C=d.breakdownTotal>0?p.value/d.breakdownTotal*100:0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:p.color}}),e.jsxs("span",{className:"typography-micro text-subtle-foreground",children:[p.label," ",e.jsxs("span",{className:"tabular-nums",children:[C.toFixed(0),"%"]})]})]},p.key)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Raw messages"}),e.jsx("div",{className:"mt-2.5 space-y-1",children:[...h].reverse().map(p=>{const x=pt(p.info).role,P=x==="assistant",_=x==="user",U=s[p.info.id]===!0,w=a===p.info.id,E=p.info.time?.created??null,S=yi(p.parts),M=P?Mt({info:p.info,parts:p.parts}):null,j=_?ji(p.parts):"",T=Ci(E,t),Y=S||"—",X=M?Si(M.input,M.output,Ge):"",z=x||"unknown",Z=S?`${z}: ${S}`:z,le=U?JSON.stringify({info:p.info,parts:p.parts},null,2):"";return e.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[e.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":U,onClick:()=>{r(H=>({...H,[p.info.id]:H[p.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:P?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[_?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",j]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:P?Y:Z}),P&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:X})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:T})]})}),U&&e.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:e.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[e.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:e.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:H=>{H.stopPropagation(),y(p.info.id,le)},"aria-label":w?"Copied":"Copy JSON",title:w?"Copied":"Copy",children:w?e.jsx(W,{name:"check",className:"size-3.5"}):e.jsx(W,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Xr,{language:"json",code:le,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},p.info.id)})})]})]})})},Li=n.lazy(()=>Oe(()=>import("./AgentsSurface-BmHImX8m.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])).then(t=>({default:t.AgentsSurface}))),Bi=Ke(()=>Oe(()=>import("./DiffView-C70pbgk-.js"),__vite__mapDeps([14,1,2,3,5,6,7,8,9,10,4,11,12,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55])).then(t=>({default:t.DiffView}))),Oi=Ke(()=>Oe(()=>import("./FilesView-nFJYEdRw.js"),__vite__mapDeps([56,1,2,3,5,6,7,8,9,10,4,11,12,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,53,54,35,36,20,21,22,23,24,25,26,27,28,29,30,31,32,33,73,74,48,49,50,51,52,75,76,17,18,19,34,37,38,39,40,41,42,43,77,78,79,80,81,47])).then(t=>({default:t.FilesView}))),$i=Ke(()=>Oe(()=>import("./GitView-MIDG5RYW.js"),__vite__mapDeps([82,7,1,2,3,4,5,6,8,9,10,11,12,48,49,50,51,52,15,83,84,85,86,46,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,16,44,45,47,53,54])).then(t=>({default:t.GitView}))),Fi=Ke(()=>Oe(()=>import("./PullRequestsSurface-o_AXDjbO.js"),__vite__mapDeps([87,7,1,2,3,88,5,6,8,9,10,4,11,12,48,49,50,51,52,89,83,84,46,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,16,44,45,47,53,54])).then(t=>({default:t.PullRequestsSurface}))),Wi=Ke(()=>Oe(()=>import("./IssuesSurface-uNlozeu0.js"),__vite__mapDeps([90,1,2,3,88,5,6,7,8,9,10,4,11,12,48,49,50,51,52,89,83,84,91])).then(t=>({default:t.IssuesSurface}))),zi=380,Hi=1400,Sn=600,Ui=100,Vi=24,Ls=720,Bs=t=>Number.isFinite(t)?Math.min(Hi,Math.max(zi,Math.round(t))):Sn,Ki=t=>{const s=t?.parentElement?.clientWidth;return!s||s<=0?null:s},Xi=(t,s)=>{if(!t)return"";const r=t.replace(/\\/g,"/"),a=s.replace(/\\/g,"/").replace(/\/+$/,"");return a&&r.startsWith(a+"/")?r.slice(a.length+1):r},Kt=(t,s=null)=>t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?es(s).label:t==="terminal"?"Terminal":t==="pull-requests"?"Pull requests":t==="issues"?"Issues":t==="extensions"?"Extensions":t==="agents"?"Agents":"Context",kn=t=>{if(!t)return null;const s=t.replace(/\\/g,"/").trim();if(!s)return null;const r=s.split("/").filter(Boolean);return r.length===0?s:r[r.length-1]||null},qi=(t,s=null)=>{if(t.label)return t.label;if(t.mode==="file")return kn(t.targetPath)||"Files";if(t.mode==="preview"){const r=t.targetPath;if(r)try{const a=new URL(r);return a.host||a.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":Kt(t.mode,s)},It=(t,s=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(Ct,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(Rr,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(W,{name:es(s).icon,className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(W,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(W,{name:"pie-chart",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(W,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(W,{name:"global",className:"h-3.5 w-3.5"});if(t.mode==="pull-requests")return e.jsx(W,{name:"git-pull-request",className:"h-3.5 w-3.5"});if(t.mode==="issues")return e.jsx(W,{name:"task",className:"h-3.5 w-3.5"});if(t.mode==="extensions")return e.jsx(W,{name:"plug-2",className:"h-3.5 w-3.5"});if(t.mode==="agents")return e.jsx(W,{name:"robot-2",className:"h-3.5 w-3.5"})},Yi=(t,s)=>t.length<=s?t:`${t.slice(0,s-3)}...`,Gi=()=>{const t=bt()??"",s=n.useMemo(()=>Be(t),[t]),r=K(v=>s?v.contextPanelByDirectory[s]:void 0),a=K(v=>v.closeContextPanel),i=K(v=>v.closeContextPanelTab),o=K(v=>v.openContextPanelTab),u=K(v=>v.toggleContextPanelExpanded),l=K(v=>v.setContextPanelWidth),c=K(v=>v.setActiveContextPanelTab),h=K(v=>v.reorderContextPanelTabs),f=Ue(v=>v.setSelectedPath),y=K(v=>v.openContextPreview),d=K(v=>v.contextEditorTreeVisible),b=K(v=>v.toggleContextEditorTree),p=Me(v=>v.currentSessionId),C=n.useMemo(()=>r?.tabs??[],[r?.tabs]),x=C.find(v=>v.id===r?.activeTabId)??C[C.length-1]??null,P=!!(r?.isOpen&&x),_=!!(P&&r?.expanded),[U,w]=n.useState(null),E=r?.width,S=Jr,M=U??(typeof window<"u"?window.innerWidth:Sn*2),j=Bs(E??Math.round(S*M)),T=rn(s||null),[Y,X]=n.useState(!1),[z,Z]=n.useState(null),[le,H]=n.useState(null),[ne,N]=n.useState(null),[F,oe]=n.useState(null),D=n.useRef(0),O=n.useRef(j),G=n.useRef(null),ue=n.useRef(null),ge=n.useRef(null),he=n.useRef(!1);n.useLayoutEffect(()=>{const v=ge.current?.parentElement;if(!v||typeof ResizeObserver>"u")return;const me=new ResizeObserver(()=>{w(v.clientWidth||null)});return me.observe(v),w(v.clientWidth||null),()=>me.disconnect()},[]),n.useEffect(()=>{if(!P||he.current){he.current=P;return}const v=window.requestAnimationFrame(()=>{ge.current?.focus({preventScroll:!0})});return he.current=!0,()=>window.cancelAnimationFrame(v)},[P]);const be=n.useRef(null),je=n.useRef(null),Ce=n.useCallback(()=>{je.current=null;const v=ge.current,me=G.current;!v||me===null||v.style.setProperty("--oc-context-panel-width",`${me}px`)},[]);n.useEffect(()=>()=>{je.current!==null&&clearTimeout(je.current)},[]);const ve=n.useCallback(v=>{const me=Bs(v),Ae=be.current;return Ae===null?me:Math.min(me,Math.max(1,Ae))},[]),ye=n.useCallback(v=>{!P||_||!s||(ue.current=v.pointerId,X(!0),D.current=v.clientX,O.current=j,G.current=j,be.current=Ki(ge.current),document.documentElement.style.cursor="col-resize",v.preventDefault())},[s,_,P,j]),Re=n.useCallback(()=>{const v=ve(G.current??j);G.current=null,be.current=null,je.current!==null&&(clearTimeout(je.current),je.current=null),document.documentElement.style.cursor="",s&&l(s,v),X(!1),ue.current=null},[ve,s,l,j]);n.useEffect(()=>{if(!Y)return;const v=$e=>{if(ue.current!==$e.pointerId)return;const Nn=D.current-$e.clientX,ns=ve(O.current+Nn);G.current!==ns&&(G.current=ns,je.current===null&&(je.current=setTimeout(Ce,Ui)))},me=$e=>{ue.current===$e.pointerId&&Re()},Ae=()=>{Re()};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",me),window.addEventListener("pointercancel",me),window.addEventListener("blur",Ae),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",me),window.removeEventListener("pointercancel",me),window.removeEventListener("blur",Ae)}},[Ce,ve,Re,Y]),n.useEffect(()=>{Y||(G.current=null,document.documentElement.style.cursor="")},[Y]);const Te=n.useCallback(()=>{s&&a(s)},[a,s]),Se=n.useCallback(()=>{s&&u(s)},[s,u]),ke=n.useCallback(v=>{v.key==="Escape"&&(Yr(v.target)||(v.preventDefault(),v.stopPropagation(),Te()))},[Te]);n.useEffect(()=>{if(!(!s||!x)&&x.mode==="file"&&x.targetPath){f(s,x.targetPath,{allowOutsideRoot:!0});return}},[x,s,f]);const Ne=n.useCallback(v=>{!s||x?.mode!=="diff"||o(s,{mode:"diff",targetPath:x.targetPath,stagedDiff:v==="staged",diffScope:v})},[x,s,o]),De=x?.mode==="file"||x?.mode==="preview",B=n.useMemo(()=>x?C.filter(v=>v.mode===x.mode):[],[x,C]),J=n.useMemo(()=>B.map(v=>{const me=qi(v,T),Ae=Yi(me,Vi),$e=Xi(v.targetPath,t);return{id:v.id,label:Ae,icon:It(v,T),title:$e?`${me}: ${$e}`:me,closeLabel:`Close ${Ae} tab`}}),[B,t,T]),re=x?.mode==="pull-requests",L=x?.mode==="issues",ee=K(v=>v.gitReturnToFile?.directory===s?v.gitReturnToFile.focusPath:null),ae=x?.mode==="context"?e.jsx(Ii,{}):x?.mode==="extensions"?e.jsx(Gr,{sessionId:p}):x?.mode==="agents"?e.jsx(n.Suspense,{fallback:null,children:e.jsx(Li,{sessionId:p})}):x?.mode==="git"?e.jsx(n.Suspense,{fallback:null,children:e.jsx($i,{isActive:P,gitHeaderSlot:x?.mode==="git"?le:null,onlyFilePath:ee})}):x?.mode==="pull-requests"?e.jsx(n.Suspense,{fallback:null,children:e.jsx(Fi,{headerActionsSlot:re?F:null,headerActionsPresentation:"desktop"},`pull-requests:${s}`)}):x?.mode==="issues"?e.jsx(n.Suspense,{fallback:null,children:e.jsx(Wi,{headerActionsSlot:L?F:null,headerActionsPresentation:"desktop"},`issues:${s}`)}):x?.mode==="preview"?e.jsx(gi,{rawUrl:x.targetPath??"",onNavigate:v=>y(t,v)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(W,{name:"global",className:"h-12 w-12 text-subtle-foreground"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"Preview"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Use Project Actions or a terminal Preview button to open a preview."})]}),g=n.useMemo(()=>C.filter(v=>v.mode==="browser"),[C]),A=n.useMemo(()=>C.filter(v=>v.mode==="diff"),[C]),te=n.useMemo(()=>C.some(v=>v.mode==="terminal"),[C]),de=n.useMemo(()=>C.some(v=>v.mode==="file"),[C]),m=n.useMemo(()=>C.some(v=>v.mode==="file"&&v.targetPath),[C]),I=x?.mode==="file"?x.targetPath??null:null,V=_?U:j,pe=!!(m&&V!==null&&V<Ls),[Ee,Ie]=n.useState(!1);n.useEffect(()=>{Ie(!1)},[I]);const Le=!m&&V!==null&&V<Ls,Xe=Le?!0:pe?Ee:d,Ye=K(v=>v.fileTreeReveal);n.useEffect(()=>{Ye&&(pe?Ie(!0):K.getState().contextEditorTreeVisible||b())},[Ye,b,pe]);const k=n.useCallback(()=>{if(pe){Ie(v=>!v);return}b()},[b,pe]),q=x?.mode==="file",ce=K(v=>v.gitReturnToFile),ie=K(v=>v.clearGitReturnToFile),we=K(v=>v.showAllGitChanges),se=ce&&ce.directory===s&&x?.mode==="git"?C.find(v=>v.id===ce.tabId&&v.mode==="file"&&v.targetPath)??null:null;n.useEffect(()=>{ce&&(!P||x?.mode!=="git"||ce.directory!==s)&&ie()},[x?.mode,ie,s,ce,P]);const Pe=x?.mode==="terminal",_e=x?.mode==="git",He=x?.mode==="diff",R=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[De?e.jsx(un,{items:J,activeId:x?.id??null,onSelect:v=>{s&&c(s,v)},onClose:v=>{if(s){for(const me of C.find(Ae=>Ae.id===v)?.browser?.pages??[])Js(s,me.id);i(s,v)}},onReorder:(v,me)=>{s&&h(s,v,me)},layoutMode:"scrollable",variant:"default"}):Pe?e.jsx("div",{ref:v=>{Z(v)},className:"flex min-w-0 flex-1 items-center px-1"}):_e?e.jsx("div",{ref:v=>{H(v)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):He?e.jsx("div",{ref:v=>{N(v)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):re||L?e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[x?It(x,T):null,e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:x?Kt(x.mode,T):null}),e.jsx("span",{className:"min-w-0 flex-1"}),e.jsx("div",{ref:v=>{oe(v)},className:"flex shrink-0 items-center gap-1"})]}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[x?It(x,T):null,e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:x?Kt(x.mode,T):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[q&&!Le?e.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:k,className:fe("h-8 w-8 p-0",Xe&&"bg-interactive-selection text-foreground"),title:Xe?"Hide file tree":"Show file tree","aria-label":"Toggle file tree","aria-pressed":Xe,children:e.jsx(W,{name:"node-tree",className:"size-4"})}):null,e.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:Se,className:"h-8 w-8 p-0",title:_?"Collapse panel":"Expand panel","aria-label":_?"Collapse panel":"Expand panel",children:_?e.jsx(W,{name:"fullscreen-exit",className:"size-4"}):e.jsx(W,{name:"fullscreen",className:"size-4"})}),e.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:Te,className:"h-8 w-8 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(W,{name:"close",className:"size-4"})})]})]}),$=P?_?{"--oc-context-panel-width":U!==null?`${U}px`:"100%",width:U!==null?`${U}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${j}px`}:{"--oc-context-panel-width":`${j}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:ge,"data-context-panel":"true",tabIndex:-1,inert:!P||void 0,className:fe("flex min-h-0 flex-col overflow-hidden bg-background",_?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!P&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:ke,style:$,children:[P&&!_&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),P&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!_&&e.jsx("div",{className:fe("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",Y&&"bg-[var(--interactive-border)]"),onPointerDown:ye,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:fe("relative z-10 flex h-full min-h-0 shrink-0 flex-col duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none","transition-[width,opacity]",!P&&"pointer-events-none select-none opacity-0"),style:{width:_?U!==null?`${U}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!P,children:[R,e.jsxs("div",{className:fe("relative min-h-0 flex-1 overflow-hidden",Y&&"pointer-events-none"),children:[de?e.jsxs("div",{className:fe("absolute inset-0 flex",q?"flex":"hidden"),children:[e.jsx("div",{className:"relative h-full min-w-0 flex-1",children:m?e.jsx(n.Suspense,{fallback:null,children:e.jsx(Oi,{mode:"editor-only",isVisible:P&&q})}):Le?null:e.jsx(ui,{directory:t})}),e.jsx(di,{visible:Xe,overlay:pe||Le,onDismissOverlay:pe?()=>Ie(!1):void 0})]}):null,g.map(v=>e.jsx("div",{className:fe("absolute inset-0",x?.id!==v.id&&"hidden"),children:e.jsx(Ja,{directory:s,browser:v.browser,onScreen:P&&x?.id===v.id})},v.id)),P?A.filter(v=>x?.id===v.id).map(v=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(n.Suspense,{fallback:null,children:e.jsx(Bi,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:v.diffScope??(v.stagedDiff?"staged":"working"),onDiffScopeChange:Ne,targetFilePath:v.targetPath,flushContent:!0,toolbarSlot:He?ne:null})})},v.id)):null,te?e.jsx("div",{className:fe("absolute inset-0",x?.mode==="terminal"?"block":"hidden"),children:e.jsx(en,{visible:P&&x?.mode==="terminal",terminalHeaderSlot:Pe?z:null})}):null,P&&x?.mode==="git"?e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[se?e.jsxs("div",{className:"flex h-9 shrink-0 items-center border-b border-border/60 pl-1.5 pr-1",children:[e.jsxs(Q,{variant:"ghost",size:"xs",onClick:()=>{ie(),c(s,se.id)},className:"min-w-0 text-muted-foreground hover:text-foreground",children:[e.jsx(W,{name:"arrow-left",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:`Back to ${kn(se.targetPath)??"file"}`})]}),ce?.focusPath?e.jsx(Q,{variant:"ghost",size:"xs",onClick:we,className:"ml-auto shrink-0 text-muted-foreground hover:text-foreground",children:"Show all changes"}):null]}):null,e.jsx("div",{className:"relative min-h-0 flex-1",children:ae})]}):P&&!q&&x?.mode!=="browser"&&x?.mode!=="diff"&&x?.mode!=="terminal"?ae:null]})]})]})},Ji=150,Qi=500,Zi=[],Je=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),yt=(t,s)=>{if(!t||typeof t!="object")return;const r=t[s];return typeof r=="number"&&Number.isFinite(r)?r:void 0},el=t=>t>99?"99+":String(t),tl=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",sl=({surface:t,isActive:s,showActivityDot:r,label:a,description:i,badgeCount:o,badgeAriaLabel:u,badgeDescription:l,orderNumber:c,showOrderNumber:h,onSelect:f,chartPercentage:y,chartDetails:d})=>{const{attributes:b,listeners:p,setNodeRef:C,transform:x,transition:P,isDragging:_}=Hs({id:t.id}),U=o!=null&&o>0?el(o):null;return e.jsx("div",{ref:C,style:{transform:Us.Translate.toString(x),transition:P},className:fe("relative",_&&"z-10 opacity-70"),children:e.jsxs(et,{delayDuration:Ji,children:[e.jsx(tt,{asChild:!0,children:e.jsxs("button",{type:"button",...b,...p,onClick:()=>f(t),"aria-label":u??a,"aria-pressed":s,className:fe("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[t.id==="context"&&typeof y=="number"?e.jsx(gs,{percentage:y,className:"size-[18px] -rotate-90"}):e.jsx(W,{name:t.icon,className:"h-[18px] w-[18px]"}),h&&c!=null?e.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-muted px-1 text-[0.625rem] font-medium leading-none text-muted-foreground",children:c===10?"0":c}):U?e.jsx("span",{"aria-hidden":"true",className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[0.625rem] font-semibold leading-none",style:{backgroundColor:"var(--status-info-background)",color:"var(--status-info)"},children:U}):r?e.jsx("span",{"aria-hidden":"true",className:"absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-[var(--status-info)]"}):null]})}),e.jsx(st,{side:"left",sideOffset:8,className:t.id==="context"&&d?"p-0 border-0 bg-transparent shadow-none":void 0,children:t.id==="context"&&d?e.jsx("div",{className:"w-[300px] overflow-hidden rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[e.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:e.jsx(gs,{percentage:d.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:a}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:d.hasData?e.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[e.jsxs("span",{className:fe("font-semibold",tl(d.percentage)),children:[d.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${Je(d.totalTokens)}/${Je(d.contextLimit)}`})]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:"No data yet"})})]}),d.hasData?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Je(d.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Je(d.contextLimit)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Je(d.outputLimit)})]}),typeof d.cacheRead=="number"&&typeof d.cacheWrite=="number"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Je(d.cacheRead)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Je(d.cacheWrite)})]})]}):null,typeof d.cacheHitPercent=="number"?e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache hit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:`${d.cacheHitPercent.toFixed(1)}%`})]}):null]}):e.jsx("div",{className:"px-2.5 py-2 typography-micro text-muted-foreground",children:i})]})}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:a}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:i}),l?e.jsx("span",{className:"typography-micro text-muted-foreground",children:l}):null]})})]})})},nl=()=>{const t=bt(),s=t?Vn(t):"",r=K(g=>s?g.contextPanelByDirectory[s]:void 0),a=K(g=>g.contextRailOrder),i=K(g=>g.setContextRailOrder),o=K(g=>g.openContextSurface),u=K(g=>g.shortcutOverrides),{screenWidth:l}=kt(),{git:c,github:h}=Nt(),f=qt(s||null),y=rn(s||null),d=on(g=>g.ensureStatus),b=ps(g=>g.ensureScope);n.useEffect(()=>{s&&d(s,c)},[s,d,c]),n.useEffect(()=>{!s||!h||b(s,h)},[s,b,h]);const p=n.useMemo(()=>Kn("switch_context_surface",u),[u]),[C,x]=n.useState(!1);n.useEffect(()=>{const g=new Set;let A=null,te=!1;const de=Ee=>Ee.length===1&&Ee>="0"&&Ee<="9",m=()=>{as(p,g)?!te&&A===null&&(A=setTimeout(()=>x(!0),Qi)):(te=!1,A!==null&&(clearTimeout(A),A=null),x(!1))},I=Ee=>{if(g.add(Ee.key.toLowerCase()),de(Ee.key)&&as(p,g)){te=!0,A!==null&&(clearTimeout(A),A=null),x(!1);return}m()},V=Ee=>{g.delete(Ee.key.toLowerCase()),m()},pe=()=>{g.clear(),te=!1,A!==null&&(clearTimeout(A),A=null),x(!1)};return window.addEventListener("keydown",I,!0),window.addEventListener("keyup",V,!0),window.addEventListener("blur",pe),()=>{window.removeEventListener("keydown",I,!0),window.removeEventListener("keyup",V,!0),window.removeEventListener("blur",pe),A!==null&&clearTimeout(A)}},[p]);const P=$s(Bt(Dn,{activationConstraint:{distance:8}}),Bt(Tn,{activationConstraint:{delay:200,tolerance:6}})),_=r?.tabs??Zi,U=_.find(g=>g.id===r?.activeTabId)??null,w=r?.isOpen?U?.mode??null:null,E=f?.files.length??0,S=Me(g=>g.currentSessionId),M=Me(g=>!!g.newSessionDraft?.open),j=Ze(g=>g.providers),T=Ze(g=>g.currentProviderId),Y=Ze(g=>g.currentModelId),X=Ze(g=>g.getCurrentModel()),z=Ze(g=>g.getModelMetadata);Ze(g=>g.modelsMetadata.size);const Z=Qr(n.useCallback(g=>S?g.sessionModelSelections.get(S)??null:null,[S])),le=sn(S??""),H=n.useMemo(()=>{for(let g=le.length-1;g>=0;g-=1){const A=le[g];if(A?.info.role==="assistant")try{if($t(A).total>0)return A}catch{continue}}return null},[le]),N=n.useMemo(()=>{for(let g=le.length-1;g>=0;g-=1){const A=le[g]?.info;if(A.role!=="user")continue;const te=A.model,de=te?.providerID??te?.providerId,m=te?.modelID??te?.modelId;if(typeof de=="string"&&de.trim()&&typeof m=="string"&&m.trim())return{providerID:de,modelID:m}}return null},[le])??(()=>{const g=H?.info.model,A=g?.providerID??g?.providerId,te=g?.modelID??g?.modelId;return A&&te?{providerID:A,modelID:te}:null})()??(Z?{providerID:Z.providerId,modelID:Z.modelId}:null)??(T&&Y?{providerID:T,modelID:Y}:null),oe=(N?j.find(g=>g.id===N.providerID):void 0)?.models.find(g=>g.id===N?.modelID),D=N?z(N.providerID,N.modelID):void 0,O=yt(oe?.limit,"context")??D?.limit?.context??yt(X?.limit,"context")??0,G=yt(oe?.limit,"output")??D?.limit?.output??yt(X?.limit,"output")??0,ue=H?(()=>{try{return $t(H)}catch{return null}})():null,ge=H?.info?.usage,he=ge?Zs(ge):ue?.total??0,be=!M&&he>0&&O>0?Math.min(he/O*100,999):0,Ce=!M&&!!H&&he>0&&O>0?be:null,ve=ue?Qs({input:ue.input,cache:{read:ue.cacheRead,write:ue.cacheWrite}}):null,ye=ve?.hasInput?ve.percent:null,Re=n.useMemo(()=>{const g=!!H&&he>0&&O>0;return{percentage:be,totalTokens:he,contextLimit:O,outputLimit:G,cacheRead:ue?.cacheRead??null,cacheWrite:ue?.cacheWrite??null,cacheHitPercent:ye,hasData:g}},[ue,ye,O,H,G,be,he]),Te=ms(g=>S?g.reducer.bySession.get(S)?.extensionWidgets:void 0,(g,A)=>g===A,S?`session:${S}`:"chrome"),Se=n.useMemo(()=>Te?.size?[...Te.entries()].map(([g,A])=>`${g}:${A.lines.join(`
137
+ `)}`).join(";"):"",[Te]),ke=Se!=="",Ne=n.useRef({});n.useEffect(()=>{w==="extensions"&&S&&Se&&(Ne.current[S]=Se)},[w,S,Se]);const De=S?Ne.current[S]??"":"",B=w!=="extensions"&&Se!==""&&De!==Se,J=ms(g=>S?Zr(g.reducer.bySession.get(S)):!1,void 0,S?`session:${S}`:"chrome"),re=ps(g=>s?g.entriesByDirectory[s]??null:null),L=n.useMemo(()=>{if(!re)return{isLoading:!0,hasResult:!1,hasGitHubRepo:!1,hasError:!1};const g=re.scope?.repositories??[];return{isLoading:re.isLoading,hasResult:!!(re.scope||re.error),hasGitHubRepo:g.some(A=>!!(A.host&&A.owner&&A.repo&&!A.disabledReason)),hasError:!!(re.error&&!re.scope)}},[re]),ee=n.useMemo(()=>eo({railOrder:a,tabs:_,githubScope:L,hasExtensionContent:ke,hasAgentContent:J}),[a,l,_,L,ke,J]),ae=n.useCallback(g=>{const{active:A,over:te}=g;if(!te||A.id===te.id)return;const de=to(K.getState().contextRailOrder).map(V=>V.id),m=de.indexOf(A.id),I=de.indexOf(te.id);m===-1||I===-1||i(An(de,m,I))},[i]);return s?e.jsx("nav",{"aria-label":"Panel surfaces",className:"flex h-full w-11 flex-shrink-0 flex-col items-center gap-1 bg-background py-2",children:e.jsx(Fs,{sensors:P,collisionDetection:Ws,onDragEnd:ae,children:e.jsx(zs,{items:ee.map(g=>g.id),strategy:_n,children:ee.map((g,A)=>{const te=g.id==="git"?es(y):null,de=te?{...g,...te}:g,m=de.label,I=g.id==="git"&&y===!0?E:0,V=I>0?I:null,pe=g.id==="context",Ee=g.id==="extensions"?B:!1;return e.jsx(sl,{surface:de,isActive:w===g.mode,showActivityDot:Ee,label:m,description:de.description,badgeCount:V,badgeAriaLabel:V!==null?V===1?`${m}, ${V} changed file`:`${m}, ${V} changed files`:null,badgeDescription:V!==null?V===1?`${V} changed file`:`${V} changed files`:null,chartPercentage:pe?Ce:void 0,chartDetails:pe?Re:void 0,orderNumber:A+1,showOrderNumber:C,onSelect:Ie=>o(s,Ie.mode)},g.id)})})})}):null},rl=(t,s)=>!t||s.length===0?"":JSON.stringify([t,s]),ol=(t,s,r,a)=>!r||a!==r||t.length===0?[]:ft(t,s,i=>i.name,{limit:10,threshold:.4}),al=new Set,il=[{keys:["↑","↓"],label:"Navigate"},{keys:["↵"],label:"Open"},{keys:["Esc"],label:"Close"}],Lt=t=>{if(!t)return"";const s=t.replace(/\\/g,"/"),r=s.startsWith("//");let a=s.replace(/\/+/g,"/");r&&!a.startsWith("//")&&(a=`/${a}`);const i=a==="/",o=/^[A-Za-z]:\/$/.test(a);return!i&&!o&&(a=a.replace(/\/+$/,"")),a},ll=()=>{const t=K(m=>m.isCommandPaletteOpen),s=K(m=>m.setCommandPaletteOpen),r=K(m=>m.setActiveMainTab),a=K(m=>m.setSettingsDialogOpen),i=K(m=>m.setSettingsPage),o=K(m=>m.setSessionSwitcherOpen),u=K(m=>m.toggleSidebar),l=K(m=>m.openContextOverview),c=K(m=>m.openContextSurface),h=K(m=>m.openContextFile),f=K(m=>m.shortcutOverrides),y=Me(m=>m.openNewSessionDraft),d=Me(m=>m.setCurrentSession),b=so({archived:!1}),p=no(n.useCallback(m=>t?m.ids:al,[t])),C=ro(n.useCallback(m=>t?m.rankById:oo,[t])),x=is(m=>m.currentDirectory),P=is(m=>m.homeDirectory),_=xs(m=>m.getActiveProject()),U=xs(m=>m.projects),w=bt(),E=Xn(m=>m.searchFiles),{files:S,git:M}=Nt(),j=on(m=>m.ensureStatus),{isMobile:T}=kt(),Y=n.useMemo(()=>w?Lt(w):null,[w]),[X,z]=n.useState(""),le=ao(X,200).trim(),H=X.trim();n.useEffect(()=>{t&&z("")},[t]),n.useEffect(()=>{if(!t||!M)return;const m=setTimeout(()=>{const I=new Set;for(const V of b){const pe=Tt(V);!pe||I.has(pe)||(I.add(pe),j(pe,M))}},0);return()=>clearTimeout(m)},[t,b,M,j]);const ne=n.useCallback(()=>s(!1),[s]),N=n.useCallback(m=>()=>{ne(),m()},[ne]),F=n.useMemo(()=>{const m=[{id:"new-session",title:"New session",icon:e.jsx(W,{name:"chat-new",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New session",onSelect:N(()=>{r("chat"),o(!1),y()})},{id:"add-project",title:"Add folder",icon:e.jsx(W,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add folder",onSelect:N(()=>{io.requestDirectoryDialog()})},{id:"toggle-sidebar",title:T?"Show session switcher":"Toggle sidebar",icon:e.jsx(W,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:T?"Show session switcher":"Toggle sidebar",onSelect:N(()=>{if(T){const{isSessionSwitcherOpen:I}=K.getState();o(!I)}else u()})},{id:"toggle-terminal",title:"Toggle terminal",icon:e.jsx(W,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle terminal",onSelect:N(()=>{x&&c(x,"terminal")})},{id:"context-usage",title:"Show context usage",icon:e.jsx(W,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show context usage",onSelect:N(()=>{x&&l(x)})},{id:"open-settings",title:"Open settings…",icon:e.jsx(W,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open settings…",onSelect:N(()=>a(!0))}];return qn()&&m.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat window",icon:e.jsx(W,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat window",onSelect:N(()=>{Vs("desktop_open_draft_mini_chat_window",{directory:Lt(x||_?.path||""),projectId:_?.id??null}).catch(I=>{console.warn("[command-palette] failed to open draft mini chat window",I)})})}),m},[N,T,r,o,y,u,c,x,l,a,_?.id,_?.path]),oe=n.useMemo(()=>{const m=Ks();return{isWeb:!m&&Yn(),isDesktop:m,isMobile:T}},[T]),D=n.useMemo(()=>Er.filter(m=>m.slug!=="home").filter(m=>m.isAvailable?m.isAvailable(oe):!0).map(m=>{const I=Tr(m.slug)??"settings-3",V=(m.keywords??[]).join(" ");return{id:`settings:${m.slug}`,title:m.title,icon:e.jsx(W,{name:I,className:"mr-2 h-4 w-4"}),searchText:`${m.title} ${m.group} ${V}`,onSelect:N(()=>{i(m.slug),a(!0)})}}),[oe,N,i,a]),O=n.useMemo(()=>lo(b,p,C),[b,p,C]),G=co(),ue=n.useCallback(m=>{if(!m)return null;let I=null;for(const V of U){const pe=V.path.replace(/\/+$/,"");(m===pe||m.startsWith(`${pe}/`))&&(!I||pe.length>I.path.length)&&(I=V)}return I},[U]),ge=n.useCallback((m,I)=>{if(!m)return null;const V=G.get(m)?.trim()||null;if(!V||V==="HEAD"||!I)return V;const pe=I.path.replace(/\/+$/,"");return m===pe||V===G.get(pe)?.trim()?null:V},[G]),[he,be]=n.useState([]),[je,Ce]=n.useState(""),ve=rl(Y,le);n.useEffect(()=>{if(!t){be([]),Ce("");return}if(!ve){be([]),Ce("");return}if(!Y){be([]),Ce("");return}let m=!1;return E(Y,le,10,{type:"file"}).then(I=>{m||(be(I.map(V=>({path:Lt(V.path),name:V.name,relativePath:V.relativePath}))),Ce(ve))}).catch(()=>{m||(be([]),Ce(ve))}),()=>{m=!0}},[t,Y,le,ve,E]);const ye=H.length>0,Re=n.useMemo(()=>ye?ft(F,H,m=>m.searchText,{limit:7,noFuzzy:!0}):F.map(m=>({item:m,score:0})),[F,H,ye]),Te=n.useMemo(()=>ye?ft(D,H,m=>m.searchText,{limit:7,noFuzzy:!0}):[],[D,H,ye]),Se=n.useMemo(()=>ye?ft(O,H,m=>m.title||"",{limit:7,threshold:.2}):O.slice(0,5).map(m=>({item:m,score:0})),[O,H,ye]),ke=n.useMemo(()=>t?ol(he,le,ve,je):[],[t,he,je,ve,le]),Ne=t&&ve.length>0&&je!==ve,De=n.useMemo(()=>{if(!ye)return[];const m=U.map(I=>({...I,displayName:I.label||I.path.split("/").pop()||I.path,searchText:`${I.label||""} ${I.path}`}));return ft(m,H,I=>I.searchText,{limit:7,threshold:.4})},[U,H,ye]),B=Re.map(m=>m.item),J=Te.map(m=>m.item),re=Se.map(m=>m.item),L=ye?ke.map(m=>m.item):[],ee=ye?De.map(m=>m.item):[],ae=n.useMemo(()=>{if(!ye)return["commands","sessions"];const m=V=>V.length?V[0].score:1/0,I=[{key:"commands",score:m(Re)},{key:"settings",score:m(Te)},{key:"sessions",score:m(Se)},{key:"files",score:m(ke)},{key:"projects",score:m(De)}];return I.sort((V,pe)=>V.score-pe.score),I.map(V=>V.key)},[ye,Re,Te,Se,ke,De]),g=n.useCallback(m=>{ne(),d(m.id,Tt(m))},[ne,d]),A=n.useCallback(async m=>{if(!Y)return;const I=await cn(S,m,{directory:Y});if(!I.ok){xe.error(dn(I.reason));return}h(Y,m),ne()},[Y,S,h,ne]),te=n.useCallback((m,I)=>{ne(),y({selectedProjectId:m,directoryOverride:I})},[ne,y]),de=n.useCallback(m=>qs(Ys(m,f)),[f]);return e.jsxs(Yt,{open:t,onOpenChange:s,children:[e.jsxs(Jt,{className:"sr-only",children:[e.jsx(Qt,{children:"Command palette"}),e.jsx(Zt,{children:"Search files, sessions, and commands."})]}),e.jsxs(Gt,{showCloseButton:!1,className:fe("w-full max-w-xl gap-0 self-start overflow-hidden rounded-2xl p-0","mt-[max(env(safe-area-inset-top),0.25rem)] max-h-[calc(100%-0.5rem)] sm:mt-[10vh] sm:max-h-[80vh]"),children:[e.jsxs(uo,{shouldFilter:!1,className:fe("rounded-none","[&_[data-slot=command-input-wrapper]]:h-12 [&_[data-slot=command-input-wrapper]]:border-border/60 [&_[data-slot=command-input-wrapper]]:px-3.5","[&_[cmdk-input]]:h-12 [&_[cmdk-input]]:text-[length:var(--text-markdown)] md:[&_[cmdk-input]]:text-[length:var(--text-ui-label)]","[&_[cmdk-list]]:p-1.5 [&_[cmdk-group]]:p-0 [&_[cmdk-group]+[cmdk-group]]:mt-1","[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:pt-1.5 [&_[cmdk-group-heading]]:text-[length:var(--text-micro)]","[&_[cmdk-item]]:gap-2.5 [&_[cmdk-item]]:px-2.5 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]]:text-[length:var(--text-ui-label)]"),children:[e.jsx(ho,{value:X,onValueChange:z,placeholder:"Search files, sessions, commands..."}),e.jsxs(fo,{children:[e.jsx(po,{children:"No results found."}),ae.map(m=>m==="commands"&&B.length>0?e.jsx(ut,{heading:"Commands",children:B.map(I=>e.jsxs(ht,{value:I.id,onSelect:I.onSelect,children:[I.icon,e.jsx("span",{children:I.title}),I.shortcutId?e.jsx(mo,{children:de(I.shortcutId)}):null]},I.id))},"commands"):m==="settings"&&J.length>0?e.jsx(ut,{heading:"Settings",children:J.map(I=>e.jsxs(ht,{value:I.id,onSelect:I.onSelect,children:[I.icon,e.jsx("span",{children:I.title})]},I.id))},"settings"):m==="sessions"&&re.length>0?e.jsx(ut,{heading:"Sessions",children:re.map(I=>{const V=nn(I),pe=Tt(I),Ee=ue(pe),Ie=ge(pe,Ee),Le=Ee?go(Ee):xo(pe,P)?"No folder":null;return e.jsxs(ht,{value:`session:${I.id}`,onSelect:()=>g(I),children:[e.jsx(W,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:V}),Le||Ie?e.jsxs("span",{className:"ml-auto inline-flex min-w-0 max-w-[45%] shrink items-center gap-1.5 text-muted-foreground typography-meta",children:[Le?e.jsx("span",{className:"min-w-0 max-w-[140px] shrink-0 truncate",children:Le}):null,Ie?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1",children:[e.jsx(W,{name:"git-branch",className:"h-3 w-3 shrink-0"}),e.jsx(bo,{value:Ie,className:"min-w-0 max-w-[120px]"})]}):null]}):null]},I.id)})},"sessions"):m==="files"&&L.length>0?e.jsx(ut,{heading:"Files",children:L.map(I=>{const V=Gn(I.relativePath||I.name,{maxLength:80});return e.jsxs(ht,{value:`file:${I.path}`,onSelect:()=>{A(I.path)},children:[e.jsx(Ct,{filePath:I.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":I.relativePath,children:V})]},`file:${I.path}`)})},"files"):m==="projects"&&ee.length>0?e.jsx(ut,{heading:"Projects",children:ee.map(I=>{const V=I.displayName;return e.jsxs(ht,{value:`project:${I.id}`,onSelect:()=>te(I.id,I.path),children:[e.jsx(wo,{directory:I.path,label:V,className:"mr-2 size-4"}),e.jsx("span",{className:"truncate",children:V}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:I.path})]},`project:${I.id}`)})},"projects"):null),Ne?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]}),T?null:e.jsx("div",{className:"flex min-h-10 shrink-0 items-center border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:e.jsx(yo,{hints:il.map(m=>m.label==="Close"?{...m,onSelect:()=>s(!1)}:m)})})]})]})},cl=(t,s,r)=>Qn(t)?qs(Ys(t,r)):s,dl=()=>{const t=K(o=>o.isHelpDialogOpen),s=K(o=>o.setHelpDialogOpen),r=K(o=>o.shortcutOverrides),a=Jn(),i=[{categoryKey:"Navigation & commands",items:[{id:"open_command_palette",descriptionKey:"Open command palette",icon:"command",keys:""},{id:"open_help",descriptionKey:"Show Keyboard Shortcuts (this dialog)",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"Toggle session sidebar",icon:"layout-left",keys:""},{id:"add_selection_to_chat",descriptionKey:"Add selection to chat",icon:"add",keys:""},{id:"open_model_selector",descriptionKey:"Open model selector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"Navigate Models (in picker)",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"Adjust Thinking Mode (in picker, when supported)",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"Cycle thinking (global shortcut)",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${a} + N`],descriptionKey:"New Window (desktop only)",icon:"window"}]},{categoryKey:"Session management",items:[{id:"new_chat",descriptionKey:"Create new session",icon:"add",keys:""},{id:"focus_input",descriptionKey:"Focus chat input",icon:"text",keys:""},{id:"cycle_session_folder",descriptionKey:"Cycle session folder",icon:"folder-open",keys:""},{id:"cycle_draft_folder",descriptionKey:"Cycle draft folder",icon:"folder-3",keys:""},{id:"open_timeline_dialog",descriptionKey:"Open conversation timeline",icon:"history",keys:""},{id:"abort_run",descriptionKey:"Abort active run (double press)",icon:"close-circle",keys:""}]},{categoryKey:"Panels",items:[{id:"open_right_sidebar",descriptionKey:"Open right sidebar",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{keys:[`${a} + 1...0`],descriptionKey:"Switch Context Panel Surface (number key)",icon:"layout-right"}]},{categoryKey:"Interface",items:[{id:"cycle_theme",descriptionKey:"Cycle Theme (Light → Dark → System)",icon:"palette",keys:""},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"Open settings",icon:"settings-3",keys:""}]}];return e.jsx(Yt,{open:t,onOpenChange:s,children:e.jsxs(Gt,{className:"w-[92vw] max-w-[1120px] h-[84vh] max-h-[900px] flex flex-col overflow-hidden",children:[e.jsxs(Jt,{children:[e.jsxs(Qt,{className:"flex items-center gap-2",children:[e.jsx(W,{name:"command",className:"h-5 w-5"}),"Keyboard shortcuts"]}),e.jsx(Zt,{children:"Use these keyboard shortcuts to navigate PiChamber efficiently"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:e.jsx("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-x-10",children:i.map(o=>e.jsxs("div",{className:"min-w-0 break-inside-avoid",children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:o.categoryKey}),e.jsx("div",{className:"space-y-1",children:o.items.map(u=>{const l=u.id?cl(u.id,Array.isArray(u.keys)?u.keys[0]:u.keys,r):Array.isArray(u.keys)?u.keys:u.keys.split(" / ");return e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u.icon&&e.jsx(W,{name:u.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:u.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l)?l:[l]).map((c,h)=>e.jsxs(n.Fragment,{children:[h>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:c})]},`${c}-${h}`))})]},u.id||u.descriptionKey)})})]},o.categoryKey))})})]})})},ul=n.createContext(null),hl=({children:t,value:s})=>e.jsx(ul.Provider,{value:s,children:t}),Os=Ke(()=>Oe(()=>import("./GitView-MIDG5RYW.js"),__vite__mapDeps([82,7,1,2,3,4,5,6,8,9,10,11,12,48,49,50,51,52,15,83,84,85,86,46,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,16,44,45,47,53,54])).then(t=>({default:t.GitView}))),fl=Ke(()=>Oe(()=>import("./DiffView-C70pbgk-.js"),__vite__mapDeps([14,1,2,3,5,6,7,8,9,10,4,11,12,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55])).then(t=>({default:t.DiffView}))),pl=Ke(()=>Oe(()=>import("./FilesView-nFJYEdRw.js"),__vite__mapDeps([56,1,2,3,5,6,7,8,9,10,4,11,12,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,53,54,35,36,20,21,22,23,24,25,26,27,28,29,30,31,32,33,73,74,48,49,50,51,52,75,76,17,18,19,34,37,38,39,40,41,42,43,77,78,79,80,81,47])).then(t=>({default:t.FilesView}))),ml=Ke(()=>Oe(()=>import("./DiagramView-BZQxoiZu.js"),__vite__mapDeps([92,1,2,3,4,5,6,7,8,9,10,11,12,73,74])).then(t=>({default:t.DiagramView}))),gl=Ke(()=>Oe(()=>import("./SettingsView-BHBpt2Um.js").then(t=>t.h),__vite__mapDeps([93,1,2,3,5,6,7,8,9,10,4,11,12,48,49,50,51,52,94,95,96,85,86])).then(t=>({default:t.SettingsView}))),xl=Ke(()=>Oe(()=>import("./SettingsWindow-Cb4st5y5.js"),__vite__mapDeps([97,1,2,3,5,6,7,8,9,10,4,11,12,93,48,49,50,51,52,94,95,96,85,86])).then(t=>({default:t.SettingsWindow}))),bl=()=>{const t=K(N=>N.isSidebarOpen),s=K(N=>N.activeMainTab),r=K(N=>N.setIsMobile),a=K(N=>N.isSessionSwitcherOpen),i=K(N=>N.isSettingsDialogOpen),o=K(N=>N.setSettingsDialogOpen),[u,l]=n.useState(!1);n.useEffect(()=>{i&&l(!0)},[i]),n.useEffect(()=>{const N=()=>K.getState().closeMainSurfaces(),F=Me.subscribe((D,O)=>{const G=!!D.currentSessionId&&D.currentSessionId!==O.currentSessionId,ue=!!D.newSessionDraft?.open&&D.newSessionDraft!==O.newSessionDraft;(G||ue)&&N()}),oe=K.subscribe((D,O)=>{D.activeMainTab!==O.activeMainTab&&N()});return()=>{F(),oe()}},[]);const{isMobile:c}=kt(),h=n.useRef(!1),[f,y]=n.useState(!1),[d,b]=n.useState(!1),[p,C]=n.useState(!1),[x,P]=n.useState(!1),_=n.useCallback(N=>{y(N),K.getState().setSessionSwitcherOpen(N)},[]),U=n.useRef(typeof window>"u"?0:window.innerWidth),w=n.useRef(null),E=n.useRef(!1),S=n.useRef(!1),M=n.useRef(!1),j=n.useRef(null),T=n.useRef(null),Y=rs(-U.current),X=Fe.useRef(0),z=rs(U.current),Z=Fe.useRef(0);Fe.useEffect(()=>{c&&(X.current=window.innerWidth,Z.current=window.innerWidth)},[c]),Fe.useEffect(()=>{if(!c)return;const N=()=>{const F=window.innerWidth;X.current=F,Z.current=F,f||Y.get()<-10&&Y.set(-F),d||z.get()>10&&z.set(F)};return window.addEventListener("resize",N),window.addEventListener("orientationchange",N),()=>{window.removeEventListener("resize",N),window.removeEventListener("orientationchange",N)}},[c,Y,z,f,d]),Fe.useEffect(()=>{if(!c){C(!1);return}f&&C(!0);const N=X.current||U.current||(typeof window<"u"?window.innerWidth:0),F=wt(Y,f?0:-N,{type:"spring",stiffness:400,damping:35,mass:.8});return j.current=F,()=>F.stop()},[f,c,Y]),Fe.useEffect(()=>{if(!c){P(!1);return}d&&P(!0);const N=Z.current||U.current||(typeof window<"u"?window.innerWidth:0),F=wt(z,d?0:N,{type:"spring",stiffness:400,damping:35,mass:.8});return T.current=F,()=>F.stop()},[c,d,z]),Fe.useEffect(()=>{if(c)return Y.on("change",N=>{const F=X.current||U.current,oe=f||N>-F+.5;C(D=>D===oe?D:oe)})},[c,Y,f]),Fe.useEffect(()=>{if(c)return z.on("change",N=>{const F=Z.current||U.current,oe=d||N<F-.5;P(D=>D===oe?D:oe)})},[c,d,z]),Fe.useEffect(()=>{c&&!a&&f&&_(!1)},[a,c,f,_]),Fe.useEffect(()=>{if(!c){h.current=!1;return}h.current||(h.current=!0,_(!1),b(!1))},[c,_]),Fe.useEffect(()=>{if(!c||s!=="chat"||f||d||i)return;let N=!1,F;return(D=>{F=window.setTimeout(()=>{if(N)return;const O=Me.getState(),G=K.getState();G.activeMainTab!=="chat"||G.isSettingsDialogOpen||O.currentSessionId||O.newSessionDraft?.open||O.openNewSessionDraft({automatic:!0})},D)})(500),()=>{N=!0,F!==void 0&&window.clearTimeout(F)}},[s,c,i,f,d]),Fe.useEffect(()=>{!c||!i||(_(!1),b(!1))},[c,i,_]),n.useEffect(()=>{K.getState().isMobile!==c&&r(c)},[c,r]);const le=n.useCallback(()=>{f&&_(!1),b(!d)},[f,d,_]);Dr(w,{enabled:c,leftOpen:f,rightOpen:d,leftWidth:()=>X.current||U.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>Z.current||U.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:N=>{const F=X.current||U.current||(typeof window<"u"?window.innerWidth:0);Y.set(F*(N-1))},onRightProgress:N=>{const F=Z.current||U.current||(typeof window<"u"?window.innerWidth:0);z.set(F*(1-N))},onLeftOpen:()=>{d&&b(!1),_(!0)},onLeftClose:()=>_(!1),onRightOpen:()=>{f&&_(!1),b(!0)},onRightClose:()=>b(!1),onDragStart:N=>{E.current=!0,N==="left"?(S.current=f,j.current?.stop(),p||C(!0)):(M.current=d,T.current?.stop(),x||P(!0))},onDragEnd:(N,F)=>{if(E.current=!1,N==="left"&&typeof F=="boolean"){const oe=S.current;if(F===oe){const D=X.current||U.current||(typeof window<"u"?window.innerWidth:0),O=wt(Y,oe?0:-D,{type:"spring",stiffness:400,damping:35,mass:.8});j.current=O}}if(N==="right"&&typeof F=="boolean"){const oe=M.current;if(F===oe){const D=Z.current||U.current||(typeof window<"u"?window.innerWidth:0),O=wt(z,oe?0:D,{type:"spring",stiffness:400,damping:35,mass:.8});T.current=O}}}});const H=n.useMemo(()=>{if(!c&&s!=="terminal"&&s!=="diagram"||c&&s==="git"&&(d||x))return null;switch(s){case"git":return e.jsx(n.Suspense,{fallback:null,children:e.jsx(Os,{isActive:!0})});case"diff":return e.jsx(n.Suspense,{fallback:null,children:e.jsx(fl,{})});case"terminal":return e.jsx(en,{onCloseView:()=>K.getState().setActiveMainTab("chat")});case"files":return e.jsx(n.Suspense,{fallback:null,children:e.jsx(pl,{})});case"diagram":return e.jsx(n.Suspense,{fallback:null,children:e.jsx(ml,{})});default:return null}},[s,c,x,d]),ne=s==="chat";return e.jsxs(Ar,{children:[e.jsx(_r,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:fe("main-content-safe-area",c?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(ll,{}),e.jsx(dl,{}),e.jsx(Mr,{}),c?e.jsxs(hl,{value:{leftDrawerOpen:f,rightDrawerOpen:d,toggleLeftDrawer:()=>{const N=!f;d&&b(!1),_(N)},toggleRightDrawer:le,leftDrawerX:Y,rightDrawerX:z,leftDrawerWidth:X,rightDrawerWidth:Z,setMobileLeftDrawerOpen:_,setRightSidebarOpen:b},children:[!i&&e.jsx(cs,{onToggleLeftDrawer:()=>{const N=!f;d&&b(!1),_(N)},onToggleRightDrawer:()=>{le()},leftDrawerOpen:f,rightDrawerOpen:d}),e.jsx("div",{"data-page-scroll-lock":"true",className:fe("flex flex-1 overflow-hidden relative",i&&"hidden"),children:e.jsxs("main",{ref:w,className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:[e.jsx("div",{className:fe("absolute inset-0",!ne&&"invisible"),children:e.jsx(ze,{children:e.jsx(ds,{active:ne&&!i})})}),H&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ze,{children:H})}),e.jsx(ze,{children:e.jsx(us,{})}),e.jsx(os.div,{className:fe("absolute inset-0 z-20 bg-sidebar",!p&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:Y},"aria-hidden":!f,children:e.jsx(ze,{children:e.jsx(hs,{mobileVariant:!0,isVisible:p})})}),e.jsx(os.div,{className:fe("absolute inset-0 z-20 bg-sidebar",!x&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:z},"aria-hidden":!d,children:e.jsx(ze,{children:d||x?e.jsx(n.Suspense,{fallback:null,children:e.jsx(Os,{isActive:d})}):null})})]})}),i&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(ze,{children:e.jsx(n.Suspense,{fallback:null,children:e.jsx(gl,{onClose:()=>o(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(Go,{isOpen:t,isMobile:c,children:e.jsx(hs,{isVisible:t})}),e.jsxs("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden bg-background","data-page-scroll-lock":"true",children:[e.jsx(cs,{}),e.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden bg-background","data-page-scroll-lock":"true",children:[e.jsx("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border bg-background","data-page-scroll-lock":"true",children:e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden","data-page-scroll-lock":"true",children:e.jsxs("div",{className:"relative flex flex-1 min-h-0 min-w-0 overflow-hidden","data-page-scroll-lock":"true","data-chat-area":"true",children:[e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[e.jsx("div",{className:fe("absolute inset-0",!ne&&"invisible"),children:e.jsx(ze,{children:e.jsx(ds,{active:ne&&!i})})}),H&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ze,{children:H})}),e.jsx(ze,{children:e.jsx(us,{})})]}),e.jsx(Gi,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(ze,{children:e.jsx(nl,{})})})]})]})]}),u?e.jsx(n.Suspense,{fallback:null,children:e.jsx(xl,{open:i,onOpenChange:o})}):null]})]})]})},wl=()=>(Po(),Br(),e.jsxs(Or,{children:[e.jsx(Ro,{embeddedBackgroundWorkEnabled:!0}),e.jsx(Eo,{}),e.jsx(To,{}),e.jsx($r,{}),e.jsx(Do,{}),e.jsx(Ao,{}),e.jsx(bl,{}),e.jsx(Fr,{}),e.jsx(_o,{}),e.jsx(Mo,{})]}));function yl({apis:t}){const s=t??Gs(),[r,a]=n.useState(0);return n.useEffect(()=>Zn(i=>{if(i.runtimeKey===i.previousRuntimeKey){er();return}Lr(i),a(o=>o+1)}),[]),n.useEffect(()=>{let i=!0,o=null,u=null,l=null;return tr().then(()=>{i&&(o=vo(),u=jo(),l=So())}),()=>{i=!1,o?.(),u?.(),l?.()}},[r]),n.useEffect(()=>{s&&sr(s)},[s]),s?e.jsx(ze,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(ko,{apis:s,children:e.jsx(Co,{children:e.jsx(No,{children:e.jsx(wl,{})})},r)})})}):e.jsx(ze,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const Cn=document.getElementById("root");if(!Cn)throw new Error("Root element not found");Mn.createRoot(Cn).render(e.jsx(Fe.StrictMode,{children:e.jsx(Io,{children:e.jsx(Lo,{children:e.jsx(yl,{apis:Gs()??void 0})})})}));