@pi-chamber/web 0.2.1 → 0.2.2

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 (75) hide show
  1. package/dist/assets/{CommitSection-BQBmpPVE.js → CommitSection-DPjTv8fA.js} +1 -1
  2. package/dist/assets/{DiagramEditor-Cp22TGpq.js → DiagramEditor-ChOor9l9.js} +1 -1
  3. package/dist/assets/{DiagramView-E4HJ4ZPU.js → DiagramView-3hAT86v_.js} +1 -1
  4. package/dist/assets/{DiffView-d23o9CKP.js → DiffView-D1dyOiw2.js} +2 -2
  5. package/dist/assets/FilesView-BCzghrc7.js +14 -0
  6. package/dist/assets/{GitView-CkUONO1-.js → GitView-CYF1E1p4.js} +4 -4
  7. package/dist/assets/{JsonTreeView-By2oGMNK.js → JsonTreeView-CrJO6LNu.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-DUghE55t.js → MarkdownRendererImpl-BmKjrkGD.js} +2 -2
  9. package/dist/assets/{PatchDiff-BjN6zMtK.js → PatchDiff-DgvPLx6x.js} +1 -1
  10. package/dist/assets/{PierreDiffViewer-B38_7NnU.js → PierreDiffViewer-InnT0JVA.js} +2 -2
  11. package/dist/assets/{SessionSwitcherDropdown-NbVfnqQQ.js → SessionSwitcherDropdown-C0OdvirK.js} +102 -102
  12. package/dist/assets/{SettingsView-C2dCv0r7.js → SettingsView-JAfC_cBL.js} +1 -1
  13. package/dist/assets/{SettingsWindow-DsMhdX5H.js → SettingsWindow-BBEsjcJE.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-DVesARmI.js → ToolOutputDialog-gzwcb8nI.js} +4 -4
  15. package/dist/assets/{ToolPartDiffPreview-C2N_oIO-.js → ToolPartDiffPreview-C45V5bhy.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-B7eVR6Pt.js → VirtualizedFileDiff-uKfnkQWb.js} +1 -1
  17. package/dist/assets/{collapsible-CPkWB1VR.js → collapsible-Bq8sDiKS.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-BsZulefS.js → computeVirtualFileMetrics-BPgZ_RSe.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-BmmlK5E3.js → contextFileOpenGuard-CydO7PkI.js} +1 -1
  20. package/dist/assets/{index-C84KrQoy.js → index-BSuNNtBh.js} +1 -1
  21. package/dist/assets/{index-BhXma4dv.js → index-CH7o4-_q.js} +1 -1
  22. package/dist/assets/index-o4Eea60G.css +1 -0
  23. package/dist/assets/{isDiffPlainText-DsuyxFXo.js → isDiffPlainText-f9b4cKNo.js} +1 -1
  24. package/dist/assets/{isFilePlainText-CCYoe7us.js → isFilePlainText-BjESb-gU.js} +1 -1
  25. package/dist/assets/{main-ClYgYVm1.js → main-B508FBXr.js} +2 -2
  26. package/dist/assets/main-nG4uFyAy.js +133 -0
  27. package/dist/assets/{markdownCore-D2uqals1.js → markdownCore-BFmf8a-O.js} +2 -2
  28. package/dist/assets/{miniChat-DmX9SjxM.js → miniChat-BTlz8IPL.js} +2 -2
  29. package/dist/assets/{mobile-C-PCxN62.js → mobile-DBkrRt80.js} +2 -2
  30. package/dist/assets/renderElectronMiniChatApp-DW3fSR5w.js +1 -0
  31. package/dist/assets/renderMobileApp-9qkroKty.js +14 -0
  32. package/dist/assets/{runtimeSurface-CouGjZ3A.js → runtimeSurface-Bec4O8FD.js} +1 -1
  33. package/dist/assets/{useInlineCommentController-buNJ3xB4.js → useInlineCommentController-CHmIm0Rr.js} +2 -2
  34. package/dist/assets/usePanelSlide-DCX8qQ4K.js +56 -0
  35. package/dist/assets/{useWindowTitle-CnF4pKz0.js → useWindowTitle-CE5N_NeU.js} +3 -3
  36. package/dist/assets/{vendor-codemirror-autocomplete-3xMyV7a2.js → vendor-codemirror-autocomplete-BS2SpSAZ.js} +1 -1
  37. package/dist/assets/{vendor-codemirror-commands-Bzf12ODH.js → vendor-codemirror-commands-RrgJ8H_6.js} +1 -1
  38. package/dist/assets/{vendor-codemirror-lang-angular-0K6s6cvb.js → vendor-codemirror-lang-angular-ADhO_TUK.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-lang-cpp-B0aL03z-.js → vendor-codemirror-lang-cpp-BGCWj7Om.js} +1 -1
  40. package/dist/assets/{vendor-codemirror-lang-css-C4jEScp7.js → vendor-codemirror-lang-css-Ba8JZ6fp.js} +1 -1
  41. package/dist/assets/{vendor-codemirror-lang-go-CgrfVBPr.js → vendor-codemirror-lang-go-DyTiHXo4.js} +1 -1
  42. package/dist/assets/{vendor-codemirror-lang-html-C1Svvdey.js → vendor-codemirror-lang-html-DK27qQri.js} +1 -1
  43. package/dist/assets/{vendor-codemirror-lang-java-DNPz7_Bx.js → vendor-codemirror-lang-java-CvFfnhPQ.js} +1 -1
  44. package/dist/assets/{vendor-codemirror-lang-javascript-CrbeaEAU.js → vendor-codemirror-lang-javascript-BUlYhQ3o.js} +1 -1
  45. package/dist/assets/{vendor-codemirror-lang-jinja-DL8BR_RG.js → vendor-codemirror-lang-jinja-wBMtAEvT.js} +1 -1
  46. package/dist/assets/{vendor-codemirror-lang-json-BTvAjwkJ.js → vendor-codemirror-lang-json-CqayksDf.js} +1 -1
  47. package/dist/assets/{vendor-codemirror-lang-less-CPABt6NZ.js → vendor-codemirror-lang-less-Ct3-H1PB.js} +1 -1
  48. package/dist/assets/{vendor-codemirror-lang-liquid-BLOLOBMg.js → vendor-codemirror-lang-liquid-XspREksq.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-lang-markdown-BloD9GN-.js → vendor-codemirror-lang-markdown-CvO36Y1p.js} +1 -1
  50. package/dist/assets/{vendor-codemirror-lang-php-FIZMTuWM.js → vendor-codemirror-lang-php-BlUF9cCe.js} +1 -1
  51. package/dist/assets/{vendor-codemirror-lang-python-CR2g6ukK.js → vendor-codemirror-lang-python-_2bIYTiJ.js} +1 -1
  52. package/dist/assets/{vendor-codemirror-lang-rust-lsPqn4k4.js → vendor-codemirror-lang-rust-BdTYih_U.js} +1 -1
  53. package/dist/assets/{vendor-codemirror-lang-sass-CtECMwzH.js → vendor-codemirror-lang-sass-E6MhfOFk.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-lang-sql-BtmZrrZH.js → vendor-codemirror-lang-sql-B1BRhQSF.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-lang-vue-Br6DrntY.js → vendor-codemirror-lang-vue-BYQJRa1Q.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-lang-wast-DT7IlCnb.js → vendor-codemirror-lang-wast-D706yuyC.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-xml-wNr-LZOf.js → vendor-codemirror-lang-xml--MfWU6Dj.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-yaml-BTKFwfc2.js → vendor-codemirror-lang-yaml-CRUFIbRX.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-language-BuDklWi8.js → vendor-codemirror-language-E2vgV9K3.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-language-data-qBLdzwMc.js → vendor-codemirror-language-data-q1yHU1R9.js} +2 -2
  61. package/dist/assets/{vendor-codemirror-search-BzyfPoRb.js → vendor-codemirror-search-8kyQdB3f.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-state-Wdz6Qsow.js → vendor-codemirror-state-CNWM3Q8V.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-view-pXtfpqbT.js → vendor-codemirror-view-DSzLbZiS.js} +1 -1
  64. package/dist/assets/{vendor-replit-codemirror-vim-BUqe2Slv.js → vendor-replit-codemirror-vim-BJY5fGLS.js} +1 -1
  65. package/dist/assets/{web-components-BhO08KaW.js → web-components-CLirSfwt.js} +1 -1
  66. package/dist/index.html +4 -4
  67. package/dist/mini-chat.html +3 -3
  68. package/dist/mobile.html +3 -3
  69. package/package.json +1 -1
  70. package/dist/assets/FilesView-DIDB-xK7.js +0 -14
  71. package/dist/assets/index-BZXqJcua.css +0 -1
  72. package/dist/assets/main-CmrF_CaW.js +0 -133
  73. package/dist/assets/renderElectronMiniChatApp-BhXZtZlU.js +0 -1
  74. package/dist/assets/renderMobileApp-DUSTAPWw.js +0 -23
  75. package/dist/assets/usePanelSlide-BRwyEEzi.js +0 -47
