@pi-chamber/web 0.9.6 → 0.9.7
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/dist/assets/{DiagramView-0Iq1ak1I.js → DiagramView-BvrCkm_z.js} +1 -1
- package/dist/assets/{DiffView-DD1AFRi3.js → DiffView-DMvRLRN1.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-CoKwDovb.js → FileSaveConflictDialog-DGa9u43J.js} +1 -1
- package/dist/assets/{FilesView-B_BF39ef.js → FilesView-CNHu4RnC.js} +4 -4
- package/dist/assets/{GitView-LFEpCasf.js → GitView-Cbepz-bR.js} +3 -3
- package/dist/assets/{JsonTreeView-Cwjgvh4g.js → JsonTreeView-C2X5oXQm.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-_7kV1yNw.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
- package/dist/assets/{PatchDiff-DG43C1HW.js → PatchDiff-i_9BIlgo.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DCFXPY3d.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-QY7FKuEQ.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
- package/dist/assets/{SessionUnreadDot-DGT31A3z.js → SessionUnreadDot-CDRZswx-.js} +1 -1
- package/dist/assets/SettingsView-hyAGp836.js +2 -0
- package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
- package/dist/assets/{ToolOutputDialog-IlCrS6BR.js → ToolOutputDialog-CJ87b80H.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-D68JV0rR.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-Bl-rAYeh.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
- package/dist/assets/{collapsible-BjniCdZ5.js → collapsible-DesjbW8a.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-FSOm2VrW.js → computeVirtualFileMetrics-CsAu9rOt.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-Bxb6AIPa.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
- package/dist/assets/{gitStatusPredicates-DxolDpMd.js → gitStatusPredicates-D_31YElh.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-BZpvAhrX.js +8 -0
- package/dist/assets/{index-Dh58uD3I.js → index-CXLVW_GG.js} +1 -1
- package/dist/assets/{isDiffPlainText-D3_04XCh.js → isDiffPlainText-BX609Lau.js} +1 -1
- package/dist/assets/{isFilePlainText-CHouYQhH.js → isFilePlainText-FgBWqu9b.js} +1 -1
- package/dist/assets/{main-CH3EqGJI.js → main-C_pL2r_k.js} +2 -2
- package/dist/assets/{main-HzTrVvbB.js → main-tv2uysSs.js} +7 -7
- package/dist/assets/{markdownCore-DJU4KvHP.js → markdownCore-D3Ibaffd.js} +1 -1
- package/dist/assets/{miniChat-Ca3TpaaA.js → miniChat-B0xQlBzZ.js} +2 -2
- package/dist/assets/{mobile-lj4gpGsO.js → mobile-BmSlVuhn.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
- package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
- package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
- package/dist/assets/{runtimeSurface-CE_VNjdH.js → runtimeSurface-egSD9pqj.js} +1 -1
- package/dist/assets/{useAppFontEffects-BvFAP9zG.js → useAppFontEffects-C9QQrBIx.js} +104 -104
- package/dist/assets/{useFilesViewSearch-BD79p3A2.js → useFilesViewSearch-BTZutbn-.js} +2 -2
- package/dist/assets/{usePushVisibilityBeacon-CWg0j-Wg.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
- package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-CP3j3-xu.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
- package/dist/assets/{web-components-DWuadqra.js → web-components-CYngz9Ml.js} +1 -1
- 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/index.js +17 -3
- package/server/lib/client-auth/DOCUMENTATION.md +184 -0
- package/server/lib/client-auth/live-revocation.test.js +567 -0
- package/server/lib/client-auth/principal-tracker.js +383 -0
- package/server/lib/client-auth/principal-tracker.test.js +321 -0
- package/server/lib/client-auth/remote-clients.js +31 -0
- package/server/lib/client-auth/remote-clients.test.js +44 -0
- package/server/lib/pi/event-stream.js +269 -0
- package/server/lib/pi/event-stream.test.js +776 -0
- package/server/lib/pi/routes.js +76 -25
- package/server/lib/pi/routes.test.js +48 -4
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -4
- package/server/lib/pi/session-daemon/ipc-client.js +19 -15
- package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
- package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
- package/server/lib/pi/session-daemon/session-daemon.js +55 -6
- package/server/lib/pi/session-daemon/session-daemon.test.js +10 -4
- package/server/lib/pi/session-daemon/session-replay.test.js +8 -3
- package/server/lib/pi/session-daemon/supervisor.js +30 -5
- package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
- package/server/lib/pi/ui-settings-store.js +1 -1
- package/server/lib/pi/ui-settings-store.test.js +3 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/stt/DOCUMENTATION.md +2 -0
- package/server/lib/stt/runtime.js +39 -2
- package/server/lib/stt/runtime.test.js +53 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +48 -2
- package/server/lib/terminal/runtime.test.js +35 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
- package/server/lib/ui-auth/ui-auth.js +98 -0
- package/server/lib/ui-auth/ui-auth.test.js +249 -0
- package/server/lib/workspace/host.js +3 -1
- package/dist/assets/SettingsView-eG-wN-yY.js +0 -2
- package/dist/assets/SettingsWindow-Dvnp8YrA.js +0 -1
- package/dist/assets/index-BpmGBboM.css +0 -1
- package/dist/assets/index-DZnzXhTs.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +0 -2
- package/dist/assets/renderMobileApp-CcWQ1sCf.js +0 -11
- package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +0 -53
- package/dist/assets/useSwitcherItems-CazJ6Yox.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-
|
|
2
|
-
import{R as r,j as e,r as Se,e as Wn}from"./vendor-react-B5Z1Mdn3.js";import"./vendor-katex-CNckGUMB.js";import{u as ee,m as ie,r as et,z as Zt,A as Fn,e as en,B as tn,a as Bn,C as zn,D as Un,E as Pe,F as Hn,G as Te,H as Vn,I as Kn,J as Xn,K as Rt,L as He,n as qn,M as Gn,N as Yn,O as Jn,P as Qn,Q as nn,R as rn,S as Zn,T as er,U as tr,w as nr,x as rr,q as sn,v as sr}from"./index-DZnzXhTs.js";import{_ as Re}from"./vendor-vite-runtime-DD1OZmLC.js";import{h as or,q as ar,t as ir,v as lr,w as cr,x as dr,y as on,z as an,B as ut,T as ln,E as ur,G as hr,I as pr,j as fr,p as mr,n as gr,o as xr,H as Et,C as Tt,A as _t,S as Dt,k as wr,l as yr,m as br,F as vr,W as jr}from"./runtimeEndpointReset-D2MmSbDk.js";import{Y as rt,I as K,E as Ne,Z as st,f as je,t as ve,_ as Sr,B as me,o as tt,P as cn,$ as ft,a0 as Cr,a1 as Le,a2 as Oe,a3 as Nr,a4 as $e,a5 as kr,a6 as mt,a7 as Pr,a8 as Rr,a9 as gt,aa as qe,ab as dn,ac as At,ad as Er,ae as xt,af as wt,ag as yt,ah as bt,ai as vt,aj as Tr,ak as _r,al as Dr,am as Ar,an as un,y as Ie,ao as Ve,ap as Mr,aq as Ir,ar as De,as as hn,at as Lr,au as jt,av as Or,aw as pn,ax as $r,ay as Wr,az as Fr,aA as Mt,aB as Br,b as zr,c as Ur,aC as Hr,a as It,aD as Vr,r as ot,aE as Kr,aF as Xr,aG as qr,aH as Gr,aI as Yr,aJ as Jr,aK as Qr,aL as ze,aM as Ue,aN as Zr,V as es,X as ts,R as ns,K as rs,T as ss,H as os,S as as,W as is,L as ls,M as cs,Q as ds,U as us}from"./useAppFontEffects-BvFAP9zG.js";import{v as fn,g as mn}from"./contextFileOpenGuard-Bxb6AIPa.js";import{g as gn,u as hs,s as ps,i as fs,a as ms,b as gs}from"./useFilesViewSearch-BD79p3A2.js";import{c as xn,d as ht,P as xs,D as wn,e as yn,f as ws,T as ys,M as bs}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{S as bn,h as vs,u as vn,a as js,v as Ss}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as jn}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{g as Sn}from"./SessionUnreadDot-DGT31A3z.js";import{u as Lt,a as Ge,m as Ot}from"./vendor-framer-motion-CfplGuM0.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-CdaWtC7e.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-xterm-xterm-CrXqRur4.js";import"./permissionStore-iKN1K2_x.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-CE_VNjdH.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-CP3j3-xu.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-CNlncqrr.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";const Cs=280,$t=4,Ns=({transform:t})=>({...t,y:0}),ks=({id:t,children:n,className:o})=>{const{attributes:i,listeners:a,setNodeRef:m,transform:w,transition:u,isDragging:f}=vn({id:t});return e.jsx("div",{ref:m,"data-sortable-tab-id":t,style:{transform:jn.Transform.toString(w),transition:u},className:ie("h-full rounded-md",o,f&&"opacity-50"),...i,...a,children:n})},Ps=({id:t,children:n,className:o})=>e.jsx("div",{className:ie("h-full",o),"data-sortable-tab-id":t,children:n}),Rs=({items:t,activeId:n,onSelect:o,onClose:i,onReorder:a,layoutMode:m="scrollable",variant:w="default",activePillInsetClassName:u,activePillButtonClassName:f,inactiveTabsIconOnly:g=!1,animateActivePill:v,activePillLowercase:h=!0,nonCompositedIndicator:c=!1,className:P})=>{const d=ee(k=>k.isMobile),{isTablet:C}=rt(),j=d||C,N=r.useRef(null),[T,B]=r.useState({left:!1,right:!1}),re=r.useMemo(()=>t.map(k=>k.id),[t]),F=m==="scrollable",te=w==="default",z=w==="active-pill",b=z||w==="animated",G=te,U=b||G,O=z&&F,H=b,ne=v??b,R=typeof a=="function",J=R?ks:Ps,S=r.useRef(new Map),[L,q]=r.useState(null),[M,A]=r.useState(!1),[ce,ue]=r.useState(null),de=r.useRef(!1),ye=r.useRef(0),pe=r.useRef(n),xe=r.useRef(null),he=r.useMemo(()=>{if(!U||!ce||!n||ce===n)return 0;const k=t.findIndex(ae=>ae.id===ce),Z=t.findIndex(ae=>ae.id===n);return k<0||Z<0?0:k>Z?$t:-$t},[n,t,ce,U]),D=xn(ht(xs,{activationConstraint:{distance:8}})),$=r.useCallback((k,Z)=>!k||!Z?k===Z:Math.abs(k.left-Z.left)<.5&&Math.abs(k.top-Z.top)<.5&&Math.abs(k.width-Z.width)<.5&&Math.abs(k.height-Z.height)<.5,[]),x=r.useCallback((k,Z)=>{if(Z){S.current.set(k,Z);return}S.current.delete(k)},[]),_=r.useCallback(()=>{if(!U||!n){q(Q=>Q===null?Q:null);return}const k=N.current,Z=S.current.get(n);if(!k||!Z){q(Q=>Q===null?Q:null);return}let ae=0,E=0,oe=Z;for(;oe&&oe!==k;)ae+=oe.offsetLeft,E+=oe.offsetTop,oe=oe.offsetParent;const se={left:ae,top:E,width:Z.offsetWidth,height:Z.offsetHeight};q(Q=>$(Q,se)?Q:se)},[n,$,U]),V=r.useCallback(()=>{if(!F){B({left:!1,right:!1});return}const k=N.current;if(!k){B({left:!1,right:!1});return}B({left:k.scrollLeft>2,right:k.scrollLeft+k.clientWidth<k.scrollWidth-2})},[F]);r.useEffect(()=>{if(!F){B({left:!1,right:!1});return}const k=N.current;if(!k)return;V(),k.addEventListener("scroll",V,{passive:!0});const Z=new ResizeObserver(V);return Z.observe(k),()=>{k.removeEventListener("scroll",V),Z.disconnect()}},[F,t.length,V]),r.useEffect(()=>{if(!U){q(null);return}_();const k=N.current;if(!k)return;const Z=new ResizeObserver(()=>{performance.now()-ye.current>Cs&&A(!1),_()});if(Z.observe(k),n){const ae=S.current.get(n);ae&&Z.observe(ae)}return()=>{Z.disconnect()}},[n,t.length,_,U]),r.useLayoutEffect(()=>{_()});const le=re.join("\0");r.useLayoutEffect(()=>{if(!U){de.current=!1,A(!1);return}const k=xe.current!==le;if(xe.current=le,!de.current){de.current=!0,pe.current=n;return}const Z=pe.current!==n;if(pe.current=n,!Z||k){A(!1);return}ye.current=performance.now(),A(!0)},[n,le,U]),r.useEffect(()=>{if(!F||!n)return;const k=N.current;if(!k)return;const Z=window.requestAnimationFrame(()=>{const ae=typeof window.CSS?.escape=="function"?window.CSS.escape(n):n.replace(/"/g,'\\"'),E=k.querySelector(`[data-sortable-tab-id="${ae}"]`);E&&(E.scrollIntoView({block:"nearest",inline:"nearest"}),V())});return()=>{window.cancelAnimationFrame(Z)}},[n,F,t.length,V]);const fe=r.useCallback(k=>{if(!a)return;const{active:Z,over:ae}=k;!ae||Z.id===ae.id||a(String(Z.id),String(ae.id))},[a]),we=e.jsxs("div",{className:ie("relative flex h-full min-w-0 flex-1",P),children:[F&&T.left?e.jsx("div",{className:ie("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",b?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,F&&T.right?e.jsx("div",{className:ie("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",b?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e.jsxs("div",{ref:N,className:ie("relative flex h-full min-w-0 flex-1",b?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",b&&"@container/pill-tabs",b&&"pill-tabs__track",b&&(u??"gap-0.5 py-0.5"),G&&"items-center overflow-y-hidden",H&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",F?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:F?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[b&&L?e.jsx("div",{className:ie("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",ne&&M&&(c?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:c?{left:`${L.left+he}px`,top:`${L.top}px`,width:`${L.width}px`,height:`${L.height}px`}:{transform:`translate3d(${L.left+he}px, ${L.top}px, 0)`,width:`${L.width}px`,height:`${L.height}px`}}):null,G&&L?e.jsx("div",{className:ie("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",M&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${L.left+he}px, 0, 0)`,width:`${L.width}px`},"aria-hidden":!0}):null,t.map(k=>{const Z=k.id===n,ae=g&&b&&!Z&&!!k.icon,E=!ae,oe=!!k.icon,se=g&&b&&Z&&!F&&!O,Q=k.closable!==!1&&!!i,W=Q&&!!k.icon,s=F||O?void 0:b?se?"flex-none basis-auto":d?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",p=Q?I=>{I.button===1&&(I.preventDefault(),I.stopPropagation(),i?.(k.id))}:void 0,X=Q?I=>{I.button===1&&I.preventDefault()}:void 0,l=I=>oe?e.jsxs("span",{className:I,children:[e.jsx("span",{className:ie("flex items-center justify-center transition-opacity",W&&(j?"opacity-0":"group-hover:opacity-0")),children:k.icon}),W?e.jsx("span",{role:"button",tabIndex:-1,className:ie("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>{Y.stopPropagation(),i?.(k.id)},"aria-label":k.closeLabel??`Close ${k.label} tab`,title:k.closeLabel??`Close ${k.label} tab`,children:e.jsx(K,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return e.jsx(J,{id:k.id,className:s,children:e.jsxs("div",{ref:I=>x(k.id,I),onAuxClick:p,onMouseDown:X,className:ie("group flex h-full min-w-0 flex-nowrap items-center",F||O?"shrink-0":b?"w-full":"w-full min-w-0",b?"relative z-10 bg-transparent":Z?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":Z,"aria-label":ae?k.title??k.label:void 0,onClick:()=>o(k.id),onPointerDown:U?()=>{A(!0),ue(k.id)}:void 0,onPointerUp:U?()=>ue(null):void 0,onPointerLeave:U?()=>ue(null):void 0,onPointerCancel:U?()=>ue(null):void 0,className:ie(b?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",b&&h?"lowercase":null,b&&(ae?"gap-0":"gap-1.5"),b?O?"shrink-0 whitespace-nowrap px-3 text-center":F?"max-w-56 shrink-0 px-3 text-center":ae?"px-2 !min-w-0 text-center":se?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":F?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",b?f??(z?d?"h-[38px]":"h-[31px]":"h-7"):null,b?Z?"text-foreground":"text-muted-foreground hover:text-foreground":null,b?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:k.title??k.label,children:b?e.jsxs(e.Fragment,{children:[l("relative flex h-4 w-4 shrink-0 items-center justify-center"),E?e.jsx("span",{className:"animated-tabs__label truncate",children:k.label}):null]}):e.jsxs("span",{className:ie("flex min-w-0 flex-nowrap items-center gap-1.5",!F&&"justify-center"),children:[l(ie("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",Z?"text-[var(--primary-base)]":"text-muted-foreground")),e.jsx("span",{className:"truncate leading-[1.2]",children:k.label})]})}),Q&&!W?e.jsx("button",{type:"button",onPointerDown:I=>{I.stopPropagation()},onClick:I=>{I.stopPropagation(),i?.(k.id)},className:ie("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",b?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",b?Z?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":Z?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":k.closeLabel??`Close ${k.label} tab`,title:k.closeLabel??`Close ${k.label} tab`,children:e.jsx(K,{name:"close",className:"h-3 w-3"})}):null]})},k.id)})]})]});return R?e.jsxs(wn,{sensors:D,collisionDetection:yn,onDragEnd:fe,modifiers:[Ns],children:[e.jsx(bn,{items:re,strategy:vs,children:we}),e.jsx(ws,{dropAnimation:null})]}):we},Wt=280,Ft=280,Bt=500,Es=({isOpen:t,isMobile:n,children:o,className:i,topBar:a})=>{const m=ee(y=>y.sidebarWidth),w=ee(y=>y.setSidebarWidth),[u,f]=r.useState(!1),g=r.useRef(0),v=r.useRef(m||Wt),h=r.useRef(null),c=r.useRef(null),P=r.useRef(null),d=r.useCallback(y=>Math.min(Bt,Math.max(Ft,y)),[]),C=r.useCallback(y=>{const b=P.current;b&&(b.style.width=`${y}px`,b.style.minWidth=`${y}px`,b.style.maxWidth=`${y}px`,b.style.setProperty("--oc-left-sidebar-width",`${y}px`))},[]);r.useEffect(()=>{n&&u&&f(!1)},[n,u]),r.useEffect(()=>{u||(h.current=null,c.current=null)},[u]);const j=or(t);if(n)return null;const N=Math.min(Bt,Math.max(Ft,m||Wt)),T=j.layoutVisible?N:0,B=y=>{if(t){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}c.current=y.pointerId,f(!0),g.current=y.clientX,v.current=T,h.current=T,C(T),y.preventDefault()}},re=y=>{if(n||!u||c.current!==y.pointerId)return;const b=y.clientX-g.current,G=d(v.current+b);h.current!==G&&(h.current=G,C(G))},F=y=>{if(c.current!==y.pointerId||n)return;try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}const b=d(h.current??T);c.current=null,h.current=null,f(!1),w(b)},te=u?h.current??T:T,z=u?te:T;return e.jsxs("aside",{ref:P,className:ie("relative flex h-full overflow-hidden motion-reduce:transition-none","bg-sidebar",i),style:{width:`${z}px`,minWidth:`${z}px`,maxWidth:`${z}px`,"--oc-left-sidebar-width":`${u?te:N}px`,overflowX:"clip",transform:u||j.slidIn?"translateX(0)":"translateX(-100%)",transition:u?"none":j.transition},"aria-hidden":!t||z===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:ie("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",u&&"bg-[var(--interactive-border)]"),onPointerDown:B,onPointerMove:re,onPointerUp:F,onPointerCancel:F,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:ie("relative z-10 flex h-full shrink-0 flex-col",u&&"pointer-events-none",!t&&"pointer-events-none select-none"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[a,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(Ne,{children:o})})]})]})},Ts=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},zt=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Fe=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"&&Ts(n.center)&&zt(n.attributes)&&zt(n.computedStyle)&&Array.isArray(n.ancestry)},St=({pageUrl:t,viewport:n,devicePixelRatio:o,target:i,screenshotAttached:a,intro:m})=>{const w=i.text.trim(),u=Object.entries(i.attributes).map(([P,d])=>`${P}="${d}"`).join(" "),f=i.computedStyle,g=i.bounds,v=i.center,h=m.replace(/[.:]+$/g,""),c=i.ancestry.map(P=>P.selectorPart).join(" > ");return[`${h}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${o}`,`Screenshot: ${a?"attached":"not attached"}`,`Element: ${i.tag}`,w?`Text: ${w}`:null,`- Selector: ${i.selector}`,`- Path: ${i.path}`,c?`- Ancestry: ${c}`:null,u?`- Attributes: ${u}`:null,`- Bounds: x=${Math.round(g.x)}, y=${Math.round(g.y)}, width=${Math.round(g.width)}, height=${Math.round(g.height)}`,`- Center: x=${Math.round(v.x)}, y=${Math.round(v.y)}`,`Styles: display=${f.display}; position=${f.position}; font=${f.fontWeight} ${f.fontSize} / ${f.lineHeight} ${f.fontFamily}; color=${f.color}; background=${f.backgroundColor}; z-index=${f.zIndex}`].filter(P=>typeof P=="string").join(`
|
|
3
|
-
`)},ke=new Map,_s=3e4,Ct=t=>{const n=ke.get(t);return n?n.expiresAt-Date.now()<=_s?(ke.delete(t),null):n:null},Ds=t=>{try{return new URL(t).origin}catch{return t}},Be="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",at=new Map;function Cn(t){const n="#ffffff",o=t.defaultView??window;try{const i=t.body?o.getComputedStyle(t.body).backgroundColor:"";if(i&&i!=="rgba(0, 0, 0, 0)"&&i!=="transparent")return i;const a=o.getComputedStyle(t.documentElement).backgroundColor;if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a}catch{}return n}const Nn=t=>new Promise((n,o)=>{const i=new FileReader;i.onloadend=()=>n(typeof i.result=="string"?i.result:Be),i.onerror=()=>o(i.error??new Error("Failed to read image blob")),i.readAsDataURL(t)}),As=async(t,n=.82)=>{const o=await new Promise(i=>t.toBlob(i,"image/jpeg",n));return o&&(await Nn(o)).split(",",2)[1]||""},it=async(t,n)=>{try{const o=await fetch(t,{credentials:n});return o.ok?await Nn(await o.blob()):null}catch{return null}},Ms=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,o=Ct(n);if(o)return`${o.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const i=at.get(n),a=i??(async()=>{try{const w=await et("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!w.ok)return ke.delete(n),null;const u=await w.json(),f=typeof u.proxyBasePath=="string"?u.proxyBasePath:"",g=typeof u.expiresAt=="number"?u.expiresAt:0;if(!f)return ke.delete(n),null;const v={proxyBasePath:f,expiresAt:g};return ke.set(n,v),v}catch{return ke.delete(n),null}finally{at.delete(n)}})();i||at.set(n,a);const m=await a;return m?`${m.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},kn=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 it(o.toString(),"include")??Be;const i=await Ms(o),a=i?await it(i,"include"):null;return a||(await it(o.toString(),"omit")??Be)}catch{return Be}},Is=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const o=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let i=t;for(const a of o){const m=a[2]||"";if(!m||m.startsWith("data:"))continue;const w=await kn(m,n);i=i.replace(a[0],`url("${w}")`)}return i},Ut=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),Pn=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},Ls=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},Os=(t,n,o)=>{const i=[],a=t.defaultView??window,w=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const u of w){const f=u.textContent?.replace(/\s+/g," ").trim()??"";if(!f||!f.includes(" "))continue;const g=u.getBoundingClientRect();if(g.width<=0||g.height<=0||g.right<0||g.bottom<0||g.left>n||g.top>o)continue;const v=a.getComputedStyle(u);if(v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)continue;const h=v.getPropertyValue("text-wrap"),c=v.getPropertyValue("text-wrap-mode"),P=v.whiteSpace.includes("nowrap")||h==="nowrap"||c==="nowrap",d=g.height<=Ls(v)*1.7;!P&&(!d||g.width>n*.72)||(i.push(Pn(u)),u.style.whiteSpace="nowrap",u.style.overflowWrap="normal",u.style.wordBreak="normal",u.style.setProperty("text-wrap","nowrap"),u.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let u=i.length-1;u>=0;u-=1)i[u]?.()}},$s=(t,n,o,i)=>{const a=[],m=t.defaultView??window,w=m.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,u=m.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,f=Array.from(t.querySelectorAll("*")).filter(g=>{const v=m.getComputedStyle(g);if(v.position!=="fixed"||v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)return!1;const h=g.getBoundingClientRect();return h.width>0&&h.height>0&&h.right>=0&&h.bottom>=0&&h.left<=n&&h.top<=o}).filter((g,v,h)=>!h.some((c,P)=>P<v&&c.contains(g)));for(const g of f){const v=g.getBoundingClientRect(),h=m.getComputedStyle(g),c=Math.ceil(v.width)+8,P=Math.ceil(v.height)+2;i?.add(g),a.push(Pn(g)),g.style.position="absolute",g.style.top=`${v.top+u}px`,g.style.left=`${v.left+w}px`,g.style.right="auto",g.style.bottom="auto",g.style.width=`${c}px`,g.style.minWidth=`${c}px`,g.style.height=`${P}px`,g.style.minHeight=`${P}px`,g.style.margin="0",g.style.boxSizing="border-box",g.style.transform="none",h.zIndex!=="auto"&&(g.style.zIndex=h.zIndex)}return()=>{for(let g=a.length-1;g>=0;g-=1)a[g]?.()}},Rn=async(t,n,o,i={})=>{const a=[],m=t.defaultView??window,w=h=>{if(h===t.documentElement||h===t.body)return!0;try{const c=h.getBoundingClientRect();return c.width>0&&c.height>0&&c.right>=0&&c.bottom>=0&&c.left<=n&&c.top<=o}catch{return!1}};if(i.applyLayoutWorkarounds){const h=new WeakSet;a.push($s(t,n,o,h)),a.push(Os(t,n,o))}const u=new Map;for(const h of Array.from(t.images))u.set(h,h.currentSrc||h.src||h.getAttribute("src")||"");const f=Array.from(t.querySelectorAll("picture"));for(const h of f){const c=Array.from(h.querySelectorAll("source"));if(c.length===0)continue;const P=c.map(d=>({source:d,srcset:d.getAttribute("srcset"),sizes:d.getAttribute("sizes")}));a.push(()=>{for(const d of P)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 c)d.removeAttribute("srcset"),d.removeAttribute("sizes")}const g=Array.from(t.images).filter(h=>w(h));await Promise.all(g.map(async h=>{const c=u.get(h)||h.currentSrc||h.src||h.getAttribute("src")||"";if(!c)return;await Ut(h);const P=await kn(c,t),d={src:h.getAttribute("src"),srcset:h.getAttribute("srcset"),sizes:h.getAttribute("sizes")};a.push(()=>{d.src===null?h.removeAttribute("src"):h.setAttribute("src",d.src),d.srcset===null?h.removeAttribute("srcset"):h.setAttribute("srcset",d.srcset),d.sizes===null?h.removeAttribute("sizes"):h.setAttribute("sizes",d.sizes)}),h.removeAttribute("srcset"),h.removeAttribute("sizes"),h.setAttribute("src",P||Be),await Ut(h)}));const v=Array.from(t.querySelectorAll("*")).filter(w);return await Promise.all(v.map(async h=>{const c=m.getComputedStyle(h).backgroundImage;if(!c||c==="none"||!c.includes("url("))return;const P=await Is(c,t);if(P===c)return;const d=h.style.backgroundImage;a.push(()=>{h.style.backgroundImage=d}),h.style.backgroundImage=P})),()=>{for(let h=a.length-1;h>=0;h-=1)try{a[h]?.()}catch{}}},Ws=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},Je=(...t)=>{Ws()&&console.info("[preview-capture]",...t)},En=(t,n=8)=>{const o=[];try{const i=t.querySelectorAll("*");for(const a of i){const m=a.scrollTop||0,w=a.scrollLeft||0;if(m<=0&&w<=0)continue;const u=a.tagName.toLowerCase(),f=a.id?`#${a.id}`:"",g=typeof a.className=="string"&&a.className?`.${a.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(o.push({selector:`${u}${f}${g}`,scrollTop:m,scrollLeft:w,clientWidth:a.clientWidth,clientHeight:a.clientHeight,scrollWidth:a.scrollWidth,scrollHeight:a.scrollHeight}),o.length>=n)break}}catch{}return o},Ke="data-oc-fixed-pin",Fs=(t,n,o)=>{if(n<=0&&o<=0)return()=>{};const i=t.defaultView;if(!i)return()=>{};const a=[],m=[];try{for(const w of t.querySelectorAll("*")){if(i.getComputedStyle(w).position!=="fixed")continue;const u=w.getBoundingClientRect();if(!(u.width>0&&u.height>0))continue;w.setAttribute(Ke,JSON.stringify({top:u.top+o,left:u.left+n,width:u.width,height:u.height})),a.push(w);const f=w.tagName.toLowerCase(),g=typeof w.className=="string"&&w.className?`.${w.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";m.push({selector:`${f}${g}`,top:Math.round(u.top),left:Math.round(u.left),width:Math.round(u.width),height:Math.round(u.height)})}}catch{}return Je("tagged fixed elements",m),()=>{for(const w of a)try{w.removeAttribute(Ke)}catch{}}},Bs={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const o of n.querySelectorAll(`[${Ke}]`)){let i;try{i=JSON.parse(o.getAttribute(Ke)||"")}catch{continue}o.style.setProperty("position","absolute","important"),o.style.setProperty("top",`${i.top}px`,"important"),o.style.setProperty("left",`${i.left}px`,"important"),o.style.setProperty("right","auto","important"),o.style.setProperty("bottom","auto","important"),o.style.setProperty("width",`${i.width}px`,"important"),o.style.setProperty("height",`${i.height}px`,"important"),o.removeAttribute(Ke)}}},We="data-oc-scroll-pin",zs=t=>{const n=[],o=En(t,64);try{const m=t.documentElement,w=t.body;for(const u of t.querySelectorAll("*")){const f=u.scrollTop||0,g=u.scrollLeft||0;if(f<=0&&g<=0)continue;const v=u!==m&&u!==w;v&&u.setAttribute(We,JSON.stringify({top:f,left:g})),n.push({el:u,top:f,left:g,tagged:v})}}catch{}return{reapply:()=>{for(const m of n)try{m.el.scrollHeight,m.el.scrollTop!==m.top&&(m.el.scrollTop=m.top),m.el.scrollLeft!==m.left&&(m.el.scrollLeft=m.left)}catch{}},cleanup:()=>{for(const m of n)if(m.tagged)try{m.el.removeAttribute(We)}catch{}},snapshot:o}},Us={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 i of n.querySelectorAll(`[${We}]`)){let a;try{a=JSON.parse(i.getAttribute(We)||"")}catch{i.removeAttribute(We);continue}const m=`translate(${-a.left}px, ${-a.top}px)`,w=i.children.length===1&&i.firstElementChild instanceof HTMLElement&&i.firstElementChild.style.willChange==="transform"?i.firstElementChild:null;if(w)w.style.transform=m;else{i.style.overflow="hidden";const u=o.createElement("div");for(u.style.transform=m,u.style.willChange="transform",u.style.display="inline-block",u.style.width="100%";i.firstChild;)u.appendChild(i.firstChild);i.appendChild(u)}i.removeAttribute(We)}}},Tn=async(t,n)=>{if(typeof window<"u")try{const o=t.getBoundingClientRect(),i=await Zt("desktop_capture_page_rect",{x:o.left,y:o.top,width:o.width,height:o.height});if(!i)throw new Error("Desktop screenshot capture is not available");const a=new Image;await new Promise((d,C)=>{a.onload=()=>d(),a.onerror=()=>C(new Error("Failed to load desktop preview screenshot")),a.src=`data:${i.mime};base64,${i.base64}`});const m=Math.max(1,a.naturalWidth||i.width||Math.floor(o.width)),w=Math.max(1,a.naturalHeight||i.height||Math.floor(o.height)),f=Math.min(1,1200/m),g=document.createElement("canvas");g.width=Math.floor(m*f),g.height=Math.floor(w*f);const v=g.getContext("2d");if(!v)return null;v.scale(f,f),v.drawImage(a,0,0,m,w);const h=m/Math.max(1,o.width),c=w/Math.max(1,o.height);v.fillStyle="rgba(37, 99, 235, 0.28)",v.strokeStyle="rgb(37, 99, 235)",v.lineWidth=Math.max(2,2*h),v.fillRect(n.bounds.x*h,n.bounds.y*c,n.bounds.width*h,n.bounds.height*c),v.strokeRect(n.bounds.x*h,n.bounds.y*c,n.bounds.width*h,n.bounds.height*c);const P=await new Promise(d=>g.toBlob(d,"image/jpeg",.82));return P?new File([P],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(o){return console.warn("[preview] failed to capture annotation screenshot:",o),null}return await Vs(t,n)},Nt=async(t,n,o,i,a,m)=>{if(!t)return null;try{const w=new Image;await new Promise((j,N)=>{w.onload=()=>j(),w.onerror=()=>N(new Error("Failed to load desktop browser screenshot")),w.src=`data:image/jpeg;base64,${t}`});const u=Math.max(1,w.naturalWidth||n),f=Math.max(1,w.naturalHeight||o),v=Math.min(1,1200/u),h=document.createElement("canvas");h.width=Math.floor(u*v),h.height=Math.floor(f*v);const c=h.getContext("2d");if(!c)return null;c.scale(v,v),c.drawImage(w,0,0,u,f);const P=u/Math.max(1,i||u),d=f/Math.max(1,a||f);c.fillStyle="rgba(37, 99, 235, 0.14)",c.strokeStyle="rgb(37, 99, 235)",c.lineWidth=Math.max(2,2*P),c.fillRect(m.bounds.x*P,m.bounds.y*d,m.bounds.width*P,m.bounds.height*d),c.strokeRect(m.bounds.x*P,m.bounds.y*d,m.bounds.width*P,m.bounds.height*d);const C=await new Promise(j=>h.toBlob(j,"image/jpeg",.82));return C?new File([C],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}};async function Hs(t,n){try{const o=t.contentWindow,i=t.contentDocument??o?.document,a=i?.documentElement;if(!o||!i||!a)return null;const m=t.getBoundingClientRect(),w=Math.max(1,Math.ceil(o.innerWidth||t.clientWidth||m.width)),u=Math.max(1,Math.ceil(o.innerHeight||t.clientHeight||m.height)),f=i.body,g=i.scrollingElement instanceof HTMLElement?i.scrollingElement:null,v=o.scrollX||0,h=o.scrollY||0,c=o.pageXOffset||0,P=o.pageYOffset||0,d=o.visualViewport?.pageLeft||o.visualViewport?.offsetLeft||0,C=o.visualViewport?.pageTop||o.visualViewport?.offsetTop||0,j=a.scrollLeft||0,N=a.scrollTop||0,T=f?.scrollLeft||0,B=f?.scrollTop||0,re=g?.scrollLeft||0,F=g?.scrollTop||0,te=Math.max(v,c,d,j,T,re),z=Math.max(h,P,C,N,B,F);Je("scroll sources",{windowScrollX:v,windowScrollY:h,pageScrollX:c,pageScrollY:P,visualViewportScrollX:d,visualViewportScrollY:C,rootScrollX:j,rootScrollY:N,bodyScrollX:T,bodyScrollY:B,scrollingElementScrollX:re,scrollingElementScrollY:F,scrollingElementTag:g?.tagName?.toLowerCase()??null,resolvedScrollX:te,resolvedScrollY:z,nestedScrolledElements:En(i)});const y=Math.max(w,a.scrollWidth||0,f?.scrollWidth||0,Math.ceil(a.getBoundingClientRect().width||0)),b=Math.max(u,a.scrollHeight||0,f?.scrollHeight||0,Math.ceil(a.getBoundingClientRect().height||0)),G=Math.min(2,Math.max(1,window.devicePixelRatio||1)),U=a.style.scrollBehavior,O=f?.style.scrollBehavior??"";a.style.scrollBehavior="auto",f&&(f.style.scrollBehavior="auto");const H=zs(i);Je("nested scroll snapshot",H.snapshot);let ne=()=>{},R=()=>{};try{await i.fonts?.ready.catch(()=>{}),ne=await Rn(i,w,u,{applyLayoutWorkarounds:!1}),o.scrollTo(te,z),R=Fs(i,te,z),H.reapply();const{snapdom:J}=await Re(async()=>{const{snapdom:x}=await import("./vendor-zumer-snapdom-Btyu_Xi2.js");return{snapdom:x}},[]),S={backgroundColor:Cn(i),cache:"disabled",dpr:G,embedFonts:!0,fast:!1,height:b,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[Bs,Us],quality:.82,width:y},q=await(await J(a,S)).toCanvas();if(!q.width||!q.height)return null;const M=q.width/Math.max(1,y),A=q.height/Math.max(1,b),ce=Math.min(q.width,Math.max(1,Math.round(w*M))),ue=Math.min(q.height,Math.max(1,Math.round(u*A))),de=Math.max(0,q.width-ce),ye=Math.max(0,q.height-ue),pe=Math.min(de,Math.max(0,Math.round(te*M))),xe=Math.min(ye,Math.max(0,Math.round(z*A)));Je("capture geometry",{viewportWidth:w,viewportHeight:u,captureWidth:y,captureHeight:b,canvasWidth:q.width,canvasHeight:q.height,xScale:M,yScale:A,sourceX:pe,sourceY:xe,sourceWidth:ce,sourceHeight:ue});const he=i.createElement("canvas");he.width=ce,he.height=ue;const D=he.getContext("2d");if(!D)return null;D.drawImage(q,pe,xe,ce,ue,0,0,ce,ue);const $=await As(he,.82);return $?await Nt($,w,u,w,u,n):null}finally{R(),H.cleanup(),ne(),o.scrollTo(te,z),H.reapply(),a.style.scrollBehavior=U,f&&(f.style.scrollBehavior=O)}}catch(o){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",o),null}}async function Vs(t,n){const o=await Hs(t,n);if(o)return o;try{const i=t.contentWindow,a=t.contentDocument??i?.document,m=a?.documentElement;if(!i||!a||!m)return null;const w=t.getBoundingClientRect(),u=Math.max(1,Math.ceil(i.innerWidth||t.clientWidth||w.width)),f=Math.max(1,Math.ceil(i.innerHeight||t.clientHeight||w.height)),g=i.scrollX||a.documentElement.scrollLeft||a.body?.scrollLeft||0,v=i.scrollY||a.documentElement.scrollTop||a.body?.scrollTop||0,h=a.body,c=Math.max(f,m.scrollHeight||0,h?.scrollHeight||0),P=Math.min(2,Math.max(1,window.devicePixelRatio||1)),d=m.style.scrollBehavior,C=h?.style.scrollBehavior??"";m.style.scrollBehavior="auto",h&&(h.style.scrollBehavior="auto");let j="",N=()=>{};try{await a.fonts?.ready.catch(()=>{}),N=await Rn(a,u,f,{applyLayoutWorkarounds:!0}),i.scrollTo(g,v);const{getFontEmbedCSS:B,toJpeg:re}=await Re(async()=>{const{getFontEmbedCSS:te,toJpeg:z}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:te,toJpeg:z}},[]),F=await B(m).catch(()=>"");j=await re(m,{quality:.82,pixelRatio:P,width:u,height:f,backgroundColor:Cn(a),imagePlaceholder:Be,fontEmbedCSS:F||void 0,style:{transform:`translate(${-g}px, ${-v}px)`,transformOrigin:"top left",minWidth:`${u}px`,minHeight:`${c}px`},cacheBust:!0})}finally{N(),i.scrollTo(g,v),m.style.scrollBehavior=d,h&&(h.style.scrollBehavior=C)}const T=j.split(",",2)[1]||"";return T?await Nt(T,u,f,u,f,n):null}catch(i){return console.warn("[preview] failed to capture iframe DOM screenshot:",i),null}}const Ht=200,Ks=(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",nt=t=>{const n=st.getState();n.setPendingSyntheticParts([...n.pendingSyntheticParts??[],{text:t,synthetic:!0}])},_n=async t=>{const n=await t.json().catch(()=>({}));if(!t.ok)return{ok:!1,message:typeof n.error=="string"?n.error:`HTTP ${t.status}`};const o=typeof n.proxyBasePath=="string"?n.proxyBasePath:"",i=typeof n.previewToken=="string"?n.previewToken:"";return!o||!i?{ok:!1,message:"Could not start preview proxy."}:{ok:!0,target:{proxyBasePath:o,previewToken:i,expiresAt:typeof n.expiresAt=="number"?n.expiresAt:0}}},Dn=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Vt=(t,n,o)=>{t.postMessage(o,Dn(n))},Xs=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}},Kt=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}};function An(t){const[n,o]=r.useState("");return r.useEffect(()=>{if(!t){o("");return}let i=!1;return o(""),Fn(en()).then(a=>{!i&&a&&o(t)}).catch(()=>{}),()=>{i=!0}},[t]),n}const Mn=`new Promise((resolve) => {
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-DMvRLRN1.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-BZpvAhrX.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BXgR2dKM.css","assets/useAppFontEffects-C9QQrBIx.js","assets/vendor-base-ui-CdaWtC7e.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-egSD9pqj.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-0f_rLdj_.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-CNlncqrr.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/gitStatusPredicates-D_31YElh.js","assets/web-components-CYngz9Ml.js","assets/computeVirtualFileMetrics-CsAu9rOt.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-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.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-CFpvcZ1g.js","assets/isDiffPlainText-BX609Lau.js","assets/vendor-diff-C3JhlQdm.js","assets/runtimeEndpointReset-B6_gFvBD.js","assets/SessionUnreadDot-CDRZswx-.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/permissionStore-iKN1K2_x.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/contextFileOpenGuard-rILslsBJ.js","assets/FilesView-CNHu4RnC.js","assets/FileSaveConflictDialog-DGa9u43J.js","assets/vendor-react-drawio-BYDptOsj.js","assets/useFilesViewSearch-BTZutbn-.js","assets/JsonTreeView-C2X5oXQm.js","assets/Virtualizer-BSHVMKgK.js","assets/isFilePlainText-FgBWqu9b.js","assets/vendor-codemirror-search-BV44140v.js","assets/vendor-replit-codemirror-vim-DaSwPsXt.js","assets/GitView-Cbepz-bR.js","assets/collapsible-DesjbW8a.js","assets/DiagramView-BvrCkm_z.js","assets/SettingsView-hyAGp836.js","assets/vendor-qrcode-B0KNSajT.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/SettingsWindow-BfPUzBbq.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as r,j as e,r as Se,e as Wn}from"./vendor-react-B5Z1Mdn3.js";import"./vendor-katex-CNckGUMB.js";import{u as ee,n as ie,l as et,B as Zt,C as Fn,f as en,D as tn,a as Bn,E as zn,F as Un,G as Pe,H as Hn,I as Te,J as Vn,K as Kn,L as Xn,M as Rt,N as He,o as qn,O as Gn,P as Yn,Q as Jn,R as Qn,S as nn,T as rn,U as Zn,V as er,W as tr,y as nr,X as rr,z as sr,t as sn,x as or}from"./index-BZpvAhrX.js";import{_ as Re}from"./vendor-vite-runtime-DD1OZmLC.js";import{h as ar,q as ir,t as lr,v as cr,w as dr,x as ur,y as on,z as an,B as ut,T as ln,E as hr,G as pr,I as fr,j as mr,p as gr,n as xr,o as wr,H as Et,C as Tt,A as _t,S as Dt,k as yr,l as br,m as vr,F as jr,W as Sr}from"./runtimeEndpointReset-B6_gFvBD.js";import{_ as rt,I as K,E as Ne,$ as st,f as je,t as ve,a0 as Cr,B as me,o as tt,P as cn,a1 as ft,a2 as Nr,a3 as Le,a4 as Oe,a5 as kr,a6 as $e,a7 as Pr,a8 as mt,a9 as Rr,aa as Er,ab as gt,ac as qe,ad as dn,ae as At,af as Tr,ag as xt,ah as wt,ai as yt,aj as bt,ak as vt,al as _r,am as Dr,an as Ar,ao as Mr,ap as un,y as Ie,aq as Ve,ar as Ir,as as Lr,at as De,au as hn,av as Or,aw as jt,ax as $r,ay as pn,az as Wr,aA as Fr,aB as Br,aC as Mt,aD as zr,b as Ur,c as Hr,aE as Vr,a as It,aF as Kr,r as ot,aG as Xr,aH as qr,aI as Gr,aJ as Yr,aK as Jr,aL as Qr,aM as Zr,aN as ze,aO as Ue,aP as es,Y as ts,Z as ns,R as rs,M as ss,T as os,K as as,S as is,W as ls,N as cs,O as ds,V as us,X as hs}from"./useAppFontEffects-C9QQrBIx.js";import{v as fn,g as mn}from"./contextFileOpenGuard-rILslsBJ.js";import{g as gn,u as ps,s as fs,i as ms,a as gs,b as xs}from"./useFilesViewSearch-BTZutbn-.js";import{c as xn,d as ht,P as ws,D as wn,e as yn,f as ys,T as bs,M as vs}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{S as bn,h as js,u as vn,a as Ss,v as Cs}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as jn}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{g as Sn}from"./SessionUnreadDot-CDRZswx-.js";import{u as Lt,a as Ge,m as Ot}from"./vendor-framer-motion-CfplGuM0.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-zustand-GVb4H8HE.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-base-ui-CdaWtC7e.js";import"./vendor-floating-ui-utils-BzXdqYpP.js";import"./vendor-floating-ui-react-dom-BZOGXAGe.js";import"./vendor-floating-ui-dom-WyXykhNi.js";import"./vendor-floating-ui-core-CXmKXOXc.js";import"./vendor-use-sync-external-store-D0AXkdQC.js";import"./vendor-tanstack-react-virtual-2skouoFw.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-xterm-xterm-CrXqRur4.js";import"./permissionStore-iKN1K2_x.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-sonner-BDtm25td.js";import"./vendor-codemirror-view-Ct4T37Ue.js";import"./vendor-codemirror-state-CNWM3Q8V.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./runtimeSurface-egSD9pqj.js";import"./vendor-cmdk-zXx6sGnS.js";import"./vendor-radix-ui-react-dialog-D2yhEu2p.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-8xy6TJML.js";import"./vendor-radix-ui-react-context-CFsX-AUC.js";import"./vendor-radix-ui-react-id-D2kS9K1j.js";import"./vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js";import"./vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js";import"./vendor-radix-ui-react-dismissable-layer-DrorBNg9.js";import"./vendor-radix-ui-react-primitive-DkH8dMOR.js";import"./vendor-radix-ui-react-slot-BIDFZX0-.js";import"./vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js";import"./vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js";import"./vendor-radix-ui-react-focus-scope-D2BkImwt.js";import"./vendor-radix-ui-react-portal-YgCRIyi7.js";import"./vendor-radix-ui-react-presence-D432pCMB.js";import"./vendor-radix-ui-react-focus-guards-BfdFmL7c.js";import"./vendor-react-remove-scroll-vR1dy1aP.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-CSAHp1YF.js";import"./vendor-react-style-singleton-Ctw6HnYx.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-Vv4V8Nd1.js";import"./vendor-use-callback-ref-CVVuCyLj.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BByA_dGF.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-DuOEwJ3f.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-wd6iRebq.js";import"./vendor-codemirror-lang-json-CZ07HmNC.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-djiuoTi8.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CKHqhW5R.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-DtcZDGqe.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-0f_rLdj_.js";import"./vendor-codemirror-lang-python-DzzokVau.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-CNlncqrr.js";import"./vendor-dnd-kit-accessibility-DZKKhs9S.js";import"./vendor-motion-dom-DhJ-sYS5.js";import"./vendor-motion-utils-CKEGc_YG.js";const Ns=280,$t=4,ks=({transform:t})=>({...t,y:0}),Ps=({id:t,children:n,className:o})=>{const{attributes:i,listeners:a,setNodeRef:m,transform:w,transition:u,isDragging:f}=vn({id:t});return e.jsx("div",{ref:m,"data-sortable-tab-id":t,style:{transform:jn.Transform.toString(w),transition:u},className:ie("h-full rounded-md",o,f&&"opacity-50"),...i,...a,children:n})},Rs=({id:t,children:n,className:o})=>e.jsx("div",{className:ie("h-full",o),"data-sortable-tab-id":t,children:n}),Es=({items:t,activeId:n,onSelect:o,onClose:i,onReorder:a,layoutMode:m="scrollable",variant:w="default",activePillInsetClassName:u,activePillButtonClassName:f,inactiveTabsIconOnly:g=!1,animateActivePill:v,activePillLowercase:h=!0,nonCompositedIndicator:c=!1,className:P})=>{const d=ee(k=>k.isMobile),{isTablet:C}=rt(),j=d||C,N=r.useRef(null),[T,B]=r.useState({left:!1,right:!1}),re=r.useMemo(()=>t.map(k=>k.id),[t]),F=m==="scrollable",te=w==="default",z=w==="active-pill",b=z||w==="animated",G=te,U=b||G,O=z&&F,H=b,ne=v??b,R=typeof a=="function",J=R?Ps:Rs,S=r.useRef(new Map),[L,q]=r.useState(null),[M,A]=r.useState(!1),[ce,ue]=r.useState(null),de=r.useRef(!1),ye=r.useRef(0),pe=r.useRef(n),xe=r.useRef(null),he=r.useMemo(()=>{if(!U||!ce||!n||ce===n)return 0;const k=t.findIndex(ae=>ae.id===ce),Z=t.findIndex(ae=>ae.id===n);return k<0||Z<0?0:k>Z?$t:-$t},[n,t,ce,U]),D=xn(ht(ws,{activationConstraint:{distance:8}})),$=r.useCallback((k,Z)=>!k||!Z?k===Z:Math.abs(k.left-Z.left)<.5&&Math.abs(k.top-Z.top)<.5&&Math.abs(k.width-Z.width)<.5&&Math.abs(k.height-Z.height)<.5,[]),x=r.useCallback((k,Z)=>{if(Z){S.current.set(k,Z);return}S.current.delete(k)},[]),_=r.useCallback(()=>{if(!U||!n){q(Q=>Q===null?Q:null);return}const k=N.current,Z=S.current.get(n);if(!k||!Z){q(Q=>Q===null?Q:null);return}let ae=0,E=0,oe=Z;for(;oe&&oe!==k;)ae+=oe.offsetLeft,E+=oe.offsetTop,oe=oe.offsetParent;const se={left:ae,top:E,width:Z.offsetWidth,height:Z.offsetHeight};q(Q=>$(Q,se)?Q:se)},[n,$,U]),V=r.useCallback(()=>{if(!F){B({left:!1,right:!1});return}const k=N.current;if(!k){B({left:!1,right:!1});return}B({left:k.scrollLeft>2,right:k.scrollLeft+k.clientWidth<k.scrollWidth-2})},[F]);r.useEffect(()=>{if(!F){B({left:!1,right:!1});return}const k=N.current;if(!k)return;V(),k.addEventListener("scroll",V,{passive:!0});const Z=new ResizeObserver(V);return Z.observe(k),()=>{k.removeEventListener("scroll",V),Z.disconnect()}},[F,t.length,V]),r.useEffect(()=>{if(!U){q(null);return}_();const k=N.current;if(!k)return;const Z=new ResizeObserver(()=>{performance.now()-ye.current>Ns&&A(!1),_()});if(Z.observe(k),n){const ae=S.current.get(n);ae&&Z.observe(ae)}return()=>{Z.disconnect()}},[n,t.length,_,U]),r.useLayoutEffect(()=>{_()});const le=re.join("\0");r.useLayoutEffect(()=>{if(!U){de.current=!1,A(!1);return}const k=xe.current!==le;if(xe.current=le,!de.current){de.current=!0,pe.current=n;return}const Z=pe.current!==n;if(pe.current=n,!Z||k){A(!1);return}ye.current=performance.now(),A(!0)},[n,le,U]),r.useEffect(()=>{if(!F||!n)return;const k=N.current;if(!k)return;const Z=window.requestAnimationFrame(()=>{const ae=typeof window.CSS?.escape=="function"?window.CSS.escape(n):n.replace(/"/g,'\\"'),E=k.querySelector(`[data-sortable-tab-id="${ae}"]`);E&&(E.scrollIntoView({block:"nearest",inline:"nearest"}),V())});return()=>{window.cancelAnimationFrame(Z)}},[n,F,t.length,V]);const fe=r.useCallback(k=>{if(!a)return;const{active:Z,over:ae}=k;!ae||Z.id===ae.id||a(String(Z.id),String(ae.id))},[a]),we=e.jsxs("div",{className:ie("relative flex h-full min-w-0 flex-1",P),children:[F&&T.left?e.jsx("div",{className:ie("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",b?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,F&&T.right?e.jsx("div",{className:ie("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",b?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e.jsxs("div",{ref:N,className:ie("relative flex h-full min-w-0 flex-1",b?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",b&&"@container/pill-tabs",b&&"pill-tabs__track",b&&(u??"gap-0.5 py-0.5"),G&&"items-center overflow-y-hidden",H&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",F?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:F?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[b&&L?e.jsx("div",{className:ie("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",ne&&M&&(c?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:c?{left:`${L.left+he}px`,top:`${L.top}px`,width:`${L.width}px`,height:`${L.height}px`}:{transform:`translate3d(${L.left+he}px, ${L.top}px, 0)`,width:`${L.width}px`,height:`${L.height}px`}}):null,G&&L?e.jsx("div",{className:ie("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",M&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${L.left+he}px, 0, 0)`,width:`${L.width}px`},"aria-hidden":!0}):null,t.map(k=>{const Z=k.id===n,ae=g&&b&&!Z&&!!k.icon,E=!ae,oe=!!k.icon,se=g&&b&&Z&&!F&&!O,Q=k.closable!==!1&&!!i,W=Q&&!!k.icon,s=F||O?void 0:b?se?"flex-none basis-auto":d?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",p=Q?I=>{I.button===1&&(I.preventDefault(),I.stopPropagation(),i?.(k.id))}:void 0,X=Q?I=>{I.button===1&&I.preventDefault()}:void 0,l=I=>oe?e.jsxs("span",{className:I,children:[e.jsx("span",{className:ie("flex items-center justify-center transition-opacity",W&&(j?"opacity-0":"group-hover:opacity-0")),children:k.icon}),W?e.jsx("span",{role:"button",tabIndex:-1,className:ie("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>{Y.stopPropagation(),i?.(k.id)},"aria-label":k.closeLabel??`Close ${k.label} tab`,title:k.closeLabel??`Close ${k.label} tab`,children:e.jsx(K,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return e.jsx(J,{id:k.id,className:s,children:e.jsxs("div",{ref:I=>x(k.id,I),onAuxClick:p,onMouseDown:X,className:ie("group flex h-full min-w-0 flex-nowrap items-center",F||O?"shrink-0":b?"w-full":"w-full min-w-0",b?"relative z-10 bg-transparent":Z?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":Z,"aria-label":ae?k.title??k.label:void 0,onClick:()=>o(k.id),onPointerDown:U?()=>{A(!0),ue(k.id)}:void 0,onPointerUp:U?()=>ue(null):void 0,onPointerLeave:U?()=>ue(null):void 0,onPointerCancel:U?()=>ue(null):void 0,className:ie(b?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",b&&h?"lowercase":null,b&&(ae?"gap-0":"gap-1.5"),b?O?"shrink-0 whitespace-nowrap px-3 text-center":F?"max-w-56 shrink-0 px-3 text-center":ae?"px-2 !min-w-0 text-center":se?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":F?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",b?f??(z?d?"h-[38px]":"h-[31px]":"h-7"):null,b?Z?"text-foreground":"text-muted-foreground hover:text-foreground":null,b?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:k.title??k.label,children:b?e.jsxs(e.Fragment,{children:[l("relative flex h-4 w-4 shrink-0 items-center justify-center"),E?e.jsx("span",{className:"animated-tabs__label truncate",children:k.label}):null]}):e.jsxs("span",{className:ie("flex min-w-0 flex-nowrap items-center gap-1.5",!F&&"justify-center"),children:[l(ie("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",Z?"text-[var(--primary-base)]":"text-muted-foreground")),e.jsx("span",{className:"truncate leading-[1.2]",children:k.label})]})}),Q&&!W?e.jsx("button",{type:"button",onPointerDown:I=>{I.stopPropagation()},onClick:I=>{I.stopPropagation(),i?.(k.id)},className:ie("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",b?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",b?Z?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":Z?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":k.closeLabel??`Close ${k.label} tab`,title:k.closeLabel??`Close ${k.label} tab`,children:e.jsx(K,{name:"close",className:"h-3 w-3"})}):null]})},k.id)})]})]});return R?e.jsxs(wn,{sensors:D,collisionDetection:yn,onDragEnd:fe,modifiers:[ks],children:[e.jsx(bn,{items:re,strategy:js,children:we}),e.jsx(ys,{dropAnimation:null})]}):we},Wt=280,Ft=280,Bt=500,Ts=({isOpen:t,isMobile:n,children:o,className:i,topBar:a})=>{const m=ee(y=>y.sidebarWidth),w=ee(y=>y.setSidebarWidth),[u,f]=r.useState(!1),g=r.useRef(0),v=r.useRef(m||Wt),h=r.useRef(null),c=r.useRef(null),P=r.useRef(null),d=r.useCallback(y=>Math.min(Bt,Math.max(Ft,y)),[]),C=r.useCallback(y=>{const b=P.current;b&&(b.style.width=`${y}px`,b.style.minWidth=`${y}px`,b.style.maxWidth=`${y}px`,b.style.setProperty("--oc-left-sidebar-width",`${y}px`))},[]);r.useEffect(()=>{n&&u&&f(!1)},[n,u]),r.useEffect(()=>{u||(h.current=null,c.current=null)},[u]);const j=ar(t);if(n)return null;const N=Math.min(Bt,Math.max(Ft,m||Wt)),T=j.layoutVisible?N:0,B=y=>{if(t){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}c.current=y.pointerId,f(!0),g.current=y.clientX,v.current=T,h.current=T,C(T),y.preventDefault()}},re=y=>{if(n||!u||c.current!==y.pointerId)return;const b=y.clientX-g.current,G=d(v.current+b);h.current!==G&&(h.current=G,C(G))},F=y=>{if(c.current!==y.pointerId||n)return;try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}const b=d(h.current??T);c.current=null,h.current=null,f(!1),w(b)},te=u?h.current??T:T,z=u?te:T;return e.jsxs("aside",{ref:P,className:ie("relative flex h-full overflow-hidden motion-reduce:transition-none","bg-sidebar",i),style:{width:`${z}px`,minWidth:`${z}px`,maxWidth:`${z}px`,"--oc-left-sidebar-width":`${u?te:N}px`,overflowX:"clip",transform:u||j.slidIn?"translateX(0)":"translateX(-100%)",transition:u?"none":j.transition},"aria-hidden":!t||z===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:ie("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",u&&"bg-[var(--interactive-border)]"),onPointerDown:B,onPointerMove:re,onPointerUp:F,onPointerCancel:F,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:ie("relative z-10 flex h-full shrink-0 flex-col",u&&"pointer-events-none",!t&&"pointer-events-none select-none"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[a,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(Ne,{children:o})})]})]})},_s=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},zt=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),Fe=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"&&_s(n.center)&&zt(n.attributes)&&zt(n.computedStyle)&&Array.isArray(n.ancestry)},St=({pageUrl:t,viewport:n,devicePixelRatio:o,target:i,screenshotAttached:a,intro:m})=>{const w=i.text.trim(),u=Object.entries(i.attributes).map(([P,d])=>`${P}="${d}"`).join(" "),f=i.computedStyle,g=i.bounds,v=i.center,h=m.replace(/[.:]+$/g,""),c=i.ancestry.map(P=>P.selectorPart).join(" > ");return[`${h}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${o}`,`Screenshot: ${a?"attached":"not attached"}`,`Element: ${i.tag}`,w?`Text: ${w}`:null,`- Selector: ${i.selector}`,`- Path: ${i.path}`,c?`- Ancestry: ${c}`:null,u?`- Attributes: ${u}`:null,`- Bounds: x=${Math.round(g.x)}, y=${Math.round(g.y)}, width=${Math.round(g.width)}, height=${Math.round(g.height)}`,`- Center: x=${Math.round(v.x)}, y=${Math.round(v.y)}`,`Styles: display=${f.display}; position=${f.position}; font=${f.fontWeight} ${f.fontSize} / ${f.lineHeight} ${f.fontFamily}; color=${f.color}; background=${f.backgroundColor}; z-index=${f.zIndex}`].filter(P=>typeof P=="string").join(`
|
|
3
|
+
`)},ke=new Map,Ds=3e4,Ct=t=>{const n=ke.get(t);return n?n.expiresAt-Date.now()<=Ds?(ke.delete(t),null):n:null},As=t=>{try{return new URL(t).origin}catch{return t}},Be="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",at=new Map;function Cn(t){const n="#ffffff",o=t.defaultView??window;try{const i=t.body?o.getComputedStyle(t.body).backgroundColor:"";if(i&&i!=="rgba(0, 0, 0, 0)"&&i!=="transparent")return i;const a=o.getComputedStyle(t.documentElement).backgroundColor;if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a}catch{}return n}const Nn=t=>new Promise((n,o)=>{const i=new FileReader;i.onloadend=()=>n(typeof i.result=="string"?i.result:Be),i.onerror=()=>o(i.error??new Error("Failed to read image blob")),i.readAsDataURL(t)}),Ms=async(t,n=.82)=>{const o=await new Promise(i=>t.toBlob(i,"image/jpeg",n));return o&&(await Nn(o)).split(",",2)[1]||""},it=async(t,n)=>{try{const o=await fetch(t,{credentials:n});return o.ok?await Nn(await o.blob()):null}catch{return null}},Is=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,o=Ct(n);if(o)return`${o.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const i=at.get(n),a=i??(async()=>{try{const w=await et("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!w.ok)return ke.delete(n),null;const u=await w.json(),f=typeof u.proxyBasePath=="string"?u.proxyBasePath:"",g=typeof u.expiresAt=="number"?u.expiresAt:0;if(!f)return ke.delete(n),null;const v={proxyBasePath:f,expiresAt:g};return ke.set(n,v),v}catch{return ke.delete(n),null}finally{at.delete(n)}})();i||at.set(n,a);const m=await a;return m?`${m.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},kn=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 it(o.toString(),"include")??Be;const i=await Is(o),a=i?await it(i,"include"):null;return a||(await it(o.toString(),"omit")??Be)}catch{return Be}},Ls=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const o=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let i=t;for(const a of o){const m=a[2]||"";if(!m||m.startsWith("data:"))continue;const w=await kn(m,n);i=i.replace(a[0],`url("${w}")`)}return i},Ut=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),Pn=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},Os=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},$s=(t,n,o)=>{const i=[],a=t.defaultView??window,w=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const u of w){const f=u.textContent?.replace(/\s+/g," ").trim()??"";if(!f||!f.includes(" "))continue;const g=u.getBoundingClientRect();if(g.width<=0||g.height<=0||g.right<0||g.bottom<0||g.left>n||g.top>o)continue;const v=a.getComputedStyle(u);if(v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)continue;const h=v.getPropertyValue("text-wrap"),c=v.getPropertyValue("text-wrap-mode"),P=v.whiteSpace.includes("nowrap")||h==="nowrap"||c==="nowrap",d=g.height<=Os(v)*1.7;!P&&(!d||g.width>n*.72)||(i.push(Pn(u)),u.style.whiteSpace="nowrap",u.style.overflowWrap="normal",u.style.wordBreak="normal",u.style.setProperty("text-wrap","nowrap"),u.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let u=i.length-1;u>=0;u-=1)i[u]?.()}},Ws=(t,n,o,i)=>{const a=[],m=t.defaultView??window,w=m.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,u=m.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,f=Array.from(t.querySelectorAll("*")).filter(g=>{const v=m.getComputedStyle(g);if(v.position!=="fixed"||v.display==="none"||v.visibility==="hidden"||Number(v.opacity)===0)return!1;const h=g.getBoundingClientRect();return h.width>0&&h.height>0&&h.right>=0&&h.bottom>=0&&h.left<=n&&h.top<=o}).filter((g,v,h)=>!h.some((c,P)=>P<v&&c.contains(g)));for(const g of f){const v=g.getBoundingClientRect(),h=m.getComputedStyle(g),c=Math.ceil(v.width)+8,P=Math.ceil(v.height)+2;i?.add(g),a.push(Pn(g)),g.style.position="absolute",g.style.top=`${v.top+u}px`,g.style.left=`${v.left+w}px`,g.style.right="auto",g.style.bottom="auto",g.style.width=`${c}px`,g.style.minWidth=`${c}px`,g.style.height=`${P}px`,g.style.minHeight=`${P}px`,g.style.margin="0",g.style.boxSizing="border-box",g.style.transform="none",h.zIndex!=="auto"&&(g.style.zIndex=h.zIndex)}return()=>{for(let g=a.length-1;g>=0;g-=1)a[g]?.()}},Rn=async(t,n,o,i={})=>{const a=[],m=t.defaultView??window,w=h=>{if(h===t.documentElement||h===t.body)return!0;try{const c=h.getBoundingClientRect();return c.width>0&&c.height>0&&c.right>=0&&c.bottom>=0&&c.left<=n&&c.top<=o}catch{return!1}};if(i.applyLayoutWorkarounds){const h=new WeakSet;a.push(Ws(t,n,o,h)),a.push($s(t,n,o))}const u=new Map;for(const h of Array.from(t.images))u.set(h,h.currentSrc||h.src||h.getAttribute("src")||"");const f=Array.from(t.querySelectorAll("picture"));for(const h of f){const c=Array.from(h.querySelectorAll("source"));if(c.length===0)continue;const P=c.map(d=>({source:d,srcset:d.getAttribute("srcset"),sizes:d.getAttribute("sizes")}));a.push(()=>{for(const d of P)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 c)d.removeAttribute("srcset"),d.removeAttribute("sizes")}const g=Array.from(t.images).filter(h=>w(h));await Promise.all(g.map(async h=>{const c=u.get(h)||h.currentSrc||h.src||h.getAttribute("src")||"";if(!c)return;await Ut(h);const P=await kn(c,t),d={src:h.getAttribute("src"),srcset:h.getAttribute("srcset"),sizes:h.getAttribute("sizes")};a.push(()=>{d.src===null?h.removeAttribute("src"):h.setAttribute("src",d.src),d.srcset===null?h.removeAttribute("srcset"):h.setAttribute("srcset",d.srcset),d.sizes===null?h.removeAttribute("sizes"):h.setAttribute("sizes",d.sizes)}),h.removeAttribute("srcset"),h.removeAttribute("sizes"),h.setAttribute("src",P||Be),await Ut(h)}));const v=Array.from(t.querySelectorAll("*")).filter(w);return await Promise.all(v.map(async h=>{const c=m.getComputedStyle(h).backgroundImage;if(!c||c==="none"||!c.includes("url("))return;const P=await Ls(c,t);if(P===c)return;const d=h.style.backgroundImage;a.push(()=>{h.style.backgroundImage=d}),h.style.backgroundImage=P})),()=>{for(let h=a.length-1;h>=0;h-=1)try{a[h]?.()}catch{}}},Fs=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},Je=(...t)=>{Fs()&&console.info("[preview-capture]",...t)},En=(t,n=8)=>{const o=[];try{const i=t.querySelectorAll("*");for(const a of i){const m=a.scrollTop||0,w=a.scrollLeft||0;if(m<=0&&w<=0)continue;const u=a.tagName.toLowerCase(),f=a.id?`#${a.id}`:"",g=typeof a.className=="string"&&a.className?`.${a.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(o.push({selector:`${u}${f}${g}`,scrollTop:m,scrollLeft:w,clientWidth:a.clientWidth,clientHeight:a.clientHeight,scrollWidth:a.scrollWidth,scrollHeight:a.scrollHeight}),o.length>=n)break}}catch{}return o},Ke="data-oc-fixed-pin",Bs=(t,n,o)=>{if(n<=0&&o<=0)return()=>{};const i=t.defaultView;if(!i)return()=>{};const a=[],m=[];try{for(const w of t.querySelectorAll("*")){if(i.getComputedStyle(w).position!=="fixed")continue;const u=w.getBoundingClientRect();if(!(u.width>0&&u.height>0))continue;w.setAttribute(Ke,JSON.stringify({top:u.top+o,left:u.left+n,width:u.width,height:u.height})),a.push(w);const f=w.tagName.toLowerCase(),g=typeof w.className=="string"&&w.className?`.${w.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";m.push({selector:`${f}${g}`,top:Math.round(u.top),left:Math.round(u.left),width:Math.round(u.width),height:Math.round(u.height)})}}catch{}return Je("tagged fixed elements",m),()=>{for(const w of a)try{w.removeAttribute(Ke)}catch{}}},zs={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const o of n.querySelectorAll(`[${Ke}]`)){let i;try{i=JSON.parse(o.getAttribute(Ke)||"")}catch{continue}o.style.setProperty("position","absolute","important"),o.style.setProperty("top",`${i.top}px`,"important"),o.style.setProperty("left",`${i.left}px`,"important"),o.style.setProperty("right","auto","important"),o.style.setProperty("bottom","auto","important"),o.style.setProperty("width",`${i.width}px`,"important"),o.style.setProperty("height",`${i.height}px`,"important"),o.removeAttribute(Ke)}}},We="data-oc-scroll-pin",Us=t=>{const n=[],o=En(t,64);try{const m=t.documentElement,w=t.body;for(const u of t.querySelectorAll("*")){const f=u.scrollTop||0,g=u.scrollLeft||0;if(f<=0&&g<=0)continue;const v=u!==m&&u!==w;v&&u.setAttribute(We,JSON.stringify({top:f,left:g})),n.push({el:u,top:f,left:g,tagged:v})}}catch{}return{reapply:()=>{for(const m of n)try{m.el.scrollHeight,m.el.scrollTop!==m.top&&(m.el.scrollTop=m.top),m.el.scrollLeft!==m.left&&(m.el.scrollLeft=m.left)}catch{}},cleanup:()=>{for(const m of n)if(m.tagged)try{m.el.removeAttribute(We)}catch{}},snapshot:o}},Hs={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 i of n.querySelectorAll(`[${We}]`)){let a;try{a=JSON.parse(i.getAttribute(We)||"")}catch{i.removeAttribute(We);continue}const m=`translate(${-a.left}px, ${-a.top}px)`,w=i.children.length===1&&i.firstElementChild instanceof HTMLElement&&i.firstElementChild.style.willChange==="transform"?i.firstElementChild:null;if(w)w.style.transform=m;else{i.style.overflow="hidden";const u=o.createElement("div");for(u.style.transform=m,u.style.willChange="transform",u.style.display="inline-block",u.style.width="100%";i.firstChild;)u.appendChild(i.firstChild);i.appendChild(u)}i.removeAttribute(We)}}},Tn=async(t,n)=>{if(typeof window<"u")try{const o=t.getBoundingClientRect(),i=await Zt("desktop_capture_page_rect",{x:o.left,y:o.top,width:o.width,height:o.height});if(!i)throw new Error("Desktop screenshot capture is not available");const a=new Image;await new Promise((d,C)=>{a.onload=()=>d(),a.onerror=()=>C(new Error("Failed to load desktop preview screenshot")),a.src=`data:${i.mime};base64,${i.base64}`});const m=Math.max(1,a.naturalWidth||i.width||Math.floor(o.width)),w=Math.max(1,a.naturalHeight||i.height||Math.floor(o.height)),f=Math.min(1,1200/m),g=document.createElement("canvas");g.width=Math.floor(m*f),g.height=Math.floor(w*f);const v=g.getContext("2d");if(!v)return null;v.scale(f,f),v.drawImage(a,0,0,m,w);const h=m/Math.max(1,o.width),c=w/Math.max(1,o.height);v.fillStyle="rgba(37, 99, 235, 0.28)",v.strokeStyle="rgb(37, 99, 235)",v.lineWidth=Math.max(2,2*h),v.fillRect(n.bounds.x*h,n.bounds.y*c,n.bounds.width*h,n.bounds.height*c),v.strokeRect(n.bounds.x*h,n.bounds.y*c,n.bounds.width*h,n.bounds.height*c);const P=await new Promise(d=>g.toBlob(d,"image/jpeg",.82));return P?new File([P],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(o){return console.warn("[preview] failed to capture annotation screenshot:",o),null}return await Ks(t,n)},Nt=async(t,n,o,i,a,m)=>{if(!t)return null;try{const w=new Image;await new Promise((j,N)=>{w.onload=()=>j(),w.onerror=()=>N(new Error("Failed to load desktop browser screenshot")),w.src=`data:image/jpeg;base64,${t}`});const u=Math.max(1,w.naturalWidth||n),f=Math.max(1,w.naturalHeight||o),v=Math.min(1,1200/u),h=document.createElement("canvas");h.width=Math.floor(u*v),h.height=Math.floor(f*v);const c=h.getContext("2d");if(!c)return null;c.scale(v,v),c.drawImage(w,0,0,u,f);const P=u/Math.max(1,i||u),d=f/Math.max(1,a||f);c.fillStyle="rgba(37, 99, 235, 0.14)",c.strokeStyle="rgb(37, 99, 235)",c.lineWidth=Math.max(2,2*P),c.fillRect(m.bounds.x*P,m.bounds.y*d,m.bounds.width*P,m.bounds.height*d),c.strokeRect(m.bounds.x*P,m.bounds.y*d,m.bounds.width*P,m.bounds.height*d);const C=await new Promise(j=>h.toBlob(j,"image/jpeg",.82));return C?new File([C],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}};async function Vs(t,n){try{const o=t.contentWindow,i=t.contentDocument??o?.document,a=i?.documentElement;if(!o||!i||!a)return null;const m=t.getBoundingClientRect(),w=Math.max(1,Math.ceil(o.innerWidth||t.clientWidth||m.width)),u=Math.max(1,Math.ceil(o.innerHeight||t.clientHeight||m.height)),f=i.body,g=i.scrollingElement instanceof HTMLElement?i.scrollingElement:null,v=o.scrollX||0,h=o.scrollY||0,c=o.pageXOffset||0,P=o.pageYOffset||0,d=o.visualViewport?.pageLeft||o.visualViewport?.offsetLeft||0,C=o.visualViewport?.pageTop||o.visualViewport?.offsetTop||0,j=a.scrollLeft||0,N=a.scrollTop||0,T=f?.scrollLeft||0,B=f?.scrollTop||0,re=g?.scrollLeft||0,F=g?.scrollTop||0,te=Math.max(v,c,d,j,T,re),z=Math.max(h,P,C,N,B,F);Je("scroll sources",{windowScrollX:v,windowScrollY:h,pageScrollX:c,pageScrollY:P,visualViewportScrollX:d,visualViewportScrollY:C,rootScrollX:j,rootScrollY:N,bodyScrollX:T,bodyScrollY:B,scrollingElementScrollX:re,scrollingElementScrollY:F,scrollingElementTag:g?.tagName?.toLowerCase()??null,resolvedScrollX:te,resolvedScrollY:z,nestedScrolledElements:En(i)});const y=Math.max(w,a.scrollWidth||0,f?.scrollWidth||0,Math.ceil(a.getBoundingClientRect().width||0)),b=Math.max(u,a.scrollHeight||0,f?.scrollHeight||0,Math.ceil(a.getBoundingClientRect().height||0)),G=Math.min(2,Math.max(1,window.devicePixelRatio||1)),U=a.style.scrollBehavior,O=f?.style.scrollBehavior??"";a.style.scrollBehavior="auto",f&&(f.style.scrollBehavior="auto");const H=Us(i);Je("nested scroll snapshot",H.snapshot);let ne=()=>{},R=()=>{};try{await i.fonts?.ready.catch(()=>{}),ne=await Rn(i,w,u,{applyLayoutWorkarounds:!1}),o.scrollTo(te,z),R=Bs(i,te,z),H.reapply();const{snapdom:J}=await Re(async()=>{const{snapdom:x}=await import("./vendor-zumer-snapdom-Btyu_Xi2.js");return{snapdom:x}},[]),S={backgroundColor:Cn(i),cache:"disabled",dpr:G,embedFonts:!0,fast:!1,height:b,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[zs,Hs],quality:.82,width:y},q=await(await J(a,S)).toCanvas();if(!q.width||!q.height)return null;const M=q.width/Math.max(1,y),A=q.height/Math.max(1,b),ce=Math.min(q.width,Math.max(1,Math.round(w*M))),ue=Math.min(q.height,Math.max(1,Math.round(u*A))),de=Math.max(0,q.width-ce),ye=Math.max(0,q.height-ue),pe=Math.min(de,Math.max(0,Math.round(te*M))),xe=Math.min(ye,Math.max(0,Math.round(z*A)));Je("capture geometry",{viewportWidth:w,viewportHeight:u,captureWidth:y,captureHeight:b,canvasWidth:q.width,canvasHeight:q.height,xScale:M,yScale:A,sourceX:pe,sourceY:xe,sourceWidth:ce,sourceHeight:ue});const he=i.createElement("canvas");he.width=ce,he.height=ue;const D=he.getContext("2d");if(!D)return null;D.drawImage(q,pe,xe,ce,ue,0,0,ce,ue);const $=await Ms(he,.82);return $?await Nt($,w,u,w,u,n):null}finally{R(),H.cleanup(),ne(),o.scrollTo(te,z),H.reapply(),a.style.scrollBehavior=U,f&&(f.style.scrollBehavior=O)}}catch(o){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",o),null}}async function Ks(t,n){const o=await Vs(t,n);if(o)return o;try{const i=t.contentWindow,a=t.contentDocument??i?.document,m=a?.documentElement;if(!i||!a||!m)return null;const w=t.getBoundingClientRect(),u=Math.max(1,Math.ceil(i.innerWidth||t.clientWidth||w.width)),f=Math.max(1,Math.ceil(i.innerHeight||t.clientHeight||w.height)),g=i.scrollX||a.documentElement.scrollLeft||a.body?.scrollLeft||0,v=i.scrollY||a.documentElement.scrollTop||a.body?.scrollTop||0,h=a.body,c=Math.max(f,m.scrollHeight||0,h?.scrollHeight||0),P=Math.min(2,Math.max(1,window.devicePixelRatio||1)),d=m.style.scrollBehavior,C=h?.style.scrollBehavior??"";m.style.scrollBehavior="auto",h&&(h.style.scrollBehavior="auto");let j="",N=()=>{};try{await a.fonts?.ready.catch(()=>{}),N=await Rn(a,u,f,{applyLayoutWorkarounds:!0}),i.scrollTo(g,v);const{getFontEmbedCSS:B,toJpeg:re}=await Re(async()=>{const{getFontEmbedCSS:te,toJpeg:z}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:te,toJpeg:z}},[]),F=await B(m).catch(()=>"");j=await re(m,{quality:.82,pixelRatio:P,width:u,height:f,backgroundColor:Cn(a),imagePlaceholder:Be,fontEmbedCSS:F||void 0,style:{transform:`translate(${-g}px, ${-v}px)`,transformOrigin:"top left",minWidth:`${u}px`,minHeight:`${c}px`},cacheBust:!0})}finally{N(),i.scrollTo(g,v),m.style.scrollBehavior=d,h&&(h.style.scrollBehavior=C)}const T=j.split(",",2)[1]||"";return T?await Nt(T,u,f,u,f,n):null}catch(i){return console.warn("[preview] failed to capture iframe DOM screenshot:",i),null}}const Ht=200,Xs=(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",nt=t=>{const n=st.getState();n.setPendingSyntheticParts([...n.pendingSyntheticParts??[],{text:t,synthetic:!0}])},_n=async t=>{const n=await t.json().catch(()=>({}));if(!t.ok)return{ok:!1,message:typeof n.error=="string"?n.error:`HTTP ${t.status}`};const o=typeof n.proxyBasePath=="string"?n.proxyBasePath:"",i=typeof n.previewToken=="string"?n.previewToken:"";return!o||!i?{ok:!1,message:"Could not start preview proxy."}:{ok:!0,target:{proxyBasePath:o,previewToken:i,expiresAt:typeof n.expiresAt=="number"?n.expiresAt:0}}},Dn=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Vt=(t,n,o)=>{t.postMessage(o,Dn(n))},qs=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}},Kt=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}};function An(t){const[n,o]=r.useState("");return r.useEffect(()=>{if(!t){o("");return}let i=!1;return o(""),Fn(en()).then(a=>{!i&&a&&o(t)}).catch(()=>{}),()=>{i=!0}},[t]),n}const Mn=`new Promise((resolve) => {
|
|
4
4
|
const existing = document.getElementById('__pichamber_desktop_browser_overlay');
|
|
5
5
|
if (existing) existing.remove();
|
|
6
6
|
if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
|
|
@@ -91,7 +91,7 @@ import{R as r,j as e,r as Se,e as Wn}from"./vendor-react-B5Z1Mdn3.js";import"./v
|
|
|
91
91
|
}
|
|
92
92
|
const overlay = document.getElementById('__pichamber_desktop_browser_overlay');
|
|
93
93
|
if (overlay) overlay.remove();
|
|
94
|
-
})()`,
|
|
94
|
+
})()`,Gs=`(() => {
|
|
95
95
|
if (window.__pichamberSameWebviewNavigationInstalled) return;
|
|
96
96
|
window.__pichamberSameWebviewNavigationInstalled = true;
|
|
97
97
|
|
|
@@ -123,8 +123,8 @@ import{R as r,j as e,r as Se,e as Wn}from"./vendor-react-B5Z1Mdn3.js";import"./v
|
|
|
123
123
|
event.preventDefault();
|
|
124
124
|
event.stopPropagation();
|
|
125
125
|
}, true);
|
|
126
|
-
})()`,Xe=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"}},Xt=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)},Gs=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,Ys=({initialUrl:t,directory:n,tabID:o})=>{const i=r.useRef(null),a=ee(D=>D.setContextPanelTabTargetPath),m=Xe(t),w=m!=="about:blank"?m:"",[u,f]=r.useState(w),[g,v]=r.useState(w),[h,c]=r.useState(w),[P,d]=r.useState(()=>w?[w]:[]),[C,j]=r.useState(()=>w?0:-1),[N,T]=r.useReducer(D=>D+1,0),[B,re]=r.useState(!!w),[F,te]=r.useState(!1),[z,y]=r.useState(null),[b,G]=r.useState({status:"idle"}),U=je(D=>D.currentSessionId),O=je(D=>D.newSessionDraft?.open),H=st(D=>D.addAttachedFile),ne=r.useCallback(D=>{!D||D==="about:blank"||!n||!o||a(n,o,D)},[n,o,a]),R=r.useCallback((D,$)=>{const x=Xe(D),_=x!=="about:blank"?x:"";v(_),f(_),$?.inFrame?re(!1):(c(_),re(!!_)),ne(_),d(V=>{if(!_)return j(-1),[];if($?.replaceHistory)return V;const le=C>=0?V.slice(0,C+1):[];if(le[le.length-1]===_)return j(le.length-1),le;const we=[...le,_];return j(we.length-1),we})},[C,ne]),J=r.useCallback(D=>{const $=P[D];$&&(j(D),v($),c($),f($),re(!0),ne($))},[P,ne]),S=r.useCallback(()=>{if(g){re(!0);try{i.current?.contentWindow?.location.reload()}catch{T()}}},[g]);r.useEffect(()=>{if(!h){G({status:"idle"});return}const D=Ds(h),$=Ct(D);if($?.previewToken){G({status:"ready",proxyBasePath:$.proxyBasePath,previewToken:$.previewToken,expiresAt:$.expiresAt});return}$&&ke.delete(D);let x=!1;return G({status:"loading"}),re(!0),(async()=>{try{const _=await et("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:h,allowExternal:!0})}),V=await _n(_);if(!V.ok){x||G({status:"error",message:V.message});return}ke.set(D,V.target),x||G({status:"ready",...V.target})}catch(_){if(!x){const V=_ instanceof Error?_.message:String(_);G({status:"error",message:V})}}})(),()=>{x=!0}},[h]);const L=h&&b.status==="ready"?`${b.proxyBasePath}|${b.previewToken||""}|${N}`:"",q=An(L),M=r.useMemo(()=>{if(q!==L||!h||b.status!=="ready")return"";try{const D=new URL(h),$=D.pathname||"/",x=new URLSearchParams(D.search);x.delete("oc_url_token"),x.delete("oc_client_token"),x.set("ocPreview",String(N)),x.set("oc_preview_token",b.previewToken||"");const _=x.toString();return tn().authenticatedAsset(`${b.proxyBasePath}${$}${_?`?${_}`:""}${D.hash}`)}catch{return""}},[h,b,L,N,q]),A=M||(b.status==="error"?h:""),ce=r.useCallback(D=>{if(!D||!h||b.status!=="ready")return"";try{const $=new URL(D,window.location.origin),x=b.proxyBasePath.endsWith("/")?b.proxyBasePath.slice(0,-1):b.proxyBasePath;if($.origin!==window.location.origin||!$.pathname.startsWith(x))return"";const _=$.pathname.slice(x.length)||"/",V=new URL(h).origin;return Kt(new URL(`${_}${$.search}${$.hash}`,V).toString())}catch{return""}},[h,b]),ue=r.useCallback(D=>{if(!D||!h||b.status!=="ready")return"";try{const $=new URL(D,window.location.origin),x=new URL(h).origin;if($.origin!==window.location.origin||x===window.location.origin)return"";const _=b.proxyBasePath.endsWith("/")?b.proxyBasePath.slice(0,-1):b.proxyBasePath;return $.pathname.startsWith(_)?"":Kt(new URL(`${$.pathname}${$.search}${$.hash}`,x).toString())}catch{return""}},[h,b]),de=r.useCallback(D=>{const $=i.current?.contentWindow;$&&$.postMessage({source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:D},window.location.origin)},[]),ye=r.useCallback(async D=>{if(!(U??(O?"draft":null))){ve.error("Open a chat session before attaching preview annotations");return}const x=i.current,_=x?.contentWindow,V=x?.getBoundingClientRect(),le={width:Number.isFinite(_?.innerWidth)?_?.innerWidth??V?.width??0:V?.width??0,height:Number.isFinite(_?.innerHeight)?_?.innerHeight??V?.height??0:V?.height??0},fe=x?await Tn(x,D):null,we=!!fe;fe&&await H(fe),nt(St({pageUrl:g,viewport:le,devicePixelRatio:window.devicePixelRatio||1,target:D,screenshotAttached:we,intro:we?"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."})),ve.success("Preview annotation attached to chat")},[H,U,g,O]),pe=r.useCallback(()=>{const D=i.current;y(null),de(!1),D&&Xt(D,Qe).catch(()=>{})},[de]);r.useEffect(()=>{if(!F)return;const D=$=>{$.key==="Escape"&&($.preventDefault(),$.stopImmediatePropagation(),te(!1),pe())};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[pe,F]),r.useEffect(()=>()=>pe(),[pe]),r.useEffect(()=>{const D=$=>{if($.source!==i.current?.contentWindow)return;const x=$.data;if(!(!x||x.source!=="pichamber-preview-bridge"||x.version!==1)){if(x.type==="ready"){const _=typeof x.url=="string"?x.url:"",V=ce(_);V&&V!==g&&R(V,{inFrame:!0});return}if(x.type==="hover"){y(Fe(x.target)?x.target:null);return}if(x.type==="select"&&Fe(x.target)){y(null),te(!1),de(!1),ye(x.target);return}if(x.type==="navigate-preview"){const _=typeof x.url=="string"?x.url:"",V=ue(_);if(V){R(V);return}_&&R(_)}}};return window.addEventListener("message",D),()=>window.removeEventListener("message",D)},[R,ye,g,ce,ue,de]);const xe=r.useCallback(()=>{const D=i.current;if(!(!D||!g)){if(F){te(!1),pe();return}if(M){y(null),te(!0),de(!0);return}te(!0),(async()=>{try{const $=await Xt(D,Mn);if(te(!1),!$||!Fe($))return;await ye($)}catch{te(!1),ve.error("This page cannot be inspected from the browser panel.")}})()}},[ye,pe,g,F,de,M]),he=r.useCallback(()=>{try{const D=i.current?.contentWindow?.location.href||"",$=ue(D);if($){R($,{inFrame:!0});return}}catch{}re(!1),F&&M&&de(!0)},[R,ue,F,de,M]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:C<=0,onClick:()=>J(C-1),children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:C<0||C>=P.length-1,onClick:()=>J(C+1),children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:S,children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:D=>{D.preventDefault(),R(u)},children:e.jsx("input",{value:u,onChange:D=>f(D.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(me,{type:"button",variant:F?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:xe,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:()=>{tt(g)},children:e.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[A?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("iframe",{ref:i,src:A,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:he},`${o}:${N}`),F&&z?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:z.bounds.x,top:z.bounds.y,width:z.bounds.width,height:z.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:[z.tag,z.text?` · ${z.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(cn,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:"Enter an address above to start browsing the web"}),e.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:"Pages opened here run with full access to PiChamber — needed for inspect and screenshots. Only open sites you trust: a malicious page could read your data or act on your behalf."})]}),B?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Js=({initialUrl:t,directory:n,tabID:o})=>{const i=r.useRef(null),a=ee(y=>y.setContextPanelTabTargetPath),m=Xe(t),w=m!=="about:blank"?m:"",u=r.useRef(Xe(t)),[f,g]=r.useState(w),[v,h]=r.useState(w),[c,P]=r.useState(!1),[d,C]=r.useState(!0),j=r.useRef(null),N=d,T=r.useCallback(y=>{!y||y==="about:blank"||!n||!o||a(n,o,y)},[n,o,a]),B=je(y=>y.currentSessionId),re=je(y=>y.newSessionDraft?.open),F=st(y=>y.addAttachedFile);r.useEffect(()=>{const y=i.current;if(!y)return;const b=()=>{try{const R=y.getURL();R&&R!=="about:blank"&&(h(R),g(R),T(R))}catch{}},G=R=>{const J=R.detail;typeof J?.url=="string"&&J.url&&(h(J.url),g(J.url),T(J.url))},U=()=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>C(!0),200)},O=()=>{j.current&&clearTimeout(j.current),C(!1),b()},H=R=>{const J=R.detail;if(J?.disposition==="new-window"||J?.disposition==="foreground-tab"||J?.disposition==="background-tab"){R.preventDefault();const S=i.current;typeof S?.loadURL=="function"&&J.url&&S.loadURL(J.url)}},ne=()=>{try{y.executeJavaScript?.(qs,!0).catch(()=>{})}catch{}};y.addEventListener("did-navigate",G),y.addEventListener("did-navigate-in-page",G),y.addEventListener("did-start-loading",U),y.addEventListener("did-stop-loading",O),y.addEventListener("new-window",H),y.addEventListener("dom-ready",ne);try{y.isLoading()||(C(!1),b())}catch{}return ne(),()=>{j.current&&clearTimeout(j.current),y.removeEventListener("did-navigate",G),y.removeEventListener("did-navigate-in-page",G),y.removeEventListener("did-start-loading",U),y.removeEventListener("did-stop-loading",O),y.removeEventListener("new-window",H),y.removeEventListener("dom-ready",ne)}},[T]),r.useEffect(()=>{const y=setTimeout(()=>C(!1),3e4);return()=>clearTimeout(y)},[]),r.useEffect(()=>{if(!c)return;const y=b=>{if(b.key!=="Escape")return;b.preventDefault(),b.stopImmediatePropagation(),P(!1);const G=i.current;try{G?.executeJavaScript?.(Qe).catch(()=>{})}catch{}};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[c]),r.useEffect(()=>{const y=i.current;return()=>{try{const b=y?.getURL?.();b&&b!=="about:blank"&&a(n,o,b)}catch{}try{y?.executeJavaScript?.(Qe).catch(()=>{})}catch{}}},[n,o,a]);const te=r.useCallback(y=>{const b=i.current;if(typeof b?.loadURL!="function")return;const G=Xe(y);try{b.loadURL(G)}catch{}},[]),z=r.useCallback(()=>{const y=i.current;if(y){if(c){P(!1);try{y.executeJavaScript?.(Qe).catch(()=>{})}catch{}return}P(!0),y.executeJavaScript?.(Mn,!0).then(async b=>{if(P(!1),!b||!Fe(b))return;if(!(B??(re?"draft":null))){ve.error("Open a chat session before attaching preview annotations");return}const U=typeof y.getWebContentsId=="function"?y.getWebContentsId():null;if(U==null)return;const O=await Sr("desktop_browser_capture_page",{webContentsId:U}),H=await y.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),ne=Number.isFinite(H?.width)?H.width:O.width,R=Number.isFinite(H?.height)?H.height:O.height,J=await Nt(O.base64,O.width,O.height,ne,R,b),S=!!J;J&&await F(J),nt(St({pageUrl:v,viewport:{width:ne,height:R},devicePixelRatio:window.devicePixelRatio||1,target:b,screenshotAttached:S,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."})),ve.success("Preview annotation attached to chat")}).catch(()=>P(!1))}},[F,B,v,c,re]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goBack?.()}catch{}},children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goForward?.()}catch{}},children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.reload?.()}catch{}},children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:y=>{y.preventDefault(),te(f)},children:e.jsx("input",{value:f,onChange:y=>g(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(me,{type:"button",variant:c?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:z,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{tt(v)},children:e.jsx(K,{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:i,src:u.current,partition:"persist:pichamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!v||v==="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(cn,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,N?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Qs=t=>{const n=Gs()?Js:Ys;return e.jsx(n,{...t})},Zs=8,_e=new Map,kt=t=>JSON.stringify([Bn(),t]),qt=t=>{const n=kt(t),o=_e.get(n);return o?(o.touchedAt=Date.now(),_e.delete(n),_e.set(n,o),o):null},lt=t=>{const n=kt(t),o=_e.get(n);if(o)return o.touchedAt=Date.now(),o;if(_e.size>=Zs){const a=_e.keys().next().value;a!==void 0&&_e.delete(a)}const i={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return _e.set(n,i),i},eo=t=>{_e.delete(kt(t))},In=(t,n)=>e.jsx(ft,{filePath:t,extension:n}),to=({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}})},no=({node:t,root:n,isExpanded:o,isActive:i,isBrowserClient:a,status:m,badge:w,permissions:u,downloadFile:f,onSelect:g,onToggle:v,onRevealPath:h,onOpenDialog:c})=>{const P=t.type==="directory",{canRename:d,canCreateFile:C,canCreateFolder:j,canDelete:N,canReveal:T}=u,B=!P&&!!f,re=T&&!a,F=d||C||j||N||B||re,[te,z]=r.useState(!1),[y,b]=r.useState(!1),G=r.useCallback(R=>{F&&(R?.preventDefault(),b(!0))},[F]),U=r.useCallback(()=>{P?v(t.path):g(t)},[P,t,g,v]),O=r.useCallback(R=>{R.stopPropagation(),b(!1),z(!0)},[]),H=({Item:R,Separator:J})=>e.jsxs(e.Fragment,{children:[d&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("rename",t)},children:[e.jsx(K,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(R,{onClick:S=>{S.stopPropagation(),mt(t.path).then(L=>{if(L.ok){ve.success("Path copied");return}ve.error("Copy failed")})},children:[e.jsx(K,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!P&&f&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),f(t.path).catch(L=>{console.error("Download failed:",L),ve.error("Operation failed")})},children:[e.jsx(K,{name:"download",className:"mr-2 h-4 w-4"})," ",a?"Download":"Save"]}),re&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),h(t.path)},children:[e.jsx(K,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",zn()]}),P&&(C||j)&&e.jsxs(e.Fragment,{children:[e.jsx(J,{}),C&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("createFile",t)},children:[e.jsx(K,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),j&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("createFolder",t)},children:[e.jsx(K,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),N&&e.jsxs(e.Fragment,{children:[e.jsx(J,{}),e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(K,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),ne=r.useCallback(R=>{const J=gn(n,t.path);J&&(R.dataTransfer.setData("application/x-pichamber-file-path",J),R.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(ar,{open:y,onOpenChange:b,children:[e.jsxs(ir,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:G}),children:[e.jsxs("button",{type:"button",onClick:U,onContextMenu:G,draggable:!0,onDragStart:ne,className:ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",i?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[P?o?e.jsx(K,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(K,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):In(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!P&&m&&e.jsx(to,{status:m}),P&&w&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[w.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",w.modified]}),w.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",w.added]})]})]}),F&&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(Cr,{open:te,onOpenChange:z,children:[e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(Nr,{asChild:!0,children:e.jsx(me,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:O,title:"File menu","aria-label":"File menu",children:e.jsx(K,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(kr,{align:"end",side:"bottom",onCloseAutoFocus:()=>z(!1),children:H({Item:Pr,Separator:Rr})})]})})]}),e.jsx(lr,{className:"min-w-[180px]",children:H({Item:cr,Separator:dr})})]})},ro=(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,so=r.memo(no,ro),oo=()=>{const{files:t,runtime:n}=gt(),o=Un(n.platform),i=qe()??"",a=Pe(i.trim()),m=Hn(),w=ee(s=>s.openContextFile),u=dn(i),[f,g]=r.useState(""),v=r.useRef(null),{results:h,searching:c}=hs({directory:i,query:f,chrome:"desktop",showGitignored:m}),[P,d]=r.useState({}),[C,j]=r.useState({}),N=r.useRef(new Set),T=r.useRef(new Set),B=r.useRef(null);r.useEffect(()=>{if(!a){d({}),j({}),N.current=new Set;return}const s=qt(a);s?(d({...s.childrenByDir}),j({...s.loadErrorsByDir}),N.current=new Set(s.loadedDirs)):(d({}),j({}),N.current=new Set)},[a]),r.useEffect(()=>{if(!a)return;const s=lt(a);s.childrenByDir=P},[a,P]),r.useEffect(()=>{if(!a)return;const s=lt(a);s.loadErrorsByDir=C},[a,C]),r.useEffect(()=>{if(!a)return;const s=lt(a);s.loadedDirs=new Set(N.current)},[a,P,C]),r.useEffect(()=>()=>{if(!a)return;const s=qt(a);s&&s.loadedDirs.size===0&&Object.keys(s.childrenByDir).length===0&&eo(a)},[a]);const re=r.useMemo(()=>[],[]),F=r.useMemo(()=>[],[]),te=Te(s=>a?s.byRoot[a]?.expandedPaths??re:re),z=Te(s=>a?s.byRoot[a]?.selectedPath??null:null),y=Te(s=>s.setSelectedPath),b=Te(s=>s.addOpenPath),G=Te(s=>s.removeOpenPathsByPrefix),U=Te(s=>s.toggleExpandedPath),O=Te(s=>s.collapseAllExpandedPaths),H=ee(s=>a?s.contextPanelByDirectory[a]?.tabs??F:F),ne=r.useMemo(()=>new Set(H.map(s=>s.mode==="file"?s.targetPath:null).filter(s=>typeof s=="string"&&s.length>0).map(s=>Pe(s))),[H]),R=r.useCallback(s=>{t.revealPath&&t.revealPath(s).catch(()=>{ve.error("Failed to reveal path")})},[t]),J=r.useCallback((s,p)=>{const X=p.filter(l=>l&&typeof l.name=="string"&&l.name.length>0).filter(l=>m||!ps(l.name)).map(l=>{const I=l.name,Y=Pe(l.path||""),ge=Y?fs(Y)?Y:Pe(`${s}/${Y}`):Pe(`${s}/${I}`),be=l.isDirectory?"directory":"file",Ee=be==="file"&&I.includes(".")?I.split(".").pop()?.toLowerCase():void 0;return{name:I,path:ge,type:be,extension:Ee}});return ms(X)},[m]),S=r.useCallback(async(s,p)=>{const X=Pe(s.trim());if(!X||N.current.has(X)||T.current.has(X))return;T.current=new Set(T.current),T.current.add(X);const l=t.listDirectory?t.listDirectory(X).then(I=>I.entries.map(Y=>({name:Y.name,path:Y.path,isDirectory:Y.isDirectory}))):Vn(X).then(I=>I.map(Y=>({name:Y.name,path:Y.path,isDirectory:Y.isDirectory})));try{const I=await l;if(p?.())return;const Y=J(X,I);N.current=new Set(N.current),N.current.add(X),j(ge=>{if(!ge[X])return ge;const be={...ge};return delete be[X],be}),d(ge=>({...ge,[X]:Y}))}catch(I){if(p?.())return;const Y=I instanceof Error?I.message:String(I??"");console.error("Failed to load sidebar directory:",I),j(ge=>({...ge,[X]:Y}))}finally{T.current=new Set(T.current),T.current.delete(X)}},[t,J]),L=r.useCallback(async()=>{if(!a)return;B.current?.abort();const s=new AbortController;B.current=s;try{const X=(Te.getState().byRoot[a]?.expandedPaths??[]).map(Y=>Pe(Y)).filter(Y=>!!Y&&Y!==a&&Y.startsWith(`${a}/`)),l=[a,...X];N.current=new Set(N.current);for(const Y of l)N.current.delete(Y);j(Y=>{if(Object.keys(Y).length===0)return Y;const ge={...Y};let be=!1;for(const Ee of l)Ee in ge&&(delete ge[Ee],be=!0);return be?ge:Y});const I=()=>s.signal.aborted;await S(a,I);for(let Y=0;Y<X.length&&!s.signal.aborted;Y+=3){const ge=X.slice(Y,Y+3);await Promise.all(ge.map(be=>S(be,I)))}}catch(p){if(s.signal.aborted)return;console.error("Failed to refresh sidebar tree:",p)}finally{B.current===s&&(B.current=null)}},[S,a]),q=r.useCallback(async s=>{if(!s){await L();return}const p=Pe(s);N.current=new Set(N.current),N.current.delete(p),T.current=new Set(T.current),T.current.delete(p),await S(p)},[S,L]),M=r.useCallback(()=>{a&&y(a,null)},[a,y]),{operation:A,target:ce,inputValue:ue,setInputValue:de,submitting:ye,inputRef:pe,open:xe,close:he,submit:D,capabilities:{canCreateFile:$,canCreateFolder:x,canRename:_,canDelete:V}}=gs({files:t,root:a,selectedPath:z??"",refreshDirectory:q,removeOpenPathsByPrefix:G,clearSelectedPath:M}),le=!!t.revealPath,fe=r.useMemo(()=>({canRename:_,canCreateFile:$,canCreateFolder:x,canDelete:V,canReveal:le}),[_,$,x,V,le]);r.useEffect(()=>{a&&(B.current?.abort(),N.current=new Set,T.current=new Set,j({}),d(s=>Object.keys(s).length===0?s:{}),S(a))},[S,a,m]),r.useEffect(()=>{if(!a||te.length===0)return;const s=te.map(l=>Pe(l)).filter(l=>!!l&&l!==a&&l.startsWith(`${a}/`)&&!N.current.has(l)&&!T.current.has(l)).sort((l,I)=>l.split("/").length-I.split("/").length);if(s.length===0)return;let p=!1;const X=()=>p;return(async()=>{for(let l=0;l<s.length&&!p;l+=3){const I=s.slice(l,l+3);await Promise.all(I.map(Y=>S(Y,X)))}})(),()=>{p=!0}},[te,S,a]);const we=r.useMemo(()=>{const s=new Map;if(!u?.files)return s;for(const p of u.files)p.index==="A"||p.working_dir==="?"?s.set(p.path,"git-added"):p.index==="D"?s.set(p.path,"git-deleted"):(p.index==="M"||p.working_dir==="M")&&s.set(p.path,"git-modified");return s},[u]),k=r.useMemo(()=>{const s=new Map;if(!u?.files||!a)return s;for(const p of u.files){const X=p.index==="M"||p.working_dir==="M",l=p.index==="A"||p.working_dir==="?";if(!X&&!l)continue;const I=p.path.split("/");if(I.length<=1)continue;let Y=a;for(let ge=0;ge<I.length-1;ge++){Y=`${Y}/${I[ge]}`;let be=s.get(Y);be||(be={modified:0,added:0},s.set(Y,be)),X&&be.modified++,l&&be.added++}}return s},[u,a]),Z=r.useCallback(s=>{if(ne.has(s))return"open";if(we.size===0)return null;const p=s.startsWith(a+"/")?s.slice(a.length+1):s;return we.get(p)??null},[ne,we,a]),ae=r.useCallback(s=>{if(k.size===0)return null;const p=k.get(s);return p&&p.modified+p.added>0?p:null},[k]),E=r.useCallback(async s=>{if(!a)return;const p=await fn(t,s.path,{directory:a});if(!p.ok){ve.error(mn(p.reason));return}y(a,s.path),b(a,s.path),w(a,s.path)},[b,t,w,a,y]),oe=r.useCallback(async s=>{const p=Pe(s);a&&(U(a,p),N.current.has(p)||await S(p))},[S,a,U]);function se(s,p){const X=P[s]??[];return X.map((l,I)=>{const Y=l.type==="directory",ge=Y&&te.includes(l.path),be=z===l.path,Ee=I===X.length-1;return e.jsxs("li",{className:"relative",children:[p>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ee&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(so,{node:l,root:a,isExpanded:ge,isActive:be,isBrowserClient:o,status:Y?void 0:Z(l.path),badge:Y?ae(l.path):void 0,permissions:fe,downloadFile:t.downloadFile,onSelect:E,onToggle:oe,onRevealPath:R,onOpenDialog:xe}),Y&&ge&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[C[l.path]?e.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:C[l.path],children:C[l.path]}),e.jsxs(me,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{q(l.path)},children:[e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,se(l.path,p+1)]})]},l.path)})}const Q=!!(a&&P[a]),W=a?C[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:[$&&e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>xe("createFile",{path:i,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(K,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"New File"})]}),x&&e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>xe("createFolder",{path:i,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(K,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>{L()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(K,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>{a&&O(a)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(K,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]}),e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(K,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(At,{ref:v,value:f,onChange:s=>g(s.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),f.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:()=>{g(""),v.current?.focus()},children:e.jsx(K,{name:"close",className:"h-4 w-4"})}):null]})]}),e.jsx(Er,{outerClassName:"flex-1 min-h-0",className:"p-2",children:e.jsx("ul",{className:"flex flex-col",children:c?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(K,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):h.length>0?h.map(s=>{const p=z===s.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>E(s),draggable:!0,onDragStart:X=>{const l=s.relativePath||gn(a??"",s.path);!l||l==="."||(X.dataTransfer.setData("application/x-pichamber-file-path",l),X.dataTransfer.effectAllowed="copy")},className:ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors cursor-grab active:cursor-grabbing",p?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:s.path,children:[In(s.path,s.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:s.relativePath??s.path})]})},s.path)}):W?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:W}),e.jsxs(me,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{L()},children:[e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):Q&&a?se(a,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(xt,{open:!!A,onOpenChange:s=>!s&&he(),children:e.jsxs(wt,{children:[e.jsxs(yt,{children:[e.jsxs(bt,{children:[A==="createFile"&&"Create File",A==="createFolder"&&"Create Folder",A==="rename"&&"Rename",A==="delete"&&"Delete"]}),e.jsxs(vt,{children:[A==="createFile"&&`Create a new file in ${ce?.path??"root"}`,A==="createFolder"&&`Create a new folder in ${ce?.path??"root"}`,A==="rename"&&`Rename ${ce?.name??""}`,A==="delete"&&`Are you sure you want to delete ${ce?.name??""}? This action cannot be undone.`]})]}),A!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(At,{ref:pe,value:ue,onChange:s=>de(s.target.value),placeholder:A==="rename"?"New name":"Name",onKeyDown:s=>{s.key==="Enter"&&D()},autoFocus:!0})}),e.jsxs(Tr,{children:[e.jsx(me,{variant:"outline",onClick:he,disabled:ye,children:"Cancel"}),e.jsx(me,{variant:A==="delete"?"destructive":"default",onClick:()=>{D()},disabled:ye||A!=="delete"&&!ue.trim(),children:ye?e.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):A==="delete"?"Delete":"Confirm"})]})]})})]})},ao=200,io=480,lo=({visible:t})=>{const n=ee(j=>j.contextEditorTreeWidth),o=ee(j=>j.setContextEditorTreeWidth),[i,a]=r.useState(!1),m=r.useRef(0),w=r.useRef(n),u=r.useRef(null),f=r.useRef(null),g=r.useRef(null),v=r.useCallback(j=>Math.min(io,Math.max(ao,Math.round(j))),[]),h=r.useCallback(j=>{const N=g.current;N&&(N.style.width=`${j}px`,N.style.setProperty("--oc-editor-tree-width",`${j}px`))},[]),c=j=>{if(t){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}f.current=j.pointerId,a(!0),m.current=j.clientX,w.current=n,u.current=n,j.preventDefault()}},P=j=>{if(!i||f.current!==j.pointerId)return;const N=m.current-j.clientX,T=v(w.current+N);u.current!==T&&(u.current=T,h(T))},d=j=>{if(f.current!==j.pointerId)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const N=v(u.current??n);f.current=null,u.current=null,a(!1),o(N)},C=t?n:0;return e.jsxs("div",{ref:g,className:ie("relative h-full flex-shrink-0 overflow-hidden border-l border-border bg-background will-change-[width] motion-reduce:transition-none",!t&&"border-l-0"),style:{width:`${i?u.current??C:C}px`,"--oc-editor-tree-width":`${i?u.current??n:n}px`,overflowX:"clip",transitionProperty:i?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&e.jsx("div",{className:ie("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",i&&"bg-[var(--interactive-border)]"),onPointerDown:c,onPointerMove:P,onPointerUp:d,onPointerCancel:d,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:ie("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",i&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,children:e.jsx(oo,{})})]})},co="x-pichamber-preview-target-error",uo=t=>{const n=t.get(co);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},ho=(t,n)=>uo(t)?n?"stop-retrying":"retry-registration":"none",po=({rawUrl:t,onNavigate:n})=>{const{currentTheme:o}=_r(),[i,a]=r.useReducer(E=>E+1,0),[m,w]=r.useReducer(E=>E+1,0),[u,f]=r.useState({status:"idle"}),g=r.useRef(null),v=r.useRef(1),[h,c]=r.useState(!1),[P,d]=r.useState(!1),[C,j]=r.useState("all"),[N,T]=r.useState([]),[B,re]=r.useState(!1),[F,te]=r.useState(null),z=je(E=>E.currentSessionId),y=je(E=>E.newSessionDraft?.open),b=qe(),G=st(E=>E.addAttachedFile);let U=null;try{U=t?new URL(t):null}catch{U=null}const O=U?U.hostname==="localhost"||U.hostname==="127.0.0.1"||U.hostname==="::1"||U.hostname==="[::1]"||U.hostname==="0.0.0.0":!1,H=U?U.hostname==="0.0.0.0"?new URL(U.toString().replace("0.0.0.0","127.0.0.1")):U:null,ne=H?H.toString():"",R=ne?`${en()||"same-origin"}|${ne}`:"",J=o.metadata.variant;r.useEffect(()=>{if(!ne||!O){f({status:"idle"});return}const E=Ct(R);if(E?.previewToken){f({status:"ready",proxyBasePath:E.proxyBasePath,previewToken:E.previewToken,expiresAt:E.expiresAt});return}E&&ke.delete(R);let oe=!1;return f({status:"loading"}),(async()=>{try{const se=await et("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:ne})}),Q=await _n(se);if(!Q.ok){ke.delete(R),oe||f({status:"error",message:Q.message});return}ke.set(R,Q.target),oe||f({status:"ready",...Q.target})}catch(se){if(ke.delete(R),!oe){const Q=se instanceof Error?se.message:String(se);f({status:"error",message:Q})}}})(),()=>{oe=!0}},[O,R,m,ne]);const S=H&&(H.protocol==="http:"||H.protocol==="https:")?H.toString():"",L=O&&u.status==="ready"?`${u.proxyBasePath}|${u.previewToken||""}|${i}`:"",q=An(L),M=O&&u.status==="ready"&&H&&q===L?(()=>{const E=H.pathname||"/",oe=new URLSearchParams(H.search);oe.delete("oc_url_token"),oe.delete("oc_client_token"),oe.set("ocPreview",String(i)),oe.set("oc_preview_token",u.previewToken||"");const se=oe.toString(),Q=H.hash||"";return tn().authenticatedAsset(`${u.proxyBasePath}${E}${se?`?${se}`:""}${Q}`)})():"",A=O?M:S,ce=O?Xs(M):S,ue=O&&(u.status==="loading"||u.status==="idle"||q!==L),de=O&&u.status==="error",ye=r.useCallback(E=>{if(!(z??(y?"draft":null))||!b){ve.error("Open a chat session before attaching preview annotations");return}const se=t||A||"",Q=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},W=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let s=!1;try{const p=g.current,X=p?await Tn(p,E):null;X&&(await G(X),s=!0)}catch{s=!1}nt(St({pageUrl:se,viewport:Q,devicePixelRatio:W,target:E,screenshotAttached:s,intro:"This is a selected DOM element from the in-app preview."})),ve.success("Preview annotation attached to chat")})()},[G,z,b,A,y,t]);r.useEffect(()=>{c(!1),T([]),d(!1),j("all"),re(!1),te(null),v.current=1},[A]),r.useEffect(()=>{const E=g.current?.contentWindow;!h||!E||Vt(E,M,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:B})},[h,B,M]),r.useEffect(()=>{const E=g.current?.contentWindow;!h||!E||Vt(E,M,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:J})},[h,J,M]),r.useEffect(()=>{if(!B||typeof window>"u")return;const E=oe=>{oe.key==="Escape"&&(oe.preventDefault(),oe.stopImmediatePropagation(),re(!1))};return window.addEventListener("keydown",E,!0),()=>window.removeEventListener("keydown",E,!0)},[B]),r.useEffect(()=>{if(!O||typeof window>"u")return;const E=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},oe=Q=>{const W=v.current;v.current+=1,T(s=>{const p=[...s,{...Q,id:W}];return p.length>Ht?p.slice(p.length-Ht):p})},se=Q=>{if(Q.source!==g.current?.contentWindow)return;const W=Q.data;if(!(!W||W.source!=="pichamber-preview-bridge"||W.version!==1)){if(W.type==="ready"){c(!0);return}if(W.type==="console"){const s=W.level==="error"||W.level==="warn"||W.level==="info"||W.level==="debug"?W.level:"log",p=Array.isArray(W.args)?W.args.map(E).filter(Boolean):[];oe({level:s,message:p.join(" "),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="runtime-error"){const s=E(W.filename),p=typeof W.line=="number"?W.line:null,X=typeof W.column=="number"?W.column:null,l=s?`${s}${p!==null?`:${p}${X!==null?`:${X}`:""}`:""}`:"",I=E(W.stack);oe({level:"runtime",message:E(W.message)||"Runtime error",details:[l,I].filter(Boolean).join(`
|
|
127
|
-
`),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="resource-error"){const s=E(W.tag)||"resource",p=E(W.url);oe({level:"resource",message:p?`${s}: ${p}`:s,details:E(W.outerHTML),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="hover"){te(Fe(W.target)?W.target:null);return}if(W.type==="select"&&Fe(W.target)){te(W.target),re(!1),ye(W.target);return}if(W.type==="navigate-preview"){const s=typeof W.url=="string"?W.url:"",p=W.navigation==="external"?"external":"proxy";if(s&&p==="external"){tt(s);return}s&&n(s)}}};return window.addEventListener("message",se),()=>{window.removeEventListener("message",se)}},[ye,O,n]);const pe=N.filter(E=>E.level==="error"||E.level==="runtime"||E.level==="resource").length,xe=N.filter(E=>
|
|
126
|
+
})()`,Xe=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"}},Xt=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)},Ys=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,Js=({initialUrl:t,directory:n,tabID:o})=>{const i=r.useRef(null),a=ee(D=>D.setContextPanelTabTargetPath),m=Xe(t),w=m!=="about:blank"?m:"",[u,f]=r.useState(w),[g,v]=r.useState(w),[h,c]=r.useState(w),[P,d]=r.useState(()=>w?[w]:[]),[C,j]=r.useState(()=>w?0:-1),[N,T]=r.useReducer(D=>D+1,0),[B,re]=r.useState(!!w),[F,te]=r.useState(!1),[z,y]=r.useState(null),[b,G]=r.useState({status:"idle"}),U=je(D=>D.currentSessionId),O=je(D=>D.newSessionDraft?.open),H=st(D=>D.addAttachedFile),ne=r.useCallback(D=>{!D||D==="about:blank"||!n||!o||a(n,o,D)},[n,o,a]),R=r.useCallback((D,$)=>{const x=Xe(D),_=x!=="about:blank"?x:"";v(_),f(_),$?.inFrame?re(!1):(c(_),re(!!_)),ne(_),d(V=>{if(!_)return j(-1),[];if($?.replaceHistory)return V;const le=C>=0?V.slice(0,C+1):[];if(le[le.length-1]===_)return j(le.length-1),le;const we=[...le,_];return j(we.length-1),we})},[C,ne]),J=r.useCallback(D=>{const $=P[D];$&&(j(D),v($),c($),f($),re(!0),ne($))},[P,ne]),S=r.useCallback(()=>{if(g){re(!0);try{i.current?.contentWindow?.location.reload()}catch{T()}}},[g]);r.useEffect(()=>{if(!h){G({status:"idle"});return}const D=As(h),$=Ct(D);if($?.previewToken){G({status:"ready",proxyBasePath:$.proxyBasePath,previewToken:$.previewToken,expiresAt:$.expiresAt});return}$&&ke.delete(D);let x=!1;return G({status:"loading"}),re(!0),(async()=>{try{const _=await et("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:h,allowExternal:!0})}),V=await _n(_);if(!V.ok){x||G({status:"error",message:V.message});return}ke.set(D,V.target),x||G({status:"ready",...V.target})}catch(_){if(!x){const V=_ instanceof Error?_.message:String(_);G({status:"error",message:V})}}})(),()=>{x=!0}},[h]);const L=h&&b.status==="ready"?`${b.proxyBasePath}|${b.previewToken||""}|${N}`:"",q=An(L),M=r.useMemo(()=>{if(q!==L||!h||b.status!=="ready")return"";try{const D=new URL(h),$=D.pathname||"/",x=new URLSearchParams(D.search);x.delete("oc_url_token"),x.delete("oc_client_token"),x.set("ocPreview",String(N)),x.set("oc_preview_token",b.previewToken||"");const _=x.toString();return tn().authenticatedAsset(`${b.proxyBasePath}${$}${_?`?${_}`:""}${D.hash}`)}catch{return""}},[h,b,L,N,q]),A=M||(b.status==="error"?h:""),ce=r.useCallback(D=>{if(!D||!h||b.status!=="ready")return"";try{const $=new URL(D,window.location.origin),x=b.proxyBasePath.endsWith("/")?b.proxyBasePath.slice(0,-1):b.proxyBasePath;if($.origin!==window.location.origin||!$.pathname.startsWith(x))return"";const _=$.pathname.slice(x.length)||"/",V=new URL(h).origin;return Kt(new URL(`${_}${$.search}${$.hash}`,V).toString())}catch{return""}},[h,b]),ue=r.useCallback(D=>{if(!D||!h||b.status!=="ready")return"";try{const $=new URL(D,window.location.origin),x=new URL(h).origin;if($.origin!==window.location.origin||x===window.location.origin)return"";const _=b.proxyBasePath.endsWith("/")?b.proxyBasePath.slice(0,-1):b.proxyBasePath;return $.pathname.startsWith(_)?"":Kt(new URL(`${$.pathname}${$.search}${$.hash}`,x).toString())}catch{return""}},[h,b]),de=r.useCallback(D=>{const $=i.current?.contentWindow;$&&$.postMessage({source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:D},window.location.origin)},[]),ye=r.useCallback(async D=>{if(!(U??(O?"draft":null))){ve.error("Open a chat session before attaching preview annotations");return}const x=i.current,_=x?.contentWindow,V=x?.getBoundingClientRect(),le={width:Number.isFinite(_?.innerWidth)?_?.innerWidth??V?.width??0:V?.width??0,height:Number.isFinite(_?.innerHeight)?_?.innerHeight??V?.height??0:V?.height??0},fe=x?await Tn(x,D):null,we=!!fe;fe&&await H(fe),nt(St({pageUrl:g,viewport:le,devicePixelRatio:window.devicePixelRatio||1,target:D,screenshotAttached:we,intro:we?"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."})),ve.success("Preview annotation attached to chat")},[H,U,g,O]),pe=r.useCallback(()=>{const D=i.current;y(null),de(!1),D&&Xt(D,Qe).catch(()=>{})},[de]);r.useEffect(()=>{if(!F)return;const D=$=>{$.key==="Escape"&&($.preventDefault(),$.stopImmediatePropagation(),te(!1),pe())};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[pe,F]),r.useEffect(()=>()=>pe(),[pe]),r.useEffect(()=>{const D=$=>{if($.source!==i.current?.contentWindow)return;const x=$.data;if(!(!x||x.source!=="pichamber-preview-bridge"||x.version!==1)){if(x.type==="ready"){const _=typeof x.url=="string"?x.url:"",V=ce(_);V&&V!==g&&R(V,{inFrame:!0});return}if(x.type==="hover"){y(Fe(x.target)?x.target:null);return}if(x.type==="select"&&Fe(x.target)){y(null),te(!1),de(!1),ye(x.target);return}if(x.type==="navigate-preview"){const _=typeof x.url=="string"?x.url:"",V=ue(_);if(V){R(V);return}_&&R(_)}}};return window.addEventListener("message",D),()=>window.removeEventListener("message",D)},[R,ye,g,ce,ue,de]);const xe=r.useCallback(()=>{const D=i.current;if(!(!D||!g)){if(F){te(!1),pe();return}if(M){y(null),te(!0),de(!0);return}te(!0),(async()=>{try{const $=await Xt(D,Mn);if(te(!1),!$||!Fe($))return;await ye($)}catch{te(!1),ve.error("This page cannot be inspected from the browser panel.")}})()}},[ye,pe,g,F,de,M]),he=r.useCallback(()=>{try{const D=i.current?.contentWindow?.location.href||"",$=ue(D);if($){R($,{inFrame:!0});return}}catch{}re(!1),F&&M&&de(!0)},[R,ue,F,de,M]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:C<=0,onClick:()=>J(C-1),children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:C<0||C>=P.length-1,onClick:()=>J(C+1),children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:S,children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:D=>{D.preventDefault(),R(u)},children:e.jsx("input",{value:u,onChange:D=>f(D.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(me,{type:"button",variant:F?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:xe,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:()=>{tt(g)},children:e.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[A?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("iframe",{ref:i,src:A,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:he},`${o}:${N}`),F&&z?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:z.bounds.x,top:z.bounds.y,width:z.bounds.width,height:z.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:[z.tag,z.text?` · ${z.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(cn,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground",children:"Enter an address above to start browsing the web"}),e.jsx("span",{className:"max-w-md typography-micro leading-relaxed text-status-warning/70",children:"Pages opened here run with full access to PiChamber — needed for inspect and screenshots. Only open sites you trust: a malicious page could read your data or act on your behalf."})]}),B?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Qs=({initialUrl:t,directory:n,tabID:o})=>{const i=r.useRef(null),a=ee(y=>y.setContextPanelTabTargetPath),m=Xe(t),w=m!=="about:blank"?m:"",u=r.useRef(Xe(t)),[f,g]=r.useState(w),[v,h]=r.useState(w),[c,P]=r.useState(!1),[d,C]=r.useState(!0),j=r.useRef(null),N=d,T=r.useCallback(y=>{!y||y==="about:blank"||!n||!o||a(n,o,y)},[n,o,a]),B=je(y=>y.currentSessionId),re=je(y=>y.newSessionDraft?.open),F=st(y=>y.addAttachedFile);r.useEffect(()=>{const y=i.current;if(!y)return;const b=()=>{try{const R=y.getURL();R&&R!=="about:blank"&&(h(R),g(R),T(R))}catch{}},G=R=>{const J=R.detail;typeof J?.url=="string"&&J.url&&(h(J.url),g(J.url),T(J.url))},U=()=>{j.current&&clearTimeout(j.current),j.current=setTimeout(()=>C(!0),200)},O=()=>{j.current&&clearTimeout(j.current),C(!1),b()},H=R=>{const J=R.detail;if(J?.disposition==="new-window"||J?.disposition==="foreground-tab"||J?.disposition==="background-tab"){R.preventDefault();const S=i.current;typeof S?.loadURL=="function"&&J.url&&S.loadURL(J.url)}},ne=()=>{try{y.executeJavaScript?.(Gs,!0).catch(()=>{})}catch{}};y.addEventListener("did-navigate",G),y.addEventListener("did-navigate-in-page",G),y.addEventListener("did-start-loading",U),y.addEventListener("did-stop-loading",O),y.addEventListener("new-window",H),y.addEventListener("dom-ready",ne);try{y.isLoading()||(C(!1),b())}catch{}return ne(),()=>{j.current&&clearTimeout(j.current),y.removeEventListener("did-navigate",G),y.removeEventListener("did-navigate-in-page",G),y.removeEventListener("did-start-loading",U),y.removeEventListener("did-stop-loading",O),y.removeEventListener("new-window",H),y.removeEventListener("dom-ready",ne)}},[T]),r.useEffect(()=>{const y=setTimeout(()=>C(!1),3e4);return()=>clearTimeout(y)},[]),r.useEffect(()=>{if(!c)return;const y=b=>{if(b.key!=="Escape")return;b.preventDefault(),b.stopImmediatePropagation(),P(!1);const G=i.current;try{G?.executeJavaScript?.(Qe).catch(()=>{})}catch{}};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[c]),r.useEffect(()=>{const y=i.current;return()=>{try{const b=y?.getURL?.();b&&b!=="about:blank"&&a(n,o,b)}catch{}try{y?.executeJavaScript?.(Qe).catch(()=>{})}catch{}}},[n,o,a]);const te=r.useCallback(y=>{const b=i.current;if(typeof b?.loadURL!="function")return;const G=Xe(y);try{b.loadURL(G)}catch{}},[]),z=r.useCallback(()=>{const y=i.current;if(y){if(c){P(!1);try{y.executeJavaScript?.(Qe).catch(()=>{})}catch{}return}P(!0),y.executeJavaScript?.(Mn,!0).then(async b=>{if(P(!1),!b||!Fe(b))return;if(!(B??(re?"draft":null))){ve.error("Open a chat session before attaching preview annotations");return}const U=typeof y.getWebContentsId=="function"?y.getWebContentsId():null;if(U==null)return;const O=await Cr("desktop_browser_capture_page",{webContentsId:U}),H=await y.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),ne=Number.isFinite(H?.width)?H.width:O.width,R=Number.isFinite(H?.height)?H.height:O.height,J=await Nt(O.base64,O.width,O.height,ne,R,b),S=!!J;J&&await F(J),nt(St({pageUrl:v,viewport:{width:ne,height:R},devicePixelRatio:window.devicePixelRatio||1,target:b,screenshotAttached:S,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."})),ve.success("Preview annotation attached to chat")}).catch(()=>P(!1))}},[F,B,v,c,re]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goBack?.()}catch{}},children:e.jsx(K,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goForward?.()}catch{}},children:e.jsx(K,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.reload?.()}catch{}},children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:y=>{y.preventDefault(),te(f)},children:e.jsx("input",{value:f,onChange:y=>g(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(me,{type:"button",variant:c?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:z,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{tt(v)},children:e.jsx(K,{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:i,src:u.current,partition:"persist:pichamber-browser",allowpopups:!0,style:{width:"100%",height:"100%",border:"none"}}),(!v||v==="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(cn,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,N?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Zs=t=>{const n=Ys()?Qs:Js;return e.jsx(n,{...t})},eo=8,_e=new Map,kt=t=>JSON.stringify([Bn(),t]),qt=t=>{const n=kt(t),o=_e.get(n);return o?(o.touchedAt=Date.now(),_e.delete(n),_e.set(n,o),o):null},lt=t=>{const n=kt(t),o=_e.get(n);if(o)return o.touchedAt=Date.now(),o;if(_e.size>=eo){const a=_e.keys().next().value;a!==void 0&&_e.delete(a)}const i={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return _e.set(n,i),i},to=t=>{_e.delete(kt(t))},In=(t,n)=>e.jsx(ft,{filePath:t,extension:n}),no=({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}})},ro=({node:t,root:n,isExpanded:o,isActive:i,isBrowserClient:a,status:m,badge:w,permissions:u,downloadFile:f,onSelect:g,onToggle:v,onRevealPath:h,onOpenDialog:c})=>{const P=t.type==="directory",{canRename:d,canCreateFile:C,canCreateFolder:j,canDelete:N,canReveal:T}=u,B=!P&&!!f,re=T&&!a,F=d||C||j||N||B||re,[te,z]=r.useState(!1),[y,b]=r.useState(!1),G=r.useCallback(R=>{F&&(R?.preventDefault(),b(!0))},[F]),U=r.useCallback(()=>{P?v(t.path):g(t)},[P,t,g,v]),O=r.useCallback(R=>{R.stopPropagation(),b(!1),z(!0)},[]),H=({Item:R,Separator:J})=>e.jsxs(e.Fragment,{children:[d&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("rename",t)},children:[e.jsx(K,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(R,{onClick:S=>{S.stopPropagation(),mt(t.path).then(L=>{if(L.ok){ve.success("Path copied");return}ve.error("Copy failed")})},children:[e.jsx(K,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy Path"]}),!P&&f&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),f(t.path).catch(L=>{console.error("Download failed:",L),ve.error("Operation failed")})},children:[e.jsx(K,{name:"download",className:"mr-2 h-4 w-4"})," ",a?"Download":"Save"]}),re&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),h(t.path)},children:[e.jsx(K,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",zn()]}),P&&(C||j)&&e.jsxs(e.Fragment,{children:[e.jsx(J,{}),C&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("createFile",t)},children:[e.jsx(K,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New File"]}),j&&e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("createFolder",t)},children:[e.jsx(K,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New Folder"]})]}),N&&e.jsxs(e.Fragment,{children:[e.jsx(J,{}),e.jsxs(R,{onClick:S=>{S.stopPropagation(),c("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(K,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),ne=r.useCallback(R=>{const J=gn(n,t.path);J&&(R.dataTransfer.setData("application/x-pichamber-file-path",J),R.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(ir,{open:y,onOpenChange:b,children:[e.jsxs(lr,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:G}),children:[e.jsxs("button",{type:"button",onClick:U,onContextMenu:G,draggable:!0,onDragStart:ne,className:ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",i?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[P?o?e.jsx(K,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(K,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):In(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!P&&m&&e.jsx(no,{status:m}),P&&w&&e.jsxs("span",{className:"text-xs flex items-center gap-1 ml-auto mr-1",children:[w.modified>0&&e.jsxs("span",{className:"text-[var(--status-warning)]",children:["M",w.modified]}),w.added>0&&e.jsxs("span",{className:"text-[var(--status-success)]",children:["+",w.added]})]})]}),F&&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(Nr,{open:te,onOpenChange:z,children:[e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(kr,{asChild:!0,children:e.jsx(me,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:O,title:"File menu","aria-label":"File menu",children:e.jsx(K,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(Pr,{align:"end",side:"bottom",onCloseAutoFocus:()=>z(!1),children:H({Item:Rr,Separator:Er})})]})})]}),e.jsx(cr,{className:"min-w-[180px]",children:H({Item:dr,Separator:ur})})]})},so=(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,oo=r.memo(ro,so),ao=()=>{const{files:t,runtime:n}=gt(),o=Un(n.platform),i=qe()??"",a=Pe(i.trim()),m=Hn(),w=ee(s=>s.openContextFile),u=dn(i),[f,g]=r.useState(""),v=r.useRef(null),{results:h,searching:c}=ps({directory:i,query:f,chrome:"desktop",showGitignored:m}),[P,d]=r.useState({}),[C,j]=r.useState({}),N=r.useRef(new Set),T=r.useRef(new Set),B=r.useRef(null);r.useEffect(()=>{if(!a){d({}),j({}),N.current=new Set;return}const s=qt(a);s?(d({...s.childrenByDir}),j({...s.loadErrorsByDir}),N.current=new Set(s.loadedDirs)):(d({}),j({}),N.current=new Set)},[a]),r.useEffect(()=>{if(!a)return;const s=lt(a);s.childrenByDir=P},[a,P]),r.useEffect(()=>{if(!a)return;const s=lt(a);s.loadErrorsByDir=C},[a,C]),r.useEffect(()=>{if(!a)return;const s=lt(a);s.loadedDirs=new Set(N.current)},[a,P,C]),r.useEffect(()=>()=>{if(!a)return;const s=qt(a);s&&s.loadedDirs.size===0&&Object.keys(s.childrenByDir).length===0&&to(a)},[a]);const re=r.useMemo(()=>[],[]),F=r.useMemo(()=>[],[]),te=Te(s=>a?s.byRoot[a]?.expandedPaths??re:re),z=Te(s=>a?s.byRoot[a]?.selectedPath??null:null),y=Te(s=>s.setSelectedPath),b=Te(s=>s.addOpenPath),G=Te(s=>s.removeOpenPathsByPrefix),U=Te(s=>s.toggleExpandedPath),O=Te(s=>s.collapseAllExpandedPaths),H=ee(s=>a?s.contextPanelByDirectory[a]?.tabs??F:F),ne=r.useMemo(()=>new Set(H.map(s=>s.mode==="file"?s.targetPath:null).filter(s=>typeof s=="string"&&s.length>0).map(s=>Pe(s))),[H]),R=r.useCallback(s=>{t.revealPath&&t.revealPath(s).catch(()=>{ve.error("Failed to reveal path")})},[t]),J=r.useCallback((s,p)=>{const X=p.filter(l=>l&&typeof l.name=="string"&&l.name.length>0).filter(l=>m||!fs(l.name)).map(l=>{const I=l.name,Y=Pe(l.path||""),ge=Y?ms(Y)?Y:Pe(`${s}/${Y}`):Pe(`${s}/${I}`),be=l.isDirectory?"directory":"file",Ee=be==="file"&&I.includes(".")?I.split(".").pop()?.toLowerCase():void 0;return{name:I,path:ge,type:be,extension:Ee}});return gs(X)},[m]),S=r.useCallback(async(s,p)=>{const X=Pe(s.trim());if(!X||N.current.has(X)||T.current.has(X))return;T.current=new Set(T.current),T.current.add(X);const l=t.listDirectory?t.listDirectory(X).then(I=>I.entries.map(Y=>({name:Y.name,path:Y.path,isDirectory:Y.isDirectory}))):Vn(X).then(I=>I.map(Y=>({name:Y.name,path:Y.path,isDirectory:Y.isDirectory})));try{const I=await l;if(p?.())return;const Y=J(X,I);N.current=new Set(N.current),N.current.add(X),j(ge=>{if(!ge[X])return ge;const be={...ge};return delete be[X],be}),d(ge=>({...ge,[X]:Y}))}catch(I){if(p?.())return;const Y=I instanceof Error?I.message:String(I??"");console.error("Failed to load sidebar directory:",I),j(ge=>({...ge,[X]:Y}))}finally{T.current=new Set(T.current),T.current.delete(X)}},[t,J]),L=r.useCallback(async()=>{if(!a)return;B.current?.abort();const s=new AbortController;B.current=s;try{const X=(Te.getState().byRoot[a]?.expandedPaths??[]).map(Y=>Pe(Y)).filter(Y=>!!Y&&Y!==a&&Y.startsWith(`${a}/`)),l=[a,...X];N.current=new Set(N.current);for(const Y of l)N.current.delete(Y);j(Y=>{if(Object.keys(Y).length===0)return Y;const ge={...Y};let be=!1;for(const Ee of l)Ee in ge&&(delete ge[Ee],be=!0);return be?ge:Y});const I=()=>s.signal.aborted;await S(a,I);for(let Y=0;Y<X.length&&!s.signal.aborted;Y+=3){const ge=X.slice(Y,Y+3);await Promise.all(ge.map(be=>S(be,I)))}}catch(p){if(s.signal.aborted)return;console.error("Failed to refresh sidebar tree:",p)}finally{B.current===s&&(B.current=null)}},[S,a]),q=r.useCallback(async s=>{if(!s){await L();return}const p=Pe(s);N.current=new Set(N.current),N.current.delete(p),T.current=new Set(T.current),T.current.delete(p),await S(p)},[S,L]),M=r.useCallback(()=>{a&&y(a,null)},[a,y]),{operation:A,target:ce,inputValue:ue,setInputValue:de,submitting:ye,inputRef:pe,open:xe,close:he,submit:D,capabilities:{canCreateFile:$,canCreateFolder:x,canRename:_,canDelete:V}}=xs({files:t,root:a,selectedPath:z??"",refreshDirectory:q,removeOpenPathsByPrefix:G,clearSelectedPath:M}),le=!!t.revealPath,fe=r.useMemo(()=>({canRename:_,canCreateFile:$,canCreateFolder:x,canDelete:V,canReveal:le}),[_,$,x,V,le]);r.useEffect(()=>{a&&(B.current?.abort(),N.current=new Set,T.current=new Set,j({}),d(s=>Object.keys(s).length===0?s:{}),S(a))},[S,a,m]),r.useEffect(()=>{if(!a||te.length===0)return;const s=te.map(l=>Pe(l)).filter(l=>!!l&&l!==a&&l.startsWith(`${a}/`)&&!N.current.has(l)&&!T.current.has(l)).sort((l,I)=>l.split("/").length-I.split("/").length);if(s.length===0)return;let p=!1;const X=()=>p;return(async()=>{for(let l=0;l<s.length&&!p;l+=3){const I=s.slice(l,l+3);await Promise.all(I.map(Y=>S(Y,X)))}})(),()=>{p=!0}},[te,S,a]);const we=r.useMemo(()=>{const s=new Map;if(!u?.files)return s;for(const p of u.files)p.index==="A"||p.working_dir==="?"?s.set(p.path,"git-added"):p.index==="D"?s.set(p.path,"git-deleted"):(p.index==="M"||p.working_dir==="M")&&s.set(p.path,"git-modified");return s},[u]),k=r.useMemo(()=>{const s=new Map;if(!u?.files||!a)return s;for(const p of u.files){const X=p.index==="M"||p.working_dir==="M",l=p.index==="A"||p.working_dir==="?";if(!X&&!l)continue;const I=p.path.split("/");if(I.length<=1)continue;let Y=a;for(let ge=0;ge<I.length-1;ge++){Y=`${Y}/${I[ge]}`;let be=s.get(Y);be||(be={modified:0,added:0},s.set(Y,be)),X&&be.modified++,l&&be.added++}}return s},[u,a]),Z=r.useCallback(s=>{if(ne.has(s))return"open";if(we.size===0)return null;const p=s.startsWith(a+"/")?s.slice(a.length+1):s;return we.get(p)??null},[ne,we,a]),ae=r.useCallback(s=>{if(k.size===0)return null;const p=k.get(s);return p&&p.modified+p.added>0?p:null},[k]),E=r.useCallback(async s=>{if(!a)return;const p=await fn(t,s.path,{directory:a});if(!p.ok){ve.error(mn(p.reason));return}y(a,s.path),b(a,s.path),w(a,s.path)},[b,t,w,a,y]),oe=r.useCallback(async s=>{const p=Pe(s);a&&(U(a,p),N.current.has(p)||await S(p))},[S,a,U]);function se(s,p){const X=P[s]??[];return X.map((l,I)=>{const Y=l.type==="directory",ge=Y&&te.includes(l.path),be=z===l.path,Ee=I===X.length-1;return e.jsxs("li",{className:"relative",children:[p>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),Ee&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-sidebar/50"})]}),e.jsx(oo,{node:l,root:a,isExpanded:ge,isActive:be,isBrowserClient:o,status:Y?void 0:Z(l.path),badge:Y?ae(l.path):void 0,permissions:fe,downloadFile:t.downloadFile,onSelect:E,onToggle:oe,onRevealPath:R,onOpenDialog:xe}),Y&&ge&&e.jsxs("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:[C[l.path]?e.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:C[l.path],children:C[l.path]}),e.jsxs(me,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{q(l.path)},children:[e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,se(l.path,p+1)]})]},l.path)})}const Q=!!(a&&P[a]),W=a?C[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:[$&&e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>xe("createFile",{path:i,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File","aria-label":"New File",children:e.jsx(K,{name:"file-add",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"New File"})]}),x&&e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>xe("createFolder",{path:i,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder","aria-label":"New Folder",children:e.jsx(K,{name:"folder-add",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"New Folder"})]}),e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>{L()},className:"h-8 w-8 p-0 flex-shrink-0",title:"Refresh","aria-label":"Refresh",children:e.jsx(K,{name:"refresh",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Le,{children:[e.jsx(Oe,{asChild:!0,children:e.jsx("span",{className:"inline-flex flex-shrink-0",children:e.jsx(me,{variant:"ghost",size:"sm",onClick:()=>{a&&O(a)},className:"h-8 w-8 p-0 flex-shrink-0",title:"Collapse all folders","aria-label":"Collapse all folders",children:e.jsx(K,{name:"collapse-vertical",className:"h-4 w-4"})})})}),e.jsx($e,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]}),e.jsxs("div",{className:"relative min-w-0",children:[e.jsx(K,{name:"search",className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(At,{ref:v,value:f,onChange:s=>g(s.target.value),placeholder:"Search files...",className:"h-8 pl-8 pr-8 typography-meta"}),f.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:()=>{g(""),v.current?.focus()},children:e.jsx(K,{name:"close",className:"h-4 w-4"})}):null]})]}),e.jsx(Tr,{outerClassName:"flex-1 min-h-0",className:"p-2",children:e.jsx("ul",{className:"flex flex-col",children:c?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(K,{name:"loader-4",className:"h-4 w-4 animate-spin"}),"Searching..."]}):h.length>0?h.map(s=>{const p=z===s.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>E(s),draggable:!0,onDragStart:X=>{const l=s.relativePath||gn(a??"",s.path);!l||l==="."||(X.dataTransfer.setData("application/x-pichamber-file-path",l),X.dataTransfer.effectAllowed="copy")},className:ie("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors cursor-grab active:cursor-grabbing",p?"bg-interactive-selection/70":"hover:bg-interactive-hover/40"),title:s.path,children:[In(s.path,s.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},children:s.relativePath??s.path})]})},s.path)}):W?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:W}),e.jsxs(me,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{L()},children:[e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):Q&&a?se(a,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(xt,{open:!!A,onOpenChange:s=>!s&&he(),children:e.jsxs(wt,{children:[e.jsxs(yt,{children:[e.jsxs(bt,{children:[A==="createFile"&&"Create File",A==="createFolder"&&"Create Folder",A==="rename"&&"Rename",A==="delete"&&"Delete"]}),e.jsxs(vt,{children:[A==="createFile"&&`Create a new file in ${ce?.path??"root"}`,A==="createFolder"&&`Create a new folder in ${ce?.path??"root"}`,A==="rename"&&`Rename ${ce?.name??""}`,A==="delete"&&`Are you sure you want to delete ${ce?.name??""}? This action cannot be undone.`]})]}),A!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(At,{ref:pe,value:ue,onChange:s=>de(s.target.value),placeholder:A==="rename"?"New name":"Name",onKeyDown:s=>{s.key==="Enter"&&D()},autoFocus:!0})}),e.jsxs(_r,{children:[e.jsx(me,{variant:"outline",onClick:he,disabled:ye,children:"Cancel"}),e.jsx(me,{variant:A==="delete"?"destructive":"default",onClick:()=>{D()},disabled:ye||A!=="delete"&&!ue.trim(),children:ye?e.jsx(K,{name:"loader-4",className:"size-4 animate-spin"}):A==="delete"?"Delete":"Confirm"})]})]})})]})},io=200,lo=480,co=({visible:t})=>{const n=ee(j=>j.contextEditorTreeWidth),o=ee(j=>j.setContextEditorTreeWidth),[i,a]=r.useState(!1),m=r.useRef(0),w=r.useRef(n),u=r.useRef(null),f=r.useRef(null),g=r.useRef(null),v=r.useCallback(j=>Math.min(lo,Math.max(io,Math.round(j))),[]),h=r.useCallback(j=>{const N=g.current;N&&(N.style.width=`${j}px`,N.style.setProperty("--oc-editor-tree-width",`${j}px`))},[]),c=j=>{if(t){try{j.currentTarget.setPointerCapture(j.pointerId)}catch{}f.current=j.pointerId,a(!0),m.current=j.clientX,w.current=n,u.current=n,j.preventDefault()}},P=j=>{if(!i||f.current!==j.pointerId)return;const N=m.current-j.clientX,T=v(w.current+N);u.current!==T&&(u.current=T,h(T))},d=j=>{if(f.current!==j.pointerId)return;try{j.currentTarget.releasePointerCapture(j.pointerId)}catch{}const N=v(u.current??n);f.current=null,u.current=null,a(!1),o(N)},C=t?n:0;return e.jsxs("div",{ref:g,className:ie("relative h-full flex-shrink-0 overflow-hidden border-l border-border bg-background will-change-[width] motion-reduce:transition-none",!t&&"border-l-0"),style:{width:`${i?u.current??C:C}px`,"--oc-editor-tree-width":`${i?u.current??n:n}px`,overflowX:"clip",transitionProperty:i?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&e.jsx("div",{className:ie("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",i&&"bg-[var(--interactive-border)]"),onPointerDown:c,onPointerMove:P,onPointerUp:d,onPointerCancel:d,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:ie("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",i&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,children:e.jsx(ao,{})})]})},uo="x-pichamber-preview-target-error",ho=t=>{const n=t.get(uo);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},po=(t,n)=>ho(t)?n?"stop-retrying":"retry-registration":"none",fo=({rawUrl:t,onNavigate:n})=>{const{currentTheme:o}=Dr(),[i,a]=r.useReducer(E=>E+1,0),[m,w]=r.useReducer(E=>E+1,0),[u,f]=r.useState({status:"idle"}),g=r.useRef(null),v=r.useRef(1),[h,c]=r.useState(!1),[P,d]=r.useState(!1),[C,j]=r.useState("all"),[N,T]=r.useState([]),[B,re]=r.useState(!1),[F,te]=r.useState(null),z=je(E=>E.currentSessionId),y=je(E=>E.newSessionDraft?.open),b=qe(),G=st(E=>E.addAttachedFile);let U=null;try{U=t?new URL(t):null}catch{U=null}const O=U?U.hostname==="localhost"||U.hostname==="127.0.0.1"||U.hostname==="::1"||U.hostname==="[::1]"||U.hostname==="0.0.0.0":!1,H=U?U.hostname==="0.0.0.0"?new URL(U.toString().replace("0.0.0.0","127.0.0.1")):U:null,ne=H?H.toString():"",R=ne?`${en()||"same-origin"}|${ne}`:"",J=o.metadata.variant;r.useEffect(()=>{if(!ne||!O){f({status:"idle"});return}const E=Ct(R);if(E?.previewToken){f({status:"ready",proxyBasePath:E.proxyBasePath,previewToken:E.previewToken,expiresAt:E.expiresAt});return}E&&ke.delete(R);let oe=!1;return f({status:"loading"}),(async()=>{try{const se=await et("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:ne})}),Q=await _n(se);if(!Q.ok){ke.delete(R),oe||f({status:"error",message:Q.message});return}ke.set(R,Q.target),oe||f({status:"ready",...Q.target})}catch(se){if(ke.delete(R),!oe){const Q=se instanceof Error?se.message:String(se);f({status:"error",message:Q})}}})(),()=>{oe=!0}},[O,R,m,ne]);const S=H&&(H.protocol==="http:"||H.protocol==="https:")?H.toString():"",L=O&&u.status==="ready"?`${u.proxyBasePath}|${u.previewToken||""}|${i}`:"",q=An(L),M=O&&u.status==="ready"&&H&&q===L?(()=>{const E=H.pathname||"/",oe=new URLSearchParams(H.search);oe.delete("oc_url_token"),oe.delete("oc_client_token"),oe.set("ocPreview",String(i)),oe.set("oc_preview_token",u.previewToken||"");const se=oe.toString(),Q=H.hash||"";return tn().authenticatedAsset(`${u.proxyBasePath}${E}${se?`?${se}`:""}${Q}`)})():"",A=O?M:S,ce=O?qs(M):S,ue=O&&(u.status==="loading"||u.status==="idle"||q!==L),de=O&&u.status==="error",ye=r.useCallback(E=>{if(!(z??(y?"draft":null))||!b){ve.error("Open a chat session before attaching preview annotations");return}const se=t||A||"",Q=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},W=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let s=!1;try{const p=g.current,X=p?await Tn(p,E):null;X&&(await G(X),s=!0)}catch{s=!1}nt(St({pageUrl:se,viewport:Q,devicePixelRatio:W,target:E,screenshotAttached:s,intro:"This is a selected DOM element from the in-app preview."})),ve.success("Preview annotation attached to chat")})()},[G,z,b,A,y,t]);r.useEffect(()=>{c(!1),T([]),d(!1),j("all"),re(!1),te(null),v.current=1},[A]),r.useEffect(()=>{const E=g.current?.contentWindow;!h||!E||Vt(E,M,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:B})},[h,B,M]),r.useEffect(()=>{const E=g.current?.contentWindow;!h||!E||Vt(E,M,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:J})},[h,J,M]),r.useEffect(()=>{if(!B||typeof window>"u")return;const E=oe=>{oe.key==="Escape"&&(oe.preventDefault(),oe.stopImmediatePropagation(),re(!1))};return window.addEventListener("keydown",E,!0),()=>window.removeEventListener("keydown",E,!0)},[B]),r.useEffect(()=>{if(!O||typeof window>"u")return;const E=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},oe=Q=>{const W=v.current;v.current+=1,T(s=>{const p=[...s,{...Q,id:W}];return p.length>Ht?p.slice(p.length-Ht):p})},se=Q=>{if(Q.source!==g.current?.contentWindow)return;const W=Q.data;if(!(!W||W.source!=="pichamber-preview-bridge"||W.version!==1)){if(W.type==="ready"){c(!0);return}if(W.type==="console"){const s=W.level==="error"||W.level==="warn"||W.level==="info"||W.level==="debug"?W.level:"log",p=Array.isArray(W.args)?W.args.map(E).filter(Boolean):[];oe({level:s,message:p.join(" "),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="runtime-error"){const s=E(W.filename),p=typeof W.line=="number"?W.line:null,X=typeof W.column=="number"?W.column:null,l=s?`${s}${p!==null?`:${p}${X!==null?`:${X}`:""}`:""}`:"",I=E(W.stack);oe({level:"runtime",message:E(W.message)||"Runtime error",details:[l,I].filter(Boolean).join(`
|
|
127
|
+
`),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="resource-error"){const s=E(W.tag)||"resource",p=E(W.url);oe({level:"resource",message:p?`${s}: ${p}`:s,details:E(W.outerHTML),ts:typeof W.ts=="number"?W.ts:Date.now()});return}if(W.type==="hover"){te(Fe(W.target)?W.target:null);return}if(W.type==="select"&&Fe(W.target)){te(W.target),re(!1),ye(W.target);return}if(W.type==="navigate-preview"){const s=typeof W.url=="string"?W.url:"",p=W.navigation==="external"?"external":"proxy";if(s&&p==="external"){tt(s);return}s&&n(s)}}};return window.addEventListener("message",se),()=>{window.removeEventListener("message",se)}},[ye,O,n]);const pe=N.filter(E=>E.level==="error"||E.level==="runtime"||E.level==="resource").length,xe=N.filter(E=>Xs(E,C)),he=r.useCallback(()=>{const E=[`Preview URL: ${t||A||""}`,`Events: ${N.length}`,""].join(`
|
|
128
128
|
`),oe=N.map(se=>{const Q=new Date(se.ts).toISOString(),W=se.details?`
|
|
129
129
|
${se.details}`:"";return`[${Q}] [${se.level}] ${se.message}${W}`}).join(`
|
|
130
130
|
`);mt(`${E}${oe}`).then(se=>{se.ok?ve.success("Preview console copied"):ve.error("Failed to copy preview console")})},[N,A,t]),D=r.useCallback(()=>{if(!(z??(y?"draft":null))||!b){ve.error("Open a chat session before attaching preview logs");return}const oe=[`Preview URL: ${t||A||""}`,`Events: ${N.length}`,""].join(`
|
|
@@ -132,4 +132,4 @@ ${se.details}`:"";return`[${Q}] [${se.level}] ${se.message}${W}`}).join(`
|
|
|
132
132
|
${Q.details}`:"";return`[${W}] [${Q.level}] ${Q.message}${s}`}).join(`
|
|
133
133
|
`);nt(`These are browser console logs from the dev server running for this project.
|
|
134
134
|
|
|
135
|
-
${oe}${se}`),ve.success("Preview console attached to chat")},[N,z,b,A,y,t]),[$,x]=r.useState("unknown"),_=r.useRef(0),V=r.useRef(0),le=r.useRef(""),fe=r.useRef(""),we=15e3;r.useEffect(()=>{if(!M){x("unknown"),le.current="",_.current=0,V.current=0;return}let E=!1,oe=null;le.current!==R&&(le.current=R,_.current=Date.now(),V.current=0);const se=Q=>{oe=setTimeout(()=>{E||a()},Q)};return x("unknown"),(async()=>{const W=await(async()=>{try{return await et(M,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(E)return;if(!W){x("unreachable"),se(5e3);return}const s=ho(W.headers,fe.current===R);if(s!=="none"){if(ke.delete(R),s==="retry-registration")fe.current=R,f({status:"loading"}),w();else{const l=await W.json().catch(()=>({}));if(E)return;const I=typeof l?.error=="string"?l.error:`HTTP ${W.status}`;f({status:"error",message:I})}return}if(W.status!==502){fe.current="",x("reachable");return}const p=_.current||Date.now();if(Date.now()-p<we){x("starting"),V.current+=1;const l=V.current,I=Math.min(2e3,250*Math.pow(2,Math.min(4,l)));se(I);return}x("unreachable"),se(5e3)})(),()=>{E=!0,oe&&clearTimeout(oe)}},[R,M,i]);const k=O&&u.status==="ready"&&($==="unknown"||$==="starting"),Z=O&&u.status==="ready"&&$==="unreachable",ae=r.useCallback(E=>{if(!O||u.status!=="ready"||typeof window>"u")return;const oe=E.currentTarget.contentWindow;if(oe)try{const se=oe.location,Q=Dn(M);if(se.origin!==Q||se.pathname.startsWith(u.proxyBasePath))return;const W=`${u.proxyBasePath}${se.pathname}${se.search}${se.hash}`;oe.location.replace(W)}catch{}},[O,M,u]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:ce||t,children:ce||t||"No preview URL"}),e.jsx(me,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:"Reload preview","aria-label":"Reload preview",disabled:!A,children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{S&&tt(S)},title:"Open in browser","aria-label":"Open in browser",disabled:!S,children:e.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"})}),O?e.jsx(me,{type:"button",size:"sm",variant:B?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>re(E=>!E),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!h,children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}):null,O?e.jsxs(me,{type:"button",size:"sm",variant:P?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>d(E=>!E),title:h?"Open preview console":"Waiting for preview console","aria-label":h?"Open preview console":"Waiting for preview console",disabled:!h&&N.length===0,children:[e.jsx(K,{name:"terminal-box",className:"h-3.5 w-3.5"}),pe>0?e.jsx("span",{className:"typography-micro text-status-error",children:pe}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[k?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."})]}):Z?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(me,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:"Retry"})]}):A&&(!O||$==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:g,src:A,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:J},onLoad:ae,sandbox:O?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${A}:${i}`),B&&F?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:F.bounds.x,top:F.bounds.y,width:F.bounds.width,height:F.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:[F.tag,F.text?` · ${F.text}`:""]})}):null]}):ue?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):de?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[e.jsx("div",{children:"Could not start preview proxy."}),u.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:u.message}):null]}):e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Preview needs a valid http(s) URL."}),P?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(me,{type:"button",size:"xs",variant:"ghost",onClick:D,disabled:N.length===0,children:"Attach"}),e.jsx(me,{type:"button",size:"xs",variant:"ghost",onClick:he,disabled:N.length===0,children:"Copy"}),e.jsx(me,{type:"button",size:"xs",variant:"ghost",onClick:()=>T([]),disabled:N.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(me,{type:"button",size:"xs",variant:C===E?"secondary":"ghost",onClick:()=>j(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:N.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):xe.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):xe.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:ie("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]})]})},Pt=t=>t,pt=t=>{const n=Pt(t).type;return typeof n=="string"?n:""},fo=t=>{const n=Pt(t).tool;return typeof n=="string"?n:""},mo=t=>{const n=Pt(t).text;return typeof n=="string"?n:""},go=t=>{const n=pt(t);return n==="tool"?fo(t).trim().toLowerCase()||"tool":n||"unknown"},xo=t=>{if(t.length===0)return"";const n=[];for(const o of t){const i=go(o);n.includes(i)||n.push(i)}return n.join(" + ")},wo=t=>t.replace(/\s+/g," ").trim(),yo=t=>{for(const o of t)if(pt(o)==="text"){const i=wo(mo(o));if(i.length===0)continue;return i}const n=t.filter(o=>pt(o)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},bo=(t,n,o)=>`${o(t)} / ${o(n)}`,vo=t=>{if(t==="12h")return!0;if(t==="24h")return!1},jo=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const o=vo(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}})},So={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},Ze={user:0,assistant:0,tool:0,other:0},Co=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,ct=t=>ut(t),No=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},Ce=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,o)=>n+Ce(o),0):t&&typeof t=="object"?Object.values(t).reduce((n,o)=>n+Ce(o),0):0,ko=(t,n)=>{const o=t,i=typeof o.type=="string"?o.type:"";if(i==="reasoning")return{...Ze,assistant:Ce(o.text)+Ce(o.content)};const a=No(o.text,o.content,o.value,o.source?.value,o.source?.text?.value);return i==="tool"||n==="tool"?{user:0,assistant:0,tool:Ce(o.input)+Ce(o.output)+Ce(o.error)+Ce(o.call?.input)+Ce(o.call?.output)+Ce(o.call?.error)+Ce(o.raw)+Math.round(Ce(o.metadata)*.25)+Math.round(Ce(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}},Gt=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),Po=t=>{const n=Ve(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},Ro=(t,n)=>{if(t.length===0)return{...Ze};const o=t.reduce((i,a)=>{const m=Po(a);let w={...Ze};for(const u of a.parts)w=Gt(w,ko(u,m));return Gt(i,w)},{...Ze});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)}},Ae=t=>t.toLocaleString("en-US"),Eo=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),To=(t,n)=>!t||!Number.isFinite(t)?"-":Ir(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),_o=(t,n,o)=>{const i=t.find(m=>m.id===n),a=i?.models?.find(m=>m.id===o);return{providerName:i?.name||n||"-",modelName:a?.name||o||"-",contextLimit:typeof a?.limit?.context=="number"?a.limit.context:null}},Do=()=>{const t=ee(d=>d.timeFormatPreference),[n,o]=r.useState({}),{value:i,show:a,clear:m}=Dr(null,2e3),w=je(d=>d.currentSessionId),u=je(d=>d.currentSessionDirectory),f=Ar(),g=un(w??""),v=Ie(d=>d.providers);r.useEffect(()=>{o(d=>Object.keys(d).length>0?{}:d),m()},[m,u,w]);const h=r.useCallback(async(d,C)=>{(await mt(C)).ok?a(d):m()},[m,a]),c=r.useMemo(()=>{const d=w?f.find(M=>M.id===w)??null:null,C=g.filter(M=>Ve(M.info).role==="assistant"),j=g.filter(M=>Ve(M.info).isUser);let N=null;for(let M=C.length-1;M>=0;M-=1){const A=C[M];if(ct(A).total>0){N=A;break}}const T=N?ct(N):So,B=N?.info?.usage,re=on({input:T.input,cache:{read:T.cacheRead,write:T.cacheWrite}}),F=C.reduce((M,A)=>{const ce=Co(A.info.cost);return M+ce},0),te=N?.info?.model??null,z=_o(v,te?.providerID||"",te?.modelID||""),y=z.contextLimit,b=B?an(B):T.total,G=y&&y>0?Math.min(999,b/y*100):0,U=[...g].reverse().find(M=>Ve(M.info).isUser&&typeof M.info.system=="string")?.info?.system||"",O=Ro(g,U),H=O.user,ne=O.assistant,R=O.tool,J=B?0:Math.max(0,T.input-H-ne-R),S=H+ne+R+J,L=g[0]?.info?.time?.created,q=g.length>0?g[g.length-1]?.info?.time?.created:null;return{sessionTitle:Sn(d),messagesCount:g.length,userMessagesCount:j.length,assistantMessagesCount:C.length,createdAt:d?.time?.created??L??null,lastActivityAt:q??d?.time?.created??null,providerModel:z,tokenBreakdown:T,usagePercent:G,cacheHitRate:re,totalAssistantCost:F,contextLimit:y,contextWindowTokens:b,hasUsage:B!==void 0,breakdown:{user:H,assistant:ne,tool:R,other:J},breakdownTotal:S}},[w,v,g,f]);if(!w)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 P=[{key:"user",label:"User",value:c.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:c.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool Calls",value:c.breakdown.tool,color:"var(--status-warning)"},...c.hasUsage?[]:[{key:"other",label:"Other",value:c.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:c.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:[c.providerModel.providerName," / ",c.providerModel.modelName]}),c.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:To(c.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:[Ae(c.contextWindowTokens),c.contextLimit?` / ${Ae(c.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:c.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,c.usagePercent)}%`,backgroundColor:c.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:`${c.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:Ae(c.messagesCount)},{label:"User",value:Ae(c.userMessagesCount)},{label:"Assistant",value:Ae(c.assistantMessagesCount)},{label:"Cost",value:Eo(c.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:c.tokenBreakdown.input,format:"count"},{label:"Output",value:c.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:c.tokenBreakdown.reasoning,format:"count"},{label:"Cache Read",value:c.tokenBreakdown.cacheRead,format:"count"},{label:"Cache Write",value:c.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache Hit",value:c.cacheHitRate.hasInput?c.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)}%`:Ae(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:P.map(d=>d.value<=0||c.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${d.value/c.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:P.map(d=>{const C=c.breakdownTotal>0?d.value/c.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:[C.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:[...g].reverse().map(d=>{const j=Ve(d.info).role,N=j==="assistant",T=j==="user",B=n[d.info.id]===!0,re=i===d.info.id,F=d.info.time?.created??null,te=xo(d.parts),z=N?ct({info:d.info,parts:d.parts}):null,y=T?yo(d.parts):"",b=jo(F,t),G=te||"—",U=z?bo(z.input,z.output,Ae):"",O=j||"unknown",H=te?`${O}: ${te}`:O,ne=B?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":B,onClick:()=>{o(R=>({...R,[d.info.id]:R[d.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:N?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[T?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",y]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:N?G:H}),N&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:U})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:b})]})}),B&&e.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:e.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[e.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:e.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:R=>{R.stopPropagation(),h(d.info.id,ne)},"aria-label":re?"Copied":"Copy JSON",title:re?"Copied":"Copy",children:re?e.jsx(K,{name:"check",className:"size-3.5"}):e.jsx(K,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Mr,{language:"json",code:ne,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},d.info.id)})})]})]})})},Ao=De(()=>Re(()=>import("./DiffView-DD1AFRi3.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,119])).then(t=>({default:t.DiffView}))),Mo=De(()=>Re(()=>import("./FilesView-B_BF39ef.js"),__vite__mapDeps([120,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,117,118,99,100,84,85,86,87,88,89,90,91,92,93,94,95,96,97,121,122,111,112,113,114,115,116,123,124,81,82,83,98,101,102,103,104,105,106,107,125,126,127,128])).then(t=>({default:t.FilesView}))),Io=De(()=>Re(()=>import("./GitView-LFEpCasf.js"),__vite__mapDeps([129,24,1,2,9,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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,114,115,116,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,117,118,130])).then(t=>({default:t.GitView}))),Lo=380,Oo=1400,Ln=600,$o=100,Wo=24,Yt=t=>Number.isFinite(t)?Math.min(Oo,Math.max(Lo,Math.round(t))):Ln,Fo=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},Bo=(t,n)=>{if(!t)return"";const o=t.replace(/\\/g,"/"),i=n.replace(/\\/g,"/").replace(/\/+$/,"");return i&&o.startsWith(i+"/")?o.slice(i.length+1):o},On=(t,n=null)=>t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?jt(n).label:t==="terminal"?"Terminal":"Context",zo=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},Uo=(t,n=null)=>{if(t.label)return t.label;if(t.mode==="file")return zo(t.targetPath)||"Files";if(t.mode==="preview"){const o=t.targetPath;if(o)try{const i=new URL(o);return i.host||i.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":On(t.mode,n)},Jt=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(ft,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(ur,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(K,{name:jt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(K,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(K,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(K,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(K,{name:"global",className:"h-3.5 w-3.5"})},Ho=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,Vo=()=>{const t=qe()??"",n=r.useMemo(()=>Pe(t),[t]),o=ee(l=>n?l.contextPanelByDirectory[n]:void 0),i=ee(l=>l.closeContextPanel),a=ee(l=>l.closeContextPanelTab),m=ee(l=>l.openContextPanelTab),w=ee(l=>l.toggleContextPanelExpanded),u=ee(l=>l.setContextPanelWidth),f=ee(l=>l.setActiveContextPanelTab),g=ee(l=>l.reorderContextPanelTabs),v=Te(l=>l.setSelectedPath),h=ee(l=>l.openContextPreview),c=ee(l=>l.contextEditorTreeVisible),P=ee(l=>l.toggleContextEditorTree),d=r.useMemo(()=>o?.tabs??[],[o?.tabs]),C=d.find(l=>l.id===o?.activeTabId)??d[d.length-1]??null,j=!!(o?.isOpen&&C),N=!!(j&&o?.expanded),[T,B]=r.useState(null),re=o?.width,F=Or,te=T??(typeof window<"u"?window.innerWidth:Ln*2),z=Yt(re??Math.round(F*te)),y=hn(n||null),[b,G]=r.useState(!1),[U,O]=r.useState(null),[H,ne]=r.useState(null),[R,J]=r.useState(null),S=r.useRef(0),L=r.useRef(z),q=r.useRef(null),M=r.useRef(null),A=r.useRef(null),ce=r.useRef(!1);r.useLayoutEffect(()=>{const l=A.current?.parentElement;if(!l||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>{B(l.clientWidth||null)});return I.observe(l),B(l.clientWidth||null),()=>I.disconnect()},[]),r.useEffect(()=>{if(!j||ce.current){ce.current=j;return}const l=window.requestAnimationFrame(()=>{A.current?.focus({preventScroll:!0})});return ce.current=!0,()=>window.cancelAnimationFrame(l)},[j]);const ue=r.useRef(null),de=r.useRef(null),ye=r.useCallback(()=>{de.current=null;const l=A.current,I=q.current;!l||I===null||l.style.setProperty("--oc-context-panel-width",`${I}px`)},[]);r.useEffect(()=>()=>{de.current!==null&&clearTimeout(de.current)},[]);const pe=r.useCallback(l=>{const I=Yt(l),Y=ue.current;return Y===null?I:Math.min(I,Math.max(1,Y))},[]),xe=r.useCallback(l=>{!j||N||!n||(M.current=l.pointerId,G(!0),S.current=l.clientX,L.current=z,q.current=z,ue.current=Fo(A.current),document.documentElement.style.cursor="col-resize",l.preventDefault())},[n,N,j,z]),he=r.useCallback(()=>{const l=pe(q.current??z);q.current=null,ue.current=null,de.current!==null&&(clearTimeout(de.current),de.current=null),document.documentElement.style.cursor="",n&&u(n,l),G(!1),M.current=null},[pe,n,u,z]);r.useEffect(()=>{if(!b)return;const l=ge=>{if(M.current!==ge.pointerId)return;const be=S.current-ge.clientX,Ee=pe(L.current+be);q.current!==Ee&&(q.current=Ee,de.current===null&&(de.current=setTimeout(ye,$o)))},I=ge=>{M.current===ge.pointerId&&he()},Y=()=>{he()};return window.addEventListener("pointermove",l),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",I),window.addEventListener("blur",Y),()=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",I),window.removeEventListener("blur",Y)}},[ye,pe,he,b]),r.useEffect(()=>{b||(q.current=null,document.documentElement.style.cursor="")},[b]);const D=r.useCallback(()=>{n&&i(n)},[i,n]),$=r.useCallback(()=>{n&&w(n)},[n,w]),x=r.useCallback(l=>{l.key==="Escape"&&(Lr(l.target)||(l.preventDefault(),l.stopPropagation(),D()))},[D]);r.useEffect(()=>{if(!(!n||!C)&&C.mode==="file"&&C.targetPath){v(n,C.targetPath,{allowOutsideRoot:!0});return}},[C,n,v]);const _=r.useCallback(l=>{!n||C?.mode!=="diff"||m(n,{mode:"diff",targetPath:C.targetPath,stagedDiff:l==="staged",diffScope:l})},[C,n,m]),V=C?.mode==="file"||C?.mode==="preview",le=r.useMemo(()=>C?d.filter(l=>l.mode===C.mode):[],[C,d]),fe=r.useMemo(()=>le.map(l=>{const I=Uo(l,y),Y=Ho(I,Wo),ge=Bo(l.targetPath,t);return{id:l.id,label:Y,icon:Jt(l,y),title:ge?`${I}: ${ge}`:I,closeLabel:`Close ${Y} tab`}}),[le,t,y]),we=C?.mode==="context"?e.jsx(Do,{}):C?.mode==="git"?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Io,{isActive:j,gitHeaderSlot:C?.mode==="git"?H:null})}):C?.mode==="preview"?e.jsx(po,{rawUrl:C.targetPath??"",onNavigate:l=>h(t,l)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(K,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"Preview"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Use Project Actions or a terminal Preview button to open a preview."})]}),k=r.useMemo(()=>d.filter(l=>l.mode==="browser"),[d]),Z=r.useMemo(()=>d.filter(l=>l.mode==="diff"),[d]),ae=r.useMemo(()=>d.some(l=>l.mode==="terminal"),[d]),E=r.useMemo(()=>d.some(l=>l.mode==="file"),[d]),oe=r.useMemo(()=>d.some(l=>l.mode==="file"&&l.targetPath),[d]),se=C?.mode==="file",Q=C?.mode==="terminal",W=C?.mode==="git",s=C?.mode==="diff",p=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[V?e.jsx(Rs,{items:fe,activeId:C?.id??null,onSelect:l=>{n&&f(n,l)},onClose:l=>{n&&a(n,l)},onReorder:(l,I)=>{n&&g(n,l,I)},layoutMode:"scrollable",variant:"default"}):Q?e.jsx("div",{ref:l=>{O(l)},className:"flex min-w-0 flex-1 items-center px-1"}):W?e.jsx("div",{ref:l=>{ne(l)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):s?e.jsx("div",{ref:l=>{J(l)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[C?Jt(C,y):null,e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:C?On(C.mode,y):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[se?e.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:P,className:"h-7 w-7 p-0",title:"Toggle file tree","aria-label":"Toggle file tree","aria-pressed":c,children:e.jsx(K,{name:"layout-right",className:"h-3.5 w-3.5"})}):null,e.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:$,className:"h-7 w-7 p-0",title:N?"Collapse panel":"Expand panel","aria-label":N?"Collapse panel":"Expand panel",children:N?e.jsx(K,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):e.jsx(K,{name:"fullscreen",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:D,className:"h-7 w-7 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]})]}),X=j?N?{"--oc-context-panel-width":T!==null?`${T}px`:"100%",width:T!==null?`${T}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${z}px`}:{"--oc-context-panel-width":`${z}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:A,"data-context-panel":"true",tabIndex:-1,inert:!j||void 0,className:ie("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",!j&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:x,style:X,children:[j&&!N&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),j&&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:ie("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",b&&"bg-[var(--interactive-border)]"),onPointerDown:xe,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:ie("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]",!j&&"pointer-events-none select-none opacity-0"),style:{width:N?T!==null?`${T}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!j,children:[p,e.jsxs("div",{className:ie("relative min-h-0 flex-1 overflow-hidden",b&&"pointer-events-none"),children:[E?e.jsxs("div",{className:ie("absolute inset-0 flex",se?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:oe?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Mo,{mode:"editor-only",isVisible:j&&se})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(K,{name:"file-code",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"No file open"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Pick a file from the tree to start editing."})]})}),e.jsx(lo,{visible:c})]}):null,k.map(l=>e.jsx("div",{className:ie("absolute inset-0",C?.id!==l.id&&"hidden"),children:e.jsx(Qs,{initialUrl:l.targetPath??"",directory:n,tabID:l.id})},l.id)),j?Z.filter(l=>C?.id===l.id).map(l=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(Ao,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:l.diffScope??(l.stagedDiff?"staged":"working"),onDiffScopeChange:_,targetFilePath:l.targetPath,flushContent:!0,toolbarSlot:s?R:null})})},l.id)):null,ae?e.jsx("div",{className:ie("absolute inset-0",C?.mode==="terminal"?"block":"hidden"),children:e.jsx(ln,{visible:j&&C?.mode==="terminal",terminalHeaderSlot:Q?U:null})}):null,j&&!se&&C?.mode!=="browser"&&C?.mode!=="diff"&&C?.mode!=="terminal"?we:null]})]})]})},Ko=150,Xo=500,qo=[],Me=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),Ye=(t,n)=>{if(!t||typeof t!="object")return;const o=t[n];return typeof o=="number"&&Number.isFinite(o)?o:void 0},Go=t=>t>99?"99+":String(t),Yo=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",Jo=({surface:t,isActive:n,showActivityDot:o,label:i,description:a,badgeCount:m,badgeAriaLabel:w,badgeDescription:u,orderNumber:f,showOrderNumber:g,onSelect:v,chartPercentage:h,chartDetails:c})=>{const{attributes:P,listeners:d,setNodeRef:C,transform:j,transition:N,isDragging:T}=vn({id:t.id}),B=m!=null&&m>0?Go(m):null;return e.jsx("div",{ref:C,style:{transform:jn.Translate.toString(j),transition:N},className:ie("relative",T&&"z-10 opacity-70"),children:e.jsxs(Le,{delayDuration:Ko,children:[e.jsx(Oe,{asChild:!0,children:e.jsxs("button",{type:"button",...P,...d,onClick:()=>v(t),"aria-label":w??i,"aria-pressed":n,className:ie("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"text-primary":"text-muted-foreground hover:text-foreground"),children:[t.id==="context"&&typeof h=="number"?e.jsx(Mt,{percentage:h,className:"size-[18px] -rotate-90"}):e.jsx(K,{name:t.icon,className:"h-[18px] w-[18px]"}),g&&f!=null?e.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-muted px-1 text-[0.625rem] font-medium leading-none text-muted-foreground",children:f===10?"0":f}):B?e.jsx("span",{"aria-hidden":"true",className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[0.625rem] font-semibold leading-none",style:{backgroundColor:"var(--status-info-background)",color:"var(--status-info)"},children:B}):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($e,{side:"left",sideOffset:8,className:t.id==="context"&&c?"p-0 border-0 bg-transparent shadow-none":void 0,children:t.id==="context"&&c?e.jsx("div",{className:"w-[300px] overflow-hidden rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[e.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:e.jsx(Mt,{percentage:c.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:i}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:c.hasData?e.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[e.jsxs("span",{className:ie("font-semibold",Yo(c.percentage)),children:[c.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${Me(c.totalTokens)}/${Me(c.contextLimit)}`})]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:"No data yet"})})]}),c.hasData?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.contextLimit)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.outputLimit)})]}),typeof c.cacheRead=="number"&&typeof c.cacheWrite=="number"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.cacheRead)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.cacheWrite)})]})]}):null,typeof c.cacheHitPercent=="number"?e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache hit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:`${c.cacheHitPercent.toFixed(1)}%`})]}):null]}):e.jsx("div",{className:"px-2.5 py-2 typography-micro text-muted-foreground",children:a})]})}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:i}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:a}),u?e.jsx("span",{className:"typography-micro text-muted-foreground",children:u}):null]})})]})})},Qo=()=>{const t=qe(),n=t?Kn(t):"",o=ee(x=>n?x.contextPanelByDirectory[n]:void 0),i=ee(x=>x.contextRailOrder),a=ee(x=>x.setContextRailOrder),m=ee(x=>x.openContextSurface),w=ee(x=>x.shortcutOverrides),{screenWidth:u}=rt(),{git:f}=gt(),g=dn(n||null),v=hn(n||null),h=pn(x=>x.ensureStatus);r.useEffect(()=>{n&&h(n,f)},[n,h,f]);const c=r.useMemo(()=>Xn("switch_context_surface",w),[w]),[P,d]=r.useState(!1);r.useEffect(()=>{const x=new Set;let _=null,V=!1;const le=ae=>ae.length===1&&ae>="0"&&ae<="9",fe=()=>{Rt(c,x)?!V&&_===null&&(_=setTimeout(()=>d(!0),Xo)):(V=!1,_!==null&&(clearTimeout(_),_=null),d(!1))},we=ae=>{if(x.add(ae.key.toLowerCase()),le(ae.key)&&Rt(c,x)){V=!0,_!==null&&(clearTimeout(_),_=null),d(!1);return}fe()},k=ae=>{x.delete(ae.key.toLowerCase()),fe()},Z=()=>{x.clear(),V=!1,_!==null&&(clearTimeout(_),_=null),d(!1)};return window.addEventListener("keydown",we,!0),window.addEventListener("keyup",k,!0),window.addEventListener("blur",Z),()=>{window.removeEventListener("keydown",we,!0),window.removeEventListener("keyup",k,!0),window.removeEventListener("blur",Z),_!==null&&clearTimeout(_)}},[c]);const C=xn(ht(bs,{activationConstraint:{distance:8}}),ht(ys,{activationConstraint:{delay:200,tolerance:6}})),j=o?.tabs??qo,N=j.find(x=>x.id===o?.activeTabId)??null,T=o?.isOpen?N?.mode??null:null,B=g?.files.length??0,re=je(x=>x.currentSessionId),F=je(x=>!!x.newSessionDraft?.open),te=Ie(x=>x.providers),z=Ie(x=>x.currentProviderId),y=Ie(x=>x.currentModelId),b=Ie(x=>x.getCurrentModel()),G=Ie(x=>x.getModelMetadata);Ie(x=>x.modelsMetadata.size);const U=$r(r.useCallback(x=>re?x.sessionModelSelections.get(re)??null:null,[re])),O=un(re??""),H=r.useMemo(()=>{for(let x=O.length-1;x>=0;x-=1){const _=O[x];if(_?.info.role==="assistant")try{if(ut(_).total>0)return _}catch{continue}}return null},[O]),R=r.useMemo(()=>{for(let x=O.length-1;x>=0;x-=1){const _=O[x]?.info;if(_.role!=="user")continue;const V=_.model,le=V?.providerID??V?.providerId,fe=V?.modelID??V?.modelId;if(typeof le=="string"&&le.trim()&&typeof fe=="string"&&fe.trim())return{providerID:le,modelID:fe}}return null},[O])??(()=>{const x=H?.info.model,_=x?.providerID??x?.providerId,V=x?.modelID??x?.modelId;return _&&V?{providerID:_,modelID:V}:null})()??(U?{providerID:U.providerId,modelID:U.modelId}:null)??(z&&y?{providerID:z,modelID:y}:null),S=(R?te.find(x=>x.id===R.providerID):void 0)?.models.find(x=>x.id===R?.modelID),L=R?G(R.providerID,R.modelID):void 0,q=Ye(S?.limit,"context")??L?.limit?.context??Ye(b?.limit,"context")??0,M=Ye(S?.limit,"output")??L?.limit?.output??Ye(b?.limit,"output")??0,A=H?(()=>{try{return ut(H)}catch{return null}})():null,ce=H?.info?.usage,ue=ce?an(ce):A?.total??0,de=!F&&ue>0&&q>0?Math.min(ue/q*100,999):0,ye=de,pe=A?on({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}):null,xe=pe?.hasInput?pe.percent:null,he=r.useMemo(()=>{const x=!!H&&ue>0&&q>0;return{percentage:de,totalTokens:ue,contextLimit:q,outputLimit:M,cacheRead:A?.cacheRead??null,cacheWrite:A?.cacheWrite??null,cacheHitPercent:xe,hasData:x}},[A,xe,q,H,M,de,ue]),D=r.useMemo(()=>Wr({railOrder:i,tabs:j}),[i,u,j]),$=r.useCallback(x=>{const{active:_,over:V}=x;if(!V||_.id===V.id)return;const le=Fr(ee.getState().contextRailOrder).map(k=>k.id),fe=le.indexOf(_.id),we=le.indexOf(V.id);fe===-1||we===-1||a(js(le,fe,we))},[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(wn,{sensors:C,collisionDetection:yn,onDragEnd:$,children:e.jsx(bn,{items:D.map(x=>x.id),strategy:Ss,children:D.map((x,_)=>{const V=x.id==="git"?jt(v):null,le=V?{...x,...V}:x,fe=le.label,we=x.id==="git"&&v===!0?B:0,k=we>0?we:null,Z=x.id==="context";return e.jsx(Jo,{surface:le,isActive:T===x.mode,showActivityDot:!1,label:fe,description:le.description,badgeCount:k,badgeAriaLabel:k!==null?k===1?`${fe}, ${k} changed file`:`${fe}, ${k} changed files`:null,badgeDescription:k!==null?k===1?`${k} changed file`:`${k} changed files`:null,chartPercentage:Z?ye:void 0,chartDetails:Z?he:void 0,orderNumber:_+1,showOrderNumber:P,onSelect:ae=>m(n,ae.mode)},x.id)})})})}):null},Zo=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),ea=(t,n,o,i)=>!o||i!==o||t.length===0?[]:He(t,n,a=>a.name,{limit:10,threshold:.4}),ta=new Set,dt=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),o=n.startsWith("//");let i=n.replace(/\/+/g,"/");o&&!i.startsWith("//")&&(i=`/${i}`);const a=i==="/",m=/^[A-Za-z]:\/$/.test(i);return!a&&!m&&(i=i.replace(/\/+$/,"")),i},na=()=>{const t=ee(s=>s.isCommandPaletteOpen),n=ee(s=>s.setCommandPaletteOpen),o=ee(s=>s.setActiveMainTab),i=ee(s=>s.setSettingsDialogOpen),a=ee(s=>s.setSettingsPage),m=ee(s=>s.setSessionSwitcherOpen),w=ee(s=>s.toggleSidebar),u=ee(s=>s.openContextOverview),f=ee(s=>s.openContextSurface),g=ee(s=>s.openContextFile),v=ee(s=>s.shortcutOverrides),h=je(s=>s.openNewSessionDraft),c=je(s=>s.setCurrentSession),P=Br({archived:!1}),d=zr(r.useCallback(s=>t?s.ids:ta,[t])),C=Ur(r.useCallback(s=>t?s.rankById:Hr,[t])),j=qn(s=>s.currentDirectory),N=It(s=>s.getActiveProject()),T=It(s=>s.projects),B=qe(),re=Gn(s=>s.searchFiles),{files:F,git:te}=gt(),z=pn(s=>s.ensureStatus),{isMobile:y}=rt(),b=r.useMemo(()=>B?dt(B):null,[B]),[G,U]=r.useState(""),H=Vr(G,200).trim(),ne=G.trim();r.useEffect(()=>{t&&U("")},[t]),r.useEffect(()=>{if(!t||!te)return;const s=setTimeout(()=>{const p=new Set;for(const X of P){const l=ot(X);!l||p.has(l)||(p.add(l),z(l,te))}},0);return()=>clearTimeout(s)},[t,P,te,z]);const R=r.useCallback(()=>n(!1),[n]),J=r.useCallback(s=>()=>{R(),s()},[R]),S=r.useMemo(()=>{const s=[{id:"new-session",title:"New Session",icon:e.jsx(K,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:J(()=>{o("chat"),m(!1),h()})},{id:"add-project",title:"Add Project",icon:e.jsx(K,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:J(()=>{Kr.requestDirectoryDialog()})},{id:"toggle-sidebar",title:y?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(K,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:y?"Show Session Switcher":"Toggle Sidebar",onSelect:J(()=>{if(y){const{isSessionSwitcherOpen:p}=ee.getState();m(!p)}else w()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(K,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:J(()=>{j&&f(j,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(K,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:J(()=>{j&&u(j)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(K,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:J(()=>i(!0))}];return Yn()&&s.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(K,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:J(()=>{Zt("desktop_open_draft_mini_chat_window",{directory:dt(j||N?.path||""),projectId:N?.id??null}).catch(p=>{console.warn("[command-palette] failed to open draft mini chat window",p)})})}),s},[J,y,o,m,h,w,f,j,u,i,N?.id,N?.path]),L=r.useMemo(()=>{const s=Jn();return{isWeb:!s&&Qn(),isDesktop:s,isMobile:y}},[y]),q=r.useMemo(()=>hr.filter(s=>s.slug!=="home").filter(s=>s.isAvailable?s.isAvailable(L):!0).map(s=>{const p=pr(s.slug)??"settings-3",X=(s.keywords??[]).join(" ");return{id:`settings:${s.slug}`,title:s.title,icon:e.jsx(K,{name:p,className:"mr-2 h-4 w-4"}),searchText:`${s.title} ${s.group} ${X}`,onSelect:J(()=>{a(s.slug),i(!0)})}}),[L,J,a,i]),M=r.useMemo(()=>Xr(P,d,C),[P,d,C]),A=qr(),ce=r.useCallback((s,p)=>p&&A.get(p)?.trim()||null,[A]),[ue,de]=r.useState([]),[ye,pe]=r.useState(""),xe=Zo(b,H);r.useEffect(()=>{if(!t){de([]),pe("");return}if(!xe){de([]),pe("");return}if(!b){de([]),pe("");return}let s=!1;return re(b,H,10,{type:"file"}).then(p=>{s||(de(p.map(X=>({path:dt(X.path),name:X.name,relativePath:X.relativePath}))),pe(xe))}).catch(()=>{s||(de([]),pe(xe))}),()=>{s=!0}},[t,b,H,xe,re]);const he=ne.length>0,D=r.useMemo(()=>he?He(S,ne,s=>s.searchText,{limit:7,noFuzzy:!0}):S.map(s=>({item:s,score:0})),[S,ne,he]),$=r.useMemo(()=>he?He(q,ne,s=>s.searchText,{limit:7,noFuzzy:!0}):[],[q,ne,he]),x=r.useMemo(()=>he?He(M,ne,s=>s.title||"",{limit:7,threshold:.2}):M.slice(0,5).map(s=>({item:s,score:0})),[M,ne,he]),_=r.useMemo(()=>t?ea(ue,H,xe,ye):[],[t,ue,ye,xe,H]),V=t&&xe.length>0&&ye!==xe,le=r.useMemo(()=>{if(!he)return[];const s=T.map(p=>({...p,displayName:p.label||p.path.split("/").pop()||p.path,searchText:`${p.label||""} ${p.path}`}));return He(s,ne,p=>p.searchText,{limit:7,threshold:.4})},[T,ne,he]),fe=D.map(s=>s.item),we=$.map(s=>s.item),k=x.map(s=>s.item),Z=he?_.map(s=>s.item):[],ae=he?le.map(s=>s.item):[],E=r.useMemo(()=>{if(!he)return["commands","sessions"];const s=X=>X.length?X[0].score:1/0,p=[{key:"commands",score:s(D)},{key:"settings",score:s($)},{key:"sessions",score:s(x)},{key:"files",score:s(_)},{key:"projects",score:s(le)}];return p.sort((X,l)=>X.score-l.score),p.map(X=>X.key)},[he,D,$,x,_,le]),oe=r.useCallback(s=>{R(),c(s.id,ot(s))},[R,c]),se=r.useCallback(async s=>{if(!b)return;const p=await fn(F,s,{directory:b});if(!p.ok){ve.error(mn(p.reason));return}g(b,s),R()},[b,F,g,R]),Q=r.useCallback((s,p)=>{R(),h({selectedProjectId:s,directoryOverride:p})},[R,h]),W=r.useCallback(s=>nn(rn(s,v)),[v]);return e.jsxs(xt,{open:t,onOpenChange:n,children:[e.jsxs(yt,{className:"sr-only",children:[e.jsx(bt,{children:"Command Palette"}),e.jsx(vt,{children:"Search files, sessions, and commands."})]}),e.jsx(wt,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs(Gr,{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(Yr,{value:G,onValueChange:U,placeholder:"Search files, sessions, commands..."}),e.jsxs(Jr,{children:[e.jsx(Qr,{children:"No results found."}),E.map(s=>s==="commands"&&fe.length>0?e.jsx(ze,{children:fe.map(p=>e.jsxs(Ue,{value:p.id,onSelect:p.onSelect,children:[p.icon,e.jsx("span",{children:p.title}),p.shortcutId?e.jsx(Zr,{children:W(p.shortcutId)}):null]},p.id))},"commands"):s==="settings"&&we.length>0?e.jsx(ze,{children:we.map(p=>e.jsxs(Ue,{value:p.id,onSelect:p.onSelect,children:[p.icon,e.jsx("span",{children:p.title})]},p.id))},"settings"):s==="sessions"&&k.length>0?e.jsx(ze,{children:k.map(p=>{const X=Sn(p),l=ot(p),I=ce(p.id,l);return e.jsxs(Ue,{value:`session:${p.id}`,onSelect:()=>oe(p),children:[e.jsx(K,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:X}),I?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(K,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:I})]}):null]},p.id)})},"sessions"):s==="files"&&Z.length>0?e.jsx(ze,{children:Z.map(p=>{const X=Zn(p.relativePath||p.name,{maxLength:80});return e.jsxs(Ue,{value:`file:${p.path}`,onSelect:()=>{se(p.path)},children:[e.jsx(ft,{filePath:p.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":p.relativePath,children:X})]},`file:${p.path}`)})},"files"):s==="projects"&&ae.length>0?e.jsx(ze,{children:ae.map(p=>{const X=p.displayName;return e.jsxs(Ue,{value:`project:${p.id}`,onSelect:()=>Q(p.id,p.path),children:[e.jsx(K,{name:"folder",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:X}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:p.path})]},`project:${p.id}`)})},"projects"):null),V?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},ra=(t,n,o)=>tr(t)?nn(rn(t,o)):n,sa=()=>{const t=ee(m=>m.isHelpDialogOpen),n=ee(m=>m.setHelpDialogOpen),o=ee(m=>m.shortcutOverrides),i=er(),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 + ${i} + N`],descriptionKey:"New Window (desktop only)",icon:"window"}]},{categoryKey:"Session Management",items:[{id:"new_chat",descriptionKey:"Create New Session",icon:"add",keys:""},{id:"focus_input",descriptionKey:"Focus Chat Input",icon:"text",keys:""},{id:"cycle_session_folder",descriptionKey:"Cycle session folder",icon:"folder-open",keys:""},{id:"cycle_draft_folder",descriptionKey:"Cycle draft folder",icon:"folder-3",keys:""},{id:"open_timeline_dialog",descriptionKey:"Open conversation timeline",icon:"history",keys:""},{id:"abort_run",descriptionKey:"Abort active run (double press)",icon:"close-circle",keys:""}]},{categoryKey:"Panels",items:[{id:"open_right_sidebar",descriptionKey:"Open right sidebar",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{keys:[`${i} + 1...0`],descriptionKey:"Switch Context Panel Surface (number key)",icon:"layout-right"}]},{categoryKey:"Interface",items:[{id:"cycle_theme",descriptionKey:"Cycle Theme (Light → Dark → System)",icon:"palette",keys:""},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"Open Settings",icon:"settings-3",keys:""}]}];return e.jsx(xt,{open:t,onOpenChange:n,children:e.jsxs(wt,{className:"w-[92vw] max-w-[1120px] h-[84vh] max-h-[900px] flex flex-col overflow-hidden",children:[e.jsxs(yt,{children:[e.jsxs(bt,{className:"flex items-center gap-2",children:[e.jsx(K,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(vt,{children:"Use these keyboard shortcuts to navigate PiChamber efficiently"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:e.jsx("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-x-10",children:a.map(m=>e.jsxs("div",{className:"min-w-0 break-inside-avoid",children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:m.categoryKey}),e.jsx("div",{className:"space-y-1",children:m.items.map(w=>{const u=w.id?ra(w.id,Array.isArray(w.keys)?w.keys[0]:w.keys,o):Array.isArray(w.keys)?w.keys:w.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:[w.icon&&e.jsx(K,{name:w.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:w.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(u)?u:[u]).map((f,g)=>e.jsxs(r.Fragment,{children:[g>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:f})]},`${f}-${g}`))})]},w.id||w.descriptionKey)})})]},m.categoryKey))})})]})})},oa=r.createContext(null),aa=({children:t,value:n})=>e.jsx(oa.Provider,{value:n,children:t}),Qt=De(()=>Re(()=>import("./GitView-LFEpCasf.js"),__vite__mapDeps([129,24,1,2,9,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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,114,115,116,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,117,118,130])).then(t=>({default:t.GitView}))),ia=De(()=>Re(()=>import("./DiffView-DD1AFRi3.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,119])).then(t=>({default:t.DiffView}))),la=De(()=>Re(()=>import("./FilesView-B_BF39ef.js"),__vite__mapDeps([120,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,117,118,99,100,84,85,86,87,88,89,90,91,92,93,94,95,96,97,121,122,111,112,113,114,115,116,123,124,81,82,83,98,101,102,103,104,105,106,107,125,126,127,128])).then(t=>({default:t.FilesView}))),ca=De(()=>Re(()=>import("./DiagramView-0Iq1ak1I.js"),__vite__mapDeps([131,1,2,9,3,4,5,6,7,8,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,121,122])).then(t=>({default:t.DiagramView}))),da=De(()=>Re(()=>import("./SettingsView-eG-wN-yY.js").then(t=>t.a),__vite__mapDeps([132,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,114,115,116,133,134,130])).then(t=>({default:t.SettingsView}))),ua=De(()=>Re(()=>import("./SettingsWindow-Dvnp8YrA.js"),__vite__mapDeps([135,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,132,111,112,113,114,115,116,133,134,130])).then(t=>({default:t.SettingsWindow}))),ha=()=>{const t=ee(S=>S.isSidebarOpen),n=ee(S=>S.activeMainTab),o=ee(S=>S.setIsMobile),i=ee(S=>S.isSessionSwitcherOpen),a=ee(S=>S.isSettingsDialogOpen),m=ee(S=>S.setSettingsDialogOpen),[w,u]=r.useState(!1);r.useEffect(()=>{a&&u(!0)},[a]),r.useEffect(()=>{const S=()=>ee.getState().closeMainSurfaces(),L=je.subscribe((M,A)=>{const ce=!!M.currentSessionId&&M.currentSessionId!==A.currentSessionId,ue=!!M.newSessionDraft?.open&&M.newSessionDraft!==A.newSessionDraft;(ce||ue)&&S()}),q=ee.subscribe((M,A)=>{M.activeMainTab!==A.activeMainTab&&S()});return()=>{L(),q()}},[]);const{isMobile:f}=rt(),g=r.useRef(!1),[v,h]=r.useState(!1),[c,P]=r.useState(!1),[d,C]=r.useState(!1),[j,N]=r.useState(!1),T=r.useCallback(S=>{h(S),ee.getState().setSessionSwitcherOpen(S)},[]),B=r.useRef(typeof window>"u"?0:window.innerWidth),re=r.useRef(null),F=r.useRef(!1),te=r.useRef(!1),z=r.useRef(!1),y=r.useRef(null),b=r.useRef(null),G=Lt(-B.current),U=Se.useRef(0),O=Lt(B.current),H=Se.useRef(0);Se.useEffect(()=>{f&&(U.current=window.innerWidth,H.current=window.innerWidth)},[f]),Se.useEffect(()=>{if(!f)return;const S=()=>{const L=window.innerWidth;U.current=L,H.current=L,v||G.get()<-10&&G.set(-L),c||O.get()>10&&O.set(L)};return window.addEventListener("resize",S),window.addEventListener("orientationchange",S),()=>{window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S)}},[f,G,O,v,c]),Se.useEffect(()=>{if(!f){C(!1);return}v&&C(!0);const S=U.current||B.current||(typeof window<"u"?window.innerWidth:0),L=Ge(G,v?0:-S,{type:"spring",stiffness:400,damping:35,mass:.8});return y.current=L,()=>L.stop()},[v,f,G]),Se.useEffect(()=>{if(!f){N(!1);return}c&&N(!0);const S=H.current||B.current||(typeof window<"u"?window.innerWidth:0),L=Ge(O,c?0:S,{type:"spring",stiffness:400,damping:35,mass:.8});return b.current=L,()=>L.stop()},[f,c,O]),Se.useEffect(()=>{if(f)return G.on("change",S=>{const L=U.current||B.current,q=v||S>-L+.5;C(M=>M===q?M:q)})},[f,G,v]),Se.useEffect(()=>{if(f)return O.on("change",S=>{const L=H.current||B.current,q=c||S<L-.5;N(M=>M===q?M:q)})},[f,c,O]),Se.useEffect(()=>{f&&!i&&v&&T(!1)},[i,f,v,T]),Se.useEffect(()=>{if(!f){g.current=!1;return}g.current||(g.current=!0,T(!1),P(!1))},[f,T]),Se.useEffect(()=>{if(!f||n!=="chat"||v||c||a)return;let S=!1,L;return(M=>{L=window.setTimeout(()=>{if(S)return;const A=je.getState(),ce=ee.getState();ce.activeMainTab!=="chat"||ce.isSettingsDialogOpen||A.currentSessionId||A.newSessionDraft?.open||A.openNewSessionDraft({automatic:!0})},M)})(500),()=>{S=!0,L!==void 0&&window.clearTimeout(L)}},[n,f,a,v,c]),Se.useEffect(()=>{!f||!a||(T(!1),P(!1))},[f,a,T]),r.useEffect(()=>{ee.getState().isMobile!==f&&o(f)},[f,o]);const ne=r.useCallback(()=>{v&&T(!1),P(!c)},[v,c,T]);fr(re,{enabled:f,leftOpen:v,rightOpen:c,leftWidth:()=>U.current||B.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>H.current||B.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:S=>{const L=U.current||B.current||(typeof window<"u"?window.innerWidth:0);G.set(L*(S-1))},onRightProgress:S=>{const L=H.current||B.current||(typeof window<"u"?window.innerWidth:0);O.set(L*(1-S))},onLeftOpen:()=>{c&&P(!1),T(!0)},onLeftClose:()=>T(!1),onRightOpen:()=>{v&&T(!1),P(!0)},onRightClose:()=>P(!1),onDragStart:S=>{F.current=!0,S==="left"?(te.current=v,y.current?.stop(),d||C(!0)):(z.current=c,b.current?.stop(),j||N(!0))},onDragEnd:(S,L)=>{if(F.current=!1,S==="left"&&typeof L=="boolean"){const q=te.current;if(L===q){const M=U.current||B.current||(typeof window<"u"?window.innerWidth:0),A=Ge(G,q?0:-M,{type:"spring",stiffness:400,damping:35,mass:.8});y.current=A}}if(S==="right"&&typeof L=="boolean"){const q=z.current;if(L===q){const M=H.current||B.current||(typeof window<"u"?window.innerWidth:0),A=Ge(O,q?0:M,{type:"spring",stiffness:400,damping:35,mass:.8});b.current=A}}}});const R=r.useMemo(()=>{if(!f&&n!=="terminal"&&n!=="diagram"||f&&n==="git"&&(c||j))return null;switch(n){case"git":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(Qt,{isActive:!0})});case"diff":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(ia,{})});case"terminal":return e.jsx(ln,{onCloseView:()=>ee.getState().setActiveMainTab("chat")});case"files":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(la,{})});case"diagram":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(ca,{})});default:return null}},[n,f,j,c]),J=n==="chat";return e.jsxs(mr,{children:[e.jsx(gr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:ie("main-content-safe-area",f?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(na,{}),e.jsx(sa,{}),e.jsx(xr,{}),f?e.jsxs(aa,{value:{leftDrawerOpen:v,rightDrawerOpen:c,toggleLeftDrawer:()=>{const S=!v;c&&P(!1),T(S)},toggleRightDrawer:ne,leftDrawerX:G,rightDrawerX:O,leftDrawerWidth:U,rightDrawerWidth:H,setMobileLeftDrawerOpen:T,setRightSidebarOpen:P},children:[!a&&e.jsx(Et,{onToggleLeftDrawer:()=>{const S=!v;c&&P(!1),T(S)},onToggleRightDrawer:()=>{ne()},leftDrawerOpen:v,rightDrawerOpen:c}),e.jsx("div",{"data-page-scroll-lock":"true",className:ie("flex flex-1 overflow-hidden relative",a&&"hidden"),children:e.jsxs("main",{ref:re,className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:[e.jsx("div",{className:ie("absolute inset-0",!J&&"invisible"),children:e.jsx(Ne,{children:e.jsx(Tt,{active:J&&!a})})}),R&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ne,{children:R})}),e.jsx(Ne,{children:e.jsx(_t,{})}),e.jsx(Ot.div,{className:ie("absolute inset-0 z-20 bg-sidebar",!d&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:G},"aria-hidden":!v,children:e.jsx(Ne,{children:e.jsx(Dt,{mobileVariant:!0,isVisible:d})})}),e.jsx(Ot.div,{className:ie("absolute inset-0 z-20 bg-sidebar",!j&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:O},"aria-hidden":!c,children:e.jsx(Ne,{children:c||j?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Qt,{isActive:c})}):null})})]})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(Ne,{children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(da,{onClose:()=>m(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(wr,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(Es,{isOpen:t,isMobile:f,children:e.jsx(Dt,{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(Et,{}),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:ie("absolute inset-0",!J&&"invisible"),children:e.jsx(Ne,{children:e.jsx(Tt,{active:J&&!a})})}),R&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ne,{children:R})}),e.jsx(Ne,{children:e.jsx(_t,{})})]}),e.jsx(Vo,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Ne,{children:e.jsx(Qo,{})})})]})]})]}),w?e.jsx(r.Suspense,{fallback:null,children:e.jsx(ua,{open:a,onOpenChange:m})}):null]})]})]})},pa=()=>(os(),br(),e.jsxs(vr,{children:[e.jsx(as,{embeddedBackgroundWorkEnabled:!0}),e.jsx(is,{}),e.jsx(ha,{}),e.jsx(jr,{}),e.jsx(ls,{}),e.jsx(cs,{})]}));function fa({apis:t}){const n=t??sn(),[o,i]=r.useState(0);return r.useEffect(()=>nr(a=>{a.runtimeKey!==a.previousRuntimeKey&&(yr(a),i(m=>m+1))}),[]),r.useEffect(()=>{let a=!0,m=null,w=null;return rr().then(()=>{a&&(m=es(),w=ts())}),()=>{a=!1,m?.(),w?.()}},[o]),r.useEffect(()=>{n&&sr(n)},[n]),n?e.jsx(Ne,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(ns,{apis:n,children:e.jsx(rs,{children:e.jsx(ss,{children:e.jsx(pa,{})})},o)})})}):e.jsx(Ne,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const $n=document.getElementById("root");if(!$n)throw new Error("Root element not found");Wn.createRoot($n).render(e.jsx(Se.StrictMode,{children:e.jsx(ds,{children:e.jsx(us,{children:e.jsx(fa,{apis:sn()??void 0})})})}));
|
|
135
|
+
${oe}${se}`),ve.success("Preview console attached to chat")},[N,z,b,A,y,t]),[$,x]=r.useState("unknown"),_=r.useRef(0),V=r.useRef(0),le=r.useRef(""),fe=r.useRef(""),we=15e3;r.useEffect(()=>{if(!M){x("unknown"),le.current="",_.current=0,V.current=0;return}let E=!1,oe=null;le.current!==R&&(le.current=R,_.current=Date.now(),V.current=0);const se=Q=>{oe=setTimeout(()=>{E||a()},Q)};return x("unknown"),(async()=>{const W=await(async()=>{try{return await et(M,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(E)return;if(!W){x("unreachable"),se(5e3);return}const s=po(W.headers,fe.current===R);if(s!=="none"){if(ke.delete(R),s==="retry-registration")fe.current=R,f({status:"loading"}),w();else{const l=await W.json().catch(()=>({}));if(E)return;const I=typeof l?.error=="string"?l.error:`HTTP ${W.status}`;f({status:"error",message:I})}return}if(W.status!==502){fe.current="",x("reachable");return}const p=_.current||Date.now();if(Date.now()-p<we){x("starting"),V.current+=1;const l=V.current,I=Math.min(2e3,250*Math.pow(2,Math.min(4,l)));se(I);return}x("unreachable"),se(5e3)})(),()=>{E=!0,oe&&clearTimeout(oe)}},[R,M,i]);const k=O&&u.status==="ready"&&($==="unknown"||$==="starting"),Z=O&&u.status==="ready"&&$==="unreachable",ae=r.useCallback(E=>{if(!O||u.status!=="ready"||typeof window>"u")return;const oe=E.currentTarget.contentWindow;if(oe)try{const se=oe.location,Q=Dn(M);if(se.origin!==Q||se.pathname.startsWith(u.proxyBasePath))return;const W=`${u.proxyBasePath}${se.pathname}${se.search}${se.hash}`;oe.location.replace(W)}catch{}},[O,M,u]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:ce||t,children:ce||t||"No preview URL"}),e.jsx(me,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>a(),title:"Reload preview","aria-label":"Reload preview",disabled:!A,children:e.jsx(K,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{S&&tt(S)},title:"Open in browser","aria-label":"Open in browser",disabled:!S,children:e.jsx(K,{name:"external-link",className:"h-3.5 w-3.5"})}),O?e.jsx(me,{type:"button",size:"sm",variant:B?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>re(E=>!E),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!h,children:e.jsx(K,{name:"cursor",className:"h-3.5 w-3.5"})}):null,O?e.jsxs(me,{type:"button",size:"sm",variant:P?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>d(E=>!E),title:h?"Open preview console":"Waiting for preview console","aria-label":h?"Open preview console":"Waiting for preview console",disabled:!h&&N.length===0,children:[e.jsx(K,{name:"terminal-box",className:"h-3.5 w-3.5"}),pe>0?e.jsx("span",{className:"typography-micro text-status-error",children:pe}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[k?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."})]}):Z?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(me,{type:"button",size:"sm",variant:"outline",onClick:()=>a(),children:"Retry"})]}):A&&(!O||$==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:g,src:A,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:J},onLoad:ae,sandbox:O?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${A}:${i}`),B&&F?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:F.bounds.x,top:F.bounds.y,width:F.bounds.width,height:F.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:[F.tag,F.text?` · ${F.text}`:""]})}):null]}):ue?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):de?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[e.jsx("div",{children:"Could not start preview proxy."}),u.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:u.message}):null]}):e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Preview needs a valid http(s) URL."}),P?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(me,{type:"button",size:"xs",variant:"ghost",onClick:D,disabled:N.length===0,children:"Attach"}),e.jsx(me,{type:"button",size:"xs",variant:"ghost",onClick:he,disabled:N.length===0,children:"Copy"}),e.jsx(me,{type:"button",size:"xs",variant:"ghost",onClick:()=>T([]),disabled:N.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(me,{type:"button",size:"xs",variant:C===E?"secondary":"ghost",onClick:()=>j(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:N.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):xe.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):xe.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:ie("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]})]})},Pt=t=>t,pt=t=>{const n=Pt(t).type;return typeof n=="string"?n:""},mo=t=>{const n=Pt(t).tool;return typeof n=="string"?n:""},go=t=>{const n=Pt(t).text;return typeof n=="string"?n:""},xo=t=>{const n=pt(t);return n==="tool"?mo(t).trim().toLowerCase()||"tool":n||"unknown"},wo=t=>{if(t.length===0)return"";const n=[];for(const o of t){const i=xo(o);n.includes(i)||n.push(i)}return n.join(" + ")},yo=t=>t.replace(/\s+/g," ").trim(),bo=t=>{for(const o of t)if(pt(o)==="text"){const i=yo(go(o));if(i.length===0)continue;return i}const n=t.filter(o=>pt(o)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},vo=(t,n,o)=>`${o(t)} / ${o(n)}`,jo=t=>{if(t==="12h")return!0;if(t==="24h")return!1},So=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const o=jo(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}})},Co={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},Ze={user:0,assistant:0,tool:0,other:0},No=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,ct=t=>ut(t),ko=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},Ce=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,o)=>n+Ce(o),0):t&&typeof t=="object"?Object.values(t).reduce((n,o)=>n+Ce(o),0):0,Po=(t,n)=>{const o=t,i=typeof o.type=="string"?o.type:"";if(i==="reasoning")return{...Ze,assistant:Ce(o.text)+Ce(o.content)};const a=ko(o.text,o.content,o.value,o.source?.value,o.source?.text?.value);return i==="tool"||n==="tool"?{user:0,assistant:0,tool:Ce(o.input)+Ce(o.output)+Ce(o.error)+Ce(o.call?.input)+Ce(o.call?.output)+Ce(o.call?.error)+Ce(o.raw)+Math.round(Ce(o.metadata)*.25)+Math.round(Ce(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}},Gt=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),Ro=t=>{const n=Ve(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},Eo=(t,n)=>{if(t.length===0)return{...Ze};const o=t.reduce((i,a)=>{const m=Ro(a);let w={...Ze};for(const u of a.parts)w=Gt(w,Po(u,m));return Gt(i,w)},{...Ze});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)}},Ae=t=>t.toLocaleString("en-US"),To=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),_o=(t,n)=>!t||!Number.isFinite(t)?"-":Lr(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),Do=(t,n,o)=>{const i=t.find(m=>m.id===n),a=i?.models?.find(m=>m.id===o);return{providerName:i?.name||n||"-",modelName:a?.name||o||"-",contextLimit:typeof a?.limit?.context=="number"?a.limit.context:null}},Ao=()=>{const t=ee(d=>d.timeFormatPreference),[n,o]=r.useState({}),{value:i,show:a,clear:m}=Ar(null,2e3),w=je(d=>d.currentSessionId),u=je(d=>d.currentSessionDirectory),f=Mr(),g=un(w??""),v=Ie(d=>d.providers);r.useEffect(()=>{o(d=>Object.keys(d).length>0?{}:d),m()},[m,u,w]);const h=r.useCallback(async(d,C)=>{(await mt(C)).ok?a(d):m()},[m,a]),c=r.useMemo(()=>{const d=w?f.find(M=>M.id===w)??null:null,C=g.filter(M=>Ve(M.info).role==="assistant"),j=g.filter(M=>Ve(M.info).isUser);let N=null;for(let M=C.length-1;M>=0;M-=1){const A=C[M];if(ct(A).total>0){N=A;break}}const T=N?ct(N):Co,B=N?.info?.usage,re=on({input:T.input,cache:{read:T.cacheRead,write:T.cacheWrite}}),F=C.reduce((M,A)=>{const ce=No(A.info.cost);return M+ce},0),te=N?.info?.model??null,z=Do(v,te?.providerID||"",te?.modelID||""),y=z.contextLimit,b=B?an(B):T.total,G=y&&y>0?Math.min(999,b/y*100):0,U=[...g].reverse().find(M=>Ve(M.info).isUser&&typeof M.info.system=="string")?.info?.system||"",O=Eo(g,U),H=O.user,ne=O.assistant,R=O.tool,J=B?0:Math.max(0,T.input-H-ne-R),S=H+ne+R+J,L=g[0]?.info?.time?.created,q=g.length>0?g[g.length-1]?.info?.time?.created:null;return{sessionTitle:Sn(d),messagesCount:g.length,userMessagesCount:j.length,assistantMessagesCount:C.length,createdAt:d?.time?.created??L??null,lastActivityAt:q??d?.time?.created??null,providerModel:z,tokenBreakdown:T,usagePercent:G,cacheHitRate:re,totalAssistantCost:F,contextLimit:y,contextWindowTokens:b,hasUsage:B!==void 0,breakdown:{user:H,assistant:ne,tool:R,other:J},breakdownTotal:S}},[w,v,g,f]);if(!w)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 P=[{key:"user",label:"User",value:c.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:c.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool Calls",value:c.breakdown.tool,color:"var(--status-warning)"},...c.hasUsage?[]:[{key:"other",label:"Other",value:c.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:c.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:[c.providerModel.providerName," / ",c.providerModel.modelName]}),c.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:_o(c.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:[Ae(c.contextWindowTokens),c.contextLimit?` / ${Ae(c.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:c.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,c.usagePercent)}%`,backgroundColor:c.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:`${c.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:Ae(c.messagesCount)},{label:"User",value:Ae(c.userMessagesCount)},{label:"Assistant",value:Ae(c.assistantMessagesCount)},{label:"Cost",value:To(c.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:c.tokenBreakdown.input,format:"count"},{label:"Output",value:c.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:c.tokenBreakdown.reasoning,format:"count"},{label:"Cache Read",value:c.tokenBreakdown.cacheRead,format:"count"},{label:"Cache Write",value:c.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache Hit",value:c.cacheHitRate.hasInput?c.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)}%`:Ae(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:P.map(d=>d.value<=0||c.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${d.value/c.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:P.map(d=>{const C=c.breakdownTotal>0?d.value/c.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:[C.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:[...g].reverse().map(d=>{const j=Ve(d.info).role,N=j==="assistant",T=j==="user",B=n[d.info.id]===!0,re=i===d.info.id,F=d.info.time?.created??null,te=wo(d.parts),z=N?ct({info:d.info,parts:d.parts}):null,y=T?bo(d.parts):"",b=So(F,t),G=te||"—",U=z?vo(z.input,z.output,Ae):"",O=j||"unknown",H=te?`${O}: ${te}`:O,ne=B?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":B,onClick:()=>{o(R=>({...R,[d.info.id]:R[d.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:N?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[T?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",y]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:N?G:H}),N&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:U})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:b})]})}),B&&e.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:e.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[e.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:e.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:R=>{R.stopPropagation(),h(d.info.id,ne)},"aria-label":re?"Copied":"Copy JSON",title:re?"Copied":"Copy",children:re?e.jsx(K,{name:"check",className:"size-3.5"}):e.jsx(K,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Ir,{language:"json",code:ne,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},d.info.id)})})]})]})})},Mo=De(()=>Re(()=>import("./DiffView-DMvRLRN1.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,119])).then(t=>({default:t.DiffView}))),Io=De(()=>Re(()=>import("./FilesView-CNHu4RnC.js"),__vite__mapDeps([120,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,117,118,99,100,84,85,86,87,88,89,90,91,92,93,94,95,96,97,121,122,111,112,113,114,115,116,123,124,81,82,83,98,101,102,103,104,105,106,107,125,126,127,128])).then(t=>({default:t.FilesView}))),Lo=De(()=>Re(()=>import("./GitView-Cbepz-bR.js"),__vite__mapDeps([129,24,1,2,9,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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,114,115,116,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,117,118,130])).then(t=>({default:t.GitView}))),Oo=380,$o=1400,Ln=600,Wo=100,Fo=24,Yt=t=>Number.isFinite(t)?Math.min($o,Math.max(Oo,Math.round(t))):Ln,Bo=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},zo=(t,n)=>{if(!t)return"";const o=t.replace(/\\/g,"/"),i=n.replace(/\\/g,"/").replace(/\/+$/,"");return i&&o.startsWith(i+"/")?o.slice(i.length+1):o},On=(t,n=null)=>t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?jt(n).label:t==="terminal"?"Terminal":"Context",Uo=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},Ho=(t,n=null)=>{if(t.label)return t.label;if(t.mode==="file")return Uo(t.targetPath)||"Files";if(t.mode==="preview"){const o=t.targetPath;if(o)try{const i=new URL(o);return i.host||i.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":On(t.mode,n)},Jt=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(ft,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(hr,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(K,{name:jt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(K,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(K,{name:"donut-chart-fill",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(K,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(K,{name:"global",className:"h-3.5 w-3.5"})},Vo=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,Ko=()=>{const t=qe()??"",n=r.useMemo(()=>Pe(t),[t]),o=ee(l=>n?l.contextPanelByDirectory[n]:void 0),i=ee(l=>l.closeContextPanel),a=ee(l=>l.closeContextPanelTab),m=ee(l=>l.openContextPanelTab),w=ee(l=>l.toggleContextPanelExpanded),u=ee(l=>l.setContextPanelWidth),f=ee(l=>l.setActiveContextPanelTab),g=ee(l=>l.reorderContextPanelTabs),v=Te(l=>l.setSelectedPath),h=ee(l=>l.openContextPreview),c=ee(l=>l.contextEditorTreeVisible),P=ee(l=>l.toggleContextEditorTree),d=r.useMemo(()=>o?.tabs??[],[o?.tabs]),C=d.find(l=>l.id===o?.activeTabId)??d[d.length-1]??null,j=!!(o?.isOpen&&C),N=!!(j&&o?.expanded),[T,B]=r.useState(null),re=o?.width,F=$r,te=T??(typeof window<"u"?window.innerWidth:Ln*2),z=Yt(re??Math.round(F*te)),y=hn(n||null),[b,G]=r.useState(!1),[U,O]=r.useState(null),[H,ne]=r.useState(null),[R,J]=r.useState(null),S=r.useRef(0),L=r.useRef(z),q=r.useRef(null),M=r.useRef(null),A=r.useRef(null),ce=r.useRef(!1);r.useLayoutEffect(()=>{const l=A.current?.parentElement;if(!l||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>{B(l.clientWidth||null)});return I.observe(l),B(l.clientWidth||null),()=>I.disconnect()},[]),r.useEffect(()=>{if(!j||ce.current){ce.current=j;return}const l=window.requestAnimationFrame(()=>{A.current?.focus({preventScroll:!0})});return ce.current=!0,()=>window.cancelAnimationFrame(l)},[j]);const ue=r.useRef(null),de=r.useRef(null),ye=r.useCallback(()=>{de.current=null;const l=A.current,I=q.current;!l||I===null||l.style.setProperty("--oc-context-panel-width",`${I}px`)},[]);r.useEffect(()=>()=>{de.current!==null&&clearTimeout(de.current)},[]);const pe=r.useCallback(l=>{const I=Yt(l),Y=ue.current;return Y===null?I:Math.min(I,Math.max(1,Y))},[]),xe=r.useCallback(l=>{!j||N||!n||(M.current=l.pointerId,G(!0),S.current=l.clientX,L.current=z,q.current=z,ue.current=Bo(A.current),document.documentElement.style.cursor="col-resize",l.preventDefault())},[n,N,j,z]),he=r.useCallback(()=>{const l=pe(q.current??z);q.current=null,ue.current=null,de.current!==null&&(clearTimeout(de.current),de.current=null),document.documentElement.style.cursor="",n&&u(n,l),G(!1),M.current=null},[pe,n,u,z]);r.useEffect(()=>{if(!b)return;const l=ge=>{if(M.current!==ge.pointerId)return;const be=S.current-ge.clientX,Ee=pe(L.current+be);q.current!==Ee&&(q.current=Ee,de.current===null&&(de.current=setTimeout(ye,Wo)))},I=ge=>{M.current===ge.pointerId&&he()},Y=()=>{he()};return window.addEventListener("pointermove",l),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",I),window.addEventListener("blur",Y),()=>{window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",I),window.removeEventListener("blur",Y)}},[ye,pe,he,b]),r.useEffect(()=>{b||(q.current=null,document.documentElement.style.cursor="")},[b]);const D=r.useCallback(()=>{n&&i(n)},[i,n]),$=r.useCallback(()=>{n&&w(n)},[n,w]),x=r.useCallback(l=>{l.key==="Escape"&&(Or(l.target)||(l.preventDefault(),l.stopPropagation(),D()))},[D]);r.useEffect(()=>{if(!(!n||!C)&&C.mode==="file"&&C.targetPath){v(n,C.targetPath,{allowOutsideRoot:!0});return}},[C,n,v]);const _=r.useCallback(l=>{!n||C?.mode!=="diff"||m(n,{mode:"diff",targetPath:C.targetPath,stagedDiff:l==="staged",diffScope:l})},[C,n,m]),V=C?.mode==="file"||C?.mode==="preview",le=r.useMemo(()=>C?d.filter(l=>l.mode===C.mode):[],[C,d]),fe=r.useMemo(()=>le.map(l=>{const I=Ho(l,y),Y=Vo(I,Fo),ge=zo(l.targetPath,t);return{id:l.id,label:Y,icon:Jt(l,y),title:ge?`${I}: ${ge}`:I,closeLabel:`Close ${Y} tab`}}),[le,t,y]),we=C?.mode==="context"?e.jsx(Ao,{}):C?.mode==="git"?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Lo,{isActive:j,gitHeaderSlot:C?.mode==="git"?H:null})}):C?.mode==="preview"?e.jsx(fo,{rawUrl:C.targetPath??"",onNavigate:l=>h(t,l)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(K,{name:"global",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"Preview"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Use Project Actions or a terminal Preview button to open a preview."})]}),k=r.useMemo(()=>d.filter(l=>l.mode==="browser"),[d]),Z=r.useMemo(()=>d.filter(l=>l.mode==="diff"),[d]),ae=r.useMemo(()=>d.some(l=>l.mode==="terminal"),[d]),E=r.useMemo(()=>d.some(l=>l.mode==="file"),[d]),oe=r.useMemo(()=>d.some(l=>l.mode==="file"&&l.targetPath),[d]),se=C?.mode==="file",Q=C?.mode==="terminal",W=C?.mode==="git",s=C?.mode==="diff",p=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[V?e.jsx(Es,{items:fe,activeId:C?.id??null,onSelect:l=>{n&&f(n,l)},onClose:l=>{n&&a(n,l)},onReorder:(l,I)=>{n&&g(n,l,I)},layoutMode:"scrollable",variant:"default"}):Q?e.jsx("div",{ref:l=>{O(l)},className:"flex min-w-0 flex-1 items-center px-1"}):W?e.jsx("div",{ref:l=>{ne(l)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):s?e.jsx("div",{ref:l=>{J(l)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[C?Jt(C,y):null,e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:C?On(C.mode,y):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[se?e.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:P,className:"h-7 w-7 p-0",title:"Toggle file tree","aria-label":"Toggle file tree","aria-pressed":c,children:e.jsx(K,{name:"layout-right",className:"h-3.5 w-3.5"})}):null,e.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:$,className:"h-7 w-7 p-0",title:N?"Collapse panel":"Expand panel","aria-label":N?"Collapse panel":"Expand panel",children:N?e.jsx(K,{name:"fullscreen-exit",className:"h-3.5 w-3.5"}):e.jsx(K,{name:"fullscreen",className:"h-3.5 w-3.5"})}),e.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:D,className:"h-7 w-7 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(K,{name:"close",className:"h-3.5 w-3.5"})})]})]}),X=j?N?{"--oc-context-panel-width":T!==null?`${T}px`:"100%",width:T!==null?`${T}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${z}px`}:{"--oc-context-panel-width":`${z}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:A,"data-context-panel":"true",tabIndex:-1,inert:!j||void 0,className:ie("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",!j&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:x,style:X,children:[j&&!N&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),j&&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:ie("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",b&&"bg-[var(--interactive-border)]"),onPointerDown:xe,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:ie("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]",!j&&"pointer-events-none select-none opacity-0"),style:{width:N?T!==null?`${T}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!j,children:[p,e.jsxs("div",{className:ie("relative min-h-0 flex-1 overflow-hidden",b&&"pointer-events-none"),children:[E?e.jsxs("div",{className:ie("absolute inset-0 flex",se?"flex":"hidden"),children:[e.jsx("div",{className:"h-full min-w-0 flex-1",children:oe?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Io,{mode:"editor-only",isVisible:j&&se})}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(K,{name:"file-code",className:"h-12 w-12 text-muted-foreground/50"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"No file open"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Pick a file from the tree to start editing."})]})}),e.jsx(co,{visible:c})]}):null,k.map(l=>e.jsx("div",{className:ie("absolute inset-0",C?.id!==l.id&&"hidden"),children:e.jsx(Zs,{initialUrl:l.targetPath??"",directory:n,tabID:l.id})},l.id)),j?Z.filter(l=>C?.id===l.id).map(l=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(Mo,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:l.diffScope??(l.stagedDiff?"staged":"working"),onDiffScopeChange:_,targetFilePath:l.targetPath,flushContent:!0,toolbarSlot:s?R:null})})},l.id)):null,ae?e.jsx("div",{className:ie("absolute inset-0",C?.mode==="terminal"?"block":"hidden"),children:e.jsx(ln,{visible:j&&C?.mode==="terminal",terminalHeaderSlot:Q?U:null})}):null,j&&!se&&C?.mode!=="browser"&&C?.mode!=="diff"&&C?.mode!=="terminal"?we:null]})]})]})},Xo=150,qo=500,Go=[],Me=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),Ye=(t,n)=>{if(!t||typeof t!="object")return;const o=t[n];return typeof o=="number"&&Number.isFinite(o)?o:void 0},Yo=t=>t>99?"99+":String(t),Jo=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",Qo=({surface:t,isActive:n,showActivityDot:o,label:i,description:a,badgeCount:m,badgeAriaLabel:w,badgeDescription:u,orderNumber:f,showOrderNumber:g,onSelect:v,chartPercentage:h,chartDetails:c})=>{const{attributes:P,listeners:d,setNodeRef:C,transform:j,transition:N,isDragging:T}=vn({id:t.id}),B=m!=null&&m>0?Yo(m):null;return e.jsx("div",{ref:C,style:{transform:jn.Translate.toString(j),transition:N},className:ie("relative",T&&"z-10 opacity-70"),children:e.jsxs(Le,{delayDuration:Xo,children:[e.jsx(Oe,{asChild:!0,children:e.jsxs("button",{type:"button",...P,...d,onClick:()=>v(t),"aria-label":w??i,"aria-pressed":n,className:ie("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"text-primary":"text-muted-foreground hover:text-foreground"),children:[t.id==="context"&&typeof h=="number"?e.jsx(Mt,{percentage:h,className:"size-[18px] -rotate-90"}):e.jsx(K,{name:t.icon,className:"h-[18px] w-[18px]"}),g&&f!=null?e.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-muted px-1 text-[0.625rem] font-medium leading-none text-muted-foreground",children:f===10?"0":f}):B?e.jsx("span",{"aria-hidden":"true",className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[0.625rem] font-semibold leading-none",style:{backgroundColor:"var(--status-info-background)",color:"var(--status-info)"},children:B}):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($e,{side:"left",sideOffset:8,className:t.id==="context"&&c?"p-0 border-0 bg-transparent shadow-none":void 0,children:t.id==="context"&&c?e.jsx("div",{className:"w-[300px] overflow-hidden rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[e.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:e.jsx(Mt,{percentage:c.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:i}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:c.hasData?e.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[e.jsxs("span",{className:ie("font-semibold",Jo(c.percentage)),children:[c.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${Me(c.totalTokens)}/${Me(c.contextLimit)}`})]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:"No data yet"})})]}),c.hasData?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.contextLimit)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.outputLimit)})]}),typeof c.cacheRead=="number"&&typeof c.cacheWrite=="number"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.cacheRead)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Me(c.cacheWrite)})]})]}):null,typeof c.cacheHitPercent=="number"?e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache hit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:`${c.cacheHitPercent.toFixed(1)}%`})]}):null]}):e.jsx("div",{className:"px-2.5 py-2 typography-micro text-muted-foreground",children:a})]})}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:i}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:a}),u?e.jsx("span",{className:"typography-micro text-muted-foreground",children:u}):null]})})]})})},Zo=()=>{const t=qe(),n=t?Kn(t):"",o=ee(x=>n?x.contextPanelByDirectory[n]:void 0),i=ee(x=>x.contextRailOrder),a=ee(x=>x.setContextRailOrder),m=ee(x=>x.openContextSurface),w=ee(x=>x.shortcutOverrides),{screenWidth:u}=rt(),{git:f}=gt(),g=dn(n||null),v=hn(n||null),h=pn(x=>x.ensureStatus);r.useEffect(()=>{n&&h(n,f)},[n,h,f]);const c=r.useMemo(()=>Xn("switch_context_surface",w),[w]),[P,d]=r.useState(!1);r.useEffect(()=>{const x=new Set;let _=null,V=!1;const le=ae=>ae.length===1&&ae>="0"&&ae<="9",fe=()=>{Rt(c,x)?!V&&_===null&&(_=setTimeout(()=>d(!0),qo)):(V=!1,_!==null&&(clearTimeout(_),_=null),d(!1))},we=ae=>{if(x.add(ae.key.toLowerCase()),le(ae.key)&&Rt(c,x)){V=!0,_!==null&&(clearTimeout(_),_=null),d(!1);return}fe()},k=ae=>{x.delete(ae.key.toLowerCase()),fe()},Z=()=>{x.clear(),V=!1,_!==null&&(clearTimeout(_),_=null),d(!1)};return window.addEventListener("keydown",we,!0),window.addEventListener("keyup",k,!0),window.addEventListener("blur",Z),()=>{window.removeEventListener("keydown",we,!0),window.removeEventListener("keyup",k,!0),window.removeEventListener("blur",Z),_!==null&&clearTimeout(_)}},[c]);const C=xn(ht(vs,{activationConstraint:{distance:8}}),ht(bs,{activationConstraint:{delay:200,tolerance:6}})),j=o?.tabs??Go,N=j.find(x=>x.id===o?.activeTabId)??null,T=o?.isOpen?N?.mode??null:null,B=g?.files.length??0,re=je(x=>x.currentSessionId),F=je(x=>!!x.newSessionDraft?.open),te=Ie(x=>x.providers),z=Ie(x=>x.currentProviderId),y=Ie(x=>x.currentModelId),b=Ie(x=>x.getCurrentModel()),G=Ie(x=>x.getModelMetadata);Ie(x=>x.modelsMetadata.size);const U=Wr(r.useCallback(x=>re?x.sessionModelSelections.get(re)??null:null,[re])),O=un(re??""),H=r.useMemo(()=>{for(let x=O.length-1;x>=0;x-=1){const _=O[x];if(_?.info.role==="assistant")try{if(ut(_).total>0)return _}catch{continue}}return null},[O]),R=r.useMemo(()=>{for(let x=O.length-1;x>=0;x-=1){const _=O[x]?.info;if(_.role!=="user")continue;const V=_.model,le=V?.providerID??V?.providerId,fe=V?.modelID??V?.modelId;if(typeof le=="string"&&le.trim()&&typeof fe=="string"&&fe.trim())return{providerID:le,modelID:fe}}return null},[O])??(()=>{const x=H?.info.model,_=x?.providerID??x?.providerId,V=x?.modelID??x?.modelId;return _&&V?{providerID:_,modelID:V}:null})()??(U?{providerID:U.providerId,modelID:U.modelId}:null)??(z&&y?{providerID:z,modelID:y}:null),S=(R?te.find(x=>x.id===R.providerID):void 0)?.models.find(x=>x.id===R?.modelID),L=R?G(R.providerID,R.modelID):void 0,q=Ye(S?.limit,"context")??L?.limit?.context??Ye(b?.limit,"context")??0,M=Ye(S?.limit,"output")??L?.limit?.output??Ye(b?.limit,"output")??0,A=H?(()=>{try{return ut(H)}catch{return null}})():null,ce=H?.info?.usage,ue=ce?an(ce):A?.total??0,de=!F&&ue>0&&q>0?Math.min(ue/q*100,999):0,ye=de,pe=A?on({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}):null,xe=pe?.hasInput?pe.percent:null,he=r.useMemo(()=>{const x=!!H&&ue>0&&q>0;return{percentage:de,totalTokens:ue,contextLimit:q,outputLimit:M,cacheRead:A?.cacheRead??null,cacheWrite:A?.cacheWrite??null,cacheHitPercent:xe,hasData:x}},[A,xe,q,H,M,de,ue]),D=r.useMemo(()=>Fr({railOrder:i,tabs:j}),[i,u,j]),$=r.useCallback(x=>{const{active:_,over:V}=x;if(!V||_.id===V.id)return;const le=Br(ee.getState().contextRailOrder).map(k=>k.id),fe=le.indexOf(_.id),we=le.indexOf(V.id);fe===-1||we===-1||a(Ss(le,fe,we))},[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(wn,{sensors:C,collisionDetection:yn,onDragEnd:$,children:e.jsx(bn,{items:D.map(x=>x.id),strategy:Cs,children:D.map((x,_)=>{const V=x.id==="git"?jt(v):null,le=V?{...x,...V}:x,fe=le.label,we=x.id==="git"&&v===!0?B:0,k=we>0?we:null,Z=x.id==="context";return e.jsx(Qo,{surface:le,isActive:T===x.mode,showActivityDot:!1,label:fe,description:le.description,badgeCount:k,badgeAriaLabel:k!==null?k===1?`${fe}, ${k} changed file`:`${fe}, ${k} changed files`:null,badgeDescription:k!==null?k===1?`${k} changed file`:`${k} changed files`:null,chartPercentage:Z?ye:void 0,chartDetails:Z?he:void 0,orderNumber:_+1,showOrderNumber:P,onSelect:ae=>m(n,ae.mode)},x.id)})})})}):null},ea=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),ta=(t,n,o,i)=>!o||i!==o||t.length===0?[]:He(t,n,a=>a.name,{limit:10,threshold:.4}),na=new Set,dt=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),o=n.startsWith("//");let i=n.replace(/\/+/g,"/");o&&!i.startsWith("//")&&(i=`/${i}`);const a=i==="/",m=/^[A-Za-z]:\/$/.test(i);return!a&&!m&&(i=i.replace(/\/+$/,"")),i},ra=()=>{const t=ee(s=>s.isCommandPaletteOpen),n=ee(s=>s.setCommandPaletteOpen),o=ee(s=>s.setActiveMainTab),i=ee(s=>s.setSettingsDialogOpen),a=ee(s=>s.setSettingsPage),m=ee(s=>s.setSessionSwitcherOpen),w=ee(s=>s.toggleSidebar),u=ee(s=>s.openContextOverview),f=ee(s=>s.openContextSurface),g=ee(s=>s.openContextFile),v=ee(s=>s.shortcutOverrides),h=je(s=>s.openNewSessionDraft),c=je(s=>s.setCurrentSession),P=zr({archived:!1}),d=Ur(r.useCallback(s=>t?s.ids:na,[t])),C=Hr(r.useCallback(s=>t?s.rankById:Vr,[t])),j=qn(s=>s.currentDirectory),N=It(s=>s.getActiveProject()),T=It(s=>s.projects),B=qe(),re=Gn(s=>s.searchFiles),{files:F,git:te}=gt(),z=pn(s=>s.ensureStatus),{isMobile:y}=rt(),b=r.useMemo(()=>B?dt(B):null,[B]),[G,U]=r.useState(""),H=Kr(G,200).trim(),ne=G.trim();r.useEffect(()=>{t&&U("")},[t]),r.useEffect(()=>{if(!t||!te)return;const s=setTimeout(()=>{const p=new Set;for(const X of P){const l=ot(X);!l||p.has(l)||(p.add(l),z(l,te))}},0);return()=>clearTimeout(s)},[t,P,te,z]);const R=r.useCallback(()=>n(!1),[n]),J=r.useCallback(s=>()=>{R(),s()},[R]),S=r.useMemo(()=>{const s=[{id:"new-session",title:"New Session",icon:e.jsx(K,{name:"add",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New Session",onSelect:J(()=>{o("chat"),m(!1),h()})},{id:"add-project",title:"Add Project",icon:e.jsx(K,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add Project",onSelect:J(()=>{Xr.requestDirectoryDialog()})},{id:"toggle-sidebar",title:y?"Show Session Switcher":"Toggle Sidebar",icon:e.jsx(K,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:y?"Show Session Switcher":"Toggle Sidebar",onSelect:J(()=>{if(y){const{isSessionSwitcherOpen:p}=ee.getState();m(!p)}else w()})},{id:"toggle-terminal",title:"Toggle Terminal",icon:e.jsx(K,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle Terminal",onSelect:J(()=>{j&&f(j,"terminal")})},{id:"context-usage",title:"Show Context Usage",icon:e.jsx(K,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show Context Usage",onSelect:J(()=>{j&&u(j)})},{id:"open-settings",title:"Open Settings...",icon:e.jsx(K,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open Settings...",onSelect:J(()=>i(!0))}];return Yn()&&s.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat Window",icon:e.jsx(K,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat Window",onSelect:J(()=>{Zt("desktop_open_draft_mini_chat_window",{directory:dt(j||N?.path||""),projectId:N?.id??null}).catch(p=>{console.warn("[command-palette] failed to open draft mini chat window",p)})})}),s},[J,y,o,m,h,w,f,j,u,i,N?.id,N?.path]),L=r.useMemo(()=>{const s=Jn();return{isWeb:!s&&Qn(),isDesktop:s,isMobile:y}},[y]),q=r.useMemo(()=>pr.filter(s=>s.slug!=="home").filter(s=>s.isAvailable?s.isAvailable(L):!0).map(s=>{const p=fr(s.slug)??"settings-3",X=(s.keywords??[]).join(" ");return{id:`settings:${s.slug}`,title:s.title,icon:e.jsx(K,{name:p,className:"mr-2 h-4 w-4"}),searchText:`${s.title} ${s.group} ${X}`,onSelect:J(()=>{a(s.slug),i(!0)})}}),[L,J,a,i]),M=r.useMemo(()=>qr(P,d,C),[P,d,C]),A=Gr(),ce=r.useCallback((s,p)=>p&&A.get(p)?.trim()||null,[A]),[ue,de]=r.useState([]),[ye,pe]=r.useState(""),xe=ea(b,H);r.useEffect(()=>{if(!t){de([]),pe("");return}if(!xe){de([]),pe("");return}if(!b){de([]),pe("");return}let s=!1;return re(b,H,10,{type:"file"}).then(p=>{s||(de(p.map(X=>({path:dt(X.path),name:X.name,relativePath:X.relativePath}))),pe(xe))}).catch(()=>{s||(de([]),pe(xe))}),()=>{s=!0}},[t,b,H,xe,re]);const he=ne.length>0,D=r.useMemo(()=>he?He(S,ne,s=>s.searchText,{limit:7,noFuzzy:!0}):S.map(s=>({item:s,score:0})),[S,ne,he]),$=r.useMemo(()=>he?He(q,ne,s=>s.searchText,{limit:7,noFuzzy:!0}):[],[q,ne,he]),x=r.useMemo(()=>he?He(M,ne,s=>s.title||"",{limit:7,threshold:.2}):M.slice(0,5).map(s=>({item:s,score:0})),[M,ne,he]),_=r.useMemo(()=>t?ta(ue,H,xe,ye):[],[t,ue,ye,xe,H]),V=t&&xe.length>0&&ye!==xe,le=r.useMemo(()=>{if(!he)return[];const s=T.map(p=>({...p,displayName:p.label||p.path.split("/").pop()||p.path,searchText:`${p.label||""} ${p.path}`}));return He(s,ne,p=>p.searchText,{limit:7,threshold:.4})},[T,ne,he]),fe=D.map(s=>s.item),we=$.map(s=>s.item),k=x.map(s=>s.item),Z=he?_.map(s=>s.item):[],ae=he?le.map(s=>s.item):[],E=r.useMemo(()=>{if(!he)return["commands","sessions"];const s=X=>X.length?X[0].score:1/0,p=[{key:"commands",score:s(D)},{key:"settings",score:s($)},{key:"sessions",score:s(x)},{key:"files",score:s(_)},{key:"projects",score:s(le)}];return p.sort((X,l)=>X.score-l.score),p.map(X=>X.key)},[he,D,$,x,_,le]),oe=r.useCallback(s=>{R(),c(s.id,ot(s))},[R,c]),se=r.useCallback(async s=>{if(!b)return;const p=await fn(F,s,{directory:b});if(!p.ok){ve.error(mn(p.reason));return}g(b,s),R()},[b,F,g,R]),Q=r.useCallback((s,p)=>{R(),h({selectedProjectId:s,directoryOverride:p})},[R,h]),W=r.useCallback(s=>nn(rn(s,v)),[v]);return e.jsxs(xt,{open:t,onOpenChange:n,children:[e.jsxs(yt,{className:"sr-only",children:[e.jsx(bt,{children:"Command Palette"}),e.jsx(vt,{children:"Search files, sessions, and commands."})]}),e.jsx(wt,{className:"overflow-hidden p-0",showCloseButton:!0,children:e.jsxs(Yr,{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(Jr,{value:G,onValueChange:U,placeholder:"Search files, sessions, commands..."}),e.jsxs(Qr,{children:[e.jsx(Zr,{children:"No results found."}),E.map(s=>s==="commands"&&fe.length>0?e.jsx(ze,{children:fe.map(p=>e.jsxs(Ue,{value:p.id,onSelect:p.onSelect,children:[p.icon,e.jsx("span",{children:p.title}),p.shortcutId?e.jsx(es,{children:W(p.shortcutId)}):null]},p.id))},"commands"):s==="settings"&&we.length>0?e.jsx(ze,{children:we.map(p=>e.jsxs(Ue,{value:p.id,onSelect:p.onSelect,children:[p.icon,e.jsx("span",{children:p.title})]},p.id))},"settings"):s==="sessions"&&k.length>0?e.jsx(ze,{children:k.map(p=>{const X=Sn(p),l=ot(p),I=ce(p.id,l);return e.jsxs(Ue,{value:`session:${p.id}`,onSelect:()=>oe(p),children:[e.jsx(K,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:X}),I?e.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-muted-foreground typography-meta",children:[e.jsx(K,{name:"git-branch",className:"h-3 w-3"}),e.jsx("span",{className:"truncate max-w-[160px]",children:I})]}):null]},p.id)})},"sessions"):s==="files"&&Z.length>0?e.jsx(ze,{children:Z.map(p=>{const X=Zn(p.relativePath||p.name,{maxLength:80});return e.jsxs(Ue,{value:`file:${p.path}`,onSelect:()=>{se(p.path)},children:[e.jsx(ft,{filePath:p.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":p.relativePath,children:X})]},`file:${p.path}`)})},"files"):s==="projects"&&ae.length>0?e.jsx(ze,{children:ae.map(p=>{const X=p.displayName;return e.jsxs(Ue,{value:`project:${p.id}`,onSelect:()=>Q(p.id,p.path),children:[e.jsx(K,{name:"folder",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:X}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:p.path})]},`project:${p.id}`)})},"projects"):null),V?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]})})]})},sa=(t,n,o)=>tr(t)?nn(rn(t,o)):n,oa=()=>{const t=ee(m=>m.isHelpDialogOpen),n=ee(m=>m.setHelpDialogOpen),o=ee(m=>m.shortcutOverrides),i=er(),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 + ${i} + N`],descriptionKey:"New Window (desktop only)",icon:"window"}]},{categoryKey:"Session Management",items:[{id:"new_chat",descriptionKey:"Create New Session",icon:"add",keys:""},{id:"focus_input",descriptionKey:"Focus Chat Input",icon:"text",keys:""},{id:"cycle_session_folder",descriptionKey:"Cycle session folder",icon:"folder-open",keys:""},{id:"cycle_draft_folder",descriptionKey:"Cycle draft folder",icon:"folder-3",keys:""},{id:"open_timeline_dialog",descriptionKey:"Open conversation timeline",icon:"history",keys:""},{id:"abort_run",descriptionKey:"Abort active run (double press)",icon:"close-circle",keys:""}]},{categoryKey:"Panels",items:[{id:"open_right_sidebar",descriptionKey:"Open right sidebar",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{keys:[`${i} + 1...0`],descriptionKey:"Switch Context Panel Surface (number key)",icon:"layout-right"}]},{categoryKey:"Interface",items:[{id:"cycle_theme",descriptionKey:"Cycle Theme (Light → Dark → System)",icon:"palette",keys:""},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"Open Settings",icon:"settings-3",keys:""}]}];return e.jsx(xt,{open:t,onOpenChange:n,children:e.jsxs(wt,{className:"w-[92vw] max-w-[1120px] h-[84vh] max-h-[900px] flex flex-col overflow-hidden",children:[e.jsxs(yt,{children:[e.jsxs(bt,{className:"flex items-center gap-2",children:[e.jsx(K,{name:"command",className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(vt,{children:"Use these keyboard shortcuts to navigate PiChamber efficiently"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:e.jsx("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-x-10",children:a.map(m=>e.jsxs("div",{className:"min-w-0 break-inside-avoid",children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:m.categoryKey}),e.jsx("div",{className:"space-y-1",children:m.items.map(w=>{const u=w.id?sa(w.id,Array.isArray(w.keys)?w.keys[0]:w.keys,o):Array.isArray(w.keys)?w.keys:w.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:[w.icon&&e.jsx(K,{name:w.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:w.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(u)?u:[u]).map((f,g)=>e.jsxs(r.Fragment,{children:[g>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:f})]},`${f}-${g}`))})]},w.id||w.descriptionKey)})})]},m.categoryKey))})})]})})},aa=r.createContext(null),ia=({children:t,value:n})=>e.jsx(aa.Provider,{value:n,children:t}),Qt=De(()=>Re(()=>import("./GitView-Cbepz-bR.js"),__vite__mapDeps([129,24,1,2,9,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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,114,115,116,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,117,118,130])).then(t=>({default:t.GitView}))),la=De(()=>Re(()=>import("./DiffView-DMvRLRN1.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,119])).then(t=>({default:t.DiffView}))),ca=De(()=>Re(()=>import("./FilesView-CNHu4RnC.js"),__vite__mapDeps([120,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,117,118,99,100,84,85,86,87,88,89,90,91,92,93,94,95,96,97,121,122,111,112,113,114,115,116,123,124,81,82,83,98,101,102,103,104,105,106,107,125,126,127,128])).then(t=>({default:t.FilesView}))),da=De(()=>Re(()=>import("./DiagramView-BvrCkm_z.js"),__vite__mapDeps([131,1,2,9,3,4,5,6,7,8,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,121,122])).then(t=>({default:t.DiagramView}))),ua=De(()=>Re(()=>import("./SettingsView-hyAGp836.js").then(t=>t.a),__vite__mapDeps([132,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,114,115,116,133,134,130])).then(t=>({default:t.SettingsView}))),ha=De(()=>Re(()=>import("./SettingsWindow-BfPUzBbq.js"),__vite__mapDeps([135,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,132,111,112,113,114,115,116,133,134,130])).then(t=>({default:t.SettingsWindow}))),pa=()=>{const t=ee(S=>S.isSidebarOpen),n=ee(S=>S.activeMainTab),o=ee(S=>S.setIsMobile),i=ee(S=>S.isSessionSwitcherOpen),a=ee(S=>S.isSettingsDialogOpen),m=ee(S=>S.setSettingsDialogOpen),[w,u]=r.useState(!1);r.useEffect(()=>{a&&u(!0)},[a]),r.useEffect(()=>{const S=()=>ee.getState().closeMainSurfaces(),L=je.subscribe((M,A)=>{const ce=!!M.currentSessionId&&M.currentSessionId!==A.currentSessionId,ue=!!M.newSessionDraft?.open&&M.newSessionDraft!==A.newSessionDraft;(ce||ue)&&S()}),q=ee.subscribe((M,A)=>{M.activeMainTab!==A.activeMainTab&&S()});return()=>{L(),q()}},[]);const{isMobile:f}=rt(),g=r.useRef(!1),[v,h]=r.useState(!1),[c,P]=r.useState(!1),[d,C]=r.useState(!1),[j,N]=r.useState(!1),T=r.useCallback(S=>{h(S),ee.getState().setSessionSwitcherOpen(S)},[]),B=r.useRef(typeof window>"u"?0:window.innerWidth),re=r.useRef(null),F=r.useRef(!1),te=r.useRef(!1),z=r.useRef(!1),y=r.useRef(null),b=r.useRef(null),G=Lt(-B.current),U=Se.useRef(0),O=Lt(B.current),H=Se.useRef(0);Se.useEffect(()=>{f&&(U.current=window.innerWidth,H.current=window.innerWidth)},[f]),Se.useEffect(()=>{if(!f)return;const S=()=>{const L=window.innerWidth;U.current=L,H.current=L,v||G.get()<-10&&G.set(-L),c||O.get()>10&&O.set(L)};return window.addEventListener("resize",S),window.addEventListener("orientationchange",S),()=>{window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S)}},[f,G,O,v,c]),Se.useEffect(()=>{if(!f){C(!1);return}v&&C(!0);const S=U.current||B.current||(typeof window<"u"?window.innerWidth:0),L=Ge(G,v?0:-S,{type:"spring",stiffness:400,damping:35,mass:.8});return y.current=L,()=>L.stop()},[v,f,G]),Se.useEffect(()=>{if(!f){N(!1);return}c&&N(!0);const S=H.current||B.current||(typeof window<"u"?window.innerWidth:0),L=Ge(O,c?0:S,{type:"spring",stiffness:400,damping:35,mass:.8});return b.current=L,()=>L.stop()},[f,c,O]),Se.useEffect(()=>{if(f)return G.on("change",S=>{const L=U.current||B.current,q=v||S>-L+.5;C(M=>M===q?M:q)})},[f,G,v]),Se.useEffect(()=>{if(f)return O.on("change",S=>{const L=H.current||B.current,q=c||S<L-.5;N(M=>M===q?M:q)})},[f,c,O]),Se.useEffect(()=>{f&&!i&&v&&T(!1)},[i,f,v,T]),Se.useEffect(()=>{if(!f){g.current=!1;return}g.current||(g.current=!0,T(!1),P(!1))},[f,T]),Se.useEffect(()=>{if(!f||n!=="chat"||v||c||a)return;let S=!1,L;return(M=>{L=window.setTimeout(()=>{if(S)return;const A=je.getState(),ce=ee.getState();ce.activeMainTab!=="chat"||ce.isSettingsDialogOpen||A.currentSessionId||A.newSessionDraft?.open||A.openNewSessionDraft({automatic:!0})},M)})(500),()=>{S=!0,L!==void 0&&window.clearTimeout(L)}},[n,f,a,v,c]),Se.useEffect(()=>{!f||!a||(T(!1),P(!1))},[f,a,T]),r.useEffect(()=>{ee.getState().isMobile!==f&&o(f)},[f,o]);const ne=r.useCallback(()=>{v&&T(!1),P(!c)},[v,c,T]);mr(re,{enabled:f,leftOpen:v,rightOpen:c,leftWidth:()=>U.current||B.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>H.current||B.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:S=>{const L=U.current||B.current||(typeof window<"u"?window.innerWidth:0);G.set(L*(S-1))},onRightProgress:S=>{const L=H.current||B.current||(typeof window<"u"?window.innerWidth:0);O.set(L*(1-S))},onLeftOpen:()=>{c&&P(!1),T(!0)},onLeftClose:()=>T(!1),onRightOpen:()=>{v&&T(!1),P(!0)},onRightClose:()=>P(!1),onDragStart:S=>{F.current=!0,S==="left"?(te.current=v,y.current?.stop(),d||C(!0)):(z.current=c,b.current?.stop(),j||N(!0))},onDragEnd:(S,L)=>{if(F.current=!1,S==="left"&&typeof L=="boolean"){const q=te.current;if(L===q){const M=U.current||B.current||(typeof window<"u"?window.innerWidth:0),A=Ge(G,q?0:-M,{type:"spring",stiffness:400,damping:35,mass:.8});y.current=A}}if(S==="right"&&typeof L=="boolean"){const q=z.current;if(L===q){const M=H.current||B.current||(typeof window<"u"?window.innerWidth:0),A=Ge(O,q?0:M,{type:"spring",stiffness:400,damping:35,mass:.8});b.current=A}}}});const R=r.useMemo(()=>{if(!f&&n!=="terminal"&&n!=="diagram"||f&&n==="git"&&(c||j))return null;switch(n){case"git":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(Qt,{isActive:!0})});case"diff":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(la,{})});case"terminal":return e.jsx(ln,{onCloseView:()=>ee.getState().setActiveMainTab("chat")});case"files":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(ca,{})});case"diagram":return e.jsx(r.Suspense,{fallback:null,children:e.jsx(da,{})});default:return null}},[n,f,j,c]),J=n==="chat";return e.jsxs(gr,{children:[e.jsx(xr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:ie("main-content-safe-area",f?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(ra,{}),e.jsx(oa,{}),e.jsx(wr,{}),f?e.jsxs(ia,{value:{leftDrawerOpen:v,rightDrawerOpen:c,toggleLeftDrawer:()=>{const S=!v;c&&P(!1),T(S)},toggleRightDrawer:ne,leftDrawerX:G,rightDrawerX:O,leftDrawerWidth:U,rightDrawerWidth:H,setMobileLeftDrawerOpen:T,setRightSidebarOpen:P},children:[!a&&e.jsx(Et,{onToggleLeftDrawer:()=>{const S=!v;c&&P(!1),T(S)},onToggleRightDrawer:()=>{ne()},leftDrawerOpen:v,rightDrawerOpen:c}),e.jsx("div",{"data-page-scroll-lock":"true",className:ie("flex flex-1 overflow-hidden relative",a&&"hidden"),children:e.jsxs("main",{ref:re,className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:[e.jsx("div",{className:ie("absolute inset-0",!J&&"invisible"),children:e.jsx(Ne,{children:e.jsx(Tt,{active:J&&!a})})}),R&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ne,{children:R})}),e.jsx(Ne,{children:e.jsx(_t,{})}),e.jsx(Ot.div,{className:ie("absolute inset-0 z-20 bg-sidebar",!d&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:G},"aria-hidden":!v,children:e.jsx(Ne,{children:e.jsx(Dt,{mobileVariant:!0,isVisible:d})})}),e.jsx(Ot.div,{className:ie("absolute inset-0 z-20 bg-sidebar",!j&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:O},"aria-hidden":!c,children:e.jsx(Ne,{children:c||j?e.jsx(r.Suspense,{fallback:null,children:e.jsx(Qt,{isActive:c})}):null})})]})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(Ne,{children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(ua,{onClose:()=>m(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(yr,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(Ts,{isOpen:t,isMobile:f,children:e.jsx(Dt,{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(Et,{}),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:ie("absolute inset-0",!J&&"invisible"),children:e.jsx(Ne,{children:e.jsx(Tt,{active:J&&!a})})}),R&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Ne,{children:R})}),e.jsx(Ne,{children:e.jsx(_t,{})})]}),e.jsx(Ko,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Ne,{children:e.jsx(Zo,{})})})]})]})]}),w?e.jsx(r.Suspense,{fallback:null,children:e.jsx(ha,{open:a,onOpenChange:m})}):null]})]})]})},fa=()=>(as(),vr(),e.jsxs(jr,{children:[e.jsx(is,{embeddedBackgroundWorkEnabled:!0}),e.jsx(ls,{}),e.jsx(pa,{}),e.jsx(Sr,{}),e.jsx(cs,{}),e.jsx(ds,{})]}));function ma({apis:t}){const n=t??sn(),[o,i]=r.useState(0);return r.useEffect(()=>nr(a=>{if(a.runtimeKey===a.previousRuntimeKey){rr();return}br(a),i(m=>m+1)}),[]),r.useEffect(()=>{let a=!0,m=null,w=null;return sr().then(()=>{a&&(m=ts(),w=ns())}),()=>{a=!1,m?.(),w?.()}},[o]),r.useEffect(()=>{n&&or(n)},[n]),n?e.jsx(Ne,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(rs,{apis:n,children:e.jsx(ss,{children:e.jsx(os,{children:e.jsx(fa,{})})},o)})})}):e.jsx(Ne,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const $n=document.getElementById("root");if(!$n)throw new Error("Root element not found");Wn.createRoot($n).render(e.jsx(Se.StrictMode,{children:e.jsx(us,{children:e.jsx(hs,{children:e.jsx(ma,{apis:sn()??void 0})})})}));
|