@pi-chamber/web 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/bin/cli.test.js +6 -8
  2. package/bin/lib/cli-tunnel-capabilities.js +0 -2
  3. package/dist/assets/{CommitSection-DPjTv8fA.js → CommitSection-C336377Z.js} +1 -1
  4. package/dist/assets/{DiagramEditor-ChOor9l9.js → DiagramEditor-gHLCXHtr.js} +1 -1
  5. package/dist/assets/{DiagramView-3hAT86v_.js → DiagramView-DlHzRRBc.js} +1 -1
  6. package/dist/assets/{DiffView-D1dyOiw2.js → DiffView-5wHwK-lg.js} +1 -1
  7. package/dist/assets/{FilesView-BCzghrc7.js → FilesView-5bswI3JZ.js} +6 -6
  8. package/dist/assets/{GitView-CYF1E1p4.js → GitView-BfykGpGh.js} +4 -4
  9. package/dist/assets/{JsonTreeView-CrJO6LNu.js → JsonTreeView-HVwQS7qG.js} +1 -1
  10. package/dist/assets/{MarkdownRendererImpl-BmKjrkGD.js → MarkdownRendererImpl-kjd4e0N8.js} +1 -1
  11. package/dist/assets/{PatchDiff-DgvPLx6x.js → PatchDiff-Dlm4RU8n.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-InnT0JVA.js → PierreDiffViewer-St32rXlD.js} +1 -1
  13. package/dist/assets/{SessionSwitcherDropdown-C0OdvirK.js → SessionSwitcherDropdown-D5bWfZNA.js} +100 -101
  14. package/dist/assets/SettingsView-FGe5TEQq.js +4 -0
  15. package/dist/assets/SettingsWindow-Ck_uhTnx.js +1 -0
  16. package/dist/assets/{ToolOutputDialog-gzwcb8nI.js → ToolOutputDialog-BCONUv3r.js} +5 -5
  17. package/dist/assets/{ToolPartDiffPreview-C45V5bhy.js → ToolPartDiffPreview-BdVuk2kc.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-uKfnkQWb.js → VirtualizedFileDiff-BsAZM0jo.js} +1 -1
  19. package/dist/assets/{collapsible-Bq8sDiKS.js → collapsible-Wnmq-13H.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-BPgZ_RSe.js → computeVirtualFileMetrics-skbyL2Az.js} +2 -2
  21. package/dist/assets/{contextFileOpenGuard-CydO7PkI.js → contextFileOpenGuard-BsxQITMZ.js} +1 -1
  22. package/dist/assets/index-8TL2HlaR.js +8 -0
  23. package/dist/assets/{index-BSuNNtBh.js → index-Bfp6eYap.js} +1 -1
  24. package/dist/assets/index-riABQmQ_.css +1 -0
  25. package/dist/assets/{isDiffPlainText-f9b4cKNo.js → isDiffPlainText-dZkfk3yG.js} +1 -1
  26. package/dist/assets/{isFilePlainText-BjESb-gU.js → isFilePlainText-UL_tMQZx.js} +1 -1
  27. package/dist/assets/{main-B508FBXr.js → main-CHQfoyRP.js} +2 -2
  28. package/dist/assets/main-DbnYXZeK.js +133 -0
  29. package/dist/assets/{markdownCore-BFmf8a-O.js → markdownCore-qX3mJFkL.js} +2 -2
  30. package/dist/assets/{miniChat-BTlz8IPL.js → miniChat-3QtCNwHl.js} +2 -2
  31. package/dist/assets/{mobile-DBkrRt80.js → mobile-B_CyfRAX.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-OToslrv-.js +1 -0
  33. package/dist/assets/renderMobileApp-BD_wep_I.js +14 -0
  34. package/dist/assets/{runtimeSurface-Bec4O8FD.js → runtimeSurface-CkdOpqo7.js} +1 -1
  35. package/dist/assets/{useInlineCommentController-CHmIm0Rr.js → useInlineCommentController-DVif5Fr8.js} +2 -2
  36. package/dist/assets/usePanelSlide-C_PJmPXW.js +56 -0
  37. package/dist/assets/{useWindowTitle-CE5N_NeU.js → useWindowTitle-BZVlLMCy.js} +3 -3
  38. package/dist/assets/{vendor-base-ui-DwfTg5wD.js → vendor-base-ui-DL8r2fgQ.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-q1yHU1R9.js → vendor-codemirror-language-data-C-924Z4o.js} +2 -2
  40. package/dist/assets/{vendor-sonner-dWA7qvjr.js → vendor-sonner-CW8w438f.js} +1 -1
  41. package/dist/assets/{web-components-CLirSfwt.js → web-components-BG-6PEN4.js} +1 -1
  42. package/dist/index.html +4 -4
  43. package/dist/mini-chat.html +3 -3
  44. package/dist/mobile.html +3 -3
  45. package/package.json +1 -1
  46. package/server/lib/package-manager.js +0 -34
  47. package/server/lib/pi/routes.js +52 -4
  48. package/server/lib/pi/routes.test.js +14 -6
  49. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -3
  50. package/server/lib/pi/session-daemon/message-entry-aliases.js +100 -0
  51. package/server/lib/pi/session-daemon/runtime-registry.js +3 -0
  52. package/server/lib/pi/session-daemon/session-daemon.js +184 -16
  53. package/server/lib/pi/session-daemon/session-daemon.test.js +310 -5
  54. package/server/lib/pi/session-daemon/supervisor.js +20 -1
  55. package/server/lib/pi/session-daemon/supervisor.test.js +43 -0
  56. package/server/lib/tunnels/DOCUMENTATION.md +6 -7
  57. package/server/lib/tunnels/executable-search.test.js +4 -4
  58. package/server/lib/tunnels/install-help.js +0 -10
  59. package/server/lib/tunnels/install-help.test.js +0 -9
  60. package/server/lib/tunnels/types.js +0 -1
  61. package/dist/assets/SettingsView-JAfC_cBL.js +0 -3
  62. package/dist/assets/SettingsWindow-BBEsjcJE.js +0 -1
  63. package/dist/assets/index-CH7o4-_q.js +0 -8
  64. package/dist/assets/index-o4Eea60G.css +0 -1
  65. package/dist/assets/main-nG4uFyAy.js +0 -133
  66. package/dist/assets/renderElectronMiniChatApp-DW3fSR5w.js +0 -1
  67. package/dist/assets/renderMobileApp-9qkroKty.js +0 -14
  68. package/dist/assets/usePanelSlide-DCX8qQ4K.js +0 -56
  69. package/server/lib/ngrok-tunnel.js +0 -343
  70. package/server/lib/ngrok-tunnel.test.js +0 -50
  71. package/server/lib/tunnels/providers/ngrok.js +0 -32
@@ -0,0 +1,133 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-5wHwK-lg.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-8TL2HlaR.js","assets/vendor-zustand-CnsBKjP5.js","assets/index-riABQmQ_.css","assets/SessionSwitcherDropdown-D5bWfZNA.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.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/runtimeSurface-CkdOpqo7.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-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-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.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-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-C-924Z4o.js","assets/vendor-codemirror-lang-python-_2bIYTiJ.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-RrgJ8H_6.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-CW8w438f.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/PierreDiffViewer-St32rXlD.js","assets/web-components-BG-6PEN4.js","assets/computeVirtualFileMetrics-skbyL2Az.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-BsAZM0jo.js","assets/isDiffPlainText-dZkfk3yG.js","assets/vendor-diff-C3JhlQdm.js","assets/usePanelSlide-C_PJmPXW.js","assets/permissionStore-BRcQ9Jgt.js","assets/usePanelSlide-BV3KOtdA.css","assets/useInlineCommentController-DVif5Fr8.js","assets/collapsible-Wnmq-13H.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/contextFileOpenGuard-BsxQITMZ.js","assets/FilesView-5bswI3JZ.js","assets/vendor-codemirror-search-8kyQdB3f.js","assets/vendor-replit-codemirror-vim-BJY5fGLS.js","assets/JsonTreeView-HVwQS7qG.js","assets/Virtualizer-BxW2CJGB.js","assets/isFilePlainText-UL_tMQZx.js","assets/DiagramEditor-gHLCXHtr.js","assets/vendor-react-drawio-Boqanm0j.js","assets/GitView-BfykGpGh.js","assets/CommitSection-C336377Z.js","assets/DiagramView-DlHzRRBc.js","assets/SettingsView-FGe5TEQq.js","assets/vendor-qrcode-COsmt6jn.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/SettingsWindow-Ck_uhTnx.js"])))=>i.map(i=>d[i]);
2
+ import{R as r,j as e,r as Me,e as Gn}from"./vendor-react-DYyjh7Q0.js";import"./vendor-katex-CHD9BdDO.js";import{u as te,z as Yn,A as Jn,B as Qn,C as hn,o as $e,D as Zn,a as pn,E as mn,r as dt,F as er,G as tr,H as nr,e as ut,I as fn,J as gn,K as rr,m as sr,L as or,M as ar,N as ir,w as lr,x as cr,q as xn,v as dr}from"./index-8TL2HlaR.js";import{_ as Le}from"./vendor-vite-runtime-DD1OZmLC.js";import{l as ur,p as hr,q as pr,t as mr,v as fr,w as gr,P as wn,x as xr,T as yn,y as wr,z as yr,B as br,m as vr,o as Sr,j as jr,k as Cr,H as Ft,C as Bt,A as zt,S as Ut,n as kr,f as Nr,h as Pr,F as Er}from"./usePanelSlide-C_PJmPXW.js";import{f as Se,X as Ie,I as V,as as Rr,T as Ue,q as He,at as Tr,B as fe,s as Ve,au as Dr,F as jt,av as Ct,t as me,aw as _r,C as kt,E as nt,G as bn,ax as vn,Y as Ht,ay as Mr,D as Nt,w as Pt,x as Et,y as Rt,z as Tt,A as Ar,az as Ir,aA as Lr,h as De,aB as Or,aC as Sn,a5 as ze,aD as Qe,aE as jn,aF as Cn,aG as $r,aH as vt,aI as Wr,U as We,aJ as kn,H as Nn,aK as Fr,aL as Br,aM as zr,aN as Ur,aO as Hr,aP as Dt,aQ as _t,aR as Mt,o as ht,aS as Vr,P as Pn,aT as Kr,aU as Xr,aV as At,K as En,aW as qr,aX as Gr,aY as Yr,aZ as Jr,a_ as Vt,a$ as Kt,b0 as Ze,b1 as Qr,c as Zr,d as es,b2 as ts,b as Xt,r as ft,b3 as ns,b4 as rs,b5 as ss,b6 as Rn,b7 as Tn,b8 as os,b9 as as,ba as is,bb as ls,bc as Ye,bd as Je,be as cs,bf as ds,bg as us,bh as hs,ae as ps,ad as ms,af as fs,ab as gs,ag as xs,ah as ws,ai as ys,ap as bs,aq as vs,ar as Ss}from"./SessionSwitcherDropdown-D5bWfZNA.js";import{v as Dn,g as _n}from"./contextFileOpenGuard-BsxQITMZ.js";import{c as js,d as qt,T as Cs,M as ks,D as Ns,e as Ps}from"./vendor-dnd-kit-core-GipZW2tY.js";import{a as Es,S as Rs,v as Ts,u as Ds}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as _s}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{u as Gt,a as st,m as Yt}from"./vendor-framer-motion-DJASDzNt.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-CnsBKjP5.js";import"./vendor-base-ui-DL8r2fgQ.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./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-CkdOpqo7.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-E2vgV9K3.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-DSzLbZiS.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-BUlYhQ3o.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-BS2SpSAZ.js";import"./vendor-codemirror-lang-json-CqayksDf.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-Ba8JZ6fp.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-DK27qQri.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-CvO36Y1p.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-C-924Z4o.js";import"./vendor-codemirror-lang-python-_2bIYTiJ.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-RrgJ8H_6.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-sonner-CW8w438f.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 Jt=280,Qt=280,Zt=500,Ms=({isOpen:t,isMobile:n,children:s,className:o,topBar:a})=>{const d=te(A=>A.sidebarWidth),y=te(A=>A.setSidebarWidth),[u,m]=r.useState(!1),x=r.useRef(0),v=r.useRef(d||Jt),p=r.useRef(null),i=r.useRef(null),C=r.useRef(null),f=r.useCallback(A=>Math.min(Zt,Math.max(Qt,A)),[]),W=r.useCallback(A=>{const b=C.current;b&&(b.style.width=`${A}px`,b.style.minWidth=`${A}px`,b.style.maxWidth=`${A}px`,b.style.setProperty("--oc-left-sidebar-width",`${A}px`))},[]);r.useEffect(()=>{n&&u&&m(!1)},[n,u]),r.useEffect(()=>{u||(p.current=null,i.current=null)},[u]);const P=ur(t);if(n)return null;const F=Math.min(Zt,Math.max(Qt,d||Jt)),O=t?F:0,B=A=>{if(t){try{A.currentTarget.setPointerCapture(A.pointerId)}catch{}i.current=A.pointerId,m(!0),x.current=A.clientX,v.current=O,p.current=O,W(O),A.preventDefault()}},$=A=>{if(n||!u||i.current!==A.pointerId)return;const b=A.clientX-x.current,z=f(v.current+b);p.current!==z&&(p.current=z,W(z))},k=A=>{if(i.current!==A.pointerId||n)return;try{A.currentTarget.releasePointerCapture(A.pointerId)}catch{}const b=f(p.current??O);i.current=null,p.current=null,m(!1),y(b)},R=u?p.current??O:O,D=u?R:O;return e.jsxs("aside",{ref:C,className:Se("relative flex h-full overflow-hidden border-r border-border motion-reduce:transition-none","bg-sidebar",!t&&"border-r-0",o),style:{width:`${D}px`,minWidth:`${D}px`,maxWidth:`${D}px`,"--oc-left-sidebar-width":`${u?R:F}px`,overflowX:"clip",transform:u||P.slidIn?"translateX(0)":"translateX(-100%)",transition:u?"none":P.transition},"aria-hidden":!t||D===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:Se("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",u&&"bg-[var(--interactive-border)]"),onPointerDown:B,onPointerMove:$,onPointerUp:k,onPointerCancel:k,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:Se("relative z-10 flex h-full shrink-0 flex-col",u&&"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(Ie,{children:s})})]})]})},As=t=>t.slice().sort((n,s)=>n.type!==s.type?n.type==="directory"?-1:1:n.name.localeCompare(s.name)),Ee=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},Mn=(t,n)=>{const s=Ee(n),o=Ee(t).replace(/\/+$/,"");return s===o?".":!o||!s.startsWith(`${o}/`)?s:s.slice(o.length+1)},Is=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),Ls=new Set(["node_modules"]),Os=t=>Ls.has(t),$s=t=>{const n=Ee(t);return n==="node_modules"||n.endsWith("/node_modules")||n.includes("/node_modules/")},Ws=8,Oe=new Map,It=t=>JSON.stringify([pn(),t]),Fs=t=>{const n=It(t),s=Oe.get(n);return s?(s.touchedAt=Date.now(),Oe.delete(n),Oe.set(n,s),s):null},gt=t=>{const n=It(t),s=Oe.get(n);if(s)return s.touchedAt=Date.now(),s;if(Oe.size>=Ws){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},Bs=t=>{Oe.delete(It(t))},An=(t,n)=>e.jsx(jt,{filePath:t,extension:n}),zs=({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}})},Us=({node:t,root:n,isExpanded:s,isActive:o,isBrowserClient:a,status:d,badge:y,permissions:u,downloadFile:m,onSelect:x,onToggle:v,onRevealPath:p,onOpenDialog:i})=>{const C=t.type==="directory",{canRename:f,canCreateFile:W,canCreateFolder:P,canDelete:F,canReveal:O}=u,B=!C&&!!m,$=O&&!a,k=f||W||P||F||B||$,[R,D]=r.useState(!1),[A,b]=r.useState(!1),z=r.useCallback(E=>{k&&(E?.preventDefault(),b(!0))},[k]),ne=r.useCallback(()=>{C?v(t.path):x(t)},[C,t,x,v]),G=r.useCallback(E=>{E.stopPropagation(),b(!1),D(!0)},[]),U=({Item:E,Separator:H})=>e.jsxs(e.Fragment,{children:[f&&e.jsxs(E,{onClick:S=>{S.stopPropagation(),i("rename",t)},children:[e.jsx(V,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(E,{onClick:S=>{S.stopPropagation(),Ct(t.path).then(I=>{if(I.ok){me.success("Path copied");return}me.error("Copy failed")})},children:[e.jsx(V,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!C&&m&&e.jsxs(E,{onClick:S=>{S.stopPropagation(),m(t.path).catch(I=>{console.error("Download failed:",I),me.error("Operation failed")})},children:[e.jsx(V,{name:"download",className:"mr-2 h-4 w-4"})," ",a?"Download":"Save"]}),$&&e.jsxs(E,{onClick:S=>{S.stopPropagation(),p(t.path)},children:[e.jsx(V,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",_r()]}),C&&(W||P)&&e.jsxs(e.Fragment,{children:[e.jsx(H,{}),W&&e.jsxs(E,{onClick:S=>{S.stopPropagation(),i("createFile",t)},children:[e.jsx(V,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),P&&e.jsxs(E,{onClick:S=>{S.stopPropagation(),i("createFolder",t)},children:[e.jsx(V,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),F&&e.jsxs(e.Fragment,{children:[e.jsx(H,{}),e.jsxs(E,{onClick:S=>{S.stopPropagation(),i("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(V,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),J=r.useCallback(E=>{const H=Mn(n,t.path);!H||H==="."||(E.dataTransfer.setData("application/x-pichamber-file-path",H),E.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(hr,{open:A,onOpenChange:b,children:[e.jsxs(pr,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:z}),children:[e.jsxs("button",{type:"button",onClick:ne,onContextMenu:z,draggable:!0,onDragStart:J,className:Se("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(V,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(V,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):An(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!C&&d&&e.jsx(zs,{status:d}),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]})]})]}),k&&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(Rr,{open:R,onOpenChange:D,children:[e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(Tr,{asChild:!0,children:e.jsx(fe,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:G,title:"File menu","aria-label":"File menu",children:e.jsx(V,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(Dr,{align:"end",side:"bottom",onCloseAutoFocus:()=>D(!1),children:U({Item:Ir,Separator:Lr})})]})})]}),e.jsx(mr,{className:"min-w-[180px]",children:U({Item:fr,Separator:gr})})]})},Hs=(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,Vs=r.memo(Us,Hs),Ks=()=>{const{files:t,runtime:n}=kt(),s=Yn(n.platform),o=nt()??"",a=Ee(o.trim()),d=Jn(),y=Qn(),u=hn(w=>w.searchFiles),m=te(w=>w.openContextFile),x=bn(o),[v,p]=r.useState(""),i=vn(v,200),C=r.useRef(null),[f,W]=r.useState([]),[P,F]=r.useState(!1),[O,B]=r.useState({}),[$,k]=r.useState({}),R=r.useRef(new Set),D=r.useRef(new Set),A=r.useRef(null);r.useEffect(()=>{if(!a){B({}),k({}),R.current=new Set;return}const w=Fs(a);w?(B({...w.childrenByDir}),k({...w.loadErrorsByDir}),R.current=new Set(w.loadedDirs)):(B({}),k({}),R.current=new Set)},[a]),r.useEffect(()=>{if(!a)return;const w=gt(a);w.childrenByDir=O},[a,O]),r.useEffect(()=>{if(!a)return;const w=gt(a);w.loadErrorsByDir=$},[a,$]),r.useEffect(()=>{if(!a)return;const w=gt(a);w.loadedDirs=new Set(R.current)},[a,O,$]),r.useEffect(()=>()=>{if(!a)return;const w=Oe.get(a);w&&w.loadedDirs.size===0&&Object.keys(w.childrenByDir).length===0&&Bs(a)},[a]);const b=r.useMemo(()=>[],[]),z=r.useMemo(()=>[],[]),ne=$e(w=>a?w.byRoot[a]?.expandedPaths??b:b),G=$e(w=>a?w.byRoot[a]?.selectedPath??null:null),U=$e(w=>w.setSelectedPath),J=$e(w=>w.addOpenPath),E=$e(w=>w.removeOpenPathsByPrefix),H=$e(w=>w.toggleExpandedPath),S=$e(w=>w.collapseAllExpandedPaths),I=te(w=>a?w.contextPanelByDirectory[a]?.tabs??z:z),Q=r.useMemo(()=>new Set(I.map(w=>w.mode==="file"?w.targetPath:null).filter(w=>typeof w=="string"&&w.length>0).map(w=>Ee(w))),[I]),[_,q]=r.useState(null),[re,ce]=r.useState(null),[he,je]=r.useState(""),[ge,xe]=r.useState(!1),ie=!!t.writeFile,Ce=!!t.createDirectory,ke=!!t.rename,h=!!t.delete,j=!!t.revealPath,M=r.useMemo(()=>({canRename:ke,canCreateFile:ie,canCreateFolder:Ce,canDelete:h,canReveal:j}),[ke,ie,Ce,h,j]),X=r.useCallback(w=>{t.revealPath&&t.revealPath(w).catch(()=>{me.error("Failed to reveal path")})},[t]),Z=r.useCallback((w,T)=>{q(w),ce(T),je(w==="rename"&&T.name||""),xe(!1)},[]),pe=r.useCallback((w,T)=>{const de=T.filter(L=>L&&typeof L.name=="string"&&L.name.length>0).filter(L=>d||!L.name.startsWith(".")).filter(L=>y||!Os(L.name)).map(L=>{const ae=L.name,K=Ee(L.path||""),we=K?Is(K)?K:Ee(`${w}/${K}`):Ee(`${w}/${ae}`),c=L.isDirectory?"directory":"file",Y=c==="file"&&ae.includes(".")?ae.split(".").pop()?.toLowerCase():void 0;return{name:ae,path:we,type:c,extension:Y}});return As(de)},[y,d]),se=r.useCallback(async(w,T)=>{const de=Ee(w.trim());if(!de||R.current.has(de)||D.current.has(de))return;D.current=new Set(D.current),D.current.add(de);const L=t.listDirectory?t.listDirectory(de).then(ae=>ae.entries.map(K=>({name:K.name,path:K.path,isDirectory:K.isDirectory}))):Zn(de).then(ae=>ae.map(K=>({name:K.name,path:K.path,isDirectory:K.isDirectory})));try{const ae=await L;if(T?.())return;const K=pe(de,ae);R.current=new Set(R.current),R.current.add(de),k(we=>{if(!we[de])return we;const c={...we};return delete c[de],c}),B(we=>({...we,[de]:K}))}catch(ae){if(T?.())return;const K=ae instanceof Error?ae.message:String(ae??"");console.error("Failed to load sidebar directory:",ae),k(we=>({...we,[de]:K}))}finally{D.current=new Set(D.current),D.current.delete(de)}},[t,pe]),ve=r.useCallback(async()=>{if(!a)return;A.current?.abort();const w=new AbortController;A.current=w;try{const de=($e.getState().byRoot[a]?.expandedPaths??[]).map(K=>Ee(K)).filter(K=>!!K&&K!==a&&K.startsWith(`${a}/`)),L=[a,...de];R.current=new Set(R.current);for(const K of L)R.current.delete(K);k(K=>{if(Object.keys(K).length===0)return K;const we={...K};let c=!1;for(const Y of L)Y in we&&(delete we[Y],c=!0);return c?we:K});const ae=()=>w.signal.aborted;await se(a,ae);for(let K=0;K<de.length&&!w.signal.aborted;K+=3){const we=de.slice(K,K+3);await Promise.all(we.map(c=>se(c,ae)))}}catch(T){if(w.signal.aborted)return;console.error("Failed to refresh sidebar tree:",T)}finally{A.current===w&&(A.current=null)}},[se,a]),ye=r.useCallback(async w=>{if(!w){await ve();return}const T=Ee(w);R.current=new Set(R.current),R.current.delete(T),D.current=new Set(D.current),D.current.delete(T),await se(T)},[se,ve]);r.useEffect(()=>{a&&(A.current?.abort(),R.current=new Set,D.current=new Set,k({}),B(w=>Object.keys(w).length===0?w:{}),se(a))},[se,a,d,y]),r.useEffect(()=>{if(!a||ne.length===0)return;const w=ne.map(L=>Ee(L)).filter(L=>!!L&&L!==a&&L.startsWith(`${a}/`)&&!R.current.has(L)&&!D.current.has(L)).sort((L,ae)=>L.split("/").length-ae.split("/").length);if(w.length===0)return;let T=!1;const de=()=>T;return(async()=>{for(let L=0;L<w.length&&!T;L+=3){const ae=w.slice(L,L+3);await Promise.all(ae.map(K=>se(K,de)))}})(),()=>{T=!0}},[ne,se,a]),r.useEffect(()=>{if(!o){W([]),F(!1);return}const w=i.trim();if(!w){W([]),F(!1);return}let T=!1;return F(!0),u(o,w,150,{includeHidden:d,respectGitignore:!y,type:"file"}).then(de=>{if(T)return;const ae=de.filter(K=>y||!$s(K.path)).map(K=>({name:K.name,path:Ee(K.path),type:"file",extension:K.extension,relativePath:K.relativePath}));W(ae)}).catch(()=>{T||W([])}).finally(()=>{T||F(!1)}),()=>{T=!0}},[o,i,u,d,y]);const Re=r.useMemo(()=>{const w=new Map;if(!x?.files)return w;for(const T of x.files)T.index==="A"||T.working_dir==="?"?w.set(T.path,"git-added"):T.index==="D"?w.set(T.path,"git-deleted"):(T.index==="M"||T.working_dir==="M")&&w.set(T.path,"git-modified");return w},[x]),_e=r.useMemo(()=>{const w=new Map;if(!x?.files||!a)return w;for(const T of x.files){const de=T.index==="M"||T.working_dir==="M",L=T.index==="A"||T.working_dir==="?";if(!de&&!L)continue;const ae=T.path.split("/");if(ae.length<=1)continue;let K=a;for(let we=0;we<ae.length-1;we++){K=`${K}/${ae[we]}`;let c=w.get(K);c||(c={modified:0,added:0},w.set(K,c)),de&&c.modified++,L&&c.added++}}return w},[x,a]),N=r.useCallback(w=>{if(Q.has(w))return"open";if(Re.size===0)return null;const T=w.startsWith(a+"/")?w.slice(a.length+1):w;return Re.get(T)??null},[Q,Re,a]),le=r.useCallback(w=>{if(_e.size===0)return null;const T=_e.get(w);return T&&T.modified+T.added>0?T:null},[_e]),oe=r.useCallback(async w=>{if(!a)return;const T=await Dn(t,w.path,{directory:a});if(!T.ok){me.error(_n(T.reason));return}U(a,w.path),J(a,w.path),m(a,w.path)},[J,t,m,a,U]),l=r.useCallback(async w=>{const T=Ee(w);a&&(H(a,T),R.current.has(T)||await se(T))},[se,a,H]),g=r.useCallback(async w=>{if(w?.preventDefault(),!re||!_)return;xe(!0);const T=()=>xe(!1),de=()=>q(null);if(_==="createFile"){if(!he.trim()){me.error("Filename is required"),T();return}if(!t.writeFile){me.error("Write not supported"),T();return}const L=re.path,ae=L?`${L}/`:"",K=Ee(`${ae}${he.trim()}`);await t.writeFile(K,"").then(async we=>{we.success&&(me.success("File created"),await ye(L)),de()}).catch(()=>me.error("Operation failed")).finally(T);return}if(_==="createFolder"){if(!he.trim()){me.error("Folder name is required"),T();return}const L=re.path,ae=L?`${L}/`:"",K=Ee(`${ae}${he.trim()}`);await t.createDirectory(K).then(async we=>{we.success&&(me.success("Folder created"),await ye(L)),de()}).catch(()=>me.error("Operation failed")).finally(T);return}if(_==="rename"){if(!he.trim()){me.error("Name is required"),T();return}if(!t.rename){me.error("Rename not supported"),T();return}const L=re.path,ae=L.split("/").slice(0,-1).join("/"),K=ae?`${ae}/`:"",we=Ee(`${K}${he.trim()}`);await t.rename(L,we).then(async c=>{c.success&&(me.success("Renamed successfully"),await ye(ae),a&&E(a,L),(G===L||G&&G.startsWith(`${L}/`))&&U(a,null)),de()}).catch(()=>me.error("Operation failed")).finally(T);return}if(_==="delete"){if(!t.delete){me.error("Delete not supported"),T();return}const L=re.path,ae=L.split("/").slice(0,-1).join("/");await t.delete(L).then(async K=>{K.success&&(me.success("Deleted successfully"),await ye(ae),a&&E(a,L),(G===L||G&&G.startsWith(L+"/"))&&U(a,null)),de()}).catch(()=>me.error("Operation failed")).finally(T);return}T()},[_,re,he,t,ye,E,a,G,U]);function ee(w,T){const de=O[w]??[];return de.map((L,ae)=>{const K=L.type==="directory",we=K&&ne.includes(L.path),c=G===L.path,Y=ae===de.length-1;return e.jsxs("li",{className:"relative",children:[T>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Y&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(Vs,{node:L,root:a,isExpanded:we,isActive:c,isBrowserClient:s,status:K?void 0:N(L.path),badge:K?le(L.path):void 0,permissions:M,downloadFile:t.downloadFile,onSelect:oe,onToggle:l,onRevealPath:X,onOpenDialog:Z}),K&&we&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[$[L.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:$[L.path],children:$[L.path]}),e.jsxs(fe,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{ye(L.path)},children:[e.jsx(V,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,ee(L.path,T+1)]})]},L.path)})}const ue=!!(a&&O[a]),Pe=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:[ie&&e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(fe,{variant:"ghost",size:"sm",onClick:()=>Z("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(V,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"New File"})]}),Ce&&e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(fe,{variant:"ghost",size:"sm",onClick:()=>Z("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(V,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(fe,{variant:"ghost",size:"sm",onClick:()=>{ve()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(V,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Ue,{children:[e.jsx(He,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(fe,{variant:"ghost",size:"sm",onClick:()=>{a&&S(a)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(V,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx(Ve,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]}),e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(V,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(Ht,{ref:C,value:v,onChange:w=>p(w.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:()=>{p(""),C.current?.focus()},children:e.jsx(V,{name:"close",className:"h-4 w-4"})}):null]})]}),e.jsx(Mr,{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(V,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):f.length>0?f.map(w=>{const T=G===w.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>oe(w),draggable:!0,onDragStart:de=>{const L=w.relativePath||Mn(a??"",w.path);!L||L==="."||(de.dataTransfer.setData("application/x-pichamber-file-path",L),de.dataTransfer.effectAllowed="copy")},className:Se("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",T?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:w.path,children:[An(w.path,w.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:w.relativePath??w.path})]})},w.path)}):Pe?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:Pe}),e.jsxs(fe,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ve()},children:[e.jsx(V,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):ue&&a?ee(a,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(Nt,{open:!!_,onOpenChange:w=>!w&&q(null),children:e.jsxs(Pt,{children:[e.jsxs(Et,{children:[e.jsxs(Rt,{children:[_==="createFile"&&"Create File",_==="createFolder"&&"Create Folder",_==="rename"&&"Rename",_==="delete"&&"Delete"]}),e.jsxs(Tt,{children:[_==="createFile"&&`Create a new file in ${re?.path??"root"}`,_==="createFolder"&&`Create a new folder in ${re?.path??"root"}`,_==="rename"&&`Rename ${re?.name??""}`,_==="delete"&&`Are you sure you want to delete ${re?.name??""}? This action cannot be undone.`]})]}),_!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(Ht,{value:he,onChange:w=>je(w.target.value),placeholder:_==="rename"?"New name":"Name",onKeyDown:w=>{w.key==="Enter"&&g()},autoFocus:!0})}),e.jsxs(Ar,{children:[e.jsx(fe,{variant:"outline",onClick:()=>q(null),disabled:ge,children:"Cancel"}),e.jsx(fe,{variant:_==="delete"?"destructive":"default",onClick:()=>{g()},disabled:ge||_!=="delete"&&!he.trim(),children:ge?e.jsx(V,{name:"loader-4",className:"size-4 animate-spin"}):_==="delete"?"Delete":"Confirm"})]})]})})]})},Lt=t=>t,St=t=>{const n=Lt(t).type;return typeof n=="string"?n:""},Xs=t=>{const n=Lt(t).tool;return typeof n=="string"?n:""},qs=t=>{const n=Lt(t).text;return typeof n=="string"?n:""},Gs=t=>{const n=St(t);return n==="tool"?Xs(t).trim().toLowerCase()||"tool":n||"unknown"},Ys=t=>{if(t.length===0)return"";const n=[];for(const s of t){const o=Gs(s);n.includes(o)||n.push(o)}return n.join(" + ")},Js=t=>t.replace(/\s+/g," ").trim(),Qs=t=>{for(const s of t)if(St(s)==="text"){const o=Js(qs(s));if(o.length===0)continue;return o}const n=t.filter(s=>St(s)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},Zs=(t,n,s)=>`${s(t)} / ${s(n)}`,eo=t=>{if(t==="12h")return!0;if(t==="24h")return!1},to=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const s=eo(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}})},no={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},at={user:0,assistant:0,tool:0,other:0},ro=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,xt=t=>vt(t),so=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},Ae=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,s)=>n+Ae(s),0):t&&typeof t=="object"?Object.values(t).reduce((n,s)=>n+Ae(s),0):0,oo=(t,n)=>{const s=t,o=typeof s.type=="string"?s.type:"";if(o==="reasoning")return{...at,assistant:Ae(s.text)+Ae(s.content)};const a=so(s.text,s.content,s.value,s.source?.value,s.source?.text?.value);return o==="tool"||n==="tool"?{user:0,assistant:0,tool:Ae(s.input)+Ae(s.output)+Ae(s.error)+Ae(s.call?.input)+Ae(s.call?.output)+Ae(s.call?.error)+Ae(s.raw)+Math.round(Ae(s.metadata)*.25)+Math.round(Ae(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}},en=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),ao=t=>{const n=Qe(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},io=(t,n)=>{if(t.length===0)return{...at};const s=t.reduce((o,a)=>{const d=ao(a);let y={...at};for(const u of a.parts)y=en(y,oo(u,d));return en(o,y)},{...at});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)}},Fe=t=>t.toLocaleString("en-US"),lo=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),co=(t,n)=>!t||!Number.isFinite(t)?"-":Wr(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),uo=(t,n,s)=>{const o=t.find(d=>d.id===n),a=o?.models?.find(d=>d.id===s);return{providerName:o?.name||n||"-",modelName:a?.name||s||"-",contextLimit:typeof a?.limit?.context=="number"?a.limit.context:null}},ho=()=>{const t=te(f=>f.timeFormatPreference),[n,s]=r.useState({}),[o,a]=r.useState(null),d=r.useRef(null),y=De(f=>f.currentSessionId),u=De(f=>f.currentSessionDirectory),m=Or(),x=Sn(y??""),v=ze(f=>f.providers);r.useEffect(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null),s(f=>Object.keys(f).length>0?{}:f),a(null)},[u,y]),r.useEffect(()=>()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]);const p=r.useCallback(async(f,W)=>{(await Ct(W)).ok?(a(f),d.current!==null&&window.clearTimeout(d.current),d.current=window.setTimeout(()=>{a(F=>F===f?null:F),d.current=null},2e3)):a(null)},[]),i=r.useMemo(()=>{const f=y?m.find(_=>_.id===y)??null:null,W=x.filter(_=>Qe(_.info).role==="assistant"),P=x.filter(_=>Qe(_.info).isUser);let F=null;for(let _=W.length-1;_>=0;_-=1){const q=W[_];if(xt(q).total>0){F=q;break}}const O=F?xt(F):no,B=F?.info?.usage,$=jn({input:O.input,cache:{read:O.cacheRead,write:O.cacheWrite}}),k=W.reduce((_,q)=>{const re=ro(q.info.cost);return _+re},0),R=F?.info?.model??null,D=uo(v,R?.providerID||"",R?.modelID||""),A=D.contextLimit,b=B?Cn(B):O.total,z=A&&A>0?Math.min(999,b/A*100):0,ne=[...x].reverse().find(_=>Qe(_.info).isUser&&typeof _.info.system=="string")?.info?.system||"",G=io(x,ne),U=G.user,J=G.assistant,E=G.tool,H=B?0:Math.max(0,O.input-U-J-E),S=U+J+E+H,I=x[0]?.info?.time?.created,Q=x.length>0?x[x.length-1]?.info?.time?.created:null;return{sessionTitle:f?.title||"Untitled Session",messagesCount:x.length,userMessagesCount:P.length,assistantMessagesCount:W.length,createdAt:f?.time?.created??I??null,lastActivityAt:Q??f?.time?.created??null,providerModel:D,tokenBreakdown:O,usagePercent:z,cacheHitRate:$,totalAssistantCost:k,contextLimit:A,contextWindowTokens:b,hasUsage:B!==void 0,breakdown:{user:U,assistant:J,tool:E,other:H},breakdownTotal:S}},[y,v,x,m]);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:i.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:i.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool Calls",value:i.breakdown.tool,color:"var(--status-warning)"},...i.hasUsage?[]:[{key:"other",label:"Other",value:i.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:i.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:[i.providerModel.providerName," / ",i.providerModel.modelName]}),i.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:co(i.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:[Fe(i.contextWindowTokens),i.contextLimit?` / ${Fe(i.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:i.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,i.usagePercent)}%`,backgroundColor:i.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:`${i.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:Fe(i.messagesCount)},{label:"User",value:Fe(i.userMessagesCount)},{label:"Assistant",value:Fe(i.assistantMessagesCount)},{label:"Cost",value:lo(i.totalAssistantCost)}].map(f=>e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:f.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:f.value})]},f.label))}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:"Last Assistant Message"}),e.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:"Input",value:i.tokenBreakdown.input,format:"count"},{label:"Output",value:i.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:i.tokenBreakdown.reasoning,format:"count"},{label:"Cache Read",value:i.tokenBreakdown.cacheRead,format:"count"},{label:"Cache Write",value:i.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache Hit",value:i.cacheHitRate.hasInput?i.cacheHitRate.percent:null,format:"percent"}].map(f=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:f.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:f.value!==null&&f.value!==void 0?f.format==="percent"?`${f.value.toFixed(1)}%`:Fe(f.value):"—"})]},f.label))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:C.map(f=>f.value<=0||i.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${f.value/i.breakdownTotal*100}%`,backgroundColor:f.color}},f.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:C.map(f=>{const W=i.breakdownTotal>0?f.value/i.breakdownTotal*100:0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:f.color}}),e.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[f.label," ",e.jsxs("span",{className:"tabular-nums",children:[W.toFixed(0),"%"]})]})]},f.key)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Raw Messages"}),e.jsx("div",{className:"mt-2.5 space-y-1",children:[...x].reverse().map(f=>{const P=Qe(f.info).role,F=P==="assistant",O=P==="user",B=n[f.info.id]===!0,$=o===f.info.id,k=f.info.time?.created??null,R=Ys(f.parts),D=F?xt({info:f.info,parts:f.parts}):null,A=O?Qs(f.parts):"",b=to(k,t),z=R||"—",ne=D?Zs(D.input,D.output,Fe):"",G=P||"unknown",U=R?`${G}: ${R}`:G,J=B?JSON.stringify({info:f.info,parts:f.parts},null,2):"";return e.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[e.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":B,onClick:()=>{s(E=>({...E,[f.info.id]:E[f.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:F?"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:"})," ",A]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:F?z:U}),F&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:ne})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:b})]})}),B&&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(),p(f.info.id,J)},"aria-label":$?"Copied":"Copy JSON",title:$?"Copied":"Copy",children:$?e.jsx(V,{name:"check",className:"size-3.5"}):e.jsx(V,{name:"file-copy",className:"size-3.5"})})}),e.jsx($r,{language:"json",code:J,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},f.info.id)})})]})]})})},po="x-pichamber-preview-target-error",mo=t=>{const n=t.get(po);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},fo=(t,n)=>mo(t)?n?"stop-retrying":"retry-registration":"none",go=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},tn=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Xe=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"&&go(n.center)&&tn(n.attributes)&&tn(n.computedStyle)&&Array.isArray(n.ancestry)},Ot=({pageUrl:t,viewport:n,devicePixelRatio:s,target:o,screenshotAttached:a,intro:d})=>{const y=o.text.trim(),u=Object.entries(o.attributes).map(([C,f])=>`${C}="${f}"`).join(" "),m=o.computedStyle,x=o.bounds,v=o.center,p=d.replace(/[.:]+$/g,""),i=o.ancestry.map(C=>C.selectorPart).join(" > ");return[`${p}:`,`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}`,i?`- Ancestry: ${i}`:null,u?`- Attributes: ${u}`:null,`- Bounds: x=${Math.round(x.x)}, y=${Math.round(x.y)}, width=${Math.round(x.width)}, height=${Math.round(x.height)}`,`- Center: x=${Math.round(v.x)}, y=${Math.round(v.y)}`,`Styles: display=${m.display}; position=${m.position}; font=${m.fontWeight} ${m.fontSize} / ${m.lineHeight} ${m.fontFamily}; color=${m.color}; background=${m.backgroundColor}; z-index=${m.zIndex}`].filter(C=>typeof C=="string").join(`
3
+ `)},In=async(t,n)=>{if(typeof window<"u")try{const s=t.getBoundingClientRect(),o=await mn("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((f,W)=>{a.onload=()=>f(),a.onerror=()=>W(new Error("Failed to load desktop preview screenshot")),a.src=`data:${o.mime};base64,${o.base64}`});const d=Math.max(1,a.naturalWidth||o.width||Math.floor(s.width)),y=Math.max(1,a.naturalHeight||o.height||Math.floor(s.height)),m=Math.min(1,1200/d),x=document.createElement("canvas");x.width=Math.floor(d*m),x.height=Math.floor(y*m);const v=x.getContext("2d");if(!v)return null;v.scale(m,m),v.drawImage(a,0,0,d,y);const p=d/Math.max(1,s.width),i=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*p),v.fillRect(n.bounds.x*p,n.bounds.y*i,n.bounds.width*p,n.bounds.height*i),v.strokeRect(n.bounds.x*p,n.bounds.y*i,n.bounds.width*p,n.bounds.height*i);const C=await new Promise(f=>x.toBlob(f,"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 Do(t,n)},$t=async(t,n,s,o,a,d)=>{if(!t)return null;try{const y=new Image;await new Promise((P,F)=>{y.onload=()=>P(),y.onerror=()=>F(new Error("Failed to load desktop browser screenshot")),y.src=`data:image/jpeg;base64,${t}`});const u=Math.max(1,y.naturalWidth||n),m=Math.max(1,y.naturalHeight||s),v=Math.min(1,1200/u),p=document.createElement("canvas");p.width=Math.floor(u*v),p.height=Math.floor(m*v);const i=p.getContext("2d");if(!i)return null;i.scale(v,v),i.drawImage(y,0,0,u,m);const C=u/Math.max(1,o||u),f=m/Math.max(1,a||m);i.fillStyle="rgba(37, 99, 235, 0.14)",i.strokeStyle="rgb(37, 99, 235)",i.lineWidth=Math.max(2,2*C),i.fillRect(d.bounds.x*C,d.bounds.y*f,d.bounds.width*C,d.bounds.height*f),i.strokeRect(d.bounds.x*C,d.bounds.y*f,d.bounds.width*C,d.bounds.height*f);const W=await new Promise(P=>p.toBlob(P,"image/jpeg",.82));return W?new File([W],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},qe="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Te=new Map,wt=new Map,xo=3e4,Wt=t=>{const n=Te.get(t);return n?n.expiresAt-Date.now()<=xo?(Te.delete(t),null):n:null},wo=t=>{try{return new URL(t).origin}catch{return t}};function Ln(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 On=t=>new Promise((n,s)=>{const o=new FileReader;o.onloadend=()=>n(typeof o.result=="string"?o.result:qe),o.onerror=()=>s(o.error??new Error("Failed to read image blob")),o.readAsDataURL(t)}),yo=async(t,n=.82)=>{const s=await new Promise(o=>t.toBlob(o,"image/jpeg",n));return s&&(await On(s)).split(",",2)[1]||""},bo=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},it=(...t)=>{bo()&&console.info("[preview-capture]",...t)},$n=(t,n=8)=>{const s=[];try{const o=t.querySelectorAll("*");for(const a of o){const d=a.scrollTop||0,y=a.scrollLeft||0;if(d<=0&&y<=0)continue;const u=a.tagName.toLowerCase(),m=a.id?`#${a.id}`:"",x=typeof a.className=="string"&&a.className?`.${a.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(s.push({selector:`${u}${m}${x}`,scrollTop:d,scrollLeft:y,clientWidth:a.clientWidth,clientHeight:a.clientHeight,scrollWidth:a.scrollWidth,scrollHeight:a.scrollHeight}),s.length>=n)break}}catch{}return s},et="data-oc-fixed-pin",vo=(t,n,s)=>{if(n<=0&&s<=0)return()=>{};const o=t.defaultView;if(!o)return()=>{};const a=[],d=[];try{for(const y of t.querySelectorAll("*")){if(o.getComputedStyle(y).position!=="fixed")continue;const u=y.getBoundingClientRect();if(!(u.width>0&&u.height>0))continue;y.setAttribute(et,JSON.stringify({top:u.top+s,left:u.left+n,width:u.width,height:u.height})),a.push(y);const m=y.tagName.toLowerCase(),x=typeof y.className=="string"&&y.className?`.${y.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";d.push({selector:`${m}${x}`,top:Math.round(u.top),left:Math.round(u.left),width:Math.round(u.width),height:Math.round(u.height)})}}catch{}return it("tagged fixed elements",d),()=>{for(const y of a)try{y.removeAttribute(et)}catch{}}},So={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const s of n.querySelectorAll(`[${et}]`)){let o;try{o=JSON.parse(s.getAttribute(et)||"")}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(et)}}},Ke="data-oc-scroll-pin",jo=t=>{const n=[],s=$n(t,64);try{const d=t.documentElement,y=t.body;for(const u of t.querySelectorAll("*")){const m=u.scrollTop||0,x=u.scrollLeft||0;if(m<=0&&x<=0)continue;const v=u!==d&&u!==y;v&&u.setAttribute(Ke,JSON.stringify({top:m,left:x})),n.push({el:u,top:m,left:x,tagged:v})}}catch{}return{reapply:()=>{for(const d of n)try{d.el.scrollHeight,d.el.scrollTop!==d.top&&(d.el.scrollTop=d.top),d.el.scrollLeft!==d.left&&(d.el.scrollLeft=d.left)}catch{}},cleanup:()=>{for(const d of n)if(d.tagged)try{d.el.removeAttribute(Ke)}catch{}},snapshot:s}},Co={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(`[${Ke}]`)){let a;try{a=JSON.parse(o.getAttribute(Ke)||"")}catch{o.removeAttribute(Ke);continue}const d=`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=d;else{o.style.overflow="hidden";const u=s.createElement("div");for(u.style.transform=d,u.style.willChange="transform",u.style.display="inline-block",u.style.width="100%";o.firstChild;)u.appendChild(o.firstChild);o.appendChild(u)}o.removeAttribute(Ke)}}},yt=async(t,n)=>{try{const s=await fetch(t,{credentials:n});return s.ok?await On(await s.blob()):null}catch{return null}},ko=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,s=Wt(n);if(s)return`${s.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const o=wt.get(n),a=o??(async()=>{try{const y=await dt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!y.ok)return Te.delete(n),null;const u=await y.json(),m=typeof u.proxyBasePath=="string"?u.proxyBasePath:"",x=typeof u.expiresAt=="number"?u.expiresAt:0;if(!m)return Te.delete(n),null;const v={proxyBasePath:m,expiresAt:x};return Te.set(n,v),v}catch{return Te.delete(n),null}finally{wt.delete(n)}})();o||wt.set(n,a);const d=await a;return d?`${d.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},Wn=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 yt(s.toString(),"include")??qe;const o=await ko(s),a=o?await yt(o,"include"):null;return a||(await yt(s.toString(),"omit")??qe)}catch{return qe}},No=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 d=a[2]||"";if(!d||d.startsWith("data:"))continue;const y=await Wn(d,n);o=o.replace(a[0],`url("${y}")`)}return o},nn=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),Fn=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},Po=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},Eo=(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 u of y){const m=u.textContent?.replace(/\s+/g," ").trim()??"";if(!m||!m.includes(" "))continue;const x=u.getBoundingClientRect();if(x.width<=0||x.height<=0||x.right<0||x.bottom<0||x.left>n||x.top>s)continue;const v=a.getComputedStyle(u);if(v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)continue;const p=v.getPropertyValue("text-wrap"),i=v.getPropertyValue("text-wrap-mode"),C=v.whiteSpace.includes("nowrap")||p==="nowrap"||i==="nowrap",f=x.height<=Po(v)*1.7;!C&&(!f||x.width>n*.72)||(o.push(Fn(u)),u.style.whiteSpace="nowrap",u.style.overflowWrap="normal",u.style.wordBreak="normal",u.style.setProperty("text-wrap","nowrap"),u.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let u=o.length-1;u>=0;u-=1)o[u]?.()}},Ro=(t,n,s,o)=>{const a=[],d=t.defaultView??window,y=d.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,u=d.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,m=Array.from(t.querySelectorAll("*")).filter(x=>{const v=d.getComputedStyle(x);if(v.position!=="fixed"||v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)return!1;const p=x.getBoundingClientRect();return p.width>0&&p.height>0&&p.right>=0&&p.bottom>=0&&p.left<=n&&p.top<=s}).filter((x,v,p)=>!p.some((i,C)=>C<v&&i.contains(x)));for(const x of m){const v=x.getBoundingClientRect(),p=d.getComputedStyle(x),i=Math.ceil(v.width)+8,C=Math.ceil(v.height)+2;o?.add(x),a.push(Fn(x)),x.style.position="absolute",x.style.top=`${v.top+u}px`,x.style.left=`${v.left+y}px`,x.style.right="auto",x.style.bottom="auto",x.style.width=`${i}px`,x.style.minWidth=`${i}px`,x.style.height=`${C}px`,x.style.minHeight=`${C}px`,x.style.margin="0",x.style.boxSizing="border-box",x.style.transform="none",p.zIndex!=="auto"&&(x.style.zIndex=p.zIndex)}return()=>{for(let x=a.length-1;x>=0;x-=1)a[x]?.()}},Bn=async(t,n,s,o={})=>{const a=[],d=t.defaultView??window,y=p=>{if(p===t.documentElement||p===t.body)return!0;try{const i=p.getBoundingClientRect();return i.width>0&&i.height>0&&i.right>=0&&i.bottom>=0&&i.left<=n&&i.top<=s}catch{return!1}};if(o.applyLayoutWorkarounds){const p=new WeakSet;a.push(Ro(t,n,s,p)),a.push(Eo(t,n,s))}const u=new Map;for(const p of Array.from(t.images))u.set(p,p.currentSrc||p.src||p.getAttribute("src")||"");const m=Array.from(t.querySelectorAll("picture"));for(const p of m){const i=Array.from(p.querySelectorAll("source"));if(i.length===0)continue;const C=i.map(f=>({source:f,srcset:f.getAttribute("srcset"),sizes:f.getAttribute("sizes")}));a.push(()=>{for(const f of C)f.srcset===null?f.source.removeAttribute("srcset"):f.source.setAttribute("srcset",f.srcset),f.sizes===null?f.source.removeAttribute("sizes"):f.source.setAttribute("sizes",f.sizes)});for(const f of i)f.removeAttribute("srcset"),f.removeAttribute("sizes")}const x=Array.from(t.images).filter(p=>y(p));await Promise.all(x.map(async p=>{const i=u.get(p)||p.currentSrc||p.src||p.getAttribute("src")||"";if(!i)return;await nn(p);const C=await Wn(i,t),f={src:p.getAttribute("src"),srcset:p.getAttribute("srcset"),sizes:p.getAttribute("sizes")};a.push(()=>{f.src===null?p.removeAttribute("src"):p.setAttribute("src",f.src),f.srcset===null?p.removeAttribute("srcset"):p.setAttribute("srcset",f.srcset),f.sizes===null?p.removeAttribute("sizes"):p.setAttribute("sizes",f.sizes)}),p.removeAttribute("srcset"),p.removeAttribute("sizes"),p.setAttribute("src",C||qe),await nn(p)}));const v=Array.from(t.querySelectorAll("*")).filter(y);return await Promise.all(v.map(async p=>{const i=d.getComputedStyle(p).backgroundImage;if(!i||i==="none"||!i.includes("url("))return;const C=await No(i,t);if(C===i)return;const f=p.style.backgroundImage;a.push(()=>{p.style.backgroundImage=f}),p.style.backgroundImage=C})),()=>{for(let p=a.length-1;p>=0;p-=1)try{a[p]?.()}catch{}}};async function To(t,n){try{const s=t.contentWindow,o=t.contentDocument??s?.document,a=o?.documentElement;if(!s||!o||!a)return null;const d=t.getBoundingClientRect(),y=Math.max(1,Math.ceil(s.innerWidth||t.clientWidth||d.width)),u=Math.max(1,Math.ceil(s.innerHeight||t.clientHeight||d.height)),m=o.body,x=o.scrollingElement instanceof HTMLElement?o.scrollingElement:null,v=s.scrollX||0,p=s.scrollY||0,i=s.pageXOffset||0,C=s.pageYOffset||0,f=s.visualViewport?.pageLeft||s.visualViewport?.offsetLeft||0,W=s.visualViewport?.pageTop||s.visualViewport?.offsetTop||0,P=a.scrollLeft||0,F=a.scrollTop||0,O=m?.scrollLeft||0,B=m?.scrollTop||0,$=x?.scrollLeft||0,k=x?.scrollTop||0,R=Math.max(v,i,f,P,O,$),D=Math.max(p,C,W,F,B,k);it("scroll sources",{windowScrollX:v,windowScrollY:p,pageScrollX:i,pageScrollY:C,visualViewportScrollX:f,visualViewportScrollY:W,rootScrollX:P,rootScrollY:F,bodyScrollX:O,bodyScrollY:B,scrollingElementScrollX:$,scrollingElementScrollY:k,scrollingElementTag:x?.tagName?.toLowerCase()??null,resolvedScrollX:R,resolvedScrollY:D,nestedScrolledElements:$n(o)});const A=Math.max(y,a.scrollWidth||0,m?.scrollWidth||0,Math.ceil(a.getBoundingClientRect().width||0)),b=Math.max(u,a.scrollHeight||0,m?.scrollHeight||0,Math.ceil(a.getBoundingClientRect().height||0)),z=Math.min(2,Math.max(1,window.devicePixelRatio||1)),ne=a.style.scrollBehavior,G=m?.style.scrollBehavior??"";a.style.scrollBehavior="auto",m&&(m.style.scrollBehavior="auto");const U=jo(o);it("nested scroll snapshot",U.snapshot);let J=()=>{},E=()=>{};try{await o.fonts?.ready.catch(()=>{}),J=await Bn(o,y,u,{applyLayoutWorkarounds:!1}),s.scrollTo(R,D),E=vo(o,R,D),U.reapply();const{snapdom:H}=await Le(async()=>{const{snapdom:h}=await import("./vendor-zumer-snapdom-Btyu_Xi2.js");return{snapdom:h}},[]),S={backgroundColor:Ln(o),cache:"disabled",dpr:z,embedFonts:!0,fast:!1,height:b,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[So,Co],quality:.82,width:A},Q=await(await H(a,S)).toCanvas();if(!Q.width||!Q.height)return null;const _=Q.width/Math.max(1,A),q=Q.height/Math.max(1,b),re=Math.min(Q.width,Math.max(1,Math.round(y*_))),ce=Math.min(Q.height,Math.max(1,Math.round(u*q))),he=Math.max(0,Q.width-re),je=Math.max(0,Q.height-ce),ge=Math.min(he,Math.max(0,Math.round(R*_))),xe=Math.min(je,Math.max(0,Math.round(D*q)));it("capture geometry",{viewportWidth:y,viewportHeight:u,captureWidth:A,captureHeight:b,canvasWidth:Q.width,canvasHeight:Q.height,xScale:_,yScale:q,sourceX:ge,sourceY:xe,sourceWidth:re,sourceHeight:ce});const ie=o.createElement("canvas");ie.width=re,ie.height=ce;const Ce=ie.getContext("2d");if(!Ce)return null;Ce.drawImage(Q,ge,xe,re,ce,0,0,re,ce);const ke=await yo(ie,.82);return ke?await $t(ke,y,u,y,u,n):null}finally{E(),U.cleanup(),J(),s.scrollTo(R,D),U.reapply(),a.style.scrollBehavior=ne,m&&(m.style.scrollBehavior=G)}}catch(s){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",s),null}}async function Do(t,n){const s=await To(t,n);if(s)return s;try{const o=t.contentWindow,a=t.contentDocument??o?.document,d=a?.documentElement;if(!o||!a||!d)return null;const y=t.getBoundingClientRect(),u=Math.max(1,Math.ceil(o.innerWidth||t.clientWidth||y.width)),m=Math.max(1,Math.ceil(o.innerHeight||t.clientHeight||y.height)),x=o.scrollX||a.documentElement.scrollLeft||a.body?.scrollLeft||0,v=o.scrollY||a.documentElement.scrollTop||a.body?.scrollTop||0,p=a.body,i=Math.max(m,d.scrollHeight||0,p?.scrollHeight||0),C=Math.min(2,Math.max(1,window.devicePixelRatio||1)),f=d.style.scrollBehavior,W=p?.style.scrollBehavior??"";d.style.scrollBehavior="auto",p&&(p.style.scrollBehavior="auto");let P="",F=()=>{};try{await a.fonts?.ready.catch(()=>{}),F=await Bn(a,u,m,{applyLayoutWorkarounds:!0}),o.scrollTo(x,v);const{getFontEmbedCSS:B,toJpeg:$}=await Le(async()=>{const{getFontEmbedCSS:R,toJpeg:D}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:R,toJpeg:D}},[]),k=await B(d).catch(()=>"");P=await $(d,{quality:.82,pixelRatio:C,width:u,height:m,backgroundColor:Ln(a),imagePlaceholder:qe,fontEmbedCSS:k||void 0,style:{transform:`translate(${-x}px, ${-v}px)`,transformOrigin:"top left",minWidth:`${u}px`,minHeight:`${i}px`},cacheBust:!0})}finally{F(),o.scrollTo(x,v),d.style.scrollBehavior=f,p&&(p.style.scrollBehavior=W)}const O=P.split(",",2)[1]||"";return O?await $t(O,u,m,u,m,n):null}catch(o){return console.warn("[preview] failed to capture iframe DOM screenshot:",o),null}}const _o=We(()=>Le(()=>import("./DiffView-5wHwK-lg.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}))),Mo=We(()=>Le(()=>import("./FilesView-5bswI3JZ.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}))),Ao=We(()=>Le(()=>import("./GitView-BfykGpGh.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}))),Io=380,Lo=1400,zn=600,Oo=100,$o=24,pt=new Map,rn=200,Wo=(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",Fo=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},sn=t=>Number.isFinite(t)?Math.min(Lo,Math.max(Io,Math.round(t))):zn,Bo=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},zo=(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},Un=(t,n=null)=>t==="chat"?"Chat":t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?Dt(n).label:t==="notes"?"Project notes":t==="terminal"?"Terminal":"Context",Uo=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},Ho=(t,n,s=null)=>{if(t.mode==="chat"){const o=lt(t.dedupeKey);if(o){const d=n.get(o)?.trim();if(d)return d}const a=t.sessionTitleFallback?.trim();return a||"Chat"}if(t.label)return t.label;if(t.mode==="file")return Uo(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":Un(t.mode,s)},on=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(jt,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(wr,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(V,{name:Dt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="notes")return e.jsx(V,{name:"sticky-note",className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(V,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(V,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return e.jsx(V,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(V,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(V,{name:"global",className:"h-3.5 w-3.5"})},Vo=200,Ko=480,Xo=({visible:t})=>{const n=te(P=>P.contextEditorTreeWidth),s=te(P=>P.setContextEditorTreeWidth),[o,a]=r.useState(!1),d=r.useRef(0),y=r.useRef(n),u=r.useRef(null),m=r.useRef(null),x=r.useRef(null),v=r.useCallback(P=>Math.min(Ko,Math.max(Vo,Math.round(P))),[]),p=r.useCallback(P=>{const F=x.current;F&&(F.style.width=`${P}px`,F.style.setProperty("--oc-editor-tree-width",`${P}px`))},[]),i=P=>{if(t){try{P.currentTarget.setPointerCapture(P.pointerId)}catch{}m.current=P.pointerId,a(!0),d.current=P.clientX,y.current=n,u.current=n,P.preventDefault()}},C=P=>{if(!o||m.current!==P.pointerId)return;const F=d.current-P.clientX,O=v(y.current+F);u.current!==O&&(u.current=O,p(O))},f=P=>{if(m.current!==P.pointerId)return;try{P.currentTarget.releasePointerCapture(P.pointerId)}catch{}const F=v(u.current??n);m.current=null,u.current=null,a(!1),s(F)},W=t?n:0;return e.jsxs("div",{ref:x,className:Se("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?u.current??W:W}px`,"--oc-editor-tree-width":`${o?u.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:Se("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:i,onPointerMove:C,onPointerUp:f,onPointerCancel:f,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:Se("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(Ks,{})})]})},lt=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,qo=(t,n)=>{if(t.size!==n.size)return!1;for(const[s,o]of t)if(n.get(s)!==o)return!1;return!0},Go=(t,n)=>{if(n.length===0)return pt;const s=new Set(n),o=new Map;for(const a of t){if(!s.has(a.id))continue;const d=a.title?.trim();d&&o.set(a.id,d)}return o.size===0?pt:o},Yo=(t,n)=>{const s=Kr(),o=r.useRef(pt),a=r.useRef(n);return a.current=n,r.useSyncExternalStore(s.subscribe,r.useCallback(()=>{const d=Go(s.getState().session,a.current);return qo(o.current,d)?o.current:(o.current=d,d)},[s]),()=>pt)},Hn=`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
+ });`,ct=`(() => {
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
+ })()`,Jo=`(() => {
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
+ })()`,tt=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"}},an=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)},Qo=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,Vn=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},ln=(t,n,s)=>{const o=Vn(n);t.postMessage(s,o)},Zo=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}},cn=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}},ea=({rawUrl:t,onNavigate:n})=>{const{currentTheme:s}=kn(),[o,a]=r.useReducer(N=>N+1,0),[d,y]=r.useReducer(N=>N+1,0),[u,m]=r.useState({status:"idle"}),[x,v]=r.useState(""),p=r.useRef(null),i=r.useRef(1),[C,f]=r.useState(!1),[W,P]=r.useState(!1),[F,O]=r.useState("all"),[B,$]=r.useState([]),[k,R]=r.useState(!1),[D,A]=r.useState(null),b=De(N=>N.currentSessionId),z=De(N=>N.newSessionDraft?.open),ne=nt(),G=_t(N=>N.addDraft),U=Mt(N=>N.addAttachedFile);let J=null;try{J=t?new URL(t):null}catch{J=null}const E=J?J.hostname==="localhost"||J.hostname==="127.0.0.1"||J.hostname==="::1"||J.hostname==="[::1]"||J.hostname==="0.0.0.0":!1,H=J?J.hostname==="0.0.0.0"?new URL(J.toString().replace("0.0.0.0","127.0.0.1")):J:null,S=H?H.toString():"",I=S?`${ut()||"same-origin"}|${S}`:"",Q=s.metadata.variant;r.useEffect(()=>{if(!S||!E){m({status:"idle"});return}const N=Wt(I);if(N?.previewToken){m({status:"ready",proxyBasePath:N.proxyBasePath,previewToken:N.previewToken,expiresAt:N.expiresAt});return}N&&Te.delete(I);let le=!1;return m({status:"loading"}),(async()=>{try{const oe=await dt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:S})});if(!oe.ok){Te.delete(I);const Pe=await oe.json().catch(()=>({})),w=typeof Pe?.error=="string"?Pe.error:`HTTP ${oe.status}`;le||m({status:"error",message:w});return}const l=await oe.json(),g=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",ee=typeof l.previewToken=="string"?l.previewToken:"",ue=typeof l.expiresAt=="number"?l.expiresAt:0;if(!g||!ee){Te.delete(I),le||m({status:"error",message:"Could not start preview proxy."});return}Te.set(I,{proxyBasePath:g,previewToken:ee,expiresAt:ue}),le||m({status:"ready",proxyBasePath:g,previewToken:ee,expiresAt:ue})}catch(oe){if(Te.delete(I),!le){const l=oe instanceof Error?oe.message:String(oe);m({status:"error",message:l})}}})(),()=>{le=!0}},[E,I,d,S]);const _=H&&(H.protocol==="http:"||H.protocol==="https:")?H.toString():"",q=E&&u.status==="ready"?`${u.proxyBasePath}|${u.previewToken||""}|${o}`:"";r.useEffect(()=>{if(!q){v("");return}let N=!1;return v(""),fn(ut()).then(le=>{!N&&le&&v(q)}).catch(()=>{}),()=>{N=!0}},[q]);const re=E&&u.status==="ready"&&H&&x===q?(()=>{const N=H.pathname||"/",le=new URLSearchParams(H.search);le.delete("oc_url_token"),le.delete("oc_client_token"),le.set("ocPreview",String(o)),le.set("oc_preview_token",u.previewToken||"");const oe=le.toString(),l=H.hash||"";return gn().authenticatedAsset(`${u.proxyBasePath}${N}${oe?`?${oe}`:""}${l}`)})():"",ce=E?re:_,he=E?Zo(re):_,je=E&&(u.status==="loading"||u.status==="idle"||x!==q),ge=E&&u.status==="error",xe=r.useCallback(N=>{const le=b??(z?"draft":null);if(!le||!ne){me.error("Open a chat session before attaching preview annotations");return}const oe=t||ce||"",l=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},g=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let ee=!1;try{const ue=p.current,Pe=ue?await In(ue,N):null;Pe&&(await U(Pe),ee=!0)}catch{ee=!1}G({directory:ne,sessionKey:le},{source:"preview-annotation",fileLabel:oe||"preview",startLine:1,endLine:1,code:Ot({pageUrl:oe,viewport:l,devicePixelRatio:g,target:N,screenshotAttached:ee,intro:"This is a selected DOM element from the in-app preview."}),language:"markdown",text:""}),me.success("Preview annotation attached to chat")})()},[U,G,b,ne,ce,z,t]);r.useEffect(()=>{f(!1),$([]),P(!1),O("all"),R(!1),A(null),i.current=1},[ce]),r.useEffect(()=>{const N=p.current?.contentWindow;!C||!N||ln(N,re,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:k})},[C,k,re]),r.useEffect(()=>{const N=p.current?.contentWindow;!C||!N||ln(N,re,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:Q})},[C,Q,re]),r.useEffect(()=>{if(!k||typeof window>"u")return;const N=le=>{le.key==="Escape"&&(le.preventDefault(),le.stopImmediatePropagation(),R(!1))};return window.addEventListener("keydown",N,!0),()=>window.removeEventListener("keydown",N,!0)},[k]),r.useEffect(()=>{if(!E||typeof window>"u")return;const N=l=>{if(typeof l=="string")return l;if(l==null)return"";try{return JSON.stringify(l)}catch{return String(l)}},le=l=>{const g=i.current;i.current+=1,$(ee=>{const ue=[...ee,{...l,id:g}];return ue.length>rn?ue.slice(ue.length-rn):ue})},oe=l=>{if(l.source!==p.current?.contentWindow)return;const g=l.data;if(!(!g||g.source!=="pichamber-preview-bridge"||g.version!==1)){if(g.type==="ready"){f(!0);return}if(g.type==="console"){const ee=g.level==="error"||g.level==="warn"||g.level==="info"||g.level==="debug"?g.level:"log",ue=Array.isArray(g.args)?g.args.map(N).filter(Boolean):[];le({level:ee,message:ue.join(" "),ts:typeof g.ts=="number"?g.ts:Date.now()});return}if(g.type==="runtime-error"){const ee=N(g.filename),ue=typeof g.line=="number"?g.line:null,Pe=typeof g.column=="number"?g.column:null,w=ee?`${ee}${ue!==null?`:${ue}${Pe!==null?`:${Pe}`:""}`:""}`:"",T=N(g.stack);le({level:"runtime",message:N(g.message)||"Runtime error",details:[w,T].filter(Boolean).join(`
127
+ `),ts:typeof g.ts=="number"?g.ts:Date.now()});return}if(g.type==="resource-error"){const ee=N(g.tag)||"resource",ue=N(g.url);le({level:"resource",message:ue?`${ee}: ${ue}`:ee,details:N(g.outerHTML),ts:typeof g.ts=="number"?g.ts:Date.now()});return}if(g.type==="hover"){A(Xe(g.target)?g.target:null);return}if(g.type==="select"&&Xe(g.target)){A(g.target),R(!1),xe(g.target);return}if(g.type==="navigate-preview"){const ee=typeof g.url=="string"?g.url:"",ue=g.navigation==="external"?"external":"proxy";if(ee&&ue==="external"){ht(ee);return}ee&&n(ee)}}};return window.addEventListener("message",oe),()=>{window.removeEventListener("message",oe)}},[xe,E,n]);const ie=B.filter(N=>N.level==="error"||N.level==="runtime"||N.level==="resource").length,Ce=B.filter(N=>Wo(N,F)),ke=r.useCallback(()=>{const N=[`Preview URL: ${t||ce||""}`,`Events: ${B.length}`,""].join(`
128
+ `),le=B.map(oe=>{const l=new Date(oe.ts).toISOString(),g=oe.details?`
129
+ ${oe.details}`:"";return`[${l}] [${oe.level}] ${oe.message}${g}`}).join(`
130
+ `);Ct(`${N}${le}`).then(oe=>{oe.ok?me.success("Preview console copied"):me.error("Failed to copy preview console")})},[B,ce,t]),h=r.useCallback(()=>{const N=b??(z?"draft":null);if(!N||!ne){me.error("Open a chat session before attaching preview logs");return}const le=[`Preview URL: ${t||ce||""}`,`Events: ${B.length}`,""].join(`
131
+ `),oe=B.map(l=>{const g=new Date(l.ts).toISOString(),ee=l.details?`
132
+ ${l.details}`:"";return`[${g}] [${l.level}] ${l.message}${ee}`}).join(`
133
+ `);G({directory:ne,sessionKey:N},{source:"preview-console",fileLabel:t||ce||"preview",startLine:1,endLine:Math.max(1,B.length),code:`${le}${oe}`,language:"text",text:"These are browser console logs from the dev server running for this project."}),me.success("Preview console attached to chat")},[G,B,b,ne,ce,z,t]),[j,M]=r.useState("unknown"),X=r.useRef(0),Z=r.useRef(0),pe=r.useRef(""),se=r.useRef(""),ve=15e3;r.useEffect(()=>{if(!re){M("unknown"),pe.current="",X.current=0,Z.current=0;return}let N=!1,le=null;pe.current!==I&&(pe.current=I,X.current=Date.now(),Z.current=0);const oe=l=>{le=setTimeout(()=>{N||a()},l)};return M("unknown"),(async()=>{const g=await(async()=>{try{return await dt(re,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(N)return;if(!g){M("unreachable"),oe(5e3);return}const ee=fo(g.headers,se.current===I);if(ee!=="none"){if(Te.delete(I),ee==="retry-registration")se.current=I,m({status:"loading"}),y();else{const w=await g.json().catch(()=>({}));if(N)return;const T=typeof w?.error=="string"?w.error:`HTTP ${g.status}`;m({status:"error",message:T})}return}if(g.status!==502){se.current="",M("reachable");return}const ue=X.current||Date.now();if(Date.now()-ue<ve){M("starting"),Z.current+=1;const w=Z.current,T=Math.min(2e3,250*Math.pow(2,Math.min(4,w)));oe(T);return}M("unreachable"),oe(5e3)})(),()=>{N=!0,le&&clearTimeout(le)}},[I,re,o]);const ye=E&&u.status==="ready"&&(j==="unknown"||j==="starting"),Re=E&&u.status==="ready"&&j==="unreachable",_e=r.useCallback(N=>{if(!E||u.status!=="ready"||typeof window>"u")return;const le=N.currentTarget.contentWindow;if(le)try{const oe=le.location,l=Vn(re);if(oe.origin!==l||oe.pathname.startsWith(u.proxyBasePath))return;const g=`${u.proxyBasePath}${oe.pathname}${oe.search}${oe.hash}`;le.location.replace(g)}catch{}},[E,re,u]);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:he||t,children:he||t||"No preview URL"}),e.jsx(fe,{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(V,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{_&&ht(_)},title:"Open in browser","aria-label":"Open in browser",disabled:!_,children:e.jsx(V,{name:"external-link",className:"h-3.5 w-3.5"})}),E?e.jsx(fe,{type:"button",size:"sm",variant:k?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>R(N=>!N),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!C,children:e.jsx(V,{name:"cursor",className:"h-3.5 w-3.5"})}):null,E?e.jsxs(fe,{type:"button",size:"sm",variant:W?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>P(N=>!N),title:C?"Open preview console":"Waiting for preview console","aria-label":C?"Open preview console":"Waiting for preview console",disabled:!C&&B.length===0,children:[e.jsx(V,{name:"terminal-box",className:"h-3.5 w-3.5"}),ie>0?e.jsx("span",{className:"typography-micro text-status-error",children:ie}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[ye?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."})]}):Re?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(fe,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:"Retry"})]}):ce&&(!E||j==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:p,src:ce,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:Q},onLoad:_e,sandbox:E?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${ce}:${o}`),k&&D?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:D.bounds.x,top:D.bounds.y,width:D.bounds.width,height:D.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:[D.tag,D.text?` · ${D.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."}),u.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:u.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."}),W?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(fe,{type:"button",size:"xs",variant:"ghost",onClick:h,disabled:B.length===0,children:"Attach"}),e.jsx(fe,{type:"button",size:"xs",variant:"ghost",onClick:ke,disabled:B.length===0,children:"Copy"}),e.jsx(fe,{type:"button",size:"xs",variant:"ghost",onClick:()=>$([]),disabled:B.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(N=>e.jsx(fe,{type:"button",size:"xs",variant:F===N?"secondary":"ghost",onClick:()=>O(N),children:N==="all"?"All":N==="errors"?"Errors":N==="warnings"?"Warnings":"Logs"},N))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:B.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(N=>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:Se("shrink-0 uppercase",N.level==="error"||N.level==="runtime"||N.level==="resource"?"text-status-error":N.level==="warn"?"text-status-warning":"text-muted-foreground"),children:N.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:N.message})]})},N.id))})]}):null]})]})},ta=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,na=({initialUrl:t,directory:n,tabID:s})=>{const o=r.useRef(null),a=te(h=>h.setContextPanelTabTargetPath),d=tt(t),y=d!=="about:blank"?d:"",[u,m]=r.useState(y),[x,v]=r.useState(y),[p,i]=r.useState(y),[C,f]=r.useState(()=>y?[y]:[]),[W,P]=r.useState(()=>y?0:-1),[F,O]=r.useReducer(h=>h+1,0),[B,$]=r.useState(!!y),[k,R]=r.useState(!1),[D,A]=r.useState(null),[b,z]=r.useState({status:"idle"}),[ne,G]=r.useState(""),U=De(h=>h.currentSessionId),J=De(h=>h.newSessionDraft?.open),E=_t(h=>h.addDraft),H=Mt(h=>h.addAttachedFile),S=r.useCallback(h=>{!h||h==="about:blank"||!n||!s||a(n,s,h)},[n,s,a]),I=r.useCallback((h,j)=>{const M=tt(h),X=M!=="about:blank"?M:"";v(X),m(X),j?.inFrame?$(!1):(i(X),$(!!X)),S(X),f(Z=>{if(!X)return P(-1),[];if(j?.replaceHistory)return Z;const pe=W>=0?Z.slice(0,W+1):[];if(pe[pe.length-1]===X)return P(pe.length-1),pe;const ve=[...pe,X];return P(ve.length-1),ve})},[W,S]),Q=r.useCallback(h=>{const j=C[h];j&&(P(h),v(j),i(j),m(j),$(!0),S(j))},[C,S]),_=r.useCallback(()=>{if(x){$(!0);try{o.current?.contentWindow?.location.reload()}catch{O()}}},[x]);r.useEffect(()=>{if(!p){z({status:"idle"});return}const h=wo(p),j=Wt(h);if(j?.previewToken){z({status:"ready",proxyBasePath:j.proxyBasePath,previewToken:j.previewToken,expiresAt:j.expiresAt});return}j&&Te.delete(h);let M=!1;return z({status:"loading"}),$(!0),(async()=>{try{const X=await dt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:p,allowExternal:!0})});if(!X.ok){const ye=await X.json().catch(()=>({})),Re=typeof ye?.error=="string"?ye.error:`HTTP ${X.status}`;M||z({status:"error",message:Re});return}const Z=await X.json(),pe=typeof Z.proxyBasePath=="string"?Z.proxyBasePath:"",se=typeof Z.previewToken=="string"?Z.previewToken:"",ve=typeof Z.expiresAt=="number"?Z.expiresAt:0;if(!pe||!se){M||z({status:"error",message:"Could not start preview proxy."});return}Te.set(h,{proxyBasePath:pe,previewToken:se,expiresAt:ve}),M||z({status:"ready",proxyBasePath:pe,previewToken:se,expiresAt:ve})}catch(X){if(!M){const Z=X instanceof Error?X.message:String(X);z({status:"error",message:Z})}}})(),()=>{M=!0}},[p]);const q=p&&b.status==="ready"?`${b.proxyBasePath}|${b.previewToken||""}|${F}`:"";r.useEffect(()=>{if(!q){G("");return}let h=!1;return G(""),fn(ut()).then(j=>{!h&&j&&G(q)}).catch(()=>{}),()=>{h=!0}},[q]);const re=r.useMemo(()=>{if(ne!==q||!p||b.status!=="ready")return"";try{const h=new URL(p),j=h.pathname||"/",M=new URLSearchParams(h.search);M.delete("oc_url_token"),M.delete("oc_client_token"),M.set("ocPreview",String(F)),M.set("oc_preview_token",b.previewToken||"");const X=M.toString();return gn().authenticatedAsset(`${b.proxyBasePath}${j}${X?`?${X}`:""}${h.hash}`)}catch{return""}},[p,b,q,F,ne]),ce=re||(b.status==="error"?p:""),he=r.useCallback(h=>{if(!h||!p||b.status!=="ready")return"";try{const j=new URL(h,window.location.origin),M=b.proxyBasePath.endsWith("/")?b.proxyBasePath.slice(0,-1):b.proxyBasePath;if(j.origin!==window.location.origin||!j.pathname.startsWith(M))return"";const X=j.pathname.slice(M.length)||"/",Z=new URL(p).origin;return cn(new URL(`${X}${j.search}${j.hash}`,Z).toString())}catch{return""}},[p,b]),je=r.useCallback(h=>{if(!h||!p||b.status!=="ready")return"";try{const j=new URL(h,window.location.origin),M=new URL(p).origin;if(j.origin!==window.location.origin||M===window.location.origin)return"";const X=b.proxyBasePath.endsWith("/")?b.proxyBasePath.slice(0,-1):b.proxyBasePath;return j.pathname.startsWith(X)?"":cn(new URL(`${j.pathname}${j.search}${j.hash}`,M).toString())}catch{return""}},[p,b]),ge=r.useCallback(h=>{const j=o.current?.contentWindow;j&&j.postMessage({source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:h},window.location.origin)},[]),xe=r.useCallback(async h=>{const j=U??(J?"draft":null);if(!j){me.error("Open a chat session before attaching preview annotations");return}const M=o.current,X=M?.contentWindow,Z=M?.getBoundingClientRect(),pe={width:Number.isFinite(X?.innerWidth)?X?.innerWidth??Z?.width??0:Z?.width??0,height:Number.isFinite(X?.innerHeight)?X?.innerHeight??Z?.height??0:Z?.height??0},se=M?await In(M,h):null,ve=!!se;se&&await H(se),E({directory:n,sessionKey:j},{source:"preview-annotation",fileLabel:x||"browser",startLine:1,endLine:1,code:Ot({pageUrl:x,viewport:pe,devicePixelRatio:window.devicePixelRatio||1,target:h,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:""}),me.success("Preview annotation attached to chat")},[H,E,U,x,n,J]),ie=r.useCallback(()=>{const h=o.current;A(null),ge(!1),h&&an(h,ct).catch(()=>{})},[ge]);r.useEffect(()=>{if(!k)return;const h=j=>{j.key==="Escape"&&(j.preventDefault(),j.stopImmediatePropagation(),R(!1),ie())};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[ie,k]),r.useEffect(()=>()=>ie(),[ie]),r.useEffect(()=>{const h=j=>{if(j.source!==o.current?.contentWindow)return;const M=j.data;if(!(!M||M.source!=="pichamber-preview-bridge"||M.version!==1)){if(M.type==="ready"){const X=typeof M.url=="string"?M.url:"",Z=he(X);Z&&Z!==x&&I(Z,{inFrame:!0});return}if(M.type==="hover"){A(Xe(M.target)?M.target:null);return}if(M.type==="select"&&Xe(M.target)){A(null),R(!1),ge(!1),xe(M.target);return}if(M.type==="navigate-preview"){const X=typeof M.url=="string"?M.url:"",Z=je(X);if(Z){I(Z);return}X&&I(X)}}};return window.addEventListener("message",h),()=>window.removeEventListener("message",h)},[I,xe,x,he,je,ge]);const Ce=r.useCallback(()=>{const h=o.current;if(!(!h||!x)){if(k){R(!1),ie();return}if(re){A(null),R(!0),ge(!0);return}R(!0),(async()=>{try{const j=await an(h,Hn);if(R(!1),!j||!Xe(j))return;await xe(j)}catch{R(!1),me.error("This page cannot be inspected from the browser panel.")}})()}},[xe,ie,x,k,ge,re]),ke=r.useCallback(()=>{try{const h=o.current?.contentWindow?.location.href||"",j=je(h);if(j){I(j,{inFrame:!0});return}}catch{}$(!1),k&&re&&ge(!0)},[I,je,k,ge,re]);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(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:W<=0,onClick:()=>Q(W-1),children:e.jsx(V,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:W<0||W>=C.length-1,onClick:()=>Q(W+1),children:e.jsx(V,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!x,onClick:_,children:e.jsx(V,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:h=>{h.preventDefault(),I(u)},children:e.jsx("input",{value:u,onChange:h=>m(h.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(fe,{type:"button",variant:k?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!x,onClick:Ce,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(V,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!x,onClick:()=>{ht(x)},children:e.jsx(V,{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}:${F}`),k&&D?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:D.bounds.x,top:D.bounds.y,width:D.bounds.width,height:D.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:[D.tag,D.text?` · ${D.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(Pn,{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."})]}),B?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},ra=({initialUrl:t,directory:n,tabID:s})=>{const o=r.useRef(null),a=te(b=>b.setContextPanelTabTargetPath),d=tt(t),y=d!=="about:blank"?d:"",u=r.useRef(tt(t)),[m,x]=r.useState(y),[v,p]=r.useState(y),[i,C]=r.useState(!1),[f,W]=r.useState(!0),P=r.useRef(null),F=f,O=r.useCallback(b=>{!b||b==="about:blank"||!n||!s||a(n,s,b)},[n,s,a]),B=De(b=>b.currentSessionId),$=De(b=>b.newSessionDraft?.open),k=_t(b=>b.addDraft),R=Mt(b=>b.addAttachedFile);r.useEffect(()=>{const b=o.current;if(!b)return;const z=()=>{try{const H=b.getURL();H&&H!=="about:blank"&&(p(H),x(H),O(H))}catch{}},ne=H=>{const S=H.detail;typeof S?.url=="string"&&S.url&&(p(S.url),x(S.url),O(S.url))},G=()=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>W(!0),200)},U=()=>{P.current&&clearTimeout(P.current),W(!1),z()},J=H=>{const S=H.detail;if(S?.disposition==="new-window"||S?.disposition==="foreground-tab"||S?.disposition==="background-tab"){H.preventDefault();const I=o.current;typeof I?.loadURL=="function"&&S.url&&I.loadURL(S.url)}},E=()=>{try{b.executeJavaScript?.(Jo,!0).catch(()=>{})}catch{}};b.addEventListener("did-navigate",ne),b.addEventListener("did-navigate-in-page",ne),b.addEventListener("did-start-loading",G),b.addEventListener("did-stop-loading",U),b.addEventListener("new-window",J),b.addEventListener("dom-ready",E);try{b.isLoading()||(W(!1),z())}catch{}return E(),()=>{P.current&&clearTimeout(P.current),b.removeEventListener("did-navigate",ne),b.removeEventListener("did-navigate-in-page",ne),b.removeEventListener("did-start-loading",G),b.removeEventListener("did-stop-loading",U),b.removeEventListener("new-window",J),b.removeEventListener("dom-ready",E)}},[O]),r.useEffect(()=>{const b=setTimeout(()=>W(!1),3e4);return()=>clearTimeout(b)},[]),r.useEffect(()=>{if(!i)return;const b=z=>{if(z.key!=="Escape")return;z.preventDefault(),z.stopImmediatePropagation(),C(!1);const ne=o.current;try{ne?.executeJavaScript?.(ct).catch(()=>{})}catch{}};return window.addEventListener("keydown",b,!0),()=>window.removeEventListener("keydown",b,!0)},[i]),r.useEffect(()=>{const b=o.current;return()=>{try{const z=b?.getURL?.();z&&z!=="about:blank"&&a(n,s,z)}catch{}try{b?.executeJavaScript?.(ct).catch(()=>{})}catch{}}},[n,s,a]);const D=r.useCallback(b=>{const z=o.current;if(typeof z?.loadURL!="function")return;const ne=tt(b);try{z.loadURL(ne)}catch{}},[]),A=r.useCallback(()=>{const b=o.current;if(b){if(i){C(!1);try{b.executeJavaScript?.(ct).catch(()=>{})}catch{}return}C(!0),b.executeJavaScript?.(Hn,!0).then(async z=>{if(C(!1),!z||!Xe(z))return;const ne=B??($?"draft":null);if(!ne){me.error("Open a chat session before attaching preview annotations");return}const G=typeof b.getWebContentsId=="function"?b.getWebContentsId():null;if(G==null)return;const U=await Vr("desktop_browser_capture_page",{webContentsId:G}),J=await b.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),E=Number.isFinite(J?.width)?J.width:U.width,H=Number.isFinite(J?.height)?J.height:U.height,S=await $t(U.base64,U.width,U.height,E,H,z),I=!!S;S&&await R(S),k({directory:n,sessionKey:ne},{source:"preview-annotation",fileLabel:v||"browser",startLine:1,endLine:1,code:Ot({pageUrl:v,viewport:{width:E,height:H},devicePixelRatio:window.devicePixelRatio||1,target:z,screenshotAttached:I,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:""}),me.success("Preview annotation attached to chat")}).catch(()=>C(!1))}},[R,k,B,v,n,i,$]);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(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goBack?.()}catch{}},children:e.jsx(V,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.goForward?.()}catch{}},children:e.jsx(V,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{o.current?.reload?.()}catch{}},children:e.jsx(V,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:b=>{b.preventDefault(),D(m)},children:e.jsx("input",{value:m,onChange:b=>x(b.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(fe,{type:"button",variant:i?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:A,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(V,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{ht(v)},children:e.jsx(V,{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:u.current,partition:"persist:pichamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!v||v==="about:blank")&&!f?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(Pn,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,F?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},sa=()=>{const t=nt()??"",n=r.useMemo(()=>Fo(t),[t]),s=te(c=>n?c.contextPanelByDirectory[n]:void 0),o=te(c=>c.closeContextPanel),a=te(c=>c.closeContextPanelTab),d=te(c=>c.openContextPanelTab),y=te(c=>c.toggleContextPanelExpanded),u=te(c=>c.setContextPanelWidth),m=te(c=>c.setActiveContextPanelTab),x=te(c=>c.reorderContextPanelTabs),v=$e(c=>c.setSelectedPath),p=te(c=>c.openContextPreview),i=te(c=>c.contextEditorTreeVisible),C=te(c=>c.toggleContextEditorTree),f=te(c=>c.allowPromptingSubagentSessions),{themeMode:W,setThemeMode:P,lightThemeId:F,darkThemeId:O,currentTheme:B}=kn(),$=r.useMemo(()=>s?.tabs??[],[s?.tabs]),k=$.find(c=>c.id===s?.activeTabId)??$[$.length-1]??null,R=!!(s?.isOpen&&k),D=!!(R&&s?.expanded),[A,b]=r.useState(null),z=s?.width,ne=Xr,G=A??(typeof window<"u"?window.innerWidth:zn*2),U=sn(z??Math.round(ne*G)),J=r.useMemo(()=>{const c=[];for(const Y of $){if(Y.mode!=="chat")continue;const be=lt(Y.dedupeKey);be&&!c.includes(be)&&c.push(be)}return c},[$]),E=Yo(n||void 0,J),H=Nn(n||null),[S,I]=r.useState(!1),Q=r.useRef(0),_=r.useRef(U),q=r.useRef(null),re=r.useRef(null),ce=r.useRef(null),he=r.useRef(new Map),je=r.useRef(new Map),ge=r.useRef(!1);r.useLayoutEffect(()=>{const c=ce.current?.parentElement;if(!c||typeof ResizeObserver>"u")return;const Y=new ResizeObserver(()=>{b(c.clientWidth||null)});return Y.observe(c),b(c.clientWidth||null),()=>Y.disconnect()},[]),r.useEffect(()=>{if(!R||ge.current){ge.current=R;return}const c=window.requestAnimationFrame(()=>{ce.current?.focus({preventScroll:!0})});return ge.current=!0,()=>window.cancelAnimationFrame(c)},[R]);const xe=r.useRef(null),ie=r.useRef(null),Ce=r.useCallback(()=>{ie.current=null;const c=ce.current,Y=q.current;!c||Y===null||c.style.setProperty("--oc-context-panel-width",`${Y}px`)},[]);r.useEffect(()=>()=>{ie.current!==null&&clearTimeout(ie.current)},[]);const ke=r.useCallback(c=>{const Y=sn(c),be=xe.current;return be===null?Y:Math.min(Y,Math.max(1,be))},[]),h=r.useCallback(c=>{!R||D||!n||(re.current=c.pointerId,I(!0),Q.current=c.clientX,_.current=U,q.current=U,xe.current=Bo(ce.current),document.documentElement.style.cursor="col-resize",c.preventDefault())},[n,D,R,U]),j=r.useCallback(()=>{const c=ke(q.current??U);q.current=null,xe.current=null,ie.current!==null&&(clearTimeout(ie.current),ie.current=null),document.documentElement.style.cursor="",n&&u(n,c),I(!1),re.current=null},[ke,n,u,U]);r.useEffect(()=>{if(!S)return;const c=Ne=>{if(re.current!==Ne.pointerId)return;const Ge=Q.current-Ne.clientX,mt=ke(_.current+Ge);q.current!==mt&&(q.current=mt,ie.current===null&&(ie.current=setTimeout(Ce,Oo)))},Y=Ne=>{re.current===Ne.pointerId&&j()},be=()=>{j()};return window.addEventListener("pointermove",c),window.addEventListener("pointerup",Y),window.addEventListener("pointercancel",Y),window.addEventListener("blur",be),()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",Y),window.removeEventListener("pointercancel",Y),window.removeEventListener("blur",be)}},[Ce,ke,j,S]),r.useEffect(()=>{S||(q.current=null,document.documentElement.style.cursor="")},[S]);const M=r.useCallback(()=>{n&&o(n)},[o,n]),X=r.useCallback(()=>{n&&y(n)},[n,y]),Z=r.useCallback(c=>{c.key==="Escape"&&(Fr(c.target)||(c.preventDefault(),c.stopPropagation(),M()))},[M]);r.useEffect(()=>{if(!(!n||!k)&&k.mode==="file"&&k.targetPath){v(n,k.targetPath,{allowOutsideRoot:!0});return}},[k,n,v]);const pe=k?.mode==="chat"?k.id:null,se=k?.mode==="chat"?lt(k.dedupeKey):null;r.useEffect(()=>{if(!R||!n||!se||typeof window>"u")return;const c=()=>{document.visibilityState==="hidden"||!document.hasFocus()||zr(se)};c();const Y=window.setInterval(c,1e4);return window.addEventListener("focus",c),window.addEventListener("blur",c),document.addEventListener("visibilitychange",c),()=>{window.clearInterval(Y),window.removeEventListener("focus",c),window.removeEventListener("blur",c),document.removeEventListener("visibilitychange",c)}},[se,n,R]);const ve=r.useCallback((c,Y,be)=>Br(je.current,c,Y,n||null,be,{mode:W,lightThemeId:F,darkThemeId:O,currentTheme:B}),[B,O,n,F,W]);r.useEffect(()=>{const c=new Set($.map(Y=>Y.id));for(const Y of je.current.keys())c.has(Y)||je.current.delete(Y)},[$]);const ye=r.useCallback(c=>{!n||k?.mode!=="diff"||d(n,{mode:"diff",targetPath:k.targetPath,stagedDiff:c==="staged",diffScope:c})},[k,n,d]),Re=r.useCallback(()=>{if(typeof window>"u")return;const c={themeMode:W,lightThemeId:F,darkThemeId:O,currentTheme:B};for(const Y of he.current.values()){const be=Y.contentWindow;be&&be.postMessage({type:"pichamber:theme-sync",payload:c},window.location.origin)}},[B,O,F,W]),_e=r.useCallback(()=>{if(typeof window>"u")return;const c={allowPromptingSubagentSessions:f};for(const Y of he.current.values()){const be=Y.contentWindow;be&&be.postMessage({type:"pichamber:chat-settings-sync",payload:c},window.location.origin)}},[f]),N=r.useCallback(()=>{if(!(typeof window>"u"))for(const[c,Y]of he.current.entries()){const be=Y.contentWindow;if(!be)continue;const Ne={visible:pe===c};be.postMessage({type:"pichamber:embedded-visibility",payload:Ne},window.location.origin)}},[pe]);r.useEffect(()=>{if(typeof window>"u")return;const c=Y=>{if(Y.origin!==window.location.origin||!Array.from(he.current.values()).some(rt=>rt.contentWindow===Y.source))return;const Ne=Y.data;if(Ne?.type===Ur){if(typeof Ne.requestId!="string"||!Ne.requestId)return;const rt=pn(),qn={apiBaseUrl:ut(),clientToken:nr(),localOrigin:typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",runtimeHeaders:tr(),relayHostId:rt.startsWith("host:")?rt.slice(5):"",relay:er()??void 0};Y.source?.postMessage({type:Hr,requestId:Ne.requestId,payload:qn},Y.origin);return}if(Ne?.type==="pichamber:theme-sync-request"){Re();return}if(Ne?.type==="pichamber:chat-settings-request"){_e();return}if(Ne?.type!=="pichamber:cycle-theme-request")return;const Ge=["light","dark","system"],Xn=(Ge.indexOf(W)+1)%Ge.length;P(Ge[Xn])};return window.addEventListener("message",c),()=>window.removeEventListener("message",c)},[_e,Re,P,W]),r.useLayoutEffect(()=>{$.some(Y=>Y.mode==="chat")&&(Re(),_e(),N())},[O,F,_e,N,Re,$,W]);const le=k?.mode==="file"||k?.mode==="chat"||k?.mode==="preview",oe=r.useMemo(()=>k?$.filter(c=>c.mode===k.mode):[],[k,$]),l=r.useMemo(()=>oe.map(c=>{const Y=Ho(c,E,H),be=Qo(Y,$o),Ne=zo(c.targetPath,t);return{id:c.id,label:be,icon:on(c,H),title:Ne?`${Y}: ${Ne}`:Y,closeLabel:`Close ${be} tab`}}),[oe,t,H,E]),g=k?.mode==="context"?e.jsx(ho,{}):k?.mode==="git"?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Ao,{isActive:R})}):k?.mode==="notes"?e.jsx(wn,{}):k?.mode==="preview"?e.jsx(ea,{rawUrl:k.targetPath??"",onNavigate:c=>p(t,c)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(V,{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."})]}),ee=r.useMemo(()=>$.filter(c=>c.mode==="chat"),[$]),ue=r.useMemo(()=>$.filter(c=>c.mode==="browser"),[$]),Pe=r.useMemo(()=>$.filter(c=>c.mode==="diff"),[$]),w=r.useMemo(()=>$.some(c=>c.mode==="terminal"),[$]),T=ta()?ra:na,de=r.useMemo(()=>$.some(c=>c.mode==="file"),[$]),L=r.useMemo(()=>$.some(c=>c.mode==="file"&&c.targetPath),[$]),ae=k?.mode==="file",K=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[le?e.jsx(xr,{items:l,activeId:k?.id??null,onSelect:c=>{n&&m(n,c)},onClose:c=>{n&&a(n,c)},onReorder:(c,Y)=>{n&&x(n,c,Y)},layoutMode:"scrollable",variant:"default"}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[k?on(k,H):null,e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:k?Un(k.mode,H):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[ae?e.jsx(fe,{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":i,children:e.jsx(V,{name:"layout-right",className:"h-3.5 w-3.5"})}):null,e.jsx(fe,{type:"button",variant:"ghost",size:"sm",onClick:X,className:"h-7 w-7 p-0",title:D?"Collapse panel":"Expand panel","aria-label":D?"Collapse panel":"Expand panel",children:D?e.jsx(V,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):e.jsx(V,{name:"fullscreen",className:"h-3.5 w-3.5"})}),e.jsx(fe,{type:"button",variant:"ghost",size:"sm",onClick:M,className:"h-7 w-7 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(V,{name:"close",className:"h-3.5 w-3.5"})})]})]}),we=R?D?{"--oc-context-panel-width":A!==null?`${A}px`:"100%",width:A!==null?`${A}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${U}px`}:{"--oc-context-panel-width":`${U}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:ce,"data-context-panel":"true",tabIndex:-1,inert:!R||void 0,className:Se("flex min-h-0 flex-col overflow-hidden bg-background",D?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!R&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:Z,style:we,children:[R&&!D&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),R&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!D&&e.jsx("div",{className:Se("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",S&&"bg-[var(--interactive-border)]"),onPointerDown:h,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:Se("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]",!R&&"pointer-events-none select-none opacity-0"),style:{width:D?A!==null?`${A}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!R,children:[K,e.jsxs("div",{className:Se("relative min-h-0 flex-1 overflow-hidden",S&&"pointer-events-none"),children:[de?e.jsxs("div",{className:Se("absolute inset-0 flex",ae?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:L?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Mo,{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(V,{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(Xo,{visible:i})]}):null,ee.map(c=>{const Y=lt(c.dedupeKey);if(!Y)return null;const be=ve(c.id,Y,c.readOnly);return be?e.jsx("iframe",{ref:Ne=>{if(!Ne){he.current.delete(c.id);return}he.current.set(c.id,Ne)},src:be,title:`Session chat ${Y}`,className:Se("absolute inset-0 h-full w-full border-0 bg-background",pe===c.id?"block":"hidden"),onLoad:()=>{Re(),_e(),N()}},c.id):null}),ue.map(c=>e.jsx("div",{className:Se("absolute inset-0",k?.id!==c.id&&"hidden"),children:e.jsx(T,{initialUrl:c.targetPath??"",directory:n,tabID:c.id})},c.id)),R?Pe.filter(c=>k?.id===c.id).map(c=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(_o,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:c.diffScope??(c.stagedDiff?"staged":"working"),onDiffScopeChange:ye,targetFilePath:c.targetPath,flushContent:!0})})},c.id)):null,w?e.jsx("div",{className:Se("absolute inset-0",k?.mode==="terminal"?"block":"hidden"),children:e.jsx(yn,{visible:R&&k?.mode==="terminal"})}):null,R&&k?.mode!=="chat"&&!ae&&k?.mode!=="browser"&&k?.mode!=="diff"&&k?.mode!=="terminal"?g:null]})]})]})},oa=150,aa=500,ia=[],Be=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),ot=(t,n)=>{if(!t||typeof t!="object")return;const s=t[n];return typeof s=="number"&&Number.isFinite(s)?s:void 0},la=t=>t>99?"99+":String(t),ca=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",da=({surface:t,isActive:n,showActivityDot:s,label:o,description:a,badgeCount:d,badgeAriaLabel:y,badgeDescription:u,orderNumber:m,showOrderNumber:x,onSelect:v,chartPercentage:p,chartDetails:i})=>{const{attributes:C,listeners:f,setNodeRef:W,transform:P,transition:F,isDragging:O}=Ds({id:t.id}),B=d!=null&&d>0?la(d):null;return e.jsx("div",{ref:W,style:{transform:_s.Translate.toString(P),transition:F},className:Se("relative",O&&"z-10 opacity-70"),children:e.jsxs(Ue,{delayDuration:oa,children:[e.jsx(He,{asChild:!0,children:e.jsxs("button",{type:"button",...C,...f,onClick:()=>v(t),"aria-label":y??o,"aria-pressed":n,className:Se("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"text-primary":"text-muted-foreground hover:text-foreground"),children:[t.id==="context"&&typeof p=="number"?e.jsx(Kt,{percentage:p,className:"size-[18px] -rotate-90"}):e.jsx(V,{name:t.icon,className:"h-[18px] w-[18px]"}),x&&m!=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:m===10?"0":m}):B?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:B}):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(Ve,{side:"left",sideOffset:8,className:t.id==="context"&&i?"p-0 border-0 bg-transparent shadow-none":void 0,children:t.id==="context"&&i?e.jsx("div",{className:"w-[300px] overflow-hidden rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[e.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:e.jsx(Kt,{percentage:i.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:o}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:i.hasData?e.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[e.jsxs("span",{className:Se("font-semibold",ca(i.percentage)),children:[i.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${Be(i.totalTokens)}/${Be(i.contextLimit)}`})]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:"No data yet"})})]}),i.hasData?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Be(i.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Be(i.contextLimit)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Be(i.outputLimit)})]}),typeof i.cacheRead=="number"&&typeof i.cacheWrite=="number"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Be(i.cacheRead)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Be(i.cacheWrite)})]})]}):null,typeof i.cacheHitPercent=="number"?e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache hit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:`${i.cacheHitPercent.toFixed(1)}%`})]}):null]}):e.jsx("div",{className:"px-2.5 py-2 typography-micro text-muted-foreground",children:a})]})}):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}),u?e.jsx("span",{className:"typography-micro text-muted-foreground",children:u}):null]})})]})})},ua=()=>{const t=nt(),n=t?rr(t):"",s=te(h=>n?h.contextPanelByDirectory[n]:void 0),o=te(h=>h.contextRailOrder),a=te(h=>h.setContextRailOrder),d=te(h=>h.openContextSurface),y=te(h=>h.shortcutOverrides),{screenWidth:u}=At(),{git:m}=kt(),x=bn(n||null),v=Nn(n||null),p=En(h=>h.ensureStatus);r.useEffect(()=>{n&&p(n,m)},[n,p,m]);const i=r.useMemo(()=>qr("switch_context_surface",y),[y]),[C,f]=r.useState(!1);r.useEffect(()=>{const h=new Set;let j=null,M=!1;const X=ye=>ye.length===1&&ye>="0"&&ye<="9",Z=()=>{Vt(i,h)?!M&&j===null&&(j=setTimeout(()=>f(!0),aa)):(M=!1,j!==null&&(clearTimeout(j),j=null),f(!1))},pe=ye=>{if(h.add(ye.key.toLowerCase()),X(ye.key)&&Vt(i,h)){M=!0,j!==null&&(clearTimeout(j),j=null),f(!1);return}Z()},se=ye=>{h.delete(ye.key.toLowerCase()),Z()},ve=()=>{h.clear(),M=!1,j!==null&&(clearTimeout(j),j=null),f(!1)};return window.addEventListener("keydown",pe,!0),window.addEventListener("keyup",se,!0),window.addEventListener("blur",ve),()=>{window.removeEventListener("keydown",pe,!0),window.removeEventListener("keyup",se,!0),window.removeEventListener("blur",ve),j!==null&&clearTimeout(j)}},[i]);const W=js(qt(ks,{activationConstraint:{distance:8}}),qt(Cs,{activationConstraint:{delay:200,tolerance:6}})),P=s?.tabs??ia,F=P.find(h=>h.id===s?.activeTabId)??null,O=s?.isOpen?F?.mode??null:null,B=x?.files.length??0,$=De(h=>h.currentSessionId),k=De(h=>!!h.newSessionDraft?.open),R=ze(h=>h.providers),D=ze(h=>h.currentProviderId),A=ze(h=>h.currentModelId),b=ze(h=>h.getCurrentModel()),z=ze(h=>h.getModelMetadata);ze(h=>h.modelsMetadata.size);const ne=Gr(r.useCallback(h=>$?h.sessionModelSelections.get($)??null:null,[$])),G=Sn($??""),U=r.useMemo(()=>{for(let h=G.length-1;h>=0;h-=1){const j=G[h];if(j?.info.role==="assistant")try{if(vt(j).total>0)return j}catch{continue}}return null},[G]),E=r.useMemo(()=>{for(let h=G.length-1;h>=0;h-=1){const j=G[h]?.info;if(j.role!=="user")continue;const M=j.model,X=M?.providerID??M?.providerId,Z=M?.modelID??M?.modelId;if(typeof X=="string"&&X.trim()&&typeof Z=="string"&&Z.trim())return{providerID:X,modelID:Z}}return null},[G])??(()=>{const h=U?.info.model,j=h?.providerID??h?.providerId,M=h?.modelID??h?.modelId;return j&&M?{providerID:j,modelID:M}:null})()??(ne?{providerID:ne.providerId,modelID:ne.modelId}:null)??(D&&A?{providerID:D,modelID:A}:null),S=(E?R.find(h=>h.id===E.providerID):void 0)?.models.find(h=>h.id===E?.modelID),I=E?z(E.providerID,E.modelID):void 0,Q=ot(S?.limit,"context")??I?.limit?.context??ot(b?.limit,"context")??0,_=ot(S?.limit,"output")??I?.limit?.output??ot(b?.limit,"output")??0,q=U?(()=>{try{return vt(U)}catch{return null}})():null,re=U?.info?.usage,ce=re?Cn(re):q?.total??0,he=!k&&ce>0&&Q>0?Math.min(ce/Q*100,999):0,je=he,ge=q?jn({input:q.input,cache:{read:q.cacheRead,write:q.cacheWrite}}):null,xe=ge?.hasInput?ge.percent:null,ie=r.useMemo(()=>{const h=!!U&&ce>0&&Q>0;return{percentage:he,totalTokens:ce,contextLimit:Q,outputLimit:_,cacheRead:q?.cacheRead??null,cacheWrite:q?.cacheWrite??null,cacheHitPercent:xe,hasData:h}},[q,xe,Q,U,_,he,ce]),Ce=r.useMemo(()=>Yr({railOrder:o,tabs:P}),[o,u,P]),ke=r.useCallback(h=>{const{active:j,over:M}=h;if(!M||j.id===M.id)return;const X=Jr(te.getState().contextRailOrder).map(se=>se.id),Z=X.indexOf(j.id),pe=X.indexOf(M.id);Z===-1||pe===-1||a(Es(X,Z,pe))},[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(Ns,{sensors:W,collisionDetection:Ps,onDragEnd:ke,children:e.jsx(Rs,{items:Ce.map(h=>h.id),strategy:Ts,children:Ce.map((h,j)=>{const M=h.id==="git"?Dt(v):null,X=M?{...h,...M}:h,Z=X.label,pe=h.id==="git"&&v===!0?B:0,se=pe>0?pe:null,ve=h.id==="context";return e.jsx(da,{surface:X,isActive:O===h.mode,showActivityDot:!1,label:Z,description:X.description,badgeCount:se,badgeAriaLabel:se!==null?se===1?`${Z}, ${se} changed file`:`${Z}, ${se} changed files`:null,badgeDescription:se!==null?se===1?`${se} changed file`:`${se} changed files`:null,chartPercentage:ve?je:void 0,chartDetails:ve?ie:void 0,orderNumber:j+1,showOrderNumber:C,onSelect:ye=>d(n,ye.mode)},h.id)})})})}):null},ha=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),pa=(t,n,s,o)=>!s||o!==s||t.length===0?[]:Ze(t,n,a=>a.name,{limit:10,threshold:.4}),ma=new Set,bt=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==="/",d=/^[A-Za-z]:\/$/.test(o);return!a&&!d&&(o=o.replace(/\/+$/,"")),o},fa=()=>{const t=te(l=>l.isCommandPaletteOpen),n=te(l=>l.setCommandPaletteOpen),s=te(l=>l.setActiveMainTab),o=te(l=>l.setSettingsDialogOpen),a=te(l=>l.setSettingsPage),d=te(l=>l.setSessionSwitcherOpen),y=te(l=>l.toggleSidebar),u=te(l=>l.openContextOverview),m=te(l=>l.openContextSurface),x=te(l=>l.openContextFile),v=te(l=>l.shortcutOverrides),p=De(l=>l.openNewSessionDraft),i=De(l=>l.setCurrentSession),C=Qr({archived:!1}),f=Zr(r.useCallback(l=>t?l.ids:ma,[t])),W=es(r.useCallback(l=>t?l.rankById:ts,[t])),P=sr(l=>l.currentDirectory),F=Xt(l=>l.getActiveProject()),O=Xt(l=>l.projects),B=nt(),$=hn(l=>l.searchFiles),{files:k,git:R}=kt(),D=En(l=>l.ensureStatus),{isMobile:A}=At(),b=r.useMemo(()=>B?bt(B):null,[B]),[z,ne]=r.useState(""),U=vn(z,200).trim(),J=z.trim();r.useEffect(()=>{t&&ne("")},[t]),r.useEffect(()=>{if(!t||!R)return;const l=setTimeout(()=>{const g=new Set;for(const ee of C){const ue=ft(ee);!ue||g.has(ue)||(g.add(ue),D(ue,R))}},0);return()=>clearTimeout(l)},[t,C,R,D]);const E=r.useCallback(()=>n(!1),[n]),H=r.useCallback(l=>()=>{E(),l()},[E]),S=r.useMemo(()=>{const l=[{id:"new-session",title:"New Session",icon:e.jsx(V,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:H(()=>{s("chat"),d(!1),p()})},{id:"add-project",title:"Add Project",icon:e.jsx(V,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:H(()=>{ns.requestDirectoryDialog()})},{id:"toggle-sidebar",title:A?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(V,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:A?"Show Session Switcher":"Toggle Sidebar",onSelect:H(()=>{if(A){const{isSessionSwitcherOpen:g}=te.getState();d(!g)}else y()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(V,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:H(()=>{P&&m(P,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(V,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:H(()=>{P&&u(P)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(V,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:H(()=>o(!0))}];return or()&&l.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(V,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:H(()=>{mn("desktop_open_draft_mini_chat_window",{directory:bt(P||F?.path||""),projectId:F?.id??null}).catch(g=>{console.warn("[command-palette] failed to open draft mini chat window",g)})})}),l},[H,A,s,d,p,y,m,P,u,o,F?.id,F?.path]),I=r.useMemo(()=>{const l=ar();return{isWeb:!l&&ir(),isDesktop:l,isMobile:A}},[A]),Q=r.useMemo(()=>yr.filter(l=>l.slug!=="home").filter(l=>l.isAvailable?l.isAvailable(I):!0).map(l=>{const g=br(l.slug)??"settings-3",ee=(l.keywords??[]).join(" ");return{id:`settings:${l.slug}`,title:l.title,icon:e.jsx(V,{name:g,className:"mr-2 h-4 w-4"}),searchText:`${l.title} ${l.group} ${ee}`,onSelect:H(()=>{a(l.slug),o(!0)})}}),[I,H,a,o]),_=r.useMemo(()=>rs(C,f,W),[C,f,W]),q=ss(),re=r.useCallback((l,g)=>g&&q.get(g)?.trim()||null,[q]),[ce,he]=r.useState([]),[je,ge]=r.useState(""),xe=ha(b,U);r.useEffect(()=>{if(!t){he([]),ge("");return}if(!xe){he([]),ge("");return}if(!b){he([]),ge("");return}let l=!1;return $(b,U,10,{type:"file"}).then(g=>{l||(he(g.map(ee=>({path:bt(ee.path),name:ee.name,relativePath:ee.relativePath}))),ge(xe))}).catch(()=>{l||(he([]),ge(xe))}),()=>{l=!0}},[t,b,U,xe,$]);const ie=J.length>0,Ce=r.useMemo(()=>ie?Ze(S,J,l=>l.searchText,{limit:7,noFuzzy:!0}):S.map(l=>({item:l,score:0})),[S,J,ie]),ke=r.useMemo(()=>ie?Ze(Q,J,l=>l.searchText,{limit:7,noFuzzy:!0}):[],[Q,J,ie]),h=r.useMemo(()=>ie?Ze(_,J,l=>l.title||"",{limit:7,threshold:.2}):_.slice(0,5).map(l=>({item:l,score:0})),[_,J,ie]),j=r.useMemo(()=>t?pa(ce,U,xe,je):[],[t,ce,je,xe,U]),M=t&&xe.length>0&&je!==xe,X=r.useMemo(()=>{if(!ie)return[];const l=O.map(g=>({...g,displayName:g.label||g.path.split("/").pop()||g.path,searchText:`${g.label||""} ${g.path}`}));return Ze(l,J,g=>g.searchText,{limit:7,threshold:.4})},[O,J,ie]),Z=Ce.map(l=>l.item),pe=ke.map(l=>l.item),se=h.map(l=>l.item),ve=ie?j.map(l=>l.item):[],ye=ie?X.map(l=>l.item):[],Re=r.useMemo(()=>{if(!ie)return["commands","sessions"];const l=ee=>ee.length?ee[0].score:1/0,g=[{key:"commands",score:l(Ce)},{key:"settings",score:l(ke)},{key:"sessions",score:l(h)},{key:"files",score:l(j)},{key:"projects",score:l(X)}];return g.sort((ee,ue)=>ee.score-ue.score),g.map(ee=>ee.key)},[ie,Ce,ke,h,j,X]),_e=r.useCallback(l=>{E(),i(l.id,ft(l))},[E,i]),N=r.useCallback(async l=>{if(!b)return;const g=await Dn(k,l,{directory:b});if(!g.ok){me.error(_n(g.reason));return}x(b,l),E()},[b,k,x,E]),le=r.useCallback((l,g)=>{E(),p({selectedProjectId:l,directoryOverride:g})},[E,p]),oe=r.useCallback(l=>Rn(Tn(l,v)),[v]);return e.jsxs(Nt,{open:t,onOpenChange:n,children:[e.jsxs(Et,{className:"sr-only",children:[e.jsx(Rt,{children:"Command Palette"}),e.jsx(Tt,{children:"Search files, sessions, and commands."})]}),e.jsx(Pt,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs(os,{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(as,{value:z,onValueChange:ne,placeholder:"Search files, sessions, commands..."}),e.jsxs(is,{children:[e.jsx(ls,{children:"No results found."}),Re.map(l=>l==="commands"&&Z.length>0?e.jsx(Ye,{children:Z.map(g=>e.jsxs(Je,{value:g.id,onSelect:g.onSelect,children:[g.icon,e.jsx("span",{children:g.title}),g.shortcutId?e.jsx(cs,{children:oe(g.shortcutId)}):null]},g.id))},"commands"):l==="settings"&&pe.length>0?e.jsx(Ye,{children:pe.map(g=>e.jsxs(Je,{value:g.id,onSelect:g.onSelect,children:[g.icon,e.jsx("span",{children:g.title})]},g.id))},"settings"):l==="sessions"&&se.length>0?e.jsx(Ye,{children:se.map(g=>{const ee=g.title||"Untitled Session",ue=ft(g),Pe=re(g.id,ue);return e.jsxs(Je,{value:`session:${g.id}`,onSelect:()=>_e(g),children:[e.jsx(V,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:ee}),Pe?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(V,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:Pe})]}):null]},g.id)})},"sessions"):l==="files"&&ve.length>0?e.jsx(Ye,{children:ve.map(g=>{const ee=ds(g.relativePath||g.name,{maxLength:80});return e.jsxs(Je,{value:`file:${g.path}`,onSelect:()=>{N(g.path)},children:[e.jsx(jt,{filePath:g.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":g.relativePath,children:ee})]},`file:${g.path}`)})},"files"):l==="projects"&&ye.length>0?e.jsx(Ye,{children:ye.map(g=>{const ee=g.displayName;return e.jsxs(Je,{value:`project:${g.id}`,onSelect:()=>le(g.id,g.path),children:[e.jsx(V,{name:"folder",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:ee}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:g.path})]},`project:${g.id}`)})},"projects"):null),M?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},dn=(t,n,s)=>hs(t)?Rn(Tn(t,s)):n,ga=()=>{const t=te(d=>d.isHelpDialogOpen),n=te(d=>d.setHelpDialogOpen),s=te(d=>d.shortcutOverrides),o=us(),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(Nt,{open:t,onOpenChange:n,children:e.jsxs(Pt,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(Et,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(V,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Tt,{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(d=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:d.categoryKey}),e.jsx("div",{className:"space-y-1",children:d.items.map(y=>{const u=y.id?dn(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(V,{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(u)?u:[u]).map((m,x)=>e.jsxs(r.Fragment,{children:[x>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:m})]},`${m}-${x}`))})]},y.id||y.descriptionKey)})})]},d.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(V,{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 (${dn("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"]})]})]})]})})]})]})})},xa=r.createContext(null),wa=({children:t,value:n})=>e.jsx(xa.Provider,{value:n,children:t}),un=We(()=>Le(()=>import("./GitView-BfykGpGh.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}))),ya=We(()=>Le(()=>import("./DiffView-5wHwK-lg.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}))),ba=We(()=>Le(()=>import("./FilesView-5bswI3JZ.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}))),va=We(()=>Le(()=>import("./DiagramView-DlHzRRBc.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}))),Sa=We(()=>Le(()=>import("./SettingsView-FGe5TEQq.js").then(t=>t.a),__vite__mapDeps([130,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,131,132,115])).then(t=>({default:t.SettingsView}))),ja=We(()=>Le(()=>import("./SettingsWindow-Ck_uhTnx.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}))),Ca=()=>{const t=te(S=>S.isSidebarOpen),n=te(S=>S.activeMainTab),s=te(S=>S.setIsMobile),o=te(S=>S.isSessionSwitcherOpen),a=te(S=>S.isSettingsDialogOpen),d=te(S=>S.setSettingsDialogOpen),[y,u]=r.useState(!1);r.useEffect(()=>{a&&u(!0)},[a]),r.useEffect(()=>{const S=()=>te.getState().closeMainSurfaces(),I=De.subscribe((_,q)=>{const re=!!_.currentSessionId&&_.currentSessionId!==q.currentSessionId,ce=!!_.newSessionDraft?.open&&_.newSessionDraft!==q.newSessionDraft;(re||ce)&&S()}),Q=te.subscribe((_,q)=>{_.activeMainTab!==q.activeMainTab&&S()});return()=>{I(),Q()}},[]);const{isMobile:m}=At(),x=r.useRef(!1),[v,p]=r.useState(!1),[i,C]=r.useState(!1),[f,W]=r.useState(!1),[P,F]=r.useState(!1),O=r.useCallback(S=>{p(S),te.getState().setSessionSwitcherOpen(S)},[]),B=r.useRef(typeof window>"u"?0:window.innerWidth),$=r.useRef(null),k=r.useRef(!1),R=r.useRef(!1),D=r.useRef(!1),A=r.useRef(null),b=r.useRef(null),z=Gt(-B.current),ne=Me.useRef(0),G=Gt(B.current),U=Me.useRef(0);Me.useEffect(()=>{m&&(ne.current=window.innerWidth,U.current=window.innerWidth)},[m]),Me.useEffect(()=>{if(!m)return;const S=()=>{const I=window.innerWidth;ne.current=I,U.current=I,v||z.get()<-10&&z.set(-I),i||G.get()>10&&G.set(I)};return window.addEventListener("resize",S),window.addEventListener("orientationchange",S),()=>{window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S)}},[m,z,G,v,i]),Me.useEffect(()=>{if(!m){W(!1);return}v&&W(!0);const S=ne.current||B.current||(typeof window<"u"?window.innerWidth:0),I=st(z,v?0:-S,{type:"spring",stiffness:400,damping:35,mass:.8});return A.current=I,()=>I.stop()},[v,m,z]),Me.useEffect(()=>{if(!m){F(!1);return}i&&F(!0);const S=U.current||B.current||(typeof window<"u"?window.innerWidth:0),I=st(G,i?0:S,{type:"spring",stiffness:400,damping:35,mass:.8});return b.current=I,()=>I.stop()},[m,i,G]),Me.useEffect(()=>{if(m)return z.on("change",S=>{const I=ne.current||B.current,Q=v||S>-I+.5;W(_=>_===Q?_:Q)})},[m,z,v]),Me.useEffect(()=>{if(m)return G.on("change",S=>{const I=U.current||B.current,Q=i||S<I-.5;F(_=>_===Q?_:Q)})},[m,i,G]),Me.useEffect(()=>{m&&!o&&v&&O(!1)},[o,m,v,O]),Me.useEffect(()=>{if(!m){x.current=!1;return}x.current||(x.current=!0,O(!1),C(!1))},[m,O]),Me.useEffect(()=>{if(!m||n!=="chat"||v||i||a)return;let S=!1,I;const Q=_=>{I=window.setTimeout(()=>{if(S)return;const q=De.getState(),re=te.getState();if(!(re.activeMainTab!=="chat"||re.isSettingsDialogOpen||q.currentSessionId||q.newSessionDraft?.open)){if(q.isLoading){Q(250);return}q.openNewSessionDraft({automatic:!0})}},_)};return Q(500),()=>{S=!0,I!==void 0&&window.clearTimeout(I)}},[n,m,a,v,i]),Me.useEffect(()=>{!m||!a||(O(!1),C(!1))},[m,a,O]),r.useEffect(()=>{te.getState().isMobile!==m&&s(m)},[m,s]);const J=r.useCallback(()=>{v&&O(!1),C(!i)},[v,i,O]);vr($,{enabled:m,leftOpen:v,rightOpen:i,leftWidth:()=>ne.current||B.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>U.current||B.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:S=>{const I=ne.current||B.current||(typeof window<"u"?window.innerWidth:0);z.set(I*(S-1))},onRightProgress:S=>{const I=U.current||B.current||(typeof window<"u"?window.innerWidth:0);G.set(I*(1-S))},onLeftOpen:()=>{i&&C(!1),O(!0)},onLeftClose:()=>O(!1),onRightOpen:()=>{v&&O(!1),C(!0)},onRightClose:()=>C(!1),onDragStart:S=>{k.current=!0,S==="left"?(R.current=v,A.current?.stop(),f||W(!0)):(D.current=i,b.current?.stop(),P||F(!0))},onDragEnd:(S,I)=>{if(k.current=!1,S==="left"&&typeof I=="boolean"){const Q=R.current;if(I===Q){const _=ne.current||B.current||(typeof window<"u"?window.innerWidth:0),q=st(z,Q?0:-_,{type:"spring",stiffness:400,damping:35,mass:.8});A.current=q}}if(S==="right"&&typeof I=="boolean"){const Q=D.current;if(I===Q){const _=U.current||B.current||(typeof window<"u"?window.innerWidth:0),q=st(G,Q?0:_,{type:"spring",stiffness:400,damping:35,mass:.8});b.current=q}}}});const E=r.useMemo(()=>{if(!m&&n!=="terminal"&&n!=="diagram"||m&&n==="git"&&(i||P))return null;switch(n){case"git":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(un,{isActive:!0})});case"diff":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(ya,{})});case"terminal":return e.jsx(yn,{});case"files":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(ba,{})});case"context":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(wn,{})});case"diagram":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(va,{})});default:return null}},[n,m,P,i]),H=n==="chat";return e.jsxs(Sr,{children:[e.jsx(jr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:Se("main-content-safe-area",m?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(fa,{}),e.jsx(ga,{}),e.jsx(Cr,{}),m?e.jsxs(wa,{value:{leftDrawerOpen:v,rightDrawerOpen:i,toggleLeftDrawer:()=>{const S=!v;i&&C(!1),O(S)},toggleRightDrawer:J,leftDrawerX:z,rightDrawerX:G,leftDrawerWidth:ne,rightDrawerWidth:U,setMobileLeftDrawerOpen:O,setRightSidebarOpen:C},children:[!a&&e.jsx(Ft,{onToggleLeftDrawer:()=>{const S=!v;i&&C(!1),O(S)},onToggleRightDrawer:()=>{J()},leftDrawerOpen:v,rightDrawerOpen:i}),e.jsx("div",{"data-page-scroll-lock":"true",className:Se("flex flex-1 overflow-hidden relative",a&&"hidden"),children:e.jsxs("main",{ref:$,className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:[e.jsx("div",{className:Se("absolute inset-0",!H&&"invisible"),children:e.jsx(Ie,{children:e.jsx(Bt,{active:H&&!a})})}),E&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ie,{children:E})}),e.jsx(Ie,{children:e.jsx(zt,{})}),e.jsx(Yt.div,{className:Se("absolute inset-0 z-20 bg-sidebar",!f&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:z},"aria-hidden":!v,children:e.jsx(Ie,{children:e.jsx(Ut,{mobileVariant:!0,isVisible:f})})}),e.jsx(Yt.div,{className:Se("absolute inset-0 z-20 bg-sidebar",!P&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:G},"aria-hidden":!i,children:e.jsx(Ie,{children:i||P?e.jsx(r.Suspense,{fallback:null,children:e.jsx(un,{isActive:i})}):null})})]})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(Ie,{children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(Sa,{onClose:()=>d(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(kr,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(Ms,{isOpen:t,isMobile:m,className:"border-border",children:e.jsx(Ut,{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(Ft,{}),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:Se("absolute inset-0",!H&&"invisible"),children:e.jsx(Ie,{children:e.jsx(Bt,{active:H&&!a})})}),E&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ie,{children:E})}),e.jsx(Ie,{children:e.jsx(zt,{})})]}),e.jsx(sa,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Ie,{children:e.jsx(ua,{})})})]})]})]}),y?e.jsx(r.Suspense,{fallback:null,children:e.jsx(ja,{open:a,onOpenChange:d})}):null]})]})]})},ka=()=>(gs(),Pr(),e.jsxs(Er,{children:[e.jsx(xs,{embeddedBackgroundWorkEnabled:!0}),e.jsx(Ca,{}),e.jsx(ws,{}),e.jsx(ys,{})]}));function Na({apis:t}){const n=t??xn(),[s,o]=r.useState(0);return r.useEffect(()=>lr(a=>{a.runtimeKey!==a.previousRuntimeKey&&(Nr(a),o(d=>d+1))}),[]),r.useEffect(()=>{cr()},[s]),r.useEffect(()=>{n&&dr(n)},[n]),n?e.jsx(Ie,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(ps,{apis:n,children:e.jsx(ms,{children:e.jsx(fs,{children:e.jsx(ka,{})})},s)})})}):e.jsx(Ie,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const Kn=document.getElementById("root");if(!Kn)throw new Error("Root element not found");Gn.createRoot(Kn).render(e.jsx(Me.StrictMode,{children:e.jsx(bs,{children:e.jsx(vs,{children:e.jsx(Ss,{children:e.jsx(Na,{apis:xn()??void 0})})})})}));
@@ -1,2 +1,2 @@
1
- import{g as $}from"./vendor-marked-i_gIkIP3.js";import{k as z}from"./vendor-katex-CHD9BdDO.js";import{p}from"./vendor-dompurify-r8glNMJW.js";import{d$ as T,e0 as L,e1 as E,e2 as C}from"./SessionSwitcherDropdown-C0OdvirK.js";import{p as O}from"./vendor-remend-BWYYytN3.js";const I=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),k=["script","style"],v=e=>$.lexer(e),H=e=>/^\[[^\]]+\]:\s+\S+/m.test(e)||/^\[\^[^\]]+\]:\s+/m.test(e),R=e=>{const t=e.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(!t)return!1;const r=t[1];if(!r)return!1;const n=r[0],s=r.length,a=e.trimEnd().split(`
2
- `).at(-1)?.trim()??"";return!new RegExp(`^[\\t ]{0,3}${n}{${s},}[\\t ]*$`).test(a)},le=e=>{const t=e.replace(/^\n+/,"");return!!(/^[ \t]{0,3}(`{3,}|~{3,})/.test(t)||/^[ \t]{0,3}(?:> |[-*+] |\d+[.)] )/.test(t))},D=e=>{try{return O(e,{linkMode:"text-only"})}catch{return e}},g=(e,t)=>[{raw:e,src:e,mode:t?"live":"full",highlight:!t}],w=(e,t)=>{let r=-1;for(let s=e.length-1;s>=0;s-=1)if(e[s]?.type!=="space"){r=s;break}if(r<0)return[];const n=[];for(let s=0;s<e.length;s+=1){const a=e[s];if(!a||a.type==="space")continue;const i=a.raw??"",c=t.markLastLive&&s===r,o=a.type==="code"&&R(i);n.push({raw:i,src:o||c?i:D(i),mode:c?"live":"full",highlight:!t.cheap&&!o})}return n},b=(e,t,r=v)=>[{raw:e,src:e,mode:"full",highlight:!0}],N=2;class P{constructor(t=v){this.lex=t}prevText="";frozenSrc="";frozenBlocks=[];cached=null;update(t){if(this.cached&&t===this.prevText)return this.cached;if(this.prevText&&!t.startsWith(this.prevText)&&(this.frozenSrc="",this.frozenBlocks=[]),this.prevText=t,H(t))return this.frozenSrc="",this.frozenBlocks=[],this.cached=g(t,!0),this.cached;this.frozenSrc&&!t.startsWith(this.frozenSrc)&&(this.frozenSrc="",this.frozenBlocks=[]);const r=t.slice(this.frozenSrc.length);let n;try{n=this.lex(r)}catch{return this.cached=g(t,!0),this.cached}const s=[];for(let o=0;o<n.length;o+=1)n[o]?.type!=="space"&&s.push(o);const a=Math.max(0,s.length-N);if(a>0){const o=(s[a-1]??-1)+1,l=n.slice(0,o),f=w(l,{markLastLive:!1,cheap:!0});this.frozenBlocks=[...this.frozenBlocks,...f],this.frozenSrc+=l.map(m=>m.raw??"").join(""),n=n.slice(o)}const i=w(n,{markLastLive:!0,cheap:!0}),c=i.length>0?[...this.frozenBlocks,...i]:this.frozenBlocks.length>0?this.frozenBlocks:g(t,!0);return this.cached=c,c}}const F=32,h=new Map,G=e=>{const t=h.get(e);if(t)return h.delete(e),h.set(e,t),t;const r=new P;for(h.set(e,r);h.size>F;){const n=h.keys().next().value;if(typeof n!="string")break;h.delete(n)}return r},S=e=>{h.delete(e)},he=(e,t)=>{if(!e||e.length===0||e.length!==t.length||t[t.length-1]?.mode!=="live"||e[e.length-1]?.mode!=="live")return!1;for(let n=0;n<t.length-1;n+=1){const s=e[n],a=t[n];if(!s||!a||s.mode!=="full"||a.mode!=="full"||s.raw!==a.raw)return!1}return!0},u=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),y=(e,t,r)=>{try{return z.renderToString(e,{displayMode:r,throwOnError:!1})}catch{return t}},j={name:"inlineMath",level:"inline",start(e){const t=e.indexOf("\\(");return t<0?void 0:t},tokenizer(e){const t=/^\\\(([\s\S]+?)\\\)/.exec(e);if(t)return{type:"inlineMath",raw:t[0],text:t[1]??""}},renderer(e){const t=e;return y(t.text,t.raw,!1)}},q={name:"blockMath",level:"block",start(e){const t=e.indexOf("\\[");return t<0?void 0:t},tokenizer(e){const t=/^\\\[([\s\S]+?)\\\]/.exec(e);if(t)return{type:"blockMath",raw:t[0],text:t[1]??""}},renderer(e){const t=e;return y(t.text,t.raw,!0)}},A=$.use({gfm:!0,breaks:!1,extensions:[j,q],renderer:{html({text:e}){return I(e)},link({href:e,title:t,text:r}){const n=e??"",s=T(n);if(s)return`<a href="${u(C(s))}" data-pichamber-agent-mention="true" class="text-primary hover:underline" target="_blank" rel="noopener noreferrer">${r}</a>`;const a=L(n);if(a)return`<a href="${u(n)}" data-skill-name="${u(a)}" class="text-primary hover:underline">${r}</a>`;const i=t?` title="${u(t)}"`:"";return`<a href="${u(n)}"${i} class="external-link" target="_blank" rel="noopener noreferrer">${r}</a>`}}}),W=e=>e.replace(/\$\$([\s\S]*?)\$\$/g,(t,r)=>{try{return z.renderToString(r,{displayMode:!0,throwOnError:!1})}catch{return`$$${r}$$`}}),_=e=>{if(e.indexOf("$")===-1)return e;const t=/(<(?:pre|code|kbd)[^>]*>[\s\S]*?<\/(?:pre|code|kbd)>)/gi;return e.split(t).map((r,n)=>n%2===1?r:W(r)).join("")},U=/<pre><code(?:\s+class="language-([^"]*)")?>([\s\S]*?)<\/code><\/pre>/g,X=1200,Z=(e,t)=>{let r=1;for(let n=0;n<e.length;n+=1)if(e.charCodeAt(n)===10&&++r>t)return!0;return!1},J=e=>e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&"),Q=async e=>{const t=[...e.matchAll(U)];if(t.length===0)return e;const r=X;let n=e;for(const s of t){const[a,i,c]=s,o=(i||"text").toLowerCase();if(o==="mermaid")continue;const l=J(c??"");if(Z(l,r)){n=n.replace(a,()=>a.replace("<pre",`<pre data-md-lang="${o}"`));continue}const f=await E(l,o);if(f){const m=f.replace(/^<pre/,`<pre data-md-lang="${o}"`);n=n.replace(a,()=>m)}}return n},V={USE_PROFILES:{html:!0,mathMl:!0,svg:!0},ADD_TAGS:["svg","path","g","rect","line","polygon","polyline","circle","ellipse","text","tspan","defs","marker"],ADD_ATTR:["d","viewBox","preserveAspectRatio","xmlns","target","fill","stroke","stroke-width","transform","points","x","y","x1","y1","x2","y2","cx","cy","r","rx","ry","style"],FORBID_TAGS:[...k],FORBID_CONTENTS:[...k]};let M=!1;const Y=()=>{M||typeof window>"u"||!p.isSupported||(M=!0,p.addHook("afterSanitizeAttributes",e=>{e instanceof HTMLAnchorElement&&e.target==="_blank"&&e.setAttribute("rel","noopener noreferrer")}))},B=e=>p.isSupported?(Y(),p.sanitize(e,V)):"",K=240,d=new Map,ee=e=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)},x=(e,t)=>{if(d.delete(e),d.set(e,t),d.size<=K)return;const r=d.keys().next().value;r&&d.delete(r)},te=async e=>{const t=await Promise.resolve(A.parse(e.src)),r=e.highlight?_(t):t,n=e.highlight?await Q(r):r;return B(n)},re=e=>{if(!e)return"";const t=A.parse(e),r=_(t);return B(r)},ne=async(e,t,r)=>{if(!e)return r&&S(r),[];let n;return t?n=G(r).update(e):(S(r),n=b(e)),Promise.all(n.map(async(s,a)=>{if(s.mode==="live")return{id:`live:${a}`,html:"",mode:"live",raw:s.raw};const i=ee(s.raw),c=`${i}:${s.mode}:${s.highlight?1:0}`,o=`${r}:${a}:${s.mode}`,l=d.get(o);if(l&&l.hash===i)return x(o,l),{id:c,html:l.html,mode:s.mode,raw:s.raw};const f=await te(s);return x(o,{hash:i,html:f}),{id:c,html:f,mode:s.mode,raw:s.raw}}))},fe=Object.freeze(Object.defineProperty({__proto__:null,renderMarkdownBlocks:ne,renderMarkdownSync:re},Symbol.toStringTag,{value:"Module"}));export{ne as a,le as b,he as i,fe as m,re as r,G as s};
1
+ import{g as z}from"./vendor-marked-i_gIkIP3.js";import{k as $}from"./vendor-katex-CHD9BdDO.js";import{p}from"./vendor-dompurify-r8glNMJW.js";import{eH as T,eI as L,eJ as E,eK as C}from"./SessionSwitcherDropdown-D5bWfZNA.js";import{p as I}from"./vendor-remend-BWYYytN3.js";const O=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),k=["script","style"],v=e=>z.lexer(e),H=e=>/^\[[^\]]+\]:\s+\S+/m.test(e)||/^\[\^[^\]]+\]:\s+/m.test(e),R=e=>{const t=e.match(/^[ \t]{0,3}(`{3,}|~{3,})/);if(!t)return!1;const r=t[1];if(!r)return!1;const n=r[0],s=r.length,a=e.trimEnd().split(`
2
+ `).at(-1)?.trim()??"";return!new RegExp(`^[\\t ]{0,3}${n}{${s},}[\\t ]*$`).test(a)},le=e=>{const t=e.replace(/^\n+/,"");return!!(/^[ \t]{0,3}(`{3,}|~{3,})/.test(t)||/^[ \t]{0,3}(?:> |[-*+] |\d+[.)] )/.test(t))},D=e=>{try{return I(e,{linkMode:"text-only"})}catch{return e}},g=(e,t)=>[{raw:e,src:e,mode:t?"live":"full",highlight:!t}],w=(e,t)=>{let r=-1;for(let s=e.length-1;s>=0;s-=1)if(e[s]?.type!=="space"){r=s;break}if(r<0)return[];const n=[];for(let s=0;s<e.length;s+=1){const a=e[s];if(!a||a.type==="space")continue;const i=a.raw??"",c=t.markLastLive&&s===r,o=a.type==="code"&&R(i);n.push({raw:i,src:o||c?i:D(i),mode:c?"live":"full",highlight:!t.cheap&&!o})}return n},b=(e,t,r=v)=>[{raw:e,src:e,mode:"full",highlight:!0}],N=2;class P{constructor(t=v){this.lex=t}prevText="";frozenSrc="";frozenBlocks=[];cached=null;update(t){if(this.cached&&t===this.prevText)return this.cached;if(this.prevText&&!t.startsWith(this.prevText)&&(this.frozenSrc="",this.frozenBlocks=[]),this.prevText=t,H(t))return this.frozenSrc="",this.frozenBlocks=[],this.cached=g(t,!0),this.cached;this.frozenSrc&&!t.startsWith(this.frozenSrc)&&(this.frozenSrc="",this.frozenBlocks=[]);const r=t.slice(this.frozenSrc.length);let n;try{n=this.lex(r)}catch{return this.cached=g(t,!0),this.cached}const s=[];for(let o=0;o<n.length;o+=1)n[o]?.type!=="space"&&s.push(o);const a=Math.max(0,s.length-N);if(a>0){const o=(s[a-1]??-1)+1,l=n.slice(0,o),f=w(l,{markLastLive:!1,cheap:!0});this.frozenBlocks=[...this.frozenBlocks,...f],this.frozenSrc+=l.map(m=>m.raw??"").join(""),n=n.slice(o)}const i=w(n,{markLastLive:!0,cheap:!0}),c=i.length>0?[...this.frozenBlocks,...i]:this.frozenBlocks.length>0?this.frozenBlocks:g(t,!0);return this.cached=c,c}}const F=32,h=new Map,G=e=>{const t=h.get(e);if(t)return h.delete(e),h.set(e,t),t;const r=new P;for(h.set(e,r);h.size>F;){const n=h.keys().next().value;if(typeof n!="string")break;h.delete(n)}return r},S=e=>{h.delete(e)},he=(e,t)=>{if(!e||e.length===0||e.length!==t.length||t[t.length-1]?.mode!=="live"||e[e.length-1]?.mode!=="live")return!1;for(let n=0;n<t.length-1;n+=1){const s=e[n],a=t[n];if(!s||!a||s.mode!=="full"||a.mode!=="full"||s.raw!==a.raw)return!1}return!0},d=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),y=(e,t,r)=>{try{return $.renderToString(e,{displayMode:r,throwOnError:!1})}catch{return t}},j={name:"inlineMath",level:"inline",start(e){const t=e.indexOf("\\(");return t<0?void 0:t},tokenizer(e){const t=/^\\\(([\s\S]+?)\\\)/.exec(e);if(t)return{type:"inlineMath",raw:t[0],text:t[1]??""}},renderer(e){const t=e;return y(t.text,t.raw,!1)}},q={name:"blockMath",level:"block",start(e){const t=e.indexOf("\\[");return t<0?void 0:t},tokenizer(e){const t=/^\\\[([\s\S]+?)\\\]/.exec(e);if(t)return{type:"blockMath",raw:t[0],text:t[1]??""}},renderer(e){const t=e;return y(t.text,t.raw,!0)}},A=z.use({gfm:!0,breaks:!1,extensions:[j,q],renderer:{html({text:e}){return O(e)},link({href:e,title:t,text:r}){const n=e??"",s=T(n);if(s)return`<a href="${d(C(s))}" data-pichamber-agent-mention="true" class="text-primary hover:underline" target="_blank" rel="noopener noreferrer">${r}</a>`;const a=L(n);if(a)return`<a href="${d(n)}" data-skill-name="${d(a)}" class="text-primary hover:underline">${r}</a>`;const i=t?` title="${d(t)}"`:"";return`<a href="${d(n)}"${i} class="external-link" target="_blank" rel="noopener noreferrer">${r}</a>`}}}),W=e=>e.replace(/\$\$([\s\S]*?)\$\$/g,(t,r)=>{try{return $.renderToString(r,{displayMode:!0,throwOnError:!1})}catch{return`$$${r}$$`}}),_=e=>{if(e.indexOf("$")===-1)return e;const t=/(<(?:pre|code|kbd)[^>]*>[\s\S]*?<\/(?:pre|code|kbd)>)/gi;return e.split(t).map((r,n)=>n%2===1?r:W(r)).join("")},U=/<pre><code(?:\s+class="language-([^"]*)")?>([\s\S]*?)<\/code><\/pre>/g,X=1200,J=(e,t)=>{let r=1;for(let n=0;n<e.length;n+=1)if(e.charCodeAt(n)===10&&++r>t)return!0;return!1},Z=e=>e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&"),Q=async e=>{const t=[...e.matchAll(U)];if(t.length===0)return e;const r=X;let n=e;for(const s of t){const[a,i,c]=s,o=(i||"text").toLowerCase();if(o==="mermaid")continue;const l=Z(c??"");if(J(l,r)){n=n.replace(a,()=>a.replace("<pre",`<pre data-md-lang="${o}"`));continue}const f=await E(l,o);if(f){const m=f.replace(/^<pre/,`<pre data-md-lang="${o}"`);n=n.replace(a,()=>m)}}return n},V={USE_PROFILES:{html:!0,mathMl:!0,svg:!0},ADD_TAGS:["svg","path","g","rect","line","polygon","polyline","circle","ellipse","text","tspan","defs","marker"],ADD_ATTR:["d","viewBox","preserveAspectRatio","xmlns","target","fill","stroke","stroke-width","transform","points","x","y","x1","y1","x2","y2","cx","cy","r","rx","ry","style"],FORBID_TAGS:[...k],FORBID_CONTENTS:[...k]};let M=!1;const Y=()=>{M||typeof window>"u"||!p.isSupported||(M=!0,p.addHook("afterSanitizeAttributes",e=>{e instanceof HTMLAnchorElement&&e.target==="_blank"&&e.setAttribute("rel","noopener noreferrer")}))},B=e=>p.isSupported?(Y(),p.sanitize(e,V)):"",K=240,u=new Map,ee=e=>{let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(36)},x=(e,t)=>{if(u.delete(e),u.set(e,t),u.size<=K)return;const r=u.keys().next().value;r&&u.delete(r)},te=async e=>{const t=await Promise.resolve(A.parse(e.src)),r=e.highlight?_(t):t,n=e.highlight?await Q(r):r;return B(n)},re=e=>{if(!e)return"";const t=A.parse(e),r=_(t);return B(r)},ne=async(e,t,r)=>{if(!e)return r&&S(r),[];let n;return t?n=G(r).update(e):(S(r),n=b(e)),Promise.all(n.map(async(s,a)=>{if(s.mode==="live")return{id:`live:${a}`,html:"",mode:"live",raw:s.raw};const i=ee(s.raw),c=`${i}:${s.mode}:${s.highlight?1:0}`,o=`${r}:${a}:${s.mode}`,l=u.get(o);if(l&&l.hash===i)return x(o,l),{id:c,html:l.html,mode:s.mode,raw:s.raw};const f=await te(s);return x(o,{hash:i,html:f}),{id:c,html:f,mode:s.mode,raw:s.raw}}))},fe=Object.freeze(Object.defineProperty({__proto__:null,renderMarkdownBlocks:ne,renderMarkdownSync:re},Symbol.toStringTag,{value:"Module"}));export{ne as a,le as b,he as i,fe as m,re as r,G as s};