@@ -1,133 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-d23o9CKP.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-BhXma4dv.js","assets/vendor-zustand-CnsBKjP5.js","assets/index-BZXqJcua.css","assets/SessionSwitcherDropdown-NbVfnqQQ.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-CouGjZ3A.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-base-ui-DwfTg5wD.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BuDklWi8.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-Wdz6Qsow.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-pXtfpqbT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-CrbeaEAU.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-3xMyV7a2.js","assets/vendor-codemirror-lang-json-BTvAjwkJ.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-C4jEScp7.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-C1Svvdey.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-BloD9GN-.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-qBLdzwMc.js","assets/vendor-codemirror-lang-python-CR2g6ukK.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-Bzf12ODH.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-dWA7qvjr.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/PierreDiffViewer-B38_7NnU.js","assets/web-components-BhO08KaW.js","assets/computeVirtualFileMetrics-BsZulefS.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.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-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.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/VirtualizedFileDiff-B7eVR6Pt.js","assets/isDiffPlainText-DsuyxFXo.js","assets/vendor-diff-C3JhlQdm.js","assets/usePanelSlide-BRwyEEzi.js","assets/permissionStore-BRcQ9Jgt.js","assets/usePanelSlide-BV3KOtdA.css","assets/useInlineCommentController-buNJ3xB4.js","assets/collapsible-CPkWB1VR.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/contextFileOpenGuard-BmmlK5E3.js","assets/FilesView-DIDB-xK7.js","assets/vendor-codemirror-search-BzyfPoRb.js","assets/vendor-replit-codemirror-vim-BUqe2Slv.js","assets/JsonTreeView-By2oGMNK.js","assets/Virtualizer-BxW2CJGB.js","assets/isFilePlainText-CCYoe7us.js","assets/DiagramEditor-Cp22TGpq.js","assets/vendor-react-drawio-Boqanm0j.js","assets/GitView-CkUONO1-.js","assets/CommitSection-BQBmpPVE.js","assets/DiagramView-E4HJ4ZPU.js","assets/SettingsView-C2dCv0r7.js","assets/vendor-qrcode-COsmt6jn.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/SettingsWindow-DsMhdX5H.js"])))=>i.map(i=>d[i]);
2
- import{R as r,j as e,r as Me,e as Bn}from"./vendor-react-DYyjh7Q0.js";import"./vendor-katex-CHD9BdDO.js";import{u as J,x as zn,y as Un,z as Hn,A as an,n as $e,B as Vn,a as ln,C as cn,r as at,D as Kn,E as Xn,F as qn,e as it,G as dn,H as un,I as Gn,l as Yn,J as Jn,K as Qn,L as Zn,t as er,v as tr,o as hn,q as nr}from"./index-BhXma4dv.js";import{_ as Le}from"./vendor-vite-runtime-DD1OZmLC.js";import{e as rr,h as sr,i as or,j as ar,k as ir,l as lr,P as pn,m as cr,T as mn,n as dr,o as ur,p as hr,g as pr,D as mr,d as fr,H as It,C as Lt,A as Ot,S as $t,f as gr,b as xr,c as wr,F as yr}from"./usePanelSlide-BRwyEEzi.js";import{f as be,a0 as Ae,I as z,aw as br,T as Be,y as ze,ax as vr,B as he,z as Ue,ay as Sr,F as wt,az as yt,t as ue,aA as jr,K as bt,L as et,M as fn,aB as gn,a1 as Ft,aC as Cr,D as vt,C as St,E as jt,G as Ct,H as kt,J as kr,aD as Nr,aE as Pr,m as Ie,aF as Er,g as Tr,h as Rr,aG as Ye,aH as Dr,k as _r,aI as Ar,j as Mr,aJ as Ir,Z as Fe,aK as xn,N as wn,aL as Lr,aM as Or,aN as $r,aO as Fr,aP as Wr,aQ as Nt,aR as Pt,aS as Et,o as lt,aT as Br,P as yn,aU as zr,aV as Ur,aW as Tt,R as bn,aX as Hr,aY as Vr,aZ as Kr,a_ as Wt,a$ as Je,b0 as Xr,c as qr,d as Gr,b1 as Yr,b as Bt,r as ut,b2 as Jr,b3 as Qr,b4 as Zr,b5 as vn,b6 as Sn,b7 as es,b8 as ts,b9 as ns,ba as rs,bb as qe,bc as Ge,bd as ss,be as os,bf as as,bg as is,ai as ls,ah as cs,aj as ds,af as us,ak as hs,al as ps,am as ms,at as fs,au as gs,av as xs}from"./SessionSwitcherDropdown-NbVfnqQQ.js";import{v as jn,g as Cn}from"./contextFileOpenGuard-BmmlK5E3.js";import{c as ws,d as zt,T as ys,M as bs,D as vs,e as Ss}from"./vendor-dnd-kit-core-GipZW2tY.js";import{a as js,S as Cs,v as ks,u as Ns}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as Ps}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{u as Ut,a as Ht,m as Vt}from"./vendor-framer-motion-DJASDzNt.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-base-ui-DwfTg5wD.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./permissionStore-BRcQ9Jgt.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./runtimeSurface-CouGjZ3A.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BuDklWi8.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-Wdz6Qsow.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-pXtfpqbT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-CrbeaEAU.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-3xMyV7a2.js";import"./vendor-codemirror-lang-json-BTvAjwkJ.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-C4jEScp7.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-C1Svvdey.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BloD9GN-.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-qBLdzwMc.js";import"./vendor-codemirror-lang-python-CR2g6ukK.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-Bzf12ODH.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-sonner-dWA7qvjr.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";const Kt=280,Xt=280,qt=500,Es=({isOpen:t,isMobile:n,children:s,className:o,topBar:a})=>{const c=J(N=>N.sidebarWidth),y=J(N=>N.setSidebarWidth),[d,f]=r.useState(!1),g=r.useRef(0),v=r.useRef(c||Kt),h=r.useRef(null),u=r.useRef(null),C=r.useRef(null),p=r.useCallback(N=>Math.min(qt,Math.max(Xt,N)),[]),L=r.useCallback(N=>{const w=C.current;w&&(w.style.width=`${N}px`,w.style.minWidth=`${N}px`,w.style.maxWidth=`${N}px`,w.style.setProperty("--oc-left-sidebar-width",`${N}px`))},[]);r.useEffect(()=>{n&&d&&f(!1)},[n,d]),r.useEffect(()=>{d||(h.current=null,u.current=null)},[d]);const P=rr(t);if(n)return null;const I=Math.min(qt,Math.max(Xt,c||Kt)),O=t?I:0,V=N=>{if(t){try{N.currentTarget.setPointerCapture(N.pointerId)}catch{}u.current=N.pointerId,f(!0),g.current=N.clientX,v.current=O,h.current=O,L(O),N.preventDefault()}},_=N=>{if(n||!d||u.current!==N.pointerId)return;const w=N.clientX-g.current,$=p(v.current+w);h.current!==$&&(h.current=$,L($))},j=N=>{if(u.current!==N.pointerId||n)return;try{N.currentTarget.releasePointerCapture(N.pointerId)}catch{}const w=p(h.current??O);u.current=null,h.current=null,f(!1),y(w)},b=d?h.current??O:O,S=d?b:O;return e.jsxs("aside",{ref:C,className:be("relative flex h-full overflow-hidden border-r border-border motion-reduce:transition-none","bg-sidebar",!t&&"border-r-0",o),style:{width:`${S}px`,minWidth:`${S}px`,maxWidth:`${S}px`,"--oc-left-sidebar-width":`${d?b:I}px`,overflowX:"clip",transform:d||P.slidIn?"translateX(0)":"translateX(-100%)",transition:d?"none":P.transition},"aria-hidden":!t||S===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:be("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",d&&"bg-[var(--interactive-border)]"),onPointerDown:V,onPointerMove:_,onPointerUp:j,onPointerCancel:j,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:be("relative z-10 flex h-full shrink-0 flex-col",d&&"pointer-events-none",!t&&"pointer-events-none select-none"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[a,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(Ae,{children:s})})]})]})},Ts=t=>t.slice().sort((n,s)=>n.type!==s.type?n.type==="directory"?-1:1:n.name.localeCompare(s.name)),Pe=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),s=n.startsWith("//");let o=n.replace(/\/+$/g,"");return o=o.replace(/\/+/g,"/"),s&&!o.startsWith("//")&&(o=`/${o}`),o===""?n.startsWith("/")?"/":"":o},kn=(t,n)=>{const s=Pe(n),o=Pe(t).replace(/\/+$/,"");return s===o?".":!o||!s.startsWith(`${o}/`)?s:s.slice(o.length+1)},Rs=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Ds=new Set(["node_modules"]),_s=t=>Ds.has(t),As=t=>{const n=Pe(t);return n==="node_modules"||n.endsWith("/node_modules")||n.includes("/node_modules/")},Ms=8,Oe=new Map,Rt=t=>JSON.stringify([ln(),t]),Is=t=>{const n=Rt(t),s=Oe.get(n);return s?(s.touchedAt=Date.now(),Oe.delete(n),Oe.set(n,s),s):null},ht=t=>{const n=Rt(t),s=Oe.get(n);if(s)return s.touchedAt=Date.now(),s;if(Oe.size>=Ms){const a=Oe.keys().next().value;a!==void 0&&Oe.delete(a)}const o={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Oe.set(n,o),o},Ls=t=>{Oe.delete(Rt(t))},Nn=(t,n)=>e.jsx(wt,{filePath:t,extension:n}),Os=({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}})},$s=({node:t,root:n,isExpanded:s,isActive:o,isBrowserClient:a,status:c,badge:y,permissions:d,downloadFile:f,onSelect:g,onToggle:v,onRevealPath:h,onOpenDialog:u})=>{const C=t.type==="directory",{canRename:p,canCreateFile:L,canCreateFolder:P,canDelete:I,canReveal:O}=d,V=!C&&!!f,_=O&&!a,j=p||L||P||I||V||_,[b,S]=r.useState(!1),[N,w]=r.useState(!1),$=r.useCallback(E=>{j&&(E?.preventDefault(),w(!0))},[j]),T=r.useCallback(()=>{C?v(t.path):g(t)},[C,t,g,v]),H=r.useCallback(E=>{E.stopPropagation(),w(!1),S(!0)},[]),W=({Item:E,Separator:B})=>e.jsxs(e.Fragment,{children:[p&&e.jsxs(E,{onClick:K=>{K.stopPropagation(),u("rename",t)},children:[e.jsx(z,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(E,{onClick:K=>{K.stopPropagation(),yt(t.path).then(ne=>{if(ne.ok){ue.success("Path copied");return}ue.error("Copy failed")})},children:[e.jsx(z,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!C&&f&&e.jsxs(E,{onClick:K=>{K.stopPropagation(),f(t.path).catch(ne=>{console.error("Download failed:",ne),ue.error("Operation failed")})},children:[e.jsx(z,{name:"download",className:"mr-2 h-4 w-4"})," ",a?"Download":"Save"]}),_&&e.jsxs(E,{onClick:K=>{K.stopPropagation(),h(t.path)},children:[e.jsx(z,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",jr()]}),C&&(L||P)&&e.jsxs(e.Fragment,{children:[e.jsx(B,{}),L&&e.jsxs(E,{onClick:K=>{K.stopPropagation(),u("createFile",t)},children:[e.jsx(z,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),P&&e.jsxs(E,{onClick:K=>{K.stopPropagation(),u("createFolder",t)},children:[e.jsx(z,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),I&&e.jsxs(e.Fragment,{children:[e.jsx(B,{}),e.jsxs(E,{onClick:K=>{K.stopPropagation(),u("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(z,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),D=r.useCallback(E=>{const B=kn(n,t.path);!B||B==="."||(E.dataTransfer.setData("application/x-pichamber-file-path",B),E.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(sr,{open:N,onOpenChange:w,children:[e.jsxs(or,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:$}),children:[e.jsxs("button",{type:"button",onClick:T,onContextMenu:$,draggable:!0,onDragStart:D,className:be("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",o?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[C?s?e.jsx(z,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(z,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):Nn(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!C&&c&&e.jsx(Os,{status:c}),C&&y&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[y.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",y.modified]}),y.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",y.added]})]})]}),j&&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(br,{open:b,onOpenChange:S,children:[e.jsxs(Be,{children:[e.jsx(ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(vr,{asChild:!0,children:e.jsx(he,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:H,title:"File menu","aria-label":"File menu",children:e.jsx(z,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(Ue,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(Sr,{align:"end",side:"bottom",onCloseAutoFocus:()=>S(!1),children:W({Item:Nr,Separator:Pr})})]})})]}),e.jsx(ar,{className:"min-w-[180px]",children:W({Item:ir,Separator:lr})})]})},Fs=(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,Ws=r.memo($s,Fs),Bs=()=>{const{files:t,runtime:n}=bt(),s=zn(n.platform),o=et()??"",a=Pe(o.trim()),c=Un(),y=Hn(),d=an(x=>x.searchFiles),f=J(x=>x.openContextFile),g=fn(o),[v,h]=r.useState(""),u=gn(v,200),C=r.useRef(null),[p,L]=r.useState([]),[P,I]=r.useState(!1),[O,V]=r.useState({}),[_,j]=r.useState({}),b=r.useRef(new Set),S=r.useRef(new Set),N=r.useRef(null);r.useEffect(()=>{if(!a){V({}),j({}),b.current=new Set;return}const x=Is(a);x?(V({...x.childrenByDir}),j({...x.loadErrorsByDir}),b.current=new Set(x.loadedDirs)):(V({}),j({}),b.current=new Set)},[a]),r.useEffect(()=>{if(!a)return;const x=ht(a);x.childrenByDir=O},[a,O]),r.useEffect(()=>{if(!a)return;const x=ht(a);x.loadErrorsByDir=_},[a,_]),r.useEffect(()=>{if(!a)return;const x=ht(a);x.loadedDirs=new Set(b.current)},[a,O,_]),r.useEffect(()=>()=>{if(!a)return;const x=Oe.get(a);x&&x.loadedDirs.size===0&&Object.keys(x.childrenByDir).length===0&&Ls(a)},[a]);const w=r.useMemo(()=>[],[]),$=r.useMemo(()=>[],[]),T=$e(x=>a?x.byRoot[a]?.expandedPaths??w:w),H=$e(x=>a?x.byRoot[a]?.selectedPath??null:null),W=$e(x=>x.setSelectedPath),D=$e(x=>x.addOpenPath),E=$e(x=>x.removeOpenPathsByPrefix),B=$e(x=>x.toggleExpandedPath),K=$e(x=>x.collapseAllExpandedPaths),ne=J(x=>a?x.contextPanelByDirectory[a]?.tabs??$:$),fe=r.useMemo(()=>new Set(ne.map(x=>x.mode==="file"?x.targetPath:null).filter(x=>typeof x=="string"&&x.length>0).map(x=>Pe(x))),[ne]),[G,ie]=r.useState(null),[te,ce]=r.useState(null),[pe,je]=r.useState(""),[ge,xe]=r.useState(!1),se=!!t.writeFile,Ce=!!t.createDirectory,ke=!!t.rename,M=!!t.delete,F=!!t.revealPath,X=r.useMemo(()=>({canRename:ke,canCreateFile:se,canCreateFolder:Ce,canDelete:M,canReveal:F}),[ke,se,Ce,M,F]),Q=r.useCallback(x=>{t.revealPath&&t.revealPath(x).catch(()=>{ue.error("Failed to reveal path")})},[t]),oe=r.useCallback((x,R)=>{ie(x),ce(R),je(x==="rename"&&R.name||""),xe(!1)},[]),ye=r.useCallback((x,R)=>{const ae=R.filter(A=>A&&typeof A.name=="string"&&A.name.length>0).filter(A=>c||!A.name.startsWith(".")).filter(A=>y||!_s(A.name)).map(A=>{const ee=A.name,U=Pe(A.path||""),me=U?Rs(U)?U:Pe(`${x}/${U}`):Pe(`${x}/${ee}`),l=A.isDirectory?"directory":"file",q=l==="file"&&ee.includes(".")?ee.split(".").pop()?.toLowerCase():void 0;return{name:ee,path:me,type:l,extension:q}});return Ts(ae)},[y,c]),de=r.useCallback(async(x,R)=>{const ae=Pe(x.trim());if(!ae||b.current.has(ae)||S.current.has(ae))return;S.current=new Set(S.current),S.current.add(ae);const A=t.listDirectory?t.listDirectory(ae).then(ee=>ee.entries.map(U=>({name:U.name,path:U.path,isDirectory:U.isDirectory}))):Vn(ae).then(ee=>ee.map(U=>({name:U.name,path:U.path,isDirectory:U.isDirectory})));try{const ee=await A;if(R?.())return;const U=ye(ae,ee);b.current=new Set(b.current),b.current.add(ae),j(me=>{if(!me[ae])return me;const l={...me};return delete l[ae],l}),V(me=>({...me,[ae]:U}))}catch(ee){if(R?.())return;const U=ee instanceof Error?ee.message:String(ee??"");console.error("Failed to load sidebar directory:",ee),j(me=>({...me,[ae]:U}))}finally{S.current=new Set(S.current),S.current.delete(ae)}},[t,ye]),ve=r.useCallback(async()=>{if(!a)return;N.current?.abort();const x=new AbortController;N.current=x;try{const ae=($e.getState().byRoot[a]?.expandedPaths??[]).map(U=>Pe(U)).filter(U=>!!U&&U!==a&&U.startsWith(`${a}/`)),A=[a,...ae];b.current=new Set(b.current);for(const U of A)b.current.delete(U);j(U=>{if(Object.keys(U).length===0)return U;const me={...U};let l=!1;for(const q of A)q in me&&(delete me[q],l=!0);return l?me:U});const ee=()=>x.signal.aborted;await de(a,ee);for(let U=0;U<ae.length&&!x.signal.aborted;U+=3){const me=ae.slice(U,U+3);await Promise.all(me.map(l=>de(l,ee)))}}catch(R){if(x.signal.aborted)return;console.error("Failed to refresh sidebar tree:",R)}finally{N.current===x&&(N.current=null)}},[de,a]),Ee=r.useCallback(async x=>{if(!x){await ve();return}const R=Pe(x);b.current=new Set(b.current),b.current.delete(R),S.current=new Set(S.current),S.current.delete(R),await de(R)},[de,ve]);r.useEffect(()=>{a&&(N.current?.abort(),b.current=new Set,S.current=new Set,j({}),V(x=>Object.keys(x).length===0?x:{}),de(a))},[de,a,c,y]),r.useEffect(()=>{if(!a||T.length===0)return;const x=T.map(A=>Pe(A)).filter(A=>!!A&&A!==a&&A.startsWith(`${a}/`)&&!b.current.has(A)&&!S.current.has(A)).sort((A,ee)=>A.split("/").length-ee.split("/").length);if(x.length===0)return;let R=!1;const ae=()=>R;return(async()=>{for(let A=0;A<x.length&&!R;A+=3){const ee=x.slice(A,A+3);await Promise.all(ee.map(U=>de(U,ae)))}})(),()=>{R=!0}},[T,de,a]),r.useEffect(()=>{if(!o){L([]),I(!1);return}const x=u.trim();if(!x){L([]),I(!1);return}let R=!1;return I(!0),d(o,x,150,{includeHidden:c,respectGitignore:!y,type:"file"}).then(ae=>{if(R)return;const ee=ae.filter(U=>y||!As(U.path)).map(U=>({name:U.name,path:Pe(U.path),type:"file",extension:U.extension,relativePath:U.relativePath}));L(ee)}).catch(()=>{R||L([])}).finally(()=>{R||I(!1)}),()=>{R=!0}},[o,u,d,c,y]);const Te=r.useMemo(()=>{const x=new Map;if(!g?.files)return x;for(const R of g.files)R.index==="A"||R.working_dir==="?"?x.set(R.path,"git-added"):R.index==="D"?x.set(R.path,"git-deleted"):(R.index==="M"||R.working_dir==="M")&&x.set(R.path,"git-modified");return x},[g]),De=r.useMemo(()=>{const x=new Map;if(!g?.files||!a)return x;for(const R of g.files){const ae=R.index==="M"||R.working_dir==="M",A=R.index==="A"||R.working_dir==="?";if(!ae&&!A)continue;const ee=R.path.split("/");if(ee.length<=1)continue;let U=a;for(let me=0;me<ee.length-1;me++){U=`${U}/${ee[me]}`;let l=x.get(U);l||(l={modified:0,added:0},x.set(U,l)),ae&&l.modified++,A&&l.added++}}return x},[g,a]),k=r.useCallback(x=>{if(fe.has(x))return"open";if(Te.size===0)return null;const R=x.startsWith(a+"/")?x.slice(a.length+1):x;return Te.get(R)??null},[fe,Te,a]),re=r.useCallback(x=>{if(De.size===0)return null;const R=De.get(x);return R&&R.modified+R.added>0?R:null},[De]),Z=r.useCallback(async x=>{if(!a)return;const R=await jn(t,x.path,{directory:a});if(!R.ok){ue.error(Cn(R.reason));return}W(a,x.path),D(a,x.path),f(a,x.path)},[D,t,f,a,W]),i=r.useCallback(async x=>{const R=Pe(x);a&&(B(a,R),b.current.has(R)||await de(R))},[de,a,B]),m=r.useCallback(async x=>{if(x?.preventDefault(),!te||!G)return;xe(!0);const R=()=>xe(!1),ae=()=>ie(null);if(G==="createFile"){if(!pe.trim()){ue.error("Filename is required"),R();return}if(!t.writeFile){ue.error("Write not supported"),R();return}const A=te.path,ee=A?`${A}/`:"",U=Pe(`${ee}${pe.trim()}`);await t.writeFile(U,"").then(async me=>{me.success&&(ue.success("File created"),await Ee(A)),ae()}).catch(()=>ue.error("Operation failed")).finally(R);return}if(G==="createFolder"){if(!pe.trim()){ue.error("Folder name is required"),R();return}const A=te.path,ee=A?`${A}/`:"",U=Pe(`${ee}${pe.trim()}`);await t.createDirectory(U).then(async me=>{me.success&&(ue.success("Folder created"),await Ee(A)),ae()}).catch(()=>ue.error("Operation failed")).finally(R);return}if(G==="rename"){if(!pe.trim()){ue.error("Name is required"),R();return}if(!t.rename){ue.error("Rename not supported"),R();return}const A=te.path,ee=A.split("/").slice(0,-1).join("/"),U=ee?`${ee}/`:"",me=Pe(`${U}${pe.trim()}`);await t.rename(A,me).then(async l=>{l.success&&(ue.success("Renamed successfully"),await Ee(ee),a&&E(a,A),(H===A||H&&H.startsWith(`${A}/`))&&W(a,null)),ae()}).catch(()=>ue.error("Operation failed")).finally(R);return}if(G==="delete"){if(!t.delete){ue.error("Delete not supported"),R();return}const A=te.path,ee=A.split("/").slice(0,-1).join("/");await t.delete(A).then(async U=>{U.success&&(ue.success("Deleted successfully"),await Ee(ee),a&&E(a,A),(H===A||H&&H.startsWith(A+"/"))&&W(a,null)),ae()}).catch(()=>ue.error("Operation failed")).finally(R);return}R()},[G,te,pe,t,Ee,E,a,H,W]);function Y(x,R){const ae=O[x]??[];return ae.map((A,ee)=>{const U=A.type==="directory",me=U&&T.includes(A.path),l=H===A.path,q=ee===ae.length-1;return e.jsxs("li",{className:"relative",children:[R>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),q&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(Ws,{node:A,root:a,isExpanded:me,isActive:l,isBrowserClient:s,status:U?void 0:k(A.path),badge:U?re(A.path):void 0,permissions:X,downloadFile:t.downloadFile,onSelect:Z,onToggle:i,onRevealPath:Q,onOpenDialog:oe}),U&&me&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[_[A.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:_[A.path],children:_[A.path]}),e.jsxs(he,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Ee(A.path)},children:[e.jsx(z,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,Y(A.path,R+1)]})]},A.path)})}const le=!!(a&&O[a]),Ne=a?_[a]:null;return e.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col gap-2 border-b border-border/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[se&&e.jsxs(Be,{children:[e.jsx(ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(he,{variant:"ghost",size:"sm",onClick:()=>oe("createFile",{path:o,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(z,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx(Ue,{side:"bottom",sideOffset:6,children:"New File"})]}),Ce&&e.jsxs(Be,{children:[e.jsx(ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(he,{variant:"ghost",size:"sm",onClick:()=>oe("createFolder",{path:o,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(z,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx(Ue,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Be,{children:[e.jsx(ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(he,{variant:"ghost",size:"sm",onClick:()=>{ve()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(z,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx(Ue,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Be,{children:[e.jsx(ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(he,{variant:"ghost",size:"sm",onClick:()=>{a&&K(a)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(z,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx(Ue,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]}),e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(z,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(Ft,{ref:C,value:v,onChange:x=>h(x.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),v.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:()=>{h(""),C.current?.focus()},children:e.jsx(z,{name:"close",className:"h-4 w-4"})}):null]})]}),e.jsx(Cr,{outerClassName:"flex-1 min-h-0",className:"p-2",children:e.jsx("ul",{className:"flex flex-col",children:P?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(z,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):p.length>0?p.map(x=>{const R=H===x.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>Z(x),draggable:!0,onDragStart:ae=>{const A=x.relativePath||kn(a??"",x.path);!A||A==="."||(ae.dataTransfer.setData("application/x-pichamber-file-path",A),ae.dataTransfer.effectAllowed="copy")},className:be("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",R?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:x.path,children:[Nn(x.path,x.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:x.relativePath??x.path})]})},x.path)}):Ne?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:Ne}),e.jsxs(he,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ve()},children:[e.jsx(z,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):le&&a?Y(a,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(vt,{open:!!G,onOpenChange:x=>!x&&ie(null),children:e.jsxs(St,{children:[e.jsxs(jt,{children:[e.jsxs(Ct,{children:[G==="createFile"&&"Create File",G==="createFolder"&&"Create Folder",G==="rename"&&"Rename",G==="delete"&&"Delete"]}),e.jsxs(kt,{children:[G==="createFile"&&`Create a new file in ${te?.path??"root"}`,G==="createFolder"&&`Create a new folder in ${te?.path??"root"}`,G==="rename"&&`Rename ${te?.name??""}`,G==="delete"&&`Are you sure you want to delete ${te?.name??""}? This action cannot be undone.`]})]}),G!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(Ft,{value:pe,onChange:x=>je(x.target.value),placeholder:G==="rename"?"New name":"Name",onKeyDown:x=>{x.key==="Enter"&&m()},autoFocus:!0})}),e.jsxs(kr,{children:[e.jsx(he,{variant:"outline",onClick:()=>ie(null),disabled:ge,children:"Cancel"}),e.jsx(he,{variant:G==="delete"?"destructive":"default",onClick:()=>{m()},disabled:ge||G!=="delete"&&!pe.trim(),children:ge?e.jsx(z,{name:"loader-4",className:"size-4 animate-spin"}):G==="delete"?"Delete":"Confirm"})]})]})})]})},Dt=t=>t,xt=t=>{const n=Dt(t).type;return typeof n=="string"?n:""},zs=t=>{const n=Dt(t).tool;return typeof n=="string"?n:""},Us=t=>{const n=Dt(t).text;return typeof n=="string"?n:""},Hs=t=>{const n=xt(t);return n==="tool"?zs(t).trim().toLowerCase()||"tool":n||"unknown"},Vs=t=>{if(t.length===0)return"";const n=[];for(const s of t){const o=Hs(s);n.includes(o)||n.push(o)}return n.join(" + ")},Ks=t=>t.replace(/\s+/g," ").trim(),Xs=t=>{for(const s of t)if(xt(s)==="text"){const o=Ks(Us(s));if(o.length===0)continue;return o}const n=t.filter(s=>xt(s)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},qs=(t,n,s)=>`${s(t)} / ${s(n)}`,Gs=t=>{if(t==="12h")return!0;if(t==="24h")return!1},Ys=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const s=Gs(n);return new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:s===!1?"2-digit":"numeric",minute:"2-digit",...s===void 0?{}:{hour12:s}})},Js={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},nt={user:0,assistant:0,tool:0,other:0},Qs=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,pt=t=>Mr(t),Zs=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},_e=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,s)=>n+_e(s),0):t&&typeof t=="object"?Object.values(t).reduce((n,s)=>n+_e(s),0):0,eo=(t,n)=>{const s=t,o=typeof s.type=="string"?s.type:"";if(o==="reasoning")return{...nt,assistant:_e(s.text)+_e(s.content)};const a=Zs(s.text,s.content,s.value,s.source?.value,s.source?.text?.value);return o==="tool"||n==="tool"?{user:0,assistant:0,tool:_e(s.input)+_e(s.output)+_e(s.error)+_e(s.call?.input)+_e(s.call?.output)+_e(s.call?.error)+_e(s.raw)+Math.round(_e(s.metadata)*.25)+Math.round(_e(s.state)*.1),other:0}:n==="user"?{user:a.length,assistant:0,tool:0,other:0}:n==="assistant"?{user:0,assistant:a.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:a.length}},Gt=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),to=t=>{const n=Ye(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},no=(t,n)=>{if(t.length===0)return{...nt};const s=t.reduce((o,a)=>{const c=to(a);let y={...nt};for(const d of a.parts)y=Gt(y,eo(d,c));return Gt(o,y)},{...nt});return s.user+=n.length,{user:Math.ceil(s.user/4),assistant:Math.ceil(s.assistant/4),tool:Math.ceil(s.tool/4),other:Math.ceil(s.other/4)}},We=t=>t.toLocaleString("en-US"),ro=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),so=(t,n)=>!t||!Number.isFinite(t)?"-":Ir(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),oo=(t,n,s)=>{const o=t.find(c=>c.id===n),a=o?.models?.find(c=>c.id===s);return{providerName:o?.name||n||"-",modelName:a?.name||s||"-",contextLimit:typeof a?.limit?.context=="number"?a.limit.context:null}},ao=()=>{const t=J(p=>p.timeFormatPreference),[n,s]=r.useState({}),[o,a]=r.useState(null),c=r.useRef(null),y=Ie(p=>p.currentSessionId),d=Ie(p=>p.currentSessionDirectory),f=Er(),g=Tr(y??""),v=Rr(p=>p.providers);r.useEffect(()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null),s(p=>Object.keys(p).length>0?{}:p),a(null)},[d,y]),r.useEffect(()=>()=>{c.current!==null&&(window.clearTimeout(c.current),c.current=null)},[]);const h=r.useCallback(async(p,L)=>{(await yt(L)).ok?(a(p),c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{a(I=>I===p?null:I),c.current=null},2e3)):a(null)},[]),u=r.useMemo(()=>{const p=y?f.find(G=>G.id===y)??null:null,L=g.filter(G=>Ye(G.info).role==="assistant"),P=g.filter(G=>Ye(G.info).isUser);let I=null;for(let G=L.length-1;G>=0;G-=1){const ie=L[G];if(pt(ie).total>0){I=ie;break}}const O=I?pt(I):Js,V=I?.info?.usage,_=Dr({input:O.input,cache:{read:O.cacheRead,write:O.cacheWrite}}),j=L.reduce((G,ie)=>{const te=Qs(ie.info.cost);return G+te},0),b=I?.info?.model??null,S=oo(v,b?.providerID||"",b?.modelID||""),N=S.contextLimit,w=V?_r(V):O.total,$=N&&N>0?Math.min(999,w/N*100):0,T=[...g].reverse().find(G=>Ye(G.info).isUser&&typeof G.info.system=="string")?.info?.system||"",H=no(g,T),W=H.user,D=H.assistant,E=H.tool,B=V?0:Math.max(0,O.input-W-D-E),K=W+D+E+B,ne=g[0]?.info?.time?.created,fe=g.length>0?g[g.length-1]?.info?.time?.created:null;return{sessionTitle:p?.title||"Untitled Session",messagesCount:g.length,userMessagesCount:P.length,assistantMessagesCount:L.length,createdAt:p?.time?.created??ne??null,lastActivityAt:fe??p?.time?.created??null,providerModel:S,tokenBreakdown:O,usagePercent:$,cacheHitRate:_,totalAssistantCost:j,contextLimit:N,contextWindowTokens:w,hasUsage:V!==void 0,breakdown:{user:W,assistant:D,tool:E,other:B},breakdownTotal:K}},[y,v,g,f]);if(!y)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 C=[{key:"user",label:"User",value:u.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:u.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool Calls",value:u.breakdown.tool,color:"var(--status-warning)"},...u.hasUsage?[]:[{key:"other",label:"Other",value:u.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:u.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:[u.providerModel.providerName," / ",u.providerModel.modelName]}),u.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:so(u.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(u.contextWindowTokens),u.contextLimit?` / ${We(u.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:u.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,u.usagePercent)}%`,backgroundColor:u.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:`${u.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:We(u.messagesCount)},{label:"User",value:We(u.userMessagesCount)},{label:"Assistant",value:We(u.assistantMessagesCount)},{label:"Cost",value:ro(u.totalAssistantCost)}].map(p=>e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:p.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:p.value})]},p.label))}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:"Last Assistant Message"}),e.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:"Input",value:u.tokenBreakdown.input,format:"count"},{label:"Output",value:u.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:u.tokenBreakdown.reasoning,format:"count"},{label:"Cache Read",value:u.tokenBreakdown.cacheRead,format:"count"},{label:"Cache Write",value:u.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache Hit",value:u.cacheHitRate.hasInput?u.cacheHitRate.percent:null,format:"percent"}].map(p=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:p.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:p.value!==null&&p.value!==void 0?p.format==="percent"?`${p.value.toFixed(1)}%`:We(p.value):"—"})]},p.label))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:C.map(p=>p.value<=0||u.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${p.value/u.breakdownTotal*100}%`,backgroundColor:p.color}},p.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:C.map(p=>{const L=u.breakdownTotal>0?p.value/u.breakdownTotal*100:0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:p.color}}),e.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[p.label," ",e.jsxs("span",{className:"tabular-nums",children:[L.toFixed(0),"%"]})]})]},p.key)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Raw Messages"}),e.jsx("div",{className:"mt-2.5 space-y-1",children:[...g].reverse().map(p=>{const P=Ye(p.info).role,I=P==="assistant",O=P==="user",V=n[p.info.id]===!0,_=o===p.info.id,j=p.info.time?.created??null,b=Vs(p.parts),S=I?pt({info:p.info,parts:p.parts}):null,N=O?Xs(p.parts):"",w=Ys(j,t),$=b||"—",T=S?qs(S.input,S.output,We):"",H=P||"unknown",W=b?`${H}: ${b}`:H,D=V?JSON.stringify({info:p.info,parts:p.parts},null,2):"";return e.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[e.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":V,onClick:()=>{s(E=>({...E,[p.info.id]:E[p.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:I?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[O?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",N]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:I?$:W}),I&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:T})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:w})]})}),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:E=>{E.stopPropagation(),h(p.info.id,D)},"aria-label":_?"Copied":"Copy JSON",title:_?"Copied":"Copy",children:_?e.jsx(z,{name:"check",className:"size-3.5"}):e.jsx(z,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Ar,{language:"json",code:D,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},p.info.id)})})]})]})})},io="x-pichamber-preview-target-error",lo=t=>{const n=t.get(io);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},co=(t,n)=>lo(t)?n?"stop-retrying":"retry-registration":"none",uo=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},Yt=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Ve=t=>{if(!t||typeof t!="object")return!1;const n=t,s=n.bounds;return typeof n.tag=="string"&&typeof n.text=="string"&&typeof n.selector=="string"&&typeof n.path=="string"&&!!s&&typeof s?.x=="number"&&typeof s?.y=="number"&&typeof s?.width=="number"&&typeof s?.height=="number"&&uo(n.center)&&Yt(n.attributes)&&Yt(n.computedStyle)&&Array.isArray(n.ancestry)},_t=({pageUrl:t,viewport:n,devicePixelRatio:s,target:o,screenshotAttached:a,intro:c})=>{const y=o.text.trim(),d=Object.entries(o.attributes).map(([C,p])=>`${C}="${p}"`).join(" "),f=o.computedStyle,g=o.bounds,v=o.center,h=c.replace(/[.:]+$/g,""),u=o.ancestry.map(C=>C.selectorPart).join(" > ");return[`${h}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${s}`,`Screenshot: ${a?"attached":"not attached"}`,`Element: ${o.tag}`,y?`Text: ${y}`:null,`- Selector: ${o.selector}`,`- Path: ${o.path}`,u?`- Ancestry: ${u}`:null,d?`- Attributes: ${d}`:null,`- Bounds: x=${Math.round(g.x)}, y=${Math.round(g.y)}, width=${Math.round(g.width)}, height=${Math.round(g.height)}`,`- Center: x=${Math.round(v.x)}, y=${Math.round(v.y)}`,`Styles: display=${f.display}; position=${f.position}; font=${f.fontWeight} ${f.fontSize} / ${f.lineHeight} ${f.fontFamily}; color=${f.color}; background=${f.backgroundColor}; z-index=${f.zIndex}`].filter(C=>typeof C=="string").join(`
3
- `)},Pn=async(t,n)=>{if(typeof window<"u")try{const s=t.getBoundingClientRect(),o=await cn("desktop_capture_page_rect",{x:s.left,y:s.top,width:s.width,height:s.height});if(!o)throw new Error("Desktop screenshot capture is not available");const a=new Image;await new Promise((p,L)=>{a.onload=()=>p(),a.onerror=()=>L(new Error("Failed to load desktop preview screenshot")),a.src=`data:${o.mime};base64,${o.base64}`});const c=Math.max(1,a.naturalWidth||o.width||Math.floor(s.width)),y=Math.max(1,a.naturalHeight||o.height||Math.floor(s.height)),f=Math.min(1,1200/c),g=document.createElement("canvas");g.width=Math.floor(c*f),g.height=Math.floor(y*f);const v=g.getContext("2d");if(!v)return null;v.scale(f,f),v.drawImage(a,0,0,c,y);const h=c/Math.max(1,s.width),u=y/Math.max(1,s.height);v.fillStyle="rgba(37, 99, 235, 0.28)",v.strokeStyle="rgb(37, 99, 235)",v.lineWidth=Math.max(2,2*h),v.fillRect(n.bounds.x*h,n.bounds.y*u,n.bounds.width*h,n.bounds.height*u),v.strokeRect(n.bounds.x*h,n.bounds.y*u,n.bounds.width*h,n.bounds.height*u);const C=await new Promise(p=>g.toBlob(p,"image/jpeg",.82));return C?new File([C],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(s){return console.warn("[preview] failed to capture annotation screenshot:",s),null}return await No(t,n)},At=async(t,n,s,o,a,c)=>{if(!t)return null;try{const y=new Image;await new Promise((P,I)=>{y.onload=()=>P(),y.onerror=()=>I(new Error("Failed to load desktop browser screenshot")),y.src=`data:image/jpeg;base64,${t}`});const d=Math.max(1,y.naturalWidth||n),f=Math.max(1,y.naturalHeight||s),v=Math.min(1,1200/d),h=document.createElement("canvas");h.width=Math.floor(d*v),h.height=Math.floor(f*v);const u=h.getContext("2d");if(!u)return null;u.scale(v,v),u.drawImage(y,0,0,d,f);const C=d/Math.max(1,o||d),p=f/Math.max(1,a||f);u.fillStyle="rgba(37, 99, 235, 0.14)",u.strokeStyle="rgb(37, 99, 235)",u.lineWidth=Math.max(2,2*C),u.fillRect(c.bounds.x*C,c.bounds.y*p,c.bounds.width*C,c.bounds.height*p),u.strokeRect(c.bounds.x*C,c.bounds.y*p,c.bounds.width*C,c.bounds.height*p);const L=await new Promise(P=>h.toBlob(P,"image/jpeg",.82));return L?new File([L],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Ke="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Re=new Map,mt=new Map,ho=3e4,Mt=t=>{const n=Re.get(t);return n?n.expiresAt-Date.now()<=ho?(Re.delete(t),null):n:null},po=t=>{try{return new URL(t).origin}catch{return t}};function En(t){const n="#ffffff",s=t.defaultView??window;try{const o=t.body?s.getComputedStyle(t.body).backgroundColor:"";if(o&&o!=="rgba(0, 0, 0, 0)"&&o!=="transparent")return o;const a=s.getComputedStyle(t.documentElement).backgroundColor;if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a}catch{}return n}const Tn=t=>new Promise((n,s)=>{const o=new FileReader;o.onloadend=()=>n(typeof o.result=="string"?o.result:Ke),o.onerror=()=>s(o.error??new Error("Failed to read image blob")),o.readAsDataURL(t)}),mo=async(t,n=.82)=>{const s=await new Promise(o=>t.toBlob(o,"image/jpeg",n));return s&&(await Tn(s)).split(",",2)[1]||""},fo=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},rt=(...t)=>{fo()&&console.info("[preview-capture]",...t)},Rn=(t,n=8)=>{const s=[];try{const o=t.querySelectorAll("*");for(const a of o){const c=a.scrollTop||0,y=a.scrollLeft||0;if(c<=0&&y<=0)continue;const d=a.tagName.toLowerCase(),f=a.id?`#${a.id}`:"",g=typeof a.className=="string"&&a.className?`.${a.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(s.push({selector:`${d}${f}${g}`,scrollTop:c,scrollLeft:y,clientWidth:a.clientWidth,clientHeight:a.clientHeight,scrollWidth:a.scrollWidth,scrollHeight:a.scrollHeight}),s.length>=n)break}}catch{}return s},Qe="data-oc-fixed-pin",go=(t,n,s)=>{if(n<=0&&s<=0)return()=>{};const o=t.defaultView;if(!o)return()=>{};const a=[],c=[];try{for(const y of t.querySelectorAll("*")){if(o.getComputedStyle(y).position!=="fixed")continue;const d=y.getBoundingClientRect();if(!(d.width>0&&d.height>0))continue;y.setAttribute(Qe,JSON.stringify({top:d.top+s,left:d.left+n,width:d.width,height:d.height})),a.push(y);const f=y.tagName.toLowerCase(),g=typeof y.className=="string"&&y.className?`.${y.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";c.push({selector:`${f}${g}`,top:Math.round(d.top),left:Math.round(d.left),width:Math.round(d.width),height:Math.round(d.height)})}}catch{}return rt("tagged fixed elements",c),()=>{for(const y of a)try{y.removeAttribute(Qe)}catch{}}},xo={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const s of n.querySelectorAll(`[${Qe}]`)){let o;try{o=JSON.parse(s.getAttribute(Qe)||"")}catch{continue}s.style.setProperty("position","absolute","important"),s.style.setProperty("top",`${o.top}px`,"important"),s.style.setProperty("left",`${o.left}px`,"important"),s.style.setProperty("right","auto","important"),s.style.setProperty("bottom","auto","important"),s.style.setProperty("width",`${o.width}px`,"important"),s.style.setProperty("height",`${o.height}px`,"important"),s.removeAttribute(Qe)}}},He="data-oc-scroll-pin",wo=t=>{const n=[],s=Rn(t,64);try{const c=t.documentElement,y=t.body;for(const d of t.querySelectorAll("*")){const f=d.scrollTop||0,g=d.scrollLeft||0;if(f<=0&&g<=0)continue;const v=d!==c&&d!==y;v&&d.setAttribute(He,JSON.stringify({top:f,left:g})),n.push({el:d,top:f,left:g,tagged:v})}}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(He)}catch{}},snapshot:s}},yo={name:"oc-nested-scroll",afterClone(t){const n=t?.clone;if(!n||typeof n.querySelectorAll!="function")return;const s=n.ownerDocument;if(s)for(const o of n.querySelectorAll(`[${He}]`)){let a;try{a=JSON.parse(o.getAttribute(He)||"")}catch{o.removeAttribute(He);continue}const c=`translate(${-a.left}px, ${-a.top}px)`,y=o.children.length===1&&o.firstElementChild instanceof HTMLElement&&o.firstElementChild.style.willChange==="transform"?o.firstElementChild:null;if(y)y.style.transform=c;else{o.style.overflow="hidden";const d=s.createElement("div");for(d.style.transform=c,d.style.willChange="transform",d.style.display="inline-block",d.style.width="100%";o.firstChild;)d.appendChild(o.firstChild);o.appendChild(d)}o.removeAttribute(He)}}},ft=async(t,n)=>{try{const s=await fetch(t,{credentials:n});return s.ok?await Tn(await s.blob()):null}catch{return null}},bo=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,s=Mt(n);if(s)return`${s.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const o=mt.get(n),a=o??(async()=>{try{const y=await at("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!y.ok)return Re.delete(n),null;const d=await y.json(),f=typeof d.proxyBasePath=="string"?d.proxyBasePath:"",g=typeof d.expiresAt=="number"?d.expiresAt:0;if(!f)return Re.delete(n),null;const v={proxyBasePath:f,expiresAt:g};return Re.set(n,v),v}catch{return Re.delete(n),null}finally{mt.delete(n)}})();o||mt.set(n,a);const c=await a;return c?`${c.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},Dn=async(t,n)=>{if(!t||t.startsWith("data:"))return t;try{const s=new URL(t,n.baseURI);if(s.origin===window.location.origin||s.protocol!=="http:"&&s.protocol!=="https:")return await ft(s.toString(),"include")??Ke;const o=await bo(s),a=o?await ft(o,"include"):null;return a||(await ft(s.toString(),"omit")??Ke)}catch{return Ke}},vo=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const s=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let o=t;for(const a of s){const c=a[2]||"";if(!c||c.startsWith("data:"))continue;const y=await Dn(c,n);o=o.replace(a[0],`url("${y}")`)}return o},Jt=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),_n=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},So=t=>{const n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;const s=Number.parseFloat(t.fontSize);return Number.isFinite(s)&&s>0?s*1.2:16},jo=(t,n,s)=>{const o=[],a=t.defaultView??window,y=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const d of y){const f=d.textContent?.replace(/\s+/g," ").trim()??"";if(!f||!f.includes(" "))continue;const g=d.getBoundingClientRect();if(g.width<=0||g.height<=0||g.right<0||g.bottom<0||g.left>n||g.top>s)continue;const v=a.getComputedStyle(d);if(v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)continue;const h=v.getPropertyValue("text-wrap"),u=v.getPropertyValue("text-wrap-mode"),C=v.whiteSpace.includes("nowrap")||h==="nowrap"||u==="nowrap",p=g.height<=So(v)*1.7;!C&&(!p||g.width>n*.72)||(o.push(_n(d)),d.style.whiteSpace="nowrap",d.style.overflowWrap="normal",d.style.wordBreak="normal",d.style.setProperty("text-wrap","nowrap"),d.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let d=o.length-1;d>=0;d-=1)o[d]?.()}},Co=(t,n,s,o)=>{const a=[],c=t.defaultView??window,y=c.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,d=c.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,f=Array.from(t.querySelectorAll("*")).filter(g=>{const v=c.getComputedStyle(g);if(v.position!=="fixed"||v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)return!1;const h=g.getBoundingClientRect();return h.width>0&&h.height>0&&h.right>=0&&h.bottom>=0&&h.left<=n&&h.top<=s}).filter((g,v,h)=>!h.some((u,C)=>C<v&&u.contains(g)));for(const g of f){const v=g.getBoundingClientRect(),h=c.getComputedStyle(g),u=Math.ceil(v.width)+8,C=Math.ceil(v.height)+2;o?.add(g),a.push(_n(g)),g.style.position="absolute",g.style.top=`${v.top+d}px`,g.style.left=`${v.left+y}px`,g.style.right="auto",g.style.bottom="auto",g.style.width=`${u}px`,g.style.minWidth=`${u}px`,g.style.height=`${C}px`,g.style.minHeight=`${C}px`,g.style.margin="0",g.style.boxSizing="border-box",g.style.transform="none",h.zIndex!=="auto"&&(g.style.zIndex=h.zIndex)}return()=>{for(let g=a.length-1;g>=0;g-=1)a[g]?.()}},An=async(t,n,s,o={})=>{const a=[],c=t.defaultView??window,y=h=>{if(h===t.documentElement||h===t.body)return!0;try{const u=h.getBoundingClientRect();return u.width>0&&u.height>0&&u.right>=0&&u.bottom>=0&&u.left<=n&&u.top<=s}catch{return!1}};if(o.applyLayoutWorkarounds){const h=new WeakSet;a.push(Co(t,n,s,h)),a.push(jo(t,n,s))}const d=new Map;for(const h of Array.from(t.images))d.set(h,h.currentSrc||h.src||h.getAttribute("src")||"");const f=Array.from(t.querySelectorAll("picture"));for(const h of f){const u=Array.from(h.querySelectorAll("source"));if(u.length===0)continue;const C=u.map(p=>({source:p,srcset:p.getAttribute("srcset"),sizes:p.getAttribute("sizes")}));a.push(()=>{for(const p of C)p.srcset===null?p.source.removeAttribute("srcset"):p.source.setAttribute("srcset",p.srcset),p.sizes===null?p.source.removeAttribute("sizes"):p.source.setAttribute("sizes",p.sizes)});for(const p of u)p.removeAttribute("srcset"),p.removeAttribute("sizes")}const g=Array.from(t.images).filter(h=>y(h));await Promise.all(g.map(async h=>{const u=d.get(h)||h.currentSrc||h.src||h.getAttribute("src")||"";if(!u)return;await Jt(h);const C=await Dn(u,t),p={src:h.getAttribute("src"),srcset:h.getAttribute("srcset"),sizes:h.getAttribute("sizes")};a.push(()=>{p.src===null?h.removeAttribute("src"):h.setAttribute("src",p.src),p.srcset===null?h.removeAttribute("srcset"):h.setAttribute("srcset",p.srcset),p.sizes===null?h.removeAttribute("sizes"):h.setAttribute("sizes",p.sizes)}),h.removeAttribute("srcset"),h.removeAttribute("sizes"),h.setAttribute("src",C||Ke),await Jt(h)}));const v=Array.from(t.querySelectorAll("*")).filter(y);return await Promise.all(v.map(async h=>{const u=c.getComputedStyle(h).backgroundImage;if(!u||u==="none"||!u.includes("url("))return;const C=await vo(u,t);if(C===u)return;const p=h.style.backgroundImage;a.push(()=>{h.style.backgroundImage=p}),h.style.backgroundImage=C})),()=>{for(let h=a.length-1;h>=0;h-=1)try{a[h]?.()}catch{}}};async function ko(t,n){try{const s=t.contentWindow,o=t.contentDocument??s?.document,a=o?.documentElement;if(!s||!o||!a)return null;const c=t.getBoundingClientRect(),y=Math.max(1,Math.ceil(s.innerWidth||t.clientWidth||c.width)),d=Math.max(1,Math.ceil(s.innerHeight||t.clientHeight||c.height)),f=o.body,g=o.scrollingElement instanceof HTMLElement?o.scrollingElement:null,v=s.scrollX||0,h=s.scrollY||0,u=s.pageXOffset||0,C=s.pageYOffset||0,p=s.visualViewport?.pageLeft||s.visualViewport?.offsetLeft||0,L=s.visualViewport?.pageTop||s.visualViewport?.offsetTop||0,P=a.scrollLeft||0,I=a.scrollTop||0,O=f?.scrollLeft||0,V=f?.scrollTop||0,_=g?.scrollLeft||0,j=g?.scrollTop||0,b=Math.max(v,u,p,P,O,_),S=Math.max(h,C,L,I,V,j);rt("scroll sources",{windowScrollX:v,windowScrollY:h,pageScrollX:u,pageScrollY:C,visualViewportScrollX:p,visualViewportScrollY:L,rootScrollX:P,rootScrollY:I,bodyScrollX:O,bodyScrollY:V,scrollingElementScrollX:_,scrollingElementScrollY:j,scrollingElementTag:g?.tagName?.toLowerCase()??null,resolvedScrollX:b,resolvedScrollY:S,nestedScrolledElements:Rn(o)});const N=Math.max(y,a.scrollWidth||0,f?.scrollWidth||0,Math.ceil(a.getBoundingClientRect().width||0)),w=Math.max(d,a.scrollHeight||0,f?.scrollHeight||0,Math.ceil(a.getBoundingClientRect().height||0)),$=Math.min(2,Math.max(1,window.devicePixelRatio||1)),T=a.style.scrollBehavior,H=f?.style.scrollBehavior??"";a.style.scrollBehavior="auto",f&&(f.style.scrollBehavior="auto");const W=wo(o);rt("nested scroll snapshot",W.snapshot);let D=()=>{},E=()=>{};try{await o.fonts?.ready.catch(()=>{}),D=await An(o,y,d,{applyLayoutWorkarounds:!1}),s.scrollTo(b,S),E=go(o,b,S),W.reapply();const{snapdom:B}=await Le(async()=>{const{snapdom:M}=await import("./vendor-zumer-snapdom-Btyu_Xi2.js");return{snapdom:M}},[]),K={backgroundColor:En(o),cache:"disabled",dpr:$,embedFonts:!0,fast:!1,height:w,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[xo,yo],quality:.82,width:N},fe=await(await B(a,K)).toCanvas();if(!fe.width||!fe.height)return null;const G=fe.width/Math.max(1,N),ie=fe.height/Math.max(1,w),te=Math.min(fe.width,Math.max(1,Math.round(y*G))),ce=Math.min(fe.height,Math.max(1,Math.round(d*ie))),pe=Math.max(0,fe.width-te),je=Math.max(0,fe.height-ce),ge=Math.min(pe,Math.max(0,Math.round(b*G))),xe=Math.min(je,Math.max(0,Math.round(S*ie)));rt("capture geometry",{viewportWidth:y,viewportHeight:d,captureWidth:N,captureHeight:w,canvasWidth:fe.width,canvasHeight:fe.height,xScale:G,yScale:ie,sourceX:ge,sourceY:xe,sourceWidth:te,sourceHeight:ce});const se=o.createElement("canvas");se.width=te,se.height=ce;const Ce=se.getContext("2d");if(!Ce)return null;Ce.drawImage(fe,ge,xe,te,ce,0,0,te,ce);const ke=await mo(se,.82);return ke?await At(ke,y,d,y,d,n):null}finally{E(),W.cleanup(),D(),s.scrollTo(b,S),W.reapply(),a.style.scrollBehavior=T,f&&(f.style.scrollBehavior=H)}}catch(s){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",s),null}}async function No(t,n){const s=await ko(t,n);if(s)return s;try{const o=t.contentWindow,a=t.contentDocument??o?.document,c=a?.documentElement;if(!o||!a||!c)return null;const y=t.getBoundingClientRect(),d=Math.max(1,Math.ceil(o.innerWidth||t.clientWidth||y.width)),f=Math.max(1,Math.ceil(o.innerHeight||t.clientHeight||y.height)),g=o.scrollX||a.documentElement.scrollLeft||a.body?.scrollLeft||0,v=o.scrollY||a.documentElement.scrollTop||a.body?.scrollTop||0,h=a.body,u=Math.max(f,c.scrollHeight||0,h?.scrollHeight||0),C=Math.min(2,Math.max(1,window.devicePixelRatio||1)),p=c.style.scrollBehavior,L=h?.style.scrollBehavior??"";c.style.scrollBehavior="auto",h&&(h.style.scrollBehavior="auto");let P="",I=()=>{};try{await a.fonts?.ready.catch(()=>{}),I=await An(a,d,f,{applyLayoutWorkarounds:!0}),o.scrollTo(g,v);const{getFontEmbedCSS:V,toJpeg:_}=await Le(async()=>{const{getFontEmbedCSS:b,toJpeg:S}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:b,toJpeg:S}},[]),j=await V(c).catch(()=>"");P=await _(c,{quality:.82,pixelRatio:C,width:d,height:f,backgroundColor:En(a),imagePlaceholder:Ke,fontEmbedCSS:j||void 0,style:{transform:`translate(${-g}px, ${-v}px)`,transformOrigin:"top left",minWidth:`${d}px`,minHeight:`${u}px`},cacheBust:!0})}finally{I(),o.scrollTo(g,v),c.style.scrollBehavior=p,h&&(h.style.scrollBehavior=L)}const O=P.split(",",2)[1]||"";return O?await At(O,d,f,d,f,n):null}catch(o){return console.warn("[preview] failed to capture iframe DOM screenshot:",o),null}}const Po=Fe(()=>Le(()=>import("./DiffView-d23o9CKP.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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118])).then(t=>({default:t.DiffView}))),Eo=Fe(()=>Le(()=>import("./FilesView-DIDB-xK7.js"),__vite__mapDeps([119,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,120,121,122,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,123,124,116,117,125,126,114,115])).then(t=>({default:t.FilesView}))),To=Fe(()=>Le(()=>import("./GitView-CkUONO1-.js"),__vite__mapDeps([127,8,1,2,6,3,4,5,7,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,128,115,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,114,116,117])).then(t=>({default:t.GitView}))),Ro=380,Do=1400,Mn=600,_o=100,Ao=24,ct=new Map,Qt=200,Mo=(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",Io=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),s=n.startsWith("//");let o=n.replace(/\/+$/g,"");return o=o.replace(/\/+/g,"/"),s&&!o.startsWith("//")&&(o=`/${o}`),o===""?n.startsWith("/")?"/":"":o},Zt=t=>Number.isFinite(t)?Math.min(Do,Math.max(Ro,Math.round(t))):Mn,Lo=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},Oo=(t,n)=>{if(!t)return"";const s=t.replace(/\\/g,"/"),o=n.replace(/\\/g,"/").replace(/\/+$/,"");return o&&s.startsWith(o+"/")?s.slice(o.length+1):s},In=(t,n=null)=>t==="chat"?"Chat":t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?Nt(n).label:t==="notes"?"Project notes":t==="terminal"?"Terminal":"Context",$o=t=>{if(!t)return null;const n=t.replace(/\\/g,"/").trim();if(!n)return null;const s=n.split("/").filter(Boolean);return s.length===0?n:s[s.length-1]||null},Fo=(t,n,s=null)=>{if(t.mode==="chat"){const o=st(t.dedupeKey);if(o){const c=n.get(o)?.trim();if(c)return c}const a=t.sessionTitleFallback?.trim();return a||"Chat"}if(t.label)return t.label;if(t.mode==="file")return $o(t.targetPath)||"Files";if(t.mode==="preview"){const o=t.targetPath;if(o)try{const a=new URL(o);return a.host||a.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":In(t.mode,s)},en=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(wt,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(dr,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(z,{name:Nt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="notes")return e.jsx(z,{name:"sticky-note",className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(z,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(z,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return e.jsx(z,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(z,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(z,{name:"global",className:"h-3.5 w-3.5"})},Wo=200,Bo=480,zo=({visible:t})=>{const n=J(P=>P.contextEditorTreeWidth),s=J(P=>P.setContextEditorTreeWidth),[o,a]=r.useState(!1),c=r.useRef(0),y=r.useRef(n),d=r.useRef(null),f=r.useRef(null),g=r.useRef(null),v=r.useCallback(P=>Math.min(Bo,Math.max(Wo,Math.round(P))),[]),h=r.useCallback(P=>{const I=g.current;I&&(I.style.width=`${P}px`,I.style.setProperty("--oc-editor-tree-width",`${P}px`))},[]),u=P=>{if(t){try{P.currentTarget.setPointerCapture(P.pointerId)}catch{}f.current=P.pointerId,a(!0),c.current=P.clientX,y.current=n,d.current=n,P.preventDefault()}},C=P=>{if(!o||f.current!==P.pointerId)return;const I=c.current-P.clientX,O=v(y.current+I);d.current!==O&&(d.current=O,h(O))},p=P=>{if(f.current!==P.pointerId)return;try{P.currentTarget.releasePointerCapture(P.pointerId)}catch{}const I=v(d.current??n);f.current=null,d.current=null,a(!1),s(I)},L=t?n:0;return e.jsxs("div",{ref:g,className:be("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:`${o?d.current??L:L}px`,"--oc-editor-tree-width":`${o?d.current??n:n}px`,overflowX:"clip",transitionProperty:o?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&e.jsx("div",{className:be("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",o&&"bg-[var(--interactive-border)]"),onPointerDown:u,onPointerMove:C,onPointerUp:p,onPointerCancel:p,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:be("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",o&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,children:e.jsx(Bs,{})})]})},st=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,Uo=(t,n)=>{if(t.size!==n.size)return!1;for(const[s,o]of t)if(n.get(s)!==o)return!1;return!0},Ho=(t,n)=>{if(n.length===0)return ct;const s=new Set(n),o=new Map;for(const a of t){if(!s.has(a.id))continue;const c=a.title?.trim();c&&o.set(a.id,c)}return o.size===0?ct:o},Vo=(t,n)=>{const s=zr(),o=r.useRef(ct),a=r.useRef(n);return a.current=n,r.useSyncExternalStore(s.subscribe,r.useCallback(()=>{const c=Ho(s.getState().session,a.current);return Uo(o.current,c)?o.current:(o.current=c,c)},[s]),()=>ct)},Ln=`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
- });`,ot=`(() => {
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
- })()`,Ko=`(() => {
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
- })()`,Ze=t=>{const n=t.trim();if(!n)return"about:blank";try{const s=new URL(n.includes("://")?n:`https://${n}`);return s.protocol!=="http:"&&s.protocol!=="https:"?"about:blank":s.toString()}catch{return"about:blank"}},tn=async(t,n)=>{const s=t.contentWindow;if(!s)throw new Error("Iframe window is not available");const a=s.eval.call(s,n);return await Promise.resolve(a)},Xo=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,On=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},nn=(t,n,s)=>{const o=On(n);t.postMessage(s,o)},qo=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}},rn=t=>{if(!t)return t;try{const n=new URL(t);return n.searchParams.delete("ocPreview"),n.searchParams.delete("oc_preview_token"),n.searchParams.delete("oc_client_token"),n.searchParams.delete("oc_url_token"),n.toString()}catch{return t}},Go=({rawUrl:t,onNavigate:n})=>{const{currentTheme:s}=xn(),[o,a]=r.useReducer(k=>k+1,0),[c,y]=r.useReducer(k=>k+1,0),[d,f]=r.useState({status:"idle"}),[g,v]=r.useState(""),h=r.useRef(null),u=r.useRef(1),[C,p]=r.useState(!1),[L,P]=r.useState(!1),[I,O]=r.useState("all"),[V,_]=r.useState([]),[j,b]=r.useState(!1),[S,N]=r.useState(null),w=Ie(k=>k.currentSessionId),$=Ie(k=>k.newSessionDraft?.open),T=et(),H=Pt(k=>k.addDraft),W=Et(k=>k.addAttachedFile);let D=null;try{D=t?new URL(t):null}catch{D=null}const E=D?D.hostname==="localhost"||D.hostname==="127.0.0.1"||D.hostname==="::1"||D.hostname==="[::1]"||D.hostname==="0.0.0.0":!1,B=D?D.hostname==="0.0.0.0"?new URL(D.toString().replace("0.0.0.0","127.0.0.1")):D:null,K=B?B.toString():"",ne=K?`${it()||"same-origin"}|${K}`:"",fe=s.metadata.variant;r.useEffect(()=>{if(!K||!E){f({status:"idle"});return}const k=Mt(ne);if(k?.previewToken){f({status:"ready",proxyBasePath:k.proxyBasePath,previewToken:k.previewToken,expiresAt:k.expiresAt});return}k&&Re.delete(ne);let re=!1;return f({status:"loading"}),(async()=>{try{const Z=await at("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:K})});if(!Z.ok){Re.delete(ne);const Ne=await Z.json().catch(()=>({})),x=typeof Ne?.error=="string"?Ne.error:`HTTP ${Z.status}`;re||f({status:"error",message:x});return}const i=await Z.json(),m=typeof i.proxyBasePath=="string"?i.proxyBasePath:"",Y=typeof i.previewToken=="string"?i.previewToken:"",le=typeof i.expiresAt=="number"?i.expiresAt:0;if(!m||!Y){Re.delete(ne),re||f({status:"error",message:"Could not start preview proxy."});return}Re.set(ne,{proxyBasePath:m,previewToken:Y,expiresAt:le}),re||f({status:"ready",proxyBasePath:m,previewToken:Y,expiresAt:le})}catch(Z){if(Re.delete(ne),!re){const i=Z instanceof Error?Z.message:String(Z);f({status:"error",message:i})}}})(),()=>{re=!0}},[E,ne,c,K]);const G=B&&(B.protocol==="http:"||B.protocol==="https:")?B.toString():"",ie=E&&d.status==="ready"?`${d.proxyBasePath}|${d.previewToken||""}|${o}`:"";r.useEffect(()=>{if(!ie){v("");return}let k=!1;return v(""),dn(it()).then(re=>{!k&&re&&v(ie)}).catch(()=>{}),()=>{k=!0}},[ie]);const te=E&&d.status==="ready"&&B&&g===ie?(()=>{const k=B.pathname||"/",re=new URLSearchParams(B.search);re.delete("oc_url_token"),re.delete("oc_client_token"),re.set("ocPreview",String(o)),re.set("oc_preview_token",d.previewToken||"");const Z=re.toString(),i=B.hash||"";return un().authenticatedAsset(`${d.proxyBasePath}${k}${Z?`?${Z}`:""}${i}`)})():"",ce=E?te:G,pe=E?qo(te):G,je=E&&(d.status==="loading"||d.status==="idle"||g!==ie),ge=E&&d.status==="error",xe=r.useCallback(k=>{const re=w??($?"draft":null);if(!re||!T){ue.error("Open a chat session before attaching preview annotations");return}const Z=t||ce||"",i=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},m=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let Y=!1;try{const le=h.current,Ne=le?await Pn(le,k):null;Ne&&(await W(Ne),Y=!0)}catch{Y=!1}H({directory:T,sessionKey:re},{source:"preview-annotation",fileLabel:Z||"preview",startLine:1,endLine:1,code:_t({pageUrl:Z,viewport:i,devicePixelRatio:m,target:k,screenshotAttached:Y,intro:"This is a selected DOM element from the in-app preview."}),language:"markdown",text:""}),ue.success("Preview annotation attached to chat")})()},[W,H,w,T,ce,$,t]);r.useEffect(()=>{p(!1),_([]),P(!1),O("all"),b(!1),N(null),u.current=1},[ce]),r.useEffect(()=>{const k=h.current?.contentWindow;!C||!k||nn(k,te,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:j})},[C,j,te]),r.useEffect(()=>{const k=h.current?.contentWindow;!C||!k||nn(k,te,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:fe})},[C,fe,te]),r.useEffect(()=>{if(!j||typeof window>"u")return;const k=re=>{re.key==="Escape"&&(re.preventDefault(),re.stopImmediatePropagation(),b(!1))};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[j]),r.useEffect(()=>{if(!E||typeof window>"u")return;const k=i=>{if(typeof i=="string")return i;if(i==null)return"";try{return JSON.stringify(i)}catch{return String(i)}},re=i=>{const m=u.current;u.current+=1,_(Y=>{const le=[...Y,{...i,id:m}];return le.length>Qt?le.slice(le.length-Qt):le})},Z=i=>{if(i.source!==h.current?.contentWindow)return;const m=i.data;if(!(!m||m.source!=="pichamber-preview-bridge"||m.version!==1)){if(m.type==="ready"){p(!0);return}if(m.type==="console"){const Y=m.level==="error"||m.level==="warn"||m.level==="info"||m.level==="debug"?m.level:"log",le=Array.isArray(m.args)?m.args.map(k).filter(Boolean):[];re({level:Y,message:le.join(" "),ts:typeof m.ts=="number"?m.ts:Date.now()});return}if(m.type==="runtime-error"){const Y=k(m.filename),le=typeof m.line=="number"?m.line:null,Ne=typeof m.column=="number"?m.column:null,x=Y?`${Y}${le!==null?`:${le}${Ne!==null?`:${Ne}`:""}`:""}`:"",R=k(m.stack);re({level:"runtime",message:k(m.message)||"Runtime error",details:[x,R].filter(Boolean).join(`
127
- `),ts:typeof m.ts=="number"?m.ts:Date.now()});return}if(m.type==="resource-error"){const Y=k(m.tag)||"resource",le=k(m.url);re({level:"resource",message:le?`${Y}: ${le}`:Y,details:k(m.outerHTML),ts:typeof m.ts=="number"?m.ts:Date.now()});return}if(m.type==="hover"){N(Ve(m.target)?m.target:null);return}if(m.type==="select"&&Ve(m.target)){N(m.target),b(!1),xe(m.target);return}if(m.type==="navigate-preview"){const Y=typeof m.url=="string"?m.url:"",le=m.navigation==="external"?"external":"proxy";if(Y&&le==="external"){lt(Y);return}Y&&n(Y)}}};return window.addEventListener("message",Z),()=>{window.removeEventListener("message",Z)}},[xe,E,n]);const se=V.filter(k=>k.level==="error"||k.level==="runtime"||k.level==="resource").length,Ce=V.filter(k=>Mo(k,I)),ke=r.useCallback(()=>{const k=[`Preview URL: ${t||ce||""}`,`Events: ${V.length}`,""].join(`
128
- `),re=V.map(Z=>{const i=new Date(Z.ts).toISOString(),m=Z.details?`
129
- ${Z.details}`:"";return`[${i}] [${Z.level}] ${Z.message}${m}`}).join(`
130
- `);yt(`${k}${re}`).then(Z=>{Z.ok?ue.success("Preview console copied"):ue.error("Failed to copy preview console")})},[V,ce,t]),M=r.useCallback(()=>{const k=w??($?"draft":null);if(!k||!T){ue.error("Open a chat session before attaching preview logs");return}const re=[`Preview URL: ${t||ce||""}`,`Events: ${V.length}`,""].join(`
131
- `),Z=V.map(i=>{const m=new Date(i.ts).toISOString(),Y=i.details?`
132
- ${i.details}`:"";return`[${m}] [${i.level}] ${i.message}${Y}`}).join(`
133
- `);H({directory:T,sessionKey:k},{source:"preview-console",fileLabel:t||ce||"preview",startLine:1,endLine:Math.max(1,V.length),code:`${re}${Z}`,language:"text",text:"These are browser console logs from the dev server running for this project."}),ue.success("Preview console attached to chat")},[H,V,w,T,ce,$,t]),[F,X]=r.useState("unknown"),Q=r.useRef(0),oe=r.useRef(0),ye=r.useRef(""),de=r.useRef(""),ve=15e3;r.useEffect(()=>{if(!te){X("unknown"),ye.current="",Q.current=0,oe.current=0;return}let k=!1,re=null;ye.current!==ne&&(ye.current=ne,Q.current=Date.now(),oe.current=0);const Z=i=>{re=setTimeout(()=>{k||a()},i)};return X("unknown"),(async()=>{const m=await(async()=>{try{return await at(te,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(k)return;if(!m){X("unreachable"),Z(5e3);return}const Y=co(m.headers,de.current===ne);if(Y!=="none"){if(Re.delete(ne),Y==="retry-registration")de.current=ne,f({status:"loading"}),y();else{const x=await m.json().catch(()=>({}));if(k)return;const R=typeof x?.error=="string"?x.error:`HTTP ${m.status}`;f({status:"error",message:R})}return}if(m.status!==502){de.current="",X("reachable");return}const le=Q.current||Date.now();if(Date.now()-le<ve){X("starting"),oe.current+=1;const x=oe.current,R=Math.min(2e3,250*Math.pow(2,Math.min(4,x)));Z(R);return}X("unreachable"),Z(5e3)})(),()=>{k=!0,re&&clearTimeout(re)}},[ne,te,o]);const Ee=E&&d.status==="ready"&&(F==="unknown"||F==="starting"),Te=E&&d.status==="ready"&&F==="unreachable",De=r.useCallback(k=>{if(!E||d.status!=="ready"||typeof window>"u")return;const re=k.currentTarget.contentWindow;if(re)try{const Z=re.location,i=On(te);if(Z.origin!==i||Z.pathname.startsWith(d.proxyBasePath))return;const m=`${d.proxyBasePath}${Z.pathname}${Z.search}${Z.hash}`;re.location.replace(m)}catch{}},[E,te,d]);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:pe||t,children:pe||t||"No preview URL"}),e.jsx(he,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:"Reload preview","aria-label":"Reload preview",disabled:!ce,children:e.jsx(z,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{G&&lt(G)},title:"Open in browser","aria-label":"Open in browser",disabled:!G,children:e.jsx(z,{name:"external-link",className:"h-3.5 w-3.5"})}),E?e.jsx(he,{type:"button",size:"sm",variant:j?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>b(k=>!k),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!C,children:e.jsx(z,{name:"cursor",className:"h-3.5 w-3.5"})}):null,E?e.jsxs(he,{type:"button",size:"sm",variant:L?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>P(k=>!k),title:C?"Open preview console":"Waiting for preview console","aria-label":C?"Open preview console":"Waiting for preview console",disabled:!C&&V.length===0,children:[e.jsx(z,{name:"terminal-box",className:"h-3.5 w-3.5"}),se>0?e.jsx("span",{className:"typography-micro text-status-error",children:se}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Ee?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."})]}):Te?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(he,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:"Retry"})]}):ce&&(!E||F==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:h,src:ce,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:fe},onLoad:De,sandbox:E?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${ce}:${o}`),j&&S?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:S.bounds.x,top:S.bounds.y,width:S.bounds.width,height:S.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:[S.tag,S.text?` · ${S.text}`:""]})}):null]}):je?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):ge?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[e.jsx("div",{children:"Could not start preview proxy."}),d.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:d.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."}),L?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(he,{type:"button",size:"xs",variant:"ghost",onClick:M,disabled:V.length===0,children:"Attach"}),e.jsx(he,{type:"button",size:"xs",variant:"ghost",onClick:ke,disabled:V.length===0,children:"Copy"}),e.jsx(he,{type:"button",size:"xs",variant:"ghost",onClick:()=>_([]),disabled:V.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(k=>e.jsx(he,{type:"button",size:"xs",variant:I===k?"secondary":"ghost",onClick:()=>O(k),children:k==="all"?"All":k==="errors"?"Errors":k==="warnings"?"Warnings":"Logs"},k))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:V.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):Ce.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):Ce.map(k=>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:be("shrink-0 uppercase",k.level==="error"||k.level==="runtime"||k.level==="resource"?"text-status-error":k.level==="warn"?"text-status-warning":"text-muted-foreground"),children:k.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:k.message})]})},k.id))})]}):null]})]})},Yo=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,Jo=({initialUrl:t,directory:n,tabID:s})=>{const o=r.useRef(null),a=J(M=>M.setContextPanelTabTargetPath),c=Ze(t),y=c!=="about:blank"?c:"",[d,f]=r.useState(y),[g,v]=r.useState(y),[h,u]=r.useState(y),[C,p]=r.useState(()=>y?[y]:[]),[L,P]=r.useState(()=>y?0:-1),[I,O]=r.useReducer(M=>M+1,0),[V,_]=r.useState(!!y),[j,b]=r.useState(!1),[S,N]=r.useState(null),[w,$]=r.useState({status:"idle"}),[T,H]=r.useState(""),W=Ie(M=>M.currentSessionId),D=Ie(M=>M.newSessionDraft?.open),E=Pt(M=>M.addDraft),B=Et(M=>M.addAttachedFile),K=r.useCallback(M=>{!M||M==="about:blank"||!n||!s||a(n,s,M)},[n,s,a]),ne=r.useCallback((M,F)=>{const X=Ze(M),Q=X!=="about:blank"?X:"";v(Q),f(Q),F?.inFrame?_(!1):(u(Q),_(!!Q)),K(Q),p(oe=>{if(!Q)return P(-1),[];if(F?.replaceHistory)return oe;const ye=L>=0?oe.slice(0,L+1):[];if(ye[ye.length-1]===Q)return P(ye.length-1),ye;const ve=[...ye,Q];return P(ve.length-1),ve})},[L,K]),fe=r.useCallback(M=>{const F=C[M];F&&(P(M),v(F),u(F),f(F),_(!0),K(F))},[C,K]),G=r.useCallback(()=>{if(g){_(!0);try{o.current?.contentWindow?.location.reload()}catch{O()}}},[g]);r.useEffect(()=>{if(!h){$({status:"idle"});return}const M=po(h),F=Mt(M);if(F?.previewToken){$({status:"ready",proxyBasePath:F.proxyBasePath,previewToken:F.previewToken,expiresAt:F.expiresAt});return}F&&Re.delete(M);let X=!1;return $({status:"loading"}),_(!0),(async()=>{try{const Q=await at("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:h,allowExternal:!0})});if(!Q.ok){const Ee=await Q.json().catch(()=>({})),Te=typeof Ee?.error=="string"?Ee.error:`HTTP ${Q.status}`;X||$({status:"error",message:Te});return}const oe=await Q.json(),ye=typeof oe.proxyBasePath=="string"?oe.proxyBasePath:"",de=typeof oe.previewToken=="string"?oe.previewToken:"",ve=typeof oe.expiresAt=="number"?oe.expiresAt:0;if(!ye||!de){X||$({status:"error",message:"Could not start preview proxy."});return}Re.set(M,{proxyBasePath:ye,previewToken:de,expiresAt:ve}),X||$({status:"ready",proxyBasePath:ye,previewToken:de,expiresAt:ve})}catch(Q){if(!X){const oe=Q instanceof Error?Q.message:String(Q);$({status:"error",message:oe})}}})(),()=>{X=!0}},[h]);const ie=h&&w.status==="ready"?`${w.proxyBasePath}|${w.previewToken||""}|${I}`:"";r.useEffect(()=>{if(!ie){H("");return}let M=!1;return H(""),dn(it()).then(F=>{!M&&F&&H(ie)}).catch(()=>{}),()=>{M=!0}},[ie]);const te=r.useMemo(()=>{if(T!==ie||!h||w.status!=="ready")return"";try{const M=new URL(h),F=M.pathname||"/",X=new URLSearchParams(M.search);X.delete("oc_url_token"),X.delete("oc_client_token"),X.set("ocPreview",String(I)),X.set("oc_preview_token",w.previewToken||"");const Q=X.toString();return un().authenticatedAsset(`${w.proxyBasePath}${F}${Q?`?${Q}`:""}${M.hash}`)}catch{return""}},[h,w,ie,I,T]),ce=te||(w.status==="error"?h:""),pe=r.useCallback(M=>{if(!M||!h||w.status!=="ready")return"";try{const F=new URL(M,window.location.origin),X=w.proxyBasePath.endsWith("/")?w.proxyBasePath.slice(0,-1):w.proxyBasePath;if(F.origin!==window.location.origin||!F.pathname.startsWith(X))return"";const Q=F.pathname.slice(X.length)||"/",oe=new URL(h).origin;return rn(new URL(`${Q}${F.search}${F.hash}`,oe).toString())}catch{return""}},[h,w]),je=r.useCallback(M=>{if(!M||!h||w.status!=="ready")return"";try{const F=new URL(M,window.location.origin),X=new URL(h).origin;if(F.origin!==window.location.origin||X===window.location.origin)return"";const Q=w.proxyBasePath.endsWith("/")?w.proxyBasePath.slice(0,-1):w.proxyBasePath;return F.pathname.startsWith(Q)?"":rn(new URL(`${F.pathname}${F.search}${F.hash}`,X).toString())}catch{return""}},[h,w]),ge=r.useCallback(M=>{const F=o.current?.contentWindow;F&&F.postMessage({source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:M},window.location.origin)},[]),xe=r.useCallback(async M=>{const F=W??(D?"draft":null);if(!F){ue.error("Open a chat session before attaching preview annotations");return}const X=o.current,Q=X?.contentWindow,oe=X?.getBoundingClientRect(),ye={width:Number.isFinite(Q?.innerWidth)?Q?.innerWidth??oe?.width??0:oe?.width??0,height:Number.isFinite(Q?.innerHeight)?Q?.innerHeight??oe?.height??0:oe?.height??0},de=X?await Pn(X,M):null,ve=!!de;de&&await B(de),E({directory:n,sessionKey:F},{source:"preview-annotation",fileLabel:g||"browser",startLine:1,endLine:1,code:_t({pageUrl:g,viewport:ye,devicePixelRatio:window.devicePixelRatio||1,target:M,screenshotAttached:ve,intro:ve?"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."}),language:"markdown",text:""}),ue.success("Preview annotation attached to chat")},[B,E,W,g,n,D]),se=r.useCallback(()=>{const M=o.current;N(null),ge(!1),M&&tn(M,ot).catch(()=>{})},[ge]);r.useEffect(()=>{if(!j)return;const M=F=>{F.key==="Escape"&&(F.preventDefault(),F.stopImmediatePropagation(),b(!1),se())};return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[se,j]),r.useEffect(()=>()=>se(),[se]),r.useEffect(()=>{const M=F=>{if(F.source!==o.current?.contentWindow)return;const X=F.data;if(!(!X||X.source!=="pichamber-preview-bridge"||X.version!==1)){if(X.type==="ready"){const Q=typeof X.url=="string"?X.url:"",oe=pe(Q);oe&&oe!==g&&ne(oe,{inFrame:!0});return}if(X.type==="hover"){N(Ve(X.target)?X.target:null);return}if(X.type==="select"&&Ve(X.target)){N(null),b(!1),ge(!1),xe(X.target);return}if(X.type==="navigate-preview"){const Q=typeof X.url=="string"?X.url:"",oe=je(Q);if(oe){ne(oe);return}Q&&ne(Q)}}};return window.addEventListener("message",M),()=>window.removeEventListener("message",M)},[ne,xe,g,pe,je,ge]);const Ce=r.useCallback(()=>{const M=o.current;if(!(!M||!g)){if(j){b(!1),se();return}if(te){N(null),b(!0),ge(!0);return}b(!0),(async()=>{try{const F=await tn(M,Ln);if(b(!1),!F||!Ve(F))return;await xe(F)}catch{b(!1),ue.error("This page cannot be inspected from the browser panel.")}})()}},[xe,se,g,j,ge,te]),ke=r.useCallback(()=>{try{const M=o.current?.contentWindow?.location.href||"",F=je(M);if(F){ne(F,{inFrame:!0});return}}catch{}_(!1),j&&te&&ge(!0)},[ne,je,j,ge,te]);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(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:L<=0,onClick:()=>fe(L-1),children:e.jsx(z,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:L<0||L>=C.length-1,onClick:()=>fe(L+1),children:e.jsx(z,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:G,children:e.jsx(z,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:M=>{M.preventDefault(),ne(d)},children:e.jsx("input",{value:d,onChange:M=>f(M.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"})}),e.jsx(he,{type:"button",variant:j?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:Ce,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(z,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:()=>{lt(g)},children:e.jsx(z,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[ce?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("iframe",{ref:o,src:ce,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:ke},`${s}:${I}`),j&&S?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:S.bounds.x,top:S.bounds.y,width:S.bounds.width,height:S.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:[S.tag,S.text?` · ${S.text}`:""]})}):null]}):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(yn,{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",children:"Enter an address above to start browsing the web"}),e.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:"Pages opened here run with full access to PiChamber — needed for inspect and screenshots. Only open sites you trust: a malicious page could read your data or act on your behalf."})]}),V?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Qo=({initialUrl:t,directory:n,tabID:s})=>{const o=r.useRef(null),a=J(w=>w.setContextPanelTabTargetPath),c=Ze(t),y=c!=="about:blank"?c:"",d=r.useRef(Ze(t)),[f,g]=r.useState(y),[v,h]=r.useState(y),[u,C]=r.useState(!1),[p,L]=r.useState(!0),P=r.useRef(null),I=p,O=r.useCallback(w=>{!w||w==="about:blank"||!n||!s||a(n,s,w)},[n,s,a]),V=Ie(w=>w.currentSessionId),_=Ie(w=>w.newSessionDraft?.open),j=Pt(w=>w.addDraft),b=Et(w=>w.addAttachedFile);r.useEffect(()=>{const w=o.current;if(!w)return;const $=()=>{try{const B=w.getURL();B&&B!=="about:blank"&&(h(B),g(B),O(B))}catch{}},T=B=>{const K=B.detail;typeof K?.url=="string"&&K.url&&(h(K.url),g(K.url),O(K.url))},H=()=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>L(!0),200)},W=()=>{P.current&&clearTimeout(P.current),L(!1),$()},D=B=>{const K=B.detail;if(K?.disposition==="new-window"||K?.disposition==="foreground-tab"||K?.disposition==="background-tab"){B.preventDefault();const ne=o.current;typeof ne?.loadURL=="function"&&K.url&&ne.loadURL(K.url)}},E=()=>{try{w.executeJavaScript?.(Ko,!0).catch(()=>{})}catch{}};w.addEventListener("did-navigate",T),w.addEventListener("did-navigate-in-page",T),w.addEventListener("did-start-loading",H),w.addEventListener("did-stop-loading",W),w.addEventListener("new-window",D),w.addEventListener("dom-ready",E);try{w.isLoading()||(L(!1),$())}catch{}return E(),()=>{P.current&&clearTimeout(P.current),w.removeEventListener("did-navigate",T),w.removeEventListener("did-navigate-in-page",T),w.removeEventListener("did-start-loading",H),w.removeEventListener("did-stop-loading",W),w.removeEventListener("new-window",D),w.removeEventListener("dom-ready",E)}},[O]),r.useEffect(()=>{const w=setTimeout(()=>L(!1),3e4);return()=>clearTimeout(w)},[]),r.useEffect(()=>{if(!u)return;const w=$=>{if($.key!=="Escape")return;$.preventDefault(),$.stopImmediatePropagation(),C(!1);const T=o.current;try{T?.executeJavaScript?.(ot).catch(()=>{})}catch{}};return window.addEventListener("keydown",w,!0),()=>window.removeEventListener("keydown",w,!0)},[u]),r.useEffect(()=>{const w=o.current;return()=>{try{const $=w?.getURL?.();$&&$!=="about:blank"&&a(n,s,$)}catch{}try{w?.executeJavaScript?.(ot).catch(()=>{})}catch{}}},[n,s,a]);const S=r.useCallback(w=>{const $=o.current;if(typeof $?.loadURL!="function")return;const T=Ze(w);try{$.loadURL(T)}catch{}},[]),N=r.useCallback(()=>{const w=o.current;if(w){if(u){C(!1);try{w.executeJavaScript?.(ot).catch(()=>{})}catch{}return}C(!0),w.executeJavaScript?.(Ln,!0).then(async $=>{if(C(!1),!$||!Ve($))return;const T=V??(_?"draft":null);if(!T){ue.error("Open a chat session before attaching preview annotations");return}const H=typeof w.getWebContentsId=="function"?w.getWebContentsId():null;if(H==null)return;const W=await Br("desktop_browser_capture_page",{webContentsId:H}),D=await w.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),E=Number.isFinite(D?.width)?D.width:W.width,B=Number.isFinite(D?.height)?D.height:W.height,K=await At(W.base64,W.width,W.height,E,B,$),ne=!!K;K&&await b(K),j({directory:n,sessionKey:T},{source:"preview-annotation",fileLabel:v||"browser",startLine:1,endLine:1,code:_t({pageUrl:v,viewport:{width:E,height:B},devicePixelRatio:window.devicePixelRatio||1,target:$,screenshotAttached:ne,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."}),language:"markdown",text:""}),ue.success("Preview annotation attached to chat")}).catch(()=>C(!1))}},[b,j,V,v,n,u,_]);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(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:e.jsx(z,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:e.jsx(z,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:e.jsx(z,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:w=>{w.preventDefault(),S(f)},children:e.jsx("input",{value:f,onChange:w=>g(w.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"})}),e.jsx(he,{type:"button",variant:u?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:N,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(z,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{lt(v)},children:e.jsx(z,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[e.jsx("webview",{ref:o,src:d.current,partition:"persist:pichamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!v||v==="about:blank")&&!p?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(yn,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,I?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Zo=()=>{const t=et()??"",n=r.useMemo(()=>Io(t),[t]),s=J(l=>n?l.contextPanelByDirectory[n]:void 0),o=J(l=>l.closeContextPanel),a=J(l=>l.closeContextPanelTab),c=J(l=>l.openContextPanelTab),y=J(l=>l.toggleContextPanelExpanded),d=J(l=>l.setContextPanelWidth),f=J(l=>l.setActiveContextPanelTab),g=J(l=>l.reorderContextPanelTabs),v=$e(l=>l.setSelectedPath),h=J(l=>l.openContextPreview),u=J(l=>l.contextEditorTreeVisible),C=J(l=>l.toggleContextEditorTree),p=J(l=>l.allowPromptingSubagentSessions),{themeMode:L,setThemeMode:P,lightThemeId:I,darkThemeId:O,currentTheme:V}=xn(),_=r.useMemo(()=>s?.tabs??[],[s?.tabs]),j=_.find(l=>l.id===s?.activeTabId)??_[_.length-1]??null,b=!!(s?.isOpen&&j),S=!!(b&&s?.expanded),[N,w]=r.useState(null),$=s?.width,T=Ur,H=N??(typeof window<"u"?window.innerWidth:Mn*2),W=Zt($??Math.round(T*H)),D=r.useMemo(()=>{const l=[];for(const q of _){if(q.mode!=="chat")continue;const we=st(q.dedupeKey);we&&!l.includes(we)&&l.push(we)}return l},[_]),E=Vo(n||void 0,D),B=wn(n||null),[K,ne]=r.useState(!1),fe=r.useRef(0),G=r.useRef(W),ie=r.useRef(null),te=r.useRef(null),ce=r.useRef(null),pe=r.useRef(new Map),je=r.useRef(new Map),ge=r.useRef(!1);r.useLayoutEffect(()=>{const l=ce.current?.parentElement;if(!l||typeof ResizeObserver>"u")return;const q=new ResizeObserver(()=>{w(l.clientWidth||null)});return q.observe(l),w(l.clientWidth||null),()=>q.disconnect()},[]),r.useEffect(()=>{if(!b||ge.current){ge.current=b;return}const l=window.requestAnimationFrame(()=>{ce.current?.focus({preventScroll:!0})});return ge.current=!0,()=>window.cancelAnimationFrame(l)},[b]);const xe=r.useRef(null),se=r.useRef(null),Ce=r.useCallback(()=>{se.current=null;const l=ce.current,q=ie.current;!l||q===null||l.style.setProperty("--oc-context-panel-width",`${q}px`)},[]);r.useEffect(()=>()=>{se.current!==null&&clearTimeout(se.current)},[]);const ke=r.useCallback(l=>{const q=Zt(l),we=xe.current;return we===null?q:Math.min(q,Math.max(1,we))},[]),M=r.useCallback(l=>{!b||S||!n||(te.current=l.pointerId,ne(!0),fe.current=l.clientX,G.current=W,ie.current=W,xe.current=Lo(ce.current),document.documentElement.style.cursor="col-resize",l.preventDefault())},[n,S,b,W]),F=r.useCallback(()=>{const l=ke(ie.current??W);ie.current=null,xe.current=null,se.current!==null&&(clearTimeout(se.current),se.current=null),document.documentElement.style.cursor="",n&&d(n,l),ne(!1),te.current=null},[ke,n,d,W]);r.useEffect(()=>{if(!K)return;const l=Se=>{if(te.current!==Se.pointerId)return;const Xe=fe.current-Se.clientX,dt=ke(G.current+Xe);ie.current!==dt&&(ie.current=dt,se.current===null&&(se.current=setTimeout(Ce,_o)))},q=Se=>{te.current===Se.pointerId&&F()},we=()=>{F()};return window.addEventListener("pointermove",l),window.addEventListener("pointerup",q),window.addEventListener("pointercancel",q),window.addEventListener("blur",we),()=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",q),window.removeEventListener("pointercancel",q),window.removeEventListener("blur",we)}},[Ce,ke,F,K]),r.useEffect(()=>{K||(ie.current=null,document.documentElement.style.cursor="")},[K]);const X=r.useCallback(()=>{n&&o(n)},[o,n]),Q=r.useCallback(()=>{n&&y(n)},[n,y]),oe=r.useCallback(l=>{l.key==="Escape"&&(Lr(l.target)||(l.preventDefault(),l.stopPropagation(),X()))},[X]);r.useEffect(()=>{if(!(!n||!j)&&j.mode==="file"&&j.targetPath){v(n,j.targetPath,{allowOutsideRoot:!0});return}},[j,n,v]);const ye=j?.mode==="chat"?j.id:null,de=j?.mode==="chat"?st(j.dedupeKey):null;r.useEffect(()=>{if(!b||!n||!de||typeof window>"u")return;const l=()=>{document.visibilityState==="hidden"||!document.hasFocus()||$r(de)};l();const q=window.setInterval(l,1e4);return window.addEventListener("focus",l),window.addEventListener("blur",l),document.addEventListener("visibilitychange",l),()=>{window.clearInterval(q),window.removeEventListener("focus",l),window.removeEventListener("blur",l),document.removeEventListener("visibilitychange",l)}},[de,n,b]);const ve=r.useCallback((l,q,we)=>Or(je.current,l,q,n||null,we,{mode:L,lightThemeId:I,darkThemeId:O,currentTheme:V}),[V,O,n,I,L]);r.useEffect(()=>{const l=new Set(_.map(q=>q.id));for(const q of je.current.keys())l.has(q)||je.current.delete(q)},[_]);const Ee=r.useCallback(l=>{!n||j?.mode!=="diff"||c(n,{mode:"diff",targetPath:j.targetPath,stagedDiff:l==="staged",diffScope:l})},[j,n,c]),Te=r.useCallback(()=>{if(typeof window>"u")return;const l={themeMode:L,lightThemeId:I,darkThemeId:O,currentTheme:V};for(const q of pe.current.values()){const we=q.contentWindow;we&&we.postMessage({type:"pichamber:theme-sync",payload:l},window.location.origin)}},[V,O,I,L]),De=r.useCallback(()=>{if(typeof window>"u")return;const l={allowPromptingSubagentSessions:p};for(const q of pe.current.values()){const we=q.contentWindow;we&&we.postMessage({type:"pichamber:chat-settings-sync",payload:l},window.location.origin)}},[p]),k=r.useCallback(()=>{if(!(typeof window>"u"))for(const[l,q]of pe.current.entries()){const we=q.contentWindow;if(!we)continue;const Se={visible:ye===l};we.postMessage({type:"pichamber:embedded-visibility",payload:Se},window.location.origin)}},[ye]);r.useEffect(()=>{if(typeof window>"u")return;const l=q=>{if(q.origin!==window.location.origin||!Array.from(pe.current.values()).some(tt=>tt.contentWindow===q.source))return;const Se=q.data;if(Se?.type===Fr){if(typeof Se.requestId!="string"||!Se.requestId)return;const tt=ln(),Wn={apiBaseUrl:it(),clientToken:qn(),localOrigin:typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",runtimeHeaders:Xn(),relayHostId:tt.startsWith("host:")?tt.slice(5):"",relay:Kn()??void 0};q.source?.postMessage({type:Wr,requestId:Se.requestId,payload:Wn},q.origin);return}if(Se?.type==="pichamber:theme-sync-request"){Te();return}if(Se?.type==="pichamber:chat-settings-request"){De();return}if(Se?.type!=="pichamber:cycle-theme-request")return;const Xe=["light","dark","system"],Fn=(Xe.indexOf(L)+1)%Xe.length;P(Xe[Fn])};return window.addEventListener("message",l),()=>window.removeEventListener("message",l)},[De,Te,P,L]),r.useLayoutEffect(()=>{_.some(q=>q.mode==="chat")&&(Te(),De(),k())},[O,I,De,k,Te,_,L]);const re=j?.mode==="file"||j?.mode==="chat"||j?.mode==="preview",Z=r.useMemo(()=>j?_.filter(l=>l.mode===j.mode):[],[j,_]),i=r.useMemo(()=>Z.map(l=>{const q=Fo(l,E,B),we=Xo(q,Ao),Se=Oo(l.targetPath,t);return{id:l.id,label:we,icon:en(l,B),title:Se?`${q}: ${Se}`:q,closeLabel:`Close ${we} tab`}}),[Z,t,B,E]),m=j?.mode==="context"?e.jsx(ao,{}):j?.mode==="git"?e.jsx(r.Suspense,{fallback:null,children:e.jsx(To,{isActive:b})}):j?.mode==="notes"?e.jsx(pn,{}):j?.mode==="preview"?e.jsx(Go,{rawUrl:j.targetPath??"",onNavigate:l=>h(t,l)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(z,{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."})]}),Y=r.useMemo(()=>_.filter(l=>l.mode==="chat"),[_]),le=r.useMemo(()=>_.filter(l=>l.mode==="browser"),[_]),Ne=r.useMemo(()=>_.filter(l=>l.mode==="diff"),[_]),x=r.useMemo(()=>_.some(l=>l.mode==="terminal"),[_]),R=Yo()?Qo:Jo,ae=r.useMemo(()=>_.some(l=>l.mode==="file"),[_]),A=r.useMemo(()=>_.some(l=>l.mode==="file"&&l.targetPath),[_]),ee=j?.mode==="file",U=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[re?e.jsx(cr,{items:i,activeId:j?.id??null,onSelect:l=>{n&&f(n,l)},onClose:l=>{n&&a(n,l)},onReorder:(l,q)=>{n&&g(n,l,q)},layoutMode:"scrollable",variant:"default"}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[j?en(j,B):null,e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:j?In(j.mode,B):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[ee?e.jsx(he,{type:"button",variant:"ghost",size:"sm",onClick:C,className:"h-7 w-7 p-0",title:"Toggle file tree","aria-label":"Toggle file tree","aria-pressed":u,children:e.jsx(z,{name:"layout-right",className:"h-3.5 w-3.5"})}):null,e.jsx(he,{type:"button",variant:"ghost",size:"sm",onClick:Q,className:"h-7 w-7 p-0",title:S?"Collapse panel":"Expand panel","aria-label":S?"Collapse panel":"Expand panel",children:S?e.jsx(z,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):e.jsx(z,{name:"fullscreen",className:"h-3.5 w-3.5"})}),e.jsx(he,{type:"button",variant:"ghost",size:"sm",onClick:X,className:"h-7 w-7 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(z,{name:"close",className:"h-3.5 w-3.5"})})]})]}),me=b?S?{"--oc-context-panel-width":N!==null?`${N}px`:"100%",width:N!==null?`${N}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${W}px`}:{"--oc-context-panel-width":`${W}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:ce,"data-context-panel":"true",tabIndex:-1,inert:!b||void 0,className:be("flex min-h-0 flex-col overflow-hidden bg-background",S?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!b&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:oe,style:me,children:[b&&!S&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),b&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!S&&e.jsx("div",{className:be("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",K&&"bg-[var(--interactive-border)]"),onPointerDown:M,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:be("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]",!b&&"pointer-events-none select-none opacity-0"),style:{width:S?N!==null?`${N}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!b,children:[U,e.jsxs("div",{className:be("relative min-h-0 flex-1 overflow-hidden",K&&"pointer-events-none"),children:[ae?e.jsxs("div",{className:be("absolute inset-0 flex",ee?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:A?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Eo,{mode:"editor-only"})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(z,{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(zo,{visible:u})]}):null,Y.map(l=>{const q=st(l.dedupeKey);if(!q)return null;const we=ve(l.id,q,l.readOnly);return we?e.jsx("iframe",{ref:Se=>{if(!Se){pe.current.delete(l.id);return}pe.current.set(l.id,Se)},src:we,title:`Session chat ${q}`,className:be("absolute inset-0 h-full w-full border-0 bg-background",ye===l.id?"block":"hidden"),onLoad:()=>{Te(),De(),k()}},l.id):null}),le.map(l=>e.jsx("div",{className:be("absolute inset-0",j?.id!==l.id&&"hidden"),children:e.jsx(R,{initialUrl:l.targetPath??"",directory:n,tabID:l.id})},l.id)),b?Ne.filter(l=>j?.id===l.id).map(l=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(Po,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:l.diffScope??(l.stagedDiff?"staged":"working"),onDiffScopeChange:Ee,targetFilePath:l.targetPath,flushContent:!0})})},l.id)):null,x?e.jsx("div",{className:be("absolute inset-0",j?.mode==="terminal"?"block":"hidden"),children:e.jsx(mn,{visible:b&&j?.mode==="terminal"})}):null,b&&j?.mode!=="chat"&&!ee&&j?.mode!=="browser"&&j?.mode!=="diff"&&j?.mode!=="terminal"?m:null]})]})]})},ea=150,ta=500,na=[],ra=t=>t>99?"99+":String(t),sa=({surface:t,isActive:n,showActivityDot:s,label:o,description:a,badgeCount:c,badgeAriaLabel:y,badgeDescription:d,orderNumber:f,showOrderNumber:g,onSelect:v})=>{const{attributes:h,listeners:u,setNodeRef:C,transform:p,transition:L,isDragging:P}=Ns({id:t.id}),I=c!=null&&c>0?ra(c):null;return e.jsx("div",{ref:C,style:{transform:Ps.Translate.toString(p),transition:L},className:be("relative",P&&"z-10 opacity-70"),children:e.jsxs(Be,{delayDuration:ea,children:[e.jsx(ze,{asChild:!0,children:e.jsxs("button",{type:"button",...h,...u,onClick:()=>v(t),"aria-label":y??o,"aria-pressed":n,className:be("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:[e.jsx(z,{name:t.icon,className:"h-[18px] w-[18px]"}),g&&f!=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:f===10?"0":f}):I?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:I}):s?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(Ue,{side:"left",sideOffset:8,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:o}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:a}),d?e.jsx("span",{className:"typography-micro text-muted-foreground",children:d}):null]})})]})})},oa=()=>{const t=et(),n=t?Gn(t):"",s=J(b=>n?b.contextPanelByDirectory[n]:void 0),o=J(b=>b.contextRailOrder),a=J(b=>b.setContextRailOrder),c=J(b=>b.openContextSurface),y=J(b=>b.shortcutOverrides),{screenWidth:d}=Tt(),{git:f}=bt(),g=fn(n||null),v=wn(n||null),h=bn(b=>b.ensureStatus);r.useEffect(()=>{n&&h(n,f)},[n,h,f]);const u=r.useMemo(()=>Hr("switch_context_surface",y),[y]),[C,p]=r.useState(!1);r.useEffect(()=>{const b=new Set;let S=null,N=!1;const w=D=>D.length===1&&D>="0"&&D<="9",$=()=>{Wt(u,b)?!N&&S===null&&(S=setTimeout(()=>p(!0),ta)):(N=!1,S!==null&&(clearTimeout(S),S=null),p(!1))},T=D=>{if(b.add(D.key.toLowerCase()),w(D.key)&&Wt(u,b)){N=!0,S!==null&&(clearTimeout(S),S=null),p(!1);return}$()},H=D=>{b.delete(D.key.toLowerCase()),$()},W=()=>{b.clear(),N=!1,S!==null&&(clearTimeout(S),S=null),p(!1)};return window.addEventListener("keydown",T,!0),window.addEventListener("keyup",H,!0),window.addEventListener("blur",W),()=>{window.removeEventListener("keydown",T,!0),window.removeEventListener("keyup",H,!0),window.removeEventListener("blur",W),S!==null&&clearTimeout(S)}},[u]);const L=ws(zt(bs,{activationConstraint:{distance:8}}),zt(ys,{activationConstraint:{delay:200,tolerance:6}})),P=s?.tabs??na,I=P.find(b=>b.id===s?.activeTabId)??null,O=s?.isOpen?I?.mode??null:null,V=g?.files.length??0,_=r.useMemo(()=>Vr({railOrder:o,tabs:P}),[o,d,P]),j=r.useCallback(b=>{const{active:S,over:N}=b;if(!N||S.id===N.id)return;const w=Kr(J.getState().contextRailOrder).map(H=>H.id),$=w.indexOf(S.id),T=w.indexOf(N.id);$===-1||T===-1||a(js(w,$,T))},[a]);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(vs,{sensors:L,collisionDetection:Ss,onDragEnd:j,children:e.jsx(Cs,{items:_.map(b=>b.id),strategy:ks,children:_.map((b,S)=>{const N=b.id==="git"?Nt(v):null,w=N?{...b,...N}:b,$=w.label,T=b.id==="git"&&v===!0?V:0,H=T>0?T:null;return e.jsx(sa,{surface:w,isActive:O===b.mode,showActivityDot:!1,label:$,description:w.description,badgeCount:H,badgeAriaLabel:H!==null?H===1?"{label}, {count} changed file":"{label}, {count} changed files":null,badgeDescription:H!==null?H===1?"{count} changed file":"{count} changed files":null,orderNumber:S+1,showOrderNumber:C,onSelect:W=>c(n,W.mode)},b.id)})})})}):null},aa=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),ia=(t,n,s,o)=>!s||o!==s||t.length===0?[]:Je(t,n,a=>a.name,{limit:10,threshold:.4}),la=new Set,gt=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),s=n.startsWith("//");let o=n.replace(/\/+/g,"/");s&&!o.startsWith("//")&&(o=`/${o}`);const a=o==="/",c=/^[A-Za-z]:\/$/.test(o);return!a&&!c&&(o=o.replace(/\/+$/,"")),o},ca=()=>{const t=J(i=>i.isCommandPaletteOpen),n=J(i=>i.setCommandPaletteOpen),s=J(i=>i.setActiveMainTab),o=J(i=>i.setSettingsDialogOpen),a=J(i=>i.setSettingsPage),c=J(i=>i.setSessionSwitcherOpen),y=J(i=>i.toggleSidebar),d=J(i=>i.openContextOverview),f=J(i=>i.openContextSurface),g=J(i=>i.openContextFile),v=J(i=>i.shortcutOverrides),h=Ie(i=>i.openNewSessionDraft),u=Ie(i=>i.setCurrentSession),C=Xr({archived:!1}),p=qr(r.useCallback(i=>t?i.ids:la,[t])),L=Gr(r.useCallback(i=>t?i.rankById:Yr,[t])),P=Yn(i=>i.currentDirectory),I=Bt(i=>i.getActiveProject()),O=Bt(i=>i.projects),V=et(),_=an(i=>i.searchFiles),{files:j,git:b}=bt(),S=bn(i=>i.ensureStatus),{isMobile:N}=Tt(),w=r.useMemo(()=>V?gt(V):null,[V]),[$,T]=r.useState(""),W=gn($,200).trim(),D=$.trim();r.useEffect(()=>{t&&T("")},[t]),r.useEffect(()=>{if(!t||!b)return;const i=setTimeout(()=>{const m=new Set;for(const Y of C){const le=ut(Y);!le||m.has(le)||(m.add(le),S(le,b))}},0);return()=>clearTimeout(i)},[t,C,b,S]);const E=r.useCallback(()=>n(!1),[n]),B=r.useCallback(i=>()=>{E(),i()},[E]),K=r.useMemo(()=>{const i=[{id:"new-session",title:"New Session",icon:e.jsx(z,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:B(()=>{s("chat"),c(!1),h()})},{id:"add-project",title:"Add Project",icon:e.jsx(z,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:B(()=>{Jr.requestDirectoryDialog()})},{id:"toggle-sidebar",title:N?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(z,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:N?"Show Session Switcher":"Toggle Sidebar",onSelect:B(()=>{if(N){const{isSessionSwitcherOpen:m}=J.getState();c(!m)}else y()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(z,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:B(()=>{P&&f(P,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(z,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:B(()=>{P&&d(P)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(z,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:B(()=>o(!0))}];return Jn()&&i.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(z,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:B(()=>{cn("desktop_open_draft_mini_chat_window",{directory:gt(P||I?.path||""),projectId:I?.id??null}).catch(m=>{console.warn("[command-palette] failed to open draft mini chat window",m)})})}),i},[B,N,s,c,h,y,f,P,d,o,I?.id,I?.path]),ne=r.useMemo(()=>{const i=Qn();return{isWeb:!i&&Zn(),isDesktop:i,isMobile:N}},[N]),fe=r.useMemo(()=>ur.filter(i=>i.slug!=="home").filter(i=>i.isAvailable?i.isAvailable(ne):!0).map(i=>{const m=hr(i.slug)??"settings-3",Y=(i.keywords??[]).join(" ");return{id:`settings:${i.slug}`,title:i.title,icon:e.jsx(z,{name:m,className:"mr-2 h-4 w-4"}),searchText:`${i.title} ${i.group} ${Y}`,onSelect:B(()=>{a(i.slug),o(!0)})}}),[ne,B,a,o]),G=r.useMemo(()=>Qr(C,p,L),[C,p,L]),ie=Zr(),te=r.useCallback((i,m)=>m&&ie.get(m)?.trim()||null,[ie]),[ce,pe]=r.useState([]),[je,ge]=r.useState(""),xe=aa(w,W);r.useEffect(()=>{if(!t){pe([]),ge("");return}if(!xe){pe([]),ge("");return}if(!w){pe([]),ge("");return}let i=!1;return _(w,W,10,{type:"file"}).then(m=>{i||(pe(m.map(Y=>({path:gt(Y.path),name:Y.name,relativePath:Y.relativePath}))),ge(xe))}).catch(()=>{i||(pe([]),ge(xe))}),()=>{i=!0}},[t,w,W,xe,_]);const se=D.length>0,Ce=r.useMemo(()=>se?Je(K,D,i=>i.searchText,{limit:7,noFuzzy:!0}):K.map(i=>({item:i,score:0})),[K,D,se]),ke=r.useMemo(()=>se?Je(fe,D,i=>i.searchText,{limit:7,noFuzzy:!0}):[],[fe,D,se]),M=r.useMemo(()=>se?Je(G,D,i=>i.title||"",{limit:7,threshold:.2}):G.slice(0,5).map(i=>({item:i,score:0})),[G,D,se]),F=r.useMemo(()=>t?ia(ce,W,xe,je):[],[t,ce,je,xe,W]),X=t&&xe.length>0&&je!==xe,Q=r.useMemo(()=>{if(!se)return[];const i=O.map(m=>({...m,displayName:m.label||m.path.split("/").pop()||m.path,searchText:`${m.label||""} ${m.path}`}));return Je(i,D,m=>m.searchText,{limit:7,threshold:.4})},[O,D,se]),oe=Ce.map(i=>i.item),ye=ke.map(i=>i.item),de=M.map(i=>i.item),ve=se?F.map(i=>i.item):[],Ee=se?Q.map(i=>i.item):[],Te=r.useMemo(()=>{if(!se)return["commands","sessions"];const i=Y=>Y.length?Y[0].score:1/0,m=[{key:"commands",score:i(Ce)},{key:"settings",score:i(ke)},{key:"sessions",score:i(M)},{key:"files",score:i(F)},{key:"projects",score:i(Q)}];return m.sort((Y,le)=>Y.score-le.score),m.map(Y=>Y.key)},[se,Ce,ke,M,F,Q]),De=r.useCallback(i=>{E(),u(i.id,ut(i))},[E,u]),k=r.useCallback(async i=>{if(!w)return;const m=await jn(j,i,{directory:w});if(!m.ok){ue.error(Cn(m.reason));return}g(w,i),E()},[w,j,g,E]),re=r.useCallback((i,m)=>{E(),h({selectedProjectId:i,directoryOverride:m})},[E,h]),Z=r.useCallback(i=>vn(Sn(i,v)),[v]);return e.jsxs(vt,{open:t,onOpenChange:n,children:[e.jsxs(jt,{className:"sr-only",children:[e.jsx(Ct,{children:"Command Palette"}),e.jsx(kt,{children:"Search files, sessions, and commands."})]}),e.jsx(St,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs(es,{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(ts,{value:$,onValueChange:T,placeholder:"Search files, sessions, commands..."}),e.jsxs(ns,{children:[e.jsx(rs,{children:"No results found."}),Te.map(i=>i==="commands"&&oe.length>0?e.jsx(qe,{children:oe.map(m=>e.jsxs(Ge,{value:m.id,onSelect:m.onSelect,children:[m.icon,e.jsx("span",{children:m.title}),m.shortcutId?e.jsx(ss,{children:Z(m.shortcutId)}):null]},m.id))},"commands"):i==="settings"&&ye.length>0?e.jsx(qe,{children:ye.map(m=>e.jsxs(Ge,{value:m.id,onSelect:m.onSelect,children:[m.icon,e.jsx("span",{children:m.title})]},m.id))},"settings"):i==="sessions"&&de.length>0?e.jsx(qe,{children:de.map(m=>{const Y=m.title||"Untitled Session",le=ut(m),Ne=te(m.id,le);return e.jsxs(Ge,{value:`session:${m.id}`,onSelect:()=>De(m),children:[e.jsx(z,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:Y}),Ne?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(z,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:Ne})]}):null]},m.id)})},"sessions"):i==="files"&&ve.length>0?e.jsx(qe,{children:ve.map(m=>{const Y=os(m.relativePath||m.name,{maxLength:80});return e.jsxs(Ge,{value:`file:${m.path}`,onSelect:()=>{k(m.path)},children:[e.jsx(wt,{filePath:m.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":m.relativePath,children:Y})]},`file:${m.path}`)})},"files"):i==="projects"&&Ee.length>0?e.jsx(qe,{children:Ee.map(m=>{const Y=m.displayName;return e.jsxs(Ge,{value:`project:${m.id}`,onSelect:()=>re(m.id,m.path),children:[e.jsx(z,{name:"folder",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:Y}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:m.path})]},`project:${m.id}`)})},"projects"):null),X?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},sn=(t,n,s)=>is(t)?vn(Sn(t,s)):n,da=()=>{const t=J(c=>c.isHelpDialogOpen),n=J(c=>c.setHelpDialogOpen),s=J(c=>c.shortcutOverrides),o=as(),a=[{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 + ${o} + 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:"toggle_prompt_navigator",descriptionKey:"Toggle Prompt Navigator",icon:"list-unordered",keys:""},{id:"abort_run",descriptionKey:"Abort active run (double press)",icon:"close-circle",keys:""}]},{categoryKey:"Panels",items:[{id:"toggle_right_sidebar",descriptionKey:"helpDialog.item.toggleRightSidebar",icon:"layout-right",keys:""},{id:"open_right_sidebar_git",descriptionKey:"helpDialog.item.openRightSidebarGitTab",icon:"git-branch",keys:""},{id:"open_right_sidebar_files",descriptionKey:"helpDialog.item.openRightSidebarFilesTab",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{id:"toggle_terminal_expanded",descriptionKey:"helpDialog.item.toggleTerminalExpanded",icon:"window",keys:""},{keys:[`${o} + 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:"cycle_services_tab",descriptionKey:"helpDialog.item.cycleServicesTab",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"Open Settings",icon:"settings-3",keys:""}]}];return e.jsx(vt,{open:t,onOpenChange:n,children:e.jsxs(St,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(jt,{children:[e.jsxs(Ct,{className:"flex items-center gap-2",children:[e.jsx(z,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(kt,{children:"Use these keyboard shortcuts to navigate PiChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:a.map(c=>e.jsxs("div",{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(y=>{const d=y.id?sn(y.id,Array.isArray(y.keys)?y.keys[0]:y.keys,s):Array.isArray(y.keys)?y.keys:y.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:[y.icon&&e.jsx(z,{name:y.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:y.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(d)?d:[d]).map((f,g)=>e.jsxs(r.Fragment,{children:[g>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:f})]},`${f}-${g}`))})]},y.id||y.descriptionKey)})})]},c.categoryKey))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(z,{name:"question",className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsxs("li",{children:["• ",`Use Command Palette (${sn("open_command_palette",`${o} P`,s)}) to quickly access all actions`]}),e.jsxs("li",{children:["• ","The 5 most recent sessions appear in the Command Palette"]}),e.jsxs("li",{children:["• ","Theme cycling remembers your preference across sessions"]})]})]})]})})]})]})})},ua=r.createContext(null),ha=({children:t,value:n})=>e.jsx(ua.Provider,{value:n,children:t}),on=Fe(()=>Le(()=>import("./GitView-CkUONO1-.js"),__vite__mapDeps([127,8,1,2,6,3,4,5,7,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,128,115,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,114,116,117])).then(t=>({default:t.GitView}))),pa=Fe(()=>Le(()=>import("./DiffView-d23o9CKP.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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118])).then(t=>({default:t.DiffView}))),ma=Fe(()=>Le(()=>import("./FilesView-DIDB-xK7.js"),__vite__mapDeps([119,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,120,121,122,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,123,124,116,117,125,126,114,115])).then(t=>({default:t.FilesView}))),fa=Fe(()=>Le(()=>import("./DiagramView-E4HJ4ZPU.js"),__vite__mapDeps([129,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,125,126])).then(t=>({default:t.DiagramView}))),ga=Fe(()=>Le(()=>import("./SettingsView-C2dCv0r7.js").then(t=>t.b),__vite__mapDeps([130,1,2,6,3,4,5,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,131,132,115])).then(t=>({default:t.SettingsView}))),xa=Fe(()=>Le(()=>import("./SettingsWindow-DsMhdX5H.js"),__vite__mapDeps([133,1,2,6,3,4,5,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,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,130,111,112,113,131,132,115])).then(t=>({default:t.SettingsWindow}))),wa=()=>{const t=J(T=>T.isSidebarOpen),n=J(T=>T.activeMainTab),s=J(T=>T.setIsMobile),o=J(T=>T.isSessionSwitcherOpen),a=J(T=>T.isSettingsDialogOpen),c=J(T=>T.setSettingsDialogOpen),[y,d]=r.useState(!1);r.useEffect(()=>{a&&d(!0)},[a]),r.useEffect(()=>{const T=()=>J.getState().closeMainSurfaces(),H=Ie.subscribe((D,E)=>{const B=!!D.currentSessionId&&D.currentSessionId!==E.currentSessionId,K=!!D.newSessionDraft?.open&&D.newSessionDraft!==E.newSessionDraft;(B||K)&&T()}),W=J.subscribe((D,E)=>{D.activeMainTab!==E.activeMainTab&&T()});return()=>{H(),W()}},[]);const{isMobile:f}=Tt(),g=r.useRef(!1),[v,h]=r.useState(!1),[u,C]=r.useState(!1),[p,L]=r.useState(!1),[P,I]=r.useState(!1),O=r.useCallback(T=>{h(T),J.getState().setSessionSwitcherOpen(T)},[]),V=r.useRef(typeof window>"u"?0:window.innerWidth),_=Ut(-V.current),j=Me.useRef(0),b=Ut(V.current),S=Me.useRef(0);Me.useEffect(()=>{f&&(j.current=window.innerWidth,S.current=window.innerWidth)},[f]),Me.useEffect(()=>{if(!f){L(!1);return}v&&L(!0),Ht(_,v?0:-j.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[v,f,_]),Me.useEffect(()=>{if(!f){I(!1);return}u&&I(!0),Ht(b,u?0:S.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[f,u,b]),Me.useEffect(()=>{if(f)return _.on("change",T=>{const H=j.current||V.current,W=v||T>-H+.5;L(D=>D===W?D:W)})},[f,_,v]),Me.useEffect(()=>{if(f)return b.on("change",T=>{const H=S.current||V.current,W=u||T<H-.5;I(D=>D===W?D:W)})},[f,u,b]),Me.useEffect(()=>{f&&!o&&v&&O(!1)},[o,f,v,O]),Me.useEffect(()=>{if(!f){g.current=!1;return}g.current||(g.current=!0,O(!1),C(!1))},[f,O]),Me.useEffect(()=>{if(!f||n!=="chat"||v||u||a)return;let T=!1,H;const W=D=>{H=window.setTimeout(()=>{if(T)return;const E=Ie.getState(),B=J.getState();if(!(B.activeMainTab!=="chat"||B.isSettingsDialogOpen||E.currentSessionId||E.newSessionDraft?.open)){if(E.isLoading){W(250);return}E.openNewSessionDraft({automatic:!0})}},D)};return W(500),()=>{T=!0,H!==void 0&&window.clearTimeout(H)}},[n,f,a,v,u]),Me.useEffect(()=>{!f||!a||(O(!1),C(!1))},[f,a,O]),r.useEffect(()=>{J.getState().isMobile!==f&&s(f)},[f,s]);const N=r.useCallback(()=>{v&&O(!1),C(!u)},[v,u,O]),w=r.useMemo(()=>{if(!f&&n!=="terminal"&&n!=="diagram")return null;switch(n){case"git":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(on,{isActive:!u})});case"diff":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(pa,{})});case"terminal":return e.jsx(mn,{});case"files":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(ma,{})});case"context":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(pn,{})});case"diagram":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(fa,{})});default:return null}},[n,f,u]),$=n==="chat";return e.jsxs(pr,{children:[e.jsx(mr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:be("main-content-safe-area",f?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(ca,{}),e.jsx(da,{}),e.jsx(fr,{}),f?e.jsxs(ha,{value:{leftDrawerOpen:v,rightDrawerOpen:u,toggleLeftDrawer:()=>{const T=!v;u&&C(!1),O(T)},toggleRightDrawer:N,leftDrawerX:_,rightDrawerX:b,leftDrawerWidth:j,rightDrawerWidth:S,setMobileLeftDrawerOpen:O,setRightSidebarOpen:C},children:[!a&&e.jsx(It,{onToggleLeftDrawer:()=>{const T=!v;u&&C(!1),O(T)},onToggleRightDrawer:()=>{N()},leftDrawerOpen:v,rightDrawerOpen:u}),e.jsx("div",{"data-page-scroll-lock":"true",className:be("flex flex-1 overflow-hidden relative",a&&"hidden"),children:e.jsxs("main",{className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[e.jsx("div",{className:be("absolute inset-0",!$&&"invisible"),children:e.jsx(Ae,{children:e.jsx(Lt,{active:$&&!a})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ae,{children:w})}),e.jsx(Ae,{children:e.jsx(Ot,{})}),e.jsx(Vt.div,{className:be("absolute inset-0 z-20 bg-sidebar",!p&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:_},"aria-hidden":!v,children:e.jsx(Ae,{children:e.jsx($t,{mobileVariant:!0,isVisible:p})})}),P&&e.jsx(Vt.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:b},"aria-hidden":!u,children:e.jsx(Ae,{children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(on,{isActive:u})})})})]})}),a&&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(r.Suspense,{fallback:null,children:e.jsx(ga,{onClose:()=>c(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(Es,{isOpen:t,isMobile:f,className:"border-border",children:e.jsx($t,{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(It,{}),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:be("absolute inset-0",!$&&"invisible"),children:e.jsx(Ae,{children:e.jsx(Lt,{active:$&&!a})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ae,{children:w})}),e.jsx(Ae,{children:e.jsx(Ot,{})})]}),e.jsx(Zo,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Ae,{children:e.jsx(oa,{})})})]})]})]}),y?e.jsx(r.Suspense,{fallback:null,children:e.jsx(xa,{open:a,onOpenChange:c})}):null]})]})]})},ya=()=>(us(),wr(),e.jsxs(yr,{children:[e.jsx(hs,{embeddedBackgroundWorkEnabled:!0}),e.jsx(wa,{}),e.jsx(ps,{}),e.jsx(ms,{})]}));function ba({apis:t}){const n=t??hn(),[s,o]=r.useState(0);return r.useEffect(()=>er(a=>{a.runtimeKey!==a.previousRuntimeKey&&(xr(a),o(c=>c+1))}),[]),r.useEffect(()=>{tr()},[s]),r.useEffect(()=>{n&&nr(n)},[n]),n?e.jsx(Ae,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(ls,{apis:n,children:e.jsx(cs,{children:e.jsx(ds,{children:e.jsx(ya,{})})},s)})})}):e.jsx(Ae,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const $n=document.getElementById("root");if(!$n)throw new Error("Root element not found");Bn.createRoot($n).render(e.jsx(Me.StrictMode,{children:e.jsx(fs,{children:e.jsx(gs,{children:e.jsx(xs,{children:e.jsx(ba,{apis:hn()??void 0})})})})}));
@@ -1 +0,0 @@
1
- import{j as n,R as a,e as ye,r as we}from"./vendor-react-DYyjh7Q0.js";import"./vendor-katex-CHD9BdDO.js";import{l as T,Q as ge,C as U,u as Z,J as xe,q as se,o as ve,w as Se,v as Ie}from"./index-BhXma4dv.js";import{u as be,a as je,b as De,s as Ce,c as Pe,d as Me}from"./useWindowTitle-CnF4pKz0.js";import{d2 as Ee,m as h,bq as _e,b as X,h as f,aF as ee,d3 as ke,K as Le,R as Ne,cQ as Ae,ck as Re,c$ as ie,cZ as Oe,I as $,c_ as Be,B as ae,f as Te,cY as N,d4 as ce,d5 as ze,i as Ue,t as Fe,b6 as He,ae as We,af as $e,a0 as Ge,ah as Ke,ai as Ve,aj as qe,al as Je,am as Qe,d6 as Ye,cl as Ze,at as Xe,au as et,av as tt}from"./SessionSwitcherDropdown-NbVfnqQQ.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./runtimeSurface-CouGjZ3A.js";import"./vendor-dnd-kit-core-GipZW2tY.js";import"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import"./vendor-base-ui-DwfTg5wD.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BuDklWi8.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-Wdz6Qsow.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-pXtfpqbT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-CrbeaEAU.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-3xMyV7a2.js";import"./vendor-codemirror-lang-json-BTvAjwkJ.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-C4jEScp7.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-C1Svvdey.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BloD9GN-.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-qBLdzwMc.js";import"./vendor-codemirror-lang-python-CR2g6ukK.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-Bzf12ODH.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-framer-motion-DJASDzNt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-sonner-dWA7qvjr.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";const rt=({mode:e,children:r})=>n.jsx(Ee.Provider,{value:e,children:r}),nt=e=>{const r=typeof e=="string"?e.trim():"";if(!r)return"";const o=typeof window<"u"?window.__PICHAMBER_HOME__:"";if(o&&r===o)return"~";if(o&&r.startsWith(`${o}/`))return`~/${r.slice(o.length+1)}`;const d=r.split("/").filter(Boolean);return d.length<=3?r:`.../${d.slice(-3).join("/")}`},G=e=>{const r=typeof e=="string"?e.trim():"";if(!r)return"";const o=r.replace(/\\/g,"/");return o==="/"?"/":o.replace(/\/+$/,"")},ot=({mode:e})=>{const r=h(t=>t.currentSessionId),o=h(t=>!!t.newSessionDraft?.open),d=h(t=>t.newSessionDraft?.selectedProjectId??null),i=T(t=>t.currentDirectory),u=X(t=>t.projects),c=X(t=>t.getActiveProject()),M=f(t=>t.getCurrentModel),k=f(t=>t.providers),p=ee(),m=ke(r??""),E=Le(),D=Ne(t=>t.ensureStatus),_=h(t=>t.newSessionDraft?.open?G(t.newSessionDraft.directoryOverride??""):""),[w,v]=a.useState(!1),C=typeof window<"u"?window.__PICHAMBER_MACOS_MAJOR__??0:0,S=Number.isFinite(C)&&C>0,{usesFramelessChrome:x,side:A}=Ae(),s=S?C>=26?"h-12":C<=15?"h-14":"":"",g=a.useMemo(()=>r?p.find(t=>t.id===r)??null:null,[r,p]);a.useEffect(()=>{ge()&&U("desktop_get_window_pinned").then(t=>{typeof t?.pinned=="boolean"&&v(t.pinned)})},[]);const y=g?.title?.trim()||(o||e==="draft"?"New session":"Session"),I=G(g?.directory??null),K=G(i),b=I||_||K,te=nt(b);a.useEffect(()=>{b&&D(b,E.git).catch(()=>{})},[D,b,E.git]);const re=a.useMemo(()=>{const t=b;return t?u.map(l=>({...l,normalizedPath:G(l.path)})).filter(l=>l.normalizedPath&&(l.normalizedPath===t||t.startsWith(`${l.normalizedPath}/`))).sort((l,B)=>B.path.length-l.path.length)[0]??null:null},[b,u]),de=a.useMemo(()=>{const t=re??c;if(!t)return te||"PiChamber";const l=t.label?.trim();return l||(t.path.split(/[\\/]/).filter(Boolean).at(-1)??t.path)},[c,te,re]),V=Re(b||null),ne=V&&V!=="HEAD"?V:null,oe=M(),le=a.useMemo(()=>{for(let t=m.length-1;t>=0;t-=1){const l=m[t];if(l.role!=="assistant"||typeof l.providerID!="string"||typeof l.modelID!="string")continue;const W=k.find(z=>z.id===l.providerID)?.models.find(z=>z.id===l.modelID);if(W)return W}},[m,k]),F=oe?.limit?oe:le,R=F&&typeof F.limit=="object"&&F.limit!==null?F.limit:null,O=R&&typeof R.context=="number"?R.context:0,H=R&&typeof R.output=="number"?R.output:0,j=a.useMemo(()=>{if(!r||m.length===0)return null;let t,l;for(let Q=m.length-1;Q>=0;Q-=1){const Y=m[Q];if(Y.role!=="assistant")continue;const L=Y.tokens;if(!L)continue;if(L.input+L.output+L.reasoning+(L.cache?.read??0)+(L.cache?.write??0)>0){t=L,l=Y.id;break}}if(!t)return null;const B=t.input+t.output+t.reasoning+(t.cache?.read??0)+(t.cache?.write??0),W=O>0?O:2e5,z=O>0?Math.round(B/O*100):0,he=H>0?Math.round(t.output/H*100):void 0;return{totalTokens:B,percentage:z,contextLimit:O||0,outputLimit:H||void 0,normalizedOutput:he,thresholdLimit:W,lastMessageId:l}},[O,r,m,H]),[P,q]=a.useState(null),ue={WebkitAppRegion:"drag"},J={WebkitAppRegion:"no-drag"};a.useEffect(()=>{if(!r){q(t=>t===null?t:null);return}if(j&&j.totalTokens>0){q(t=>t&&t.totalTokens===j.totalTokens&&t.percentage===j.percentage&&t.contextLimit===j.contextLimit&&(t.outputLimit??0)===(j.outputLimit??0)&&(t.normalizedOutput??0)===(j.normalizedOutput??0)&&t.thresholdLimit===j.thresholdLimit&&t.lastMessageId===j.lastMessageId?t:j);return}q(t=>t===null?t:null)},[j,r]);const me=P&&P.contextLimit>0?Math.min(999,P.totalTokens/P.contextLimit*100):0,pe=a.useCallback(()=>{const t=!w;v(t),U("desktop_set_window_pinned",{pinned:t}).catch(()=>{v(!t)})},[w]),fe=a.useCallback(()=>{const t=r?{sessionId:r,directory:g?.directory??i??""}:{mode:"draft",directory:b||i||"",projectId:d};U("desktop_focus_main_window",t).then(l=>l?.focused===!0?U("desktop_close_current_window"):null)},[i,r,d,b,g]);return n.jsxs("header",{className:Te("flex items-center gap-3 bg-background pr-3",S?"pl-[5.5rem]":"pl-3",x?"h-12":s||"min-h-14"),style:ue,children:[x&&A==="left"?n.jsx(ie,{visible:!0,position:"left"}):null,n.jsx(Oe,{children:n.jsxs("button",{type:"button","aria-label":"Open session switcher",style:J,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[n.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:y}),n.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[n.jsx("span",{className:"truncate",children:de}),ne?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[n.jsx($,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),n.jsx("span",{className:"truncate",children:ne})]}):null]})]})}),n.jsx("div",{className:"min-w-0 flex-1"}),P&&P.totalTokens>0?n.jsx(Be,{totalTokens:P.totalTokens,percentage:me,colorPercentage:P.percentage,contextLimit:P.contextLimit,outputLimit:P.outputLimit??0,className:"h-9 shrink-0 pl-1 pr-1 typography-ui-label",valueClassName:"font-semibold leading-none",hideIcon:!0,showPercentIcon:!0,percentIconClassName:"h-4.5 w-4.5"}):null,n.jsx(ae,{type:"button",variant:"ghost",size:"icon",onClick:pe,"aria-label":w?"Unpin Mini Chat window":"Pin Mini Chat window",title:w?"Unpin window":"Pin above other windows",style:J,children:w?n.jsx($,{name:"pushpin-2-fill",className:"h-4 w-4"}):n.jsx($,{name:"pushpin-2",className:"h-4 w-4"})}),n.jsx(ae,{type:"button",variant:"ghost",size:"icon",onClick:fe,"aria-label":"Open session in main window",title:"Open in main window",style:J,children:n.jsx($,{name:"external-link",className:"h-4 w-4"})}),n.jsx(ie,{visible:x&&A==="right",position:"right"})]})},st=({mode:e,autoOpenDraft:r=!1,unavailable:o=!1})=>{const d=h(i=>i.currentSessionId);return n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background text-foreground",children:[n.jsx(ot,{mode:e}),n.jsx("main",{className:"min-h-0 flex-1",children:o?n.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center typography-ui-label text-muted-foreground",children:n.jsxs("div",{className:"max-w-sm rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-3",children:[n.jsx("div",{className:"font-medium text-foreground",children:"Session unavailable"}),n.jsx("div",{className:"mt-1 typography-small text-muted-foreground",children:"This session could not be loaded. It may have been deleted, archived, or opened from a different project context."})]})}):n.jsx(rt,{mode:"mini-chat",children:n.jsx(_e,{autoOpenDraft:r},d??"no-session")})})]})},it=()=>{const e=Z(i=>i.shortcutOverrides),r=T(i=>i.currentDirectory),o=X(i=>i.getActiveProject()),d=h(i=>i.openNewSessionDraft);a.useEffect(()=>{const i=c=>He(c,e),u=c=>{if(N(c,i("focus_input"))){c.preventDefault(),ce();return}if(xe()&&N(c,i("new_mini_chat"))){c.preventDefault(),U("desktop_open_draft_mini_chat_window",{directory:r||o?.path||"",projectId:o?.id??null})?.catch(p=>{console.warn("[mini-chat-shortcuts] failed to open draft mini chat window",p)});return}if(N(c,i("new_chat"))){c.preventDefault(),d({selectedProjectId:o?.id??null,directoryOverride:r||o?.path||null,preserveDirectoryOverride:!!(r||o?.path)}),ce();return}if(N(c,i("open_model_selector"))){c.preventDefault();const{isModelSelectorOpen:p,setModelSelectorOpen:m}=Z.getState();m(!p);return}if(N(c,i("cycle_thinking_variant"))){if(f.getState().getCurrentModelVariants().length===0)return;c.preventDefault(),ze(1).then(E=>{const D=h.getState().currentSessionId,_=f.getState().currentAgentName,w=f.getState().currentProviderId,v=f.getState().currentModelId;D&&_&&w&&v&&Ue.getState().saveAgentModelVariantForSession(D,_,w,v,E)}).catch(()=>{Fe.error("Couldn't update thinking")});return}const M=N(c,i("cycle_favorite_model_forward")),k=N(c,i("cycle_favorite_model_backward"));if(M||k){const{favoriteModels:p,addRecentModel:m}=Z.getState();if(p.length===0)return;c.preventDefault();const{currentProviderId:E,currentModelId:D,setProvider:_,setModel:w}=f.getState(),v=p.findIndex(x=>x.providerID===E&&x.modelID===D),S=p[(v+(M?1:-1)+p.length)%p.length];_(S.providerID),w(S.modelID),m(S.providerID,S.modelID)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[o?.id,o?.path,r,d,e])},at="pichamber:mini-chat-presence",ct=()=>{const e=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams,r=e.get("mode")==="session"?"session":"draft",o=e.get("sessionId")?.trim()||null,d=e.get("directory")?.trim()||null,i=e.get("projectId")?.trim()||null;return{mode:r,sessionId:o,directory:d,projectId:i}},dt=({config:e})=>{const r=ee(),o=T(s=>s.currentDirectory),d=T(s=>s.setDirectory),i=h(s=>s.currentSessionId),u=h(s=>!!s.newSessionDraft?.open),c=h(s=>s.newSessionDraft?.open?s.newSessionDraft.bootstrapPendingDirectory??s.newSessionDraft.directoryOverride??"":""),M=h(s=>s.setCurrentSession),k=h(s=>s.openNewSessionDraft),p=f(s=>s.initializeApp),m=f(s=>s.isInitialized),E=f(s=>s.isConnected),D=f(s=>s.loadProviders),_=f(s=>s.loadAgents),w=f(s=>s.providers.length),v=f(s=>s.agents.length),C=Ze();a.useEffect(()=>{p()},[p]),a.useEffect(()=>{if(m)return;let s=!0,g=0;const y=window.setInterval(()=>{if(s){if(g+=1,g>10){window.clearInterval(y);return}f.getState().isInitialized||f.getState().initializeApp()}},1e3);return()=>{s=!1,window.clearInterval(y)}},[m]);const S=a.useRef(!1);a.useEffect(()=>{if(!S.current&&e.mode==="session"&&e.directory){if(o===e.directory){S.current=!0;return}d(e.directory,{showOverlay:!1}),S.current=!0}},[e.directory,e.mode,o,d]),a.useEffect(()=>{e.mode!=="draft"||!u||i||!c||o===c||d(c,{showOverlay:!1})},[e.mode,o,i,c,u,d]),a.useEffect(()=>{E&&(w===0&&D({source:"electronMiniChat:recovery"}),v===0&&_({source:"electronMiniChat:recovery"}))},[v,E,_,D,w]);const x=a.useRef(!1);a.useEffect(()=>{if(x.current||e.mode!=="session"||!e.sessionId)return;if(i===e.sessionId){x.current=!0;return}if(i){x.current=!0;return}const s=r.find(y=>y.id===e.sessionId);if(!s){C.ensureSessionRenderable(e.sessionId);return}const g=s.directory??e.directory;M(e.sessionId,g),x.current=!0},[e,i,r,M,C]),a.useEffect(()=>{const s=g=>{const y=g.detail,I=typeof y?.sessionId=="string"?y.sessionId.trim():"";if(!I||h.getState().currentSessionId===I)return;const K=typeof y?.directory=="string"&&y.directory.trim().length>0?y.directory.trim():r.find(b=>b.id===I)?.directory??null;C.ensureSessionRenderable(I),M(I,K),x.current=!0};return window.addEventListener("pichamber:open-session",s),()=>window.removeEventListener("pichamber:open-session",s)},[r,M,C]),a.useEffect(()=>{e.mode!=="draft"||u||i||k({selectedProjectId:e.projectId,directoryOverride:e.directory,preserveDirectoryOverride:!!e.directory})},[e,i,u,k]);const A=a.useRef(!1);return a.useEffect(()=>{if(A.current||!m)return;const s=()=>{if(A.current)return;A.current=!0;const I=typeof document<"u"?document.getElementById("initial-loading"):null;I&&(I.classList.add("fade-out"),window.setTimeout(()=>I.remove(),300))},g=e.mode==="session"?i===e.sessionId:u,y=window.setTimeout(s,g?100:1500);return()=>window.clearTimeout(y)},[m,e.mode,e.sessionId,i,u]),null},lt=()=>{const e=h(o=>o.currentSessionId),r=T(o=>o.currentDirectory);return a.useEffect(()=>{if(!e||!r||typeof BroadcastChannel>"u")return;const o=new BroadcastChannel(at),d=c=>{o.postMessage({type:"mini-chat-session-presence",sessionId:e,directory:r,viewed:c})};d(!0);const i=window.setInterval(()=>d(!0),5e3),u=()=>d(!1);return window.addEventListener("beforeunload",u),()=>{window.clearInterval(i),window.removeEventListener("beforeunload",u),d(!1),o.close()}},[r,e]),null},ut=e=>{const r=ee(),o=h(u=>u.currentSessionId),[d,i]=a.useState(!1);return a.useEffect(()=>{if(e.mode!=="session"||!e.sessionId||o===e.sessionId){i(!1);return}if(r.some(c=>c.id===e.sessionId)){i(!1);return}const u=window.setTimeout(()=>i(!0),5e3);return()=>window.clearTimeout(u)},[e.mode,e.sessionId,o,r]),d};function mt({apis:e}){const r=a.useMemo(()=>ct(),[]),o=T(d=>d.currentDirectory);return a.useEffect(()=>{We.setDirectory(o||r.directory||void 0)},[r.directory,o]),a.useEffect(()=>(se(e),()=>se(null)),[e]),$e(),it(),be({enabled:!0}),je(),n.jsx(Ge,{children:n.jsx(Ke,{directory:o||r.directory,children:n.jsx(Ve,{apis:e,children:n.jsx(qe,{delayDuration:300,skipDelayDuration:150,children:n.jsxs("div",{className:"h-full text-foreground bg-background",children:[n.jsx(pt,{config:r}),n.jsx(Je,{}),n.jsx(Qe,{})]})})})})})}const pt=({config:e})=>{const r=ut(e);return n.jsxs(n.Fragment,{children:[n.jsx(dt,{config:e}),n.jsx(lt,{}),n.jsx(Ye,{embeddedBackgroundWorkEnabled:!0}),n.jsx(st,{mode:e.mode,autoOpenDraft:e.mode==="draft",unavailable:r})]})},ft=()=>{Se().then(()=>{Promise.all([Ie(),De()]).catch(e=>{console.error("[mini-chat-main] settings init failed:",e)}),Ce(),Pe(),Me()}).catch(e=>{console.error("[mini-chat-main] appearance init failed:",e)})};function Wr(e){const r=e??ve();if(!r)throw new Error("Runtime APIs not registered");ft();const o=document.getElementById("root");if(!o)throw new Error("Root element not found");ye.createRoot(o).render(n.jsx(we.StrictMode,{children:n.jsx(Xe,{children:n.jsx(et,{children:n.jsx(tt,{children:n.jsx(mt,{apis:r})})})})}))}export{Wr as renderElectronMiniChatApp};