@pi-chamber/web 1.0.6-rc.3 → 1.0.6-rc.5

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 (137) hide show
  1. package/dist/assets/{DiagramView-Dq5w8TCG.js → DiagramView--XO16VPB.js} +1 -1
  2. package/dist/assets/DiffView-Duy2_7Gp.js +18 -0
  3. package/dist/assets/{FileSaveConflictDialog-dFqLbFzT.js → FileSaveConflictDialog-B1DvL9zy.js} +2 -2
  4. package/dist/assets/FilesView-CjjPpE4c.js +6 -0
  5. package/dist/assets/{GitHubDetailScaffold-B2HRjT8V.js → GitHubDetailScaffold-DqxAKqCT.js} +4 -4
  6. package/dist/assets/{GitHubLinkPicker-D7I3J9_O.js → GitHubLinkPicker-ELF_chia.js} +1 -1
  7. package/dist/assets/GitHubListPrimitives-C2nGTntk.js +1 -0
  8. package/dist/assets/GitView-5fIq2nzM.js +9 -0
  9. package/dist/assets/IssuesSurface-Dq5A_bWq.js +7 -0
  10. package/dist/assets/{JsonTreeView-BJr5kBg4.js → JsonTreeView-BjFFSUwi.js} +1 -1
  11. package/dist/assets/MarkdownRendererImpl-B9Cu4TCh.js +12 -0
  12. package/dist/assets/{PatchDiff-B6RBZULC.js → PatchDiff-CTqTTcg7.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-YJJQkE7t.js → PierreDiffViewer-H2f4pJ1k.js} +15 -3
  14. package/dist/assets/PullRequestsSurface-DPpb2RW_.js +2 -0
  15. package/dist/assets/SessionSwitcherContent-B5DaBWZU.js +1 -0
  16. package/dist/assets/{SessionSwitcherDropdown-CEAid1Bd.js → SessionSwitcherDropdown-D86FaZg_.js} +2 -2
  17. package/dist/assets/SessionUnreadDot-CY9-1iV2.js +1 -0
  18. package/dist/assets/SettingsView-CiIuOi_E.js +6 -0
  19. package/dist/assets/{SettingsWindow-5dK-buUn.js → SettingsWindow-Bw1dUoJ1.js} +1 -1
  20. package/dist/assets/{StickyHorizontalScrollbar-p7EbL2-E.js → StickyHorizontalScrollbar-DNsbTLS7.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-gITobhpo.js → ToolOutputDialog-aR4kcgKL.js} +5 -5
  22. package/dist/assets/{ToolPartDiffPreview-nOJxBl-Y.js → ToolPartDiffPreview-B_wWmhtE.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-BmJk6XJm.js → VirtualizedFileDiff-BYby097w.js} +4 -4
  24. package/dist/assets/{Virtualizer-DNJrJKVb.js → Virtualizer-okhy9Aq3.js} +1 -1
  25. package/dist/assets/{collapsible-0yfy07W2.js → collapsible-Dz0bPrJ_.js} +1 -1
  26. package/dist/assets/{computeVirtualFileMetrics-BCFpa-1q.js → computeVirtualFileMetrics-8MuwxSC6.js} +1 -1
  27. package/dist/assets/{contextFileOpenGuard-BCi5nTZp.js → contextFileOpenGuard-fZ2NIQMQ.js} +1 -1
  28. package/dist/assets/fileTreeStatus-BzhMMLA9.js +7 -0
  29. package/dist/assets/gitStatusPredicates-Cyh9UhYX.js +1 -0
  30. package/dist/assets/{githubLink-CCmFsyTF.js → githubLink-D2PznPcI.js} +2 -2
  31. package/dist/assets/{index-BaeFf5Q8.js → index-BX5pAOQX.js} +1 -1
  32. package/dist/assets/index-Cs2nBW_t.js +11 -0
  33. package/dist/assets/index-tmO0fZa4.css +1 -0
  34. package/dist/assets/main-7vBNPBMb.js +137 -0
  35. package/dist/assets/{main-CgXs2e27.js → main-BI6qe8pz.js} +2 -2
  36. package/dist/assets/{markdownCore-DTNVLpYS.js → markdownCore-D5jiabKe.js} +1 -1
  37. package/dist/assets/{miniChat-CrAin_em.js → miniChat-B3up4Bnz.js} +2 -2
  38. package/dist/assets/{mobile-EK9oTupb.js → mobile-B4vLFgBc.js} +2 -2
  39. package/dist/assets/{nativeFileSave-Bhafll_7.js → nativeFileSave-DpBH1Sa3.js} +1 -1
  40. package/dist/assets/{pi-session-focus-preference-BoN1cyoG.js → pi-session-focus-preference-BrB72skF.js} +3 -3
  41. package/dist/assets/{renderDiffWithHighlighter-DixZh5Zd.js → renderDiffWithHighlighter-B6T04JGG.js} +1 -1
  42. package/dist/assets/renderElectronMiniChatApp-CX10w321.js +2 -0
  43. package/dist/assets/{renderFileWithHighlighter-s6fQq9eg.js → renderFileWithHighlighter-DtAcGyJr.js} +1 -1
  44. package/dist/assets/renderMobileApp-C9n-BhPZ.js +11 -0
  45. package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +62 -0
  46. package/dist/assets/{runtimeSurface-CJN1oo_1.js → runtimeSurface-DiP2a57a.js} +1 -1
  47. package/dist/assets/useAppFontEffects-Oyin3dgQ.js +215 -0
  48. package/dist/assets/useGitHubRemoteSearch-CZ9Hauw0.js +1 -0
  49. package/dist/assets/useSwitcherItems-BSqDA1IF.js +1 -0
  50. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js → vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-C7vVMZTg.js → vendor-base-ui-BCqPBzDj.js} +1 -1
  52. package/dist/assets/{vendor-boot-CoTxysn6.js → vendor-boot-3SaHYVb1.js} +18 -18
  53. package/dist/assets/{vendor-capacitor-app-NX6DULfp.js → vendor-capacitor-app-NbQ-WiPS.js} +1 -1
  54. package/dist/assets/{vendor-capacitor-keyboard-DJD81I9f.js → vendor-capacitor-keyboard-CgrHt8iN.js} +1 -1
  55. package/dist/assets/{vendor-capacitor-status-bar-DV24OoQV.js → vendor-capacitor-status-bar-CWt0OF5t.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-autocomplete-qsuH4Dh-.js → vendor-codemirror-autocomplete-WThuuUAz.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-ZHWyBf7j.js → vendor-codemirror-lang-angular-BbLGCxF6.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-cpp-pCTOmv-k.js → vendor-codemirror-lang-cpp-Cceks-9O.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-css-2bFuyM70.js → vendor-codemirror-lang-css-D1wpUg3Z.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-go-DrG_c7D7.js → vendor-codemirror-lang-go-Cv0zXHHM.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-html-BV8lrR8v.js → vendor-codemirror-lang-html-DbL8oT9H.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-java-DrsvH6T2.js → vendor-codemirror-lang-java-CNugenuC.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-javascript-Dkzl3s07.js → vendor-codemirror-lang-javascript-Bx_FIyZF.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-jinja-8Nn3bnoP.js → vendor-codemirror-lang-jinja-DDGjB3Zq.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-json-CsdmtHhi.js → vendor-codemirror-lang-json-DIvqf9Pb.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-less-DJuZ4cZe.js → vendor-codemirror-lang-less-D8r9dGG1.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-liquid-D2RO-Pzr.js → vendor-codemirror-lang-liquid-B24mguYi.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-markdown-C0Zu3b3n.js → vendor-codemirror-lang-markdown-v3yG2sbf.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-php-CuDtt2Zj.js → vendor-codemirror-lang-php-BcZGalqy.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-python-Cv2exx_M.js → vendor-codemirror-lang-python-b-JqEwQy.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-rust-C4TxJ6Rg.js → vendor-codemirror-lang-rust-B1uZxDW-.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sass-BmtPz8kf.js → vendor-codemirror-lang-sass-DqPrngKp.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-sql-BF1ZaXqJ.js → vendor-codemirror-lang-sql-UyCnpt-k.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-vue-DZgXrP2k.js → vendor-codemirror-lang-vue-xDwYkovV.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-wast-DsnaGtL_.js → vendor-codemirror-lang-wast-CF3169p_.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-xml-D8DzzFat.js → vendor-codemirror-lang-xml-FCtVhuOb.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-yaml-D5hBv7m6.js → vendor-codemirror-lang-yaml-g0sPmAnv.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-language-data-vn2RyN9T.js → vendor-codemirror-language-data-B03xgzP2.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-search-BVCYIV0D.js → vendor-codemirror-search-Dw3Wpu15.js} +1 -1
  80. package/dist/assets/{vendor-lezer-cpp-vqXSn3lv.js → vendor-lezer-cpp-Cu3E-KUI.js} +1 -1
  81. package/dist/assets/{vendor-lezer-css-JnEzSyZR.js → vendor-lezer-css-Cb8vp67u.js} +1 -1
  82. package/dist/assets/{vendor-lezer-go-dD2gQMIL.js → vendor-lezer-go-BTsIaOm7.js} +1 -1
  83. package/dist/assets/{vendor-lezer-html-Cr3U-1pu.js → vendor-lezer-html-UQMsUwj-.js} +1 -1
  84. package/dist/assets/{vendor-lezer-java-CRM0IMCo.js → vendor-lezer-java-BIWrFrAx.js} +1 -1
  85. package/dist/assets/{vendor-lezer-javascript-B3s21DIS.js → vendor-lezer-javascript-BH2Etgoy.js} +1 -1
  86. package/dist/assets/{vendor-lezer-json-DPFM6EBV.js → vendor-lezer-json-CE-QUCwM.js} +1 -1
  87. package/dist/assets/{vendor-lezer-lr-Bllrq8hY.js → vendor-lezer-lr-HY6Yc0Vr.js} +1 -1
  88. package/dist/assets/{vendor-lezer-markdown-6-3PLvXG.js → vendor-lezer-markdown-xFL3Evwf.js} +1 -1
  89. package/dist/assets/{vendor-lezer-php-DOyzfHRl.js → vendor-lezer-php-Cr_mQGrG.js} +1 -1
  90. package/dist/assets/{vendor-lezer-python-CdHdN5qt.js → vendor-lezer-python-BNRFWCb0.js} +1 -1
  91. package/dist/assets/{vendor-lezer-rust-CqnW8EMH.js → vendor-lezer-rust-BvfOK5cU.js} +1 -1
  92. package/dist/assets/{vendor-lezer-sass-BbcF4y6A.js → vendor-lezer-sass-qoxiLisk.js} +1 -1
  93. package/dist/assets/{vendor-lezer-xml-C31AyWoo.js → vendor-lezer-xml--x8SSpqU.js} +1 -1
  94. package/dist/assets/{vendor-lezer-yaml-Cv908yC2.js → vendor-lezer-yaml-BDo1JaEr.js} +1 -1
  95. package/dist/assets/{vendor-replit-codemirror-vim-Cwhyn_5f.js → vendor-replit-codemirror-vim-D1Fe7FiY.js} +1 -1
  96. package/dist/assets/{web-components-Bz5oGa3p.js → web-components-CkTNGkJ2.js} +4 -4
  97. package/dist/index.html +4 -4
  98. package/dist/mini-chat.html +3 -3
  99. package/dist/mobile.html +3 -3
  100. package/package.json +1 -1
  101. package/server/lib/git/DOCUMENTATION.md +1 -0
  102. package/server/lib/git/routes.js +14 -0
  103. package/server/lib/git/routes.test.js +37 -0
  104. package/server/lib/git/service.js +27 -0
  105. package/server/lib/git/service.test.js +32 -0
  106. package/server/lib/pi/archive-store.js +38 -10
  107. package/server/lib/pi/archive-store.test.js +10 -0
  108. package/server/lib/pi/routes.js +107 -2
  109. package/server/lib/pi/routes.test.js +255 -0
  110. package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -1
  111. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +18 -0
  112. package/server/lib/pi/session-daemon/session-daemon.js +24 -1
  113. package/server/lib/pi/session-shelf-store.js +252 -0
  114. package/server/lib/pi/session-shelf-store.test.js +174 -0
  115. package/server/lib/pi/ui-settings-store.js +60 -0
  116. package/server/lib/pi/ui-settings-store.test.js +105 -6
  117. package/dist/assets/DiffView-CFIjN2zy.js +0 -18
  118. package/dist/assets/FilesView-D0b2mEKA.js +0 -6
  119. package/dist/assets/GitHubListPrimitives-Dw5LAmzm.js +0 -1
  120. package/dist/assets/GitView-Dhr7qVeI.js +0 -9
  121. package/dist/assets/IssuesSurface-Bya7OsRl.js +0 -7
  122. package/dist/assets/MarkdownRendererImpl-DadkFPCz.js +0 -12
  123. package/dist/assets/PullRequestsSurface-D8JpzP5l.js +0 -2
  124. package/dist/assets/SessionSwitcherContent-CJ6C2ZKG.js +0 -1
  125. package/dist/assets/SessionUnreadDot-I1_tmqY9.js +0 -1
  126. package/dist/assets/SettingsView-B-b76XDV.js +0 -6
  127. package/dist/assets/gitStatusPredicates-BQOqDJU1.js +0 -1
  128. package/dist/assets/index-C2ISrmRR.js +0 -11
  129. package/dist/assets/index-DgwThEwf.css +0 -1
  130. package/dist/assets/main-DoVzQV56.js +0 -137
  131. package/dist/assets/renderElectronMiniChatApp-0MqKeGfI.js +0 -2
  132. package/dist/assets/renderMobileApp-BLoXL_J8.js +0 -11
  133. package/dist/assets/runtimeEndpointReset-Bv2Y1fMm.js +0 -62
  134. package/dist/assets/useAppFontEffects-D2xXdmYC.js +0 -215
  135. package/dist/assets/useFilesViewSearch-BKotcAUN.js +0 -7
  136. package/dist/assets/useGitHubRemoteSearch-CZ92xKSw.js +0 -1
  137. package/dist/assets/useSwitcherItems-BfA4omGb.js +0 -1
