@pi-chamber/web 0.1.9 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.test.js +48 -0
- package/bin/lib/DOCUMENTATION.md +2 -2
- package/bin/lib/cli-args.js +38 -11
- package/bin/lib/cli-startup.js +60 -13
- package/bin/lib/commands-startup.js +20 -5
- package/bin/lib/commands-update.js +91 -34
- package/bin/lib/commands-update.test.js +57 -42
- package/dist/assets/CommitSection-LewzHfDH.js +1 -0
- package/dist/assets/DiagramEditor-BOIJVnh3.js +1 -0
- package/dist/assets/DiagramView-CdNHezna.js +1 -0
- package/dist/assets/{DiffView-k3lX2PiV.js → DiffView-Cmw-RHIH.js} +2 -2
- package/dist/assets/{FilesView-C39IOFfs.js → FilesView-BODbL0Xm.js} +6 -6
- package/dist/assets/{GitView-CkztSaT7.js → GitView-DqYF-n_h.js} +4 -4
- package/dist/assets/JsonTreeView-DzEjA1ht.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-CF12jEtB.js → MarkdownRendererImpl-Bfq0bOSM.js} +2 -2
- package/dist/assets/PatchDiff-CtVByTC4.js +1 -0
- package/dist/assets/{PierreDiffViewer-DSQwk05R.js → PierreDiffViewer-Cwoewmiu.js} +2 -2
- package/dist/assets/{useAppFontEffects-DqOhrZWx.js → SessionSwitcherDropdown-DNjCJjzF.js} +97 -97
- package/dist/assets/{SettingsView-Bf4vWwVK.js → SettingsView-BtLvHlj4.js} +1 -1
- package/dist/assets/SettingsWindow-CPd7JmJs.js +1 -0
- package/dist/assets/{ToolOutputDialog-Brg2Humk.js → ToolOutputDialog-CFFC5eI-.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-yFq1DKSA.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-BELx71mz.js → VirtualizedFileDiff-CC5lTPJS.js} +1 -1
- package/dist/assets/collapsible-D_555Hw_.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-BcVuV0Ic.js +3 -0
- package/dist/assets/contextFileOpenGuard-BygvjHuE.js +1 -0
- package/dist/assets/index-C9CLY-is.js +1 -0
- package/dist/assets/{index-Dnby-sDS.js → index-DQr8-8RF.js} +2 -2
- package/dist/assets/index-DYrJXRkU.css +1 -0
- package/dist/assets/isDiffPlainText-Bher0UxW.js +1 -0
- package/dist/assets/isFilePlainText-EIViqOlI.js +1 -0
- package/dist/assets/main-1bIgjP48.js +2 -0
- package/dist/assets/main-JDtt2bQS.js +133 -0
- package/dist/assets/{markdownCore-BK98alzY.js → markdownCore-Bm4FxtK1.js} +2 -2
- package/dist/assets/miniChat-B7kKqKHH.js +2 -0
- package/dist/assets/mobile-DZPRce5z.js +2 -0
- package/dist/assets/renderElectronMiniChatApp-Dq0GdThJ.js +1 -0
- package/dist/assets/renderMobileApp-DlKnjObC.js +23 -0
- package/dist/assets/{runtimeSurface-DMXukysz.js → runtimeSurface-B6sKTjo7.js} +1 -1
- package/dist/assets/{useInlineCommentController-ruw8wb2Y.js → useInlineCommentController-CSR_Ju0a.js} +2 -2
- package/dist/assets/usePanelSlide-BkonU4LS.js +47 -0
- package/dist/assets/{useWindowTitle-qt23iibv.js → useWindowTitle-rt_8xbd9.js} +3 -3
- package/dist/assets/{vendor-codemirror-language-data-DVYP3hf_.js → vendor-codemirror-language-data-Be-zDX0u.js} +2 -2
- package/dist/assets/{web-components-P2py0R8j.js → web-components-DgFD1Jms.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/package-manager.js +44 -65
- package/server/lib/package-manager.test.js +27 -0
- package/server/lib/pi/routes.js +6 -0
- package/server/lib/pi/routes.test.js +32 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-daemon/session-daemon.js +11 -4
- package/server/lib/pi/session-daemon/session-daemon.test.js +24 -0
- package/dist/assets/CommitSection-DSFuOWuL.js +0 -1
- package/dist/assets/DiagramEditor-D6W6zeV7.js +0 -1
- package/dist/assets/DiagramView-r89Qi5ON.js +0 -1
- package/dist/assets/JsonTreeView-C6qt2uIj.js +0 -1
- package/dist/assets/PatchDiff-D6In_lUU.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-CvE7hsxG.js +0 -1
- package/dist/assets/SettingsWindow-B8IV35H4.js +0 -1
- package/dist/assets/ToolPartDiffPreview-rlz2ipa2.js +0 -8
- package/dist/assets/collapsible-QoPrpZP_.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-CInbUZiB.js +0 -3
- package/dist/assets/contextFileOpenGuard-BOtkNMZy.js +0 -1
- package/dist/assets/index-4sRd3SSM.js +0 -1
- package/dist/assets/index-NYG3k04a.css +0 -1
- package/dist/assets/isDiffPlainText-BquUayus.js +0 -1
- package/dist/assets/isFilePlainText-D4iUTBdr.js +0 -1
- package/dist/assets/main-Cp3YZZm1.js +0 -2
- package/dist/assets/main-CyshB9VI.js +0 -134
- package/dist/assets/miniChat-C_A4lnrT.js +0 -2
- package/dist/assets/mobile-2dXx6cUI.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-HL15h5xo.js +0 -1
- package/dist/assets/renderMobileApp-w6YFCJhq.js +0 -23
- package/dist/assets/runtimeEndpointReset-DiVqZFZB.js +0 -46
- package/dist/assets/useOpenInAppsStore-DVr2oGEm.js +0 -1
- /package/dist/assets/{runtimeEndpointReset-BV3KOtdA.css → usePanelSlide-BV3KOtdA.css} +0 -0
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-k3lX2PiV.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-Dnby-sDS.js","assets/vendor-zustand-CnsBKjP5.js","assets/index-NYG3k04a.css","assets/useAppFontEffects-DqOhrZWx.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DwfTg5wD.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-DMXukysz.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-BuDklWi8.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-Wdz6Qsow.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-pXtfpqbT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-CrbeaEAU.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-3xMyV7a2.js","assets/vendor-codemirror-lang-json-BTvAjwkJ.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-C4jEScp7.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-C1Svvdey.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-BloD9GN-.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-DVYP3hf_.js","assets/vendor-codemirror-lang-python-CR2g6ukK.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-Bzf12ODH.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-dWA7qvjr.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/PierreDiffViewer-DSQwk05R.js","assets/web-components-P2py0R8j.js","assets/computeVirtualFileMetrics-CInbUZiB.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-BELx71mz.js","assets/isDiffPlainText-BquUayus.js","assets/vendor-diff-C3JhlQdm.js","assets/runtimeEndpointReset-DiVqZFZB.js","assets/permissionStore-BRcQ9Jgt.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/useInlineCommentController-ruw8wb2Y.js","assets/collapsible-QoPrpZP_.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/contextFileOpenGuard-BOtkNMZy.js","assets/FilesView-C39IOFfs.js","assets/vendor-codemirror-search-BzyfPoRb.js","assets/vendor-replit-codemirror-vim-BUqe2Slv.js","assets/JsonTreeView-C6qt2uIj.js","assets/Virtualizer-BxW2CJGB.js","assets/isFilePlainText-D4iUTBdr.js","assets/DiagramEditor-D6W6zeV7.js","assets/vendor-react-drawio-Boqanm0j.js","assets/useOpenInAppsStore-DVr2oGEm.js","assets/GitView-CkztSaT7.js","assets/CommitSection-DSFuOWuL.js","assets/DiagramView-r89Qi5ON.js","assets/SettingsView-Bf4vWwVK.js","assets/vendor-qrcode-COsmt6jn.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/SettingsWindow-B8IV35H4.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{j as e,R as s,r as Le,e as Or}from"./vendor-react-DYyjh7Q0.js";import"./vendor-katex-CHD9BdDO.js";import{x as Wt,y as Rs,D as _r,O as Xn,z as Lr,A as Br,r as it,o as kn,u as z,B as Fr,C as Es,E as Wr,F as Ur,t as Ts,G as kt,H as Sn,e as Et,I as $r,J as zr,K as Hr,L as Vr,M as Is,n as rt,N as Kr,a as Ds,P as Gr,Q as Yr,R as Ms,S as Os,T as Xr,l as Jr,U as qr,v as Qr,q as Zr}from"./index-Dnby-sDS.js";import{_ as Qe}from"./vendor-vite-runtime-DD1OZmLC.js";import{I as C,f as ge,aw as ft,ax as gt,ay as xt,az as $e,aA as wt,aB as mt,t as ce,aC as Nn,K as $t,aD as zt,o as Ut,aE as Jn,T as He,y as Ve,z as Ke,aF as eo,aG as to,h as _s,m as Fe,p as no,x as so,b as An,aH as ro,aI as oo,aJ as ao,aK as io,aL as lo,aM as co,aN as uo,aO as ho,aP as po,aQ as en,aR as Nt,D as tn,C as nn,E as sn,G as rn,H as on,J as Ls,B as Ce,aS as mo,aT as Bs,aU as fo,aV as qn,a0 as qe,F as Pn,aW as go,L as Ht,M as Fs,aX as Ws,a1 as Qn,aY as xo,aZ as wo,g as bo,a_ as _t,a$ as yo,k as vo,b0 as jo,j as So,b1 as Ao,Z as ot,N as Us,b2 as Co,b3 as ko,b4 as No,b5 as Po,b6 as Ro,b7 as Rn,b8 as En,b9 as Tn,ba as Eo,P as $s,bb as To,R as zs,bc as Io,bd as Do,be as Mo,bf as Zn,bg as Lt,bh as Oo,c as _o,d as Lo,bi as Bo,r as fn,bj as Fo,bk as Wo,bl as Uo,bm as $o,bn as zo,bo as Ho,bp as Vo,bq as Mt,br as Ot,bs as Ko,bt as Go,bu as Yo,bv as Xo,ai as Jo,ah as qo,aj as Qo,af as Zo,ak as ea,al as ta,am as na,at as sa,au as ra,av as oa}from"./useAppFontEffects-DqOhrZWx.js";import{c as aa,d as es,T as ia,M as la,D as ca,e as da}from"./vendor-dnd-kit-core-GipZW2tY.js";import{a as ua,S as ha,v as pa,u as ma}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{u as Hs,S as fa,C as ga,W as Vs}from"./SessionSwitcherDropdown-CvE7hsxG.js";import{f as ts,g as Ne,n as xa,h as ns,t as st,i as wa,j as gn,k as ba,l as ya,s as va,m as ja,U as Sa,o as Aa,p as Ca,q as ka,v as Na,w as Pa,P as Ks,x as Ra,T as Gs,y as Ea,z as Ta,c as Ia,D as Da,e as Ma,C as ss,A as rs,S as os,b as Oa,d as _a,F as La}from"./runtimeEndpointReset-DiVqZFZB.js";import{u as ut}from"./useOpenInAppsStore-DVr2oGEm.js";import{u as Ba}from"./vendor-zustand-CnsBKjP5.js";import{v as Ys,g as Xs}from"./contextFileOpenGuard-BOtkNMZy.js";import{C as Fa}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{u as as,a as is,m as ls}from"./vendor-framer-motion-DJASDzNt.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-base-ui-DwfTg5wD.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-sVFnuruh.js";import"./vendor-floating-ui-dom-Bkw82kL9.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-B7OScDIw.js";import"./runtimeSurface-DMXukysz.js";import"./vendor-cmdk-BCEUzcHE.js";import"./vendor-radix-ui-react-dialog-jX3Dld8c.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-D1GnwnP9.js";import"./vendor-radix-ui-react-context-CM4yFQ2I.js";import"./vendor-radix-ui-react-id-BcxRjnbX.js";import"./vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js";import"./vendor-radix-ui-react-use-controllable-state-C_ecoh35.js";import"./vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js";import"./vendor-radix-ui-react-primitive-CfpW6_IT.js";import"./vendor-radix-ui-react-slot-BxUc3Pvz.js";import"./vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js";import"./vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js";import"./vendor-radix-ui-react-focus-scope-C2K7lNPv.js";import"./vendor-radix-ui-react-portal-xlJWBfDg.js";import"./vendor-radix-ui-react-presence-Btn-Dp7L.js";import"./vendor-radix-ui-react-focus-guards-D5MZ0nQs.js";import"./vendor-react-remove-scroll-CfeMe0DL.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-C9YRs2nU.js";import"./vendor-react-style-singleton-B1H4bWSG.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-C-AuTczP.js";import"./vendor-use-callback-ref-CJB0R85I.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BuDklWi8.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-Wdz6Qsow.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-pXtfpqbT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-CrbeaEAU.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-3xMyV7a2.js";import"./vendor-codemirror-lang-json-BTvAjwkJ.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-C4jEScp7.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-C1Svvdey.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BloD9GN-.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-DVYP3hf_.js";import"./vendor-codemirror-lang-python-CR2g6ukK.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-Bzf12ODH.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-sonner-dWA7qvjr.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-dnd-kit-accessibility-Cv52zwWT.js";import"./permissionStore-BRcQ9Jgt.js";import"./vendor-motion-dom-DJLgZh4Q.js";import"./vendor-motion-utils-BGh8QBgx.js";function Wa({className:t="h-5 w-5"}){return e.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${t}`,children:[e.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),e.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),e.jsx(C,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function cs({size:t,className:n,style:o,...r}){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:n,style:{width:typeof t=="number"?`${t}px`:t,height:typeof t=="number"?`${t}px`:t,...o},...r,children:e.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const Ua="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",$a="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",xn=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Ua:t.id==="terminal"?$a:void 0}),ds=({label:t,iconDataUrl:n,fallbackIconDataUrl:o})=>{const[r,a]=s.useState(!1),i=t.trim().slice(0,1).toUpperCase()||"?",p=n||o;return p&&!r?e.jsx("img",{src:p,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>a(!0)}):e.jsx("span",{className:ge("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},za=({directory:t,className:n})=>{const o=ut(d=>d.selectedAppId),r=ut(d=>d.availableApps),a=ut(d=>d.isCacheStale),i=ut(d=>d.isScanning),p=ut(d=>d.initialize),h=ut(d=>d.loadInstalledApps),m=ut(d=>d.selectApp);s.useEffect(()=>{p()},[p]);const f=Wt()&&Rs(),S=s.useMemo(()=>{const d=r.find(A=>A.id===o)??r.find(A=>A.id===_r)??r[0]??Xn[0];return xn(d||Xn[0])},[r,o]);if(!f||!t||r.length===0)return null;const x=async d=>{await Lr(t,d.id,d.appName)||await Br(t,d.appName)},b=async d=>{await m(d.id),await x(d)},k=async()=>{(await mt(t)).ok&&ce.success("Path copied to clipboard")};return e.jsxs("div",{className:ge("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",n),children:[e.jsx("button",{type:"button",onClick:()=>{x(S)},className:ge("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",i&&"animate-pulse"),"aria-label":`Open in ${S.label}`,children:e.jsx(ds,{label:S.label,iconDataUrl:S.iconDataUrl,fallbackIconDataUrl:S.fallbackIconDataUrl})}),e.jsxs(ft,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",className:ge("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:e.jsx(C,{name:"arrow-down-s",className:"h-4 w-4"})})}),e.jsxs(xt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[e.jsxs($e,{className:"flex items-center gap-2",onClick:()=>{k()},children:[e.jsx(C,{name:"file-copy",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),e.jsx(wt,{}),r.map(d=>{const A=xn(d);return e.jsxs($e,{className:"flex items-center gap-2",onClick:()=>{b(d)},children:[e.jsx(ds,{label:d.label,iconDataUrl:d.iconDataUrl,fallbackIconDataUrl:A.fallbackIconDataUrl}),e.jsx("span",{className:"typography-ui-label text-foreground",children:d.label}),S.id===d.id?e.jsx(C,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},d.id)}),a?e.jsxs($e,{className:"flex items-center gap-2",onClick:()=>{h(!0)},children:[e.jsx(C,{name:"refresh",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},Ha=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Va=["dev","start","preview","serve"];async function Ka(t,n,o){if(!t)return null;const r=Xa(n);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(o){const a=Ja(o);if(a){const i=await qa(t);return{command:`${i==="npm"?"npm run":i==="yarn"?"yarn":i==="pnpm"?"pnpm":i==="bun"?"bun run --shell=bun":"npm run"} ${a}`,label:`Start (${a})`}}}if(await Ga(t)){const a=await Ya(),i=typeof a=="number"&&Number.isFinite(a)&&a>0?a:8e3;return{command:`python3 -m http.server ${i}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${i}/`}}return null}async function Ga(t){const n=`${t}/index.html`,o=await Qt(n,t);return typeof o=="string"&&o.trim().length>0}async function Ya(){try{const t=await it("/api/system/free-port",{cache:"no-store"});if(!t.ok)return null;const n=await t.json().catch(()=>null),o=typeof n?.port=="number"?n.port:null;return o&&Number.isFinite(o)?o:null}catch{return null}}function Xa(t){for(const n of t){const o=`${n.name} ${n.command}`.toLowerCase();if(Va.some(a=>o.includes(a)))return n}return null}function Ja(t){for(const{pattern:n}of Ha)for(const o of Object.keys(t))if(n.test(o))return o;return null}async function qa(t){const n=await Qt(`${t}/package.json`,t);if(n)try{const r=JSON.parse(n),a=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(a.startsWith("bun@"))return"bun";if(a.startsWith("pnpm@"))return"pnpm";if(a.startsWith("yarn@"))return"yarn";if(a.startsWith("npm@"))return"npm"}catch{}const o=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,a]of o){const i=await Qt(`${t}/${r}`,t);if(typeof i=="string"&&i.trim().length>0)return a}return"npm"}async function Qt(t,n){if(n?.trim())try{const r=new URLSearchParams({path:t,directory:n,optional:"true"}),a=await it(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(a.ok)return a.text()}catch{}const o=kn()?.files;if(o?.readFile)try{const r=await o.readFile(t,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await it(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Qa(t){try{const n=await Qt(`${t}/package.json`,t);if(n==null)return null;const r=JSON.parse(n).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Za=(t,n,o)=>new Promise(r=>{let a=!1,i=null,p=null;const h=m=>{a||(a=!0,p&&clearTimeout(p),i?.close(),r(m))};i=t.connect(n,{onEvent:m=>{(m.type==="exit"||m.type==="snapshot"&&m.status==="exited")&&h(!0)},onError:(m,f)=>{f&&h(!0)}}),a?i.close():p=setTimeout(()=>h(!1),o)}),ei="\x1B",ti=new RegExp(`${ei}\\[[0-9;?]*[ -/]*[@-~]`,"g"),ni=/https?:\/\/[^\s<>'"`]+/gi,Xe="__pichamber_auto_discover_preview__",si=15e3,ri=t=>{let n="";for(let o=0;o<t.length;o+=1){const r=t.charCodeAt(o);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(n+=t[o])}return n},oi=t=>{const n=(t||"").trim();if(!n)return null;const o=/^https?:\/\//i.test(n)?n:`http://${n}`;try{const r=new URL(o);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},ai=t=>{const o=t.replace(ti,"").match(ni);if(!o||o.length===0)return null;const r=o.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const a=[];for(const i of r)try{const p=new URL(i);p.port&&p.port.length>0&&a.push({raw:i,parsed:p})}catch{}if(a.length>0){const i=p=>{const{parsed:h}=p,m=h.hostname.toLowerCase(),f=m==="localhost"||m==="127.0.0.1"||m==="0.0.0.0"||m==="::1",S=h.pathname||"/",x=S.split("/").filter(Boolean).length,b=S==="/"||S==="",k=!!(h.search||h.hash);let d=0;return f&&(d+=50),b&&(d+=30),d-=Math.min(x*5,20),k&&(d-=10),d};return a.sort((p,h)=>i(h)-i(p)),a[0]?.parsed.origin??a[0]?.raw??null}return r[0]??null},us=({projectRef:t,directory:n,className:o,compact:r=!1,allowMobile:a=!1})=>{const{currentTheme:i}=Nn(),{terminal:p}=$t(),{isMobile:h}=zt(),m=s.useMemo(()=>Wt(),[]),f=ts(u=>u.instances),S=ts(u=>u.load),x=z(u=>u.terminalShell),b=z(u=>u.terminalLoginShells.includes(u.terminalShell)),k=z(u=>u.setSettingsPage),d=z(u=>u.setSettingsDialogOpen),A=z(u=>u.setSettingsProjectsSelectedId),D=z(u=>u.openContextPreview),L=Ne(u=>u.ensureDirectory),H=Ne(u=>u.setTabLabel),X=Ne(u=>u.setTabIconKey),I=Ne(u=>u.setActiveTab),P=Ne(u=>u.setConnecting),w=Ne(u=>u.setTabSessionId),N=Ne(u=>u.setTabPreviewUrl),W=Ne(u=>u.projectActionRuns),y=Ne(u=>u.setProjectActionRun),Q=Ne(u=>u.updateProjectActionRunStatus),O=Ne(u=>u.removeProjectActionRun),[Y,J]=s.useState([]),[_,M]=s.useState(null),[K,ne]=s.useState(!1),ue=s.useRef({}),xe=s.useRef({}),q=s.useRef({}),le=s.useRef({}),pe=s.useRef(new Set),we=s.useRef(0),me=t?.id??null,Pe=t?.path??"",ve=s.useMemo(()=>me?{id:me,path:Pe}:null,[me,Pe]);s.useEffect(()=>{m&&S().catch(()=>{})},[m,S]);const Se=s.useCallback(async u=>{await Ut(u)},[]),fe=s.useCallback(async()=>{if(!ve)return;const u=we.current+1;we.current=u,ne(!0);try{const T=await Jn(ve);if(we.current!==u)return;const R=T.actions;J(R),M(V=>V===Xe||V&&R.some(l=>l.id===V)?V:null)}catch{if(we.current!==u)return}finally{we.current===u&&ne(!1)}},[ve]),Z=s.useMemo(()=>xa(n||ve?.path||""),[n,ve?.path]),Ee=s.useMemo(()=>_?Y.find(u=>u.id===_)??null:null,[Y,_]),U=s.useMemo(()=>({id:Xe,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),G=!h,ee=s.useMemo(()=>G?[U,...Y]:Y,[Y,U,G]);s.useEffect(()=>{fe()},[fe]),s.useEffect(()=>{if(typeof window>"u")return;const u=T=>{const R=T.detail;me&&(R?.projectId&&R.projectId!==me||fe())};return window.addEventListener(ns,u),()=>{window.removeEventListener(ns,u)}},[fe,me]),s.useEffect(()=>{_&&(_===Xe&&G||Y.some(u=>u.id===_)||M(null))},[Y,G,_]),s.useEffect(()=>{const u=()=>{const T=Ne.getState(),R=T.sessions,V=T.projectActionRuns;for(const[l,F]of Object.entries(V)){const se=R.get(F.directory)?.tabs.find(Te=>Te.id===F.tabId);if(!se||se.terminalSessionId!==F.sessionId){O(l);continue}const Ie=xe.current[l]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};xe.current[l]=Ie;const We=ee.find(Te=>Te.id===F.actionId),Ze=T.getBuffer(F.directory,F.tabId).chunks;if(!We||Ze.length===0)continue;const Ge=Ze.filter(Te=>Ie.lastSeenChunkId===null||Te.id>Ie.lastSeenChunkId);if(Ge.length===0)continue;const ze=Ge.map(Te=>Te.data).join(""),tt=`${Ie.tail}${ze}`,nt=!Ie.openedUrl&&We.autoOpenUrl===!0?ai(tt):null,De=Ge[Ge.length-1]?.id??Ie.lastSeenChunkId;if(Ie.lastSeenChunkId=De,Ie.tail=tt.slice(-512),nt)if(Ie.openedUrl=!0,Ie.openInPreview){const Te=V[l];Te&&(N(Te.directory,Te.tabId,nt,{locked:!1,autoOpened:!1}),Te.status==="waiting-for-preview"&&Q(l,"running"),window.clearTimeout(le.current[l]),delete le.current[l],D(Te.directory,nt))}else Se(nt),ce.success("Opened URL from action output");xe.current[l]=Ie}for(const l of Object.keys(xe.current))V[l]||(delete xe.current[l],window.clearTimeout(le.current[l]),delete le.current[l])};return u(),Ne.subscribe((T,R)=>{(T.sessions!==R.sessions||T.buffers!==R.buffers)&&u()})},[ee,D,Se,W,O,N,Q]);const ae=s.useCallback(async(u,T={})=>{if(!Z)throw new Error("No active directory");const R=st(Z,u.id);L(Z);const V=Ne.getState(),l=V.getDirectoryState(Z);let F=ue.current[R]||null;const oe=F?!!l?.tabs.some(We=>We.id===F):!1;(!F||!oe)&&(F=V.createTab(Z),ue.current[R]=F),H(Z,F,`Action: ${u.name}`),X(Z,F,u.icon||"play"),I(Z,F),T.revealTerminal!==!1&&z.getState().openContextPanelTab(Z,{mode:"terminal"});const Ie=Ne.getState().getDirectoryState(Z)?.tabs.find(We=>We.id===F);return{key:R,tabId:F,sessionId:Ie?.terminalSessionId??null}},[L,Z,I,X,H]),de=s.useCallback(async u=>{if(!a&&h)return;if(!Z){ce.error("No active directory for action");return}const T=st(Z,u.id),R=W[T];if(!(R&&R.status==="running")&&!pe.current.has(T)){pe.current.add(T);try{const V=u.id===Xe?await(async()=>{const[De,Te]=await Promise.all([Jn({id:ve?.id??"",path:Z}),Qa(Z)]),bt=await Ka(Z,De.actions,Te);if(!bt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Xe,name:"Auto-discover",command:bt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:bt.previewUrlHint||""}})():u,l=V.autoOpenUrl===!0&&(V.openUrl||"").trim().length>0,F=!l&&u.id!==Xe,{key:oe,tabId:se,sessionId:Ie}=await ae(V,{revealTerminal:F});let We=Ie;if(!We){P(Z,se,!0);try{We=(await p.createSession({cwd:Z,sessionId:se,shell:x,loginShell:b,themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground})).sessionId,w(Z,se,We)}finally{P(Z,se,!1)}}if(!We)throw new Error("Failed to create terminal session");q.current[oe]?.(),P(Z,se,!0);const Ze=p.connect(We,{onEvent:De=>{De.type==="snapshot"&&(Ne.getState().replaceBuffer(Z,se,De.data??"",De.sequence??0),Ne.getState().setConnecting(Z,se,!1)),De.type==="data"&&typeof De.data=="string"&&De.data.length>0&&Ne.getState().appendToBuffer(Z,se,De.data,De.sequence,De.replayData),De.type==="exit"&&(Ne.getState().setTabLifecycle(Z,se,"exited"),Ne.getState().setConnecting(Z,se,!1),Ne.getState().removeProjectActionRun(oe),delete xe.current[oe],q.current[oe]?.(),delete q.current[oe],window.clearTimeout(le.current[oe]),delete le.current[oe])},onError:(De,Te)=>{Ne.getState().setConnecting(Z,se,!1),Te&&(Ne.getState().setTabLifecycle(Z,se,"exited"),Ne.getState().setTabSessionId(Z,se,null),Ne.getState().removeProjectActionRun(oe))}});q.current[oe]=Ze.close;const Ge=V.autoOpenUrl===!0&&m&&(V.desktopOpenSshForward||"").trim().length>0,ze=V.autoOpenUrl?oi(V.openUrl):null,tt=V.autoOpenUrl&&m?wa(V.desktopOpenSshForward,f):null;y({key:oe,directory:Z,actionId:V.id,tabId:se,sessionId:We,status:V.id===Xe&&!ze?"waiting-for-preview":"running"}),window.clearTimeout(le.current[oe]),delete le.current[oe],V.id===Xe&&!ze&&(le.current[oe]=window.setTimeout(()=>{const De=Ne.getState(),Te=De.projectActionRuns[oe];De.updateProjectActionRunStatus(oe,"running"),Te&&(De.setActiveTab(Te.directory,Te.tabId),z.getState().openContextPanelTab(Te.directory,{mode:"terminal"})),delete le.current[oe]},si)),xe.current[oe]={lastSeenChunkId:null,openedUrl:!!tt||!!ze||l,tail:"",openInPreview:V.id===Xe};const nt=ri(V.command.trim().replace(/\r\n|\r/g,`
|
|
3
|
-
`));await p.sendInput(We,`${nt}\r`),tt?(N(Z,se,null,{locked:!0}),Se(tt),ce.success("Opened forwarded URL")):ze?(N(Z,se,ze,{locked:!0,autoOpened:!0}),D(Z,ze),ce.success("Opened action URL")):l?(N(Z,se,null,{locked:!0}),ce.error("Invalid custom URL format")):Ge?(N(Z,se,null,{locked:!0}),ce.error("Selected desktop SSH forward is unavailable")):N(Z,se,null,{locked:!1,autoOpened:!1})}catch(V){O(T),delete xe.current[T],q.current[T]?.(),delete q.current[T],window.clearTimeout(le.current[T]),delete le.current[T],ce.error(V instanceof Error?V.message:"Failed to run action")}finally{pe.current.delete(T)}}},[i.colors.surface.background,i.colors.syntax.base.foreground,i.metadata.variant,f,ae,a,h,m,Z,b,x,Se,D,W,O,P,y,N,w,ve?.id,p]),Ae=s.useCallback(async u=>{const T=st(Z,u.id),R=W[T];if(!R)return;Q(T,"stopping");const V=Za(p,R.sessionId,1e3);try{await p.sendInput(R.sessionId,"")}catch{}const l=await V;if(Ne.getState().getDirectoryState(R.directory)?.tabs.find(se=>se.id===R.tabId)?.terminalSessionId===R.sessionId&&!l){if(typeof p.forceKill=="function")try{await p.forceKill({sessionId:R.sessionId})}catch{}else try{await p.close(R.sessionId)}catch{}w(R.directory,R.tabId,null)}O(T),delete xe.current[T],q.current[T]?.(),delete q.current[T],window.clearTimeout(le.current[T]),delete le.current[T]},[Z,W,O,w,p,Q]),je=s.useCallback(()=>{const u=Ee??ee[0];if(!u)return;const T=st(Z,u.id),R=W[T];if(R?.status!=="stopping"){if(R){Ae(u);return}de(u)}},[ee,Z,de,W,Ee,Ae]),ke=s.useCallback((u,T=!1)=>{if(M(u.id),!T){de(u);return}const R=st(Z,u.id),V=W[R];if(V?.status!=="stopping"){if(V){Ae(u);return}de(u)}},[Z,de,W,Ae]),Be=s.useCallback(()=>{ve?.id&&(A(ve.id),k("projects"),d(!0))},[d,k,A,ve?.id]),Me=Ee??ee[0]??null,Oe=Me?W[st(Z,Me.id)]:null,E=Ne(u=>Oe?u.sessions.get(Oe.directory)?.tabs.find(T=>T.id===Oe.tabId)?.previewUrl??null:null);if(!a&&h||!ve||!Z)return null;const ie=Ee??ee[0]??null;if(!ie)return null;const he=ie.icon||"play",g=ie.id===Xe?"scan-2":gn[he]||"play",j=st(Z,ie.id),te=W[j],ye=te?.status==="stopping",_e=te?.status==="waiting-for-preview",v=!!(te&&E),B=()=>{!te||!E||D(te.directory,E)},be=ie.id===Xe;return r?e.jsxs("div",{className:"inline-flex items-center",children:[e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",disabled:K||ye,className:ge("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",o),onClick:je,"aria-label":te?`Stop ${ie.name}`:`Run ${ie.name}`,children:ye||_e?e.jsx(C,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):te?e.jsx(C,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):e.jsx(C,{name:g,className:"h-5 w-5"})})}),be?e.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),v?e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:B,children:e.jsx(C,{name:"global",className:"h-4 w-4"})})}),e.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,e.jsxs(ft,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:e.jsx(C,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),e.jsxs(xt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[e.jsxs($e,{className:"flex items-center gap-2",onClick:Be,children:[e.jsx(C,{name:"add",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),e.jsx(wt,{}),ee.map(u=>{const T=u.icon||"play",R=u.id===Xe?"scan-2":gn[T]||"play",V=st(Z,u.id),l=W[V],F=!!l,oe=l?.status==="stopping";return e.jsxs($e,{className:"flex items-center gap-2",onClick:()=>{ke(u,!0)},children:[e.jsx(C,{name:R,className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:u.name}),oe||l?.status==="waiting-for-preview"?e.jsx(C,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):F?e.jsx(C,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},u.id)})]})]})]}):e.jsxs("div",{className:ge("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",o),children:[e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:je,disabled:K||ye,className:ge("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":te?`Stop ${ie.name}`:`Run ${ie.name}`,children:e.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:ye||_e?e.jsx(C,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):te?e.jsx(C,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):e.jsx(C,{name:g,className:"h-4 w-4"})})})}),be?e.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),v?e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:B,className:ge(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:e.jsx(C,{name:"global",className:"h-4 w-4"})})}),e.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,e.jsxs(ft,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",className:ge(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:e.jsx(C,{name:"arrow-down-s",className:"h-4 w-4"})})}),e.jsxs(xt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[e.jsxs($e,{className:"flex items-center gap-2",onClick:Be,children:[e.jsx(C,{name:"add",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),e.jsx(wt,{}),ee.map(u=>{const T=u.icon||"play",R=u.id===Xe?"scan-2":gn[T]||"play",V=st(Z,u.id),l=W[V],F=!!l,oe=l?.status==="stopping";return e.jsxs($e,{className:"flex items-center gap-2",onClick:()=>{ke(u,!0)},children:[e.jsx(C,{name:R,className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:u.name}),oe||l?.status==="waiting-for-preview"?e.jsx(C,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):F?e.jsx(C,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},u.id)})]})]})]})},an="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",ii="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",li=s.memo(function({visible:n=!0,title:o,ariaLabel:r,onClick:a,className:i,Icon:p,iconClassName:h,pressed:m=!1}){return n?e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:a,"aria-label":r,"aria-pressed":m,className:ge(i??an,m&&"bg-interactive-selection text-interactive-selection-foreground"),children:e.jsx(C,{name:p,className:h??"h-[18px] w-[18px]"})})}),e.jsx(Ke,{children:e.jsx("p",{children:o})})]}):null}),ci=s.memo(function({isMobile:n,githubAuthStatus:o,githubAccounts:r,githubAvatarUrl:a,githubLogin:i,isSwitchingGitHubAccount:p,handleGitHubAccountSwitch:h}){return!o?.connected||n?null:r.length>1?e.jsxs(ft,{children:[e.jsx(gt,{asChild:!0,children:e.jsx("button",{type:"button",className:ge(an,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:i?`GitHub: ${i}`:"GitHub connected",disabled:p,children:a?e.jsx("img",{src:a,alt:i?`${i} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(C,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),e.jsxs(xt,{align:"end",className:"w-64",children:[e.jsx(eo,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),e.jsx(wt,{}),r.map(m=>{const f=m.user,S=!!m.current,x=m.source==="gh-cli"?"CLI":"OAuth";return e.jsxs($e,{className:"gap-2",disabled:p,onSelect:()=>{S||h(m.id)},children:[f?.avatarUrl?e.jsx("img",{src:f.avatarUrl,alt:f.login?`${f.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:e.jsx(C,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:f?.name?.trim()||f?.login||"GitHub"}),f?.login?e.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:f.login}),e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{children:x})]}):null]}),S?e.jsx(C,{name:"check",className:"h-4 w-4 text-primary"}):null]},m.id)})]})]}):e.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:i?`GitHub: ${i}`:"GitHub connected",children:a?e.jsx("img",{src:a,alt:i?`${i} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(C,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),di=s.memo(function({isDesktopApp:n,currentInstanceLabel:o,compactCurrentInstanceLabel:r,currentInstanceIsLocal:a,isDesktopServicesOpen:i,setIsDesktopServicesOpen:p,refreshCurrentInstanceLabel:h,shortcutLabel:m,remoteUpdateInfo:f,remoteUpdateChecking:S,remoteUpdateError:x,onOpenRemoteUpdate:b}){return e.jsxs(ft,{open:i,onOpenChange:k=>{p(k),k&&h()},children:[e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx(gt,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":n?`Open instance, usage and MCP (current: ${o})`:"Open services, usage and MCP",className:ge(an,n?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[e.jsx(C,{name:"server",className:"h-[18px] w-[18px]"}),n?e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),e.jsx(Ke,{children:e.jsx("p",{children:`Current instance: ${o} (${m("toggle_services_menu")})`})})]}),e.jsx(xt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:n?e.jsxs("div",{children:[a?null:e.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:S?"Looking for updates...":x||"This instance is up to date."})]}),f?.available?e.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:b,children:"Update"}):null]})}),e.jsx(to,{embedded:!0,open:i,onOpenChange:()=>{},onHostSwitched:()=>p(!1)})]}):null})]})}),ui=(t,n)=>t===n?!0:!t||!n?!1:t.totalTokens===n.totalTokens&&t.percentage===n.percentage&&t.contextLimit===n.contextLimit&&(t.outputLimit??0)===(n.outputLimit??0)&&(t.normalizedOutput??0)===(n.normalizedOutput??0)&&t.thresholdLimit===n.thresholdLimit&&(t.lastMessageId??"")===(n.lastMessageId??""),hi=t=>{const n=t.trim();if(!n)return"";const o=n.split(/\s+/).filter(Boolean);if(o.length>=2){const r=o[0],a=o[1].slice(0,3),i=`${r} ${a}`.trim();return o.length>2||i.length<n.length?`${i}...`:i}return n.length>12?`${n.slice(0,9).trimEnd()}...`:n},ht=t=>{if(!t)return"";const n=t.replace(/\\/g,"/");return n==="/"?"/":n.replace(/\/+$/,"")},hs=t=>!t?.isOpen||!Array.isArray(t.tabs)||t.tabs.length===0?null:(t.tabs.find(o=>o.id===t.activeTabId)??t.tabs[t.tabs.length-1])?.mode??null,ps=({onToggleLeftDrawer:t,onToggleRightDrawer:n,leftDrawerOpen:o,rightDrawerOpen:r})=>{Fr("ui.header.render");const a=z(c=>c.setSessionSwitcherOpen),i=z(c=>c.toggleSidebar),p=z(c=>c.isSidebarOpen),h=z(c=>c.openContextOverview),m=z(c=>c.closeContextPanel),f=z(c=>c.activeMainTab),S=z(c=>c.setActiveMainTab),x=z(c=>c.shortcutOverrides);z(c=>c.timeFormatPreference);const b=_s(c=>c.getCurrentModel);$t();const k=Fe(c=>c.getContextUsage),d=Fe(c=>!!c.newSessionDraft?.open),A=Fe(c=>c.currentSessionId),D=mo(),L=no(A??""),H=so(A),X=s.useMemo(()=>{if(!H)return null;const c=H;return{title:H.title??null,directory:c.directory??null,created:H.time?.created??null,slug:c.slug??null,shareUrl:H.share?.url??null,parentId:H.parentID??null}},[H]),I=An(Ba(c=>{if(!c.activeProjectId)return null;const $=c.projects.find(re=>re.id===c.activeProjectId);return $?{id:$.id,path:$.path,label:$.label}:null})),P=s.useMemo(()=>{if(!I)return null;const c=I.label?.trim();if(c)return c;const $=I.path.split(/[\\/]/).filter(Boolean);return $[$.length-1]??null},[I]),{isMobile:w}=zt(),N=null,W=s.useRef(null),[y,Q]=s.useState(()=>typeof window>"u"?!1:Wt()),O=s.useMemo(()=>Es(),[]),Y=ro(),[J,_]=s.useState(!1),M=s.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:K,side:ne}=Hs(),ue=s.useMemo(()=>{if(typeof window>"u")return null;const c=window.__PICHAMBER_MACOS_MAJOR__;if(typeof c=="number"&&Number.isFinite(c)&&c>0)return c;if(typeof navigator>"u")return null;const $=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!$)return null;const re=Number.parseInt($[1],10),Re=Number.parseInt($[2],10);return Number.isNaN(re)?null:re===10?Re:re},[]);Le.useEffect(()=>{typeof window>"u"||Q(Wt())},[]);const xe=b(),q=xe&&typeof xe.limit=="object"&&xe.limit!==null?xe.limit:null,le=q&&typeof q.context=="number"?q.context:0,pe=q&&typeof q.output=="number"?q.output:0,we=k(le,pe),[me,Pe]=s.useState(null),ve=!A||D;Le.useEffect(()=>{if(!A){Pe(c=>c===null?c:null);return}if(we&&we.totalTokens>0){Pe(c=>ui(c,we)?c:we);return}Pe(c=>c===null?c:null)},[we,A,ve]);const Se=z(c=>c.isSessionSwitcherOpen),fe=null,Z=null,Ee=[],[U,G]=s.useState(!1),[ee,ae]=s.useState(!1),[de,Ae]=s.useState("Local"),[je,ke]=s.useState(!0),[Be,Me]=s.useState(!1),[Oe,E]=s.useState(null),[ie,he]=s.useState(!1),[g,j]=s.useState(null),te=s.useMemo(()=>hi(de),[de]),ye=f==="chat"&&!!me&&me.totalTokens>0,_e=me&&me.contextLimit>0?Math.min(999,me.totalTokens/me.contextLimit*100):0,v=s.useCallback(async()=>{if(!(typeof window>"u"||!y))try{if(Rs()){Ae("Local"),ke(!0);return}ke(!1);const c=await Wr(),$=oo(),re=ao([io($),...c.hosts]);if(re.id===lo){Ae("Local"),ke(!0);return}Ae(Ur(re.label.trim()||"Instance"))}catch{Ae("Local"),ke(!0)}},[y]);Le.useEffect(()=>(v(),Ts(()=>{v()})),[v]);const B=s.useCallback(async()=>{if(je){E(null),j(null);return}he(!0),j(null);try{const c=new URLSearchParams({appType:"web",instanceMode:"remote",reportUsage:"false"}),$=await it(`/api/pi/update-check?${c.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!$.ok)throw new Error(`Server responded with ${$.status}`);const re=await $.json();E({available:re.available??!1,version:re.version,currentVersion:re.currentVersion??"unknown",body:re.body,nextSuggestedCheckInSec:typeof re.nextSuggestedCheckInSec=="number"?re.nextSuggestedCheckInSec:void 0,packageManager:re.packageManager,updateCommand:re.updateCommand})}catch(c){E(null),j(c instanceof Error?c.message:"Failed to check remote instance updates")}finally{he(!1)}},[je]);s.useEffect(()=>{E(null),j(null),Me(!1)},[je,de]),s.useEffect(()=>{if(!y||je)return;const c=3e3,$=3600*1e3;let re=!1,Re=null;const At=at=>{Re=window.setTimeout(()=>{if(re||typeof document<"u"&&document.visibilityState!=="visible"){At($);return}B().finally(()=>{re||At($)})},at)};return At(c),()=>{re=!0,Re!==null&&window.clearTimeout(Re)}},[B,je,de,y]);const be=s.useCallback(()=>{if(Oe?.available){Me(!0);return}B()},[B,Oe?.available]),u=A?X??null:null,T=s.useRef(null),[R,V]=s.useState(0);s.useEffect(()=>{if(!A){T.current&&(T.current=null,V(Re=>Re+1));return}if(u){T.current={sessionId:A,session:u,expiresAt:Date.now()+2e3};return}const c=T.current;if(!c||c.sessionId!==A)return;const $=c.expiresAt-Date.now();if($<=0){T.current=null,V(Re=>Re+1);return}const re=window.setTimeout(()=>{T.current?.sessionId===A&&(T.current=null),V(Re=>Re+1)},$);return()=>{window.clearTimeout(re)}},[A,u]);const l=(()=>{if(u)return u;if(!A)return null;const c=T.current;return c&&c.sessionId===A&&c.expiresAt>Date.now()?c.session:null})(),F=s.useMemo(()=>{const c=typeof l?.directory=="string"?l.directory:"";return ht(c||"")},[l?.directory]),oe=Fe(c=>c.newSessionDraft?.open?ht(c.newSessionDraft.directoryOverride??""):""),se=s.useMemo(()=>F||oe,[oe,F]),Ie=z(s.useCallback(c=>{const $=ht(se||"");return $?hs(c.contextPanelByDirectory[$]):null},[se])),Ze=co(se||null),Ge=!!(P||Ze),ze=s.useMemo(()=>{if(!A)return P??"PiChamber";const c=l?.title?.trim();return c&&c.length>0?c:"Untitled Session"},[P,l?.title,A]),tt=Bs(),nt=uo(),De=Fe(c=>c.updateSessionTitle),Te=Fe(c=>c.shareSession),bt=Fe(c=>c.unshareSession),Ln=Fe(c=>c.archiveSessions),Bn=Fe(c=>c.deleteSessions),[Vt,Tt]=s.useState(!1),[dr,Fn]=s.useState(!1),Kt=s.useRef(!1),[ln,cn]=s.useState(""),[lt,yt]=s.useState(null),Wn=s.useRef(null);s.useEffect(()=>{Kt.current=!1,Fn(!1),Tt(!1),cn(""),yt(null)},[A]);const ur=s.useCallback(()=>{A&&(cn(l?.title?.trim()||ze),Tt(!0))},[l?.title,A,ze]),dn=s.useCallback(async()=>{if(!A)return;const c=ln.trim();c&&c!==l?.title?.trim()&&await De(A,c),Tt(!1)},[l?.title,A,ln,De]);s.useEffect(()=>{if(!Vt)return;const c=$=>{const re=$.target;(!re||!Wn.current?.contains(re))&&dn()};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[Vt,dn]);const hr=s.useCallback(()=>{A&&mt(A).then(c=>{ce[c.ok?"success":"error"](c.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ce.error("Failed to copy session ID"))},[A]),pr=s.useCallback(async()=>{if(!A)return;const c=await Te(A),$=c?.share?.url??c?.url;if($){const re=await mt($);ce[re.ok?"success":"warning"]("Session shared",{description:re.ok?"Share link copied to clipboard.":"Failed to copy URL"});return}ce.error("Unable to share session")},[A,Te]),mr=s.useCallback(()=>{const c=l?.shareUrl;c&&mt(c).then($=>{ce[$.ok?"success":"error"]($.ok?"Copied":"Failed to copy URL")}).catch(()=>ce.error("Failed to copy URL"))},[l?.shareUrl]),fr=s.useCallback(async()=>{if(!A)return;const c=await bt(A);ce[c?"success":"error"](c?"Session unshared":"Unable to unshare session")},[A,bt]),gr=s.useCallback(async()=>{if(!A||!se){ce.error("Nothing to export");return}try{await nt.syncSession(A)}catch{ce.error("Failed to load the complete session history");return}const c=ho(tt.getState()).list;if(c.length===0){ce.error("Nothing to export");return}const $=ba(c,l?.title??null),re=ya(l?.title??null);await va($,re)||ja($,re),ce.success("Session exported")},[l?.title,A,tt,se,nt]);L?.type==="busy"||L?.type;const xr=s.useCallback(async()=>{if(!A||!lt)return;const c=po(),$=[A];for(let at=0;at<$.length;at+=1){const mn=$[at];for(const dt of c)dt.parentID===mn&&!$.includes(dt.id)&&$.push(dt.id)}const re=lt;if(yt(null),(re==="archive"?await Ln($):await Bn($)).failedIds.length>0){ce.error(re==="archive"?"Failed to archive session":"Failed to delete session");return}ce.success(re==="archive"?"Session archived":"Session deleted")},[Ln,A,Bn,lt]),Un=z(c=>c.isArchivePageOpen),Gt=s.useMemo(()=>Un?{title:"Archive",subtitle:null}:null,[Un]),ct=s.useMemo(()=>ht(se||I?.path||""),[I?.path,se]),vt=s.useMemo(()=>I?{id:I.id,path:I.path}:null,[I]),$n=s.useRef(null);s.useEffect(()=>{!vt||!ct||($n.current={projectRef:vt,directory:ct})},[ct,vt]);const jt=s.useMemo(()=>vt&&ct?{projectRef:vt,directory:ct}:$n.current,[ct,vt]),wr=s.useCallback(async c=>{},[]),It=s.useCallback(()=>{if(typeof document>"u")return;const c=document.activeElement;if(!c)return;const $=c.tagName;($==="INPUT"||$==="TEXTAREA"||$==="SELECT"||c.isContentEditable)&&c.blur()},[]),br=s.useCallback(()=>{if(w){It(),a(!Se);return}i()},[It,w,Se,a,i]),zn=s.useCallback(()=>{kt("desktop_open_draft_mini_chat_window",{directory:ht(se||I?.path||""),projectId:I?.id??null,apiBaseUrl:Et(),clientToken:Sn()}).catch(c=>{console.warn("[header] failed to open draft mini chat window",c)})},[I?.id,I?.path,se]),yr=s.useCallback(()=>{if(d){zn();return}A&&kt("desktop_open_session_mini_chat_window",{sessionId:A,directory:ht(se||I?.path||""),apiBaseUrl:Et(),clientToken:Sn()}).catch(c=>{console.warn("[header] failed to open session mini chat window",c)})},[I?.path,A,zn,d,se]),vr=s.useCallback(()=>{const c=ht(se||"");if(!c)return;const $=z.getState().contextPanelByDirectory[c];if(hs($)==="context"){m(c);return}h(c)},[m,h,se]),jr=Ie==="context",Hn=an,un=ii,hn=s.useMemo(()=>o?"sessions":r?"git":f,[f,o,r]),pn=s.useCallback(()=>{o&&t&&t(),r&&n&&n(),!t&&Se&&a(!1)},[Se,o,t,n,r,a]),Sr=s.useCallback(()=>{t?.()},[t]),Ar=s.useCallback(()=>{n?.()},[n]),Vn=s.useMemo(()=>y&&M&&!J?"5.5rem":Y?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!y||K?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[y,J,M,Y,K]);Le.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Vn)},[Vn]);const Cr=p?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",kr=p?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";Le.useEffect(()=>{if(!y||!M){_(!1);return}let c=!1;const $=async()=>{try{const Re=await kt("desktop_is_window_fullscreen");c||_(Re===!0)}catch{c||_(!1)}},re=()=>{$()};return $(),window.addEventListener("pichamber:window-resized",re),()=>{c=!0,window.removeEventListener("pichamber:window-resized",re)}},[y,M]);const Kn=s.useMemo(()=>!y||!M||ue===null?"":ue>=26?"h-12":ue<=15?"h-14":"",[y,M,ue]),Nr=s.useMemo(()=>{if(!(y&&!K))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[y,K]),Dt=s.useCallback(()=>{if(typeof document>"u")return;const c=W.current?.getBoundingClientRect().height;c&&document.documentElement.style.setProperty("--oc-header-height",`${c}px`)},[]);Le.useEffect(()=>{if(typeof window>"u")return;Dt();const c=W.current;if(!c||typeof ResizeObserver>"u")return()=>{};let $=0;const re=()=>{$||($=requestAnimationFrame(()=>{$=0,Dt()}))},Re=new ResizeObserver(re);return Re.observe(c),window.addEventListener("resize",re),window.addEventListener("orientationchange",re),()=>{$&&cancelAnimationFrame($),Re.disconnect(),window.removeEventListener("resize",re),window.removeEventListener("orientationchange",re)}},[Dt]),Le.useEffect(()=>{Dt()},[Dt,w,Kn]);const Pr=s.useCallback(async c=>{const $=c.target;$.closest(".app-region-no-drag")||$.closest("button, a, input, select, textarea")||c.button===0&&y&&await $r()},[y]),St=s.useMemo(()=>w?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[w]),Rr=s.useCallback(c=>en(Nt(c,x)),[x]);Le.useEffect(()=>{!w&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&S("chat")},[f,w,S]);const Gn=s.useMemo(()=>{const c=[];return y&&c.push({value:"instance",label:"Instance",icon:e.jsx(C,{name:"server",className:"h-3.5 w-3.5"})}),c},[y]);Le.useEffect(()=>{const c=$=>{if(fo($)&&!$.shiftKey&&!$.altKey){const re=parseInt($.key,10);re>=1&&re<=St.length&&($.preventDefault(),w&&(It(),pn()),S(St[re-1].id))}};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[It,pn,w,S,St]),Le.useEffect(()=>{const c=$=>{const re=Nt("toggle_services_menu",x);if(qn($,re)){$.preventDefault(),ee?ae(!1):(ae(!0),v());return}const Re=Nt("cycle_services_tab",x);if(qn($,Re)){if($.preventDefault(),Gn.length===0)return;ae(!0),v();return}};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[x,ee,Gn,v]);const Er=c=>{const $=f===c.id,re=c.icon==="diff",Re=re?null:c.icon,At=c.id==="chat",at=dt=>re?e.jsx(cs,{size:dt}):Re?e.jsx(C,{name:Re,className:`h-${dt/4} w-${dt/4}`}):null,mn=e.jsxs("button",{type:"button",onClick:()=>S(c.id),className:ge("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",$?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",At&&!w&&"min-w-[100px] justify-center"),"aria-label":c.label,"aria-selected":$,role:"tab",children:[w?at(20):e.jsxs(e.Fragment,{children:[at(16),e.jsx("span",{className:"header-tab-label",children:c.label})]}),c.badge!==void 0&&c.badge>0&&e.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:c.badge})]});return e.jsx(s.Fragment,{children:mn},c.id)},Tr=e.jsxs(e.Fragment,{children:[e.jsx(za,{directory:ct,className:"mr-1"}),y?e.jsx(di,{isDesktopApp:y,currentInstanceLabel:de,compactCurrentInstanceLabel:te,currentInstanceIsLocal:je,isDesktopServicesOpen:ee,setIsDesktopServicesOpen:ae,refreshCurrentInstanceLabel:v,shortcutLabel:Rr,remoteUpdateInfo:Oe,remoteUpdateChecking:ie,remoteUpdateError:g,onOpenRemoteUpdate:be}):null,e.jsx(ci,{isMobile:w,githubAuthStatus:N,githubAccounts:Ee,githubAvatarUrl:fe,githubLogin:Z,isSwitchingGitHubAccount:U,handleGitHubAccountSwitch:wr})]}),Yn=O&&(d||!!A),Ir=()=>e.jsxs("div",{onMouseDown:Pr,className:ge("app-region-drag relative flex h-12 select-none items-center pr-3",Kn),style:Nr,role:"tablist","aria-label":"Main navigation",children:[e.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:Cr}}),e.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:kr}}),e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Gt?e.jsxs("div",{className:"mr-3 flex min-w-0 flex-col items-start px-1 py-0.5 -my-0.5 text-left",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Gt.title}),Gt.subtitle?e.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:Gt.subtitle}):null]}):e.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[p?null:e.jsx(fa,{align:"start",children:e.jsx("button",{type:"button",className:Hn,"aria-label":"Open session switcher",children:e.jsx(C,{name:"history",className:"h-[18px] w-[18px]"})})}),e.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[Vt?e.jsxs("form",{ref:Wn,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:c=>{c.preventDefault(),dn()},children:[e.jsx("input",{value:ln,onChange:c=>cn(c.target.value),autoFocus:!0,onKeyDown:c=>{c.stopPropagation(),c.key==="Escape"&&Tt(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(C,{name:"check",className:"size-4"})}),e.jsx("button",{type:"button",onClick:()=>Tt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(C,{name:"close",className:"size-4"})})]}):e.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:d?"New session":ze}),Ge?e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[P?e.jsx("span",{className:"truncate",children:P}):null,Ze?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(C,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:Ze})]}):null]}):null]}),e.jsx("div",{className:ge("flex h-[18px] shrink-0 items-center justify-center",Ge?"self-start":"self-center"),children:A&&!d&&!Vt?e.jsxs(ft,{open:dr,onOpenChange:Fn,onOpenChangeComplete:c=>{!c&&Kt.current&&(Kt.current=!1,ur())},children:[e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:e.jsx(C,{name:"more",className:"size-4"})})}),e.jsxs(xt,{align:"end",className:"min-w-[190px]",children:[e.jsxs($e,{onClick:()=>{Kt.current=!0},children:[e.jsx(C,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),e.jsxs($e,{onClick:hr,children:[e.jsx(C,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),e.jsx(wt,{}),l?.shareUrl?e.jsxs(e.Fragment,{children:[e.jsxs($e,{onClick:mr,children:[e.jsx(C,{name:"file-copy",className:"mr-2 size-4"}),"Copy link"]}),e.jsxs($e,{onClick:()=>{fr()},children:[e.jsx(C,{name:"link-unlink-m",className:"mr-2 size-4"}),"Unshare"]})]}):e.jsxs($e,{onClick:()=>{pr()},children:[e.jsx(C,{name:"share-2",className:"mr-2 size-4"}),"Share"]}),e.jsxs($e,{onClick:()=>{gr()},children:[e.jsx(C,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),e.jsx(wt,{}),e.jsxs($e,{onClick:()=>yt("archive"),children:[e.jsx(C,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),e.jsxs($e,{className:"text-destructive focus:text-destructive",onClick:()=>yt("delete"),children:[e.jsx(C,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),St.length>0&&e.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:St.map(c=>Er(c))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[jt?e.jsx(us,{projectRef:jt.projectRef,directory:jt.directory,className:"mr-1"}):null,ye&&me?e.jsx(ga,{totalTokens:me.totalTokens,percentage:_e,colorPercentage:me.percentage,contextLimit:me.contextLimit,outputLimit:me.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:vr,pressed:jr,className:Yn?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,e.jsx(li,{visible:Yn,title:d?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:d?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:yr,className:ge(Hn,"mr-1"),Icon:"picture-in-picture-2"}),Tr,e.jsx(Vs,{visible:K&&ne==="right",position:"right"})]})]})]}),Dr=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t?e.jsx("button",{type:"button",onClick:Sr,className:ge(un,hn==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":o?"Close sessions":"Open sessions",children:e.jsx(C,{name:"layout-left",className:"h-5 w-5"})}):Se?e.jsx("button",{type:"button",onClick:()=>a(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:e.jsx(C,{name:"arrow-left-s",className:"h-5 w-5"})}):e.jsx("button",{type:"button",onClick:br,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:e.jsx(C,{name:"play-list-add",className:"h-5 w-5"})}),!t&&Se&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!Se||!!t)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:e.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain",children:e.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:e.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:St.map(c=>{const $=f===c.id,re=c.icon==="diff",Re=re?null:c.icon;return e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{w&&(It(),pn()),S(c.id)},"aria-label":c.label,"aria-selected":$,role:"tab",className:ge(un,"relative rounded-lg",hn===c.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[re?e.jsx(cs,{className:"h-5 w-5"}):Re?e.jsx(C,{name:Re,className:"h-5 w-5"}):null,c.badge!==void 0&&c.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:c.badge}),c.showDot&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),e.jsx(Ke,{children:e.jsx("p",{children:c.label})})]},c.id)})})})})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[jt&&e.jsx(us,{projectRef:jt.projectRef,directory:jt.directory,compact:!0,allowMobile:!0,className:"h-9"}),n?e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:Ar,className:ge(un,"relative",hn==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:e.jsx(C,{name:"layout-right",className:"h-5 w-5"})})}),e.jsx(Ke,{children:e.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Mr=ge("header-safe-area relative z-10 bg-background",w&&"border-b border-border/50");return e.jsxs(e.Fragment,{children:[e.jsx("header",{ref:W,className:Mr,style:{"--padding-scale":"1"},children:w?Dr():Ir()}),e.jsx(tn,{open:lt!==null,onOpenChange:c=>{c||yt(null)},children:e.jsxs(nn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[e.jsxs(sn,{children:[e.jsx(rn,{children:lt==="delete"?"Delete session?":"Archive session?"}),e.jsx(on,{children:lt==="delete"?`\\"${ze}\\" will be permanently deleted.`:`\\"${ze}\\" will be archived.`})]}),e.jsxs(Ls,{children:[e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>yt(null),children:"Cancel"}),e.jsx(Ce,{variant:"destructive",size:"sm",onClick:()=>{xr()},children:lt==="delete"?"Delete":"Archive"})]})]})}),e.jsx(Sa,{open:Be,onOpenChange:Me,info:Oe,downloading:!1,downloaded:!1,progress:null,error:g,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},ms=280,fs=280,gs=500,pi=({isOpen:t,isMobile:n,children:o,className:r,topBar:a})=>{const i=z(w=>w.sidebarWidth),p=z(w=>w.setSidebarWidth),[h,m]=s.useState(!1),f=s.useRef(0),S=s.useRef(i||ms),x=s.useRef(null),b=s.useRef(null),k=s.useRef(null),d=s.useCallback(w=>Math.min(gs,Math.max(fs,w)),[]),A=s.useCallback(w=>{const N=k.current;N&&(N.style.width=`${w}px`,N.style.minWidth=`${w}px`,N.style.maxWidth=`${w}px`,N.style.setProperty("--oc-left-sidebar-width",`${w}px`))},[]);if(s.useEffect(()=>{n&&h&&m(!1)},[n,h]),s.useEffect(()=>{h||(x.current=null,b.current=null)},[h]),n)return null;const D=Math.min(gs,Math.max(fs,i||ms)),L=t?D:0,H=w=>{if(t){try{w.currentTarget.setPointerCapture(w.pointerId)}catch{}b.current=w.pointerId,m(!0),f.current=w.clientX,S.current=L,x.current=L,A(L),w.preventDefault()}},X=w=>{if(n||!h||b.current!==w.pointerId)return;const N=w.clientX-f.current,W=d(S.current+N);x.current!==W&&(x.current=W,A(W))},I=w=>{if(b.current!==w.pointerId||n)return;try{w.currentTarget.releasePointerCapture(w.pointerId)}catch{}const N=d(x.current??L);b.current=null,x.current=null,m(!1),p(N)},P=h?x.current??L:L;return e.jsxs("aside",{ref:k,className:ge("relative flex h-full overflow-hidden border-r border-border will-change-[width] motion-reduce:transition-none","bg-sidebar",!t&&"border-r-0",r),style:{width:`${P}px`,minWidth:`${P}px`,maxWidth:`${P}px`,"--oc-left-sidebar-width":`${h?P:D}px`,overflowX:"clip",transitionProperty:h?"none":"width, min-width, max-width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t||L===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:ge("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",h&&"bg-[var(--interactive-border)]"),onPointerDown:H,onPointerMove:X,onPointerUp:I,onPointerCancel:I,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:ge("relative z-10 flex h-full shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",h&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),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(qe,{children:o})})]})]})},xs="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",mi=()=>{const t=z(k=>k.isSidebarOpen),n=z(k=>k.toggleSidebar),o=z(k=>k.shortcutOverrides),r=s.useRef(null),a=s.useRef(null),i=en(Nt("toggle_sidebar",o)),{usesFramelessChrome:p,side:h}=Hs(),m=!t,f=p&&h==="left",S=p,x=m||f||S,b=s.useCallback(()=>{kt("desktop_show_app_menu").catch(k=>{console.warn("[titlebar] failed to open app menu",k)})},[]);return s.useEffect(()=>{if(typeof document>"u")return;const k=X=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(X)}px`)},d=X=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(X)}px`)};if(!x){k(0),d(0);return}const A=a.current,D=r.current;if(!A||!D){k(0),d(0);return}const L=()=>{const X=Math.max(A.getBoundingClientRect().width,A.scrollWidth);k(X),d(D.getBoundingClientRect().width)};if(L(),typeof ResizeObserver>"u")return;const H=new ResizeObserver(L);return H.observe(A),H.observe(D),()=>{H.disconnect()}},[x,m,f,S]),x?e.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 top-0 z-30 flex select-none items-center pr-2",style:{height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:e.jsxs("div",{ref:a,className:"flex items-center gap-2",children:[f?e.jsx(Vs,{visible:!0,position:"left"}):null,S?e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:ge(xs,"shrink-0"),children:e.jsx(C,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),e.jsx(Ke,{children:e.jsx("p",{children:"PiChamber menu"})})]}):null,m?e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open sessions",className:ge(xs,"shrink-0"),children:e.jsx(C,{name:"layout-left",className:"h-[18px] w-[18px]"})})}),e.jsx(Ke,{children:e.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},fi=t=>t.slice().sort((n,o)=>n.type!==o.type?n.type==="directory"?-1:1:n.name.localeCompare(o.name)),Ue=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),o=n.startsWith("//");let r=n.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),o&&!r.startsWith("//")&&(r=`/${r}`),r===""?n.startsWith("/")?"/":"":r},Js=(t,n)=>{const o=Ue(n),r=Ue(t).replace(/\/+$/,"");return o===r?".":!r||!o.startsWith(`${r}/`)?o:o.slice(r.length+1)},gi=t=>t.startsWith("/")||t.startsWith("//")||/^[A-Za-z]:\//.test(t),xi=new Set(["node_modules"]),wi=t=>xi.has(t),bi=t=>{const n=Ue(t);return n==="node_modules"||n.endsWith("/node_modules")||n.includes("/node_modules/")},yi=8,et=new Map,In=t=>JSON.stringify([Ds(),t]),vi=t=>{const n=In(t),o=et.get(n);return o?(o.touchedAt=Date.now(),et.delete(n),et.set(n,o),o):null},wn=t=>{const n=In(t),o=et.get(n);if(o)return o.touchedAt=Date.now(),o;if(et.size>=yi){const a=et.keys().next().value;a!==void 0&&et.delete(a)}const r={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return et.set(n,r),r},ji=t=>{et.delete(In(t))},qs=(t,n)=>e.jsx(Pn,{filePath:t,extension:n}),Si=({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}})},Ai=({node:t,root:n,isExpanded:o,isActive:r,isBrowserClient:a,status:i,badge:p,permissions:h,downloadFile:m,onSelect:f,onToggle:S,onRevealPath:x,onOpenDialog:b})=>{const k=t.type==="directory",{canRename:d,canCreateFile:A,canCreateFolder:D,canDelete:L,canReveal:H}=h,X=!k&&!!m,I=H&&!a,P=d||A||D||L||X||I,[w,N]=s.useState(!1),[W,y]=s.useState(!1),Q=s.useCallback(M=>{P&&(M?.preventDefault(),y(!0))},[P]),O=s.useCallback(()=>{k?S(t.path):f(t)},[k,t,f,S]),Y=s.useCallback(M=>{M.stopPropagation(),y(!1),N(!0)},[]),J=({Item:M,Separator:K})=>e.jsxs(e.Fragment,{children:[d&&e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),b("rename",t)},children:[e.jsx(C,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),mt(t.path).then(ue=>{if(ue.ok){ce.success("Path copied");return}ce.error("Copy failed")})},children:[e.jsx(C,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!k&&m&&e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),m(t.path).catch(ue=>{console.error("Download failed:",ue),ce.error("Operation failed")})},children:[e.jsx(C,{name:"download",className:"mr-2 h-4 w-4"})," ",a?"Download":"Save"]}),I&&e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),x(t.path)},children:[e.jsx(C,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",go()]}),k&&(A||D)&&e.jsxs(e.Fragment,{children:[e.jsx(K,{}),A&&e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),b("createFile",t)},children:[e.jsx(C,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),D&&e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),b("createFolder",t)},children:[e.jsx(C,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),L&&e.jsxs(e.Fragment,{children:[e.jsx(K,{}),e.jsxs(M,{onClick:ne=>{ne.stopPropagation(),b("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(C,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),_=s.useCallback(M=>{const K=Js(n,t.path);!K||K==="."||(M.dataTransfer.setData("application/x-pichamber-file-path",K),M.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(Aa,{open:W,onOpenChange:y,children:[e.jsxs(Ca,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:Q}),children:[e.jsxs("button",{type:"button",onClick:O,onContextMenu:Q,draggable:!0,onDragStart:_,className:ge("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",r?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[k?o?e.jsx(C,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(C,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):qs(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!k&&i&&e.jsx(Si,{status:i}),k&&p&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[p.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",p.modified]}),p.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",p.added]})]})]}),P&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:e.jsxs(ft,{open:w,onOpenChange:N,children:[e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(gt,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:Y,title:"File menu","aria-label":"File menu",children:e.jsx(C,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(Ke,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(xt,{align:"end",side:"bottom",onCloseAutoFocus:()=>N(!1),children:J({Item:$e,Separator:wt})})]})})]}),e.jsx(ka,{className:"min-w-[180px]",children:J({Item:Na,Separator:Pa})})]})},Ci=(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,ki=s.memo(Ai,Ci),Ni=()=>{const{files:t,runtime:n}=$t(),o=zr(n.platform),r=Ht()??"",a=Ue(r.trim()),i=Hr(),p=Vr(),h=Is(v=>v.searchFiles),m=z(v=>v.openContextFile),f=Fs(r),[S,x]=s.useState(""),b=Ws(S,200),k=s.useRef(null),[d,A]=s.useState([]),[D,L]=s.useState(!1),[H,X]=s.useState({}),[I,P]=s.useState({}),w=s.useRef(new Set),N=s.useRef(new Set),W=s.useRef(null);s.useEffect(()=>{if(!a){X({}),P({}),w.current=new Set;return}const v=vi(a);v?(X({...v.childrenByDir}),P({...v.loadErrorsByDir}),w.current=new Set(v.loadedDirs)):(X({}),P({}),w.current=new Set)},[a]),s.useEffect(()=>{if(!a)return;const v=wn(a);v.childrenByDir=H},[a,H]),s.useEffect(()=>{if(!a)return;const v=wn(a);v.loadErrorsByDir=I},[a,I]),s.useEffect(()=>{if(!a)return;const v=wn(a);v.loadedDirs=new Set(w.current)},[a,H,I]),s.useEffect(()=>()=>{if(!a)return;const v=et.get(a);v&&v.loadedDirs.size===0&&Object.keys(v.childrenByDir).length===0&&ji(a)},[a]);const y=s.useMemo(()=>[],[]),Q=s.useMemo(()=>[],[]),O=rt(v=>a?v.byRoot[a]?.expandedPaths??y:y),Y=rt(v=>a?v.byRoot[a]?.selectedPath??null:null),J=rt(v=>v.setSelectedPath),_=rt(v=>v.addOpenPath),M=rt(v=>v.removeOpenPathsByPrefix),K=rt(v=>v.toggleExpandedPath),ne=rt(v=>v.collapseAllExpandedPaths),ue=z(v=>a?v.contextPanelByDirectory[a]?.tabs??Q:Q),xe=s.useMemo(()=>new Set(ue.map(v=>v.mode==="file"?v.targetPath:null).filter(v=>typeof v=="string"&&v.length>0).map(v=>Ue(v))),[ue]),[q,le]=s.useState(null),[pe,we]=s.useState(null),[me,Pe]=s.useState(""),[ve,Se]=s.useState(!1),fe=!!t.writeFile,Z=!!t.createDirectory,Ee=!!t.rename,U=!!t.delete,G=!!t.revealPath,ee=s.useMemo(()=>({canRename:Ee,canCreateFile:fe,canCreateFolder:Z,canDelete:U,canReveal:G}),[Ee,fe,Z,U,G]),ae=s.useCallback(v=>{t.revealPath&&t.revealPath(v).catch(()=>{ce.error("Failed to reveal path")})},[t]),de=s.useCallback((v,B)=>{le(v),we(B),Pe(v==="rename"&&B.name||""),Se(!1)},[]),Ae=s.useCallback((v,B)=>{const be=B.filter(u=>u&&typeof u.name=="string"&&u.name.length>0).filter(u=>i||!u.name.startsWith(".")).filter(u=>p||!wi(u.name)).map(u=>{const T=u.name,R=Ue(u.path||""),V=R?gi(R)?R:Ue(`${v}/${R}`):Ue(`${v}/${T}`),l=u.isDirectory?"directory":"file",F=l==="file"&&T.includes(".")?T.split(".").pop()?.toLowerCase():void 0;return{name:T,path:V,type:l,extension:F}});return fi(be)},[p,i]),je=s.useCallback(async(v,B)=>{const be=Ue(v.trim());if(!be||w.current.has(be)||N.current.has(be))return;N.current=new Set(N.current),N.current.add(be);const u=t.listDirectory?t.listDirectory(be).then(T=>T.entries.map(R=>({name:R.name,path:R.path,isDirectory:R.isDirectory}))):Kr(be).then(T=>T.map(R=>({name:R.name,path:R.path,isDirectory:R.isDirectory})));try{const T=await u;if(B?.())return;const R=Ae(be,T);w.current=new Set(w.current),w.current.add(be),P(V=>{if(!V[be])return V;const l={...V};return delete l[be],l}),X(V=>({...V,[be]:R}))}catch(T){if(B?.())return;const R=T instanceof Error?T.message:String(T??"");console.error("Failed to load sidebar directory:",T),P(V=>({...V,[be]:R}))}finally{N.current=new Set(N.current),N.current.delete(be)}},[t,Ae]),ke=s.useCallback(async()=>{if(!a)return;W.current?.abort();const v=new AbortController;W.current=v;try{const be=(rt.getState().byRoot[a]?.expandedPaths??[]).map(R=>Ue(R)).filter(R=>!!R&&R!==a&&R.startsWith(`${a}/`)),u=[a,...be];w.current=new Set(w.current);for(const R of u)w.current.delete(R);P(R=>{if(Object.keys(R).length===0)return R;const V={...R};let l=!1;for(const F of u)F in V&&(delete V[F],l=!0);return l?V:R});const T=()=>v.signal.aborted;await je(a,T);for(let R=0;R<be.length&&!v.signal.aborted;R+=3){const V=be.slice(R,R+3);await Promise.all(V.map(l=>je(l,T)))}}catch(B){if(v.signal.aborted)return;console.error("Failed to refresh sidebar tree:",B)}finally{W.current===v&&(W.current=null)}},[je,a]),Be=s.useCallback(async v=>{if(!v){await ke();return}const B=Ue(v);w.current=new Set(w.current),w.current.delete(B),N.current=new Set(N.current),N.current.delete(B),await je(B)},[je,ke]);s.useEffect(()=>{a&&(W.current?.abort(),w.current=new Set,N.current=new Set,P({}),X(v=>Object.keys(v).length===0?v:{}),je(a))},[je,a,i,p]),s.useEffect(()=>{if(!a||O.length===0)return;const v=O.map(u=>Ue(u)).filter(u=>!!u&&u!==a&&u.startsWith(`${a}/`)&&!w.current.has(u)&&!N.current.has(u)).sort((u,T)=>u.split("/").length-T.split("/").length);if(v.length===0)return;let B=!1;const be=()=>B;return(async()=>{for(let u=0;u<v.length&&!B;u+=3){const T=v.slice(u,u+3);await Promise.all(T.map(R=>je(R,be)))}})(),()=>{B=!0}},[O,je,a]),s.useEffect(()=>{if(!r){A([]),L(!1);return}const v=b.trim();if(!v){A([]),L(!1);return}let B=!1;return L(!0),h(r,v,150,{includeHidden:i,respectGitignore:!p,type:"file"}).then(be=>{if(B)return;const T=be.filter(R=>p||!bi(R.path)).map(R=>({name:R.name,path:Ue(R.path),type:"file",extension:R.extension,relativePath:R.relativePath}));A(T)}).catch(()=>{B||A([])}).finally(()=>{B||L(!1)}),()=>{B=!0}},[r,b,h,i,p]);const Me=s.useMemo(()=>{const v=new Map;if(!f?.files)return v;for(const B of f.files)B.index==="A"||B.working_dir==="?"?v.set(B.path,"git-added"):B.index==="D"?v.set(B.path,"git-deleted"):(B.index==="M"||B.working_dir==="M")&&v.set(B.path,"git-modified");return v},[f]),Oe=s.useMemo(()=>{const v=new Map;if(!f?.files||!a)return v;for(const B of f.files){const be=B.index==="M"||B.working_dir==="M",u=B.index==="A"||B.working_dir==="?";if(!be&&!u)continue;const T=B.path.split("/");if(T.length<=1)continue;let R=a;for(let V=0;V<T.length-1;V++){R=`${R}/${T[V]}`;let l=v.get(R);l||(l={modified:0,added:0},v.set(R,l)),be&&l.modified++,u&&l.added++}}return v},[f,a]),E=s.useCallback(v=>{if(xe.has(v))return"open";if(Me.size===0)return null;const B=v.startsWith(a+"/")?v.slice(a.length+1):v;return Me.get(B)??null},[xe,Me,a]),ie=s.useCallback(v=>{if(Oe.size===0)return null;const B=Oe.get(v);return B&&B.modified+B.added>0?B:null},[Oe]),he=s.useCallback(async v=>{if(!a)return;const B=await Ys(t,v.path,{directory:a});if(!B.ok){ce.error(Xs(B.reason));return}J(a,v.path),_(a,v.path),m(a,v.path)},[_,t,m,a,J]),g=s.useCallback(async v=>{const B=Ue(v);a&&(K(a,B),w.current.has(B)||await je(B))},[je,a,K]),j=s.useCallback(async v=>{if(v?.preventDefault(),!pe||!q)return;Se(!0);const B=()=>Se(!1),be=()=>le(null);if(q==="createFile"){if(!me.trim()){ce.error("Filename is required"),B();return}if(!t.writeFile){ce.error("Write not supported"),B();return}const u=pe.path,T=u?`${u}/`:"",R=Ue(`${T}${me.trim()}`);await t.writeFile(R,"").then(async V=>{V.success&&(ce.success("File created"),await Be(u)),be()}).catch(()=>ce.error("Operation failed")).finally(B);return}if(q==="createFolder"){if(!me.trim()){ce.error("Folder name is required"),B();return}const u=pe.path,T=u?`${u}/`:"",R=Ue(`${T}${me.trim()}`);await t.createDirectory(R).then(async V=>{V.success&&(ce.success("Folder created"),await Be(u)),be()}).catch(()=>ce.error("Operation failed")).finally(B);return}if(q==="rename"){if(!me.trim()){ce.error("Name is required"),B();return}if(!t.rename){ce.error("Rename not supported"),B();return}const u=pe.path,T=u.split("/").slice(0,-1).join("/"),R=T?`${T}/`:"",V=Ue(`${R}${me.trim()}`);await t.rename(u,V).then(async l=>{l.success&&(ce.success("Renamed successfully"),await Be(T),a&&M(a,u),(Y===u||Y&&Y.startsWith(`${u}/`))&&J(a,null)),be()}).catch(()=>ce.error("Operation failed")).finally(B);return}if(q==="delete"){if(!t.delete){ce.error("Delete not supported"),B();return}const u=pe.path,T=u.split("/").slice(0,-1).join("/");await t.delete(u).then(async R=>{R.success&&(ce.success("Deleted successfully"),await Be(T),a&&M(a,u),(Y===u||Y&&Y.startsWith(u+"/"))&&J(a,null)),be()}).catch(()=>ce.error("Operation failed")).finally(B);return}B()},[q,pe,me,t,Be,M,a,Y,J]);function te(v,B){const be=H[v]??[];return be.map((u,T)=>{const R=u.type==="directory",V=R&&O.includes(u.path),l=Y===u.path,F=T===be.length-1;return e.jsxs("li",{className:"relative",children:[B>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),F&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(ki,{node:u,root:a,isExpanded:V,isActive:l,isBrowserClient:o,status:R?void 0:E(u.path),badge:R?ie(u.path):void 0,permissions:ee,downloadFile:t.downloadFile,onSelect:he,onToggle:g,onRevealPath:ae,onOpenDialog:de}),R&&V&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[I[u.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:I[u.path],children:I[u.path]}),e.jsxs(Ce,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{Be(u.path)},children:[e.jsx(C,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,te(u.path,B+1)]})]},u.path)})}const ye=!!(a&&H[a]),_e=a?I[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:[fe&&e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>de("createFile",{path:r,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(C,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx(Ke,{side:"bottom",sideOffset:6,children:"New File"})]}),Z&&e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>de("createFolder",{path:r,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(C,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx(Ke,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{ke()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(C,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx(Ke,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(He,{children:[e.jsx(Ve,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{a&&ne(a)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(C,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx(Ke,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]}),e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(C,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(Qn,{ref:k,value:S,onChange:v=>x(v.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),S.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:()=>{x(""),k.current?.focus()},children:e.jsx(C,{name:"close",className:"h-4 w-4"})}):null]})]}),e.jsx(xo,{outerClassName:"flex-1 min-h-0",className:"p-2",children:e.jsx("ul",{className:"flex flex-col",children:D?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(C,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):d.length>0?d.map(v=>{const B=Y===v.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>he(v),draggable:!0,onDragStart:be=>{const u=v.relativePath||Js(a??"",v.path);!u||u==="."||(be.dataTransfer.setData("application/x-pichamber-file-path",u),be.dataTransfer.effectAllowed="copy")},className:ge("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",B?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:v.path,children:[qs(v.path,v.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:v.relativePath??v.path})]})},v.path)}):_e?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:_e}),e.jsxs(Ce,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{ke()},children:[e.jsx(C,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):ye&&a?te(a,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(tn,{open:!!q,onOpenChange:v=>!v&&le(null),children:e.jsxs(nn,{children:[e.jsxs(sn,{children:[e.jsxs(rn,{children:[q==="createFile"&&"Create File",q==="createFolder"&&"Create Folder",q==="rename"&&"Rename",q==="delete"&&"Delete"]}),e.jsxs(on,{children:[q==="createFile"&&`Create a new file in ${pe?.path??"root"}`,q==="createFolder"&&`Create a new folder in ${pe?.path??"root"}`,q==="rename"&&`Rename ${pe?.name??""}`,q==="delete"&&`Are you sure you want to delete ${pe?.name??""}? This action cannot be undone.`]})]}),q!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(Qn,{value:me,onChange:v=>Pe(v.target.value),placeholder:q==="rename"?"New name":"Name",onKeyDown:v=>{v.key==="Enter"&&j()},autoFocus:!0})}),e.jsxs(Ls,{children:[e.jsx(Ce,{variant:"outline",onClick:()=>le(null),disabled:ve,children:"Cancel"}),e.jsx(Ce,{variant:q==="delete"?"destructive":"default",onClick:()=>{j()},disabled:ve||q!=="delete"&&!me.trim(),children:ve?e.jsx(C,{name:"loader-4",className:"size-4 animate-spin"}):q==="delete"?"Delete":"Confirm"})]})]})})]})},Dn=t=>t,Cn=t=>{const n=Dn(t).type;return typeof n=="string"?n:""},Pi=t=>{const n=Dn(t).tool;return typeof n=="string"?n:""},Ri=t=>{const n=Dn(t).text;return typeof n=="string"?n:""},Ei=t=>{const n=Cn(t);return n==="tool"?Pi(t).trim().toLowerCase()||"tool":n||"unknown"},Ti=t=>{if(t.length===0)return"";const n=[];for(const o of t){const r=Ei(o);n.includes(r)||n.push(r)}return n.join(" + ")},Ii=t=>t.replace(/\s+/g," ").trim(),Di=t=>{for(const o of t)if(Cn(o)==="text"){const r=Ii(Ri(o));if(r.length===0)continue;return r}const n=t.filter(o=>Cn(o)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},Mi=(t,n,o)=>`${o(t)} / ${o(n)}`,Oi=t=>{if(t==="12h")return!0;if(t==="24h")return!1},_i=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const o=Oi(n);return new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:o===!1?"2-digit":"numeric",minute:"2-digit",...o===void 0?{}:{hour12:o}})},Li={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},Yt={user:0,assistant:0,tool:0,other:0},Bi=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,bn=t=>So(t),Fi=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},Je=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,o)=>n+Je(o),0):t&&typeof t=="object"?Object.values(t).reduce((n,o)=>n+Je(o),0):0,Wi=(t,n)=>{const o=t,r=typeof o.type=="string"?o.type:"";if(r==="reasoning")return{...Yt,assistant:Je(o.text)+Je(o.content)};const a=Fi(o.text,o.content,o.value,o.source?.value,o.source?.text?.value);return r==="tool"||n==="tool"?{user:0,assistant:0,tool:Je(o.input)+Je(o.output)+Je(o.error)+Je(o.call?.input)+Je(o.call?.output)+Je(o.call?.error)+Je(o.raw)+Math.round(Je(o.metadata)*.25)+Math.round(Je(o.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}},ws=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),Ui=t=>{const n=_t(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},$i=(t,n)=>{if(t.length===0)return{...Yt};const o=t.reduce((r,a)=>{const i=Ui(a);let p={...Yt};for(const h of a.parts)p=ws(p,Wi(h,i));return ws(r,p)},{...Yt});return o.user+=n.length,{user:Math.ceil(o.user/4),assistant:Math.ceil(o.assistant/4),tool:Math.ceil(o.tool/4),other:Math.ceil(o.other/4)}},pt=t=>t.toLocaleString("en-US"),zi=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),Hi=(t,n)=>!t||!Number.isFinite(t)?"-":Ao(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),Vi=(t,n,o)=>{const r=t.find(i=>i.id===n),a=r?.models?.find(i=>i.id===o);return{providerName:r?.name||n||"-",modelName:a?.name||o||"-",contextLimit:typeof a?.limit?.context=="number"?a.limit.context:null}},Ki=()=>{const t=z(d=>d.timeFormatPreference),[n,o]=s.useState({}),[r,a]=s.useState(null),i=s.useRef(null),p=Fe(d=>d.currentSessionId),h=Fe(d=>d.currentSessionDirectory),m=wo(),f=bo(p??""),S=_s(d=>d.providers);s.useEffect(()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null),o(d=>Object.keys(d).length>0?{}:d),a(null)},[h,p]),s.useEffect(()=>()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},[]);const x=s.useCallback(async(d,A)=>{(await mt(A)).ok?(a(d),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{a(L=>L===d?null:L),i.current=null},2e3)):a(null)},[]),b=s.useMemo(()=>{const d=p?m.find(q=>q.id===p)??null:null,A=f.filter(q=>_t(q.info).role==="assistant"),D=f.filter(q=>_t(q.info).isUser);let L=null;for(let q=A.length-1;q>=0;q-=1){const le=A[q];if(bn(le).total>0){L=le;break}}const H=L?bn(L):Li,X=L?.info?.usage,I=yo({input:H.input,cache:{read:H.cacheRead,write:H.cacheWrite}}),P=A.reduce((q,le)=>{const pe=Bi(le.info.cost);return q+pe},0),w=L?.info?.model??null,N=Vi(S,w?.providerID||"",w?.modelID||""),W=N.contextLimit,y=X?vo(X):H.total,Q=W&&W>0?Math.min(999,y/W*100):0,O=[...f].reverse().find(q=>_t(q.info).isUser&&typeof q.info.system=="string")?.info?.system||"",Y=$i(f,O),J=Y.user,_=Y.assistant,M=Y.tool,K=X?0:Math.max(0,H.input-J-_-M),ne=J+_+M+K,ue=f[0]?.info?.time?.created,xe=f.length>0?f[f.length-1]?.info?.time?.created:null;return{sessionTitle:d?.title||"Untitled Session",messagesCount:f.length,userMessagesCount:D.length,assistantMessagesCount:A.length,createdAt:d?.time?.created??ue??null,lastActivityAt:xe??d?.time?.created??null,providerModel:N,tokenBreakdown:H,usagePercent:Q,cacheHitRate:I,totalAssistantCost:P,contextLimit:W,contextWindowTokens:y,hasUsage:X!==void 0,breakdown:{user:J,assistant:_,tool:M,other:K},breakdownTotal:ne}},[p,S,f,m]);if(!p)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 k=[{key:"user",label:"User",value:b.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:b.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool Calls",value:b.breakdown.tool,color:"var(--status-warning)"},...b.hasUsage?[]:[{key:"other",label:"Other",value:b.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:b.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:[b.providerModel.providerName," / ",b.providerModel.modelName]}),b.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:Hi(b.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:[pt(b.contextWindowTokens),b.contextLimit?` / ${pt(b.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:b.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,b.usagePercent)}%`,backgroundColor:b.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:`${b.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:pt(b.messagesCount)},{label:"User",value:pt(b.userMessagesCount)},{label:"Assistant",value:pt(b.assistantMessagesCount)},{label:"Cost",value:zi(b.totalAssistantCost)}].map(d=>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:d.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:d.value})]},d.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:b.tokenBreakdown.input,format:"count"},{label:"Output",value:b.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:b.tokenBreakdown.reasoning,format:"count"},{label:"Cache Read",value:b.tokenBreakdown.cacheRead,format:"count"},{label:"Cache Write",value:b.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache Hit",value:b.cacheHitRate.hasInput?b.cacheHitRate.percent:null,format:"percent"}].map(d=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground/70",children:d.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:d.value!==null&&d.value!==void 0?d.format==="percent"?`${d.value.toFixed(1)}%`:pt(d.value):"—"})]},d.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:k.map(d=>d.value<=0||b.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${d.value/b.breakdownTotal*100}%`,backgroundColor:d.color}},d.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:k.map(d=>{const A=b.breakdownTotal>0?d.value/b.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:d.color}}),e.jsxs("span",{className:"typography-micro text-muted-foreground/70",children:[d.label," ",e.jsxs("span",{className:"tabular-nums",children:[A.toFixed(0),"%"]})]})]},d.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:[...f].reverse().map(d=>{const D=_t(d.info).role,L=D==="assistant",H=D==="user",X=n[d.info.id]===!0,I=r===d.info.id,P=d.info.time?.created??null,w=Ti(d.parts),N=L?bn({info:d.info,parts:d.parts}):null,W=H?Di(d.parts):"",y=_i(P,t),Q=w||"—",O=N?Mi(N.input,N.output,pt):"",Y=D||"unknown",J=w?`${Y}: ${w}`:Y,_=X?JSON.stringify({info:d.info,parts:d.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":X,onClick:()=>{o(M=>({...M,[d.info.id]:M[d.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:L?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[H?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",W]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:L?Q:J}),L&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:O})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:y})]})}),X&&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:M=>{M.stopPropagation(),x(d.info.id,_)},"aria-label":I?"Copied":"Copy JSON",title:I?"Copied":"Copy",children:I?e.jsx(C,{name:"check",className:"size-3.5"}):e.jsx(C,{name:"file-copy",className:"size-3.5"})})}),e.jsx(jo,{language:"json",code:_,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},d.info.id)})})]})]})})},Gi="x-pichamber-preview-target-error",Yi=t=>{const n=t.get(Gi);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},Xi=(t,n)=>Yi(t)?n?"stop-retrying":"retry-registration":"none",Ji=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},bs=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Pt=t=>{if(!t||typeof t!="object")return!1;const n=t,o=n.bounds;return typeof n.tag=="string"&&typeof n.text=="string"&&typeof n.selector=="string"&&typeof n.path=="string"&&!!o&&typeof o?.x=="number"&&typeof o?.y=="number"&&typeof o?.width=="number"&&typeof o?.height=="number"&&Ji(n.center)&&bs(n.attributes)&&bs(n.computedStyle)&&Array.isArray(n.ancestry)},Mn=({pageUrl:t,viewport:n,devicePixelRatio:o,target:r,screenshotAttached:a,intro:i})=>{const p=r.text.trim(),h=Object.entries(r.attributes).map(([k,d])=>`${k}="${d}"`).join(" "),m=r.computedStyle,f=r.bounds,S=r.center,x=i.replace(/[.:]+$/g,""),b=r.ancestry.map(k=>k.selectorPart).join(" > ");return[`${x}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${o}`,`Screenshot: ${a?"attached":"not attached"}`,`Element: ${r.tag}`,p?`Text: ${p}`:null,`- Selector: ${r.selector}`,`- Path: ${r.path}`,b?`- Ancestry: ${b}`:null,h?`- Attributes: ${h}`:null,`- Bounds: x=${Math.round(f.x)}, y=${Math.round(f.y)}, width=${Math.round(f.width)}, height=${Math.round(f.height)}`,`- Center: x=${Math.round(S.x)}, y=${Math.round(S.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(k=>typeof k=="string").join(`
|
|
4
|
-
`)},Qs=async(t,n)=>{if(typeof window<"u")try{const o=t.getBoundingClientRect(),r=await kt("desktop_capture_page_rect",{x:o.left,y:o.top,width:o.width,height:o.height});if(!r)throw new Error("Desktop screenshot capture is not available");const a=new Image;await new Promise((d,A)=>{a.onload=()=>d(),a.onerror=()=>A(new Error("Failed to load desktop preview screenshot")),a.src=`data:${r.mime};base64,${r.base64}`});const i=Math.max(1,a.naturalWidth||r.width||Math.floor(o.width)),p=Math.max(1,a.naturalHeight||r.height||Math.floor(o.height)),m=Math.min(1,1200/i),f=document.createElement("canvas");f.width=Math.floor(i*m),f.height=Math.floor(p*m);const S=f.getContext("2d");if(!S)return null;S.scale(m,m),S.drawImage(a,0,0,i,p);const x=i/Math.max(1,o.width),b=p/Math.max(1,o.height);S.fillStyle="rgba(37, 99, 235, 0.28)",S.strokeStyle="rgb(37, 99, 235)",S.lineWidth=Math.max(2,2*x),S.fillRect(n.bounds.x*x,n.bounds.y*b,n.bounds.width*x,n.bounds.height*b),S.strokeRect(n.bounds.x*x,n.bounds.y*b,n.bounds.width*x,n.bounds.height*b);const k=await new Promise(d=>f.toBlob(d,"image/jpeg",.82));return k?new File([k],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(o){return console.warn("[preview] failed to capture annotation screenshot:",o),null}return await ul(t,n)},On=async(t,n,o,r,a,i)=>{if(!t)return null;try{const p=new Image;await new Promise((D,L)=>{p.onload=()=>D(),p.onerror=()=>L(new Error("Failed to load desktop browser screenshot")),p.src=`data:image/jpeg;base64,${t}`});const h=Math.max(1,p.naturalWidth||n),m=Math.max(1,p.naturalHeight||o),S=Math.min(1,1200/h),x=document.createElement("canvas");x.width=Math.floor(h*S),x.height=Math.floor(m*S);const b=x.getContext("2d");if(!b)return null;b.scale(S,S),b.drawImage(p,0,0,h,m);const k=h/Math.max(1,r||h),d=m/Math.max(1,a||m);b.fillStyle="rgba(37, 99, 235, 0.14)",b.strokeStyle="rgb(37, 99, 235)",b.lineWidth=Math.max(2,2*k),b.fillRect(i.bounds.x*k,i.bounds.y*d,i.bounds.width*k,i.bounds.height*d),b.strokeRect(i.bounds.x*k,i.bounds.y*d,i.bounds.width*k,i.bounds.height*d);const A=await new Promise(D=>x.toBlob(D,"image/jpeg",.82));return A?new File([A],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}},Rt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Ye=new Map,yn=new Map,qi=3e4,_n=t=>{const n=Ye.get(t);return n?n.expiresAt-Date.now()<=qi?(Ye.delete(t),null):n:null},Qi=t=>{try{return new URL(t).origin}catch{return t}};function Zs(t){const n="#ffffff",o=t.defaultView??window;try{const r=t.body?o.getComputedStyle(t.body).backgroundColor:"";if(r&&r!=="rgba(0, 0, 0, 0)"&&r!=="transparent")return r;const a=o.getComputedStyle(t.documentElement).backgroundColor;if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a}catch{}return n}const er=t=>new Promise((n,o)=>{const r=new FileReader;r.onloadend=()=>n(typeof r.result=="string"?r.result:Rt),r.onerror=()=>o(r.error??new Error("Failed to read image blob")),r.readAsDataURL(t)}),Zi=async(t,n=.82)=>{const o=await new Promise(r=>t.toBlob(r,"image/jpeg",n));return o&&(await er(o)).split(",",2)[1]||""},el=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},Xt=(...t)=>{el()&&console.info("[preview-capture]",...t)},tr=(t,n=8)=>{const o=[];try{const r=t.querySelectorAll("*");for(const a of r){const i=a.scrollTop||0,p=a.scrollLeft||0;if(i<=0&&p<=0)continue;const h=a.tagName.toLowerCase(),m=a.id?`#${a.id}`:"",f=typeof a.className=="string"&&a.className?`.${a.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(o.push({selector:`${h}${m}${f}`,scrollTop:i,scrollLeft:p,clientWidth:a.clientWidth,clientHeight:a.clientHeight,scrollWidth:a.scrollWidth,scrollHeight:a.scrollHeight}),o.length>=n)break}}catch{}return o},Bt="data-oc-fixed-pin",tl=(t,n,o)=>{if(n<=0&&o<=0)return()=>{};const r=t.defaultView;if(!r)return()=>{};const a=[],i=[];try{for(const p of t.querySelectorAll("*")){if(r.getComputedStyle(p).position!=="fixed")continue;const h=p.getBoundingClientRect();if(!(h.width>0&&h.height>0))continue;p.setAttribute(Bt,JSON.stringify({top:h.top+o,left:h.left+n,width:h.width,height:h.height})),a.push(p);const m=p.tagName.toLowerCase(),f=typeof p.className=="string"&&p.className?`.${p.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";i.push({selector:`${m}${f}`,top:Math.round(h.top),left:Math.round(h.left),width:Math.round(h.width),height:Math.round(h.height)})}}catch{}return Xt("tagged fixed elements",i),()=>{for(const p of a)try{p.removeAttribute(Bt)}catch{}}},nl={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const o of n.querySelectorAll(`[${Bt}]`)){let r;try{r=JSON.parse(o.getAttribute(Bt)||"")}catch{continue}o.style.setProperty("position","absolute","important"),o.style.setProperty("top",`${r.top}px`,"important"),o.style.setProperty("left",`${r.left}px`,"important"),o.style.setProperty("right","auto","important"),o.style.setProperty("bottom","auto","important"),o.style.setProperty("width",`${r.width}px`,"important"),o.style.setProperty("height",`${r.height}px`,"important"),o.removeAttribute(Bt)}}},Ct="data-oc-scroll-pin",sl=t=>{const n=[],o=tr(t,64);try{const i=t.documentElement,p=t.body;for(const h of t.querySelectorAll("*")){const m=h.scrollTop||0,f=h.scrollLeft||0;if(m<=0&&f<=0)continue;const S=h!==i&&h!==p;S&&h.setAttribute(Ct,JSON.stringify({top:m,left:f})),n.push({el:h,top:m,left:f,tagged:S})}}catch{}return{reapply:()=>{for(const i of n)try{i.el.scrollHeight,i.el.scrollTop!==i.top&&(i.el.scrollTop=i.top),i.el.scrollLeft!==i.left&&(i.el.scrollLeft=i.left)}catch{}},cleanup:()=>{for(const i of n)if(i.tagged)try{i.el.removeAttribute(Ct)}catch{}},snapshot:o}},rl={name:"oc-nested-scroll",afterClone(t){const n=t?.clone;if(!n||typeof n.querySelectorAll!="function")return;const o=n.ownerDocument;if(o)for(const r of n.querySelectorAll(`[${Ct}]`)){let a;try{a=JSON.parse(r.getAttribute(Ct)||"")}catch{r.removeAttribute(Ct);continue}const i=`translate(${-a.left}px, ${-a.top}px)`,p=r.children.length===1&&r.firstElementChild instanceof HTMLElement&&r.firstElementChild.style.willChange==="transform"?r.firstElementChild:null;if(p)p.style.transform=i;else{r.style.overflow="hidden";const h=o.createElement("div");for(h.style.transform=i,h.style.willChange="transform",h.style.display="inline-block",h.style.width="100%";r.firstChild;)h.appendChild(r.firstChild);r.appendChild(h)}r.removeAttribute(Ct)}}},vn=async(t,n)=>{try{const o=await fetch(t,{credentials:n});return o.ok?await er(await o.blob()):null}catch{return null}},ol=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,o=_n(n);if(o)return`${o.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const r=yn.get(n),a=r??(async()=>{try{const p=await it("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!p.ok)return Ye.delete(n),null;const h=await p.json(),m=typeof h.proxyBasePath=="string"?h.proxyBasePath:"",f=typeof h.expiresAt=="number"?h.expiresAt:0;if(!m)return Ye.delete(n),null;const S={proxyBasePath:m,expiresAt:f};return Ye.set(n,S),S}catch{return Ye.delete(n),null}finally{yn.delete(n)}})();r||yn.set(n,a);const i=await a;return i?`${i.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},nr=async(t,n)=>{if(!t||t.startsWith("data:"))return t;try{const o=new URL(t,n.baseURI);if(o.origin===window.location.origin||o.protocol!=="http:"&&o.protocol!=="https:")return await vn(o.toString(),"include")??Rt;const r=await ol(o),a=r?await vn(r,"include"):null;return a||(await vn(o.toString(),"omit")??Rt)}catch{return Rt}},al=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const o=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let r=t;for(const a of o){const i=a[2]||"";if(!i||i.startsWith("data:"))continue;const p=await nr(i,n);r=r.replace(a[0],`url("${p}")`)}return r},ys=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),sr=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},il=t=>{const n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;const o=Number.parseFloat(t.fontSize);return Number.isFinite(o)&&o>0?o*1.2:16},ll=(t,n,o)=>{const r=[],a=t.defaultView??window,p=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const h of p){const m=h.textContent?.replace(/\s+/g," ").trim()??"";if(!m||!m.includes(" "))continue;const f=h.getBoundingClientRect();if(f.width<=0||f.height<=0||f.right<0||f.bottom<0||f.left>n||f.top>o)continue;const S=a.getComputedStyle(h);if(S.display==="none"||S.visibility==="hidden"||Number(S.opacity)===0)continue;const x=S.getPropertyValue("text-wrap"),b=S.getPropertyValue("text-wrap-mode"),k=S.whiteSpace.includes("nowrap")||x==="nowrap"||b==="nowrap",d=f.height<=il(S)*1.7;!k&&(!d||f.width>n*.72)||(r.push(sr(h)),h.style.whiteSpace="nowrap",h.style.overflowWrap="normal",h.style.wordBreak="normal",h.style.setProperty("text-wrap","nowrap"),h.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let h=r.length-1;h>=0;h-=1)r[h]?.()}},cl=(t,n,o,r)=>{const a=[],i=t.defaultView??window,p=i.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,h=i.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,m=Array.from(t.querySelectorAll("*")).filter(f=>{const S=i.getComputedStyle(f);if(S.position!=="fixed"||S.display==="none"||S.visibility==="hidden"||Number(S.opacity)===0)return!1;const x=f.getBoundingClientRect();return x.width>0&&x.height>0&&x.right>=0&&x.bottom>=0&&x.left<=n&&x.top<=o}).filter((f,S,x)=>!x.some((b,k)=>k<S&&b.contains(f)));for(const f of m){const S=f.getBoundingClientRect(),x=i.getComputedStyle(f),b=Math.ceil(S.width)+8,k=Math.ceil(S.height)+2;r?.add(f),a.push(sr(f)),f.style.position="absolute",f.style.top=`${S.top+h}px`,f.style.left=`${S.left+p}px`,f.style.right="auto",f.style.bottom="auto",f.style.width=`${b}px`,f.style.minWidth=`${b}px`,f.style.height=`${k}px`,f.style.minHeight=`${k}px`,f.style.margin="0",f.style.boxSizing="border-box",f.style.transform="none",x.zIndex!=="auto"&&(f.style.zIndex=x.zIndex)}return()=>{for(let f=a.length-1;f>=0;f-=1)a[f]?.()}},rr=async(t,n,o,r={})=>{const a=[],i=t.defaultView??window,p=x=>{if(x===t.documentElement||x===t.body)return!0;try{const b=x.getBoundingClientRect();return b.width>0&&b.height>0&&b.right>=0&&b.bottom>=0&&b.left<=n&&b.top<=o}catch{return!1}};if(r.applyLayoutWorkarounds){const x=new WeakSet;a.push(cl(t,n,o,x)),a.push(ll(t,n,o))}const h=new Map;for(const x of Array.from(t.images))h.set(x,x.currentSrc||x.src||x.getAttribute("src")||"");const m=Array.from(t.querySelectorAll("picture"));for(const x of m){const b=Array.from(x.querySelectorAll("source"));if(b.length===0)continue;const k=b.map(d=>({source:d,srcset:d.getAttribute("srcset"),sizes:d.getAttribute("sizes")}));a.push(()=>{for(const d of k)d.srcset===null?d.source.removeAttribute("srcset"):d.source.setAttribute("srcset",d.srcset),d.sizes===null?d.source.removeAttribute("sizes"):d.source.setAttribute("sizes",d.sizes)});for(const d of b)d.removeAttribute("srcset"),d.removeAttribute("sizes")}const f=Array.from(t.images).filter(x=>p(x));await Promise.all(f.map(async x=>{const b=h.get(x)||x.currentSrc||x.src||x.getAttribute("src")||"";if(!b)return;await ys(x);const k=await nr(b,t),d={src:x.getAttribute("src"),srcset:x.getAttribute("srcset"),sizes:x.getAttribute("sizes")};a.push(()=>{d.src===null?x.removeAttribute("src"):x.setAttribute("src",d.src),d.srcset===null?x.removeAttribute("srcset"):x.setAttribute("srcset",d.srcset),d.sizes===null?x.removeAttribute("sizes"):x.setAttribute("sizes",d.sizes)}),x.removeAttribute("srcset"),x.removeAttribute("sizes"),x.setAttribute("src",k||Rt),await ys(x)}));const S=Array.from(t.querySelectorAll("*")).filter(p);return await Promise.all(S.map(async x=>{const b=i.getComputedStyle(x).backgroundImage;if(!b||b==="none"||!b.includes("url("))return;const k=await al(b,t);if(k===b)return;const d=x.style.backgroundImage;a.push(()=>{x.style.backgroundImage=d}),x.style.backgroundImage=k})),()=>{for(let x=a.length-1;x>=0;x-=1)try{a[x]?.()}catch{}}};async function dl(t,n){try{const o=t.contentWindow,r=t.contentDocument??o?.document,a=r?.documentElement;if(!o||!r||!a)return null;const i=t.getBoundingClientRect(),p=Math.max(1,Math.ceil(o.innerWidth||t.clientWidth||i.width)),h=Math.max(1,Math.ceil(o.innerHeight||t.clientHeight||i.height)),m=r.body,f=r.scrollingElement instanceof HTMLElement?r.scrollingElement:null,S=o.scrollX||0,x=o.scrollY||0,b=o.pageXOffset||0,k=o.pageYOffset||0,d=o.visualViewport?.pageLeft||o.visualViewport?.offsetLeft||0,A=o.visualViewport?.pageTop||o.visualViewport?.offsetTop||0,D=a.scrollLeft||0,L=a.scrollTop||0,H=m?.scrollLeft||0,X=m?.scrollTop||0,I=f?.scrollLeft||0,P=f?.scrollTop||0,w=Math.max(S,b,d,D,H,I),N=Math.max(x,k,A,L,X,P);Xt("scroll sources",{windowScrollX:S,windowScrollY:x,pageScrollX:b,pageScrollY:k,visualViewportScrollX:d,visualViewportScrollY:A,rootScrollX:D,rootScrollY:L,bodyScrollX:H,bodyScrollY:X,scrollingElementScrollX:I,scrollingElementScrollY:P,scrollingElementTag:f?.tagName?.toLowerCase()??null,resolvedScrollX:w,resolvedScrollY:N,nestedScrolledElements:tr(r)});const W=Math.max(p,a.scrollWidth||0,m?.scrollWidth||0,Math.ceil(a.getBoundingClientRect().width||0)),y=Math.max(h,a.scrollHeight||0,m?.scrollHeight||0,Math.ceil(a.getBoundingClientRect().height||0)),Q=Math.min(2,Math.max(1,window.devicePixelRatio||1)),O=a.style.scrollBehavior,Y=m?.style.scrollBehavior??"";a.style.scrollBehavior="auto",m&&(m.style.scrollBehavior="auto");const J=sl(r);Xt("nested scroll snapshot",J.snapshot);let _=()=>{},M=()=>{};try{await r.fonts?.ready.catch(()=>{}),_=await rr(r,p,h,{applyLayoutWorkarounds:!1}),o.scrollTo(w,N),M=tl(r,w,N),J.reapply();const{snapdom:K}=await Qe(async()=>{const{snapdom:U}=await import("./vendor-zumer-snapdom-Btyu_Xi2.js");return{snapdom:U}},[]),ne={backgroundColor:Zs(r),cache:"disabled",dpr:Q,embedFonts:!0,fast:!1,height:y,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[nl,rl],quality:.82,width:W},xe=await(await K(a,ne)).toCanvas();if(!xe.width||!xe.height)return null;const q=xe.width/Math.max(1,W),le=xe.height/Math.max(1,y),pe=Math.min(xe.width,Math.max(1,Math.round(p*q))),we=Math.min(xe.height,Math.max(1,Math.round(h*le))),me=Math.max(0,xe.width-pe),Pe=Math.max(0,xe.height-we),ve=Math.min(me,Math.max(0,Math.round(w*q))),Se=Math.min(Pe,Math.max(0,Math.round(N*le)));Xt("capture geometry",{viewportWidth:p,viewportHeight:h,captureWidth:W,captureHeight:y,canvasWidth:xe.width,canvasHeight:xe.height,xScale:q,yScale:le,sourceX:ve,sourceY:Se,sourceWidth:pe,sourceHeight:we});const fe=r.createElement("canvas");fe.width=pe,fe.height=we;const Z=fe.getContext("2d");if(!Z)return null;Z.drawImage(xe,ve,Se,pe,we,0,0,pe,we);const Ee=await Zi(fe,.82);return Ee?await On(Ee,p,h,p,h,n):null}finally{M(),J.cleanup(),_(),o.scrollTo(w,N),J.reapply(),a.style.scrollBehavior=O,m&&(m.style.scrollBehavior=Y)}}catch(o){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",o),null}}async function ul(t,n){const o=await dl(t,n);if(o)return o;try{const r=t.contentWindow,a=t.contentDocument??r?.document,i=a?.documentElement;if(!r||!a||!i)return null;const p=t.getBoundingClientRect(),h=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||p.width)),m=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||p.height)),f=r.scrollX||a.documentElement.scrollLeft||a.body?.scrollLeft||0,S=r.scrollY||a.documentElement.scrollTop||a.body?.scrollTop||0,x=a.body,b=Math.max(m,i.scrollHeight||0,x?.scrollHeight||0),k=Math.min(2,Math.max(1,window.devicePixelRatio||1)),d=i.style.scrollBehavior,A=x?.style.scrollBehavior??"";i.style.scrollBehavior="auto",x&&(x.style.scrollBehavior="auto");let D="",L=()=>{};try{await a.fonts?.ready.catch(()=>{}),L=await rr(a,h,m,{applyLayoutWorkarounds:!0}),r.scrollTo(f,S);const{getFontEmbedCSS:X,toJpeg:I}=await Qe(async()=>{const{getFontEmbedCSS:w,toJpeg:N}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:w,toJpeg:N}},[]),P=await X(i).catch(()=>"");D=await I(i,{quality:.82,pixelRatio:k,width:h,height:m,backgroundColor:Zs(a),imagePlaceholder:Rt,fontEmbedCSS:P||void 0,style:{transform:`translate(${-f}px, ${-S}px)`,transformOrigin:"top left",minWidth:`${h}px`,minHeight:`${b}px`},cacheBust:!0})}finally{L(),r.scrollTo(f,S),i.style.scrollBehavior=d,x&&(x.style.scrollBehavior=A)}const H=D.split(",",2)[1]||"";return H?await On(H,h,m,h,m,n):null}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot:",r),null}}const hl=ot(()=>Qe(()=>import("./DiffView-k3lX2PiV.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}))),pl=ot(()=>Qe(()=>import("./FilesView-C39IOFfs.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,127])).then(t=>({default:t.FilesView}))),ml=ot(()=>Qe(()=>import("./GitView-CkztSaT7.js"),__vite__mapDeps([128,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,129,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}))),fl=380,gl=1400,or=600,xl=100,wl=24,Zt=new Map,vs=200,bl=(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",yl=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),o=n.startsWith("//");let r=n.replace(/\/+$/g,"");return r=r.replace(/\/+/g,"/"),o&&!r.startsWith("//")&&(r=`/${r}`),r===""?n.startsWith("/")?"/":"":r},js=t=>Number.isFinite(t)?Math.min(gl,Math.max(fl,Math.round(t))):or,vl=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},jl=(t,n)=>{if(!t)return"";const o=t.replace(/\\/g,"/"),r=n.replace(/\\/g,"/").replace(/\/+$/,"");return r&&o.startsWith(r+"/")?o.slice(r.length+1):o},ar=(t,n=null)=>t==="chat"?"Chat":t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?Rn(n).label:t==="notes"?"Project notes":t==="terminal"?"Terminal":"Context",Sl=t=>{if(!t)return null;const n=t.replace(/\\/g,"/").trim();if(!n)return null;const o=n.split("/").filter(Boolean);return o.length===0?n:o[o.length-1]||null},Al=(t,n,o=null)=>{if(t.mode==="chat"){const r=Jt(t.dedupeKey);if(r){const i=n.get(r)?.trim();if(i)return i}const a=t.sessionTitleFallback?.trim();return a||"Chat"}if(t.label)return t.label;if(t.mode==="file")return Sl(t.targetPath)||"Files";if(t.mode==="preview"){const r=t.targetPath;if(r)try{const a=new URL(r);return a.host||a.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":ar(t.mode,o)},Ss=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(Pn,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(Wa,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(C,{name:Rn(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="notes")return e.jsx(C,{name:"sticky-note",className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(C,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(C,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="chat")return e.jsx(C,{name:"chat-4",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(C,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(C,{name:"global",className:"h-3.5 w-3.5"})},Cl=200,kl=480,Nl=({visible:t})=>{const n=z(D=>D.contextEditorTreeWidth),o=z(D=>D.setContextEditorTreeWidth),[r,a]=s.useState(!1),i=s.useRef(0),p=s.useRef(n),h=s.useRef(null),m=s.useRef(null),f=s.useRef(null),S=s.useCallback(D=>Math.min(kl,Math.max(Cl,Math.round(D))),[]),x=s.useCallback(D=>{const L=f.current;L&&(L.style.width=`${D}px`,L.style.setProperty("--oc-editor-tree-width",`${D}px`))},[]),b=D=>{if(t){try{D.currentTarget.setPointerCapture(D.pointerId)}catch{}m.current=D.pointerId,a(!0),i.current=D.clientX,p.current=n,h.current=n,D.preventDefault()}},k=D=>{if(!r||m.current!==D.pointerId)return;const L=i.current-D.clientX,H=S(p.current+L);h.current!==H&&(h.current=H,x(H))},d=D=>{if(m.current!==D.pointerId)return;try{D.currentTarget.releasePointerCapture(D.pointerId)}catch{}const L=S(h.current??n);m.current=null,h.current=null,a(!1),o(L)},A=t?n:0;return e.jsxs("div",{ref:f,className:ge("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:`${r?h.current??A:A}px`,"--oc-editor-tree-width":`${r?h.current??n:n}px`,overflowX:"clip",transitionProperty:r?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&e.jsx("div",{className:ge("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",r&&"bg-[var(--interactive-border)]"),onPointerDown:b,onPointerMove:k,onPointerUp:d,onPointerCancel:d,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:ge("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",r&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,children:e.jsx(Ni,{})})]})},Jt=t=>!t||!t.startsWith("session:")?null:t.slice(8).trim()||null,Pl=(t,n)=>{if(t.size!==n.size)return!1;for(const[o,r]of t)if(n.get(o)!==r)return!1;return!0},Rl=(t,n)=>{if(n.length===0)return Zt;const o=new Set(n),r=new Map;for(const a of t){if(!o.has(a.id))continue;const i=a.title?.trim();i&&r.set(a.id,i)}return r.size===0?Zt:r},El=(t,n)=>{const o=Bs(),r=s.useRef(Zt),a=s.useRef(n);return a.current=n,s.useSyncExternalStore(o.subscribe,s.useCallback(()=>{const i=Rl(o.getState().session,a.current);return Pl(r.current,i)?r.current:(r.current=i,i)},[o]),()=>Zt)},ir=`new Promise((resolve) => {
|
|
5
|
-
const existing = document.getElementById('__pichamber_desktop_browser_overlay');
|
|
6
|
-
if (existing) existing.remove();
|
|
7
|
-
if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
|
|
8
|
-
try { window.__pichamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
|
|
9
|
-
}
|
|
10
|
-
const overlay = document.createElement('div');
|
|
11
|
-
overlay.id = '__pichamber_desktop_browser_overlay';
|
|
12
|
-
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;';
|
|
13
|
-
document.documentElement.appendChild(overlay);
|
|
14
|
-
const cssEscape = (value) => {
|
|
15
|
-
try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
|
|
16
|
-
};
|
|
17
|
-
const selectorPart = (element) => {
|
|
18
|
-
const tag = element.tagName.toLowerCase();
|
|
19
|
-
if (element.id) return tag + '#' + cssEscape(element.id);
|
|
20
|
-
const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
|
|
21
|
-
return tag + className;
|
|
22
|
-
};
|
|
23
|
-
const metadata = (element) => {
|
|
24
|
-
const rect = element.getBoundingClientRect();
|
|
25
|
-
const style = getComputedStyle(element);
|
|
26
|
-
const ancestry = [];
|
|
27
|
-
let current = element;
|
|
28
|
-
while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
|
|
29
|
-
ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
|
|
30
|
-
current = current.parentElement;
|
|
31
|
-
}
|
|
32
|
-
const attrs = {};
|
|
33
|
-
for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
|
|
34
|
-
const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
|
|
35
|
-
return {
|
|
36
|
-
frame: 'top',
|
|
37
|
-
tag: element.tagName.toLowerCase(),
|
|
38
|
-
text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
|
|
39
|
-
selector: element.id ? '#' + cssEscape(element.id) : path,
|
|
40
|
-
path,
|
|
41
|
-
bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
42
|
-
center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
|
|
43
|
-
attributes: attrs,
|
|
44
|
-
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 },
|
|
45
|
-
ancestry,
|
|
46
|
-
};
|
|
47
|
-
};
|
|
48
|
-
const move = (event) => {
|
|
49
|
-
const element = document.elementFromPoint(event.clientX, event.clientY);
|
|
50
|
-
if (!element || element === overlay || element === document.documentElement || element === document.body) return;
|
|
51
|
-
const rect = element.getBoundingClientRect();
|
|
52
|
-
overlay.style.display = 'block';
|
|
53
|
-
overlay.style.left = rect.left + 'px';
|
|
54
|
-
overlay.style.top = rect.top + 'px';
|
|
55
|
-
overlay.style.width = rect.width + 'px';
|
|
56
|
-
overlay.style.height = rect.height + 'px';
|
|
57
|
-
};
|
|
58
|
-
const cleanup = () => {
|
|
59
|
-
window.removeEventListener('mousemove', move, true);
|
|
60
|
-
window.removeEventListener('click', click, true);
|
|
61
|
-
window.removeEventListener('keydown', keydown, true);
|
|
62
|
-
if (window.__pichamberDesktopBrowserCancelInspect === cancel) {
|
|
63
|
-
delete window.__pichamberDesktopBrowserCancelInspect;
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
const cancel = () => {
|
|
67
|
-
cleanup();
|
|
68
|
-
overlay.remove();
|
|
69
|
-
resolve(null);
|
|
70
|
-
};
|
|
71
|
-
const click = (event) => {
|
|
72
|
-
event.preventDefault();
|
|
73
|
-
event.stopPropagation();
|
|
74
|
-
const element = document.elementFromPoint(event.clientX, event.clientY);
|
|
75
|
-
const result = element ? metadata(element) : null;
|
|
76
|
-
cleanup();
|
|
77
|
-
overlay.remove();
|
|
78
|
-
resolve(result);
|
|
79
|
-
};
|
|
80
|
-
const keydown = (event) => {
|
|
81
|
-
if (event.key !== 'Escape') return;
|
|
82
|
-
cancel();
|
|
83
|
-
};
|
|
84
|
-
window.__pichamberDesktopBrowserCancelInspect = cancel;
|
|
85
|
-
window.addEventListener('mousemove', move, true);
|
|
86
|
-
window.addEventListener('click', click, true);
|
|
87
|
-
window.addEventListener('keydown', keydown, true);
|
|
88
|
-
});`,qt=`(() => {
|
|
89
|
-
if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
|
|
90
|
-
window.__pichamberDesktopBrowserCancelInspect();
|
|
91
|
-
return;
|
|
92
|
-
}
|
|
93
|
-
const overlay = document.getElementById('__pichamber_desktop_browser_overlay');
|
|
94
|
-
if (overlay) overlay.remove();
|
|
95
|
-
})()`,Tl=`(() => {
|
|
96
|
-
if (window.__pichamberSameWebviewNavigationInstalled) return;
|
|
97
|
-
window.__pichamberSameWebviewNavigationInstalled = true;
|
|
98
|
-
|
|
99
|
-
const navigate = (rawUrl) => {
|
|
100
|
-
if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
|
|
101
|
-
try {
|
|
102
|
-
const url = new URL(rawUrl, window.location.href);
|
|
103
|
-
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
104
|
-
window.location.assign(url.href);
|
|
105
|
-
return true;
|
|
106
|
-
} catch (_error) {
|
|
107
|
-
return false;
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
|
|
111
|
-
const originalOpen = window.open.bind(window);
|
|
112
|
-
window.open = (url, target, features) => {
|
|
113
|
-
if (navigate(url)) return null;
|
|
114
|
-
return originalOpen(url, target, features);
|
|
115
|
-
};
|
|
116
|
-
|
|
117
|
-
document.addEventListener('click', (event) => {
|
|
118
|
-
if (event.defaultPrevented) return;
|
|
119
|
-
const target = event.target;
|
|
120
|
-
if (!(target instanceof Element)) return;
|
|
121
|
-
const anchor = target.closest('a[target="_blank"][href]');
|
|
122
|
-
if (!(anchor instanceof HTMLAnchorElement)) return;
|
|
123
|
-
if (!navigate(anchor.href)) return;
|
|
124
|
-
event.preventDefault();
|
|
125
|
-
event.stopPropagation();
|
|
126
|
-
}, true);
|
|
127
|
-
})()`,Ft=t=>{const n=t.trim();if(!n)return"about:blank";try{const o=new URL(n.includes("://")?n:`https://${n}`);return o.protocol!=="http:"&&o.protocol!=="https:"?"about:blank":o.toString()}catch{return"about:blank"}},As=async(t,n)=>{const o=t.contentWindow;if(!o)throw new Error("Iframe window is not available");const a=o.eval.call(o,n);return await Promise.resolve(a)},Il=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,lr=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Cs=(t,n,o)=>{const r=lr(n);t.postMessage(o,r)},Dl=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}},ks=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}},Ml=({rawUrl:t,onNavigate:n})=>{const{currentTheme:o}=Nn(),[r,a]=s.useReducer(E=>E+1,0),[i,p]=s.useReducer(E=>E+1,0),[h,m]=s.useState({status:"idle"}),[f,S]=s.useState(""),x=s.useRef(null),b=s.useRef(1),[k,d]=s.useState(!1),[A,D]=s.useState(!1),[L,H]=s.useState("all"),[X,I]=s.useState([]),[P,w]=s.useState(!1),[N,W]=s.useState(null),y=Fe(E=>E.currentSessionId),Q=Fe(E=>E.newSessionDraft?.open),O=Ht(),Y=En(E=>E.addDraft),J=Tn(E=>E.addAttachedFile);let _=null;try{_=t?new URL(t):null}catch{_=null}const M=_?_.hostname==="localhost"||_.hostname==="127.0.0.1"||_.hostname==="::1"||_.hostname==="[::1]"||_.hostname==="0.0.0.0":!1,K=_?_.hostname==="0.0.0.0"?new URL(_.toString().replace("0.0.0.0","127.0.0.1")):_:null,ne=K?K.toString():"",ue=ne?`${Et()||"same-origin"}|${ne}`:"",xe=o.metadata.variant;s.useEffect(()=>{if(!ne||!M){m({status:"idle"});return}const E=_n(ue);if(E?.previewToken){m({status:"ready",proxyBasePath:E.proxyBasePath,previewToken:E.previewToken,expiresAt:E.expiresAt});return}E&&Ye.delete(ue);let ie=!1;return m({status:"loading"}),(async()=>{try{const he=await it("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:ne})});if(!he.ok){Ye.delete(ue);const _e=await he.json().catch(()=>({})),v=typeof _e?.error=="string"?_e.error:`HTTP ${he.status}`;ie||m({status:"error",message:v});return}const g=await he.json(),j=typeof g.proxyBasePath=="string"?g.proxyBasePath:"",te=typeof g.previewToken=="string"?g.previewToken:"",ye=typeof g.expiresAt=="number"?g.expiresAt:0;if(!j||!te){Ye.delete(ue),ie||m({status:"error",message:"Could not start preview proxy."});return}Ye.set(ue,{proxyBasePath:j,previewToken:te,expiresAt:ye}),ie||m({status:"ready",proxyBasePath:j,previewToken:te,expiresAt:ye})}catch(he){if(Ye.delete(ue),!ie){const g=he instanceof Error?he.message:String(he);m({status:"error",message:g})}}})(),()=>{ie=!0}},[M,ue,i,ne]);const q=K&&(K.protocol==="http:"||K.protocol==="https:")?K.toString():"",le=M&&h.status==="ready"?`${h.proxyBasePath}|${h.previewToken||""}|${r}`:"";s.useEffect(()=>{if(!le){S("");return}let E=!1;return S(""),Ms(Et()).then(ie=>{!E&&ie&&S(le)}).catch(()=>{}),()=>{E=!0}},[le]);const pe=M&&h.status==="ready"&&K&&f===le?(()=>{const E=K.pathname||"/",ie=new URLSearchParams(K.search);ie.delete("oc_url_token"),ie.delete("oc_client_token"),ie.set("ocPreview",String(r)),ie.set("oc_preview_token",h.previewToken||"");const he=ie.toString(),g=K.hash||"";return Os().authenticatedAsset(`${h.proxyBasePath}${E}${he?`?${he}`:""}${g}`)})():"",we=M?pe:q,me=M?Dl(pe):q,Pe=M&&(h.status==="loading"||h.status==="idle"||f!==le),ve=M&&h.status==="error",Se=s.useCallback(E=>{const ie=y??(Q?"draft":null);if(!ie||!O){ce.error("Open a chat session before attaching preview annotations");return}const he=t||we||"",g=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},j=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let te=!1;try{const ye=x.current,_e=ye?await Qs(ye,E):null;_e&&(await J(_e),te=!0)}catch{te=!1}Y({directory:O,sessionKey:ie},{source:"preview-annotation",fileLabel:he||"preview",startLine:1,endLine:1,code:Mn({pageUrl:he,viewport:g,devicePixelRatio:j,target:E,screenshotAttached:te,intro:"This is a selected DOM element from the in-app preview."}),language:"markdown",text:""}),ce.success("Preview annotation attached to chat")})()},[J,Y,y,O,we,Q,t]);s.useEffect(()=>{d(!1),I([]),D(!1),H("all"),w(!1),W(null),b.current=1},[we]),s.useEffect(()=>{const E=x.current?.contentWindow;!k||!E||Cs(E,pe,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:P})},[k,P,pe]),s.useEffect(()=>{const E=x.current?.contentWindow;!k||!E||Cs(E,pe,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:xe})},[k,xe,pe]),s.useEffect(()=>{if(!P||typeof window>"u")return;const E=ie=>{ie.key==="Escape"&&(ie.preventDefault(),ie.stopImmediatePropagation(),w(!1))};return window.addEventListener("keydown",E,!0),()=>window.removeEventListener("keydown",E,!0)},[P]),s.useEffect(()=>{if(!M||typeof window>"u")return;const E=g=>{if(typeof g=="string")return g;if(g==null)return"";try{return JSON.stringify(g)}catch{return String(g)}},ie=g=>{const j=b.current;b.current+=1,I(te=>{const ye=[...te,{...g,id:j}];return ye.length>vs?ye.slice(ye.length-vs):ye})},he=g=>{if(g.source!==x.current?.contentWindow)return;const j=g.data;if(!(!j||j.source!=="pichamber-preview-bridge"||j.version!==1)){if(j.type==="ready"){d(!0);return}if(j.type==="console"){const te=j.level==="error"||j.level==="warn"||j.level==="info"||j.level==="debug"?j.level:"log",ye=Array.isArray(j.args)?j.args.map(E).filter(Boolean):[];ie({level:te,message:ye.join(" "),ts:typeof j.ts=="number"?j.ts:Date.now()});return}if(j.type==="runtime-error"){const te=E(j.filename),ye=typeof j.line=="number"?j.line:null,_e=typeof j.column=="number"?j.column:null,v=te?`${te}${ye!==null?`:${ye}${_e!==null?`:${_e}`:""}`:""}`:"",B=E(j.stack);ie({level:"runtime",message:E(j.message)||"Runtime error",details:[v,B].filter(Boolean).join(`
|
|
128
|
-
`),ts:typeof j.ts=="number"?j.ts:Date.now()});return}if(j.type==="resource-error"){const te=E(j.tag)||"resource",ye=E(j.url);ie({level:"resource",message:ye?`${te}: ${ye}`:te,details:E(j.outerHTML),ts:typeof j.ts=="number"?j.ts:Date.now()});return}if(j.type==="hover"){W(Pt(j.target)?j.target:null);return}if(j.type==="select"&&Pt(j.target)){W(j.target),w(!1),Se(j.target);return}if(j.type==="navigate-preview"){const te=typeof j.url=="string"?j.url:"",ye=j.navigation==="external"?"external":"proxy";if(te&&ye==="external"){Ut(te);return}te&&n(te)}}};return window.addEventListener("message",he),()=>{window.removeEventListener("message",he)}},[Se,M,n]);const fe=X.filter(E=>E.level==="error"||E.level==="runtime"||E.level==="resource").length,Z=X.filter(E=>bl(E,L)),Ee=s.useCallback(()=>{const E=[`Preview URL: ${t||we||""}`,`Events: ${X.length}`,""].join(`
|
|
129
|
-
`),ie=X.map(he=>{const g=new Date(he.ts).toISOString(),j=he.details?`
|
|
130
|
-
${he.details}`:"";return`[${g}] [${he.level}] ${he.message}${j}`}).join(`
|
|
131
|
-
`);mt(`${E}${ie}`).then(he=>{he.ok?ce.success("Preview console copied"):ce.error("Failed to copy preview console")})},[X,we,t]),U=s.useCallback(()=>{const E=y??(Q?"draft":null);if(!E||!O){ce.error("Open a chat session before attaching preview logs");return}const ie=[`Preview URL: ${t||we||""}`,`Events: ${X.length}`,""].join(`
|
|
132
|
-
`),he=X.map(g=>{const j=new Date(g.ts).toISOString(),te=g.details?`
|
|
133
|
-
${g.details}`:"";return`[${j}] [${g.level}] ${g.message}${te}`}).join(`
|
|
134
|
-
`);Y({directory:O,sessionKey:E},{source:"preview-console",fileLabel:t||we||"preview",startLine:1,endLine:Math.max(1,X.length),code:`${ie}${he}`,language:"text",text:"These are browser console logs from the dev server running for this project."}),ce.success("Preview console attached to chat")},[Y,X,y,O,we,Q,t]),[G,ee]=s.useState("unknown"),ae=s.useRef(0),de=s.useRef(0),Ae=s.useRef(""),je=s.useRef(""),ke=15e3;s.useEffect(()=>{if(!pe){ee("unknown"),Ae.current="",ae.current=0,de.current=0;return}let E=!1,ie=null;Ae.current!==ue&&(Ae.current=ue,ae.current=Date.now(),de.current=0);const he=g=>{ie=setTimeout(()=>{E||a()},g)};return ee("unknown"),(async()=>{const j=await(async()=>{try{return await it(pe,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(E)return;if(!j){ee("unreachable"),he(5e3);return}const te=Xi(j.headers,je.current===ue);if(te!=="none"){if(Ye.delete(ue),te==="retry-registration")je.current=ue,m({status:"loading"}),p();else{const v=await j.json().catch(()=>({}));if(E)return;const B=typeof v?.error=="string"?v.error:`HTTP ${j.status}`;m({status:"error",message:B})}return}if(j.status!==502){je.current="",ee("reachable");return}const ye=ae.current||Date.now();if(Date.now()-ye<ke){ee("starting"),de.current+=1;const v=de.current,B=Math.min(2e3,250*Math.pow(2,Math.min(4,v)));he(B);return}ee("unreachable"),he(5e3)})(),()=>{E=!0,ie&&clearTimeout(ie)}},[ue,pe,r]);const Be=M&&h.status==="ready"&&(G==="unknown"||G==="starting"),Me=M&&h.status==="ready"&&G==="unreachable",Oe=s.useCallback(E=>{if(!M||h.status!=="ready"||typeof window>"u")return;const ie=E.currentTarget.contentWindow;if(ie)try{const he=ie.location,g=lr(pe);if(he.origin!==g||he.pathname.startsWith(h.proxyBasePath))return;const j=`${h.proxyBasePath}${he.pathname}${he.search}${he.hash}`;ie.location.replace(j)}catch{}},[M,pe,h]);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:me||t,children:me||t||"No preview URL"}),e.jsx(Ce,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:"Reload preview","aria-label":"Reload preview",disabled:!we,children:e.jsx(C,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{q&&Ut(q)},title:"Open in browser","aria-label":"Open in browser",disabled:!q,children:e.jsx(C,{name:"external-link",className:"h-3.5 w-3.5"})}),M?e.jsx(Ce,{type:"button",size:"sm",variant:P?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>w(E=>!E),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!k,children:e.jsx(C,{name:"cursor",className:"h-3.5 w-3.5"})}):null,M?e.jsxs(Ce,{type:"button",size:"sm",variant:A?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>D(E=>!E),title:k?"Open preview console":"Waiting for preview console","aria-label":k?"Open preview console":"Waiting for preview console",disabled:!k&&X.length===0,children:[e.jsx(C,{name:"terminal-box",className:"h-3.5 w-3.5"}),fe>0?e.jsx("span",{className:"typography-micro text-status-error",children:fe}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[Be?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."})]}):Me?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(Ce,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:"Retry"})]}):we&&(!M||G==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:x,src:we,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:xe},onLoad:Oe,sandbox:M?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${we}:${r}`),P&&N?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:N.bounds.x,top:N.bounds.y,width:N.bounds.width,height:N.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:[N.tag,N.text?` · ${N.text}`:""]})}):null]}):Pe?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):ve?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."}),h.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:h.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."}),A?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(Ce,{type:"button",size:"xs",variant:"ghost",onClick:U,disabled:X.length===0,children:"Attach"}),e.jsx(Ce,{type:"button",size:"xs",variant:"ghost",onClick:Ee,disabled:X.length===0,children:"Copy"}),e.jsx(Ce,{type:"button",size:"xs",variant:"ghost",onClick:()=>I([]),disabled:X.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(E=>e.jsx(Ce,{type:"button",size:"xs",variant:L===E?"secondary":"ghost",onClick:()=>H(E),children:E==="all"?"All":E==="errors"?"Errors":E==="warnings"?"Warnings":"Logs"},E))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:X.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):Z.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):Z.map(E=>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:ge("shrink-0 uppercase",E.level==="error"||E.level==="runtime"||E.level==="resource"?"text-status-error":E.level==="warn"?"text-status-warning":"text-muted-foreground"),children:E.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:E.message})]})},E.id))})]}):null]})]})},Ol=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,_l=({initialUrl:t,directory:n,tabID:o})=>{const r=s.useRef(null),a=z(U=>U.setContextPanelTabTargetPath),i=Ft(t),p=i!=="about:blank"?i:"",[h,m]=s.useState(p),[f,S]=s.useState(p),[x,b]=s.useState(p),[k,d]=s.useState(()=>p?[p]:[]),[A,D]=s.useState(()=>p?0:-1),[L,H]=s.useReducer(U=>U+1,0),[X,I]=s.useState(!!p),[P,w]=s.useState(!1),[N,W]=s.useState(null),[y,Q]=s.useState({status:"idle"}),[O,Y]=s.useState(""),J=Fe(U=>U.currentSessionId),_=Fe(U=>U.newSessionDraft?.open),M=En(U=>U.addDraft),K=Tn(U=>U.addAttachedFile),ne=s.useCallback(U=>{!U||U==="about:blank"||!n||!o||a(n,o,U)},[n,o,a]),ue=s.useCallback((U,G)=>{const ee=Ft(U),ae=ee!=="about:blank"?ee:"";S(ae),m(ae),G?.inFrame?I(!1):(b(ae),I(!!ae)),ne(ae),d(de=>{if(!ae)return D(-1),[];if(G?.replaceHistory)return de;const Ae=A>=0?de.slice(0,A+1):[];if(Ae[Ae.length-1]===ae)return D(Ae.length-1),Ae;const ke=[...Ae,ae];return D(ke.length-1),ke})},[A,ne]),xe=s.useCallback(U=>{const G=k[U];G&&(D(U),S(G),b(G),m(G),I(!0),ne(G))},[k,ne]),q=s.useCallback(()=>{if(f){I(!0);try{r.current?.contentWindow?.location.reload()}catch{H()}}},[f]);s.useEffect(()=>{if(!x){Q({status:"idle"});return}const U=Qi(x),G=_n(U);if(G?.previewToken){Q({status:"ready",proxyBasePath:G.proxyBasePath,previewToken:G.previewToken,expiresAt:G.expiresAt});return}G&&Ye.delete(U);let ee=!1;return Q({status:"loading"}),I(!0),(async()=>{try{const ae=await it("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:x,allowExternal:!0})});if(!ae.ok){const Be=await ae.json().catch(()=>({})),Me=typeof Be?.error=="string"?Be.error:`HTTP ${ae.status}`;ee||Q({status:"error",message:Me});return}const de=await ae.json(),Ae=typeof de.proxyBasePath=="string"?de.proxyBasePath:"",je=typeof de.previewToken=="string"?de.previewToken:"",ke=typeof de.expiresAt=="number"?de.expiresAt:0;if(!Ae||!je){ee||Q({status:"error",message:"Could not start preview proxy."});return}Ye.set(U,{proxyBasePath:Ae,previewToken:je,expiresAt:ke}),ee||Q({status:"ready",proxyBasePath:Ae,previewToken:je,expiresAt:ke})}catch(ae){if(!ee){const de=ae instanceof Error?ae.message:String(ae);Q({status:"error",message:de})}}})(),()=>{ee=!0}},[x]);const le=x&&y.status==="ready"?`${y.proxyBasePath}|${y.previewToken||""}|${L}`:"";s.useEffect(()=>{if(!le){Y("");return}let U=!1;return Y(""),Ms(Et()).then(G=>{!U&&G&&Y(le)}).catch(()=>{}),()=>{U=!0}},[le]);const pe=s.useMemo(()=>{if(O!==le||!x||y.status!=="ready")return"";try{const U=new URL(x),G=U.pathname||"/",ee=new URLSearchParams(U.search);ee.delete("oc_url_token"),ee.delete("oc_client_token"),ee.set("ocPreview",String(L)),ee.set("oc_preview_token",y.previewToken||"");const ae=ee.toString();return Os().authenticatedAsset(`${y.proxyBasePath}${G}${ae?`?${ae}`:""}${U.hash}`)}catch{return""}},[x,y,le,L,O]),we=pe||(y.status==="error"?x:""),me=s.useCallback(U=>{if(!U||!x||y.status!=="ready")return"";try{const G=new URL(U,window.location.origin),ee=y.proxyBasePath.endsWith("/")?y.proxyBasePath.slice(0,-1):y.proxyBasePath;if(G.origin!==window.location.origin||!G.pathname.startsWith(ee))return"";const ae=G.pathname.slice(ee.length)||"/",de=new URL(x).origin;return ks(new URL(`${ae}${G.search}${G.hash}`,de).toString())}catch{return""}},[x,y]),Pe=s.useCallback(U=>{if(!U||!x||y.status!=="ready")return"";try{const G=new URL(U,window.location.origin),ee=new URL(x).origin;if(G.origin!==window.location.origin||ee===window.location.origin)return"";const ae=y.proxyBasePath.endsWith("/")?y.proxyBasePath.slice(0,-1):y.proxyBasePath;return G.pathname.startsWith(ae)?"":ks(new URL(`${G.pathname}${G.search}${G.hash}`,ee).toString())}catch{return""}},[x,y]),ve=s.useCallback(U=>{const G=r.current?.contentWindow;G&&G.postMessage({source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:U},window.location.origin)},[]),Se=s.useCallback(async U=>{const G=J??(_?"draft":null);if(!G){ce.error("Open a chat session before attaching preview annotations");return}const ee=r.current,ae=ee?.contentWindow,de=ee?.getBoundingClientRect(),Ae={width:Number.isFinite(ae?.innerWidth)?ae?.innerWidth??de?.width??0:de?.width??0,height:Number.isFinite(ae?.innerHeight)?ae?.innerHeight??de?.height??0:de?.height??0},je=ee?await Qs(ee,U):null,ke=!!je;je&&await K(je),M({directory:n,sessionKey:G},{source:"preview-annotation",fileLabel:f||"browser",startLine:1,endLine:1,code:Mn({pageUrl:f,viewport:Ae,devicePixelRatio:window.devicePixelRatio||1,target:U,screenshotAttached:ke,intro:ke?"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:""}),ce.success("Preview annotation attached to chat")},[K,M,J,f,n,_]),fe=s.useCallback(()=>{const U=r.current;W(null),ve(!1),U&&As(U,qt).catch(()=>{})},[ve]);s.useEffect(()=>{if(!P)return;const U=G=>{G.key==="Escape"&&(G.preventDefault(),G.stopImmediatePropagation(),w(!1),fe())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[fe,P]),s.useEffect(()=>()=>fe(),[fe]),s.useEffect(()=>{const U=G=>{if(G.source!==r.current?.contentWindow)return;const ee=G.data;if(!(!ee||ee.source!=="pichamber-preview-bridge"||ee.version!==1)){if(ee.type==="ready"){const ae=typeof ee.url=="string"?ee.url:"",de=me(ae);de&&de!==f&&ue(de,{inFrame:!0});return}if(ee.type==="hover"){W(Pt(ee.target)?ee.target:null);return}if(ee.type==="select"&&Pt(ee.target)){W(null),w(!1),ve(!1),Se(ee.target);return}if(ee.type==="navigate-preview"){const ae=typeof ee.url=="string"?ee.url:"",de=Pe(ae);if(de){ue(de);return}ae&&ue(ae)}}};return window.addEventListener("message",U),()=>window.removeEventListener("message",U)},[ue,Se,f,me,Pe,ve]);const Z=s.useCallback(()=>{const U=r.current;if(!(!U||!f)){if(P){w(!1),fe();return}if(pe){W(null),w(!0),ve(!0);return}w(!0),(async()=>{try{const G=await As(U,ir);if(w(!1),!G||!Pt(G))return;await Se(G)}catch{w(!1),ce.error("This page cannot be inspected from the browser panel.")}})()}},[Se,fe,f,P,ve,pe]),Ee=s.useCallback(()=>{try{const U=r.current?.contentWindow?.location.href||"",G=Pe(U);if(G){ue(G,{inFrame:!0});return}}catch{}I(!1),P&&pe&&ve(!0)},[ue,Pe,P,ve,pe]);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(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:A<=0,onClick:()=>xe(A-1),children:e.jsx(C,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:A<0||A>=k.length-1,onClick:()=>xe(A+1),children:e.jsx(C,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!f,onClick:q,children:e.jsx(C,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:U=>{U.preventDefault(),ue(h)},children:e.jsx("input",{value:h,onChange:U=>m(U.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(Ce,{type:"button",variant:P?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!f,onClick:Z,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(C,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!f,onClick:()=>{Ut(f)},children:e.jsx(C,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[we?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("iframe",{ref:r,src:we,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:Ee},`${o}:${L}`),P&&N?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:N.bounds.x,top:N.bounds.y,width:N.bounds.width,height:N.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:[N.tag,N.text?` · ${N.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($s,{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."})]}),X?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Ll=({initialUrl:t,directory:n,tabID:o})=>{const r=s.useRef(null),a=z(y=>y.setContextPanelTabTargetPath),i=Ft(t),p=i!=="about:blank"?i:"",h=s.useRef(Ft(t)),[m,f]=s.useState(p),[S,x]=s.useState(p),[b,k]=s.useState(!1),[d,A]=s.useState(!0),D=s.useRef(null),L=d,H=s.useCallback(y=>{!y||y==="about:blank"||!n||!o||a(n,o,y)},[n,o,a]),X=Fe(y=>y.currentSessionId),I=Fe(y=>y.newSessionDraft?.open),P=En(y=>y.addDraft),w=Tn(y=>y.addAttachedFile);s.useEffect(()=>{const y=r.current;if(!y)return;const Q=()=>{try{const K=y.getURL();K&&K!=="about:blank"&&(x(K),f(K),H(K))}catch{}},O=K=>{const ne=K.detail;typeof ne?.url=="string"&&ne.url&&(x(ne.url),f(ne.url),H(ne.url))},Y=()=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>A(!0),200)},J=()=>{D.current&&clearTimeout(D.current),A(!1),Q()},_=K=>{const ne=K.detail;if(ne?.disposition==="new-window"||ne?.disposition==="foreground-tab"||ne?.disposition==="background-tab"){K.preventDefault();const ue=r.current;typeof ue?.loadURL=="function"&&ne.url&&ue.loadURL(ne.url)}},M=()=>{try{y.executeJavaScript?.(Tl,!0).catch(()=>{})}catch{}};y.addEventListener("did-navigate",O),y.addEventListener("did-navigate-in-page",O),y.addEventListener("did-start-loading",Y),y.addEventListener("did-stop-loading",J),y.addEventListener("new-window",_),y.addEventListener("dom-ready",M);try{y.isLoading()||(A(!1),Q())}catch{}return M(),()=>{D.current&&clearTimeout(D.current),y.removeEventListener("did-navigate",O),y.removeEventListener("did-navigate-in-page",O),y.removeEventListener("did-start-loading",Y),y.removeEventListener("did-stop-loading",J),y.removeEventListener("new-window",_),y.removeEventListener("dom-ready",M)}},[H]),s.useEffect(()=>{const y=setTimeout(()=>A(!1),3e4);return()=>clearTimeout(y)},[]),s.useEffect(()=>{if(!b)return;const y=Q=>{if(Q.key!=="Escape")return;Q.preventDefault(),Q.stopImmediatePropagation(),k(!1);const O=r.current;try{O?.executeJavaScript?.(qt).catch(()=>{})}catch{}};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[b]),s.useEffect(()=>{const y=r.current;return()=>{try{const Q=y?.getURL?.();Q&&Q!=="about:blank"&&a(n,o,Q)}catch{}try{y?.executeJavaScript?.(qt).catch(()=>{})}catch{}}},[n,o,a]);const N=s.useCallback(y=>{const Q=r.current;if(typeof Q?.loadURL!="function")return;const O=Ft(y);try{Q.loadURL(O)}catch{}},[]),W=s.useCallback(()=>{const y=r.current;if(y){if(b){k(!1);try{y.executeJavaScript?.(qt).catch(()=>{})}catch{}return}k(!0),y.executeJavaScript?.(ir,!0).then(async Q=>{if(k(!1),!Q||!Pt(Q))return;const O=X??(I?"draft":null);if(!O){ce.error("Open a chat session before attaching preview annotations");return}const Y=typeof y.getWebContentsId=="function"?y.getWebContentsId():null;if(Y==null)return;const J=await Eo("desktop_browser_capture_page",{webContentsId:Y}),_=await y.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),M=Number.isFinite(_?.width)?_.width:J.width,K=Number.isFinite(_?.height)?_.height:J.height,ne=await On(J.base64,J.width,J.height,M,K,Q),ue=!!ne;ne&&await w(ne),P({directory:n,sessionKey:O},{source:"preview-annotation",fileLabel:S||"browser",startLine:1,endLine:1,code:Mn({pageUrl:S,viewport:{width:M,height:K},devicePixelRatio:window.devicePixelRatio||1,target:Q,screenshotAttached:ue,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:""}),ce.success("Preview annotation attached to chat")}).catch(()=>k(!1))}},[w,P,X,S,n,b,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(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{r.current?.goBack?.()}catch{}},children:e.jsx(C,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{r.current?.goForward?.()}catch{}},children:e.jsx(C,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{r.current?.reload?.()}catch{}},children:e.jsx(C,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:y=>{y.preventDefault(),N(m)},children:e.jsx("input",{value:m,onChange:y=>f(y.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),e.jsx(Ce,{type:"button",variant:b?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:W,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(C,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{Ut(S)},children:e.jsx(C,{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:r,src:h.current,partition:"persist:pichamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!S||S==="about:blank")&&!d?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($s,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,L?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Bl=()=>{const t=Ht()??"",n=s.useMemo(()=>yl(t),[t]),o=z(l=>n?l.contextPanelByDirectory[n]:void 0),r=z(l=>l.closeContextPanel),a=z(l=>l.closeContextPanelTab),i=z(l=>l.openContextPanelTab),p=z(l=>l.toggleContextPanelExpanded),h=z(l=>l.setContextPanelWidth),m=z(l=>l.setActiveContextPanelTab),f=z(l=>l.reorderContextPanelTabs),S=rt(l=>l.setSelectedPath),x=z(l=>l.openContextPreview),b=z(l=>l.contextEditorTreeVisible),k=z(l=>l.toggleContextEditorTree),d=z(l=>l.allowPromptingSubagentSessions),{themeMode:A,setThemeMode:D,lightThemeId:L,darkThemeId:H,currentTheme:X}=Nn(),I=s.useMemo(()=>o?.tabs??[],[o?.tabs]),P=I.find(l=>l.id===o?.activeTabId)??I[I.length-1]??null,w=!!(o?.isOpen&&P),N=!!(w&&o?.expanded),[W,y]=s.useState(null),Q=o?.width,O=To,Y=W??(typeof window<"u"?window.innerWidth:or*2),J=js(Q??Math.round(O*Y)),_=s.useMemo(()=>{const l=[];for(const F of I){if(F.mode!=="chat")continue;const oe=Jt(F.dedupeKey);oe&&!l.includes(oe)&&l.push(oe)}return l},[I]),M=El(n||void 0,_),K=Us(n||null),[ne,ue]=s.useState(!1),xe=s.useRef(0),q=s.useRef(J),le=s.useRef(null),pe=s.useRef(null),we=s.useRef(null),me=s.useRef(new Map),Pe=s.useRef(new Map),ve=s.useRef(!1);s.useLayoutEffect(()=>{const l=we.current?.parentElement;if(!l||typeof ResizeObserver>"u")return;const F=new ResizeObserver(()=>{y(l.clientWidth||null)});return F.observe(l),y(l.clientWidth||null),()=>F.disconnect()},[]),s.useEffect(()=>{if(!w||ve.current){ve.current=w;return}const l=window.requestAnimationFrame(()=>{we.current?.focus({preventScroll:!0})});return ve.current=!0,()=>window.cancelAnimationFrame(l)},[w]);const Se=s.useRef(null),fe=s.useRef(null),Z=s.useCallback(()=>{fe.current=null;const l=we.current,F=le.current;!l||F===null||l.style.setProperty("--oc-context-panel-width",`${F}px`)},[]);s.useEffect(()=>()=>{fe.current!==null&&clearTimeout(fe.current)},[]);const Ee=s.useCallback(l=>{const F=js(l),oe=Se.current;return oe===null?F:Math.min(F,Math.max(1,oe))},[]),U=s.useCallback(l=>{!w||N||!n||(pe.current=l.pointerId,ue(!0),xe.current=l.clientX,q.current=J,le.current=J,Se.current=vl(we.current),document.documentElement.style.cursor="col-resize",l.preventDefault())},[n,N,w,J]),G=s.useCallback(()=>{const l=Ee(le.current??J);le.current=null,Se.current=null,fe.current!==null&&(clearTimeout(fe.current),fe.current=null),document.documentElement.style.cursor="",n&&h(n,l),ue(!1),pe.current=null},[Ee,n,h,J]);s.useEffect(()=>{if(!ne)return;const l=se=>{if(pe.current!==se.pointerId)return;const Ie=xe.current-se.clientX,We=Ee(q.current+Ie);le.current!==We&&(le.current=We,fe.current===null&&(fe.current=setTimeout(Z,xl)))},F=se=>{pe.current===se.pointerId&&G()},oe=()=>{G()};return window.addEventListener("pointermove",l),window.addEventListener("pointerup",F),window.addEventListener("pointercancel",F),window.addEventListener("blur",oe),()=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",F),window.removeEventListener("pointercancel",F),window.removeEventListener("blur",oe)}},[Z,Ee,G,ne]),s.useEffect(()=>{ne||(le.current=null,document.documentElement.style.cursor="")},[ne]);const ee=s.useCallback(()=>{n&&r(n)},[r,n]),ae=s.useCallback(()=>{n&&p(n)},[n,p]),de=s.useCallback(l=>{l.key==="Escape"&&(Co(l.target)||(l.preventDefault(),l.stopPropagation(),ee()))},[ee]);s.useEffect(()=>{if(!(!n||!P)&&P.mode==="file"&&P.targetPath){S(n,P.targetPath,{allowOutsideRoot:!0});return}},[P,n,S]);const Ae=P?.mode==="chat"?P.id:null,je=P?.mode==="chat"?Jt(P.dedupeKey):null;s.useEffect(()=>{if(!w||!n||!je||typeof window>"u")return;const l=()=>{document.visibilityState==="hidden"||!document.hasFocus()||No(je)};l();const F=window.setInterval(l,1e4);return window.addEventListener("focus",l),window.addEventListener("blur",l),document.addEventListener("visibilitychange",l),()=>{window.clearInterval(F),window.removeEventListener("focus",l),window.removeEventListener("blur",l),document.removeEventListener("visibilitychange",l)}},[je,n,w]);const ke=s.useCallback((l,F,oe)=>ko(Pe.current,l,F,n||null,oe,{mode:A,lightThemeId:L,darkThemeId:H,currentTheme:X}),[X,H,n,L,A]);s.useEffect(()=>{const l=new Set(I.map(F=>F.id));for(const F of Pe.current.keys())l.has(F)||Pe.current.delete(F)},[I]);const Be=s.useCallback(l=>{!n||P?.mode!=="diff"||i(n,{mode:"diff",targetPath:P.targetPath,stagedDiff:l==="staged",diffScope:l})},[P,n,i]),Me=s.useCallback(()=>{if(typeof window>"u")return;const l={themeMode:A,lightThemeId:L,darkThemeId:H,currentTheme:X};for(const F of me.current.values()){const oe=F.contentWindow;oe&&oe.postMessage({type:"pichamber:theme-sync",payload:l},window.location.origin)}},[X,H,L,A]),Oe=s.useCallback(()=>{if(typeof window>"u")return;const l={allowPromptingSubagentSessions:d};for(const F of me.current.values()){const oe=F.contentWindow;oe&&oe.postMessage({type:"pichamber:chat-settings-sync",payload:l},window.location.origin)}},[d]),E=s.useCallback(()=>{if(!(typeof window>"u"))for(const[l,F]of me.current.entries()){const oe=F.contentWindow;if(!oe)continue;const se={visible:Ae===l};oe.postMessage({type:"pichamber:embedded-visibility",payload:se},window.location.origin)}},[Ae]);s.useEffect(()=>{if(typeof window>"u")return;const l=F=>{if(F.origin!==window.location.origin||!Array.from(me.current.values()).some(Ge=>Ge.contentWindow===F.source))return;const se=F.data;if(se?.type===Po){if(typeof se.requestId!="string"||!se.requestId)return;const Ge=Ds(),ze={apiBaseUrl:Et(),clientToken:Sn(),localOrigin:typeof window.__PICHAMBER_LOCAL_ORIGIN__=="string"?window.__PICHAMBER_LOCAL_ORIGIN__:"",runtimeHeaders:Yr(),relayHostId:Ge.startsWith("host:")?Ge.slice(5):"",relay:Gr()??void 0};F.source?.postMessage({type:Ro,requestId:se.requestId,payload:ze},F.origin);return}if(se?.type==="pichamber:theme-sync-request"){Me();return}if(se?.type==="pichamber:chat-settings-request"){Oe();return}if(se?.type!=="pichamber:cycle-theme-request")return;const Ie=["light","dark","system"],Ze=(Ie.indexOf(A)+1)%Ie.length;D(Ie[Ze])};return window.addEventListener("message",l),()=>window.removeEventListener("message",l)},[Oe,Me,D,A]),s.useLayoutEffect(()=>{I.some(F=>F.mode==="chat")&&(Me(),Oe(),E())},[H,L,Oe,E,Me,I,A]);const ie=P?.mode==="file"||P?.mode==="chat"||P?.mode==="preview",he=s.useMemo(()=>P?I.filter(l=>l.mode===P.mode):[],[P,I]),g=s.useMemo(()=>he.map(l=>{const F=Al(l,M,K),oe=Il(F,wl),se=jl(l.targetPath,t);return{id:l.id,label:oe,icon:Ss(l,K),title:se?`${F}: ${se}`:F,closeLabel:`Close ${oe} tab`}}),[he,t,K,M]),j=P?.mode==="context"?e.jsx(Ki,{}):P?.mode==="git"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ml,{isActive:w})}):P?.mode==="notes"?e.jsx(Ks,{}):P?.mode==="preview"?e.jsx(Ml,{rawUrl:P.targetPath??"",onNavigate:l=>x(t,l)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(C,{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."})]}),te=s.useMemo(()=>I.filter(l=>l.mode==="chat"),[I]),ye=s.useMemo(()=>I.filter(l=>l.mode==="browser"),[I]),_e=s.useMemo(()=>I.filter(l=>l.mode==="diff"),[I]),v=s.useMemo(()=>I.some(l=>l.mode==="terminal"),[I]),B=Ol()?Ll:_l,be=s.useMemo(()=>I.some(l=>l.mode==="file"),[I]),u=s.useMemo(()=>I.some(l=>l.mode==="file"&&l.targetPath),[I]),T=P?.mode==="file",R=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[ie?e.jsx(Ra,{items:g,activeId:P?.id??null,onSelect:l=>{n&&m(n,l)},onClose:l=>{n&&a(n,l)},onReorder:(l,F)=>{n&&f(n,l,F)},layoutMode:"scrollable",variant:"default"}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[P?Ss(P,K):null,e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:P?ar(P.mode,K):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[T?e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",onClick:k,className:"h-7 w-7 p-0",title:"Toggle file tree","aria-label":"Toggle file tree","aria-pressed":b,children:e.jsx(C,{name:"layout-right",className:"h-3.5 w-3.5"})}):null,e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",onClick:ae,className:"h-7 w-7 p-0",title:N?"Collapse panel":"Expand panel","aria-label":N?"Collapse panel":"Expand panel",children:N?e.jsx(C,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):e.jsx(C,{name:"fullscreen",className:"h-3.5 w-3.5"})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"sm",onClick:ee,className:"h-7 w-7 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(C,{name:"close",className:"h-3.5 w-3.5"})})]})]}),V=w?N?{"--oc-context-panel-width":W!==null?`${W}px`:"100%",width:W!==null?`${W}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${J}px`}:{"--oc-context-panel-width":`${J}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:we,"data-context-panel":"true",tabIndex:-1,inert:!w||void 0,className:ge("flex min-h-0 flex-col overflow-hidden bg-background",N?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!w&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:de,style:V,children:[w&&!N&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),w&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!N&&e.jsx("div",{className:ge("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",ne&&"bg-[var(--interactive-border)]"),onPointerDown:U,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:ge("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]",!w&&"pointer-events-none select-none opacity-0"),style:{width:N?W!==null?`${W}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!w,children:[R,e.jsxs("div",{className:ge("relative min-h-0 flex-1 overflow-hidden",ne&&"pointer-events-none"),children:[be?e.jsxs("div",{className:ge("absolute inset-0 flex",T?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:u?e.jsx(s.Suspense,{fallback:null,children:e.jsx(pl,{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(C,{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(Nl,{visible:b})]}):null,te.map(l=>{const F=Jt(l.dedupeKey);if(!F)return null;const oe=ke(l.id,F,l.readOnly);return oe?e.jsx("iframe",{ref:se=>{if(!se){me.current.delete(l.id);return}me.current.set(l.id,se)},src:oe,title:`Session chat ${F}`,className:ge("absolute inset-0 h-full w-full border-0 bg-background",Ae===l.id?"block":"hidden"),onLoad:()=>{Me(),Oe(),E()}},l.id):null}),ye.map(l=>e.jsx("div",{className:ge("absolute inset-0",P?.id!==l.id&&"hidden"),children:e.jsx(B,{initialUrl:l.targetPath??"",directory:n,tabID:l.id})},l.id)),_e.map(l=>e.jsx("div",{className:ge("absolute inset-0",P?.id!==l.id&&"hidden"),children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(hl,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:l.diffScope??(l.stagedDiff?"staged":"working"),onDiffScopeChange:Be,targetFilePath:l.targetPath,flushContent:!0})})},l.id)),v?e.jsx("div",{className:ge("absolute inset-0",P?.mode==="terminal"?"block":"hidden"),children:e.jsx(Gs,{visible:w&&P?.mode==="terminal"})}):null,P?.mode!=="chat"&&!T&&P?.mode!=="browser"&&P?.mode!=="diff"&&P?.mode!=="terminal"?j:null]})]})]})},Fl=150,Wl=500,Ul=[],$l=t=>t>99?"99+":String(t),zl=({surface:t,isActive:n,showActivityDot:o,label:r,description:a,badgeCount:i,badgeAriaLabel:p,badgeDescription:h,orderNumber:m,showOrderNumber:f,onSelect:S})=>{const{attributes:x,listeners:b,setNodeRef:k,transform:d,transition:A,isDragging:D}=ma({id:t.id}),L=i!=null&&i>0?$l(i):null;return e.jsx("div",{ref:k,style:{transform:Fa.Translate.toString(d),transition:A},className:ge("relative",D&&"z-10 opacity-70"),children:e.jsxs(He,{delayDuration:Fl,children:[e.jsx(Ve,{asChild:!0,children:e.jsxs("button",{type:"button",...x,...b,onClick:()=>S(t),"aria-label":p??r,"aria-pressed":n,className:ge("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx(C,{name:t.icon,className:"h-[18px] w-[18px]"}),f&&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}):L?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:L}):o?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(Ke,{side:"left",sideOffset:8,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:r}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:a}),h?e.jsx("span",{className:"typography-micro text-muted-foreground",children:h}):null]})})]})})},Hl=()=>{const t=Ht(),n=t?Xr(t):"",o=z(w=>n?w.contextPanelByDirectory[n]:void 0),r=z(w=>w.contextRailOrder),a=z(w=>w.setContextRailOrder),i=z(w=>w.openContextSurface),p=z(w=>w.shortcutOverrides),{screenWidth:h}=zt(),{git:m}=$t(),f=Fs(n||null),S=Us(n||null),x=zs(w=>w.ensureStatus);s.useEffect(()=>{n&&x(n,m)},[n,x,m]);const b=s.useMemo(()=>Io("switch_context_surface",p),[p]),[k,d]=s.useState(!1);s.useEffect(()=>{const w=new Set;let N=null,W=!1;const y=_=>_.length===1&&_>="0"&&_<="9",Q=()=>{Zn(b,w)?!W&&N===null&&(N=setTimeout(()=>d(!0),Wl)):(W=!1,N!==null&&(clearTimeout(N),N=null),d(!1))},O=_=>{if(w.add(_.key.toLowerCase()),y(_.key)&&Zn(b,w)){W=!0,N!==null&&(clearTimeout(N),N=null),d(!1);return}Q()},Y=_=>{w.delete(_.key.toLowerCase()),Q()},J=()=>{w.clear(),W=!1,N!==null&&(clearTimeout(N),N=null),d(!1)};return window.addEventListener("keydown",O,!0),window.addEventListener("keyup",Y,!0),window.addEventListener("blur",J),()=>{window.removeEventListener("keydown",O,!0),window.removeEventListener("keyup",Y,!0),window.removeEventListener("blur",J),N!==null&&clearTimeout(N)}},[b]);const A=aa(es(la,{activationConstraint:{distance:8}}),es(ia,{activationConstraint:{delay:200,tolerance:6}})),D=o?.tabs??Ul,L=D.find(w=>w.id===o?.activeTabId)??null,H=o?.isOpen?L?.mode??null:null,X=f?.files.length??0,I=s.useMemo(()=>Do({railOrder:r,tabs:D}),[r,h,D]),P=s.useCallback(w=>{const{active:N,over:W}=w;if(!W||N.id===W.id)return;const y=Mo(z.getState().contextRailOrder).map(Y=>Y.id),Q=y.indexOf(N.id),O=y.indexOf(W.id);Q===-1||O===-1||a(ua(y,Q,O))},[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(ca,{sensors:A,collisionDetection:da,onDragEnd:P,children:e.jsx(ha,{items:I.map(w=>w.id),strategy:pa,children:I.map((w,N)=>{const W=w.id==="git"?Rn(S):null,y=W?{...w,...W}:w,Q=y.label,O=w.id==="git"&&S===!0?X:0,Y=O>0?O:null;return e.jsx(zl,{surface:y,isActive:H===w.mode,showActivityDot:!1,label:Q,description:y.description,badgeCount:Y,badgeAriaLabel:Y!==null?Y===1?"{label}, {count} changed file":"{label}, {count} changed files":null,badgeDescription:Y!==null?Y===1?"{count} changed file":"{count} changed files":null,orderNumber:N+1,showOrderNumber:k,onSelect:J=>i(n,J.mode)},w.id)})})})}):null},Vl=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),Kl=(t,n,o,r)=>!o||r!==o||t.length===0?[]:Lt(t,n,a=>a.name,{limit:10,threshold:.4}),Gl=new Set,jn=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),o=n.startsWith("//");let r=n.replace(/\/+/g,"/");o&&!r.startsWith("//")&&(r=`/${r}`);const a=r==="/",i=/^[A-Za-z]:\/$/.test(r);return!a&&!i&&(r=r.replace(/\/+$/,"")),r},Yl=()=>{const t=z(g=>g.isCommandPaletteOpen),n=z(g=>g.setCommandPaletteOpen),o=z(g=>g.setActiveMainTab),r=z(g=>g.setSettingsDialogOpen),a=z(g=>g.setSettingsPage),i=z(g=>g.setSessionSwitcherOpen),p=z(g=>g.toggleSidebar),h=z(g=>g.openContextOverview),m=z(g=>g.openContextSurface),f=z(g=>g.openContextFile),S=z(g=>g.shortcutOverrides),x=Fe(g=>g.openNewSessionDraft),b=Fe(g=>g.setCurrentSession),k=Oo({archived:!1}),d=_o(s.useCallback(g=>t?g.ids:Gl,[t])),A=Lo(s.useCallback(g=>t?g.rankById:Bo,[t])),D=Jr(g=>g.currentDirectory),L=An(g=>g.getActiveProject()),H=An(g=>g.projects),X=Ht(),I=Is(g=>g.searchFiles),{files:P,git:w}=$t(),N=zs(g=>g.ensureStatus),{isMobile:W}=zt(),y=s.useMemo(()=>X?jn(X):null,[X]),[Q,O]=s.useState(""),J=Ws(Q,200).trim(),_=Q.trim();s.useEffect(()=>{t&&O("")},[t]),s.useEffect(()=>{if(!t||!w)return;const g=setTimeout(()=>{const j=new Set;for(const te of k){const ye=fn(te);!ye||j.has(ye)||(j.add(ye),N(ye,w))}},0);return()=>clearTimeout(g)},[t,k,w,N]);const M=s.useCallback(()=>n(!1),[n]),K=s.useCallback(g=>()=>{M(),g()},[M]),ne=s.useMemo(()=>{const g=[{id:"new-session",title:"New Session",icon:e.jsx(C,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:K(()=>{o("chat"),i(!1),x()})},{id:"add-project",title:"Add Project",icon:e.jsx(C,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:K(()=>{Fo.requestDirectoryDialog()})},{id:"toggle-sidebar",title:W?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(C,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:W?"Show Session Switcher":"Toggle Sidebar",onSelect:K(()=>{if(W){const{isSessionSwitcherOpen:j}=z.getState();i(!j)}else p()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(C,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:K(()=>{D&&m(D,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(C,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:K(()=>{D&&h(D)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(C,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:K(()=>r(!0))}];return Es()&&g.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(C,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:K(()=>{kt("desktop_open_draft_mini_chat_window",{directory:jn(D||L?.path||""),projectId:L?.id??null}).catch(j=>{console.warn("[command-palette] failed to open draft mini chat window",j)})})}),g},[K,W,o,i,x,p,m,D,h,r,L?.id,L?.path]),ue=s.useMemo(()=>{const g=Wt();return{isWeb:!g&&qr(),isDesktop:g,isMobile:W}},[W]),xe=s.useMemo(()=>Ea.filter(g=>g.slug!=="home").filter(g=>g.isAvailable?g.isAvailable(ue):!0).map(g=>{const j=Ta(g.slug)??"settings-3",te=(g.keywords??[]).join(" ");return{id:`settings:${g.slug}`,title:g.title,icon:e.jsx(C,{name:j,className:"mr-2 h-4 w-4"}),searchText:`${g.title} ${g.group} ${te}`,onSelect:K(()=>{a(g.slug),r(!0)})}}),[ue,K,a,r]),q=s.useMemo(()=>Wo(k,d,A),[k,d,A]),le=Uo(),pe=s.useCallback((g,j)=>j&&le.get(j)?.trim()||null,[le]),[we,me]=s.useState([]),[Pe,ve]=s.useState(""),Se=Vl(y,J);s.useEffect(()=>{if(!t){me([]),ve("");return}if(!Se){me([]),ve("");return}if(!y){me([]),ve("");return}let g=!1;return I(y,J,10,{type:"file"}).then(j=>{g||(me(j.map(te=>({path:jn(te.path),name:te.name,relativePath:te.relativePath}))),ve(Se))}).catch(()=>{g||(me([]),ve(Se))}),()=>{g=!0}},[t,y,J,Se,I]);const fe=_.length>0,Z=s.useMemo(()=>fe?Lt(ne,_,g=>g.searchText,{limit:7,noFuzzy:!0}):ne.map(g=>({item:g,score:0})),[ne,_,fe]),Ee=s.useMemo(()=>fe?Lt(xe,_,g=>g.searchText,{limit:7,noFuzzy:!0}):[],[xe,_,fe]),U=s.useMemo(()=>fe?Lt(q,_,g=>g.title||"",{limit:7,threshold:.2}):q.slice(0,5).map(g=>({item:g,score:0})),[q,_,fe]),G=s.useMemo(()=>t?Kl(we,J,Se,Pe):[],[t,we,Pe,Se,J]),ee=t&&Se.length>0&&Pe!==Se,ae=s.useMemo(()=>{if(!fe)return[];const g=H.map(j=>({...j,displayName:j.label||j.path.split("/").pop()||j.path,searchText:`${j.label||""} ${j.path}`}));return Lt(g,_,j=>j.searchText,{limit:7,threshold:.4})},[H,_,fe]),de=Z.map(g=>g.item),Ae=Ee.map(g=>g.item),je=U.map(g=>g.item),ke=fe?G.map(g=>g.item):[],Be=fe?ae.map(g=>g.item):[],Me=s.useMemo(()=>{if(!fe)return["commands","sessions"];const g=te=>te.length?te[0].score:1/0,j=[{key:"commands",score:g(Z)},{key:"settings",score:g(Ee)},{key:"sessions",score:g(U)},{key:"files",score:g(G)},{key:"projects",score:g(ae)}];return j.sort((te,ye)=>te.score-ye.score),j.map(te=>te.key)},[fe,Z,Ee,U,G,ae]),Oe=s.useCallback(g=>{M(),b(g.id,fn(g))},[M,b]),E=s.useCallback(async g=>{if(!y)return;const j=await Ys(P,g,{directory:y});if(!j.ok){ce.error(Xs(j.reason));return}f(y,g),M()},[y,P,f,M]),ie=s.useCallback((g,j)=>{M(),x({selectedProjectId:g,directoryOverride:j})},[M,x]),he=s.useCallback(g=>en(Nt(g,S)),[S]);return e.jsxs(tn,{open:t,onOpenChange:n,children:[e.jsxs(sn,{className:"sr-only",children:[e.jsx(rn,{children:"Command Palette"}),e.jsx(on,{children:"Search files, sessions, and commands."})]}),e.jsx(nn,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs($o,{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(zo,{value:Q,onValueChange:O,placeholder:"Search files, sessions, commands..."}),e.jsxs(Ho,{children:[e.jsx(Vo,{children:"No results found."}),Me.map(g=>g==="commands"&&de.length>0?e.jsx(Mt,{children:de.map(j=>e.jsxs(Ot,{value:j.id,onSelect:j.onSelect,children:[j.icon,e.jsx("span",{children:j.title}),j.shortcutId?e.jsx(Ko,{children:he(j.shortcutId)}):null]},j.id))},"commands"):g==="settings"&&Ae.length>0?e.jsx(Mt,{children:Ae.map(j=>e.jsxs(Ot,{value:j.id,onSelect:j.onSelect,children:[j.icon,e.jsx("span",{children:j.title})]},j.id))},"settings"):g==="sessions"&&je.length>0?e.jsx(Mt,{children:je.map(j=>{const te=j.title||"Untitled Session",ye=fn(j),_e=pe(j.id,ye);return e.jsxs(Ot,{value:`session:${j.id}`,onSelect:()=>Oe(j),children:[e.jsx(C,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:te}),_e?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(C,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:_e})]}):null]},j.id)})},"sessions"):g==="files"&&ke.length>0?e.jsx(Mt,{children:ke.map(j=>{const te=Go(j.relativePath||j.name,{maxLength:80});return e.jsxs(Ot,{value:`file:${j.path}`,onSelect:()=>{E(j.path)},children:[e.jsx(Pn,{filePath:j.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":j.relativePath,children:te})]},`file:${j.path}`)})},"files"):g==="projects"&&Be.length>0?e.jsx(Mt,{children:Be.map(j=>{const te=j.displayName;return e.jsxs(Ot,{value:`project:${j.id}`,onSelect:()=>ie(j.id,j.path),children:[e.jsx(C,{name:"folder",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:te}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:j.path})]},`project:${j.id}`)})},"projects"):null),ee?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},Ns=(t,n,o)=>Xo(t)?en(Nt(t,o)):n,Xl=()=>{const t=z(i=>i.isHelpDialogOpen),n=z(i=>i.setHelpDialogOpen),o=z(i=>i.shortcutOverrides),r=Yo(),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 + ${r} + 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:[`${r} + 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(tn,{open:t,onOpenChange:n,children:e.jsxs(nn,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(sn,{children:[e.jsxs(rn,{className:"flex items-center gap-2",children:[e.jsx(C,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(on,{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(i=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:i.categoryKey}),e.jsx("div",{className:"space-y-1",children:i.items.map(p=>{const h=p.id?Ns(p.id,Array.isArray(p.keys)?p.keys[0]:p.keys,o):Array.isArray(p.keys)?p.keys:p.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:[p.icon&&e.jsx(C,{name:p.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:p.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(h)?h:[h]).map((m,f)=>e.jsxs(s.Fragment,{children:[f>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}-${f}`))})]},p.id||p.descriptionKey)})})]},i.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(C,{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 (${Ns("open_command_palette",`${r} P`,o)}) 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"]})]})]})]})})]})]})})},Jl=s.createContext(null),ql=({children:t,value:n})=>e.jsx(Jl.Provider,{value:n,children:t}),Ps=ot(()=>Qe(()=>import("./GitView-CkztSaT7.js"),__vite__mapDeps([128,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,129,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}))),Ql=ot(()=>Qe(()=>import("./DiffView-k3lX2PiV.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}))),Zl=ot(()=>Qe(()=>import("./FilesView-C39IOFfs.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,127])).then(t=>({default:t.FilesView}))),ec=ot(()=>Qe(()=>import("./DiagramView-r89Qi5ON.js"),__vite__mapDeps([130,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}))),tc=ot(()=>Qe(()=>import("./SettingsView-Bf4vWwVK.js").then(t=>t.b),__vite__mapDeps([131,1,2,6,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,111,112,113,132,133,115])).then(t=>({default:t.SettingsView}))),nc=ot(()=>Qe(()=>import("./SettingsWindow-B8IV35H4.js"),__vite__mapDeps([134,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,131,111,112,113,132,133,115])).then(t=>({default:t.SettingsWindow}))),sc=()=>{const t=z(O=>O.isSidebarOpen),n=z(O=>O.activeMainTab),o=z(O=>O.setIsMobile),r=z(O=>O.isSessionSwitcherOpen),a=z(O=>O.isSettingsDialogOpen),i=z(O=>O.setSettingsDialogOpen),[p,h]=s.useState(!1);s.useEffect(()=>{a&&h(!0)},[a]),s.useEffect(()=>{const O=()=>z.getState().closeMainSurfaces(),Y=Fe.subscribe((_,M)=>{const K=!!_.currentSessionId&&_.currentSessionId!==M.currentSessionId,ne=!!_.newSessionDraft?.open&&_.newSessionDraft!==M.newSessionDraft;(K||ne)&&O()}),J=z.subscribe((_,M)=>{_.activeMainTab!==M.activeMainTab&&O()});return()=>{Y(),J()}},[]);const{isMobile:m}=zt(),f=s.useRef(!1),[S,x]=s.useState(!1),[b,k]=s.useState(!1),[d,A]=s.useState(!1),[D,L]=s.useState(!1),H=s.useCallback(O=>{x(O),z.getState().setSessionSwitcherOpen(O)},[]),X=s.useRef(typeof window>"u"?0:window.innerWidth),I=as(-X.current),P=Le.useRef(0),w=as(X.current),N=Le.useRef(0);Le.useEffect(()=>{m&&(P.current=window.innerWidth,N.current=window.innerWidth)},[m]),Le.useEffect(()=>{if(!m){A(!1);return}S&&A(!0),is(I,S?0:-P.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[S,m,I]),Le.useEffect(()=>{if(!m){L(!1);return}b&&L(!0),is(w,b?0:N.current,{type:"spring",stiffness:400,damping:35,mass:.8})},[m,b,w]),Le.useEffect(()=>{if(m)return I.on("change",O=>{const Y=P.current||X.current,J=S||O>-Y+.5;A(_=>_===J?_:J)})},[m,I,S]),Le.useEffect(()=>{if(m)return w.on("change",O=>{const Y=N.current||X.current,J=b||O<Y-.5;L(_=>_===J?_:J)})},[m,b,w]),Le.useEffect(()=>{m&&!r&&S&&H(!1)},[r,m,S,H]),Le.useEffect(()=>{if(!m){f.current=!1;return}f.current||(f.current=!0,H(!1),k(!1))},[m,H]),Le.useEffect(()=>{if(!m||n!=="chat"||S||b||a)return;let O=!1,Y;const J=_=>{Y=window.setTimeout(()=>{if(O)return;const M=Fe.getState(),K=z.getState();if(!(K.activeMainTab!=="chat"||K.isSettingsDialogOpen||M.currentSessionId||M.newSessionDraft?.open)){if(M.isLoading){J(250);return}M.openNewSessionDraft({automatic:!0})}},_)};return J(500),()=>{O=!0,Y!==void 0&&window.clearTimeout(Y)}},[n,m,a,S,b]),Le.useEffect(()=>{!m||!a||(H(!1),k(!1))},[m,a,H]),Ia(),s.useEffect(()=>{z.getState().isMobile!==m&&o(m)},[m,o]);const W=s.useCallback(()=>{S&&H(!1),k(!b)},[S,b,H]),y=s.useMemo(()=>{if(!m&&n!=="terminal"&&n!=="diagram")return null;switch(n){case"git":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ps,{isActive:!b})});case"diff":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ql,{})});case"terminal":return e.jsx(Gs,{});case"files":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Zl,{})});case"context":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ks,{})});case"diagram":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(ec,{})});default:return null}},[n,m,b]),Q=n==="chat";return e.jsx(Da,{children:e.jsxs("div",{"data-page-scroll-lock":"true",className:ge("main-content-safe-area",m?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(Yl,{}),e.jsx(Xl,{}),e.jsx(Ma,{}),m?e.jsxs(ql,{value:{leftDrawerOpen:S,rightDrawerOpen:b,toggleLeftDrawer:()=>{const O=!S;b&&k(!1),H(O)},toggleRightDrawer:W,leftDrawerX:I,rightDrawerX:w,leftDrawerWidth:P,rightDrawerWidth:N,setMobileLeftDrawerOpen:H,setRightSidebarOpen:k},children:[!a&&e.jsx(ps,{onToggleLeftDrawer:()=>{const O=!S;b&&k(!1),H(O)},onToggleRightDrawer:()=>{W()},leftDrawerOpen:S,rightDrawerOpen:b}),e.jsx("div",{"data-page-scroll-lock":"true",className:ge("flex flex-1 overflow-hidden relative",a&&"hidden"),children:e.jsxs("main",{className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[e.jsx("div",{className:ge("absolute inset-0",!Q&&"invisible"),children:e.jsx(qe,{children:e.jsx(ss,{active:Q&&!a})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(qe,{children:y})}),e.jsx(qe,{children:e.jsx(rs,{})}),e.jsx(ls.div,{className:ge("absolute inset-0 z-20 bg-sidebar",!d&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:I},"aria-hidden":!S,children:e.jsx(qe,{children:e.jsx(os,{mobileVariant:!0,isVisible:d})})}),D&&e.jsx(ls.div,{className:"absolute inset-0 z-20 bg-sidebar","data-page-scroll-lock":"true",style:{x:w},"aria-hidden":!b,children:e.jsx(qe,{children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ps,{isActive:b})})})})]})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(qe,{children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(tc,{onClose:()=>i(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(mi,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(pi,{isOpen:t,isMobile:m,className:"border-border",children:e.jsx(os,{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(ps,{}),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:ge("absolute inset-0",!Q&&"invisible"),children:e.jsx(qe,{children:e.jsx(ss,{active:Q&&!a})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(qe,{children:y})}),e.jsx(qe,{children:e.jsx(rs,{})})]}),e.jsx(Bl,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(qe,{children:e.jsx(Hl,{})})})]})]})]}),p?e.jsx(s.Suspense,{fallback:null,children:e.jsx(nc,{open:a,onOpenChange:i})}):null]})]})})},rc=()=>(Zo(),_a(),e.jsxs(La,{children:[e.jsx(ea,{embeddedBackgroundWorkEnabled:!0}),e.jsx(sc,{}),e.jsx(ta,{}),e.jsx(na,{})]}));function oc({apis:t}){const n=t??kn(),[o,r]=s.useState(0);return s.useEffect(()=>Ts(a=>{a.runtimeKey!==a.previousRuntimeKey&&(Oa(a),r(i=>i+1))}),[]),s.useEffect(()=>{Qr()},[o]),s.useEffect(()=>{n&&Zr(n)},[n]),n?e.jsx(qe,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(Jo,{apis:n,children:e.jsx(qo,{children:e.jsx(Qo,{children:e.jsx(rc,{})})},o)})})}):e.jsx(qe,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const cr=document.getElementById("root");if(!cr)throw new Error("Root element not found");Or.createRoot(cr).render(e.jsx(Le.StrictMode,{children:e.jsx(sa,{children:e.jsx(ra,{children:e.jsx(oa,{children:e.jsx(oc,{apis:kn()??void 0})})})})}));
|