@@ -1,137 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-CFIjN2zy.js","assets/vendor-boot-CoTxysn6.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-clsx-B-dksMZM.js","assets/index-C2ISrmRR.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-DgwThEwf.css","assets/useAppFontEffects-D2xXdmYC.js","assets/runtimeSurface-CJN1oo_1.js","assets/nativeFileSave-Bhafll_7.js","assets/gitStatusPredicates-BQOqDJU1.js","assets/VirtualizedFileDiff-BmJk6XJm.js","assets/web-components-Bz5oGa3p.js","assets/computeVirtualFileMetrics-BCFpa-1q.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-DixZh5Zd.js","assets/vendor-diff-C3JhlQdm.js","assets/PierreDiffViewer-YJJQkE7t.js","assets/StickyHorizontalScrollbar-p7EbL2-E.js","assets/runtimeEndpointReset-Bv2Y1fMm.js","assets/SessionUnreadDot-I1_tmqY9.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-BCi5nTZp.js","assets/FilesView-D0b2mEKA.js","assets/vendor-codemirror-lang-javascript-Dkzl3s07.js","assets/vendor-lezer-javascript-B3s21DIS.js","assets/vendor-lezer-lr-Bllrq8hY.js","assets/vendor-codemirror-autocomplete-qsuH4Dh-.js","assets/vendor-codemirror-lang-json-CsdmtHhi.js","assets/vendor-lezer-json-DPFM6EBV.js","assets/vendor-codemirror-lang-css-2bFuyM70.js","assets/vendor-lezer-css-JnEzSyZR.js","assets/vendor-codemirror-lang-html-BV8lrR8v.js","assets/vendor-lezer-html-Cr3U-1pu.js","assets/vendor-codemirror-lang-markdown-C0Zu3b3n.js","assets/vendor-lezer-markdown-6-3PLvXG.js","assets/vendor-codemirror-language-data-vn2RyN9T.js","assets/vendor-codemirror-lang-python-Cv2exx_M.js","assets/vendor-lezer-python-CdHdN5qt.js","assets/shell-CjFT_Tl9.js","assets/FileSaveConflictDialog-dFqLbFzT.js","assets/vendor-react-drawio-IYnLUY5N.js","assets/useFilesViewSearch-BKotcAUN.js","assets/JsonTreeView-BJr5kBg4.js","assets/Virtualizer-DNJrJKVb.js","assets/renderFileWithHighlighter-s6fQq9eg.js","assets/vendor-codemirror-search-BVCYIV0D.js","assets/vendor-replit-codemirror-vim-Cwhyn_5f.js","assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js","assets/GitView-Dhr7qVeI.js","assets/GitHubDetailScaffold-B2HRjT8V.js","assets/vendor-dompurify-BGCr_sdL.js","assets/collapsible-0yfy07W2.js","assets/vendor-base-ui-C7vVMZTg.js","assets/PullRequestsSurface-D8JpzP5l.js","assets/useGitHubRemoteSearch-CZ92xKSw.js","assets/GitHubListPrimitives-Dw5LAmzm.js","assets/IssuesSurface-Bya7OsRl.js","assets/githubLink-CCmFsyTF.js","assets/DiagramView-Dq5w8TCG.js","assets/SettingsView-B-b76XDV.js","assets/vendor-qrcode-gzL9QFkg.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js","assets/SettingsWindow-5dK-buUn.js"])))=>i.map(i=>d[i]);
2
- import{aZ as vn,a_ as Pt,a$ as os,j as e,b0 as jn,b1 as Sn,bd as kn,cd as as,b2 as is,bh as Cn,bi as Nn,bf as ls,bg as cs,c0 as ds,be as us,ce as Vt,cb as ut,aQ as Kt,aR as hs}from"./vendor-boot-CoTxysn6.js";import{R as s,a as Te}from"./vendor-react-Bz1tRBxM.js";/* empty css */import{h as Q,f as ce,z as Rt,aP as fs,a0 as Pn,cx as ps,b as ms,a as Rn,a9 as gs,_ as xs,cy as ws,n as Le,bM as bs,at as $e,G as ys,M as vs,j as En,O as js,bq as Ss,br as ks,cz as Xt,cA as st,u as Cs,ar as Ns,$ as Ps,bh as Rs,V as Tn,W as Dn,bN as Es,cB as Ts,cC as Ds,o as As,ao as Ms,p as _s,v as An,m as Is}from"./index-C2ISrmRR.js";import{_ as Me}from"./vendor-vite-runtime-DD1OZmLC.js";import{l as Ls,an as qt,ao as Os,ap as Bs,aq as $s,ar as Fs,as as Ws,at as zs,au as et,av as Hs,aw as Us,ax as Vs,ay as Ks,az as Xs,aA as qs,aB as Ys,aC as Gs,aD as Js,aE as Mn,aF as Qs,aG as Zs,aH as er,aI as tr,aJ as nr,aK as sr,aL as _n,aM as In,aN as Et,T as Ln,aO as rr,am as or,ak as ar,m as ir,w as lr,t as cr,v as dr,H as Yt,C as Gt,A as Jt,S as Qt,n as ur,p as hr,q as fr,F as pr,O as mr,W as gr}from"./runtimeEndpointReset-Bv2Y1fMm.js";import{as as gt,I as K,E as Ae,bY as it,B as oe,ah as lt,t as he,P as _t,h as Pe,o as Ge,cE as bt,cF as xr,cG as It,a$ as wr,aQ as Ve,aR as Ke,b0 as br,aS as Xe,b1 as yr,bu as vr,bK as jr,z as Lt,y as ct,cH as On,at as Zt,aO as Sr,av as Ot,aw as Bt,ax as $t,ay as Ft,az as Wt,aA as kr,bL as Cr,cI as Nr,cJ as Pr,b9 as Bn,O as He,cK as rt,v as $n,cL as Rr,cj as Er,cM as Be,bw as Fn,cN as Tr,cO as Dr,cP as zt,cQ as Ar,bh as Wn,A as en,ba as Mr,aH as _r,cR as Ir,cS as Lr,bb as tn,b8 as Or,b as Br,c as $r,bo as Fr,a as nn,bC as Wr,r as yt,aB as zr,bH as Hr,bD as Ur,cT as Vr,cU as Kr,cV as Xr,cW as qr,cX as tt,cY as nt,cZ as Yr,bs as Gr,ac as Jr,ad as Qr,ae as Zr,$ as eo,_ as to,a4 as no,Y as so,a5 as ro,a0 as oo,a1 as ao,a2 as io,a3 as lo,a6 as co,a7 as uo,aa as ho,ab as fo}from"./useAppFontEffects-D2xXdmYC.js";import{v as zn,g as Hn}from"./contextFileOpenGuard-BCi5nTZp.js";import{g as Un,u as po,s as mo,i as go,a as xo,b as wo}from"./useFilesViewSearch-BKotcAUN.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"./SessionUnreadDot-I1_tmqY9.js";/* empty css */import"./nativeFileSave-Bhafll_7.js";import"./permissionStore-zIpxq9Pq.js";import"./runtimeSurface-CJN1oo_1.js";const bo=280,sn=4,yo=({transform:t})=>({...t,y:0}),vo=({id:t,children:n,className:r})=>{const{attributes:i,listeners:o,setNodeRef:c,transform:h,transition:l,isDragging:u}=Cn({id:t});return e.jsx("div",{ref:c,"data-sortable-tab-id":t,style:{transform:Nn.Transform.toString(h),transition:l},className:ce("h-full rounded-md",r,u&&"opacity-50"),...i,...o,children:n})},jo=({id:t,children:n,className:r})=>e.jsx("div",{className:ce("h-full",r),"data-sortable-tab-id":t,children:n}),Vn=({items:t,activeId:n,onSelect:r,onClose:i,onReorder:o,layoutMode:c="scrollable",variant:h="default",activePillInsetClassName:l,activePillButtonClassName:u,inactiveTabsIconOnly:m=!1,animateActivePill:x,activePillLowercase:b=!0,nonCompositedIndicator:d=!1,className:g})=>{const f=Q(D=>D.isMobile),{isTablet:_}=gt(),w=f||_,S=s.useRef(null),[T,V]=s.useState({left:!1,right:!1}),v=s.useMemo(()=>t.map(D=>D.id),[t]),E=c==="scrollable",M=h==="default",F=h==="active-pill",P=F||h==="animated",ee=M,G=P||ee,X=F&&E,J=P,ne=x??P,z=typeof o=="function",se=z?vo:jo,k=s.useRef(new Map),[O,re]=s.useState(null),[R,I]=s.useState(!1),[Z,ae]=s.useState(null),le=s.useRef(!1),fe=s.useRef(0),ge=s.useRef(n),de=s.useRef(null),ue=s.useMemo(()=>{if(!G||!Z||!n||Z===n)return 0;const D=t.findIndex(ie=>ie.id===Z),q=t.findIndex(ie=>ie.id===n);return D<0||q<0?0:D>q?sn:-sn},[n,t,Z,G]),be=vn(Pt(os,{activationConstraint:{distance:8}})),pe=s.useCallback((D,q)=>!D||!q?D===q:Math.abs(D.left-q.left)<.5&&Math.abs(D.top-q.top)<.5&&Math.abs(D.width-q.width)<.5&&Math.abs(D.height-q.height)<.5,[]),me=s.useCallback((D,q)=>{if(q){k.current.set(D,q);return}k.current.delete(D)},[]),xe=s.useCallback(()=>{if(!G||!n){re(H=>H===null?H:null);return}const D=S.current,q=k.current.get(n);if(!D||!q){re(H=>H===null?H:null);return}let ie=0,A=0,j=q;for(;j&&j!==D;)ie+=j.offsetLeft,A+=j.offsetTop,j=j.offsetParent;const L={left:ie,top:A,width:q.offsetWidth,height:q.offsetHeight};re(H=>pe(H,L)?H:L)},[n,pe,G]),ye=s.useCallback(()=>{if(!E){V({left:!1,right:!1});return}const D=S.current;if(!D){V({left:!1,right:!1});return}V({left:D.scrollLeft>2,right:D.scrollLeft+D.clientWidth<D.scrollWidth-2})},[E]);s.useEffect(()=>{if(!E){V({left:!1,right:!1});return}const D=S.current;if(!D)return;ye(),D.addEventListener("scroll",ye,{passive:!0});const q=new ResizeObserver(ye);return q.observe(D),()=>{D.removeEventListener("scroll",ye),q.disconnect()}},[E,t.length,ye]),s.useEffect(()=>{if(!E)return;const D=S.current;if(!D)return;const q=ie=>{if(ie.ctrlKey||Math.abs(ie.deltaY)<=Math.abs(ie.deltaX))return;const A=D.scrollWidth-D.clientWidth;if(A<=0)return;const j=ie.deltaMode===WheelEvent.DOM_DELTA_LINE?ie.deltaY*16:ie.deltaMode===WheelEvent.DOM_DELTA_PAGE?ie.deltaY*D.clientWidth:ie.deltaY;ie.preventDefault(),D.scrollLeft=Math.min(A,Math.max(0,D.scrollLeft+j))};return D.addEventListener("wheel",q,{passive:!1}),()=>{D.removeEventListener("wheel",q)}},[E]),s.useEffect(()=>{if(!G){re(null);return}xe();const D=S.current;if(!D)return;const q=new ResizeObserver(()=>{performance.now()-fe.current>bo&&I(!1),xe()});if(q.observe(D),n){const ie=k.current.get(n);ie&&q.observe(ie)}return()=>{q.disconnect()}},[n,t.length,xe,G]),s.useLayoutEffect(()=>{xe()});const ve=v.join("\0");s.useLayoutEffect(()=>{if(!G){le.current=!1,I(!1);return}const D=de.current!==ve;if(de.current=ve,!le.current){le.current=!0,ge.current=n;return}const q=ge.current!==n;if(ge.current=n,!q||D){I(!1);return}fe.current=performance.now(),I(!0)},[n,ve,G]),s.useEffect(()=>{if(!E||!n)return;const D=S.current;if(!D)return;const q=window.requestAnimationFrame(()=>{const ie=typeof window.CSS?.escape=="function"?window.CSS.escape(n):n.replace(/"/g,'\\"'),A=D.querySelector(`[data-sortable-tab-id="${ie}"]`);A&&(A.scrollIntoView({block:"nearest",inline:"nearest"}),ye())});return()=>{window.cancelAnimationFrame(q)}},[n,E,t.length,ye]);const Re=s.useCallback(D=>{if(!o)return;const{active:q,over:ie}=D;!ie||q.id===ie.id||o(String(q.id),String(ie.id))},[o]),ke=e.jsxs("div",{className:ce("relative flex h-full min-w-0 flex-1",g),children:[E&&T.left?e.jsx("div",{className:ce("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",P?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,E&&T.right?e.jsx("div",{className:ce("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",P?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e.jsxs("div",{ref:S,className:ce("relative flex h-full min-w-0 flex-1",P?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",P&&"@container/pill-tabs",P&&"pill-tabs__track",P&&(l??"gap-0.5 py-0.5"),ee&&"items-center overflow-y-hidden",J&&"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:[P&&O?e.jsx("div",{className:ce("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)]",ne&&R&&(d?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:d?{left:`${O.left+ue}px`,top:`${O.top}px`,width:`${O.width}px`,height:`${O.height}px`}:{transform:`translate3d(${O.left+ue}px, ${O.top}px, 0)`,width:`${O.width}px`,height:`${O.height}px`}}):null,ee&&O?e.jsx("div",{className:ce("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",R&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${O.left+ue}px, 0, 0)`,width:`${O.width}px`},"aria-hidden":!0}):null,t.map(D=>{const q=D.id===n,ie=m&&P&&!q&&!!D.icon,A=!ie,j=!!D.icon,L=m&&P&&q&&!E&&!X,H=D.closable!==!1&&!!i,B=H&&!!D.icon,a=E||X?void 0:P?L?"flex-none basis-auto":f?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",p=H?Y=>{Y.button===1&&(Y.preventDefault(),Y.stopPropagation(),i?.(D.id))}:void 0,$=H?Y=>{Y.button===1&&Y.preventDefault()}:void 0,W=Y=>j?e.jsxs("span",{className:Y,children:[e.jsx("span",{className:ce("flex items-center justify-center transition-opacity",B&&(w?"opacity-0":"group-hover:opacity-0")),children:D.icon}),B?e.jsx("span",{role:"button",tabIndex:-1,className:ce("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",w?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:te=>te.stopPropagation(),onClick:te=>{te.stopPropagation(),i?.(D.id)},"aria-label":D.closeLabel??`Close ${D.label} tab`,title:D.closeLabel??`Close ${D.label} tab`,children:e.jsx(K,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return e.jsx(se,{id:D.id,className:a,children:e.jsxs("div",{ref:Y=>me(D.id,Y),onAuxClick:p,onMouseDown:$,className:ce("group flex h-full min-w-0 flex-nowrap items-center",E||X?"shrink-0":P?"w-full":"w-full min-w-0",P?"relative z-10 bg-transparent":q?"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":q,"aria-label":ie?D.title??D.label:void 0,onClick:()=>r(D.id),onPointerDown:G?()=>{I(!0),ae(D.id)}:void 0,onPointerUp:G?()=>ae(null):void 0,onPointerLeave:G?()=>ae(null):void 0,onPointerCancel:G?()=>ae(null):void 0,className:ce(P?"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",P&&b?"lowercase":null,P&&(ie?"gap-0":"gap-1.5"),P?X?"shrink-0 whitespace-nowrap px-3 text-center":E?"max-w-56 shrink-0 px-3 text-center":ie?"px-2 !min-w-0 text-center":L?"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",P?u??(F?f?"h-[38px]":"h-[31px]":"h-7"):null,P?q?"text-foreground":"text-muted-foreground hover:text-foreground":null,P?"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:D.title??D.label,children:P?e.jsxs(e.Fragment,{children:[W("relative flex h-4 w-4 shrink-0 items-center justify-center"),A?e.jsx("span",{className:"animated-tabs__label truncate",children:D.label}):null]}):e.jsxs("span",{className:ce("flex min-w-0 flex-nowrap items-center gap-1.5",!E&&"justify-center"),children:[W(ce("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",q?"text-[var(--primary-base)]":"text-muted-foreground")),e.jsx("span",{className:"truncate leading-[1.2]",children:D.label})]})}),H&&!B?e.jsx("button",{type:"button",onPointerDown:Y=>{Y.stopPropagation()},onClick:Y=>{Y.stopPropagation(),i?.(D.id)},className:ce("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",P?"-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",P?q?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":q?"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":D.closeLabel??`Close ${D.label} tab`,title:D.closeLabel??`Close ${D.label} tab`,children:e.jsx(K,{name:"close",className:"h-3 w-3"})}):null]})},D.id)})]})]});return z?e.jsxs(jn,{sensors:be,collisionDetection:Sn,onDragEnd:Re,modifiers:[yo],children:[e.jsx(kn,{items:v,strategy:as,children:ke}),e.jsx(is,{dropAnimation:null})]}):ke},rn=280,on=280,an=500,So=({isOpen:t,isMobile:n,children:r,className:i,topBar:o})=>{const c=Q(y=>y.sidebarWidth),h=Q(y=>y.setSidebarWidth),[l,u]=s.useState(!1),m=s.useRef(0),x=s.useRef(c||rn),b=s.useRef(null),d=s.useRef(null),g=s.useRef(null),f=s.useCallback(y=>Math.min(an,Math.max(on,y)),[]),_=s.useCallback(y=>{const P=g.current;P&&(P.style.width=`${y}px`,P.style.minWidth=`${y}px`,P.style.maxWidth=`${y}px`,P.style.setProperty("--oc-left-sidebar-width",`${y}px`))},[]);s.useEffect(()=>{n&&l&&u(!1)},[n,l]),s.useEffect(()=>{l||(b.current=null,d.current=null)},[l]);const w=Ls(t);if(n)return null;const S=Math.min(an,Math.max(on,c||rn)),T=w.layoutVisible?S:0,V=y=>{if(t){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}d.current=y.pointerId,u(!0),m.current=y.clientX,x.current=T,b.current=T,_(T),y.preventDefault()}},v=y=>{if(n||!l||d.current!==y.pointerId)return;const P=y.clientX-m.current,ee=f(x.current+P);b.current!==ee&&(b.current=ee,_(ee))},E=y=>{if(d.current!==y.pointerId||n)return;try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}const P=f(b.current??T);d.current=null,b.current=null,u(!1),h(P)},M=l?b.current??T:T,F=l?M:T;return e.jsxs("aside",{ref:g,className:ce("relative flex h-full overflow-hidden motion-reduce:transition-none","bg-sidebar",i),style:{width:`${F}px`,minWidth:`${F}px`,maxWidth:`${F}px`,"--oc-left-sidebar-width":`${l?M:S}px`,overflowX:"clip",transform:l||w.slidIn?"translateX(0)":"translateX(-100%)",transition:l?"none":w.transition},"aria-hidden":!t||F===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:ce("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:V,onPointerMove:v,onPointerUp:E,onPointerCancel:E,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:ce("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:[o,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(Ae,{children:r})})]})]})},ko=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},ln=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Je=t=>{if(!t||typeof t!="object")return!1;const n=t,r=n.bounds;return typeof n.tag=="string"&&typeof n.text=="string"&&typeof n.selector=="string"&&typeof n.path=="string"&&!!r&&typeof r?.x=="number"&&typeof r?.y=="number"&&typeof r?.width=="number"&&typeof r?.height=="number"&&ko(n.center)&&ln(n.attributes)&&ln(n.computedStyle)&&Array.isArray(n.ancestry)},xt=({pageUrl:t,viewport:n,devicePixelRatio:r,target:i,screenshotAttached:o,intro:c})=>{const h=i.text.trim(),l=Object.entries(i.attributes).map(([g,f])=>`${g}="${f}"`).join(" "),u=i.computedStyle,m=i.bounds,x=i.center,b=c.replace(/[.:]+$/g,""),d=i.ancestry.map(g=>g.selectorPart).join(" > ");return[`${b}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${r}`,`Screenshot: ${o?"attached":"not attached"}`,`Element: ${i.tag}`,h?`Text: ${h}`:null,`- Selector: ${i.selector}`,`- Path: ${i.path}`,d?`- Ancestry: ${d}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(m.x)}, y=${Math.round(m.y)}, width=${Math.round(m.width)}, height=${Math.round(m.height)}`,`- Center: x=${Math.round(x.x)}, y=${Math.round(x.y)}`,`Styles: display=${u.display}; position=${u.position}; font=${u.fontWeight} ${u.fontSize} / ${u.lineHeight} ${u.fontFamily}; color=${u.color}; background=${u.backgroundColor}; z-index=${u.zIndex}`].filter(g=>typeof g=="string").join(`
3
- `)},Oe=new Map,Co=3e4,Kn=t=>{const n=Oe.get(t);return n?n.expiresAt-Date.now()<=Co?(Oe.delete(t),null):n:null},Ye="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",vt=new Map;function Xn(t){const n="#ffffff",r=t.defaultView??window;try{const i=t.body?r.getComputedStyle(t.body).backgroundColor:"";if(i&&i!=="rgba(0, 0, 0, 0)"&&i!=="transparent")return i;const o=r.getComputedStyle(t.documentElement).backgroundColor;if(o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent")return o}catch{}return n}const qn=t=>new Promise((n,r)=>{const i=new FileReader;i.onloadend=()=>n(typeof i.result=="string"?i.result:Ye),i.onerror=()=>r(i.error??new Error("Failed to read image blob")),i.readAsDataURL(t)}),No=async(t,n=.82)=>{const r=await new Promise(i=>t.toBlob(i,"image/jpeg",n));return r&&(await qn(r)).split(",",2)[1]||""},jt=async(t,n)=>{try{const r=await fetch(t,{credentials:n});return r.ok?await qn(await r.blob()):null}catch{return null}},Po=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,r=Kn(n);if(r)return`${r.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const i=vt.get(n),o=i??(async()=>{try{const h=await Rt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!h.ok)return Oe.delete(n),null;const l=await h.json(),u=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",m=typeof l.expiresAt=="number"?l.expiresAt:0;if(!u)return Oe.delete(n),null;const x={proxyBasePath:u,expiresAt:m};return Oe.set(n,x),x}catch{return Oe.delete(n),null}finally{vt.delete(n)}})();i||vt.set(n,o);const c=await o;return c?`${c.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},Yn=async(t,n)=>{if(!t||t.startsWith("data:"))return t;try{const r=new URL(t,n.baseURI);if(r.origin===window.location.origin||r.protocol!=="http:"&&r.protocol!=="https:")return await jt(r.toString(),"include")??Ye;const i=await Po(r),o=i?await jt(i,"include"):null;return o||(await jt(r.toString(),"omit")??Ye)}catch{return Ye}},Ro=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const r=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let i=t;for(const o of r){const c=o[2]||"";if(!c||c.startsWith("data:"))continue;const h=await Yn(c,n);i=i.replace(o[0],`url("${h}")`)}return i},cn=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),Gn=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},Eo=t=>{const n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;const r=Number.parseFloat(t.fontSize);return Number.isFinite(r)&&r>0?r*1.2:16},To=(t,n,r)=>{const i=[],o=t.defaultView??window,h=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of h){const u=l.textContent?.replace(/\s+/g," ").trim()??"";if(!u||!u.includes(" "))continue;const m=l.getBoundingClientRect();if(m.width<=0||m.height<=0||m.right<0||m.bottom<0||m.left>n||m.top>r)continue;const x=o.getComputedStyle(l);if(x.display==="none"||x.visibility==="hidden"||Number(x.opacity)===0)continue;const b=x.getPropertyValue("text-wrap"),d=x.getPropertyValue("text-wrap-mode"),g=x.whiteSpace.includes("nowrap")||b==="nowrap"||d==="nowrap",f=m.height<=Eo(x)*1.7;!g&&(!f||m.width>n*.72)||(i.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=i.length-1;l>=0;l-=1)i[l]?.()}},Do=(t,n,r,i)=>{const o=[],c=t.defaultView??window,h=c.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=c.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,u=Array.from(t.querySelectorAll("*")).filter(m=>{const x=c.getComputedStyle(m);if(x.position!=="fixed"||x.display==="none"||x.visibility==="hidden"||Number(x.opacity)===0)return!1;const b=m.getBoundingClientRect();return b.width>0&&b.height>0&&b.right>=0&&b.bottom>=0&&b.left<=n&&b.top<=r}).filter((m,x,b)=>!b.some((d,g)=>g<x&&d.contains(m)));for(const m of u){const x=m.getBoundingClientRect(),b=c.getComputedStyle(m),d=Math.ceil(x.width)+8,g=Math.ceil(x.height)+2;i?.add(m),o.push(Gn(m)),m.style.position="absolute",m.style.top=`${x.top+l}px`,m.style.left=`${x.left+h}px`,m.style.right="auto",m.style.bottom="auto",m.style.width=`${d}px`,m.style.minWidth=`${d}px`,m.style.height=`${g}px`,m.style.minHeight=`${g}px`,m.style.margin="0",m.style.boxSizing="border-box",m.style.transform="none",b.zIndex!=="auto"&&(m.style.zIndex=b.zIndex)}return()=>{for(let m=o.length-1;m>=0;m-=1)o[m]?.()}},Jn=async(t,n,r,i={})=>{const o=[],c=t.defaultView??window,h=b=>{if(b===t.documentElement||b===t.body)return!0;try{const d=b.getBoundingClientRect();return d.width>0&&d.height>0&&d.right>=0&&d.bottom>=0&&d.left<=n&&d.top<=r}catch{return!1}};if(i.applyLayoutWorkarounds){const b=new WeakSet;o.push(Do(t,n,r,b)),o.push(To(t,n,r))}const l=new Map;for(const b of Array.from(t.images))l.set(b,b.currentSrc||b.src||b.getAttribute("src")||"");const u=Array.from(t.querySelectorAll("picture"));for(const b of u){const d=Array.from(b.querySelectorAll("source"));if(d.length===0)continue;const g=d.map(f=>({source:f,srcset:f.getAttribute("srcset"),sizes:f.getAttribute("sizes")}));o.push(()=>{for(const f of g)f.srcset===null?f.source.removeAttribute("srcset"):f.source.setAttribute("srcset",f.srcset),f.sizes===null?f.source.removeAttribute("sizes"):f.source.setAttribute("sizes",f.sizes)});for(const f of d)f.removeAttribute("srcset"),f.removeAttribute("sizes")}const m=Array.from(t.images).filter(b=>h(b));await Promise.all(m.map(async b=>{const d=l.get(b)||b.currentSrc||b.src||b.getAttribute("src")||"";if(!d)return;await cn(b);const g=await Yn(d,t),f={src:b.getAttribute("src"),srcset:b.getAttribute("srcset"),sizes:b.getAttribute("sizes")};o.push(()=>{f.src===null?b.removeAttribute("src"):b.setAttribute("src",f.src),f.srcset===null?b.removeAttribute("srcset"):b.setAttribute("srcset",f.srcset),f.sizes===null?b.removeAttribute("sizes"):b.setAttribute("sizes",f.sizes)}),b.removeAttribute("srcset"),b.removeAttribute("sizes"),b.setAttribute("src",g||Ye),await cn(b)}));const x=Array.from(t.querySelectorAll("*")).filter(h);return await Promise.all(x.map(async b=>{const d=c.getComputedStyle(b).backgroundImage;if(!d||d==="none"||!d.includes("url("))return;const g=await Ro(d,t);if(g===d)return;const f=b.style.backgroundImage;o.push(()=>{b.style.backgroundImage=f}),b.style.backgroundImage=g})),()=>{for(let b=o.length-1;b>=0;b-=1)try{o[b]?.()}catch{}}},Ao=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},ft=(...t)=>{Ao()&&console.info("[preview-capture]",...t)},Qn=(t,n=8)=>{const r=[];try{const i=t.querySelectorAll("*");for(const o of i){const c=o.scrollTop||0,h=o.scrollLeft||0;if(c<=0&&h<=0)continue;const l=o.tagName.toLowerCase(),u=o.id?`#${o.id}`:"",m=typeof o.className=="string"&&o.className?`.${o.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(r.push({selector:`${l}${u}${m}`,scrollTop:c,scrollLeft:h,clientWidth:o.clientWidth,clientHeight:o.clientHeight,scrollWidth:o.scrollWidth,scrollHeight:o.scrollHeight}),r.length>=n)break}}catch{}return r},ot="data-oc-fixed-pin",Mo=(t,n,r)=>{if(n<=0&&r<=0)return()=>{};const i=t.defaultView;if(!i)return()=>{};const o=[],c=[];try{for(const h of t.querySelectorAll("*")){if(i.getComputedStyle(h).position!=="fixed")continue;const l=h.getBoundingClientRect();if(!(l.width>0&&l.height>0))continue;h.setAttribute(ot,JSON.stringify({top:l.top+r,left:l.left+n,width:l.width,height:l.height})),o.push(h);const u=h.tagName.toLowerCase(),m=typeof h.className=="string"&&h.className?`.${h.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";c.push({selector:`${u}${m}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return ft("tagged fixed elements",c),()=>{for(const h of o)try{h.removeAttribute(ot)}catch{}}},_o={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const r of n.querySelectorAll(`[${ot}]`)){let i;try{i=JSON.parse(r.getAttribute(ot)||"")}catch{continue}r.style.setProperty("position","absolute","important"),r.style.setProperty("top",`${i.top}px`,"important"),r.style.setProperty("left",`${i.left}px`,"important"),r.style.setProperty("right","auto","important"),r.style.setProperty("bottom","auto","important"),r.style.setProperty("width",`${i.width}px`,"important"),r.style.setProperty("height",`${i.height}px`,"important"),r.removeAttribute(ot)}}},qe="data-oc-scroll-pin",Io=t=>{const n=[],r=Qn(t,64);try{const c=t.documentElement,h=t.body;for(const l of t.querySelectorAll("*")){const u=l.scrollTop||0,m=l.scrollLeft||0;if(u<=0&&m<=0)continue;const x=l!==c&&l!==h;x&&l.setAttribute(qe,JSON.stringify({top:u,left:m})),n.push({el:l,top:u,left:m,tagged:x})}}catch{}return{reapply:()=>{for(const c of n)try{c.el.scrollHeight,c.el.scrollTop!==c.top&&(c.el.scrollTop=c.top),c.el.scrollLeft!==c.left&&(c.el.scrollLeft=c.left)}catch{}},cleanup:()=>{for(const c of n)if(c.tagged)try{c.el.removeAttribute(qe)}catch{}},snapshot:r}},Lo={name:"oc-nested-scroll",afterClone(t){const n=t?.clone;if(!n||typeof n.querySelectorAll!="function")return;const r=n.ownerDocument;if(r)for(const i of n.querySelectorAll(`[${qe}]`)){let o;try{o=JSON.parse(i.getAttribute(qe)||"")}catch{i.removeAttribute(qe);continue}const c=`translate(${-o.left}px, ${-o.top}px)`,h=i.children.length===1&&i.firstElementChild instanceof HTMLElement&&i.firstElementChild.style.willChange==="transform"?i.firstElementChild:null;if(h)h.style.transform=c;else{i.style.overflow="hidden";const l=r.createElement("div");for(l.style.transform=c,l.style.willChange="transform",l.style.display="inline-block",l.style.width="100%";i.firstChild;)l.appendChild(i.firstChild);i.appendChild(l)}i.removeAttribute(qe)}}},Zn=async(t,n)=>{if(fs())try{const r=t.getBoundingClientRect(),i=await Pn("desktop_capture_page_rect",{x:r.left,y:r.top,width:r.width,height:r.height});if(!i)throw new Error("Desktop screenshot capture is not available");const o=new Image;await new Promise((f,_)=>{o.onload=()=>f(),o.onerror=()=>_(new Error("Failed to load desktop preview screenshot")),o.src=`data:${i.mime};base64,${i.base64}`});const c=Math.max(1,o.naturalWidth||i.width||Math.floor(r.width)),h=Math.max(1,o.naturalHeight||i.height||Math.floor(r.height)),u=Math.min(1,1200/c),m=document.createElement("canvas");m.width=Math.floor(c*u),m.height=Math.floor(h*u);const x=m.getContext("2d");if(!x)return null;x.scale(u,u),x.drawImage(o,0,0,c,h);const b=c/Math.max(1,r.width),d=h/Math.max(1,r.height);x.fillStyle="rgba(37, 99, 235, 0.28)",x.strokeStyle="rgb(37, 99, 235)",x.lineWidth=Math.max(2,2*b),x.fillRect(n.bounds.x*b,n.bounds.y*d,n.bounds.width*b,n.bounds.height*d),x.strokeRect(n.bounds.x*b,n.bounds.y*d,n.bounds.width*b,n.bounds.height*d);const g=await new Promise(f=>m.toBlob(f,"image/jpeg",.82));return g?new File([g],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(r){console.warn("[preview] failed to capture annotation screenshot:",r)}return await Bo(t,n)},wt=async(t,n,r,i,o,c)=>{if(!t)return null;try{const h=new Image;await new Promise((w,S)=>{h.onload=()=>w(),h.onerror=()=>S(new Error("Failed to load desktop browser screenshot")),h.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,h.naturalWidth||n),u=Math.max(1,h.naturalHeight||r),x=Math.min(1,1200/l),b=document.createElement("canvas");b.width=Math.floor(l*x),b.height=Math.floor(u*x);const d=b.getContext("2d");if(!d)return null;d.scale(x,x),d.drawImage(h,0,0,l,u);const g=l/Math.max(1,i||l),f=u/Math.max(1,o||u);d.fillStyle="rgba(37, 99, 235, 0.14)",d.strokeStyle="rgb(37, 99, 235)",d.lineWidth=Math.max(2,2*g),d.fillRect(c.bounds.x*g,c.bounds.y*f,c.bounds.width*g,c.bounds.height*f),d.strokeRect(c.bounds.x*g,c.bounds.y*f,c.bounds.width*g,c.bounds.height*f);const _=await new Promise(w=>b.toBlob(w,"image/jpeg",.82));return _?new File([_],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}};async function Oo(t,n){try{const r=t.contentWindow,i=t.contentDocument??r?.document,o=i?.documentElement;if(!r||!i||!o)return null;const c=t.getBoundingClientRect(),h=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||c.width)),l=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||c.height)),u=i.body,m=i.scrollingElement instanceof HTMLElement?i.scrollingElement:null,x=r.scrollX||0,b=r.scrollY||0,d=r.pageXOffset||0,g=r.pageYOffset||0,f=r.visualViewport?.pageLeft||r.visualViewport?.offsetLeft||0,_=r.visualViewport?.pageTop||r.visualViewport?.offsetTop||0,w=o.scrollLeft||0,S=o.scrollTop||0,T=u?.scrollLeft||0,V=u?.scrollTop||0,v=m?.scrollLeft||0,E=m?.scrollTop||0,M=Math.max(x,d,f,w,T,v),F=Math.max(b,g,_,S,V,E);ft("scroll sources",{windowScrollX:x,windowScrollY:b,pageScrollX:d,pageScrollY:g,visualViewportScrollX:f,visualViewportScrollY:_,rootScrollX:w,rootScrollY:S,bodyScrollX:T,bodyScrollY:V,scrollingElementScrollX:v,scrollingElementScrollY:E,scrollingElementTag:m?.tagName?.toLowerCase()??null,resolvedScrollX:M,resolvedScrollY:F,nestedScrolledElements:Qn(i)});const y=Math.max(h,o.scrollWidth||0,u?.scrollWidth||0,Math.ceil(o.getBoundingClientRect().width||0)),P=Math.max(l,o.scrollHeight||0,u?.scrollHeight||0,Math.ceil(o.getBoundingClientRect().height||0)),ee=Math.min(2,Math.max(1,window.devicePixelRatio||1)),G=o.style.scrollBehavior,X=u?.style.scrollBehavior??"";o.style.scrollBehavior="auto",u&&(u.style.scrollBehavior="auto");const J=Io(i);ft("nested scroll snapshot",J.snapshot);let ne=()=>{},z=()=>{};try{await i.fonts?.ready.catch(()=>{}),ne=await Jn(i,h,l,{applyLayoutWorkarounds:!1}),r.scrollTo(M,F),z=Mo(i,M,F),J.reapply();const{snapdom:se}=await Me(async()=>{const{snapdom:me}=await import("./vendor-zumer-snapdom-SJzqoCHV.js");return{snapdom:me}},[]),k={backgroundColor:Xn(i),cache:"disabled",dpr:ee,embedFonts:!0,fast:!1,height:P,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[_o,Lo],quality:.82,width:y},re=await(await se(o,k)).toCanvas();if(!re.width||!re.height)return null;const R=re.width/Math.max(1,y),I=re.height/Math.max(1,P),Z=Math.min(re.width,Math.max(1,Math.round(h*R))),ae=Math.min(re.height,Math.max(1,Math.round(l*I))),le=Math.max(0,re.width-Z),fe=Math.max(0,re.height-ae),ge=Math.min(le,Math.max(0,Math.round(M*R))),de=Math.min(fe,Math.max(0,Math.round(F*I)));ft("capture geometry",{viewportWidth:h,viewportHeight:l,captureWidth:y,captureHeight:P,canvasWidth:re.width,canvasHeight:re.height,xScale:R,yScale:I,sourceX:ge,sourceY:de,sourceWidth:Z,sourceHeight:ae});const ue=i.createElement("canvas");ue.width=Z,ue.height=ae;const be=ue.getContext("2d");if(!be)return null;be.drawImage(re,ge,de,Z,ae,0,0,Z,ae);const pe=await No(ue,.82);return pe?await wt(pe,h,l,h,l,n):null}finally{z(),J.cleanup(),ne(),r.scrollTo(M,F),J.reapply(),o.style.scrollBehavior=G,u&&(u.style.scrollBehavior=X)}}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",r),null}}async function Bo(t,n){const r=await Oo(t,n);if(r)return r;try{const i=t.contentWindow,o=t.contentDocument??i?.document,c=o?.documentElement;if(!i||!o||!c)return null;const h=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(i.innerWidth||t.clientWidth||h.width)),u=Math.max(1,Math.ceil(i.innerHeight||t.clientHeight||h.height)),m=i.scrollX||o.documentElement.scrollLeft||o.body?.scrollLeft||0,x=i.scrollY||o.documentElement.scrollTop||o.body?.scrollTop||0,b=o.body,d=Math.max(u,c.scrollHeight||0,b?.scrollHeight||0),g=Math.min(2,Math.max(1,window.devicePixelRatio||1)),f=c.style.scrollBehavior,_=b?.style.scrollBehavior??"";c.style.scrollBehavior="auto",b&&(b.style.scrollBehavior="auto");let w="",S=()=>{};try{await o.fonts?.ready.catch(()=>{}),S=await Jn(o,l,u,{applyLayoutWorkarounds:!0}),i.scrollTo(m,x);const{getFontEmbedCSS:V,toJpeg:v}=await Me(async()=>{const{getFontEmbedCSS:M,toJpeg:F}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:M,toJpeg:F}},[]),E=await V(c).catch(()=>"");w=await v(c,{quality:.82,pixelRatio:g,width:l,height:u,backgroundColor:Xn(o),imagePlaceholder:Ye,fontEmbedCSS:E||void 0,style:{transform:`translate(${-m}px, ${-x}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${d}px`},cacheBust:!0})}finally{S(),i.scrollTo(m,x),c.style.scrollBehavior=f,b&&(b.style.scrollBehavior=_)}const T=w.split(",",2)[1]||"";return T?await wt(T,l,u,l,u,n):null}catch(i){return console.warn("[preview] failed to capture iframe DOM screenshot:",i),null}}const dn=200,$o=(t,n)=>n==="all"?!0:n==="errors"?t.level==="error"||t.level==="runtime"||t.level==="resource":n==="warnings"?t.level==="warn":t.level==="log"||t.level==="info"||t.level==="debug",at=t=>{const n=it.getState();n.setPendingSyntheticParts([...n.pendingSyntheticParts??[],{text:t,synthetic:!0}])},Fo=async t=>{const n=await t.json().catch(()=>({}));if(!t.ok)return{ok:!1,message:typeof n.error=="string"?n.error:`HTTP ${t.status}`};const r=typeof n.proxyBasePath=="string"?n.proxyBasePath:"",i=typeof n.previewToken=="string"?n.previewToken:"";return!r||!i?{ok:!1,message:"Could not start preview proxy."}:{ok:!0,target:{proxyBasePath:r,previewToken:i,expiresAt:typeof n.expiresAt=="number"?n.expiresAt:0}}},es=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},un=(t,n,r)=>{t.postMessage(r,es(n))},Wo=t=>{if(!t)return t;try{const n=new URL(t);return n.searchParams.delete("oc_preview_token"),n.searchParams.delete("oc_client_token"),n.searchParams.delete("oc_url_token"),n.toString()}catch{return t}},ts=`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
- });`,pt=`(() => {
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
- })()`,zo=`(() => {
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
- })()`,Ho=/^(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,Tt=t=>{try{return new URL(t).host||t}catch{return t}},Qe=t=>{const n=t.trim();if(!n)return"about:blank";try{const r=Ho.test(n)?"http":"https",i=new URL(n.includes("://")?n:`${r}://${n}`);return i.protocol!=="http:"&&i.protocol!=="https:"?"about:blank":i.toString()}catch{return"about:blank"}},hn=async(t,n)=>{const r=t.contentWindow;if(!r)throw new Error("Iframe window is not available");const o=r.eval.call(r,n);return await Promise.resolve(o)};class Uo{constructor(n,r,i,o){this.tab=n,this.start=r,this.listener=i,this.deps=o}tab;start;listener;deps;socket=null;active=!1;disposed=!1;failures=0;retryTimer=null;generation=0;claimed=!1;setActive(n){if(!(this.disposed||n===this.active)){if(this.active=n,n){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(n){return this.socket?.readyState!==1?!1:(this.socket.send(JSON.stringify(n)),!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 n=this.socket;if(this.socket=null,!!n){n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null;try{n.close(1e3)}catch{}}}scheduleReconnect(){if(this.disposed||!this.active||this.retryTimer!==null)return;const n=qt[Math.min(this.failures,qt.length-1)];this.failures+=1,this.listener.onPhase("reconnecting"),this.retryTimer=this.deps.setTimeout(()=>{this.retryTimer=null,this.connect()},n)}async connect(){if(this.disposed||!this.active)return;const n=++this.generation;this.listener.onPhase(this.failures>0?"reconnecting":"connecting");let r;try{const{url:h,popup:l}=this.start();r=await this.deps.open(this.tab,h,this.claimed?null:l??null)}catch{n===this.generation&&this.scheduleReconnect();return}const{socket:i,urlAuthToken:o}=r;if(n!==this.generation||this.disposed||!this.active){try{i.close(1e3)}catch{}return}this.socket=i,i.binaryType="arraybuffer";let c=!1;i.onopen=()=>{c=!0,this.claimed=!0,this.failures=0,this.listener.onPhase("open"),this.listener.onOpen()},i.onmessage=h=>{if(typeof h.data=="string"){const u=Os(h.data);u&&this.listener.onMessage(u);return}const l=Bs(h.data);l?this.listener.onFrame(l.header,l.jpeg):this.ack()},i.onerror=()=>{},i.onclose=h=>{if(this.socket!==i)return;this.socket=null,c||this.deps.forgetToken(o);const l=c?$s(h.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 Vo=5e3,Ko=5,Xo=t=>({project:t.filter(n=>n.inProject),others:t.filter(n=>!n.inProject&&n.title).slice(0,Ko)}),fn=({label:t,servers:n,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:n.map(i=>{const o=`localhost:${i.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(i.url),children:[e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:i.title||o}),e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:[i.title?o:null,i.process].filter(Boolean).join(" · ")})]},i.port)})})]}),qo=({directory:t,onOpen:n})=>{const[r,i]=s.useState(null);return s.useEffect(()=>{let o=!1,c=null,h=null;const l=async()=>{if(document.visibilityState==="visible"){h=new AbortController;try{const u=await Fs(t,h.signal);o||i(Xo(u))}catch{}}o||(c=setTimeout(()=>{l()},Vo))};return l(),()=>{o=!0,h?.abort(),c&&clearTimeout(c)}},[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(fn,{label:"Running in this project",servers:r.project,onOpen:n}):null,r.others.length>0?e.jsx(fn,{label:r.project.length>0?"Other servers":"Running on the server",servers:r.others,onOpen:n}):null]})},Yo=({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(oe,{type:"button",variant:"ghost",size:"xs",onClick:()=>{lt(t).then(n=>{n.ok?he.success("Command copied"):he.error("Could not copy the command")})},children:"Copy"})]}),Go=t=>{const n=t.problem,r=t.installCommands;return!n||n.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}:n.kind==="missing-env"?{title:`${n.envKey} does not point to a browser`,body:`PiChamber was started with ${n.envKey} set, but no file exists at that path. Fix the path or unset it, then restart PiChamber.`,commands:[]}:n.kind==="sandbox-root"||n.kind==="launch-failed"&&n.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:[]}:n.reason==="missing-library"?{title:"Chrome is missing system libraries",body:`Chrome could not start because ${n.library??"a library"} is not installed on the server. Installing Chrome with its dependencies adds what it needs.`,commands:r,detail:n.detail}:n.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:n.detail}:{title:"Chrome did not start",body:"The server browser could not start Chrome. The output below may explain why.",commands:[],detail:n.detail}},Jo=t=>{const n=t.problem;return!n||t.allowNoSandbox?!1:n.kind==="sandbox-root"?!0:n.kind==="launch-failed"&&(n.reason==="sandbox-root"||n.reason==="sandbox-namespaces")},Qo=({status:t,onRetry:n,onUseDevice:r})=>{const[i,o]=s.useState(!1),c=Go(t),h=async()=>{o(!0);try{await Ws({allowNoSandbox:!0}),n()}catch(l){he.error(l instanceof Error?l.message:"Could not save the setting")}finally{o(!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:c.title}),e.jsx("p",{className:"typography-meta text-muted-foreground [text-wrap:pretty]",children:c.body})]}),c.commands.length>0?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:c.commands.length===1?"Run this on the server:":"Run one of these on the server:"}),c.commands.map(l=>e.jsx(Yo,{command:l},l))]}):null,Jo(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(oe,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:()=>{h()},children:"Allow without sandbox"})})]}):null,c.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:c.detail}):null,e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(oe,{type:"button",size:"sm",onClick:n,children:"Check again"}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:r,children:"Load on this device instead"})]})]})})},Zo=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"},ea=({multiple:t,uploading:n,onChoose:r,onCancel:i})=>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(oe,{type:"button",size:"xs",disabled:n,onClick:r,children:n?"Uploading...":t?"Choose files":"Choose file"}),e.jsx(oe,{type:"button",variant:"ghost",size:"xs",disabled:n,onClick:i,children:"Cancel"})]}),ta=({dialog:t,promptText:n,onPromptTextChange:r,onRespond:i})=>{const o=Zo(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:c=>{c.preventDefault(),i(!0)},children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:`${Tt(t.url)} says`}),e.jsx("p",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap typography-meta text-foreground [text-wrap:pretty]",children:o.message}),t.kind==="prompt"?e.jsx("input",{autoFocus:!0,value:n,onChange:c=>r(c.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:[o.dismiss?e.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:()=>i(!1),children:o.dismiss}):null,e.jsx(oe,{type:"submit",size:"sm",autoFocus:t.kind!=="prompt",children:o.accept})]})]})})},na=({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(oe,{type:"button",variant:"outline",size:"sm",onClick:t,children:"Reload"})]}),sa=({phase:t,status:n,failure:r,hasFrame:i,showBlank:o,directory:c,onRetry:h,onSetupRetry:l,onUseDevice:u,onOpenAddress:m})=>t==="unavailable"?n?e.jsx(Qo,{status:n,onRetry:l,onUseDevice:u}):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(oe,{type:"button",variant:"outline",size:"sm",onClick:h,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(oe,{type:"button",variant:"outline",size:"sm",onClick:h,children:"Try again"})]}):(t==="connecting"||t==="reconnecting")&&!i?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..."}):o?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(_t,{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(qo,{directory:c,onOpen:m})]}):null,ra=({decode:t,paint:n,ack:r})=>{let i={busy:!1,pending:null};const o=async(c,h)=>{const l=i;l.busy=!0;let u=null;try{u=await t(h)}catch{}if(i!==l){u?.close();return}try{u&&n(u,c)}finally{u?.close(),r(),l.busy=!1;const m=l.pending;l.pending=null,m&&o(m.header,m.jpeg)}};return{onFrame(c,h){if(i.busy){i.pending&&r(),i.pending={header:c,jpeg:h};return}o(c,h)},reset(){i={busy:!1,pending:null}}}},oa=t=>{const n=s.useRef(null),r=s.useRef(null),[i,o]=s.useState(null),c=s.useRef(t);c.current=t;const[h]=s.useState(()=>ra({decode:m=>createImageBitmap(new Blob([m],{type:"image/jpeg"})),paint:(m,x)=>{const b=n.current,d=b?.getContext("2d");b&&d&&(b.width!==m.width&&(b.width=m.width),b.height!==m.height&&(b.height=m.height),d.drawImage(m,0,0));const g=r.current;r.current=x,(!g||g.width!==x.width||g.height!==x.height)&&o({width:x.width,height:x.height})},ack:()=>c.current()})),l=s.useCallback((m,x)=>h.onFrame(m,x),[h]),u=s.useCallback(()=>h.reset(),[h]);return{canvasRef:n,headerRef:r,frameSize:i,onFrame:l,reset:u}},aa=500,pn=6,mn=["left","middle","right"],ia=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),la=({send:t,canvasRef:n,headerRef:r,areaHeight:i,inspecting:o,onInspectHover:c,onInspectPick:h})=>{const l=s.useRef(null),u=s.useRef({at:0,x:0,y:0,count:0}),m=s.useRef(null),x=s.useRef(null),b=s.useRef(i);b.current=i;const d=s.useCallback((v,E)=>{const M=n.current,F=r.current;return!M||!F?null:zs(v,E,M.getBoundingClientRect(),F)},[n,r]),g=s.useCallback(()=>l.current?.focus({preventScroll:!0}),[]);s.useEffect(()=>{const v=n.current;if(!v)return;const E=M=>{M.preventDefault();const F=d(M.clientX,M.clientY);if(!F)return;const y=M.deltaMode===1?40:M.deltaMode===2?b.current():1;t({type:"mouse",action:"wheel",...F,deltaX:M.deltaX*y,deltaY:M.deltaY*y,modifiers:et(M)})};return v.addEventListener("wheel",E,{passive:!1}),()=>v.removeEventListener("wheel",E)},[n,d,t]);const f=v=>{v.preventDefault(),g();const E=d(v.clientX,v.clientY);if(!E)return;if(v.pointerType==="touch"){m.current={id:v.pointerId,startX:v.clientX,startY:v.clientY,lastX:v.clientX,lastY:v.clientY,moved:!1},v.currentTarget.setPointerCapture(v.pointerId);return}if(v.button===3||v.button===4){t({type:v.button===3?"back":"forward"});return}if(o){v.button===0&&h(E);return}const M=mn[v.button]??"left",F=u.current,y=performance.now(),P=Math.abs(v.clientX-F.x)<5&&Math.abs(v.clientY-F.y)<5;F.count=y-F.at<aa&&P?Math.min(3,F.count+1):1,F.at=y,F.x=v.clientX,F.y=v.clientY,v.currentTarget.setPointerCapture(v.pointerId),x.current={id:v.pointerId,button:M,point:E},t({type:"mouse",action:"down",...E,button:M,buttons:v.buttons,clickCount:F.count,modifiers:et(v)})},_=v=>{const E=d(v.clientX,v.clientY);if(!E)return;const M=m.current;if(v.pointerType==="touch"){if(!M||M.id!==v.pointerId||((Math.abs(v.clientX-M.startX)>pn||Math.abs(v.clientY-M.startY)>pn)&&(M.moved=!0),!M.moved))return;const F=r.current,y=v.currentTarget.getBoundingClientRect(),P=F&&y.width>0?F.width/y.width:1;t({type:"mouse",action:"wheel",...E,deltaX:(M.lastX-v.clientX)*P,deltaY:(M.lastY-v.clientY)*P}),M.lastX=v.clientX,M.lastY=v.clientY;return}if(o){c(E);return}x.current?.id===v.pointerId&&(x.current.point=E),t({type:"mouse",action:"move",...E,buttons:v.buttons,modifiers:et(v)})},w=v=>{const E=d(v.clientX,v.clientY);if(!E)return;if(v.pointerType==="touch"){const F=m.current;if(m.current=null,!F||F.id!==v.pointerId||F.moved)return;if(o){h(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(o||v.button===3||v.button===4)return;x.current?.id===v.pointerId&&(x.current=null);const M=mn[v.button]??"left";t({type:"mouse",action:"up",...E,button:M,buttons:v.buttons,clickCount:u.current.count||1,modifiers:et(v)})},S=(v,E)=>({type:"key",action:v,key:E.key,code:E.code,keyCode:E.keyCode,location:E.nativeEvent.location,repeat:E.repeat,modifiers:et(E)});return{keyboardRef:l,focusKeyboard:g,canvasHandlers:{onPointerDown:f,onPointerMove:_,onPointerUp:w,onPointerCancel:v=>{m.current=null;const E=x.current;!E||E.id!==v.pointerId||(x.current=null,t({type:"mouse",action:"up",...E.point,button:E.button,buttons:0,clickCount:1}))},onMouseDown:v=>v.preventDefault(),onContextMenu:v=>v.preventDefault()},keyboardHandlers:{onKeyDown:v=>{v.nativeEvent.isComposing||v.keyCode===229||Hs(v,ia())||(v.preventDefault(),v.stopPropagation(),t(S("down",v)))},onKeyUp:v=>{v.nativeEvent.isComposing||v.keyCode===229||(v.stopPropagation(),t(S("up",v)))},onPaste:v=>{v.preventDefault();const E=v.clipboardData.getData("text/plain");E&&t({type:"text",text:E})},onCompositionEnd:v=>{v.data&&t({type:"text",text:v.data}),v.currentTarget.value=""},onInput:v=>{v.nativeEvent.isComposing||(v.currentTarget.value="")}}}},ca={url:"about:blank",title:"",loading:!1,canGoBack:!1,canGoForward:!1,crashed:!1},da=1500,ua=({initialUrl:t,directory:n,pageId:r,popupId:i,onScreen:o,routeToggle:c,onRouteChange:h})=>{const l=s.useMemo(()=>Us(n,r),[n,r]),u=Q(N=>N.updateBrowserPage),m=Q(N=>N.openBrowserPopup),x=Q(N=>N.closeBrowserPage),b=Pe(N=>N.currentSessionId),d=Pe(N=>N.newSessionDraft?.open),g=it(N=>N.addAttachedFile),f=Qe(t),_=f!=="about:blank"?f:"",[w,S]=s.useState(ca),[T,V]=s.useState("idle"),[v,E]=s.useState(null),[M,F]=s.useState(""),[y,P]=s.useState(_),[ee,G]=s.useState("default"),[X,J]=s.useState(null),[ne,z]=s.useState(""),[se,k]=s.useState(null),[O,re]=s.useState(!1),[R,I]=s.useState(!1),[Z,ae]=s.useState(null),[le,fe]=s.useState({width:0,height:0}),[ge,de]=s.useState(()=>typeof document>"u"||document.visibilityState==="visible"),ue=s.useRef(null),be=s.useRef(null),pe=s.useRef(null),me=s.useRef(_),xe=s.useRef(i);xe.current=i;const ye=s.useRef(null),ve=s.useRef(!1),Re=s.useRef(new Map),ke=s.useRef({seq:0,inFlight:!1,queued:null}),D=s.useRef(le);D.current=le;const q=s.useCallback(N=>pe.current?.send(N)??!1,[]),{canvasRef:ie,headerRef:A,frameSize:j,onFrame:L,reset:H}=oa(()=>pe.current?.ack()),B=s.useCallback((N,U)=>{!N||N==="about:blank"||!n||!r||u(n,r,{url:N,title:U})},[n,r,u]),a=s.useCallback(N=>{const U=Qe(N);if(U==="about:blank"){he.warning("Enter an http or https address");return}me.current=U,P(U),q({type:"navigate",url:U})||(ye.current=U)},[q]),p=s.useCallback(()=>{const{width:N,height:U}=D.current;N<=0||U<=0||q({type:"viewport",width:Math.round(N),height:Math.round(U),dpr:window.devicePixelRatio||1})},[q]),$=s.useCallback(async(N,U)=>{if(!(b??(d?"draft":null))){he.error("Open a chat session before attaching preview annotations");return}const Ne=U?await wt(U.base64,U.width,U.height,U.cssWidth,U.cssHeight,N):null;Ne&&await g(Ne);const Ie=U?.cssWidth??A.current?.width??0,Ze=U?.cssHeight??A.current?.height??0;at(xt({pageUrl:me.current,viewport:{width:Ie,height:Ze},devicePixelRatio:U&&U.cssWidth>0?U.width/U.cssWidth:1,target:N,screenshotAttached:!!Ne,intro:Ne?"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."})),he.success("Preview annotation attached to chat")},[g,b,A,d]),W=N=>{switch(N.type){case"state":{const U={url:N.url,title:N.title,loading:N.loading,canGoBack:N.canGoBack,canGoForward:N.canGoForward,crashed:N.crashed};S(U),U.url&&U.url!=="about:blank"&&(me.current=U.url,B(U.url,U.title)),ve.current||P(U.url==="about:blank"?"":U.url);return}case"cursor":G(N.cursor||"default");return;case"dialog":J(N),z(N.defaultPrompt||"");return;case"dialog-closed":J(null);return;case"file-chooser":k({id:N.id,multiple:N.multiple});return;case"file-chooser-closed":k(U=>U?.id===N.id?null:U);return;case"clipboard":lt(N.text);return;case"notice":N.kind==="blocked-server-network"?he.warning(`Blocked a page from opening ${Tt(N.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."}):N.kind==="unsupported-address"?he.warning("The server browser opens http and https addresses only"):N.kind==="upload-failed"?he.error("Upload failed",{description:N.message}):he.error(`Could not load ${Tt(N.url)}`,{description:N.message});return;case"popup":m(n,r,N.id)||he.warning("A page opened a popup, but too many tabs are open",{description:"Close a tab, then try again."});return;case"download":{const U=Re.current;if(U.get(N.id)===N.state)return;if(U.set(N.id,N.state),N.state==="completed"){const{id:Ce,filename:Ne}=N;he.success(`Downloaded ${Ne}`,{action:{label:"Save",onClick:()=>{Xs(Ce,Ne).catch(Ie=>{he.error(Ie instanceof Error?Ie.message:`Could not download ${Ne}`)})}}})}else N.state==="canceled"&&he.error(`Download of ${N.filename} failed`);return}case"inspect-hover":{const U=ke.current;if(N.requestId!==U.seq)return;U.inFlight=!1,ae(Je(N.target)?N.target:null);const Ce=U.queued;U.queued=null,Ce&&te(Ce.x,Ce.y);return}case"inspect-pick":ae(null),Je(N.target)&&$(N.target,N.screenshot);return;case"unavailable":N.status&&E(N.status),F(N.message||"");return}},Y=s.useRef(W);Y.current=W;const te=(N,U)=>{const Ce=ke.current;if(Ce.inFlight){Ce.queued={x:N,y:U};return}Ce.seq+=1,Ce.inFlight=q({type:"inspect",x:N,y:U,requestId:Ce.seq})},we=la({send:q,canvasRef:ie,headerRef:A,areaHeight:()=>D.current.height,inspecting:R,onInspectHover:N=>te(N.x,N.y),onInspectPick:N=>{ke.current.seq+=1,q({type:"inspect",...N,pick:!0,requestId:ke.current.seq}),I(!1)}}),{focusKeyboard:je}=we;s.useEffect(()=>{const N=new Uo(l,()=>({url:ye.current||me.current,popup:xe.current}),{onPhase:U=>{V(U),U==="open"&&E(null)},onOpen:()=>{xe.current&&Q.getState().updateBrowserPage(n,r,{popupId:null}),H(),ke.current.inFlight=!1,p();const U=ye.current;ye.current=null,U&&N.send({type:"navigate",url:U})},onMessage:U=>Y.current(U),onFrame:L},{open:Ys,forgetToken:qs,setTimeout:(U,Ce)=>window.setTimeout(U,Ce),clearTimeout:U=>window.clearTimeout(U)});return pe.current=N,()=>{N.dispose(),pe.current===N&&(pe.current=null)}},[n,L,r,H,p,l]),s.useEffect(()=>{T==="closed"&&x(n,r)},[x,n,r,T]);const C=o&&le.width>0&&le.height>0&&ge;s.useEffect(()=>{if(C){pe.current?.setActive(!0);return}const N=window.setTimeout(()=>pe.current?.setActive(!1),da);return()=>window.clearTimeout(N)},[C]),s.useEffect(()=>{const N=()=>de(document.visibilityState==="visible");return document.addEventListener("visibilitychange",N),()=>document.removeEventListener("visibilitychange",N)},[]),s.useEffect(()=>{const N=ue.current;if(!N)return;const U=new ResizeObserver(([Ce])=>{const{width:Ne,height:Ie}=Ce.contentRect;fe(Ze=>Ze.width===Ne&&Ze.height===Ie?Ze:{width:Ne,height:Ie})});return U.observe(N),()=>U.disconnect()},[]),s.useEffect(()=>{if(T!=="open")return;const N=window.setTimeout(p,80);return()=>window.clearTimeout(N)},[le,T,p]),s.useEffect(()=>{if(T!=="unavailable"||v)return;let N=!1;return Vs().then(U=>{N||E(U)}).catch(U=>{N||F(U instanceof Error?U.message:"Could not check the server browser")}),()=>{N=!0}},[T,v]),s.useEffect(()=>{!_||_===me.current||a(_)},[t]),s.useEffect(()=>{if(!R)return;const N=U=>{U.key==="Escape"&&(U.preventDefault(),U.stopImmediatePropagation(),I(!1),ae(null))};return window.addEventListener("keydown",N,!0),()=>window.removeEventListener("keydown",N,!0)},[R]);const Se=N=>{q({type:"dialog",accept:N,text:X?.kind==="prompt"?ne:void 0}),J(null),je()},_e=async N=>{const U=se;if(!U||!N||N.length===0)return;const Ce=U.multiple?Array.from(N):[N[0]];if(Ce.reduce((Ne,Ie)=>Ne+Ie.size,0)>Gs){he.warning(Ce.length===1?"The file is too large":"The files are too large together",{description:"The server browser uploads under 50 MB at a time."}),be.current&&(be.current.value="");return}re(!0);try{const Ne=await Promise.all(Ce.map(Ie=>Js(Ie)));q({type:"file-chooser",id:U.id,uploadIds:Ne})}catch(Ne){he.error(Ne instanceof Error?Ne.message:"Upload failed")}finally{re(!1),be.current&&(be.current.value="")}},Ee=j?Ks(j,le):null,Ue=w.url!=="about:blank",dt=T==="open"&&!Ue&&!w.loading;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(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!w.canGoBack,onClick:()=>q({type:"back"}),"aria-label":"Back",title:"Back",children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!w.canGoForward,onClick:()=>q({type:"forward"}),"aria-label":"Forward",title:"Forward",children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),w.loading?e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>q({type:"stop"}),"aria-label":"Stop loading",title:"Stop loading",children:e.jsx(K,{name:"close",className:"h-3.5 w-3.5"})}):e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!Ue,onClick:()=>q({type:"reload"}),"aria-label":"Reload",title:"Reload",children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:N=>{N.preventDefault(),ve.current=!1,a(y),je()},children:e.jsx("input",{value:y,onChange:N=>P(N.target.value),onFocus:N=>{ve.current=!0,N.currentTarget.select()},onBlur:()=>{ve.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"})}),c,e.jsx(oe,{type:"button",variant:R?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!Ue||T!=="open","aria-pressed":R,onClick:()=>{I(N=>!N),ae(null)},title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!Ue,onClick:()=>{Ge(w.url)},title:"Open in system browser","aria-label":"Open in system browser",children:e.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{ref:ue,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:Ee?{width:Ee.width,height:Ee.height}:{width:"100%",height:"100%"},children:[e.jsx("canvas",{ref:ie,className:"block h-full w-full touch-none select-none outline-none",style:{cursor:R?"crosshair":ee},...we.canvasHandlers,"aria-label":w.title?`Web page: ${w.title}`:"Web page",role:"img"}),R&&Z&&j&&Ee?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:Z.bounds.x*Ee.scale,top:Z.bounds.y*Ee.scale,width:Z.bounds.width*Ee.scale,height:Z.bounds.height*Ee.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:[Z.tag,Z.text?` · ${Z.text}`:""]})}):null]})}),e.jsx("textarea",{ref:we.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,...we.keyboardHandlers}),e.jsx("input",{ref:be,type:"file",className:"hidden",multiple:se?.multiple===!0,onChange:N=>{_e(N.target.files)}}),se?e.jsx(ea,{multiple:se.multiple,uploading:O,onChoose:()=>be.current?.click(),onCancel:()=>q({type:"file-chooser",id:se.id,uploadIds:[]})}):null,X?e.jsx(ta,{dialog:X,promptText:ne,onPromptTextChange:z,onRespond:Se}):null,w.crashed?e.jsx(na,{onReload:()=>q({type:"reload"})}):null,e.jsx(sa,{phase:T,status:v,failure:M,hasFrame:j!==null,showBlank:dt,directory:n,onRetry:()=>pe.current?.retry(),onSetupRetry:()=>{E(null),F(""),pe.current?.retry()},onUseDevice:()=>h("device"),onOpenAddress:a})]})]})},ha=t=>{try{return new URL(t).host||t}catch{return t}},fa=({route:t,onRouteChange:n})=>{const r=t==="server",i=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(oe,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 typography-micro",onClick:()=>n(r?"device":"server"),title:i,"aria-label":r?"Running on the server. Switch to this device":"Loading on this device. Switch to server",children:r?"Server":"This device"})},Dt=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,pa=({initialUrl:t,directory:n,pageId:r,routeToggle:i,onRouteChange:o})=>{const c=s.useRef(null),h=Q(R=>R.updateBrowserPage),[l,u]=s.useState(null),m=Qe(t),x=m!=="about:blank"?m:"",[b,d]=s.useState(x),[g,f]=s.useState(x),[_,w]=s.useState(()=>x?[x]:[]),[S,T]=s.useState(()=>x?0:-1),[V,v]=s.useReducer(R=>R+1,0),[E,M]=s.useState(!!x),[F,y]=s.useState(!1),P=Pe(R=>R.currentSessionId),ee=Pe(R=>R.newSessionDraft?.open),G=it(R=>R.addAttachedFile),X=s.useCallback(R=>{!R||R==="about:blank"||!n||!r||h(n,r,{url:R})},[n,r,h]),J=s.useCallback(R=>{const I=Qe(R),Z=I!=="about:blank"?I:"";f(Z),d(Z),M(!!Z),X(Z),w(ae=>{if(!Z)return T(-1),[];const le=S>=0?ae.slice(0,S+1):[];if(le[le.length-1]===Z)return T(le.length-1),le;const fe=[...le,Z];return T(fe.length-1),fe})},[S,X]),ne=s.useCallback(R=>{const I=_[R];I&&(T(R),f(I),d(I),M(!0),X(I))},[_,X]),z=s.useCallback(()=>{if(g){M(!0);try{c.current?.contentWindow?.location.reload()}catch{v()}}},[g]);s.useEffect(()=>{if(!g)return;const R=new AbortController;return Qs(g,window.location.origin,R.signal).then(I=>{I.framing==="refused"&&u(g)}).catch(()=>{}),()=>R.abort()},[g]);const se=l&&l===g?ha(g):null;s.useEffect(()=>{!x||x===g||J(x)},[t]);const k=s.useCallback(async R=>{if(!(P??(ee?"draft":null))){he.error("Open a chat session before attaching preview annotations");return}const Z=c.current,ae=Z?.contentWindow,le=Z?.getBoundingClientRect(),fe={width:Number.isFinite(ae?.innerWidth)?ae?.innerWidth??le?.width??0:le?.width??0,height:Number.isFinite(ae?.innerHeight)?ae?.innerHeight??le?.height??0:le?.height??0},ge=Z?await Zn(Z,R):null,de=!!ge;ge&&await G(ge),at(xt({pageUrl:g,viewport:fe,devicePixelRatio:window.devicePixelRatio||1,target:R,screenshotAttached:de,intro:de?"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."})),he.success("Preview annotation attached to chat")},[G,P,g,ee]),O=s.useCallback(()=>{const R=c.current;R&&hn(R,pt).catch(()=>{})},[]);s.useEffect(()=>{if(!F)return;const R=I=>{I.key==="Escape"&&(I.preventDefault(),I.stopImmediatePropagation(),y(!1),O())};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[O,F]),s.useEffect(()=>()=>O(),[O]);const re=s.useCallback(()=>{const R=c.current;if(!(!R||!g)){if(F){y(!1),O();return}y(!0),(async()=>{try{const I=await hn(R,ts);if(y(!1),!I||!Je(I))return;await k(I)}catch{y(!1),he.error("This page cannot be inspected on this device. Switch to Server to inspect it.")}})()}},[k,O,g,F]);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(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:S<=0,onClick:()=>ne(S-1),"aria-label":"Back",title:"Back",children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:S<0||S>=_.length-1,onClick:()=>ne(S+1),"aria-label":"Forward",title:"Forward",children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:z,"aria-label":"Reload",title:"Reload",children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:R=>{R.preventDefault(),J(b)},children:e.jsx("input",{value:b,onChange:R=>d(R.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"})}),i,e.jsx(oe,{type:"button",variant:F?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:re,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:()=>{Ge(g)},title:"Open in system browser","aria-label":"Open in system browser",children:e.jsx(K,{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:[g?e.jsx("iframe",{ref:c,src:g,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:()=>M(!1)},`${r}:${V}`):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(_t,{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&&!se?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null,se?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:`${se} 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(oe,{type:"button",size:"sm",onClick:()=>o("server"),children:"Use Server"}),e.jsx(oe,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ge(g)},children:"Open in system browser"})]})]}):null]})]})},ma=({initialUrl:t,directory:n,pageId:r,routeToggle:i})=>{const o=s.useRef(null),c=Q(y=>y.updateBrowserPage),h=Qe(t),l=h!=="about:blank"?h:"",[u,m]=s.useState(l),[x,b]=s.useState(l),[d]=s.useState(h),[g,f]=s.useState(!1),[_,w]=s.useState(!0),S=s.useRef(null),T=s.useCallback(y=>{!y||y==="about:blank"||!n||!r||c(n,r,{url:y})},[n,r,c]),V=Pe(y=>y.currentSessionId),v=Pe(y=>y.newSessionDraft?.open),E=it(y=>y.addAttachedFile),M=s.useCallback(y=>{const P=o.current;if(typeof P?.loadURL=="function")try{P.loadURL(Qe(y))}catch{}},[]);s.useEffect(()=>{const y=o.current;if(!y)return;const P=k=>{!k||k==="about:blank"||(b(k),m(k),T(k))},ee=()=>{try{P(y.getURL())}catch{}},G=k=>{const O=k.url;P(typeof O=="string"?O:"")},X=()=>{S.current&&clearTimeout(S.current),S.current=setTimeout(()=>w(!0),200)},J=()=>{S.current&&clearTimeout(S.current),w(!1),ee()},ne=k=>{const O=k.detail;(O?.disposition==="new-window"||O?.disposition==="foreground-tab"||O?.disposition==="background-tab")&&(k.preventDefault(),O.url&&M(O.url))},z=k=>{const O=k.title;typeof O=="string"&&n&&r&&c(n,r,{title:O})},se=()=>{try{y.executeJavaScript?.(zo,!0).catch(()=>{})}catch{}};y.addEventListener("did-navigate",G),y.addEventListener("did-navigate-in-page",G),y.addEventListener("did-start-loading",X),y.addEventListener("did-stop-loading",J),y.addEventListener("new-window",ne),y.addEventListener("page-title-updated",z),y.addEventListener("dom-ready",se);try{y.isLoading()||(w(!1),ee())}catch{}return se(),()=>{S.current&&clearTimeout(S.current),y.removeEventListener("did-navigate",G),y.removeEventListener("did-navigate-in-page",G),y.removeEventListener("did-start-loading",X),y.removeEventListener("did-stop-loading",J),y.removeEventListener("new-window",ne),y.removeEventListener("page-title-updated",z),y.removeEventListener("dom-ready",se)}},[n,M,r,T,c]),s.useEffect(()=>{const y=setTimeout(()=>w(!1),3e4);return()=>clearTimeout(y)},[]),s.useEffect(()=>{if(!g)return;const y=P=>{if(P.key!=="Escape")return;P.preventDefault(),P.stopImmediatePropagation(),f(!1);const ee=o.current;try{ee?.executeJavaScript?.(pt).catch(()=>{})}catch{}};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[g]),s.useEffect(()=>{const y=o.current;return()=>{try{const P=y?.getURL?.();P&&P!=="about:blank"&&c(n,r,{url:P})}catch{}try{y?.executeJavaScript?.(pt).catch(()=>{})}catch{}}},[n,r,c]),s.useEffect(()=>{!l||l===x||M(l)},[t]);const F=s.useCallback(()=>{const y=o.current;if(y){if(g){f(!1);try{y.executeJavaScript?.(pt).catch(()=>{})}catch{}return}f(!0),y.executeJavaScript?.(ts,!0).then(async P=>{if(f(!1),!P||!Je(P))return;if(!(V??(v?"draft":null))){he.error("Open a chat session before attaching preview annotations");return}const G=typeof y.getWebContentsId=="function"?y.getWebContentsId():null;if(G==null)return;const X=await xr("desktop_browser_capture_page",{webContentsId:G}),J=await y.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),ne=Number.isFinite(J?.width)?J.width:X.width,z=Number.isFinite(J?.height)?J.height:X.height,se=await wt(X.base64,X.width,X.height,ne,z,P),k=!!se;se&&await E(se),at(xt({pageUrl:x,viewport:{width:ne,height:z},devicePixelRatio:window.devicePixelRatio||1,target:P,screenshotAttached:k,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."})),he.success("Preview annotation attached to chat")}).catch(()=>f(!1))}},[E,V,x,g,v]);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(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:y=>{y.preventDefault(),M(u)},children:e.jsx("input",{value:u,onChange:y=>m(y.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"})}),i,e.jsx(oe,{type:"button",variant:g?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:F,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{Ge(x)},children:e.jsx(K,{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:o,src:d,partition:"persist:pichamber-browser",allowpopups:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",border:"none"}}),!x&&!_?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(_t,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,_?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},gn=28,ga=t=>t.length>gn?`${t.slice(0,gn-1)}…`:t,xa=({page:t,directory:n,route:r,onScreen:i})=>{const o=Q(x=>x.updateBrowserPage),c=Q(x=>x.setBrowserRoutePreference),h=s.useCallback(x=>{o(n,t.id,{route:x}),Dt()&&c(x)},[n,t.id,c,o]),l=e.jsx(fa,{route:r,onRouteChange:h}),u={initialUrl:t.url??"",directory:n,pageId:t.id,onScreen:i,routeToggle:l,onRouteChange:h};if(r==="server")return e.jsx(ua,{...u,popupId:t.popupId??null},r);const m=Dt()?ma:pa;return e.jsx(m,{...u},r)},wa=({directory:t,browser:n,onScreen:r})=>{const i=Q(g=>g.browserRoutePreference),o=Q(g=>g.openContextBrowser),c=Q(g=>g.activateBrowserPage),h=Q(g=>g.closeBrowserPage),l=Q(g=>g.updateBrowserPage),u=s.useMemo(()=>n?.pages??[],[n]),m=n?.activePageId??null;s.useEffect(()=>{for(const g of u)g.route||l(t,g.id,{defaultRoute:bt(null,i)})},[t,u,i,l]);const x=s.useMemo(()=>u.map(g=>{const f=ps(g);return{id:g.id,label:ga(f),title:g.url&&g.url!==f?`${f}
127
- ${g.url}`:f,closeLabel:`Close ${f}`}}),[u]),b=()=>{o(t,"",{target:"new",route:bt(null,i)})},d=g=>{Mn(t,g),h(t,g)};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(Vn,{items:x,activeId:m,onSelect:g=>c(t,g),onClose:d,layoutMode:"scrollable",variant:"default"}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",className:"mx-1 my-auto h-7 w-7 shrink-0 p-0",onClick:b,title:"New browser tab","aria-label":"New browser tab",children:e.jsx(K,{name:"add",className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"relative min-h-0 flex-1",children:u.map(g=>{const f=bt(g.route,i),_=g.id===m,w=f==="device"&&Dt();return e.jsx("div",{className:ce("absolute inset-0",!_&&(w?"invisible pointer-events-none":"hidden")),"aria-hidden":_?void 0:!0,children:e.jsx(xa,{page:g,directory:t,route:f,onScreen:r&&_})},g.id)})})]})},ba=8,Fe=new Map,Ht=t=>JSON.stringify([ms(),t]),xn=t=>{const n=Ht(t),r=Fe.get(n);return r?(r.touchedAt=Date.now(),Fe.delete(n),Fe.set(n,r),r):null},St=t=>{const n=Ht(t),r=Fe.get(n);if(r)return r.touchedAt=Date.now(),r;if(Fe.size>=ba){const o=Fe.keys().next().value;o!==void 0&&Fe.delete(o)}const i={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Fe.set(n,i),i},ya=t=>{Fe.delete(Ht(t))},ns=(t,n)=>e.jsx(It,{filePath:t,extension:n}),va=({status:t})=>{const n={open:"var(--status-info)",modified:"var(--status-warning)","git-modified":"var(--status-warning)","git-added":"var(--status-success)","git-deleted":"var(--status-error)"}[t];return e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:n}})},ja=({node:t,root:n,isExpanded:r,isActive:i,isBrowserClient:o,status:c,badge:h,permissions:l,downloadFile:u,onSelect:m,onToggle:x,onRevealPath:b,onOpenDialog:d})=>{const g=t.type==="directory",{canRename:f,canCreateFile:_,canCreateFolder:w,canDelete:S,canReveal:T}=l,V=!g&&!!u,v=T&&!o&&Rn()&&gs(),E=f||_||w||S||V||v,[M,F]=s.useState(!1),[y,P]=s.useState(!1),ee=s.useCallback(z=>{E&&(z?.preventDefault(),P(!0))},[E]),G=s.useCallback(()=>{g?x(t.path):m(t)},[g,t,m,x]),X=s.useCallback(z=>{z.stopPropagation(),P(!1),F(!0)},[]),J=({Item:z,Separator:se})=>e.jsxs(e.Fragment,{children:[f&&e.jsxs(z,{onClick:k=>{k.stopPropagation(),d("rename",t)},children:[e.jsx(K,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(z,{onClick:k=>{k.stopPropagation(),lt(t.path).then(O=>{if(O.ok){he.success("Path copied");return}he.error("Copy failed")})},children:[e.jsx(K,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!g&&u&&e.jsxs(z,{onClick:k=>{k.stopPropagation(),u(t.path).catch(O=>{console.error("Download failed:",O),he.error("Operation failed")})},children:[e.jsx(K,{name:"download",className:"mr-2 h-4 w-4"})," ",o?"Download":"Save"]}),v&&e.jsxs(z,{onClick:k=>{k.stopPropagation(),b(t.path)},children:[e.jsx(K,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",xs()]}),g&&(_||w)&&e.jsxs(e.Fragment,{children:[e.jsx(se,{}),_&&e.jsxs(z,{onClick:k=>{k.stopPropagation(),d("createFile",t)},children:[e.jsx(K,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),w&&e.jsxs(z,{onClick:k=>{k.stopPropagation(),d("createFolder",t)},children:[e.jsx(K,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),S&&e.jsxs(e.Fragment,{children:[e.jsx(se,{}),e.jsxs(z,{onClick:k=>{k.stopPropagation(),d("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(K,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),ne=s.useCallback(z=>{const se=Un(n,t.path);se&&(z.dataTransfer.setData("application/x-pichamber-file-path",se),z.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(Zs,{open:y,onOpenChange:P,children:[e.jsxs(er,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:ee}),children:[e.jsxs("button",{type:"button",onClick:G,onContextMenu:ee,draggable:!0,onDragStart:ne,className:ce("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",i?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[g?r?e.jsx(K,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(K,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):ns(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!g&&c&&e.jsx(va,{status:c}),g&&h&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[h.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",h.modified]}),h.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",h.added]})]})]}),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(wr,{open:M,onOpenChange:F,children:[e.jsxs(Ve,{children:[e.jsx(Ke,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(br,{asChild:!0,children:e.jsx(oe,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:X,title:"File menu","aria-label":"File menu",children:e.jsx(K,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(Xe,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(yr,{align:"end",side:"bottom",onCloseAutoFocus:()=>F(!1),children:J({Item:vr,Separator:jr})})]})})]}),e.jsx(tr,{className:"min-w-[180px]",children:J({Item:nr,Separator:sr})})]})},Sa=(t,n)=>t.node===n.node&&t.root===n.root&&t.isExpanded===n.isExpanded&&t.isActive===n.isActive&&t.isBrowserClient===n.isBrowserClient&&t.status===n.status&&t.badge===n.badge&&t.permissions===n.permissions&&t.downloadFile===n.downloadFile&&t.onSelect===n.onSelect&&t.onToggle===n.onToggle&&t.onRevealPath===n.onRevealPath&&t.onOpenDialog===n.onOpenDialog,ka=s.memo(ja,Sa),Ca=()=>{const{files:t,runtime:n}=Lt(),r=ws(n.platform),i=ct()??"",o=Le(i.trim()),c=bs(),h=Q(a=>a.openContextFile),l=On(i),[u,m]=s.useState(""),x=s.useRef(null),{results:b,searching:d}=po({directory:i,query:u,chrome:"desktop",showGitignored:c}),[g,f]=s.useState({}),[_,w]=s.useState({}),S=s.useRef(new Set),T=s.useRef(new Set),V=s.useRef(null);s.useEffect(()=>{if(!o){f({}),w({}),S.current=new Set;return}const a=xn(o);a?(f({...a.childrenByDir}),w({...a.loadErrorsByDir}),S.current=new Set(a.loadedDirs)):(f({}),w({}),S.current=new Set)},[o]),s.useEffect(()=>{if(!o)return;const a=St(o);a.childrenByDir=g},[o,g]),s.useEffect(()=>{if(!o)return;const a=St(o);a.loadErrorsByDir=_},[o,_]),s.useEffect(()=>{if(!o)return;const a=St(o);a.loadedDirs=new Set(S.current)},[o,g,_]),s.useEffect(()=>()=>{if(!o)return;const a=xn(o);a&&a.loadedDirs.size===0&&Object.keys(a.childrenByDir).length===0&&ya(o)},[o]);const v=s.useMemo(()=>[],[]),E=s.useMemo(()=>[],[]),M=$e(a=>o?a.byRoot[o]?.expandedPaths??v:v),F=$e(a=>o?a.byRoot[o]?.selectedPath??null:null),y=$e(a=>a.setSelectedPath),P=$e(a=>a.addOpenPath),ee=$e(a=>a.removeOpenPathsByPrefix),G=$e(a=>a.toggleExpandedPath),X=$e(a=>a.collapseAllExpandedPaths),J=Q(a=>o?a.contextPanelByDirectory[o]?.tabs??E:E),ne=s.useMemo(()=>new Set(J.map(a=>a.mode==="file"?a.targetPath:null).filter(a=>typeof a=="string"&&a.length>0).map(a=>Le(a))),[J]),z=s.useCallback(a=>{t.revealPath&&t.revealPath(a).catch(()=>{he.error("Failed to reveal path")})},[t]),se=s.useCallback((a,p)=>{const $=p.filter(W=>W&&typeof W.name=="string"&&W.name.length>0).filter(W=>c||!mo(W.name)).map(W=>{const Y=W.name,te=Le(W.path||""),we=te?go(te)?te:Le(`${a}/${te}`):Le(`${a}/${Y}`),je=W.isDirectory?"directory":"file",C=je==="file"&&Y.includes(".")?Y.split(".").pop()?.toLowerCase():void 0;return{name:Y,path:we,type:je,extension:C}});return xo($)},[c]),k=s.useCallback(async(a,p)=>{const $=Le(a.trim());if(!$||S.current.has($)||T.current.has($))return;T.current=new Set(T.current),T.current.add($);const W=t.listDirectory?t.listDirectory($).then(Y=>Y.entries.map(te=>({name:te.name,path:te.path,isDirectory:te.isDirectory}))):ys($).then(Y=>Y.map(te=>({name:te.name,path:te.path,isDirectory:te.isDirectory})));try{const Y=await W;if(p?.())return;const te=se($,Y);S.current=new Set(S.current),S.current.add($),w(we=>{if(!we[$])return we;const je={...we};return delete je[$],je}),f(we=>({...we,[$]:te}))}catch(Y){if(p?.())return;const te=Y instanceof Error?Y.message:String(Y??"");console.error("Failed to load sidebar directory:",Y),w(we=>({...we,[$]:te}))}finally{T.current=new Set(T.current),T.current.delete($)}},[t,se]),O=s.useCallback(async()=>{if(!o)return;V.current?.abort();const a=new AbortController;V.current=a;try{const $=($e.getState().byRoot[o]?.expandedPaths??[]).map(te=>Le(te)).filter(te=>!!te&&te!==o&&te.startsWith(`${o}/`)),W=[o,...$];S.current=new Set(S.current);for(const te of W)S.current.delete(te);w(te=>{if(Object.keys(te).length===0)return te;const we={...te};let je=!1;for(const C of W)C in we&&(delete we[C],je=!0);return je?we:te});const Y=()=>a.signal.aborted;await k(o,Y);for(let te=0;te<$.length&&!a.signal.aborted;te+=3){const we=$.slice(te,te+3);await Promise.all(we.map(je=>k(je,Y)))}}catch(p){if(a.signal.aborted)return;console.error("Failed to refresh sidebar tree:",p)}finally{V.current===a&&(V.current=null)}},[k,o]),re=s.useCallback(async a=>{if(!a){await O();return}const p=Le(a);S.current=new Set(S.current),S.current.delete(p),T.current=new Set(T.current),T.current.delete(p),await k(p)},[k,O]),R=s.useCallback(()=>{o&&y(o,null)},[o,y]),{operation:I,target:Z,inputValue:ae,setInputValue:le,submitting:fe,inputRef:ge,open:de,close:ue,submit:be,capabilities:{canCreateFile:pe,canCreateFolder:me,canRename:xe,canDelete:ye}}=wo({files:t,root:o,selectedPath:F??"",refreshDirectory:re,removeOpenPathsByPrefix:ee,clearSelectedPath:R}),ve=!!t.revealPath,Re=s.useMemo(()=>({canRename:xe,canCreateFile:pe,canCreateFolder:me,canDelete:ye,canReveal:ve}),[xe,pe,me,ye,ve]);s.useEffect(()=>{o&&(V.current?.abort(),S.current=new Set,T.current=new Set,w({}),f(a=>Object.keys(a).length===0?a:{}),k(o))},[k,o,c]),s.useEffect(()=>{if(!o||M.length===0)return;const a=M.map(W=>Le(W)).filter(W=>!!W&&W!==o&&W.startsWith(`${o}/`)&&!S.current.has(W)&&!T.current.has(W)).sort((W,Y)=>W.split("/").length-Y.split("/").length);if(a.length===0)return;let p=!1;const $=()=>p;return(async()=>{for(let W=0;W<a.length&&!p;W+=3){const Y=a.slice(W,W+3);await Promise.all(Y.map(te=>k(te,$)))}})(),()=>{p=!0}},[M,k,o]);const ke=s.useMemo(()=>{const a=new Map;if(!l?.files)return a;for(const p of l.files)p.index==="A"||p.working_dir==="?"?a.set(p.path,"git-added"):p.index==="D"?a.set(p.path,"git-deleted"):(p.index==="M"||p.working_dir==="M")&&a.set(p.path,"git-modified");return a},[l]),D=s.useMemo(()=>{const a=new Map;if(!l?.files||!o)return a;for(const p of l.files){const $=p.index==="M"||p.working_dir==="M",W=p.index==="A"||p.working_dir==="?";if(!$&&!W)continue;const Y=p.path.split("/");if(Y.length<=1)continue;let te=o;for(let we=0;we<Y.length-1;we++){te=`${te}/${Y[we]}`;let je=a.get(te);je||(je={modified:0,added:0},a.set(te,je)),$&&je.modified++,W&&je.added++}}return a},[l,o]),q=s.useCallback(a=>{if(ne.has(a))return"open";if(ke.size===0)return null;const p=a.startsWith(o+"/")?a.slice(o.length+1):a;return ke.get(p)??null},[ne,ke,o]),ie=s.useCallback(a=>{if(D.size===0)return null;const p=D.get(a);return p&&p.modified+p.added>0?p:null},[D]),A=s.useCallback(async a=>{if(!o)return;const p=await zn(t,a.path,{directory:o});if(!p.ok){he.error(Hn(p.reason));return}y(o,a.path),P(o,a.path),h(o,a.path)},[P,t,h,o,y]),j=s.useCallback(async a=>{const p=Le(a);o&&(G(o,p),S.current.has(p)||await k(p))},[k,o,G]);function L(a,p){const $=g[a]??[];return $.map((W,Y)=>{const te=W.type==="directory",we=te&&M.includes(W.path),je=F===W.path,C=Y===$.length-1;return e.jsxs("li",{className:"relative",children:[p>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),C&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(ka,{node:W,root:o,isExpanded:we,isActive:je,isBrowserClient:r,status:te?void 0:q(W.path),badge:te?ie(W.path):void 0,permissions:Re,downloadFile:t.downloadFile,onSelect:A,onToggle:j,onRevealPath:z,onOpenDialog:de}),te&&we&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[_[W.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.path],children:_[W.path]}),e.jsxs(oe,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{re(W.path)},children:[e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,L(W.path,p+1)]})]},W.path)})}const H=!!(o&&g[o]),B=o?_[o]:null;return e.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border/40 px-3 py-2",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(K,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(Zt,{ref:x,value:u,onChange:a=>m(a.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),u.trim().length>0?e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{m(""),x.current?.focus()},children:e.jsx(K,{name:"close",className:"h-4 w-4"})}):null]}),e.jsxs("div",{className:"flex flex-shrink-0 items-center gap-1",children:[pe&&e.jsxs(Ve,{children:[e.jsx(Ke,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>de("createFile",{path:i,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(K,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx(Xe,{side:"bottom",sideOffset:6,children:"New File"})]}),me&&e.jsxs(Ve,{children:[e.jsx(Ke,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>de("createFolder",{path:i,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(K,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx(Xe,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Ve,{children:[e.jsx(Ke,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>{O()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(K,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx(Xe,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Ve,{children:[e.jsx(Ke,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>{o&&X(o)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(K,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx(Xe,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]})]}),e.jsx(Sr,{outerClassName:"flex-1 min-h-0",className:"px-1 py-2",children:e.jsx("ul",{className:"flex flex-col",children:d?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(K,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):b.length>0?b.map(a=>{const p=F===a.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>A(a),draggable:!0,onDragStart:$=>{const W=a.relativePath||Un(o??"",a.path);!W||W==="."||($.dataTransfer.setData("application/x-pichamber-file-path",W),$.dataTransfer.effectAllowed="copy")},className:ce("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors cursor-grab active:cursor-grabbing",p?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:a.path,children:[ns(a.path,a.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:a.relativePath??a.path})]})},a.path)}):B?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:B}),e.jsxs(oe,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{O()},children:[e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):H&&o?L(o,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(Ot,{open:!!I,onOpenChange:a=>!a&&ue(),children:e.jsxs(Bt,{children:[e.jsxs($t,{children:[e.jsxs(Ft,{children:[I==="createFile"&&"Create File",I==="createFolder"&&"Create Folder",I==="rename"&&"Rename",I==="delete"&&"Delete"]}),e.jsxs(Wt,{children:[I==="createFile"&&`Create a new file in ${Z?.path??"root"}`,I==="createFolder"&&`Create a new folder in ${Z?.path??"root"}`,I==="rename"&&`Rename ${Z?.name??""}`,I==="delete"&&`Are you sure you want to delete ${Z?.name??""}? This action cannot be undone.`]})]}),I!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(Zt,{ref:ge,value:ae,onChange:a=>le(a.target.value),placeholder:I==="rename"?"New name":"Name",onKeyDown:a=>{a.key==="Enter"&&be()},autoFocus:!0})}),e.jsxs(kr,{children:[e.jsx(oe,{variant:"outline",onClick:ue,disabled:fe,children:"Cancel"}),e.jsx(oe,{variant:I==="delete"?"destructive":"default",onClick:()=>{be()},disabled:fe||I!=="delete"&&!ae.trim(),children:fe?e.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):I==="delete"?"Delete":"Confirm"})]})]})})]})},Na=200,Pa=480,Ra=({visible:t})=>{const n=Q(w=>w.contextEditorTreeWidth),r=Q(w=>w.setContextEditorTreeWidth),[i,o]=s.useState(!1),c=s.useRef(0),h=s.useRef(n),l=s.useRef(null),u=s.useRef(null),m=s.useRef(null),x=s.useCallback(w=>Math.min(Pa,Math.max(Na,Math.round(w))),[]),b=s.useCallback(w=>{const S=m.current;S&&(S.style.width=`${w}px`,S.style.setProperty("--oc-editor-tree-width",`${w}px`))},[]),d=w=>{if(t){try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}u.current=w.pointerId,o(!0),c.current=w.clientX,h.current=n,l.current=n,w.preventDefault()}},g=w=>{if(!i||u.current!==w.pointerId)return;const S=c.current-w.clientX,T=x(h.current+S);l.current!==T&&(l.current=T,b(T))},f=w=>{if(u.current!==w.pointerId)return;try{w.currentTarget.releasePointerCapture(w.pointerId)}catch{}const S=x(l.current??n);u.current=null,l.current=null,o(!1),r(S)},_=t?n:0;return e.jsxs("div",{ref:m,className:ce("relative h-full flex-shrink-0 overflow-hidden border-l border-border bg-background will-change-[width] motion-reduce:transition-none",!t&&"border-l-0"),style:{width:`${i?l.current??_:_}px`,"--oc-editor-tree-width":`${i?l.current??n:n}px`,overflowX:"clip",transitionProperty:i?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&e.jsx("div",{className:ce("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",i&&"bg-[var(--interactive-border)]"),onPointerDown:d,onPointerMove:g,onPointerUp:f,onPointerCancel:f,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:ce("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",i&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,children:e.jsx(Ca,{})})]})},Ea="x-pichamber-preview-target-error",Ta=t=>{const n=t.get(Ea);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},Da=(t,n)=>Ta(t)?n?"stop-retrying":"retry-registration":"none";function Aa(t){const[n,r]=s.useState("");return s.useEffect(()=>{if(!t){r("");return}let i=!1;return r(""),vs(En()).then(o=>{!i&&o&&r(t)}).catch(()=>{}),()=>{i=!0}},[t]),n}const Ma=({rawUrl:t,onNavigate:n})=>{const{currentTheme:r}=Cr(),[i,o]=s.useReducer(A=>A+1,0),[c,h]=s.useReducer(A=>A+1,0),[l,u]=s.useState({status:"idle"}),m=s.useRef(null),x=s.useRef(1),[b,d]=s.useState(!1),[g,f]=s.useState(!1),[_,w]=s.useState("all"),[S,T]=s.useState([]),[V,v]=s.useState(!1),[E,M]=s.useState(null),F=Pe(A=>A.currentSessionId),y=Pe(A=>A.newSessionDraft?.open),P=ct(),ee=it(A=>A.addAttachedFile);let G=null;try{G=t?new URL(t):null}catch{G=null}const X=G?G.hostname==="localhost"||G.hostname==="127.0.0.1"||G.hostname==="::1"||G.hostname==="[::1]"||G.hostname==="0.0.0.0":!1,J=G?G.hostname==="0.0.0.0"?new URL(G.toString().replace("0.0.0.0","127.0.0.1")):G:null,ne=J?J.toString():"",z=ne?`${En()||"same-origin"}|${ne}`:"",se=r.metadata.variant;s.useEffect(()=>{if(!ne||!X){u({status:"idle"});return}const A=Kn(z);if(A?.previewToken){u({status:"ready",proxyBasePath:A.proxyBasePath,previewToken:A.previewToken,expiresAt:A.expiresAt});return}A&&Oe.delete(z);let j=!1;return u({status:"loading"}),(async()=>{try{const L=await Rt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:ne})}),H=await Fo(L);if(!H.ok){Oe.delete(z),j||u({status:"error",message:H.message});return}Oe.set(z,H.target),j||u({status:"ready",...H.target})}catch(L){if(Oe.delete(z),!j){const H=L instanceof Error?L.message:String(L);u({status:"error",message:H})}}})(),()=>{j=!0}},[X,z,c,ne]);const k=J&&(J.protocol==="http:"||J.protocol==="https:")?J.toString():"",O=X&&l.status==="ready"?`${l.proxyBasePath}|${l.previewToken||""}|${i}`:"",re=Aa(O),R=X&&l.status==="ready"&&J&&re===O?(()=>{const A=J.pathname||"/",j=new URLSearchParams(J.search);j.delete("oc_url_token"),j.delete("oc_client_token"),j.set("ocPreview",String(i)),j.set("oc_preview_token",l.previewToken||"");const L=j.toString(),H=J.hash||"";return js().authenticatedAsset(`${l.proxyBasePath}${A}${L?`?${L}`:""}${H}`)})():"",I=X?R:k,Z=X?Wo(R):k,ae=X&&(l.status==="loading"||l.status==="idle"||re!==O),le=X&&l.status==="error",fe=s.useCallback(A=>{if(!(F??(y?"draft":null))||!P){he.error("Open a chat session before attaching preview annotations");return}const L=t||I||"",H=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},B=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let a=!1;try{const p=m.current,$=p?await Zn(p,A):null;$&&(await ee($),a=!0)}catch{a=!1}at(xt({pageUrl:L,viewport:H,devicePixelRatio:B,target:A,screenshotAttached:a,intro:"This is a selected DOM element from the in-app preview."})),he.success("Preview annotation attached to chat")})()},[ee,F,P,I,y,t]);s.useEffect(()=>{d(!1),T([]),f(!1),w("all"),v(!1),M(null),x.current=1},[I]),s.useEffect(()=>{const A=m.current?.contentWindow;!b||!A||un(A,R,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:V})},[b,V,R]),s.useEffect(()=>{const A=m.current?.contentWindow;!b||!A||un(A,R,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:se})},[b,se,R]),s.useEffect(()=>{if(!V||typeof window>"u")return;const A=j=>{j.key==="Escape"&&(j.preventDefault(),j.stopImmediatePropagation(),v(!1))};return window.addEventListener("keydown",A,!0),()=>window.removeEventListener("keydown",A,!0)},[V]),s.useEffect(()=>{if(!X||typeof window>"u")return;const A=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},j=H=>{const B=x.current;x.current+=1,T(a=>{const p=[...a,{...H,id:B}];return p.length>dn?p.slice(p.length-dn):p})},L=H=>{if(H.source!==m.current?.contentWindow)return;const B=H.data;if(!(!B||B.source!=="pichamber-preview-bridge"||B.version!==1)){if(B.type==="ready"){d(!0);return}if(B.type==="console"){const a=B.level==="error"||B.level==="warn"||B.level==="info"||B.level==="debug"?B.level:"log",p=Array.isArray(B.args)?B.args.map(A).filter(Boolean):[];j({level:a,message:p.join(" "),ts:typeof B.ts=="number"?B.ts:Date.now()});return}if(B.type==="runtime-error"){const a=A(B.filename),p=typeof B.line=="number"?B.line:null,$=typeof B.column=="number"?B.column:null,W=a?`${a}${p!==null?`:${p}${$!==null?`:${$}`:""}`:""}`:"",Y=A(B.stack);j({level:"runtime",message:A(B.message)||"Runtime error",details:[W,Y].filter(Boolean).join(`
128
- `),ts:typeof B.ts=="number"?B.ts:Date.now()});return}if(B.type==="resource-error"){const a=A(B.tag)||"resource",p=A(B.url);j({level:"resource",message:p?`${a}: ${p}`:a,details:A(B.outerHTML),ts:typeof B.ts=="number"?B.ts:Date.now()});return}if(B.type==="hover"){M(Je(B.target)?B.target:null);return}if(B.type==="select"&&Je(B.target)){M(B.target),v(!1),fe(B.target);return}if(B.type==="navigate-preview"){const a=typeof B.url=="string"?B.url:"",p=B.navigation==="external"?"external":"proxy";if(a&&p==="external"){Ge(a);return}a&&n(a)}}};return window.addEventListener("message",L),()=>{window.removeEventListener("message",L)}},[fe,X,n]);const ge=S.filter(A=>A.level==="error"||A.level==="runtime"||A.level==="resource").length,de=S.filter(A=>$o(A,_)),ue=s.useCallback(()=>{const A=[`Preview URL: ${t||I||""}`,`Events: ${S.length}`,""].join(`
129
- `),j=S.map(L=>{const H=new Date(L.ts).toISOString(),B=L.details?`
130
- ${L.details}`:"";return`[${H}] [${L.level}] ${L.message}${B}`}).join(`
131
- `);lt(`${A}${j}`).then(L=>{L.ok?he.success("Preview console copied"):he.error("Failed to copy preview console")})},[S,I,t]),be=s.useCallback(()=>{if(!(F??(y?"draft":null))||!P){he.error("Open a chat session before attaching preview logs");return}const j=[`Preview URL: ${t||I||""}`,`Events: ${S.length}`,""].join(`
132
- `),L=S.map(H=>{const B=new Date(H.ts).toISOString(),a=H.details?`
133
- ${H.details}`:"";return`[${B}] [${H.level}] ${H.message}${a}`}).join(`
134
- `);at(`These are browser console logs from the dev server running for this project.
135
-
136
- ${j}${L}`),he.success("Preview console attached to chat")},[S,F,P,I,y,t]),[pe,me]=s.useState("unknown"),xe=s.useRef(0),ye=s.useRef(0),ve=s.useRef(""),Re=s.useRef(""),ke=15e3;s.useEffect(()=>{if(!R){me("unknown"),ve.current="",xe.current=0,ye.current=0;return}let A=!1,j=null;ve.current!==z&&(ve.current=z,xe.current=Date.now(),ye.current=0);const L=H=>{j=setTimeout(()=>{A||o()},H)};return me("unknown"),(async()=>{const B=await(async()=>{try{return await Rt(R,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(A)return;if(!B){me("unreachable"),L(5e3);return}const a=Da(B.headers,Re.current===z);if(a!=="none"){if(Oe.delete(z),a==="retry-registration")Re.current=z,u({status:"loading"}),h();else{const W=await B.json().catch(()=>({}));if(A)return;const Y=typeof W?.error=="string"?W.error:`HTTP ${B.status}`;u({status:"error",message:Y})}return}if(B.status!==502){Re.current="",me("reachable");return}const p=xe.current||Date.now();if(Date.now()-p<ke){me("starting"),ye.current+=1;const W=ye.current,Y=Math.min(2e3,250*Math.pow(2,Math.min(4,W)));L(Y);return}me("unreachable"),L(5e3)})(),()=>{A=!0,j&&clearTimeout(j)}},[z,R,i]);const D=X&&l.status==="ready"&&(pe==="unknown"||pe==="starting"),q=X&&l.status==="ready"&&pe==="unreachable",ie=s.useCallback(A=>{if(!X||l.status!=="ready"||typeof window>"u")return;const j=A.currentTarget.contentWindow;if(j)try{const L=j.location,H=es(R);if(L.origin!==H||L.pathname.startsWith(l.proxyBasePath))return;const B=`${l.proxyBasePath}${L.pathname}${L.search}${L.hash}`;j.location.replace(B)}catch{}},[X,R,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:Z||t,children:Z||t||"No preview URL"}),e.jsx(oe,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>o(),title:"Reload preview","aria-label":"Reload preview",disabled:!I,children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(oe,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{k&&Ge(k)},title:"Open in browser","aria-label":"Open in browser",disabled:!k,children:e.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"})}),X?e.jsx(oe,{type:"button",size:"sm",variant:V?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>v(A=>!A),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!b,children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}):null,X?e.jsxs(oe,{type:"button",size:"sm",variant:g?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>f(A=>!A),title:b?"Open preview console":"Waiting for preview console","aria-label":b?"Open preview console":"Waiting for preview console",disabled:!b&&S.length===0,children:[e.jsx(K,{name:"terminal-box",className:"h-3.5 w-3.5"}),ge>0?e.jsx("span",{className:"typography-micro text-status-error",children:ge}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[D?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."})]}):q?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(oe,{type:"button",size:"sm",variant:"outline",onClick:()=>o(),children:"Retry"})]}):I&&(!X||pe==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:m,src:I,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:se},onLoad:ie,sandbox:X?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${I}:${i}`),V&&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]}):ae?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):le?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."}),g?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(oe,{type:"button",size:"xs",variant:"ghost",onClick:be,disabled:S.length===0,children:"Attach"}),e.jsx(oe,{type:"button",size:"xs",variant:"ghost",onClick:ue,disabled:S.length===0,children:"Copy"}),e.jsx(oe,{type:"button",size:"xs",variant:"ghost",onClick:()=>T([]),disabled:S.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(A=>e.jsx(oe,{type:"button",size:"xs",variant:_===A?"secondary":"ghost",onClick:()=>w(A),children:A==="all"?"All":A==="errors"?"Errors":A==="warnings"?"Warnings":"Logs"},A))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:S.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):de.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):de.map(A=>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:ce("shrink-0 uppercase",A.level==="error"||A.level==="runtime"||A.level==="resource"?"text-status-error":A.level==="warn"?"text-status-warning":"text-muted-foreground"),children:A.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:A.message})]})},A.id))})]}):null]})]})},Ut=t=>t,At=t=>{const n=Ut(t).type;return typeof n=="string"?n:""},_a=t=>{const n=Ut(t).tool;return typeof n=="string"?n:""},Ia=t=>{const n=Ut(t).text;return typeof n=="string"?n:""},La=t=>{const n=At(t);return n==="tool"?_a(t).trim().toLowerCase()||"tool":n||"unknown"},Oa=t=>{if(t.length===0)return"";const n=[];for(const r of t){const i=La(r);n.includes(i)||n.push(i)}return n.join(" + ")},Ba=t=>t.replace(/\s+/g," ").trim(),$a=t=>{for(const r of t)if(At(r)==="text"){const i=Ba(Ia(r));if(i.length===0)continue;return i}const n=t.filter(r=>At(r)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},Fa=(t,n,r)=>`${r(t)} / ${r(n)}`,Wa=t=>{if(t==="12h")return!0;if(t==="24h")return!1},za=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const r=Wa(n);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}})},Ha={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},mt={user:0,assistant:0,tool:0,other:0},Ua=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,kt=t=>Et(t),Va=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},De=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,r)=>n+De(r),0):t&&typeof t=="object"?Object.values(t).reduce((n,r)=>n+De(r),0):0,Ka=(t,n)=>{const r=t,i=typeof r.type=="string"?r.type:"";if(i==="reasoning")return{...mt,assistant:De(r.text)+De(r.content)};const o=Va(r.text,r.content,r.value,r.source?.value,r.source?.text?.value);return i==="tool"||n==="tool"?{user:0,assistant:0,tool:De(r.input)+De(r.output)+De(r.error)+De(r.call?.input)+De(r.call?.output)+De(r.call?.error)+De(r.raw)+Math.round(De(r.metadata)*.25)+Math.round(De(r.state)*.1),other:0}:n==="user"?{user:o.length,assistant:0,tool:0,other:0}:n==="assistant"?{user:0,assistant:o.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:o.length}},wn=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),Xa=t=>{const n=rt(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},qa=(t,n)=>{if(t.length===0)return{...mt};const r=t.reduce((i,o)=>{const c=Xa(o);let h={...mt};for(const l of o.parts)h=wn(h,Ka(l,c));return wn(i,h)},{...mt});return r.user+=n.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)}},We=t=>t.toLocaleString("en-US"),Ya=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),Ga=(t,n)=>!t||!Number.isFinite(t)?"-":Er(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),Ja=(t,n,r)=>{const i=t.find(c=>c.id===n),o=i?.models?.find(c=>c.id===r);return{providerName:i?.name||n||"-",modelName:o?.name||r||"-",contextLimit:typeof o?.limit?.context=="number"?o.limit.context:null}},Qa=()=>{const t=Q(f=>f.timeFormatPreference),[n,r]=s.useState({}),{value:i,show:o,clear:c}=Nr(null,2e3),h=Pe(f=>f.currentSessionId),l=Pe(f=>f.currentSessionDirectory),u=Pr(),m=Bn(h??""),x=He(f=>f.providers);s.useEffect(()=>{r(f=>Object.keys(f).length>0?{}:f),c()},[c,l,h]);const b=s.useCallback(async(f,_)=>{(await lt(_)).ok?o(f):c()},[c,o]),d=s.useMemo(()=>{const f=h?u.find(R=>R.id===h)??null:null,_=m.filter(R=>rt(R.info).role==="assistant"),w=m.filter(R=>rt(R.info).isUser);let S=null;for(let R=_.length-1;R>=0;R-=1){const I=_[R];if(kt(I).total>0){S=I;break}}const T=S?kt(S):Ha,V=S?.info?.usage,v=_n({input:T.input,cache:{read:T.cacheRead,write:T.cacheWrite}}),E=_.reduce((R,I)=>{const Z=Ua(I.info.cost);return R+Z},0),M=S?.info?.model??null,F=Ja(x,M?.providerID||"",M?.modelID||""),y=F.contextLimit,P=V?In(V):T.total,ee=y&&y>0?Math.min(999,P/y*100):0,G=[...m].reverse().find(R=>rt(R.info).isUser&&typeof R.info.system=="string")?.info?.system||"",X=qa(m,G),J=X.user,ne=X.assistant,z=X.tool,se=V?0:Math.max(0,T.input-J-ne-z),k=J+ne+z+se,O=m[0]?.info?.time?.created,re=m.length>0?m[m.length-1]?.info?.time?.created:null;return{sessionTitle:$n(f),messagesCount:m.length,userMessagesCount:w.length,assistantMessagesCount:_.length,createdAt:f?.time?.created??O??null,lastActivityAt:re??f?.time?.created??null,providerModel:F,tokenBreakdown:T,usagePercent:ee,cacheHitRate:v,totalAssistantCost:E,contextLimit:y,contextWindowTokens:P,hasUsage:V!==void 0,breakdown:{user:J,assistant:ne,tool:z,other:se},breakdownTotal:k}},[h,x,m,u]);if(!h)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 g=[{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-muted-foreground/70",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:Ga(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-muted-foreground/70",children:[We(d.contextWindowTokens),d.contextLimit?` / ${We(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:We(d.messagesCount)},{label:"User",value:We(d.userMessagesCount)},{label:"Assistant",value:We(d.assistantMessagesCount)},{label:"Cost",value:Ya(d.totalAssistantCost)}].map(f=>e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:f.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:f.value})]},f.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(f=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:f.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:f.value!==null&&f.value!==void 0?f.format==="percent"?`${f.value.toFixed(1)}%`:We(f.value):"—"})]},f.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:g.map(f=>f.value<=0||d.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${f.value/d.breakdownTotal*100}%`,backgroundColor:f.color}},f.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:g.map(f=>{const _=d.breakdownTotal>0?f.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:f.color}}),e.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[f.label," ",e.jsxs("span",{className:"tabular-nums",children:[_.toFixed(0),"%"]})]})]},f.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:[...m].reverse().map(f=>{const w=rt(f.info).role,S=w==="assistant",T=w==="user",V=n[f.info.id]===!0,v=i===f.info.id,E=f.info.time?.created??null,M=Oa(f.parts),F=S?kt({info:f.info,parts:f.parts}):null,y=T?$a(f.parts):"",P=za(E,t),ee=M||"—",G=F?Fa(F.input,F.output,We):"",X=w||"unknown",J=M?`${X}: ${M}`:X,ne=V?JSON.stringify({info:f.info,parts:f.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":V,onClick:()=>{r(z=>({...z,[f.info.id]:z[f.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:S?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[T?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",y]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:S?ee:J}),S&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:G})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:P})]})}),V&&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:z=>{z.stopPropagation(),b(f.info.id,ne)},"aria-label":v?"Copied":"Copy JSON",title:v?"Copied":"Copy",children:v?e.jsx(K,{name:"check",className:"size-3.5"}):e.jsx(K,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Rr,{language:"json",code:ne,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},f.info.id)})})]})]})})},Za=Be(()=>Me(()=>import("./DiffView-CFIjN2zy.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,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])).then(t=>({default:t.DiffView}))),ei=Be(()=>Me(()=>import("./FilesView-D0b2mEKA.js"),__vite__mapDeps([54,1,2,3,4,5,6,7,8,9,10,11,12,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,51,52,33,34,18,19,20,21,22,23,24,25,26,27,28,29,30,31,71,72,46,47,48,49,50,73,74,15,16,17,32,35,36,37,38,39,40,41,75,76,77,78,79,45])).then(t=>({default:t.FilesView}))),ti=Be(()=>Me(()=>import("./GitView-Dhr7qVeI.js"),__vite__mapDeps([80,6,1,2,3,10,4,5,7,8,9,11,12,46,47,48,49,50,13,81,82,83,84,44,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,14,42,43,45,51,52])).then(t=>({default:t.GitView}))),ni=Be(()=>Me(()=>import("./PullRequestsSurface-D8JpzP5l.js"),__vite__mapDeps([85,6,1,2,3,86,4,5,7,8,9,10,11,12,46,47,48,49,50,87,81,82,44,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,14,42,43,45,51,52])).then(t=>({default:t.PullRequestsSurface}))),si=Be(()=>Me(()=>import("./IssuesSurface-Bya7OsRl.js"),__vite__mapDeps([88,1,2,3,86,4,5,6,7,8,9,10,11,12,46,47,48,49,50,87,81,82,89])).then(t=>({default:t.IssuesSurface}))),ri=380,oi=1400,ss=600,ai=100,ii=24,bn=t=>Number.isFinite(t)?Math.min(oi,Math.max(ri,Math.round(t))):ss,li=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},ci=(t,n)=>{if(!t)return"";const r=t.replace(/\\/g,"/"),i=n.replace(/\\/g,"/").replace(/\/+$/,"");return i&&r.startsWith(i+"/")?r.slice(i.length+1):r},Mt=(t,n=null)=>t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?zt(n).label:t==="terminal"?"Terminal":t==="pull-requests"?"Pull requests":t==="issues"?"Issues":t==="extensions"?"Extensions":"Context",di=t=>{if(!t)return null;const n=t.replace(/\\/g,"/").trim();if(!n)return null;const r=n.split("/").filter(Boolean);return r.length===0?n:r[r.length-1]||null},ui=(t,n=null)=>{if(t.label)return t.label;if(t.mode==="file")return di(t.targetPath)||"Files";if(t.mode==="preview"){const r=t.targetPath;if(r)try{const i=new URL(r);return i.host||i.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":Mt(t.mode,n)},Ct=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(It,{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(K,{name:zt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(K,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(K,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(K,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(K,{name:"global",className:"h-3.5 w-3.5"});if(t.mode==="pull-requests")return e.jsx(K,{name:"git-pull-request",className:"h-3.5 w-3.5"});if(t.mode==="issues")return e.jsx(K,{name:"task",className:"h-3.5 w-3.5"});if(t.mode==="extensions")return e.jsx(K,{name:"plug-2",className:"h-3.5 w-3.5"})},hi=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,fi=()=>{const t=ct()??"",n=s.useMemo(()=>Le(t),[t]),r=Q(C=>n?C.contextPanelByDirectory[n]:void 0),i=Q(C=>C.closeContextPanel),o=Q(C=>C.closeContextPanelTab),c=Q(C=>C.openContextPanelTab),h=Q(C=>C.toggleContextPanelExpanded),l=Q(C=>C.setContextPanelWidth),u=Q(C=>C.setActiveContextPanelTab),m=Q(C=>C.reorderContextPanelTabs),x=$e(C=>C.setSelectedPath),b=Q(C=>C.openContextPreview),d=Q(C=>C.contextEditorTreeVisible),g=Q(C=>C.toggleContextEditorTree),f=Pe(C=>C.currentSessionId),_=s.useMemo(()=>r?.tabs??[],[r?.tabs]),w=_.find(C=>C.id===r?.activeTabId)??_[_.length-1]??null,S=!!(r?.isOpen&&w),T=!!(S&&r?.expanded),[V,v]=s.useState(null),E=r?.width,M=Ar,F=V??(typeof window<"u"?window.innerWidth:ss*2),y=bn(E??Math.round(M*F)),P=Fn(n||null),[ee,G]=s.useState(!1),[X,J]=s.useState(null),[ne,z]=s.useState(null),[se,k]=s.useState(null),[O,re]=s.useState(null),R=s.useRef(0),I=s.useRef(y),Z=s.useRef(null),ae=s.useRef(null),le=s.useRef(null),fe=s.useRef(!1);s.useLayoutEffect(()=>{const C=le.current?.parentElement;if(!C||typeof ResizeObserver>"u")return;const Se=new ResizeObserver(()=>{v(C.clientWidth||null)});return Se.observe(C),v(C.clientWidth||null),()=>Se.disconnect()},[]),s.useEffect(()=>{if(!S||fe.current){fe.current=S;return}const C=window.requestAnimationFrame(()=>{le.current?.focus({preventScroll:!0})});return fe.current=!0,()=>window.cancelAnimationFrame(C)},[S]);const ge=s.useRef(null),de=s.useRef(null),ue=s.useCallback(()=>{de.current=null;const C=le.current,Se=Z.current;!C||Se===null||C.style.setProperty("--oc-context-panel-width",`${Se}px`)},[]);s.useEffect(()=>()=>{de.current!==null&&clearTimeout(de.current)},[]);const be=s.useCallback(C=>{const Se=bn(C),_e=ge.current;return _e===null?Se:Math.min(Se,Math.max(1,_e))},[]),pe=s.useCallback(C=>{!S||T||!n||(ae.current=C.pointerId,G(!0),R.current=C.clientX,I.current=y,Z.current=y,ge.current=li(le.current),document.documentElement.style.cursor="col-resize",C.preventDefault())},[n,T,S,y]),me=s.useCallback(()=>{const C=be(Z.current??y);Z.current=null,ge.current=null,de.current!==null&&(clearTimeout(de.current),de.current=null),document.documentElement.style.cursor="",n&&l(n,C),G(!1),ae.current=null},[be,n,l,y]);s.useEffect(()=>{if(!ee)return;const C=Ee=>{if(ae.current!==Ee.pointerId)return;const Ue=R.current-Ee.clientX,dt=be(I.current+Ue);Z.current!==dt&&(Z.current=dt,de.current===null&&(de.current=setTimeout(ue,ai)))},Se=Ee=>{ae.current===Ee.pointerId&&me()},_e=()=>{me()};return window.addEventListener("pointermove",C),window.addEventListener("pointerup",Se),window.addEventListener("pointercancel",Se),window.addEventListener("blur",_e),()=>{window.removeEventListener("pointermove",C),window.removeEventListener("pointerup",Se),window.removeEventListener("pointercancel",Se),window.removeEventListener("blur",_e)}},[ue,be,me,ee]),s.useEffect(()=>{ee||(Z.current=null,document.documentElement.style.cursor="")},[ee]);const xe=s.useCallback(()=>{n&&i(n)},[i,n]),ye=s.useCallback(()=>{n&&h(n)},[n,h]),ve=s.useCallback(C=>{C.key==="Escape"&&(Tr(C.target)||(C.preventDefault(),C.stopPropagation(),xe()))},[xe]);s.useEffect(()=>{if(!(!n||!w)&&w.mode==="file"&&w.targetPath){x(n,w.targetPath,{allowOutsideRoot:!0});return}},[w,n,x]);const Re=s.useCallback(C=>{!n||w?.mode!=="diff"||c(n,{mode:"diff",targetPath:w.targetPath,stagedDiff:C==="staged",diffScope:C})},[w,n,c]),ke=w?.mode==="file"||w?.mode==="preview",D=s.useMemo(()=>w?_.filter(C=>C.mode===w.mode):[],[w,_]),q=s.useMemo(()=>D.map(C=>{const Se=ui(C,P),_e=hi(Se,ii),Ee=ci(C.targetPath,t);return{id:C.id,label:_e,icon:Ct(C,P),title:Ee?`${Se}: ${Ee}`:Se,closeLabel:`Close ${_e} tab`}}),[D,t,P]),ie=w?.mode==="pull-requests",A=w?.mode==="issues",j=w?.mode==="context"?e.jsx(Qa,{}):w?.mode==="extensions"?e.jsx(Dr,{sessionId:f}):w?.mode==="git"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ti,{isActive:S,gitHeaderSlot:w?.mode==="git"?ne:null})}):w?.mode==="pull-requests"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ni,{headerActionsSlot:ie?O:null,headerActionsPresentation:"desktop"},`pull-requests:${n}`)}):w?.mode==="issues"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(si,{headerActionsSlot:A?O:null,headerActionsPresentation:"desktop"},`issues:${n}`)}):w?.mode==="preview"?e.jsx(Ma,{rawUrl:w.targetPath??"",onNavigate:C=>b(t,C)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(K,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),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."})]}),L=s.useMemo(()=>_.filter(C=>C.mode==="browser"),[_]),H=s.useMemo(()=>_.filter(C=>C.mode==="diff"),[_]),B=s.useMemo(()=>_.some(C=>C.mode==="terminal"),[_]),a=s.useMemo(()=>_.some(C=>C.mode==="file"),[_]),p=s.useMemo(()=>_.some(C=>C.mode==="file"&&C.targetPath),[_]),$=w?.mode==="file",W=w?.mode==="terminal",Y=w?.mode==="git",te=w?.mode==="diff",we=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[ke?e.jsx(Vn,{items:q,activeId:w?.id??null,onSelect:C=>{n&&u(n,C)},onClose:C=>{if(n){for(const Se of _.find(_e=>_e.id===C)?.browser?.pages??[])Mn(n,Se.id);o(n,C)}},onReorder:(C,Se)=>{n&&m(n,C,Se)},layoutMode:"scrollable",variant:"default"}):W?e.jsx("div",{ref:C=>{J(C)},className:"flex min-w-0 flex-1 items-center px-1"}):Y?e.jsx("div",{ref:C=>{z(C)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):te?e.jsx("div",{ref:C=>{k(C)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):ie||A?e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[w?Ct(w,P):null,e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:w?Mt(w.mode,P):null}),e.jsx("span",{className:"min-w-0 flex-1"}),e.jsx("div",{ref:C=>{re(C)},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:[w?Ct(w,P):null,e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:w?Mt(w.mode,P):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[$?e.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:g,className:"h-8 w-8 p-0",title:"Toggle file tree","aria-label":"Toggle file tree","aria-pressed":d,children:e.jsx(K,{name:"layout-right",className:"size-4"})}):null,e.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:ye,className:"h-8 w-8 p-0",title:T?"Collapse panel":"Expand panel","aria-label":T?"Collapse panel":"Expand panel",children:T?e.jsx(K,{name:"fullscreen-exit",className:"size-4"}):e.jsx(K,{name:"fullscreen",className:"size-4"})}),e.jsx(oe,{type:"button",variant:"ghost",size:"sm",onClick:xe,className:"h-8 w-8 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(K,{name:"close",className:"size-4"})})]})]}),je=S?T?{"--oc-context-panel-width":V!==null?`${V}px`:"100%",width:V!==null?`${V}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${y}px`}:{"--oc-context-panel-width":`${y}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:le,"data-context-panel":"true",tabIndex:-1,inert:!S||void 0,className:ce("flex min-h-0 flex-col overflow-hidden bg-background",T?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!S&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:ve,style:je,children:[S&&!T&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),S&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!T&&e.jsx("div",{className:ce("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",ee&&"bg-[var(--interactive-border)]"),onPointerDown:pe,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:ce("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]",!S&&"pointer-events-none select-none opacity-0"),style:{width:T?V!==null?`${V}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!S,children:[we,e.jsxs("div",{className:ce("relative min-h-0 flex-1 overflow-hidden",ee&&"pointer-events-none"),children:[a?e.jsxs("div",{className:ce("absolute inset-0 flex",$?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:p?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ei,{mode:"editor-only",isVisible:S&&$})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(K,{name:"file-code",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"No file open"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Pick a file from the tree to start editing."})]})}),e.jsx(Ra,{visible:d})]}):null,L.map(C=>e.jsx("div",{className:ce("absolute inset-0",w?.id!==C.id&&"hidden"),children:e.jsx(wa,{directory:n,browser:C.browser,onScreen:S&&w?.id===C.id})},C.id)),S?H.filter(C=>w?.id===C.id).map(C=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(Za,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:C.diffScope??(C.stagedDiff?"staged":"working"),onDiffScopeChange:Re,targetFilePath:C.targetPath,flushContent:!0,toolbarSlot:te?se:null})})},C.id)):null,B?e.jsx("div",{className:ce("absolute inset-0",w?.mode==="terminal"?"block":"hidden"),children:e.jsx(Ln,{visible:S&&w?.mode==="terminal",terminalHeaderSlot:W?X:null})}):null,S&&!$&&w?.mode!=="browser"&&w?.mode!=="diff"&&w?.mode!=="terminal"?j:null]})]})]})},pi=150,mi=500,gi=[],ze=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),ht=(t,n)=>{if(!t||typeof t!="object")return;const r=t[n];return typeof r=="number"&&Number.isFinite(r)?r:void 0},xi=t=>t>99?"99+":String(t),wi=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",bi=({surface:t,isActive:n,showActivityDot:r,label:i,description:o,badgeCount:c,badgeAriaLabel:h,badgeDescription:l,orderNumber:u,showOrderNumber:m,onSelect:x,chartPercentage:b,chartDetails:d})=>{const{attributes:g,listeners:f,setNodeRef:_,transform:w,transition:S,isDragging:T}=Cn({id:t.id}),V=c!=null&&c>0?xi(c):null;return e.jsx("div",{ref:_,style:{transform:Nn.Translate.toString(w),transition:S},className:ce("relative",T&&"z-10 opacity-70"),children:e.jsxs(Ve,{delayDuration:pi,children:[e.jsx(Ke,{asChild:!0,children:e.jsxs("button",{type:"button",...g,...f,onClick:()=>x(t),"aria-label":h??i,"aria-pressed":n,className:ce("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"text-primary":"text-muted-foreground hover:text-foreground"),children:[t.id==="context"&&typeof b=="number"?e.jsx(tn,{percentage:b,className:"size-[18px] -rotate-90"}):e.jsx(K,{name:t.icon,className:"h-[18px] w-[18px]"}),m&&u!=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:u===10?"0":u}):V?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:V}):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(Xe,{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(tn,{percentage:d.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:i}),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:ce("font-semibold",wi(d.percentage)),children:[d.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${ze(d.totalTokens)}/${ze(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:ze(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:ze(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:ze(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:ze(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:ze(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:o})]})}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:i}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:o}),l?e.jsx("span",{className:"typography-micro text-muted-foreground",children:l}):null]})})]})})},yi=()=>{const t=ct(),n=t?Ss(t):"",r=Q(j=>n?j.contextPanelByDirectory[n]:void 0),i=Q(j=>j.contextRailOrder),o=Q(j=>j.setContextRailOrder),c=Q(j=>j.openContextSurface),h=Q(j=>j.shortcutOverrides),{screenWidth:l}=gt(),{git:u,github:m}=Lt(),x=On(n||null),b=Fn(n||null),d=Wn(j=>j.ensureStatus),g=en(j=>j.ensureScope);s.useEffect(()=>{n&&d(n,u)},[n,d,u]),s.useEffect(()=>{!n||!m||g(n,m)},[n,g,m]);const f=s.useMemo(()=>ks("switch_context_surface",h),[h]),[_,w]=s.useState(!1);s.useEffect(()=>{const j=new Set;let L=null,H=!1;const B=Y=>Y.length===1&&Y>="0"&&Y<="9",a=()=>{Xt(f,j)?!H&&L===null&&(L=setTimeout(()=>w(!0),mi)):(H=!1,L!==null&&(clearTimeout(L),L=null),w(!1))},p=Y=>{if(j.add(Y.key.toLowerCase()),B(Y.key)&&Xt(f,j)){H=!0,L!==null&&(clearTimeout(L),L=null),w(!1);return}a()},$=Y=>{j.delete(Y.key.toLowerCase()),a()},W=()=>{j.clear(),H=!1,L!==null&&(clearTimeout(L),L=null),w(!1)};return window.addEventListener("keydown",p,!0),window.addEventListener("keyup",$,!0),window.addEventListener("blur",W),()=>{window.removeEventListener("keydown",p,!0),window.removeEventListener("keyup",$,!0),window.removeEventListener("blur",W),L!==null&&clearTimeout(L)}},[f]);const S=vn(Pt(cs,{activationConstraint:{distance:8}}),Pt(ls,{activationConstraint:{delay:200,tolerance:6}})),T=r?.tabs??gi,V=T.find(j=>j.id===r?.activeTabId)??null,v=r?.isOpen?V?.mode??null:null,E=x?.files.length??0,M=Pe(j=>j.currentSessionId),F=Pe(j=>!!j.newSessionDraft?.open),y=He(j=>j.providers),P=He(j=>j.currentProviderId),ee=He(j=>j.currentModelId),G=He(j=>j.getCurrentModel()),X=He(j=>j.getModelMetadata);He(j=>j.modelsMetadata.size);const J=Mr(s.useCallback(j=>M?j.sessionModelSelections.get(M)??null:null,[M])),ne=Bn(M??""),z=s.useMemo(()=>{for(let j=ne.length-1;j>=0;j-=1){const L=ne[j];if(L?.info.role==="assistant")try{if(Et(L).total>0)return L}catch{continue}}return null},[ne]),k=s.useMemo(()=>{for(let j=ne.length-1;j>=0;j-=1){const L=ne[j]?.info;if(L.role!=="user")continue;const H=L.model,B=H?.providerID??H?.providerId,a=H?.modelID??H?.modelId;if(typeof B=="string"&&B.trim()&&typeof a=="string"&&a.trim())return{providerID:B,modelID:a}}return null},[ne])??(()=>{const j=z?.info.model,L=j?.providerID??j?.providerId,H=j?.modelID??j?.modelId;return L&&H?{providerID:L,modelID:H}:null})()??(J?{providerID:J.providerId,modelID:J.modelId}:null)??(P&&ee?{providerID:P,modelID:ee}:null),re=(k?y.find(j=>j.id===k.providerID):void 0)?.models.find(j=>j.id===k?.modelID),R=k?X(k.providerID,k.modelID):void 0,I=ht(re?.limit,"context")??R?.limit?.context??ht(G?.limit,"context")??0,Z=ht(re?.limit,"output")??R?.limit?.output??ht(G?.limit,"output")??0,ae=z?(()=>{try{return Et(z)}catch{return null}})():null,le=z?.info?.usage,fe=le?In(le):ae?.total??0,ge=!F&&fe>0&&I>0?Math.min(fe/I*100,999):0,de=ge,ue=ae?_n({input:ae.input,cache:{read:ae.cacheRead,write:ae.cacheWrite}}):null,be=ue?.hasInput?ue.percent:null,pe=s.useMemo(()=>{const j=!!z&&fe>0&&I>0;return{percentage:ge,totalTokens:fe,contextLimit:I,outputLimit:Z,cacheRead:ae?.cacheRead??null,cacheWrite:ae?.cacheWrite??null,cacheHitPercent:be,hasData:j}},[ae,be,I,z,Z,ge,fe]),me=_r(j=>M?j.reducer.bySession.get(M)?.extensionWidgets:void 0,(j,L)=>j===L,M?`session:${M}`:"chrome"),xe=s.useMemo(()=>me?.size?[...me.entries()].map(([j,L])=>`${j}:${L.lines.join(`
137
- `)}`).join(";"):"",[me]),ye=xe!=="",ve=s.useRef({});s.useEffect(()=>{v==="extensions"&&M&&xe&&(ve.current[M]=xe)},[v,M,xe]);const Re=M?ve.current[M]??"":"",ke=v!=="extensions"&&xe!==""&&Re!==xe,D=en(j=>n?j.entriesByDirectory[n]??null:null),q=s.useMemo(()=>{if(!D)return{isLoading:!0,hasResult:!1,hasGitHubRepo:!1,hasError:!1};const j=D.scope?.repositories??[];return{isLoading:D.isLoading,hasResult:!!(D.scope||D.error),hasGitHubRepo:j.some(L=>!!(L.host&&L.owner&&L.repo&&!L.disabledReason)),hasError:!!(D.error&&!D.scope)}},[D]),ie=s.useMemo(()=>Ir({railOrder:i,tabs:T,githubScope:q,hasExtensionContent:ye}),[i,l,T,q,ye]),A=s.useCallback(j=>{const{active:L,over:H}=j;if(!H||L.id===H.id)return;const B=Lr(Q.getState().contextRailOrder).map($=>$.id),a=B.indexOf(L.id),p=B.indexOf(H.id);a===-1||p===-1||o(ds(B,a,p))},[o]);return n?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(jn,{sensors:S,collisionDetection:Sn,onDragEnd:A,children:e.jsx(kn,{items:ie.map(j=>j.id),strategy:us,children:ie.map((j,L)=>{const H=j.id==="git"?zt(b):null,B=H?{...j,...H}:j,a=B.label,p=j.id==="git"&&b===!0?E:0,$=p>0?p:null,W=j.id==="context",Y=j.id==="extensions"?ke:!1;return e.jsx(bi,{surface:B,isActive:v===j.mode,showActivityDot:Y,label:a,description:B.description,badgeCount:$,badgeAriaLabel:$!==null?$===1?`${a}, ${$} changed file`:`${a}, ${$} changed files`:null,badgeDescription:$!==null?$===1?`${$} changed file`:`${$} changed files`:null,chartPercentage:W?de:void 0,chartDetails:W?pe:void 0,orderNumber:L+1,showOrderNumber:_,onSelect:te=>c(n,te.mode)},j.id)})})})}):null},vi=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),ji=(t,n,r,i)=>!r||i!==r||t.length===0?[]:st(t,n,o=>o.name,{limit:10,threshold:.4}),Si=new Set,Nt=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),r=n.startsWith("//");let i=n.replace(/\/+/g,"/");r&&!i.startsWith("//")&&(i=`/${i}`);const o=i==="/",c=/^[A-Za-z]:\/$/.test(i);return!o&&!c&&(i=i.replace(/\/+$/,"")),i},ki=()=>{const t=Q(a=>a.isCommandPaletteOpen),n=Q(a=>a.setCommandPaletteOpen),r=Q(a=>a.setActiveMainTab),i=Q(a=>a.setSettingsDialogOpen),o=Q(a=>a.setSettingsPage),c=Q(a=>a.setSessionSwitcherOpen),h=Q(a=>a.toggleSidebar),l=Q(a=>a.openContextOverview),u=Q(a=>a.openContextSurface),m=Q(a=>a.openContextFile),x=Q(a=>a.shortcutOverrides),b=Pe(a=>a.openNewSessionDraft),d=Pe(a=>a.setCurrentSession),g=Or({archived:!1}),f=Br(s.useCallback(a=>t?a.ids:Si,[t])),_=$r(s.useCallback(a=>t?a.rankById:Fr,[t])),w=Cs(a=>a.currentDirectory),S=nn(a=>a.getActiveProject()),T=nn(a=>a.projects),V=ct(),v=Ns(a=>a.searchFiles),{files:E,git:M}=Lt(),F=Wn(a=>a.ensureStatus),{isMobile:y}=gt(),P=s.useMemo(()=>V?Nt(V):null,[V]),[ee,G]=s.useState(""),J=Wr(ee,200).trim(),ne=ee.trim();s.useEffect(()=>{t&&G("")},[t]),s.useEffect(()=>{if(!t||!M)return;const a=setTimeout(()=>{const p=new Set;for(const $ of g){const W=yt($);!W||p.has(W)||(p.add(W),F(W,M))}},0);return()=>clearTimeout(a)},[t,g,M,F]);const z=s.useCallback(()=>n(!1),[n]),se=s.useCallback(a=>()=>{z(),a()},[z]),k=s.useMemo(()=>{const a=[{id:"new-session",title:"New Session",icon:e.jsx(K,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:se(()=>{r("chat"),c(!1),b()})},{id:"add-project",title:"Add Project",icon:e.jsx(K,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:se(()=>{zr.requestDirectoryDialog()})},{id:"toggle-sidebar",title:y?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(K,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:y?"Show Session Switcher":"Toggle Sidebar",onSelect:se(()=>{if(y){const{isSessionSwitcherOpen:p}=Q.getState();c(!p)}else h()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(K,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:se(()=>{w&&u(w,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(K,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:se(()=>{w&&l(w)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(K,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:se(()=>i(!0))}];return Ps()&&a.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(K,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:se(()=>{Pn("desktop_open_draft_mini_chat_window",{directory:Nt(w||S?.path||""),projectId:S?.id??null}).catch(p=>{console.warn("[command-palette] failed to open draft mini chat window",p)})})}),a},[se,y,r,c,b,h,u,w,l,i,S?.id,S?.path]),O=s.useMemo(()=>{const a=Rn();return{isWeb:!a&&Rs(),isDesktop:a,isMobile:y}},[y]),re=s.useMemo(()=>or.filter(a=>a.slug!=="home").filter(a=>a.isAvailable?a.isAvailable(O):!0).map(a=>{const p=ar(a.slug)??"settings-3",$=(a.keywords??[]).join(" ");return{id:`settings:${a.slug}`,title:a.title,icon:e.jsx(K,{name:p,className:"mr-2 h-4 w-4"}),searchText:`${a.title} ${a.group} ${$}`,onSelect:se(()=>{o(a.slug),i(!0)})}}),[O,se,o,i]),R=s.useMemo(()=>Hr(g,f,_),[g,f,_]),I=Ur(),Z=s.useCallback((a,p)=>p&&I.get(p)?.trim()||null,[I]),[ae,le]=s.useState([]),[fe,ge]=s.useState(""),de=vi(P,J);s.useEffect(()=>{if(!t){le([]),ge("");return}if(!de){le([]),ge("");return}if(!P){le([]),ge("");return}let a=!1;return v(P,J,10,{type:"file"}).then(p=>{a||(le(p.map($=>({path:Nt($.path),name:$.name,relativePath:$.relativePath}))),ge(de))}).catch(()=>{a||(le([]),ge(de))}),()=>{a=!0}},[t,P,J,de,v]);const ue=ne.length>0,be=s.useMemo(()=>ue?st(k,ne,a=>a.searchText,{limit:7,noFuzzy:!0}):k.map(a=>({item:a,score:0})),[k,ne,ue]),pe=s.useMemo(()=>ue?st(re,ne,a=>a.searchText,{limit:7,noFuzzy:!0}):[],[re,ne,ue]),me=s.useMemo(()=>ue?st(R,ne,a=>a.title||"",{limit:7,threshold:.2}):R.slice(0,5).map(a=>({item:a,score:0})),[R,ne,ue]),xe=s.useMemo(()=>t?ji(ae,J,de,fe):[],[t,ae,fe,de,J]),ye=t&&de.length>0&&fe!==de,ve=s.useMemo(()=>{if(!ue)return[];const a=T.map(p=>({...p,displayName:p.label||p.path.split("/").pop()||p.path,searchText:`${p.label||""} ${p.path}`}));return st(a,ne,p=>p.searchText,{limit:7,threshold:.4})},[T,ne,ue]),Re=be.map(a=>a.item),ke=pe.map(a=>a.item),D=me.map(a=>a.item),q=ue?xe.map(a=>a.item):[],ie=ue?ve.map(a=>a.item):[],A=s.useMemo(()=>{if(!ue)return["commands","sessions"];const a=$=>$.length?$[0].score:1/0,p=[{key:"commands",score:a(be)},{key:"settings",score:a(pe)},{key:"sessions",score:a(me)},{key:"files",score:a(xe)},{key:"projects",score:a(ve)}];return p.sort(($,W)=>$.score-W.score),p.map($=>$.key)},[ue,be,pe,me,xe,ve]),j=s.useCallback(a=>{z(),d(a.id,yt(a))},[z,d]),L=s.useCallback(async a=>{if(!P)return;const p=await zn(E,a,{directory:P});if(!p.ok){he.error(Hn(p.reason));return}m(P,a),z()},[P,E,m,z]),H=s.useCallback((a,p)=>{z(),b({selectedProjectId:a,directoryOverride:p})},[z,b]),B=s.useCallback(a=>Tn(Dn(a,x)),[x]);return e.jsxs(Ot,{open:t,onOpenChange:n,children:[e.jsxs($t,{className:"sr-only",children:[e.jsx(Ft,{children:"Command Palette"}),e.jsx(Wt,{children:"Search files, sessions, and commands."})]}),e.jsx(Bt,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs(Vr,{shouldFilter:!1,className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:[e.jsx(Kr,{value:ee,onValueChange:G,placeholder:"Search files, sessions, commands..."}),e.jsxs(Xr,{children:[e.jsx(qr,{children:"No results found."}),A.map(a=>a==="commands"&&Re.length>0?e.jsx(tt,{children:Re.map(p=>e.jsxs(nt,{value:p.id,onSelect:p.onSelect,children:[p.icon,e.jsx("span",{children:p.title}),p.shortcutId?e.jsx(Yr,{children:B(p.shortcutId)}):null]},p.id))},"commands"):a==="settings"&&ke.length>0?e.jsx(tt,{children:ke.map(p=>e.jsxs(nt,{value:p.id,onSelect:p.onSelect,children:[p.icon,e.jsx("span",{children:p.title})]},p.id))},"settings"):a==="sessions"&&D.length>0?e.jsx(tt,{children:D.map(p=>{const $=$n(p),W=yt(p),Y=Z(p.id,W);return e.jsxs(nt,{value:`session:${p.id}`,onSelect:()=>j(p),children:[e.jsx(K,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:$}),Y?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(K,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:Y})]}):null]},p.id)})},"sessions"):a==="files"&&q.length>0?e.jsx(tt,{children:q.map(p=>{const $=Es(p.relativePath||p.name,{maxLength:80});return e.jsxs(nt,{value:`file:${p.path}`,onSelect:()=>{L(p.path)},children:[e.jsx(It,{filePath:p.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":p.relativePath,children:$})]},`file:${p.path}`)})},"files"):a==="projects"&&ie.length>0?e.jsx(tt,{children:ie.map(p=>{const $=p.displayName;return e.jsxs(nt,{value:`project:${p.id}`,onSelect:()=>H(p.id,p.path),children:[e.jsx(Gr,{directory:p.path,label:$,className:"mr-2 size-4"}),e.jsx("span",{className:"truncate",children:$}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:p.path})]},`project:${p.id}`)})},"projects"):null),ye?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},Ci=(t,n,r)=>Ds(t)?Tn(Dn(t,r)):n,Ni=()=>{const t=Q(c=>c.isHelpDialogOpen),n=Q(c=>c.setHelpDialogOpen),r=Q(c=>c.shortcutOverrides),i=Ts(),o=[{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 + ${i} + 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:[`${i} + 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(Ot,{open:t,onOpenChange:n,children:e.jsxs(Bt,{className:"w-[92vw] max-w-[1120px] h-[84vh] max-h-[900px] flex flex-col overflow-hidden",children:[e.jsxs($t,{children:[e.jsxs(Ft,{className:"flex items-center gap-2",children:[e.jsx(K,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Wt,{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:o.map(c=>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:c.categoryKey}),e.jsx("div",{className:"space-y-1",children:c.items.map(h=>{const l=h.id?Ci(h.id,Array.isArray(h.keys)?h.keys[0]:h.keys,r):Array.isArray(h.keys)?h.keys:h.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:[h.icon&&e.jsx(K,{name:h.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:h.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l)?l:[l]).map((u,m)=>e.jsxs(s.Fragment,{children:[m>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:u})]},`${u}-${m}`))})]},h.id||h.descriptionKey)})})]},c.categoryKey))})})]})})},Pi=s.createContext(null),Ri=({children:t,value:n})=>e.jsx(Pi.Provider,{value:n,children:t}),yn=Be(()=>Me(()=>import("./GitView-Dhr7qVeI.js"),__vite__mapDeps([80,6,1,2,3,10,4,5,7,8,9,11,12,46,47,48,49,50,13,81,82,83,84,44,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,14,42,43,45,51,52])).then(t=>({default:t.GitView}))),Ei=Be(()=>Me(()=>import("./DiffView-CFIjN2zy.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,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])).then(t=>({default:t.DiffView}))),Ti=Be(()=>Me(()=>import("./FilesView-D0b2mEKA.js"),__vite__mapDeps([54,1,2,3,4,5,6,7,8,9,10,11,12,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,51,52,33,34,18,19,20,21,22,23,24,25,26,27,28,29,30,31,71,72,46,47,48,49,50,73,74,15,16,17,32,35,36,37,38,39,40,41,75,76,77,78,79,45])).then(t=>({default:t.FilesView}))),Di=Be(()=>Me(()=>import("./DiagramView-Dq5w8TCG.js"),__vite__mapDeps([90,1,2,3,10,4,5,6,7,8,9,11,12,71,72])).then(t=>({default:t.DiagramView}))),Ai=Be(()=>Me(()=>import("./SettingsView-B-b76XDV.js").then(t=>t.h),__vite__mapDeps([91,1,2,3,4,5,6,7,8,9,10,11,12,46,47,48,49,50,92,93,94,83,84])).then(t=>({default:t.SettingsView}))),Mi=Be(()=>Me(()=>import("./SettingsWindow-5dK-buUn.js"),__vite__mapDeps([95,1,2,3,4,5,6,7,8,9,10,11,12,91,46,47,48,49,50,92,93,94,83,84])).then(t=>({default:t.SettingsWindow}))),_i=()=>{const t=Q(k=>k.isSidebarOpen),n=Q(k=>k.activeMainTab),r=Q(k=>k.setIsMobile),i=Q(k=>k.isSessionSwitcherOpen),o=Q(k=>k.isSettingsDialogOpen),c=Q(k=>k.setSettingsDialogOpen),[h,l]=s.useState(!1);s.useEffect(()=>{o&&l(!0)},[o]),s.useEffect(()=>{const k=()=>Q.getState().closeMainSurfaces(),O=Pe.subscribe((R,I)=>{const Z=!!R.currentSessionId&&R.currentSessionId!==I.currentSessionId,ae=!!R.newSessionDraft?.open&&R.newSessionDraft!==I.newSessionDraft;(Z||ae)&&k()}),re=Q.subscribe((R,I)=>{R.activeMainTab!==I.activeMainTab&&k()});return()=>{O(),re()}},[]);const{isMobile:u}=gt(),m=s.useRef(!1),[x,b]=s.useState(!1),[d,g]=s.useState(!1),[f,_]=s.useState(!1),[w,S]=s.useState(!1),T=s.useCallback(k=>{b(k),Q.getState().setSessionSwitcherOpen(k)},[]),V=s.useRef(typeof window>"u"?0:window.innerWidth),v=s.useRef(null),E=s.useRef(!1),M=s.useRef(!1),F=s.useRef(!1),y=s.useRef(null),P=s.useRef(null),ee=Vt(-V.current),G=Te.useRef(0),X=Vt(V.current),J=Te.useRef(0);Te.useEffect(()=>{u&&(G.current=window.innerWidth,J.current=window.innerWidth)},[u]),Te.useEffect(()=>{if(!u)return;const k=()=>{const O=window.innerWidth;G.current=O,J.current=O,x||ee.get()<-10&&ee.set(-O),d||X.get()>10&&X.set(O)};return window.addEventListener("resize",k),window.addEventListener("orientationchange",k),()=>{window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k)}},[u,ee,X,x,d]),Te.useEffect(()=>{if(!u){_(!1);return}x&&_(!0);const k=G.current||V.current||(typeof window<"u"?window.innerWidth:0),O=ut(ee,x?0:-k,{type:"spring",stiffness:400,damping:35,mass:.8});return y.current=O,()=>O.stop()},[x,u,ee]),Te.useEffect(()=>{if(!u){S(!1);return}d&&S(!0);const k=J.current||V.current||(typeof window<"u"?window.innerWidth:0),O=ut(X,d?0:k,{type:"spring",stiffness:400,damping:35,mass:.8});return P.current=O,()=>O.stop()},[u,d,X]),Te.useEffect(()=>{if(u)return ee.on("change",k=>{const O=G.current||V.current,re=x||k>-O+.5;_(R=>R===re?R:re)})},[u,ee,x]),Te.useEffect(()=>{if(u)return X.on("change",k=>{const O=J.current||V.current,re=d||k<O-.5;S(R=>R===re?R:re)})},[u,d,X]),Te.useEffect(()=>{u&&!i&&x&&T(!1)},[i,u,x,T]),Te.useEffect(()=>{if(!u){m.current=!1;return}m.current||(m.current=!0,T(!1),g(!1))},[u,T]),Te.useEffect(()=>{if(!u||n!=="chat"||x||d||o)return;let k=!1,O;return(R=>{O=window.setTimeout(()=>{if(k)return;const I=Pe.getState(),Z=Q.getState();Z.activeMainTab!=="chat"||Z.isSettingsDialogOpen||I.currentSessionId||I.newSessionDraft?.open||I.openNewSessionDraft({automatic:!0})},R)})(500),()=>{k=!0,O!==void 0&&window.clearTimeout(O)}},[n,u,o,x,d]),Te.useEffect(()=>{!u||!o||(T(!1),g(!1))},[u,o,T]),s.useEffect(()=>{Q.getState().isMobile!==u&&r(u)},[u,r]);const ne=s.useCallback(()=>{x&&T(!1),g(!d)},[x,d,T]);ir(v,{enabled:u,leftOpen:x,rightOpen:d,leftWidth:()=>G.current||V.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>J.current||V.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:k=>{const O=G.current||V.current||(typeof window<"u"?window.innerWidth:0);ee.set(O*(k-1))},onRightProgress:k=>{const O=J.current||V.current||(typeof window<"u"?window.innerWidth:0);X.set(O*(1-k))},onLeftOpen:()=>{d&&g(!1),T(!0)},onLeftClose:()=>T(!1),onRightOpen:()=>{x&&T(!1),g(!0)},onRightClose:()=>g(!1),onDragStart:k=>{E.current=!0,k==="left"?(M.current=x,y.current?.stop(),f||_(!0)):(F.current=d,P.current?.stop(),w||S(!0))},onDragEnd:(k,O)=>{if(E.current=!1,k==="left"&&typeof O=="boolean"){const re=M.current;if(O===re){const R=G.current||V.current||(typeof window<"u"?window.innerWidth:0),I=ut(ee,re?0:-R,{type:"spring",stiffness:400,damping:35,mass:.8});y.current=I}}if(k==="right"&&typeof O=="boolean"){const re=F.current;if(O===re){const R=J.current||V.current||(typeof window<"u"?window.innerWidth:0),I=ut(X,re?0:R,{type:"spring",stiffness:400,damping:35,mass:.8});P.current=I}}}});const z=s.useMemo(()=>{if(!u&&n!=="terminal"&&n!=="diagram"||u&&n==="git"&&(d||w))return null;switch(n){case"git":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(yn,{isActive:!0})});case"diff":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ei,{})});case"terminal":return e.jsx(Ln,{onCloseView:()=>Q.getState().setActiveMainTab("chat")});case"files":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ti,{})});case"diagram":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Di,{})});default:return null}},[n,u,w,d]),se=n==="chat";return e.jsxs(lr,{children:[e.jsx(cr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:ce("main-content-safe-area",u?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(ki,{}),e.jsx(Ni,{}),e.jsx(dr,{}),u?e.jsxs(Ri,{value:{leftDrawerOpen:x,rightDrawerOpen:d,toggleLeftDrawer:()=>{const k=!x;d&&g(!1),T(k)},toggleRightDrawer:ne,leftDrawerX:ee,rightDrawerX:X,leftDrawerWidth:G,rightDrawerWidth:J,setMobileLeftDrawerOpen:T,setRightSidebarOpen:g},children:[!o&&e.jsx(Yt,{onToggleLeftDrawer:()=>{const k=!x;d&&g(!1),T(k)},onToggleRightDrawer:()=>{ne()},leftDrawerOpen:x,rightDrawerOpen:d}),e.jsx("div",{"data-page-scroll-lock":"true",className:ce("flex flex-1 overflow-hidden relative",o&&"hidden"),children:e.jsxs("main",{ref:v,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:ce("absolute inset-0",!se&&"invisible"),children:e.jsx(Ae,{children:e.jsx(Gt,{active:se&&!o})})}),z&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ae,{children:z})}),e.jsx(Ae,{children:e.jsx(Jt,{})}),e.jsx(Kt.div,{className:ce("absolute inset-0 z-20 bg-sidebar",!f&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:ee},"aria-hidden":!x,children:e.jsx(Ae,{children:e.jsx(Qt,{mobileVariant:!0,isVisible:f})})}),e.jsx(Kt.div,{className:ce("absolute inset-0 z-20 bg-sidebar",!w&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:X},"aria-hidden":!d,children:e.jsx(Ae,{children:d||w?e.jsx(s.Suspense,{fallback:null,children:e.jsx(yn,{isActive:d})}):null})})]})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(Ae,{children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ai,{onClose:()=>c(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(ur,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(So,{isOpen:t,isMobile:u,children:e.jsx(Qt,{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(Yt,{}),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:ce("absolute inset-0",!se&&"invisible"),children:e.jsx(Ae,{children:e.jsx(Gt,{active:se&&!o})})}),z&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ae,{children:z})}),e.jsx(Ae,{children:e.jsx(Jt,{})})]}),e.jsx(fi,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Ae,{children:e.jsx(yi,{})})})]})]})]}),h?e.jsx(s.Suspense,{fallback:null,children:e.jsx(Mi,{open:o,onOpenChange:c})}):null]})]})]})},Ii=()=>(so(),fr(),e.jsxs(pr,{children:[e.jsx(ro,{embeddedBackgroundWorkEnabled:!0}),e.jsx(oo,{}),e.jsx(ao,{}),e.jsx(mr,{}),e.jsx(io,{}),e.jsx(lo,{}),e.jsx(_i,{}),e.jsx(gr,{}),e.jsx(co,{}),e.jsx(uo,{})]}));function Li({apis:t}){const n=t??An(),[r,i]=s.useState(0);return s.useEffect(()=>As(o=>{if(o.runtimeKey===o.previousRuntimeKey){Ms();return}hr(o),i(c=>c+1)}),[]),s.useEffect(()=>{let o=!0,c=null,h=null,l=null;return _s().then(()=>{o&&(c=Jr(),h=Qr(),l=Zr())}),()=>{o=!1,c?.(),h?.(),l?.()}},[r]),s.useEffect(()=>{n&&Is(n)},[n]),n?e.jsx(Ae,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(eo,{apis:n,children:e.jsx(to,{children:e.jsx(no,{children:e.jsx(Ii,{})})},r)})})}):e.jsx(Ae,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const rs=document.getElementById("root");if(!rs)throw new Error("Root element not found");hs.createRoot(rs).render(e.jsx(Te.StrictMode,{children:e.jsx(ho,{children:e.jsx(fo,{children:e.jsx(Li,{apis:An()??void 0})})})}));