@pi-chamber/web 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramEditor-D_3eJVSw.js → DiagramEditor-DerMrS6m.js} +1 -1
- package/dist/assets/{DiagramView-pGYm0-DR.js → DiagramView-DdipXAq8.js} +1 -1
- package/dist/assets/{DiffView-BApPTLGp.js → DiffView-Gh9wjthp.js} +1 -1
- package/dist/assets/FilesView-BXp0yc0j.js +6 -0
- package/dist/assets/{GitView-uW3w_LlQ.js → GitView-BmNCkkoC.js} +3 -3
- package/dist/assets/{JsonTreeView-CpgqCk9_.js → JsonTreeView-CxXRXXzk.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-fI6n3kqT.js → MarkdownRendererImpl-DNZQgQua.js} +1 -1
- package/dist/assets/{PatchDiff-BRloGXPs.js → PatchDiff-B_NFEIX7.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-BQc-vW4s.js → SessionSwitcherContent-Q4P2TGBr.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-v_8TaIZm.js → SessionSwitcherDropdown-Cgw2mQIO.js} +2 -2
- package/dist/assets/{SessionUnreadDot-A7vSfll2.js → SessionUnreadDot-BxtTkvHB.js} +1 -1
- package/dist/assets/SettingsView-CFzxRzUq.js +2 -0
- package/dist/assets/{SettingsWindow-D7UDhYd4.js → SettingsWindow-BEjHL1ET.js} +1 -1
- package/dist/assets/{ToolOutputDialog-wpU0ylYS.js → ToolOutputDialog-C_7vJLEq.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-BvoQK5Gm.js → ToolPartDiffPreview-ClV785zX.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DdPbLdh7.js → VirtualizedFileDiff-DrxkW2WQ.js} +1 -1
- package/dist/assets/{collapsible-BO6FIjvn.js → collapsible-CR3-hRMy.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DMvXzUJh.js → computeVirtualFileMetrics-D0mQcleY.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-BwXQVjtS.js → contextFileOpenGuard-BRc5Z0g-.js} +1 -1
- package/dist/assets/{gitStatusPredicates-CgNk6M2_.js → gitStatusPredicates-DBGDfr1K.js} +1 -1
- package/dist/assets/{index-C3SyF-cA.js → index-CMfiVUIr.js} +1 -1
- package/dist/assets/index-CzO3ooje.css +1 -0
- package/dist/assets/index-ivrh3jfy.js +8 -0
- package/dist/assets/{isDiffPlainText-BboRbmcm.js → isDiffPlainText-MmBA1REG.js} +1 -1
- package/dist/assets/{isFilePlainText-BpTnLRyI.js → isFilePlainText-bQAPxqO9.js} +1 -1
- package/dist/assets/{main-CMOAwZnJ.js → main-BoVfUG73.js} +8 -8
- package/dist/assets/{main-xLwCWLu-.js → main-zZrKd3hZ.js} +2 -2
- package/dist/assets/{markdownCore-CmFv4H-w.js → markdownCore-B9jXCPry.js} +1 -1
- package/dist/assets/{miniChat-Vwo4K1IK.js → miniChat-Di2oVS5o.js} +2 -2
- package/dist/assets/{mobile-BRaxtEoC.js → mobile-VU_G_SgX.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-DM4rRUUz.js → renderElectronMiniChatApp-Bi1927c8.js} +2 -2
- package/dist/assets/{renderMobileApp-DWWewNhc.js → renderMobileApp-D9mxhuaM.js} +3 -3
- package/dist/assets/runtimeEndpointReset-DImT35Ug.js +54 -0
- package/dist/assets/{runtimeSurface-SmPSdfop.js → runtimeSurface-CBaS2Ank.js} +1 -1
- package/dist/assets/{useAppFontEffects-Bg-8jtrQ.js → useAppFontEffects-8ZU-TTIW.js} +105 -105
- package/dist/assets/{useFilesViewSearch-GLcYNIUV.js → useFilesViewSearch-COow9O9x.js} +1 -1
- package/dist/assets/{usePushVisibilityBeacon-VSYBfNoY.js → usePushVisibilityBeacon-zYd3ppNh.js} +1 -1
- package/dist/assets/{useSwitcherItems-BkEt9K-N.js → useSwitcherItems-DOQqhi-e.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B5cJDWBR.js → vendor-codemirror-language-data-B_0wrsbo.js} +2 -2
- package/dist/assets/{web-components-0H9kvZwn.js → web-components-C9ENH49P.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/lib/pi/routes.test.js +39 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-daemon/extension-bridge.js +14 -11
- package/server/lib/pi/session-daemon/prompt-operations.test.js +73 -6
- package/server/lib/pi/session-daemon/session-daemon.js +163 -21
- package/server/lib/relay/host-client.test.js +3 -1
- package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
- package/server/lib/ui-auth/ui-auth.js +23 -26
- package/server/lib/ui-auth/ui-auth.test.js +27 -0
- package/dist/assets/FilesView-CiPpuGiF.js +0 -6
- package/dist/assets/SettingsView-CphlZvfd.js +0 -2
- package/dist/assets/index-BebQicw3.css +0 -1
- package/dist/assets/index-Bkz23mZq.js +0 -8
- package/dist/assets/runtimeEndpointReset-BF60eHSx.js +0 -54
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-C3SyF-cA.js","assets/useAppFontEffects-Bg-8jtrQ.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-Bkz23mZq.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BebQicw3.css","assets/vendor-base-ui-vkqQ2P9o.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-SmPSdfop.js","assets/vendor-dnd-kit-core-CP8ck10N.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-B-Icjoj4.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-B5cJDWBR.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.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/computeVirtualFileMetrics-DMvXzUJh.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/isFilePlainText-BpTnLRyI.js","assets/isDiffPlainText-BboRbmcm.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-v_8TaIZm.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as vs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Me,j as t,R as i}from"./vendor-react-B5Z1Mdn3.js";import{cV as Ms,i as xc,cc as bc,D as Rt,E as Fe,F as Le,a as Et,U as Re,I as D,G as Oe,b as Pt,bM as yc,bN as wc,bO as vc,bP as Sc,bQ as nr,bR as qs,ck as Ro,bm as Xe,t as ie,c as dt,k as ve,b9 as ks,bg as ln,M as Ii,aQ as Kt,aR as Ht,bi as us,bj as os,bk as fs,bl as Ns,cW as jc,be as Cs,cX as Xs,cY as Cc,ca as $s,Z as Vs,cZ as rr,c_ as Eo,c$ as Po,d0 as tn,aw as Di,ao as ys,aL as Mo,af as cn,ci as Cr,d1 as kc,d2 as Nc,d3 as Ac,d4 as Ic,K as Dc,d5 as kr,d6 as Rc,L as Gt,d7 as Ec,d8 as Pc,cw as Mc,cj as Tc,d9 as Fc,cS as Lc,as as Ri,at as Ei,da as Pi,u as Nr,r as Ts,bZ as Vr,bd as Oc,Y as Bc,bB as To,bA as _c,bz as zc,bJ as Mi,db as Uc,g as Qr,j as Gs,Q as Ti,dc as lt,d as Ar,dd as $c,de as Gc,bv as Kc,df as Hn,dg as Fo,dh as Fi,bK as Li,di as Ir,dj as Oi,S as Bi,ba as Hc,dk as Wc,dl as Yc,l as _i,bW as qc,dm as Vc,dn as Qc,m as Jc,dp as Xc,e as Zc,dq as ed,bV as td,s as sd,f as nd,a7 as zi,dr as Dr,ds as rd,dt as od,bL as id,cU as ad,du as ld,a3 as cd,aN as Ui,c3 as dd,aB as ud,bn as Ls,dv as fd,dw as hd,bX as pd,dx as md,R as $i,ah as gd,dy as xd,W as Gi,dz as Ki,cC as bd,cD as yd,dA as wd,cu as vd,bU as Sd,dB as jd,dC as Cd}from"./useAppFontEffects-Bg-8jtrQ.js";import{g as Lo,aW as kd,aX as Oo,aY as Nd,i as Ad,h as Id,A as Dd,r as Mt,C as dn,B as Rd,c as z,aZ as Ed,b as Os,a_ as Jr,a$ as Xr,b0 as Pd,b1 as Md,f as Bs,M as Td,b2 as Fd,b3 as Ld,b4 as Od,as as ts,p as ss,b5 as Bd,b6 as _d,b7 as zd,y as Zr,b8 as Ud,b9 as $d,ba as Gd,u as se,z as Kd,n as ye,bb as _s,D as Ft,bc as Bo,bd as Rr,w as Wn,be as Hd,aA as Wd,$ as eo,m as sn,bf as Yd,bg as qd,T as Hi,G as Vd,l as Wi,j as nn,bh as Er,H as Pr,a4 as jn,bi as Qd,bj as Qs,ay as or,bk as Mr,bl as ws,bm as _o,bn as Tr,bo as Yi,bp as Fr,bq as Jd,ah as Xd,br as Zd,bs as eu,bt as tu,bu as su,ak as nu,a3 as ru,V as ou,k as zo,bv as qi,d as iu,L as au}from"./index-Bkz23mZq.js";import{c as hs,d as Vi,p as to,u as Lr,a as lu}from"./vendor-zustand-GVb4H8HE.js";import{g as ds,d as cu,e as Qi,r as du,h as Ji,i as En,j as Xi,b as un,c as fn,s as uu,k as fu,l as hu,m as Uo,n as Yn,f as pu,S as mu,a as gu,t as xu,o as bu}from"./SessionUnreadDot-A7vSfll2.js";import{i as Zi,j as ea,k as ta,l as sa,m as na,M as ra,S as oa,D as yu,c as wu,d as vu,e as Su,f as ju,g as Cu,h as ku}from"./vendor-base-ui-vkqQ2P9o.js";import{c as so,d as On,P as ia,D as no,e as ro,f as aa,b as Nu,a as Au,T as Iu,M as Du}from"./vendor-dnd-kit-core-CP8ck10N.js";import{u as Ru}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as la,v as Eu,u as ca,h as Pu}from"./vendor-dnd-kit-sortable-B-Icjoj4.js";import{C as da}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{usePermissionStore as Mu}from"./permissionStore-iKN1K2_x.js";const Tu="chat";function ua(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ms.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ms.SETTINGS,n),s}return e.tab!==Tu&&s.set(Ms.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ms.FILE,e.diffFile),s}function Fu(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Lu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=ua(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ms.SESSION)&&s.set(Ms.SESSION,o);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Or(e,s={}){if(!(typeof window>"u")&&!(!s.force&&Lu(e)))try{const n=ua(e),r=Fu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ou=["typescript","javascript","tsx","jsx","json","markdown"],fa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let $o=null;const ha=()=>($o??=Promise.all([vs(()=>import("./index-C3SyF-cA.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])),vs(()=>import("./workerFactory-tw7cIdmV.js"),[]),vs(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([110,111,97,98,24,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),$o),hn={},Go=new Set,Br=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const Bu=()=>{for(const e of Br)e()},pa=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:fa[e].lineDiffType})},_r=e=>{typeof window>"u"||Go.has(e)||(Go.add(e),ha().then(s=>{if(hn[e])return;const n=fa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ou,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),hn[e]=r,pa(e,r),Bu()}))},_u=e=>(Br.add(e),()=>Br.delete(e)),zu=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(hn)){const n=hn[s];n&&pa(s,n)}}},sx=({children:e})=>{const s=xc(),n=Lo(!1),r=Lo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===o)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Me.useEffect(()=>{let d=!1;return ha().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),zu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Me.useEffect(()=>{if(typeof window>"u")return;const d=()=>{_r("unified"),_r("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},nx=(e="unified")=>{const s=Me.useSyncExternalStore(_u,()=>hn[e],()=>{});return Me.useEffect(()=>{_r(e)},[e]),s};function Uu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=bc();return e}catch{return"unknown"}}function $u(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function Gu(){const e=Rd();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function Ku(e){const s=new URLSearchParams;return s.set("deviceClass",Uu()),s.set("arch",$u()),s.set("platform",Gu()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",dn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ir(e,s){try{const n=Ku(e);s&&n.set("currentVersion",s);const r=await Mt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Hu(){return Ad()?"mobile":Id()?"desktop":Dd()?"web":null}const Ko={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=hs()((e,s)=>({...Ko,checkForUpdates:async()=>{const n=Hu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.8.1",[l,c]=await Promise.allSettled([Oo(),ir("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ir("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ir("mobile","0.8.1"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await Oo();if(!o?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await Nd(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await kd())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(Ko)}})),Wu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Yu=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=i.useState(!1),[f,h]=i.useState(""),[x,g]=i.useState(!1),[m,p]=i.useState(!1),[y,b]=i.useState(""),[A,v]=i.useState(!1),C=i.useRef(null),S=i.useCallback(P=>{P.stopPropagation()},[]),I=l.length>1,k=i.useMemo(()=>Wu(y),[y]),w=i.useMemo(()=>{const P=f.toLowerCase();return P?s.filter(B=>B.toLowerCase().includes(P)):s},[f,s]),j=i.useMemo(()=>{const P=f.toLowerCase();return P?n.filter(B=>B.toLowerCase().includes(P)):n},[f,n]),E=P=>{if(P===e){u(!1);return}o(P),u(!1),h("")},T=()=>{g(!0),setTimeout(()=>C.current?.focus(),50)},U=async()=>{if(!(!k||A)){if(I){p(!0);return}v(!0);try{await a(k,l[0]),b(""),g(!1),u(!1)}finally{v(!1)}}},_=async P=>{if(!(!k||A)){v(!0);try{await a(k,P),b(""),g(!1),p(!1),u(!1)}finally{v(!1)}}},$=()=>{p(!1)},K=()=>{b(""),g(!1),p(!1)};return i.useEffect(()=>{d||(h(""),g(!1),p(!1),b(""))},[d]),t.jsxs(Rt,{open:d,onOpenChange:u,children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Oe,{sideOffset:8,children:"Current branch"})]}),t.jsx(Pt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(yc,{className:"h-full min-h-0",children:[t.jsx(wc,{placeholder:"Search branches...",value:f,onValueChange:h,onKeyDown:S}),t.jsxs(vc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Sc,{children:"No branches found."}),t.jsx(nr,{children:m?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:$,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:k})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(P=>t.jsxs("button",{type:"button",onClick:()=>_(P),disabled:A,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[A?t.jsx(D,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,P.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:P.pushUrl})]},P.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:C,placeholder:"New branch name",value:y,onChange:P=>b(P.target.value),onClick:P=>P.stopPropagation(),onKeyDown:P=>{S(P),P.key==="Enter"?(P.preventDefault(),U()):P.key==="Escape"&&(P.preventDefault(),K())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:U,disabled:!k||A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:A?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:K,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsxs(qs,{onSelect:T,children:[t.jsx(D,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Local branches",children:[w.map(P=>t.jsxs(qs,{onSelect:()=>E(P),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:P}),(r?.[P]?.ahead||r?.[P]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[P].ahead||0," ahead ·"," ",r[P].behind||0," behind"]})]}),e===P&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${P}`)),w.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Remote branches",children:[j.map(P=>t.jsx(qs,{onSelect:()=>E(P),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:P})},`remote-${P}`)),j.length===0&&t.jsx(qs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},qu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Vu=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,o]=i.useState(!1),[a,l]=i.useState(e||""),[c,d]=i.useState(!1),u=i.useRef(null),f=()=>{!e||!s||(l(e),o(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const m=qu(a);if(m===e){o(!1);return}d(!0);try{await s(e,m),o(!1),l("")}finally{d(!1)}},x=()=>{o(!1),l("")},g=m=>{m.key==="Enter"?(m.preventDefault(),h()):m.key==="Escape"&&(m.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:m=>{m.preventDefault(),h()},children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:m=>l(m.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:g,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(D,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(D,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:"Rename branch",children:t.jsx(D,{name:"edit",className:"size-4"})})]})]})},Qu=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:o,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:f=!1})=>{const h=i.useRef(!1),x=!!l,g=s.find(S=>S.name===u)??s[0],m=d>0&&f,p=a||e!==null||x||!g||m,y=a||e!==null||x||s.length===0,b=c>0||d>0,A=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=m?"Commit or stash your changes before syncing":g?b?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",C=()=>{g&&r(g)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:m?0:void 0,children:t.jsxs("button",{type:"button",onClick:C,disabled:p,className:z("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(D,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:A})]})})}),t.jsx(Oe,{sideOffset:8,children:v})]}),t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:y,"aria-label":"More sync actions",children:t.jsx(D,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Pt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(S=>t.jsx(Xe,{onSelect:I=>{if(h.current){I.preventDefault(),h.current=!1;return}n(S)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(D,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${S.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:S.fetchUrl})]})}),o&&S.name!==u?t.jsx(Re,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:I=>{h.current=!0,I.preventDefault(),I.stopPropagation()},onClick:I=>{h.current=!0,I.preventDefault(),I.stopPropagation(),o(S)},"aria-label":`Remove remote ${S.name}`,title:`Remove remote ${S.name}`,children:l===S.name?t.jsx(D,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(D,{name:"close",className:"size-3.5"})}):null]})},S.name))})]})]})},Ju={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Xu={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function ma(e){return e&&Xu[e]||"var(--primary)"}const Ho=({icon:e,className:s,colorToken:n})=>{const r=Ju[e??"branch"]??"user-3";return t.jsx(D,{name:r,className:s,style:{color:ma(n)}})},ga=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Rt,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:ma(e?.color)},disabled:a,children:[r?t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(Ho,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Oe,{sideOffset:8,children:"Git identity"})]}),t.jsx(Pt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(Xe,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(Ho,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(D,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},Zu=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,o=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(Fe,{delayDuration:n,children:[t.jsx(Le,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(D,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),o?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(Oe,{sideOffset:8,children:a})]})},rx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:f,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:g,availableIdentities:m,onSelectIdentity:p,isApplyingIdentity:y,isWorktreeMode:b,onOpenHistory:A,onOpenGraph:v,onOpenStashes:C,onOpenUpdateBranch:S,onOpenReintegrateCommits:I,pullRequest:k,prChecks:w,onOpenPullRequest:j})=>{if(!e)return null;const E=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:A||v||C||S?t.jsxs(Rt,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(D,{name:"more-fill",className:"size-4"})})})}),t.jsx(Oe,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Pt,{align:"end",children:[A?t.jsxs(Xe,{onSelect:A,children:[t.jsx(D,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(Xe,{onSelect:v,children:[t.jsx(D,{name:"git-branch",className:"size-4"}),"Graph"]}):null,C?t.jsxs(Xe,{onSelect:C,children:[t.jsx(D,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,S?t.jsxs(Xe,{onSelect:S,children:[t.jsx(D,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,I?t.jsxs(Xe,{onSelect:I,children:[t.jsx(D,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),T=w?w.state==="success"?"var(--status-success)":w.state==="failure"?"var(--status-error)":"var(--status-warning)":null,U=k?k.state==="merged"?"merged":k.state==="closed"?"closed":k.draft?"draft":w?.state==="failure"||k.mergeable===!1||k.mergeableState==="blocked"||k.mergeableState==="dirty"?"blocked":"open":null,_=k&&j?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",onClick:j,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(D,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${U})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${k.number}`}),T?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:T}}):null]})}),t.jsx(Oe,{sideOffset:8,children:"Open pull request"})]}):null,$=t.jsx(Qu,{syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),K=e.upstreamComparison?t.jsx(Zu,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,P=t.jsx(ga,{activeProfile:g,identities:m,onSelect:p,isApplying:y,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:b?t.jsx(Vu,{currentBranch:e.current,onRename:x}):t.jsx(Yu,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:P})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[_?t.jsx("div",{className:"shrink-0",children:_}):null,t.jsx("div",{className:"min-w-0 flex-1"}),K?t.jsx("div",{className:"min-w-0 shrink",children:K}):null,E,t.jsx("div",{className:"shrink-0",children:$})]})]})},ef=e=>e==="/",zs=e=>e.replace(/\\/g,"/"),Us=e=>{if(!e||ef(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),Bn=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},oo=e=>e.lastIndexOf("/"),xa=e=>{if(Fs(e))return e;const s=oo(e);return s<0?e:e.slice(0,s+1)},ba=e=>{const s=oo(e);return e.slice(s+1)},ya=e=>{const s=Us(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=oo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},wa=e=>Fs(e)&&ya(e)!==null,tf=e=>{if(!wa(e))return null;const s=Us(e.trim());return ba(s)||s},sf=(e,s)=>`${xa(e)}${s}/`,Ss=e=>{if(!e)return null;const s=Us(zs(e.trim()));return s?s.toLowerCase():null},Wo=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},nf=(e,s)=>{const n=Us(zs(e.trim())),r=Us(zs(s.trim()));if(!n)return"";if(!r)return Bn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Bn(n)},rf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,zr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},of=async()=>Ed(),af=()=>{const[e,s]=Me.useState(!1),[n,r]=Me.useState(!1);Me.useEffect(()=>{s(Os()),r(Jr())},[]);const o=Me.useCallback(async c=>e?await Xr(c):{success:!0,path:c},[e]),a=Me.useCallback(async c=>e?await Pd():{success:!0},[e]),l=Me.useCallback(async c=>e?await Md():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function lf({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Bs(Z=>Z.homeDirectory),{canRequestAccess:o,startAccessing:a}=af(),l=i.useRef(null),c=i.useRef(new Map),[d,u]=i.useState(""),[f,h]=i.useState("~/"),[x,g]=i.useState([]),[m,p]=i.useState(!1),[y,b]=i.useState(!1),[A,v]=i.useState(null),[C,S]=i.useState(0),[I,k]=i.useState(0),[w,j]=i.useState(!1),[E,T]=i.useState(!1),[U,_]=i.useState("right"),$=i.useRef("~/"),K=d||r;i.useEffect(()=>{if(!e)return;h("~/"),g([]),k(0),j(!1),T(!1),$.current="~/",_("right"),n||requestAnimationFrame(()=>zr(l.current));let Z=!1;return(async()=>{const L=await of();Z||(u(L||r||""),n||requestAnimationFrame(()=>zr(l.current)))})(),()=>{Z=!0}},[r,e,n]);const P=i.useMemo(()=>xa(f),[f]),B=i.useMemo(()=>Fs(f)?"":ba(f),[f]),R=i.useMemo(()=>K?Wo(P,K):"",[P,K]);i.useEffect(()=>{const Z=$.current;Z!==P&&(_(P.length>=Z.length?"right":"left"),$.current=P)},[P]),i.useEffect(()=>{if(!e||!R){g([]),v(null);return}let Z=!1;return p(!0),b(!1),v(null),Td(R).then(ue=>{if(Z)return;b(!1),v(null);const L=ue.filter(Y=>Y.isDirectory).map(Y=>({name:Y.name,path:zs(Y.path)})).sort((Y,le)=>Y.name.localeCompare(le.name));g(L)}).catch(ue=>{if(!Z){g([]);const L=Fd(ue)?ue.reason:"unknown";v(L),b(L==="not-found")}}).finally(()=>{Z||p(!1)}),()=>{Z=!0}},[R,C,e]);const F=i.useMemo(()=>{const Z=B.toLowerCase(),ue=E||B.startsWith(".");return x.filter(L=>L.name.toLowerCase().startsWith(Z)&&(ue||!L.name.startsWith(".")))},[B,x,E]),V=i.useMemo(()=>tf(f),[f]),G=i.useMemo(()=>ya(f),[f]),M=i.useMemo(()=>{const Z=[],ue=Ss(R);wa(f)&&V&&G&&Z.push({type:"parent",value:"browse:up",name:V,path:G,alreadyAdded:!!(ue&&s.has(ue))});for(const L of F){const Y=Ss(L.path);Z.push({type:"directory",value:`browse:${L.path}`,name:L.name,path:L.path,alreadyAdded:!!(Y&&s.has(Y))})}return Z},[s,R,V,F,G,f]);i.useEffect(()=>{k(0)},[f,M.length]);const ee=i.useMemo(()=>K?Us(Wo(f,K)):"",[K,f]),H=Ss(ee),we=!!(H&&s.has(H)),ce=i.useMemo(()=>B?F.find(Z=>Z.name===B)??null:null,[B,F]),ae=!!(ee&&!we&&(A===null||A==="not-found")&&(Fs(f)&&y||!Fs(f)&&B.trim().length>0&&ce===null)),xe=M[I]??null,be=!!xe,ge=i.useCallback(Z=>{h(Bn(Z))},[]),Se=i.useCallback(Z=>{h(sf(f,Z.name))},[f]),je=i.useCallback(Z=>{if(Z){if(Z.type==="parent"){ge(Z.path);return}Se(Z)}},[ge,Se]),ke=i.useCallback(async Z=>{const ue=await a(Z);if(!ue.success)return ie.error("Failed to open directory",{description:ue.error||"Desktop could not grant file access."}),!1;const L=K?nf(Z,K):Bn(zs(Z));return ge(L),!0},[ge,K,a]),Ce=i.useCallback(async()=>{if(!w){j(!0);try{if(Jr()){const ue=await Xr(ee);if(!ue.success||!ue.path){ue.error&&ue.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:ue.error});return}await ke(ue.path);return}const Z=await Ld(ee);if(Z.status==="cancelled")return;if(Z.status!=="picked"){ie.error("Couldn't open a folder picker",{description:Z.error});return}await ke(Z.path)}catch(Z){ie.error("Failed to select directory",{description:Z instanceof Error?Z.message:"Unknown error occurred."})}finally{j(!1)}}},[ke,w,ee]);return{inputRef:l,rowRefs:c,query:f,setQuery:h,isLoading:m,isBrowseDirectoryMissing:y,browseErrorReason:A,browseReloadKey:C,setBrowseReloadKey:S,highlightedIndex:I,setHighlightedIndex:k,isPickingLocation:w,showHidden:E,setShowHidden:T,folderEnterFrom:U,explorerRootDirectory:K,browseDirectoryDisplayPath:P,browseDirectoryAbsolutePath:R,browseFilterQuery:B,filteredEntries:F,rows:M,targetPath:ee,isAlreadyAdded:we,shouldCreateTarget:ae,highlightedRow:xe,hasHighlightedBrowseItem:be,canRequestAccess:o,browseToDisplayPath:ge,browseToEntry:Se,executeRow:je,applyPickedLocation:ke,handleBrowseLocation:Ce}}const bs=hs()(Vi(to((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=ss()?.git,o=r?await r.getGitIdentities():await Gd();return e({profiles:o,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=ss()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await $d();if(r&&r.userName&&r.userEmail){const o={id:"global",name:"Global Identity",userName:r.userName,userEmail:r.userEmail,authType:r.sshCommand?"ssh":void 0,sshKey:r.sshCommand?r.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:o})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=ss()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await Ud();return e({discoveredCredentials:r}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const o=r.trim();return o.length>0?o:null};try{let r=null;if(r===null){const o=ss()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Mt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Zr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};ts("saving");const o=ss()?.git;return o?await o.createGitIdentity(r):await zd(r),ts("saved"),await s().loadProfiles(),!0}catch(r){return ts("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(c=>c.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};ts("saving");const l=ss()?.git;return l?await l.updateGitIdentity(n,a):await _d(n,a),ts("saved"),await s().loadProfiles(),!0}catch(o){return ts("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{ts("saving");const r=ss()?.git;return r?await r.deleteGitIdentity(n):await Bd(n),ts("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ts("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:o}=s();return n==="global"?o||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(o=>!n.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Od(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=bs);function cf({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=dt(G=>G.addProject),h=se(G=>G.setActiveMainTab),x=se(G=>G.setSessionSwitcherOpen),g=ve(G=>G.openNewSessionDraft),m=bs(G=>G.profiles),p=bs(G=>G.globalIdentity),y=bs(G=>G.defaultGitIdentityId),b=bs(G=>G.loadProfiles),A=bs(G=>G.loadGlobalIdentity),v=bs(G=>G.loadDefaultGitIdentityId),[C,S]=i.useState(!1),[I,k]=i.useState(!1),[w,j]=i.useState(""),[E,T]=i.useState(null);i.useEffect(()=>{e&&(S(!1),k(!1),j(""),T(null))},[e]),i.useEffect(()=>{e&&(b(),A(),v())},[v,b,A,e]);const U=i.useMemo(()=>{const G=new Map;p&&G.set(p.id,p);for(const M of m)G.set(M.id,M);return Array.from(G.values())},[m,p]);i.useEffect(()=>{if(!e||!I||E!==null)return;const G=typeof y=="string"?y.trim():"";if(G&&U.some(ee=>ee.id===G)){T(G);return}const M=U.find(ee=>ee.authType==="ssh"||ee.sshKey);M&&T(M.id)},[U,y,I,e,E]);const _=i.useMemo(()=>U.find(G=>G.id===E)??null,[U,E]),$=i.useCallback((G,M)=>{h("chat"),n&&x(!1),g({selectedProjectId:G,directoryOverride:M}),s()},[n,s,g,h,x]),K=i.useCallback(async G=>{if(!G||C)return;const M=Ss(G);if(M&&r.has(M))return;let ee=G;S(!0);try{const H=!I&&a&&Ss(G)===Ss(o);if(I){const ce=w.trim();if(!ce){ie.error("Enter a repository URL before cloning.");return}const ae=await Mt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ce,destinationPath:G,gitIdentityId:_?.id??null})});if(!ae.ok)throw new Error("Failed to clone git repository");ee=(await ae.json()).path||G}else if(H&&!(await Mt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:G})})).ok)throw new Error("Failed to select directory");const we=f(ee);if(!we){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}$(we.id,we.path)}catch(H){ie.error("Failed to select directory",{description:H instanceof Error?H.message:"Unknown error occurred."})}finally{S(!1)}},[f,r,c,w,I,C,$,_?.id,a,o]),P=!C&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,B=P&&w.trim().length>0,R=I?B:P,F=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:C,isCloneMode:I,setIsCloneMode:k,cloneRemoteUrl:w,setCloneRemoteUrl:j,selectedGitIdentityId:E,setSelectedGitIdentityId:T,availableGitIdentities:U,selectedGitIdentity:_,canSubmit:R,submitActionLabel:d?"Already added":I?C?"Cloning...":"Clone & add":C?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:F,finalizeSelection:K}}const df=({open:e,onOpenChange:s})=>{const n=dt(L=>L.projects),{isMobile:r,isTablet:o}=ks(),a=r||o,l=i.useMemo(()=>new Set(n.map(L=>Ss(L.path)).filter(L=>!!L)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:d,rowRefs:u,query:f,setQuery:h,isLoading:x,browseErrorReason:g,setBrowseReloadKey:m,highlightedIndex:p,setHighlightedIndex:y,isPickingLocation:b,showHidden:A,setShowHidden:v,folderEnterFrom:C,browseDirectoryDisplayPath:S,browseDirectoryAbsolutePath:I,rows:k,targetPath:w,isAlreadyAdded:j,shouldCreateTarget:E,highlightedRow:T,hasHighlightedBrowseItem:U,canRequestAccess:_,executeRow:$,handleBrowseLocation:K}=lf({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:P,isCloneMode:B,setIsCloneMode:R,cloneRemoteUrl:F,setCloneRemoteUrl:V,setSelectedGitIdentityId:G,availableGitIdentities:M,selectedGitIdentity:ee,canSubmit:H,submitActionLabel:we,submitModifierLabel:ce,finalizeSelection:ae}=cf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:E,browseErrorReason:g,browseDirectoryAbsolutePath:I,isAlreadyAdded:j,isPickingLocation:b});i.useLayoutEffect(()=>{const L=d.current;L&&(L.scrollLeft=L.scrollWidth)},[d,f]),i.useLayoutEffect(()=>{!e||a||zr(d.current)},[d,e,a]),i.useLayoutEffect(()=>{const L=k[p];L&&u.current.get(L.value)?.scrollIntoView({block:"nearest"})},[p,u,k]);const xe=i.useCallback(L=>{if(L.key==="ArrowDown"){L.preventDefault(),y(Y=>Math.min(k.length-1,Y+1));return}if(L.key==="ArrowUp"){L.preventDefault(),y(Y=>Math.max(0,Y-1));return}if(L.key==="Enter"){if(L.preventDefault(),rf(L)){ae(w);return}U&&$(T);return}L.key==="Backspace"&&f===""&&(L.preventDefault(),c())},[$,ae,c,U,T,f,k.length,y,w]),be=t.jsxs("button",{type:"button",onClick:()=>v(L=>!L),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[A?t.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),ge=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(D,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(ln,{ref:d,value:f,onChange:L=>h(zs(L.target.value)),onKeyDown:xe,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Re,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:P||b,onMouseDown:L=>L.preventDefault(),onClick:()=>{K()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(D,{name:"folder-open",className:"h-3.5 w-3.5"}),b?"Opening...":"Browse"]})]})}),Se=k.some(L=>L.type==="parent"),je=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Re,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":B,disabled:P||b,onClick:()=>R(L=>!L),children:[t.jsx(D,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),B?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(ln,{value:F,onChange:L=>V(L.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(ga,{activeProfile:ee,identities:M,onSelect:L=>G(L.id),isApplying:P,iconOnly:!0})]})]}):null,j?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:z("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",C==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):g&&g!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:g==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[g==="os-permission"&&_?t.jsx(Re,{size:"xs",onClick:()=>{K()},disabled:b,children:"Grant access"}):null,t.jsx(Re,{variant:"outline",size:"xs",onClick:()=>m(L=>L+1),children:"Try again"})]})]}):k.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:k.map((L,Y)=>{const le=Y===p,W=L.type==="directory"&&Se;return t.jsxs("button",{ref:X=>{X?u.current.set(L.value,X):u.current.delete(L.value)},type:"button","aria-label":L.type==="parent"?L.alreadyAdded?`Go back from ${L.name}, already added`:`Go back from ${L.name}`:L.alreadyAdded?`Open ${L.name}, already added`:`Open ${L.name}`,onMouseEnter:()=>y(Y),onMouseDown:X=>X.preventDefault(),onClick:()=>$(L),className:z("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",le&&"bg-interactive-selection text-interactive-selection-foreground",!le&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:z("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[L.type==="parent"?t.jsx(D,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(D,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:L.name})]}),L.alreadyAdded?t.jsx("span",{className:z("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",le?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,L.type==="parent"?t.jsx(D,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},L.value)})})},S)]})}),ke=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ge,je]}),Ce=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(D,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(D,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:ce}),t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Z=t.jsx(Re,{size:r?"xs":"default",onClick:()=>{ae(w)},disabled:!H,className:z(r&&"w-full flex-1"),children:we}),ue=()=>t.jsxs(t.Fragment,{children:[r?null:Ce,t.jsx("div",{className:z("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:Z})]});return r?t.jsx(Ii,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ue()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:be}),ke]})}):t.jsx(Kt,{open:e,onOpenChange:s,children:t.jsxs(Ht,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(us,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(os,{children:"Add folder"}),t.jsx(fs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),be]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:ke}),t.jsx(Ns,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ue()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,ox=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=jc,c=ve(I=>I.deleteSessions),d=se(I=>I.showDeletionDialog),u=se(I=>I.setShowDeletionDialog),{isMobile:f,isTablet:h,hasTouchInput:x}=ks(),g=f||h||x;i.useEffect(()=>Kd(()=>{s(!1)}),[]);const m=i.useCallback(I=>{r({sessions:I.sessions,dateLabel:I.dateLabel})},[]),p=i.useCallback(()=>{r(null),a(!1)},[]),y=i.useCallback(async I=>{if(I.sessions.length===0)return;if(I.sessions.length===1){const E=I.sessions[0];await l(E.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const k=I.sessions.map(E=>E.id),{deletedIds:w,failedIds:j}=await c(k);if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:I.dateLabel?`Removed all sessions from ${I.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Cn(E)})}j.length>0&&ie.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>Cs.onDeleteRequest(I=>{if(!d){y(I);return}m(I)}),[m,d,y]),i.useEffect(()=>Cs.onDirectoryRequest(()=>{s(!0)}),[]);const b=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const I=n.sessions[0];if(!await l(I.id)){ie.error("Failed to delete session"),a(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const I=n.sessions.map(E=>E.id),k=await c(I),w=k.deletedIds,j=k.failedIds;if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Cn(E),action:{label:"OK",onClick:()=>{}}})}if(j.length>0&&(ie.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:Cn("Please try again in a moment.")}),w.length===0)){a(!1);return}}p()}finally{a(!1)}}},[n,l,c,p]),A=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(I=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:ds(I)})},I.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,C=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(D,{name:"checkbox-blank",className:"size-4"}):t.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Re,{variant:"ghost",onClick:p,disabled:o,children:"Cancel"}),t.jsx(Re,{variant:"destructive",onClick:b,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),S=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[g?t.jsx(Ii,{open:!!n,onClose:()=>{o||p()},title:S,footer:t.jsx("div",{className:"flex justify-end gap-2",children:C}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[A&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:A}),v]})}):t.jsx(Kt,{open:!!n,onOpenChange:I=>{if(!I){if(o)return;p()}},children:t.jsxs(Ht,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(us,{children:[t.jsx(os,{children:S}),A&&t.jsx(fs,{children:A})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Ns,{className:"mt-2 gap-2 pt-1 pb-1",children:C})]})}),t.jsx(df,{open:e,onOpenChange:s})]})},ix=()=>{const e=Xs(d=>d.entries),s=se(d=>d.isMobile),n=se(d=>d.activeMainTab),r=ve(d=>d.newSessionDraft),o=ve(d=>d.openNewSessionDraft),a=ve(d=>d.setNewSessionDraftTarget),l=n==="chat",c=i.useMemo(()=>{const d=Cc(r?.worktreeIntent),u=!!r?.open,f=[];for(const h of e.values()){const x=u&&h.key===d,g=x&&l;if(h.state){g||f.push(h);continue}h.receipt&&!x&&f.push(h)}return f},[e,r?.worktreeIntent,r?.open,l]);return c.length===0?null:t.jsx("div",{className:z("pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3",s?"bottom-[calc(var(--oc-safe-area-bottom,0px)+5.5rem)]":"bottom-4"),"aria-live":"polite",children:t.jsx("div",{className:"pointer-events-auto flex w-full max-w-[640px] flex-col gap-2",children:c.map(d=>t.jsx(uf,{entry:d,onDismissFailed:()=>Xs.getState().dismissFailed(d.key),onDismissCompleted:()=>Xs.getState().clearEntry(d.key),onOpenWorktree:()=>{const u=d.receipt;u&&(r?.open?a({directoryOverride:u.path,worktreeIntent:null}):o({directoryOverride:u.path}),Xs.getState().clearEntry(d.key),se.getState().setActiveMainTab("chat"))}},d.key))})})},uf=({entry:e,onDismissFailed:s,onDismissCompleted:n,onOpenWorktree:r})=>{const o=e.state?.phase==="failed",a=!!(e.state&&!o),l=!e.state&&!!e.receipt,c=o?e.state?.label??"Worktree creation failed":a?e.state?.label??"Creating worktree...":e.receipt?`Worktree ready: ${e.receipt.branch??e.path??"new worktree"}`:"",d=o?e.state?.error:l?e.receipt?.path:null;return t.jsxs("div",{className:z("flex items-center gap-3 rounded-xl border px-3 py-2.5 shadow-lg backdrop-blur",o?"border-[var(--status-error-border)] bg-[var(--status-error-background)] text-[var(--status-error-foreground)]":l?"border-[var(--border)] bg-[var(--surface-elevated)] text-foreground":"border-[var(--border)] bg-[var(--surface-muted)] text-muted-foreground"),role:o?"alert":"status",children:[a?t.jsx($s,{variant:"inline",text:null,animationType:"spinner"}):l?t.jsx(D,{name:"git-branch",className:"h-4 w-4 shrink-0 text-[var(--status-success)]"}):t.jsx(D,{name:"alert",className:"h-4 w-4 shrink-0"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"typography-ui-label truncate",children:c}),d?t.jsx("p",{className:"mt-0.5 break-words text-xs opacity-80 line-clamp-2",children:d}):null,a&&e.branch?t.jsx("p",{className:"mt-0.5 truncate text-xs opacity-60",children:e.branch}):null]}),o?t.jsx(Re,{type:"button",variant:"ghost",size:"xs",onClick:s,"aria-label":"Dismiss error",children:"Dismiss"}):null,l?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Re,{type:"button",size:"xs",onClick:r,children:"Open"}),t.jsx(Re,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Dismiss",children:t.jsx(D,{name:"close",className:"h-3.5 w-3.5"})})]}):null,a?t.jsx("span",{className:"hidden shrink-0 text-xs opacity-60 sm:inline",children:"In background"}):null]})},ff=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],hf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function pf(e){const s=e.trim().toLowerCase();return ff.find(n=>n.slug===s)??null}function mf(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=hf[s];if(n)return n;const r=pf(s);return r?r.slug:"home"}function ax(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"snippets":return"chat-thread";case"prompt-templates":return"terminal";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}function lx(){const e=i.useRef(!1),s=i.useRef(!1),n=ve(f=>f.setCurrentSession),r=se(f=>f.setActiveMainTab),o=se(f=>f.setSettingsDialogOpen),a=se(f=>f.setSettingsPage),l=se(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const h=ve.getState().currentSessionId,x=Vs().getState().selectedSessionId;if(f.sessionId!==h||f.sessionId!==x){const g=ve.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,g)}}if(f.settingsPath){a(mf(f.settingsPath)),o(!0);return}se.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,o,a,l]),d=i.useCallback(()=>{const f=ve.getState(),h=Vs().getState(),x=se.getState();return{sessionId:rr({currentSessionId:f.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=i.useCallback((f={})=>{if(s.current)return;const h=d();Or(h,f)},[d]);i.useEffect(()=>{if(e.current||(e.current=!0,!Eo()))return;const f=Po();(async()=>(await c(f),Or({...d(),sessionId:f.sessionId??rr({currentSessionId:ve.getState().currentSessionId,piSelectedSessionId:Vs().getState().selectedSessionId,draft:ve.getState().newSessionDraft}),tab:f.tab??se.getState().activeMainTab,settingsPath:f.settingsPath??se.getState().settingsPage,diffFile:f.diffFile??se.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),i.useEffect(()=>{const f=()=>{const y=ve.getState(),b=Vs().getState();return rr({currentSessionId:y.currentSessionId,piSelectedSessionId:b.selectedSessionId,draft:y.newSessionDraft})};let h=f(),x=ve.getState().newSessionDraft?.open===!0;const g=()=>{const y=ve.getState(),b=f(),A=y.newSessionDraft?.open===!0;b===h&&A===x||s.current||(h=b,x=A,u({replace:!0}))},m=ve.subscribe(()=>{g()}),p=Vs().subscribe(()=>{g()});return()=>{m(),p()}},[u]),i.useEffect(()=>{let f=se.getState().activeMainTab,h=se.getState().isSettingsDialogOpen,x=se.getState().settingsPage,g=se.getState().pendingDiffFile;return se.subscribe(p=>{if(s.current)return;const y=p.activeMainTab!==f,b=p.isSettingsDialogOpen!==h,A=p.settingsPage!==x,v=p.pendingDiffFile!==g&&p.activeMainTab==="diff";f=p.activeMainTab,h=p.isSettingsDialogOpen,x=p.settingsPage,g=p.pendingDiffFile,(y||b||A||v)&&u()})},[u]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const h=Po();if(Eo())c(h);else{const x=se.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function gf(e=!0){const s=Mn(r=>r.checkForUpdates),n=i.useRef(s);i.useEffect(()=>{n.current=s},[s]),i.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},f=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),g=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(g)},h))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function cx(){const e=tn(s=>s.connection==="ready",void 0,"chrome");return gf(e),null}const Yo=12,xf=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],bf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=xf,onComplete:a})=>{const l=Me.useRef(!1);Me.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Me.useMemo(()=>Array.from({length:Yo},(d,u)=>{const f=Math.PI*2*u/Yo;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:z("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((f,h)=>{const x=f.x*d.radius,g=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:m},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},yf=({durationMs:e=3400}={})=>{const[s,n]=Me.useState({isActive:!1,cycle:0}),r=Me.useRef(null),o=Me.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Me.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Me.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Me.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},va=i.createContext(void 0),dx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=yf(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(va.Provider,{value:a,children:[e,t.jsx(bf,{isActive:s,burstKey:n})]})},wf={triggerFireworks:()=>{},dismissFireworks:()=>{}},ux=()=>i.useContext(va)??wf,qo="https://github.com/RyderAsKing/PiChamber/releases";function vf(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function Sf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Vo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function jf(e,s){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(a!==l)return l-a}return 0}function Cf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const Qo=2e3,kf=600*1e3;async function Nf(){try{const e=await Mt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Af(){try{return(await Mt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function If(e,s=Math.ceil(kf/Qo),n=Qo){for(let r=0;r<s;r++){try{const o=await Mt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await Af())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const Sa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,h]=Me.useState(!1),[x,g]=Me.useState("idle"),[m,p]=Me.useState(null),y=n?.version?n.releaseUrl||`${qo}/tag/v${n.version}`:qo,b=n?.downloadUrl||y,A=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",C=u==="mobile",S=n?.updateCommand||"pichamber update";Me.useEffect(()=>{e||(g("idle"),p(null))},[e]);const I=async()=>{(await cn(S)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},k=Me.useCallback(async U=>{await Di(U)},[]),w=Me.useCallback(async()=>{g("updating"),p(null);const U=await Nf();if(!U.success){g("error"),p(U.error||"Update failed");return}U.autoRestart&&(g("restarting"),await new Promise($=>setTimeout($,2e3))),g("reconnecting"),await If(n?.currentVersion)?window.location.reload():(g("error"),p("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),j=Me.useCallback(()=>{k(b)},[k,b]),E=x!=="idle"&&x!=="error",T=Me.useMemo(()=>{if(!n?.body)return null;const U=n.body.trim();if(!U)return null;const _=Cf(U);return _.length===0?{kind:"raw",title:"What's new",content:Vo(U)}:{kind:"sections",title:"What's new",sections:[..._].sort((K,P)=>jf(K.version,P.version)).map(K=>({version:K.version,dateLabel:vf(K.date),content:Vo(Sf(K.raw)||U)}))}},[n?.body]);return t.jsx(Kt,{open:e,onOpenChange:E?void 0:s,children:t.jsxs(Ht,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(os,{className:"flex items-center gap-2.5",children:[t.jsx(D,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&E&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(D,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!E&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ys,{className:"max-h-[400px] p-0",fillContainer:!1,children:T.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:U=>{const $=U.target.closest("a");$&&$.href&&(U.preventDefault(),U.stopPropagation(),k($.href))},children:t.jsx(Mo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(U=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",U.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:U.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:_=>{const K=_.target.closest("a");K&&K.href&&(_.preventDefault(),_.stopPropagation(),k(K.href))},children:t.jsx(Mo,{content:U.content,disableLinkSafety:!0,enableFileReferences:!1})})]},U.version))})})}),v&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(D,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:S}),t.jsx("button",{onClick:I,className:z("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(D,{name:"check",className:"h-4 w-4"}):t.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]})]}),!v&&!C&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[A,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${A}%`}})})]}),(l||m)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||m})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!C&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!C&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!C&&o&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),C&&t.jsxs(Re,{onClick:j,size:"default",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!E&&t.jsxs("button",{onClick:w,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&E&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Df=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=i.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":o,className:z("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:z("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),pn=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(Fe,{open:r,onOpenChange:o,children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:z("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(D,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Oe,{sideOffset:8,className:z("max-w-sm",n),children:e})]})},fx="w-full min-w-40 max-w-48",hx="settings",Rf="w-full min-w-40 max-w-48",px="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ef="w-full max-w-[24rem]",mx="min-w-0 flex-1",gx="flex w-full min-w-0 items-center gap-2",xx="typography-meta shrink-0 text-muted-foreground tabular-nums",ja="space-y-3.5",Pf="space-y-1.5",bx="typography-settings-page-title text-muted-foreground",Mf="typography-settings-section-title text-foreground",Ca="typography-settings-group-title text-foreground",io="typography-settings-field-label text-foreground",Tf="typography-settings-description text-muted-foreground",mn="typography-meta text-muted-foreground",yx="typography-meta font-medium text-foreground",wx="typography-settings-section-title text-foreground",Ff=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:z("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Mf,children:e}):e,n,r!=null?t.jsx(pn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Tf,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:z(d),children:a})]})},vx=({children:e,className:s})=>t.jsx("div",{className:z("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Lf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:z(Ca,s),children:e}),Sx=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:z("space-y-2",o),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Lf,{children:e}),n!=null?t.jsx(pn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:mn,children:s}):null]}):null,t.jsx("div",{className:z(a),children:r})]}),rn=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:mn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:z("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:z("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},jx=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:z("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),s!=null?t.jsx("p",{className:z(mn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:z("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Cx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:z("pt-4",s),children:e}),Of=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:z("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[t.jsx(Cr,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:io,children:n}),d,u!=null?t.jsx(pn,{children:u}):null]}),h?t.jsx("span",{className:mn,children:r}):null]})]})},kx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:z("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Df,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:z("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:mn,children:r}):null]})]}),Nx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:z(Pf,n),children:s});function Ax({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:z("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Re,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Bf extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(kc,{className:"w-full max-w-md",children:[t.jsx(Nc,{className:"text-center",children:t.jsxs(Ac,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(D,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Ic,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Re,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(D,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function _f(e){return t.jsx(Bf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const Ix=({active:e=!0})=>{const s=ve(n=>n.currentSessionId);return t.jsx(_f,{sessionId:s||void 0,children:t.jsx(Dc,{active:e},s??"no-session")})};function zf({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ka=Me.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:h,...x},g)=>{const m=Me.useRef(null),p=Me.useRef(null),[y,b]=Me.useState(null),A=c??y,v=Me.useCallback(S=>{const I=m.current;if(!I)return;p.current={startY:S.clientY,startHeight:I.getBoundingClientRect().height};const k=S.currentTarget;k.setPointerCapture(S.pointerId);const w=E=>{const T=p.current;if(!T)return;const U=T.startHeight+(E.clientY-T.startY),_=Math.max(82,U);d?d(_):b(_)},j=()=>{p.current=null,k.removeEventListener("pointermove",w),k.removeEventListener("pointerup",j),k.removeEventListener("pointercancel",j)};k.addEventListener("pointermove",w),k.addEventListener("pointerup",j),k.addEventListener("pointercancel",j),S.preventDefault()},[d]),C=Me.useCallback(S=>{if(S.target.closest('textarea, button, [role="separator"]'))return;const k=m.current?.querySelector("textarea");k&&document.activeElement!==k&&(S.preventDefault(),k.focus())},[]);return f?t.jsx(ys,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:z("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:m,onPointerDown:C,style:A!==null?{height:`${A}px`}:void 0,className:z("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:g,className:z("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(zf,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ka.displayName="Textarea";const Na=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],on=Object.fromEntries(Na.map(e=>[e.key,e.Icon])),Ur="pichamber:project-actions-updated",Aa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ns=(e,s)=>`${Aa(e)}::${s}`,Ia=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Ff,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),$r=e=>e.name.trim().length>0&&e.command.trim().length>0,Uf=e=>e.name.trim().length===0&&e.command.trim().length===0,$f=e=>!$r(e)&&!Uf(e),Gf=(e,s)=>e.some(r=>s.has(r.id)&&!$r(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter($r)},Kf=450,Hf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Wf=()=>({id:Hf(),name:"",command:"",icon:"play"}),Yf=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,d]=i.useState(new Set),u=i.useRef(!1);i.useEffect(()=>{let b=!1;return o(!0),(async()=>{try{const A=await kr(e);if(b)return;n(A.actions),l(JSON.stringify({actions:A.actions})),d(new Set(A.actions.map(v=>v.id)))}catch{if(b)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{b||o(!1)}})(),()=>{b=!0}},[e]);const f=i.useMemo(()=>Gf(s,c),[s,c]),h=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=a!==null&&f.canPersist&&h!==a,g=i.useCallback(async b=>await Rc(e,{actions:b,primaryActionId:null})?(l(JSON.stringify({actions:b})),d(new Set(b.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ur,{detail:{projectId:e.id}})),!0):(ie.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!x||r||u.current)return;const b=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await g(f.actions)}finally{u.current=!1}})())},Kf);return()=>{window.clearTimeout(b)}},[x,r,g,f.actions]);const m=i.useCallback(()=>{const b=Wf();n(A=>[...A,b])},[]),p=i.useCallback(b=>{n(A=>A.filter(v=>v.id!==b))},[]),y=i.useCallback((b,A)=>{n(v=>v.map(C=>C.id===b?A(C):C))},[]);return t.jsx(Ia,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Re,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[t.jsx(D,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:z("space-y-6",Ef),children:s.map((b,A)=>{const v=b.icon||"play",C=on[v]||"play",S=b.name.trim()||`Action ${A+1}`,I=$f(b);return t.jsxs("div",{className:ja,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ca,children:S}),t.jsx(Re,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>p(b.id),"aria-label":`Delete ${S}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(rn,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(D,{name:C,className:"h-4 w-4"})})}),t.jsx(Pt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Na.map(k=>{const w=k.Icon,j=(b.icon||"play")===k.key;return t.jsx("button",{type:"button",onClick:()=>y(b.id,E=>({...E,icon:k.key})),className:z("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",j&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${k.label}`,children:t.jsx(D,{name:w,className:"h-4 w-4"})},k.key)})})})]}),t.jsx(ln,{value:b.name,onChange:k=>y(b.id,w=>({...w,name:k.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(rn,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ka,{value:b.command,onChange:k=>y(b.id,w=>({...w,command:k.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),I?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Of,{checked:b.autoOpenUrl===!0,onChange:k=>y(b.id,w=>({...w,...k?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${S}`}),b.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(rn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(ln,{value:b.openUrl||"",onChange:k=>y(b.id,w=>({...w,openUrl:k.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},b.id)})})})},qf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Vf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Gt(w=>w.providers),d=Gt(w=>w.modelsMetadata),u=se(w=>w.hiddenModels),f=se(w=>w.isFavoriteModel),h=se(w=>w.toggleFavoriteModel),x=se(w=>w.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:m}=Ec(),[p,y]=i.useState(!1),[b,A]=i.useState("");i.useEffect(()=>{p||A("")},[p]);const v=e?c.find(w=>w.id===e.providerId):void 0,C=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,S=e?Pc(C,e.modelId):s,I=i.useMemo(()=>e?u.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):u,[u,e]),k=i.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),y(!1)},[l]);return t.jsxs(Rt,{modal:!1,open:p,onOpenChange:w=>{r||y(w)},children:[t.jsx(Et,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:z(Tc({size:"default"}),Rf,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Mc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:z("truncate",e?"text-foreground":"text-muted-foreground"),children:S})]}),t.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Pt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Fc,{providers:c,favoriteModels:g,recentModels:m,modelsMetadata:d,searchQuery:b,onSearchQueryChange:A,onSelect:k,labels:{...qf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:I,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>h(w.providerID,w.modelID),onReorderFavorite:(w,j)=>x(w.providerID,w.modelID,j.providerID,j.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",Qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Gt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Ia,{title:"Project",divider:!1,children:t.jsxs("div",{className:ja,children:[t.jsx(rn,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(ln,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(rn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ar,children:t.jsx(Vf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ar,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Jf=e=>{const[s,n]=i.useState(""),[r,o]=i.useState(void 0);i.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const a=i.useMemo(()=>Lc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=i.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Xf=450,Zf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:a}=e,l=i.useRef(!1);i.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},Xf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},eh=({project:e,onIdentitySave:s})=>{const n=Jf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Zf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Qf,{form:n}),t.jsx(Yf,{projectRef:r})]})};function Da({...e}){return t.jsx(Zi,{...e})}function Ra({...e}){return t.jsx(ea,{...e})}function Ea({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(ta,{children:t.jsx(sa,{className:z("app-region-no-drag z-50",s),children:t.jsx(na,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:z(Ri,e),...o,children:n})})})}function Gr({className:e,...s}){return t.jsx(ra,{className:z(Ei,e),...s})}function th({className:e,...s}){return t.jsx(oa,{className:z(Pi,e),...s})}const kn=100;function Dx(){const e=se(w=>w.isArchivePageOpen),s=se(w=>w.setArchivePageOpen),n=se(w=>w.setActiveMainTab),r=ve(w=>w.setCurrentSession),o=ve(w=>w.unarchiveSession),a=Bs(w=>w.homeDirectory),l=Nr({archived:!0}),[c,d]=i.useState(""),[u,f]=i.useState(null),[h,x]=i.useState(kn),g=c.trim().toLowerCase(),m=i.useMemo(()=>e?[...l].sort((w,j)=>(j.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),p=i.useMemo(()=>{const w=new Map;for(const j of m){const E=ye(Ts(j))??"",T=w.get(E);if(T){T.sessions.push(j);continue}w.set(E,{directory:E,label:E?_s(E,a)||E:"other projects",sessions:[j]})}return[...w.values()].sort((j,E)=>E.sessions.length-j.sessions.length)},[a,m]),y=i.useMemo(()=>g?m.filter(w=>(w.title??"").toLowerCase().includes(g)):u===null?m:p.find(w=>w.directory===u)?.sessions??[],[p,g,u,m]),b=y.slice(0,h),A=y.length-b.length,v=l.length,C=i.useCallback(w=>{f(w),x(kn)},[]),S=i.useCallback(w=>{const j=ye(Ts(w));r(w.id,j??void 0),n("chat"),s(!1)},[n,r,s]),I=i.useCallback(w=>{o(w.id).then(j=>{j?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const k=(w,j,E,T,U,_,$)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:U,title:_,className:z("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",$?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",T?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:j}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),$?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Cs.requestDelete({sessions:$,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${j}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return t.jsx(yu,{open:e,onOpenChange:s,children:t.jsxs(wu,{children:[t.jsx(vu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Su,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(ju,{className:"sr-only",children:"Archived sessions"}),t.jsx(Cu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(ku,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(D,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[k("__all__","All directories",v,u===null,()=>C(null)),p.map(w=>k(w.directory||"__none__",w.label,w.sessions.length,u===w.directory,()=>C(w.directory),w.directory||void 0,w.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:w=>{d(w.target.value),x(kn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:y.length===1?`${y.length} archived session`:`${y.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[b.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):b.map(w=>{const j=ye(Ts(w))??"",E=j?_s(j,a)||j:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>S(w),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),S(w))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:ds(w)}),g&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:j,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:cu(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),I(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${ds(w)}`,children:t.jsx(D,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),Cs.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${ds(w)}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),A>0?t.jsx("button",{type:"button",onClick:()=>x(w=>w+kn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const Pa=380,lr=8,sh=140;function nh({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[d,u]=i.useState(!1),[f,h]=i.useState(null),{enabled:x}=Vr();return i.useLayoutEffect(()=>{if(!e||!x||!l)return;const g=()=>{const y=n.current?.getBoundingClientRect(),b=a.current?.getBoundingClientRect();if(!y||!b){h(null);return}const A=y.left-b.left;h(Math.min(Math.max(A,lr),Math.max(lr,b.width-Pa-lr)))};g();const m=a.current;if(typeof ResizeObserver>"u"||!m)return;const p=new ResizeObserver(g);return p.observe(m),()=>p.disconnect()},[n,x,e,l]),i.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const g=window.setTimeout(()=>{c(!1),u(!1)},sh);return()=>window.clearTimeout(g)},[e,l]),i.useEffect(()=>{if(!e)return;const g=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[s,e]),i.useEffect(()=>{if(!e)return;const g=m=>{const p=m.target;if(!(p instanceof Node)){s();return}o.current?.contains(p)||n.current?.contains(p)||s()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const Jo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},_n=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Nn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(D,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),rh=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=nh({open:e,onClose:s,anchorRef:n,closeOnWheel:!0});return l?t.jsxs("div",{ref:a,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:z("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...u?{top:8,left:d??8,width:`min(${Pa}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{iconNode:t.jsx(Mi,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:z("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:_n(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:_n(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Nn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
|
|
3
|
-
@keyframes session-metadata-in {
|
|
4
|
-
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
|
-
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
6
|
-
}
|
|
7
|
-
@keyframes session-metadata-out {
|
|
8
|
-
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
9
|
-
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
10
|
-
}
|
|
11
|
-
`})]}):null},oh=i.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:a}){const l=i.useRef(null),c=Oc(r??""),d=Gt(P=>P.providers),u=Gt(P=>P.currentProviderId),f=Gt(P=>P.currentModelId),h=Gt(P=>P.getCurrentModel()),x=Gt(P=>P.getModelMetadata);Gt(P=>P.modelsMetadata.size);const g=Bc(i.useCallback(P=>r?P.sessionModelSelections.get(r)??null:null,[r])),m=i.useMemo(()=>{for(let P=c.length-1;P>=0;P-=1){const B=c[P]?.info;if(B.role!=="user")continue;const R=B.model,F=R?.providerID??R?.providerId,V=R?.modelID??R?.modelId,G=typeof F=="string"&&F.trim().length>0?F:void 0,M=typeof V=="string"&&V.trim().length>0?V:void 0;if(G&&M)return{providerID:G,modelID:M}}return null},[c]),p=i.useMemo(()=>{for(let P=c.length-1;P>=0;P-=1){const B=c[P];if(B?.info.role==="assistant"&&To(B).total>0)return B}return null},[c]),y=m??(()=>{const P=p?.info.model,B=P?.providerID??P?.providerId,R=P?.modelID??P?.modelId;return B&&R?{providerID:B,modelID:R}:null})()??(g?{providerID:g.providerId,modelID:g.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),A=(y?d.find(P=>P.id===y.providerID):void 0)?.models.find(P=>P.id===y?.modelID),v=y?x(y.providerID,y.modelID):void 0,C=Jo(A?.limit,"context")??v?.limit?.context??Jo(h?.limit,"context")??0,S=p?To(p):null,I=p?.info?.usage,k=I?_c(I):S?.total??0,w=!a&&k>0&&C>0?Math.min(k/C*100,999):null,j=w!==null?`${_n(k)}/${_n(C)}`:null,E=w===null?"":w>=90?"text-[var(--status-error)]":w>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",T=S?.cacheRead??null,U=S?.cacheWrite??null,_=S?zc({input:S.input,cache:{read:S.cacheRead,write:S.cacheWrite}}):{percent:0,hasInput:!1},$=_.hasInput?_.percent:null,K=w!==null&&j?{percentage:w,tokens:j,colorClass:E,cacheRead:T,cacheWrite:U,cacheHitPercent:$}:null;return t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:l,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":s,onClick:()=>n(P=>!P),style:{touchAction:"manipulation"},children:t.jsx(Mi,{percentage:K?.percentage??0,size:20,className:"size-5 -rotate-90"})}),t.jsx(rh,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:K})]})}),Xo=600,ih=1,ah=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},lh=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:o})=>{const a=i.useRef(new Map),l=i.useRef([]),c=i.useRef(new Set),d=i.useRef(0),u=!1,f=i.useCallback(m=>`${m.directory}
|
|
12
|
-
${m.sessionId}`,[]),h=i.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(m=>window.clearTimeout(m)),a.current.clear()},[]),x=i.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<ih&&l.current.length>0;){const m=l.current.shift();if(!m)break;m.generation!==d.current||ve.getState().currentSessionId===m.sessionId||Uc(m.sessionId,m.directory).renderable}},[e,u,o,f]),g=i.useCallback(m=>{const p=m?.id,y=ah(m);if(!e||u||!p||!y||p===s||typeof window>"u")return;const b={sessionId:p,directory:y,generation:d.current};f(b)},[s,e,u,x,f]);i.useEffect(()=>{h()},[h,s,e,u]),i.useEffect(()=>{if(!e||u||!s||n.length===0)return;const m=window.setTimeout(()=>{const p=n.findIndex(y=>y.id===s);p<0||(g(n[p-1]),g(n[p+1]))},Xo);return()=>window.clearTimeout(m)},[s,e,u,g,n]),i.useEffect(()=>{if(!e||u||!s||r.length===0)return;const m=window.setTimeout(()=>{const p=r.findIndex(y=>y.id===s);p<0||(g(r[p-1]),g(r[p+1]))},Xo);return()=>window.clearTimeout(m)},[s,e,u,r,g]),i.useEffect(()=>h,[h])},ch=e=>{const s=ve(n=>n.currentSessionId);return lh({...e,currentSessionId:s}),null},dh=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:o,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:f}=e;i.useEffect(()=>{!n||o||!a||l||s.forEach(h=>{if(c.has(h.normalizedPath))return;const x=Qi(h.normalizedPath),g=r.archivedSessionsByProject.get(h.id)??[],m=d[x]??[],p=new Map(m.map(y=>[y.name.toLowerCase(),y]));g.forEach(y=>{const b=du(y,h.normalizedPath),A=b.toLowerCase();let v=p.get(A);v||(v=u(x,b),p.set(A,v)),v.sessionIds.includes(y.id)||f(x,v.id,y.id)})})},[s,n,r,o,a,l,c,d,u,f])},uh=e=>({getOrderedGroups:i.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];o.forEach(u=>{const f=a.get(u);f&&(l.push(f),a.delete(u))});const c=[],d=[];return r.forEach(u=>{a.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[e])}),fh=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:h,buildGroupSearchText:x,foldersMap:g}=e,m=i.useRef(new Map),p=i.useMemo(()=>{const k=m.current,w=new Map;let j=0,E=0;const T=(_,$)=>_.length===$.length&&_.every((K,P)=>K===$[P]),U=s.map(_=>{const $=n(_.id),K=r(_.id),P=a.has(_.id)?!!a.get(_.id):c,B=l.get(_.id)??null,R=o.get(_.normalizedPath)??[],F=k.get(_.id);if(F&&F.project===_&&T(F.activeSessions,$)&&T(F.archivedSessions,K)&&F.rootBranch===B&&F.isRepo===P&&F.worktrees===R&&F.buildGroupedSessions===d)return j+=1,w.set(_.id,F),F.section;E+=1;const V=Ji([...$,...K]),G=d(V,_.normalizedPath,R,B,P),M={project:_,groups:G};return w.set(_.id,{project:_,activeSessions:$,archivedSessions:K,rootBranch:B,isRepo:P,worktrees:R,buildGroupedSessions:d,section:M}),M});return m.current=w,j>0&&Ft("ui.sidebar.project_section.reused",j),E>0&&Ft("ui.sidebar.project_section.rebuilt",E),U},[s,n,r,o,a,c,d,l]),y=i.useMemo(()=>p,[p]),b=i.useMemo(()=>{const k=new WeakMap;if(!u)return k;const w=j=>j.reduce((E,T)=>E+1+w(T.children),0);return y.forEach(j=>{j.groups.forEach(E=>{const T=h(E.sessions,f),U=w(T),_=x(E).includes(f),$=ye(E.directory??null),P=($?g[$]??[]:[]).filter(B=>B.name.toLowerCase().includes(f)).length;k.set(E,{filteredNodes:T,matchedSessionCount:U,folderNameMatchCount:P,groupMatches:_,hasMatch:_||U>0||P>0})})}),k},[u,y,h,f,x,g]),A=i.useMemo(()=>u?y.map(k=>({...k,groups:k.groups.filter(w=>b.get(w)?.hasMatch===!0)})).filter(k=>k.groups.length>0):y,[u,y,b]),v=u?A:y,C=i.useRef(new WeakMap),S=i.useMemo(()=>{const k=C.current;return v.map(w=>{const j=k.get(w);if(j&&j.query===f)return j.section;const E=w.groups.filter(B=>!B.isArchivedBucket),T=w.groups.filter(B=>B.isArchivedBucket),U=E.flatMap(B=>u?b.get(B)?.filteredNodes??[]:B.sessions),_=E.map(B=>({scopeKey:B.folderScopeKey??ye(B.directory??null),directory:B.directory??null})).filter(B=>!!B.scopeKey),$=E.find(B=>B.isMain)??null,K={id:"flat",label:$?.label??"",branch:$?.branch??null,description:$?.description??null,isMain:!0,isArchivedBucket:!1,directory:$?.directory??w.project.normalizedPath,folderScopeKey:$?.folderScopeKey??w.project.normalizedPath,folderScopes:_,sessions:U};if(u){const B=E.map(R=>b.get(R)).filter(R=>!!R);b.set(K,{filteredNodes:U,matchedSessionCount:B.reduce((R,F)=>R+F.matchedSessionCount,0),folderNameMatchCount:B.reduce((R,F)=>R+F.folderNameMatchCount,0),groupMatches:B.some(R=>R.groupMatches),hasMatch:B.some(R=>R.hasMatch)})}const P={project:w.project,groups:[K,...T]};return k.set(w,{query:f,section:P}),P})},[b,u,f,v]),I=i.useMemo(()=>u?v.reduce((k,w)=>k+w.groups.reduce((j,E)=>{const T=b.get(E);if(!T)return j;const U=T.folderNameMatchCount+(T.groupMatches?1:0);return j+T.matchedSessionCount+U},0),0):0,[u,v,b]);return{projectSections:p,visibleProjectSections:y,groupSearchDataByGroup:b,searchableProjectSections:A,sectionsForRender:v,flatSectionsForRender:S,searchMatchCount:I}},hh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:h}=e,x=i.useMemo(()=>{const m=new Map,p=new Map,y=(b,A,v,C)=>{m.has(b)||m.set(b,new Map);const S=m.get(b);C.forEach(I=>{const k=ye(I.session.directory??v??A);S.set(I.session.id,{directory:k}),p.has(b)||p.set(b,{id:I.session.id,directory:k}),I.children.length>0&&y(b,A,k,I.children)})};return s.forEach(b=>{b.groups.forEach(A=>{y(b.project.id,b.project.normalizedPath,A.directory,A.sessions)})}),{metaByProject:m,firstSessionByProject:p}},[s]),g=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){g.current=n;return}if(g.current===n)return;const m=s.find(I=>I.project.id===n);if(!m)return;g.current=n;const p=x.metaByProject.get(n);if(a&&p&&p.has(a)){o(I=>{if(I.get(n)===a)return I;const k=new Map(I);return k.set(n,a),k});return}const y=a?Array.from(x.metaByProject.entries()).some(([I,k])=>I!==n&&k.has(a)):!1;if(a&&p&&!y)return;if(!p||p.size===0){f("chat"),d&&h(!1),u({selectedProjectId:m.project.id,directoryOverride:m.project.normalizedPath});return}const b=r.get(n),A=b&&p.has(b)?b:null,v=x.firstSessionByProject.get(n)?.id??null,C=A??v;if(!C||C===a)return;const S=p.get(C)?.directory??null;l(C,S,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,x,f,h,o]),i.useEffect(()=>{if(!n||!a)return;const m=x.metaByProject.get(n);!m||!m.has(a)||o(p=>{if(p.get(n)===a)return p;const y=new Map(p);return y.set(n,a),y})},[n,a,x,o])},ph=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=ve(c=>c.currentSessionId),o=ve(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return hh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},Zo=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],mh=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},gh=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,Ma=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=mh(e.trim())%Zo.length;return Zo[s]},xh=(e,s)=>{const n=Ma(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},ei=e=>!!e.time?.archived,bh=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=ye(a.directory??null)??"";return`${ds(a)} ${l}`.toLowerCase()},[]),r=i.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):a,[n]),o=i.useCallback((a,l,c=[],d,u)=>{const f=ye(l??null),h=Ji(a).sort((k,w)=>Qr(k,w,e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(h.map(k=>[k.id,k])),g=new Map,m=new Map;h.forEach(k=>{const w=k.parentID??null,j=w?x.get(w):null,E=j&&ei(j)===ei(k)?w:null;g.set(k.id,E),E&&m.set(E,(m.get(E)??0)+1)});const p=c.map(k=>({worktree:k,directory:ye(k.path)})).filter(k=>!!k.directory&&!k.worktree.isPrimary).sort((k,w)=>w.directory.length-k.directory.length),y=(k,w)=>w===k||w.startsWith(`${k}/`),b=k=>{const w=ye(k.directory??null);return w?p.find(j=>y(j.directory,w))?.worktree??null:null},A=(k,w)=>{const j=gh(k.id,g,m);return{session:k,children:[],worktree:w,forkColorId:j}},v=[],C=new Map,S=[];for(const k of p)C.set(k.directory,[]);h.forEach(k=>{const w=b(k),j=A(k,w);k.time?.archived?S.push(j):w?C.get(ye(w.path)??"")?.push(j):v.push(j)});const I=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?Bo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:v}];for(const{worktree:k,directory:w}of p)I.push({id:`worktree:${w}`,label:k.branch||(k.detached?"Detached HEAD":k.name),branch:k.branch,description:Bo(w,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:k,directory:w,folderScopeKey:w,sessions:C.get(w)??[]});return S.length>0&&I.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?Qi(f):null,sessions:S}),I},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},yh=({mobileVariant:e,isTablet:s})=>!e&&!s,wh=({enabled:e=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{i.useEffect(()=>{if(!e||!s||typeof window>"u")return;const a=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(a)},[e,s,r]),i.useEffect(()=>{if(!e||!s||typeof document>"u")return;const a=l=>{o.current&&(o.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e,s,n,o])},vh=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((v,C,S)=>{Rr("navigation.session_select"),se.getState().closeMainSurfaces();const I=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},k=S?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===ve.getState().currentSessionId){e.allowReselect&&k&&e.onSessionSelected?.(v),I();return}Rr("navigation.session_state_set"),e.setCurrentSession(v,C??null),k&&e.onSessionSelected?.(v),I()},[e]),a=i.useCallback((v,C)=>{e.setEditingId(v),e.setEditTitle(C)},[e]),l=i.useCallback(async v=>{if(!e.editingId)return;const C=(v??e.editTitle).trim();C&&await e.updateSessionTitle(e.editingId,C),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=i.useCallback(async(v,C)=>{try{return(await cn(v)).ok?(n(C),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=i.useCallback(async v=>{const C=await e.shareSession(v.id);if(!C?.share?.url){ie.error("Unable to share session");return}const S=await d(C.share.url,v.id);ie[S?"success":"warning"]("Session shared",{description:S?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=i.useCallback((v,C)=>{d(v,C).then(S=>{S||ie.error("Failed to copy URL")})},[d]),h=i.useCallback(v=>{cn(v).then(C=>{if(C.ok){ie.success("Session ID copied");return}ie.error("Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[]),x=i.useCallback(async v=>{await e.unshareSession(v)?ie.success("Session unshared"):ie.error("Unable to unshare session")},[e]),g=i.useCallback(v=>{const C=[],S=I=>{(e.childrenMap.get(I)??[]).forEach(w=>{C.push(w),S(w.id)})};return S(v),C},[e.childrenMap]),m=i.useCallback((v,C)=>C?v:v.filter(S=>!S.time?.archived),[]),p=i.useCallback(async(v,C,S)=>{const I=C?.archivedBucket===!0||C?.hardDelete===!0,k=S?.descendantIds??m(g(v.id),I).map(T=>T.id);if(k.length===0){(I?await e.deleteSession(v.id):await e.archiveSession(v.id))?ie.success(I?"Session deleted":"Session archived"):ie.error(I?"Failed to delete session":"Failed to archive session");return}const w=[v.id,...k];if(I){const{deletedIds:T,failedIds:U}=await e.deleteSessions(w);if(U.length===0){const _=T.length;ie.success(_===1?`Deleted ${_} session`:`Deleted ${_} sessions`)}else ie.error("Failed to delete session");return}const{archivedIds:j,failedIds:E}=await e.archiveSessions(w);j.length>0&&ie.success(j.length===1?`Archived ${j.length} session`:`Archived ${j.length} sessions`),E.length>0&&ie.error(E.length===1?`Failed to archive ${E.length} session`:`Failed to archive ${E.length} sessions`)},[e,g,m]),y=i.useCallback((v,C)=>{const S=C?.archivedBucket===!0||C?.hardDelete===!0,I=m(g(v.id),S).map(k=>k.id);if(!e.showDeletionDialog||C?.skipConfirm===!0){p(v,C,{descendantIds:I});return}e.setDeleteSessionConfirm({session:v,descendantCount:I.length,descendantIds:I,archivedBucket:S})},[e,g,p,m]),b=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,archivedBucket:C,descendantIds:S}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await p(v,{archivedBucket:C},{descendantIds:S})},[e,p]),A=i.useCallback(async v=>{await e.unarchiveSession(v.id)?ie.success("Session restored"):ie.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:h,handleUnshareSession:x,handleDeleteSession:y,handleRestoreSession:A,confirmDeleteSession:b}},Sh=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:a,setCollapsedProjects:l}=e,c=i.useRef(null),d=i.useRef(null),u=i.useCallback(()=>{const h=d.current;if(d.current=null,c.current=null,!h)return;const{projects:x}=dt.getState(),g=x.map(m=>({...m,sidebarCollapsed:h.has(m.id)}));Zr({projects:g}).catch(()=>{})},[]),f=i.useCallback(h=>{typeof window>"u"||(d.current=h,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return i.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),i.useEffect(()=>{try{const h=s.getItem(n.sessionExpanded);if(h){const g=JSON.parse(h);Array.isArray(g)&&a(new Set(g.filter(m=>typeof m=="string")))}const x=s.getItem(n.projectCollapse);if(x){const g=JSON.parse(x);Array.isArray(g)&&l(new Set(g.filter(m=>typeof m=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const h=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(h))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:f}},jh=3;let zn=0;const Ta=[],Ch=()=>zn<jh?(zn+=1,Promise.resolve()):new Promise(e=>{Ta.push(e)}),kh=()=>{const e=Ta.shift();if(e){e();return}zn=Math.max(0,zn-1)},Nh=async e=>{await Ch();try{return await e()}finally{kh()}},Ah=5*6e4,Ih=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=Gs(),c=Ti(h=>h.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(h=>{Nh(()=>c(h.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const h=new Map;s.forEach(x=>{h.set(x.id,r.get(x.normalizedPath)?.isGitRepo??null)}),o(h)},[n,s,r,o]);const d=i.useMemo(()=>s.map(h=>{const x=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${x}`}).join("|"),[s,r]),u=i.useRef(new Map),f=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let h=!1;const x=setTimeout(()=>{(async()=>{const m=new Set(s.map(v=>v.id));for(const v of u.current.keys())m.has(v)||(u.current.delete(v),f.current.delete(v));const p=Date.now();if(s.filter(v=>{const C=r.get(v.normalizedPath);if(C?.isGitRepo===!1)return u.current.delete(v.id),f.current.delete(v.id),!1;if(C?.isGitRepo!==!0||C.branch===null)return!1;const S=C.branch.trim(),I=`${v.normalizedPath}\0${S}`,k=u.current.get(v.id);if(k===I){const w=f.current.get(v.id);return w&&(w.at=p),!1}return!(k!==void 0&&p-(f.current.get(v.id)?.at??0)<Ah)}).length===0)return;const b=[];if(s.forEach(v=>{const C=r.get(v.normalizedPath)?.branch?.trim()??"",S=`${v.normalizedPath}\0${C}`;C&&b.push({id:v.id,inputKey:S,branch:C})}),h||b.length===0)return;const A=Date.now();a(v=>{const C=new Map(v);return b.forEach(({id:S,branch:I})=>{I&&C.set(S,I)}),C}),b.forEach(({id:v,inputKey:C,branch:S})=>{u.current.set(v,C),S&&f.current.set(v,{branch:S,at:A})})})()},150);return()=>{h=!0,clearTimeout(x)}},[n,s,d,r,a])},Dh=e=>{const{ownership:s}=e,n=i.useCallback(o=>s.sessionsByProject.get(o)??[],[s]),r=i.useCallback(o=>s.archivedSessionsByProject.get(o)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Rh=e=>{if(e.runtimeKey!==Wn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=Hd(e.sessionId,e.directory,e.runtimeKey);s&&Wd.getState().clearQueue(s),lt.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),Ar.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=$c(e.runtimeKey,e.directory,e.sessionId);n&&Gc(n,!0),Kc.getState().clearStashedAttachmentsForSession(e)},Eh=e=>{const s=new Map;for(const n of e){const r=Ts(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Ph=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},Mh=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Wn(),l=Eh(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const d of Ph(c,l))Rh({runtimeKey:a,...d});o.current={runtimeKey:a,identities:l}},[s,n,r])},Th=(e,s)=>e?s.kind!==e.kind?s.kind==="project":s.projectRoot.length!==e.projectRoot.length?s.projectRoot.length>e.projectRoot.length:s.projectId.localeCompare(e.projectId)<0:!0,ti=(e,s,n)=>{Th(e.get(s),n)&&e.set(s,n)},Fa=e=>{const s=e;return ye(s.directory)??ye(s.project?.worktree)},Fh=(e,s,n)=>{if(e.time?.archived)return!0;const r=Fa(e);if(!r)return n?.allowUnknownDirectory??!0;if(Hn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const a of s)if(ye(a)?.toLowerCase()===o)return!0;return!1},Lh=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const s=e.lastIndexOf("/");return s<0?null:s===0?"/":s===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,s)},Oh=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const g of s){const m=ye(g.normalizedPath);if(!m)continue;const p=a.get(m);(!p||g.id.localeCompare(p.id)<0)&&a.set(m,g),ti(o,m,{projectId:g.id,projectRoot:m,scopeDirectory:m,kind:"project"})}if(n)for(const[g,m]of n){const p=ye(g),y=p?a.get(p):void 0;if(!(!y||!p))for(const b of m||[]){const A=ye(b?.path);A&&ti(o,A,{projectId:y.id,projectRoot:p,scopeDirectory:A,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,f=new Map,h=g=>{if(!g)return null;if(l.has(g))return l.get(g)??null;const m=[];let p=g,y=null;for(;p;){if(l.has(p)){y=l.get(p)??null;break}if(m.push(p),y=o.get(p)??null,y)break;p=Lh(p)}for(const b of m)l.set(b,y);return y},x=(g,m,p)=>{for(const y of g){const b=Fa(y);if(Hn(b))continue;const A=h(b);if(!A)continue;c.set(y.id,A);const v=m.get(A.projectId);if(v?v.push(y):m.set(A.projectId,[y]),!p)continue;const C=p.get(A.scopeDirectory);C?C.add(y.id):p.set(A.scopeDirectory,new Set([y.id]))}};return x(e,d,f),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:l.size}};function La({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:z("inline-flex items-center",r),"aria-label":n??s,title:n??s,children:t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):t.jsx("span",{className:z("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx($s,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Bh=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:h,projectId:x,mobileVariant:g=!1,alwaysShowActions:m=g,isRenaming:p=!1,renameDraft:y="",onRenameDraftChange:b,onRenameSave:A,onRenameCancel:v,droppableRef:C,isDropTarget:S=!1,onNewSession:I,depth:k=0,hideActions:w=!1,archivedBucket:j=!1})=>{const[E,T]=i.useState(!1),[U,_]=i.useState(""),$=i.useRef(null),K=p||E,P=p?y:U,B=i.useCallback(()=>{_(e.name),T(!0)},[e.name]),R=i.useCallback(()=>{const M=P.trim();M&&M!==e.name&&c(M),p&&A&&A(),T(!1),_("")},[P,e.name,p,c,A]),F=i.useCallback(()=>{p&&v&&v(),T(!1),_("")},[p,v]),V=i.useCallback(M=>{p&&b?b(M):_(M)},[p,b]);i.useEffect(()=>{if(!p)return;const M=()=>{const we=$.current;we&&(we.focus(),we.select())},ee=requestAnimationFrame(M),H=window.setTimeout(M,0);return()=>{cancelAnimationFrame(ee),window.clearTimeout(H)}},[p]);const G=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:C,className:z("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",S&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:K?void 0:M=>{M.currentTarget.blur(),l()},role:K?void 0:"button",tabIndex:K?void 0:0,onKeyDown:K?void 0:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:z("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",j?m?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":m?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(D,{name:G,className:z(En,S?"text-primary":"text-muted-foreground")}),K?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),onSubmit:M=>{M.preventDefault(),R()},children:[t.jsx("input",{ref:$,value:P,onChange:M=>V(M.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:M=>M.stopPropagation(),onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),onKeyDown:M=>{if(M.key==="Escape"){M.stopPropagation(),F();return}(M.key===" "||M.key==="Enter")&&M.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:M=>M.stopPropagation(),onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),children:t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),F()},onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("span",{className:z(Xi,S?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(Oe,{side:"right",sideOffset:8,className:"max-w-xs",children:s??e.name})]}),t.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),a?t.jsx(La,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(D,{name:"arrow-right-s",className:z(En,"text-muted-foreground")}):t.jsx(D,{name:"arrow-down-s",className:z(En,"text-muted-foreground")})]})]}),!K&&(!w||j)?t.jsx("div",{className:z("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",m?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:t.jsxs("div",{className:"flex items-center gap-0.5",children:[!j&&I?t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),I()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${e.name}`,title:"New session",children:t.jsx(D,{name:"add",className:"size-4"})}):null,j?null:t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),B()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:t.jsx(D,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":j?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(D,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(M=>t.jsx(i.Fragment,{children:u(M,0,h??null,x??null,j,void 0,"project",f?.(M))},M.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},_h=i.memo(Bh),zh=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=Nu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),d=i.useCallback(u=>{u.stopPropagation(),a?.onPointerDown&&a.onPointerDown(u)},[a]);return t.jsx("div",{ref:l,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Uh=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Au({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},$h=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=so(On(ia,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,d]=i.useState("Session"),[u,f]=i.useState(null),[h,x]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const g=m=>{l(null),f(null),x(null);const{active:p,over:y}=m;if(!y)return;const b=p.data.current,A=y.data.current;b?.type==="session"&&b.sessionId&&A?.type==="folder"&&A.folderId&&n(b.sessionId,A.folderId)};return t.jsxs(no,{sensors:o,collisionDetection:ro,onDragStart:m=>{const p=m.active.data.current;if(p?.type==="session"&&p.sessionId){l(p.sessionId),d(p.sessionTitle??"Session");const y=m.active.rect.current.initial?.width,b=m.active.rect.current.initial?.height;f(typeof y=="number"?y:null),x(typeof b=="number"?b:null)}},onDragCancel:()=>{l(null),f(null),x(null)},onDragEnd:g,children:[r,t.jsx(aa,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:h?`${h}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[t.jsx(D,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),t.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},js=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:z(o?uu:fu,r),children:[t.jsx(D,{name:e,className:z(un(o),"text-muted-foreground")}),t.jsx("span",{className:z(fn(o),"flex-1 text-muted-foreground"),children:s})]}),si=(e,s,n)=>{if(!s)return;const r=o=>{let a=o.session.id===s;for(const l of o.children)a=r(l)||a;return a&&n.add(o.session.id),a};for(const o of e)r(o)},rs=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(rs(n,s))return!0;return!1},Gh=(e,s,n)=>{const r=new Map,o=a=>{const l=Ts(a.session)??n;if(l){const c=r.get(l)??[];c.push(a.session.id),r.set(l,c)}if(!(a===e&&s))for(const c of a.children)o(c)};return o(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},Kh=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let a=r.session.parentID??null;for(;a&&!o.has(a);){if(n.has(a)&&s.has(a))return!1;o.add(a),a=s.get(a)?.session?.parentID??null}return!0})},ni=new WeakMap;let ri=1;const Hh=e=>{const s=ni.get(e);if(s!==void 0)return s;const n=ri;return ri+=1,ni.set(e,n),n},Kr=e=>e.children.length===0?"":e.children.map(n=>{const r=Hh(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Kr(n)}`}).join("|"),Oa=(e,s,n,r,o,a)=>{const l=Wn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,h=u.session.directory??a,x=Fo(l,f??"",d.session.id),g=Fo(l,h??"",u.session.id);return(x?n.has(x):!1)!==(g?r.has(g):!1)?!0:d.children.some((m,p)=>c(m,u.children[p]))};return c(e,s)},Un=(e,s,n,r)=>{if(!s)return null;const o=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${o}:${c.session.id}`===s)return a=c.session.id,!0;for(const u of c.children)if(l(u))return!0;return!1};return e.forEach(c=>l(c)),a},Ba=(e,s)=>"",Wh=hs(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),_a=e=>null,ao=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,za=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let o=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(o="unread");for(const l of e.children)if(o=ao(o,za(l,s,n,r)),o==="active")return o;return o},Ua=(e,s,n,r)=>{let o=null;for(const a of e)if(o=ao(o,za(a,s,n,r)),o==="active")return o;return o},Yh=50,qh=28;function Vh({visibleSessions:e,shouldVirtualize:s,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:a,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:d}){const u=i.useRef(null),[f,h]=i.useState(null),[x,g]=i.useState(0),[,m]=i.useState(0);i.useEffect(()=>{if(!s)return;const b=u.current;if(!b||typeof ResizeObserver>"u")return;const A=new ResizeObserver(()=>m(v=>v+1));return A.observe(b),()=>A.disconnect()},[s]),i.useLayoutEffect(()=>{if(!s){f!==null&&h(null),x!==0&&g(0);return}const b=u.current;if(!b)return;let A=f;const v=r?.current??null;if(v&&v.contains(b)){if(A=v,A!==f){h(A);return}}else if(!A||!A.contains(b)){let S=b.parentElement;for(;S;){const I=window.getComputedStyle(S);if(I.overflowY==="auto"||I.overflowY==="scroll"){A=S;break}S=S.parentElement}if(A!==f){h(A);return}}if(!A)return;const C=b.getBoundingClientRect().top-A.getBoundingClientRect().top+A.scrollTop;g(S=>Math.abs(S-C)<1?S:C)},[f,x,r,s]);const p=s&&f!==null,y=Ru({count:e.length,enabled:p,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>qh,overscan:n?20:8,scrollMargin:x,getItemKey:b=>e[b]?.session.id??b});return t.jsx("div",{ref:u,children:s?t.jsx("div",{style:{height:y.getTotalSize(),position:"relative"},children:y.getVirtualItems().map(b=>{const A=e[b.index];return A?t.jsx("div",{"data-index":b.index,ref:y.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${b.start-x}px)`},children:c(A,0,o,a,l,void 0,"project",d(A))},A.session.id):null})}):e.map(b=>t.jsx(i.Fragment,{children:c(b,0,o,a,l,void 0,"project",d(b))},b.session.id))})}const Tn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),o=r.length;if(o===0)return e;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(e.slice(l,c));const d=e.slice(c,c+o);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e};function Qh({group:e,groupKey:s,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:a,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:h,statusLine:x,allGroupSessions:g,projectId:m,activeProjectId:p,setActiveProjectIdOnly:y,setActiveMainTab:b,mobileVariant:A,setSessionSwitcherOpen:v,openNewSessionDraft:C}){return t.jsxs("div",{className:z("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(s),role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),r(s))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[t.jsx("div",{ref:c?.setActivatorNodeRef,className:z("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.listeners??{},children:t.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[t.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:e.isArchivedBucket?t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(D,{name:"archive",className:z("size-4 shrink-0 text-muted-foreground",a?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:z("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(D,{name:"arrow-right-s",className:"size-4"}):t.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:Tn(e.label,o)}),f]}):!e.isMain||e.worktree?t.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(D,{name:"git-branch",className:z("size-4 shrink-0",!d&&"text-muted-foreground",a?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),t.jsx("span",{className:z("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(D,{name:"arrow-right-s",className:"size-4"}):t.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Tn(e.label,o)}),f,u?t.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:d?{color:d}:void 0,children:["#",u.number]}):null]}):t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"min-w-0 truncate",children:Tn(e.label,o)}),f]})}),h&&x?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?t.jsx(D,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(D,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),t.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:x.label})]}):null]})}),e.isArchivedBucket&&g.length>0?t.jsx("div",{className:z("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),Cs.requestDelete({sessions:g,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${e.label}`,children:t.jsx(D,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?t.jsx("div",{className:z("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),m&&m!==p&&y(m),b("chat"),A&&v(!1),C({selectedProjectId:m,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:t.jsx(D,{name:"add",className:"h-4 w-4"})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]})}const An=(e,s)=>s?e.sessions.some(n=>rs(n,s)):!1,Jh=(e,s,n)=>e.sessions.some(r=>Oa(r,r,s,n,e.directory,e.directory)),Xh=(e,s,n)=>{const r=o=>{const a=o.session.id;return s.get(a)!==n.get(a)?!0:o.children.some(r)};return e.sessions.some(r)},oi=(e,s,n)=>{const r=o=>s.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Zh=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},ep=(e,s,n)=>{const r=e.isArchivedBucket?"archived":"active",o=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(o)};return e.sessions.some(o)},tp=(e,s)=>{if(e.group!==s.group||e.groupKey!==s.groupKey||e.projectId!==s.projectId||e.hideGroupLabel!==s.hideGroupLabel||e.compactBodyPadding!==s.compactBodyPadding||e.groupSearchDataByGroup!==s.groupSearchDataByGroup||e.visibleSessionCount!==s.visibleSessionCount||e.collapsedGroups!==s.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==s.collapsedGroups.has(s.groupKey)||e.pinnedSessionIds!==s.pinnedSessionIds&&Jh(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&ep(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&Xh(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(An(e.group,e.editingId)||An(s.group,s.editingId))||e.editTitle!==s.editTitle&&(An(e.group,e.editingId)||An(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Un(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Un(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&oi(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&oi(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&Zh(s.group,s.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===s.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===s.normalizedSessionSearchQuery&&e.hideDirectoryControls===s.hideDirectoryControls&&e.collapsedFolderIds===s.collapsedFolderIds&&e.toggleFolderCollapse===s.toggleFolderCollapse&&e.renameFolder===s.renameFolder&&e.deleteFolder===s.deleteFolder&&e.showDeletionDialog===s.showDeletionDialog&&e.setDeleteFolderConfirm===s.setDeleteFolderConfirm&&e.renderSessionNode===s.renderSessionNode&&e.showMoreGroupSessions===s.showMoreGroupSessions&&e.resetGroupSessionLimit===s.resetGroupSessionLimit&&e.mobileVariant===s.mobileVariant&&e.alwaysShowActions===s.alwaysShowActions&&e.activeProjectId===s.activeProjectId&&e.setActiveProjectIdOnly===s.setActiveProjectIdOnly&&e.setActiveMainTab===s.setActiveMainTab&&e.setSessionSwitcherOpen===s.setSessionSwitcherOpen&&e.openNewSessionDraft===s.openNewSessionDraft&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.renamingFolderId===s.renamingFolderId&&e.renameFolderDraft===s.renameFolderDraft&&e.setRenameFolderDraft===s.setRenameFolderDraft&&e.setRenamingFolderId===s.setRenamingFolderId&&e.onToggleCollapsedGroup===s.onToggleCollapsedGroup&&e.dragHandleProps===s.dragHandleProps&&e.scrollContainerRef===s.scrollContainerRef};function sp({group:e,isCollapsed:s}){const n=Fi(),r=i.useMemo(()=>{const x=e.folderScopes?.map(g=>ye(g.directory))??[ye(e.directory??null)];return[...new Set(x.filter(g=>!!g))]},[e.directory,e.folderScopes]);i.useSyncExternalStore(i.useCallback(x=>r.length>0?n.subscribeBootstrap(x):()=>{},[r.length,n]),i.useCallback(()=>r.map(x=>`${x}\0${n.getBootstrapState(x)??""}\0${n.getBootstrapFailure(x)??""}`).join(""),[r,n]),i.useCallback(()=>"",[]));const o=r.some(x=>{const g=n.getBootstrapState(x);return g==="queued"||g==="running"}),a=r.find(x=>n.getBootstrapState(x)==="failed")??null,l=a?n.getBootstrapFailure(a):void 0,c=l==="os-permission"&&Jr(),[d,u]=i.useState(!1),f=i.useCallback(()=>{a&&n.requestBootstrap({directory:a,priority:s?"visible":"expanded",reason:e.isMain?"project-expanded":"worktree-expanded",force:!0})},[n,a,e.isMain,s]),h=i.useCallback(async()=>{if(!(!a||!c||d)){u(!0);try{(await Xr(a)).success&&f()}finally{u(!1)}}},[c,a,d,f]);return{bootstrapLoading:o,failedBootstrapDirectory:a,bootstrapFailure:l,canGrantBootstrapAccess:c,isRequestingBootstrapAccess:d,retryFailedBootstrap:f,grantFailedBootstrapAccess:h}}function np({group:e,sourceGroupNodes:s,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:a,unreadActivitySessionIds:l,notifyOnSubtasks:c,collectGroupSessions:d}){const u=lt(I=>I.foldersMap),f=e.folderScopeKey??ye(e.directory??null),h=i.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=i.useMemo(()=>h.flatMap(({scopeKey:I,directory:k})=>(u[I]??[]).map(w=>({folder:w,scopeKey:I,scopeDirectory:k}))),[h,u]),g=i.useMemo(()=>{const I=new Map,k=w=>{w.forEach(j=>{I.set(j.session.id,j),j.children.length>0&&k(j.children)})};return k(s),I},[s]),m=i.useMemo(()=>x.map(({folder:I,scopeKey:k,scopeDirectory:w})=>{const j=Kh(I.sessionIds,g).sort(o);return{folder:I,scopeKey:k,scopeDirectory:w,nodes:j}}),[x,g,o]),p=i.useMemo(()=>{const I=new Map(m.map(E=>[E.folder.id,E])),k=new Map;for(const{folder:E}of m){if(!E.parentId)continue;const T=k.get(E.parentId);T?T.push(E.id):k.set(E.parentId,[E.id])}const w=new Map,j=E=>{const T=w.get(E);if(T!==void 0)return T;const U=I.get(E);if(!U)return w.set(E,!1),!1;const _=k.get(E)??[];if(e.isArchivedBucket&&U.nodes.length===0){const P=_.some(B=>j(B));return w.set(E,P),P}if(!n||U.folder.name.toLowerCase().includes(r)||U.nodes.length>0)return w.set(E,!0),!0;const K=_.some(P=>j(P));return w.set(E,K),K};return m.filter(({folder:E})=>j(E.id))},[m,e.isArchivedBucket,n,r]),y=i.useMemo(()=>new Set(p.flatMap(I=>I.folder.sessionIds)),[p]),b=i.useMemo(()=>s.filter(I=>!y.has(I.session.id)),[s,y]),A=i.useMemo(()=>p.filter(({folder:I})=>!I.parentId),[p]),v=i.useMemo(()=>{const I=new Map;return p.forEach(k=>{if(!k.folder.parentId)return;const w=I.get(k.folder.parentId)??[];w.push(k),I.set(k.folder.parentId,w)}),I},[p]),C=i.useMemo(()=>{const I=new Map(p.map(j=>[j.folder.id,j])),k=new Map,w=(j,E)=>{const T=k.get(j);if(T!==void 0)return T;if(E.has(j))return null;E.add(j);const U=I.get(j);let _=U?Ua(U.nodes,a,l,c):null;for(const $ of v.get(j)??[])if(_=ao(_,w($.folder.id,E)),_==="active")break;return k.set(j,_),_};return p.forEach(({folder:j})=>w(j.id,new Set)),k},[a,p,v,c,l]),S=i.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const I=new Map,k=new Map;for(const{folder:j}of p){if(!j.parentId)continue;const E=k.get(j.parentId)??[];E.push(j.id),k.set(j.parentId,E)}const w=(j,E)=>{if(E.has(j))return[];E.add(j);const T=p.find(({folder:$})=>$.id===j),U=T?d(T.nodes):[],_=k.get(j)??[];for(const $ of _)U.push(...w($,E));return U};for(const{folder:j}of p)I.set(j.id,w(j.id,new Set));return I},[p,d,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:h,allFoldersForGroup:p,rootFolders:A,ungroupedSessions:b,folderActivityStateById:C,folderSessionsForDeleteById:S}}function rp(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:h,toggleFolderCollapse:x,renameFolder:g,deleteFolder:m,showDeletionDialog:p,setDeleteFolderConfirm:y,renderSessionNode:b,showMoreGroupSessions:A,resetGroupSessionLimit:v,mobileVariant:C,alwaysShowActions:S,activeProjectId:I,setActiveProjectIdOnly:k,setActiveMainTab:w,setSessionSwitcherOpen:j,openNewSessionDraft:E,addSessionToFolder:T,createFolderAndStartRename:U,renamingFolderId:_,renameFolderDraft:$,setRenameFolderDraft:K,setRenamingFolderId:P,pinnedSessionIds:B,expandedParents:R,sessionOrderIndex:F,editingId:V,openSidebarMenuKey:G,activeActivitySessionIds:M,unreadActivitySessionIds:ee,notifyOnSubtasks:H,onToggleCollapsedGroup:we,dragHandleProps:ce,compactBodyPadding:ae=!1,scrollContainerRef:xe}=e,be=i.useCallback((pe,_e)=>{const me=F.get(pe.session.id),Te=F.get(_e.session.id);if(me!==void 0||Te!==void 0){if(me===void 0)return 1;if(Te===void 0)return-1;if(me!==Te)return me-Te}return Qr(pe.session,_e.session,B,Li)},[B,F]),ge=a?c.get(s):null,Se=a?!1:u.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const pe=ye(s.directory??null),_e=s.branch?.trim();return pe&&_e?Ba():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const je=_a(),ke=void 0,{bootstrapLoading:Ce,failedBootstrapDirectory:Z,bootstrapFailure:ue,canGrantBootstrapAccess:L,isRequestingBootstrapAccess:Y,retryFailedBootstrap:le,grantFailedBootstrapAccess:W}=sp({group:s,isCollapsed:Se}),X=f?10:5,te=Math.max(X,d??X),ne=a?ge?.groupMatches===!0:!1,Ae=a,Ie=i.useMemo(()=>[...Ae?ge?.filteredNodes??[]:s.sessions].sort(be),[be,s.sessions,ge?.filteredNodes,Ae]),Pe=i.useCallback(pe=>{const _e=[],me=Te=>{Te.forEach($e=>{_e.push($e.session),$e.children.length>0&&me($e.children)})};return me(pe),_e},[]),{folderScopeKey:De,folderScopes:Ge,allFoldersForGroup:de,rootFolders:ze,ungroupedSessions:Ne,folderActivityStateById:Ye,folderSessionsForDeleteById:J}=np({group:s,sourceGroupNodes:Ie,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,compareSessionNodes:be,activeActivitySessionIds:M,unreadActivitySessionIds:ee,notifyOnSubtasks:H,collectGroupSessions:Pe}),Be="project",We=i.useMemo(()=>{const pe=new Set;return si(Ie,V,pe),de.forEach(({nodes:_e})=>{si(_e,V,pe)}),pe},[Ie,de,V]),Ue=i.useMemo(()=>{if(!G)return null;const pe=Un(Ie,G,Be,!!s.isArchivedBucket);if(pe)return pe;for(const{nodes:_e}of de){const me=Un(_e,G,Be,!!s.isArchivedBucket);if(me)return me}return null},[G,Ie,de,s.isArchivedBucket]),Ve=i.useCallback(pe=>{const _e=new WeakMap,me=Te=>{_e.set(Te,Kr(Te));for(const $e of Te.children)me($e)};return pe.forEach(me),_e},[]),gt=i.useMemo(()=>Ve(Ie),[Ve,Ie]),Wt=i.useMemo(()=>{const pe=new WeakMap;return de.forEach(({nodes:_e})=>{_e.forEach(me=>pe.set(me,Kr(me)))}),pe},[de]),ot=i.useCallback(pe=>gt.get(pe)??Wt.get(pe)??"",[gt,Wt]),Je=i.useCallback(pe=>({subtreeContainsEditing:We,menuOpenSessionId:Ue,nodeStructureKey:ot(pe)}),[We,Ue,ot]),xt=Ne.length,tt=s.isArchivedBucket||a?Ne:Ne.slice(0,te),st=xt-tt.length,St=!s.isArchivedBucket&&!a&&xt>X&&st===0,Yt=s.isArchivedBucket===!0&&!a&&tt.length>=Yh,ut=s.isArchivedBucket?"archived":"active",qe=Yt&&tt.some(pe=>{if(pe.children.length===0)return!1;const _e=`project:${ut}:${pe.session.id}`;return R.has(_e)}),bt=i.useMemo(()=>Pe(Ie),[Pe,Ie]);if(a&&!ne&&ze.length===0&&Ne.length===0)return null;const jt=!s.isMain&&!!s.branch,Lt=s.branch&&hu(s.branch,s.label)?{label:s.branch,color:null}:null,ft=Se?Ua(Ie,M,ee,H):null,qt=ft?t.jsx(La,{state:ft,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Ot=(pe,_e)=>{const{folder:me,scopeKey:Te,scopeDirectory:$e,nodes:Ze}=pe,Qt=J.get(me.id)??[],nt=a?!1:h.has(me.id);return t.jsx(Uh,{folderId:me.id,children:(Jt,kt)=>t.jsx(_h,{folder:me,displayName:_e,sessions:Ze,isCollapsed:nt,collapsedActivityState:nt?Ye.get(me.id)??null:null,onToggle:()=>x(me.id),onRename:it=>{g(Te,me.id,it)},onDelete:()=>{if(s.isArchivedBucket){Cs.requestDelete({sessions:Qt,mode:"session"});return}if(!p){m(Te,me.id);return}const it=de.filter(({folder:_t})=>_t.parentId===me.id).length,Xt=Ze.length;y({scopeKey:Te,folderId:me.id,folderName:me.name,subFolderCount:it,sessionCount:Xt})},renderSessionNode:b,getRenderExtras:ot?it=>({subtreeContainsEditing:We,menuOpenSessionId:Ue,nodeStructureKey:ot(it),childRenderExtrasFor:Je}):void 0,groupDirectory:$e??s.directory,projectId:r,mobileVariant:C,alwaysShowActions:S,isRenaming:_===me.id,renameDraft:_===me.id?$:void 0,onRenameDraftChange:it=>K(it),onRenameSave:()=>{const it=$.trim();it&&g(Te,me.id,it),P(null),K("")},onRenameCancel:()=>{P(null),K("")},droppableRef:Jt,isDropTarget:kt,depth:0,onNewSession:()=>{r&&r!==I&&k(r),w("chat"),C&&j(!1),E({selectedProjectId:r,directoryOverride:$e??s.directory,targetFolderId:me.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},me.id)},Ct=()=>{const pe=new Map;for(const Te of de){const $e=Te.folder.parentId;if(!$e)continue;const Ze=pe.get($e);Ze?Ze.push(Te):pe.set($e,[Te])}const _e=[],me=(Te,$e)=>{const Ze=$e?`${$e} / ${Te.folder.name}`:Te.folder.name;_e.push(Ot(Te,Ze)),!(!a&&h.has(Te.folder.id))&&(pe.get(Te.folder.id)??[]).forEach(nt=>me(nt,Ze))};return ze.forEach(Te=>me(Te,"")),_e},Vt=S?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",Bt=Z?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[ue==="os-permission"?"Folder access is required.":"Could not refresh sessions.",L?t.jsx(Re,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:Y,onClick:()=>{W()},children:"Grant access"}):null,t.jsx(Re,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:le,children:"Try again"})]}):null,is=t.jsxs($h,{scopeKey:Ge[0]?.scopeKey??De,hasFolders:de.length>0,onSessionDroppedOnFolder:(pe,_e)=>{const me=de.find(({folder:$e})=>$e.id===_e);if(!me)return;const Te=lt.getState();for(const{scopeKey:$e}of Ge)$e!==me.scopeKey&&Te.getSessionFolderId($e,pe)&&Te.removeSessionFromFolder($e,pe);T(me.scopeKey,_e,pe)},children:[Ct(),s.isArchivedBucket?t.jsx(Vh,{visibleSessions:tt,shouldVirtualize:Yt,hasExpandedParent:qe,scrollContainerRef:xe,groupDirectory:s.directory,projectId:r,isArchivedBucket:s.isArchivedBucket===!0,renderSessionNode:b,getRenderExtras:pe=>({subtreeContainsEditing:We,menuOpenSessionId:Ue,nodeStructureKey:ot(pe),childRenderExtrasFor:Je})}):tt.map(pe=>t.jsx(i.Fragment,{children:b(pe,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:We,menuOpenSessionId:Ue,nodeStructureKey:ot(pe),childRenderExtrasFor:Je})},pe.session.id)),xt===0&&de.length===0?s.isArchivedBucket?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):Ce?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:t.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t.jsx(D,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):Bt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:Bt}):t.jsx(js,{icon:"chat-new",onClick:()=>{E({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,xt>0&&Bt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:Bt}):null,st>0?t.jsx(js,{icon:"arrow-down-s",onClick:()=>A(n,tt.length),children:st===1?"Show 1 more session":`Show ${st} more sessions`}):null,St?t.jsx(js,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:is})}):t.jsxs("div",{className:"oc-group",children:[t.jsx(Qh,{group:s,groupKey:n,isCollapsed:Se,onToggleCollapsedGroup:we,normalizedSessionSearchQuery:l,alwaysShowActions:S,groupHeaderRightPadding:Vt,dragHandleProps:ce,groupPrColor:ke,groupPrSummary:je,groupActivityIndicator:qt,showBranchSubtitle:jt,statusLine:Lt,allGroupSessions:bt,projectId:r,activeProjectId:I,setActiveProjectIdOnly:k,setActiveMainTab:w,mobileVariant:C,setSessionSwitcherOpen:j,openNewSessionDraft:E}),Se?null:t.jsx("div",{className:"oc-group-body",children:is})]})}const op=i.memo(rp,tp);function ip(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:h,sessionSearchInputRef:x,sessionSearchQuery:g,setSessionSearchQuery:m,hasSessionSearchQuery:p,searchMatchCount:y,selectionModeEnabled:b,onToggleSelectionMode:A,mobileVariant:v=!1}=e;if(s)return null;const C=z(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return t.jsx("div",{className:z("select-none flex-shrink-0",v?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:z("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:z("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:z("flex min-w-0 items-center",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[o?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:C,"aria-label":"Settings",children:t.jsx(D,{name:"settings-3",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!v&&a?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:C,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(D,{name:"server",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:C,"aria-label":"Update",children:t.jsx(D,{name:"download",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,v?null:t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:C,"aria-label":"Add project",children:t.jsx(D,{name:"folder-add",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),v?null:t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:C,"aria-label":"Archive",children:t.jsx(D,{name:"archive",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:z("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>h(S=>!S),className:C,"aria-label":"Search sessions","aria-expanded":f,children:t.jsx(D,{name:"search",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:A,className:z(C,b&&"bg-interactive-hover text-primary"),"aria-label":b?"Exit selection":"Select sessions","aria-pressed":b,children:t.jsx(D,{name:"checkbox-multiple",className:d})})}),t.jsx(Oe,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:b?"Exit selection":"Select sessions"})})]})]})]}),f?t.jsxs("div",{className:z(v?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:p?t.jsx("span",{children:y===1?`${y} match`:`${y} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{ref:x,value:g,onChange:S=>m(S.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:S=>{S.key==="Escape"&&(S.stopPropagation(),p?m(""):h(!1))}}),g.length>0?t.jsx("button",{type:"button",onClick:()=>m(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:t.jsx(D,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function ap(e){const s=se(o=>o.toggleSidebar),n=se(o=>o.shortcutOverrides),r=eo(sn("toggle_sidebar",n));return t.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${Uo})`}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${Uo})))`}}),t.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsxs("button",{type:"button",onClick:e.onNewSession,className:z("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),children:[t.jsx(D,{name:"chat-new",className:z(En,"text-current")}),t.jsx("span",{className:Xi,children:"New session"})]}),e.showSidebarToggle?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Hide sessions",children:t.jsx(D,{name:"layout-left",className:"size-4"})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const $a=500,lp=({projectId:e,worktree:s,isSelected:n,hasActive:r,onSelect:o,onClose:a,mobileVariant:l=!1})=>{const[c,d]=i.useState(!1),u=i.useRef(null),f=s.branch||(s.detached?"Detached HEAD":s.name),h=i.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);i.useEffect(()=>()=>h(),[h]);const x=i.useCallback(()=>{h(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},$a)},[h]);return t.jsxs(Da,{open:c,onOpenChange:d,children:[t.jsxs(Ra,{render:t.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:h,onTouchEnd:h,onTouchCancel:h,style:{touchAction:"manipulation"},className:z($n(l,n),"pl-6"),"aria-pressed":n,title:s.path}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx(D,{name:"git-branch",className:z(un(l),"text-muted-foreground")}),t.jsx("span",{className:fn(l),children:f})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx($s,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsx(Ea,{className:"min-w-[160px]",children:t.jsxs(Gr,{disabled:!a,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>a?.(e,s),className:"text-destructive focus:text-destructive",children:[t.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close worktree"})]})})]})},$n=(e,s)=>z("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),cp=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:a,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h=!1})=>{const{listeners:x,setNodeRef:g,transform:m,transition:p,isDragging:y}=ca({id:e.id,disabled:!c}),[b,A]=i.useState(!1),v=i.useRef(null),C=i.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);i.useEffect(()=>()=>C(),[C]);const S=i.useCallback(()=>{C(),v.current=window.setTimeout(()=>{v.current=null,A(!0)},$a)},[C]);return t.jsx("div",{ref:g,style:{transform:da.Translate.toString(m),transition:p},className:z(y&&"opacity-60"),children:t.jsxs(Da,{open:b,onOpenChange:A,children:[t.jsxs(Ra,{render:t.jsx("button",{type:"button",onClick:()=>{b||d()},onTouchStart:S,onTouchMove:C,onTouchEnd:C,onTouchCancel:C,style:{touchAction:"manipulation"},className:$n(h,n),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:z("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${s}`:void 0,...c?x:{},children:t.jsx(D,{name:"folder",className:z(un(h),"text-muted-foreground")})}),t.jsx("span",{className:fn(h),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx($s,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,a?t.jsx("span",{title:a,"aria-label":"Worktree discovery failed",children:t.jsx(D,{name:"error-warning",className:"size-4 text-[var(--status-warning-foreground)]"})}):null,o?t.jsx(D,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(Ea,{className:"min-w-[160px]",children:[t.jsxs(Gr,{onClick:()=>u(e.id),children:[t.jsx(D,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(th,{}),t.jsxs(Gr,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},dp=({projects:e,selectedProjectId:s,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:a,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:h,activeDirectoriesByProject:x,homeDirectory:g,className:m,mobileVariant:p=!1})=>{const y=s===null,b=dt(S=>S.reorderProjects),A=e.length>1,v=so(On(Du,{activationConstraint:{distance:8}}),On(Iu,{activationConstraint:{delay:200,tolerance:6}})),C=i.useCallback(S=>{const{active:I,over:k}=S;if(!k||I.id===k.id)return;const w=dt.getState().projects,j=w.findIndex(T=>T.id===I.id),E=w.findIndex(T=>T.id===k.id);j<0||E<0||b(j,E)},[b]);return t.jsxs("div",{className:z("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:$n(p,y),"aria-pressed":y,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(D,{name:"chat-history",className:un(p)}),t.jsx("span",{className:fn(p),children:"All sessions"})]})}),t.jsx(no,{sensors:v,collisionDetection:ro,onDragEnd:C,children:t.jsx(la,{items:e.map(S=>S.id),strategy:Eu,children:e.map(S=>{const I=s===S.id,k=I&&!n,w=r.get(S.normalizedPath)??[],j=Yn(S.label?.trim()||_s(S.normalizedPath,g)||S.normalizedPath),E=x?.get(S.id),T=ye(S.normalizedPath)?.toLowerCase()??"",U=T?E?.has(T)??!1:!1,_=(E?.size??0)>0,$=h?.(S.id)??!1,K=x?I?U:_:$;return t.jsxs(i.Fragment,{children:[t.jsx(cp,{project:S,label:j,isSelected:k,hasActive:K,hasWorktrees:w.length>0,worktreeError:o.get(S.normalizedPath),isExpanded:I,canDrag:A,onSelect:()=>a(S.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p}),I?w.map(P=>{const B=n===P.path,R=ye(P.path)?.toLowerCase()??"",F=R?E?.has(R)??!1:!1,V=x?F:!1;return t.jsx(lp,{projectId:S.id,worktree:P,isSelected:B,hasActive:V,onSelect:()=>l?.(S.id,P.path),onClose:c,mobileVariant:p},P.path)}):null]},S.id)})})}),t.jsxs("button",{type:"button",onClick:d,className:$n(p,!1),children:[t.jsx(D,{name:"add",className:un(p)}),t.jsx("span",{className:fn(p),children:"Add folder"})]})]})},cr="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function up({onOpenSettings:e,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:a=!0}){return!o&&!a?null:t.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?t.jsxs(t.Fragment,{children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:cr,"aria-label":"Settings",children:t.jsx(D,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(Oe,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:cr,"aria-label":"Shortcuts",children:t.jsx(D,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(Oe,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:cr,"aria-label":"About PiChamber",children:t.jsx(D,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(Oe,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Re,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:r,children:"Update"}):null]})}const fp=(e,s)=>Yn(e.label?.trim()||_s(e.normalizedPath,s)||e.normalizedPath);function hp(e){Ft("ui.sidebar_projects_list.render");const s=i.useRef(new Map),n=i.useRef(e.getOrderedGroups);n.current!==e.getOrderedGroups&&(n.current=e.getOrderedGroups,s.current.clear());const r=(h,x)=>{const g=s.current,m=g.get(h);if(m&&m.groups===x)return m.ordered;const p=e.getOrderedGroups(h,x);if(g.set(h,{groups:x,ordered:p}),g.size>256){const y=g.keys().next().value;y!==void 0&&g.delete(y)}return p},o=i.useRef(null),a=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const h=[],x=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const g of x){const m=fp(g.project,e.homeDirectory);for(const p of g.groups)if(!p.isArchivedBucket)for(const y of p.sessions){const b=!!e.pinnedSessionIds?.has(y.session.id),A=y.session.time?.updated||y.session.time?.created||0;h.push({node:y,project:g.project,projectLabel:m,isPinned:b,timestamp:A,globalSession:g===e.allFoldersOnlySection})}}return h.sort((g,m)=>g.isPinned!==m.isPinned?g.isPinned?-1:1:m.timestamp-g.timestamp),h},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=i.useState(30);i.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const d=a.slice(0,l),u=a.length-d.length;if(e.sharedSessionsOnly)return t.jsx(ys,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const f=e.isAllFoldersView&&!!e.allFoldersOnlySection;return e.projectSections.length===0&&!f?t.jsx(ys,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0&&!f?t.jsx(ys,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):t.jsx("div",{className:"relative flex min-h-0 flex-1",children:t.jsx(ys,{ref:o,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.showOnlyMainWorkspace?t.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const h=e.sectionsForRender.find(p=>p.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!h)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const x=h.groups.find(p=>p.isMain&&p.sessions.length>0)??h.groups.find(p=>p.sessions.length>0)??h.groups.find(p=>p.isMain)??h.groups[0];if(!x)return t.jsx(js,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath}),children:"New session"});const g=h.groups.find(p=>p.isArchivedBucket);return[x,...g&&g.id!==x.id?[g]:[]].map(p=>{const y=`${h.project.id}:${p.id}`,b=p.id===x.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(p,y,h.project.id,b,null,!0,o)},y)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[d.map(({node:h,project:x,projectLabel:g,globalSession:m})=>{const p=h.session.directory??x.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(h,0,p,x.id,!1,{projectLabel:g,showFolderLabel:!0,globalSession:m},"project")},h.session.id)}),u>0?t.jsx(js,{icon:"arrow-down-s",onClick:()=>c(h=>h+30),children:u===1?"Show 1 more session":`Show ${u} more sessions`}):null,l>30&&a.length>30?t.jsx(js,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(h=>{const x=h.project.id,g=r(x,h.groups),m=g.find(y=>y.isMain)??null,p=m?g.filter(y=>y.id!==m.id):g;return t.jsxs("div",{children:[m?e.renderGroupSessions(m,`${x}:${m.id}`,x,!0,null,void 0,o):null,p.map(y=>{const b=`${x}:${y.id}`,A=g.length===1;return t.jsx(i.Fragment,{children:e.renderGroupSessions(y,b,x,A,null,void 0,o)},y.id)})]},x)})})]})})})}const pp=i.memo(hp);let Hr=!1;const Wr=new Set;let ii=!1;function mp(){for(const e of Wr)e()}function lo(e){Hr!==e&&(Hr=e,mp())}function gp(e){e.key==="Shift"&&lo(!0)}function xp(e){e.key==="Shift"&&lo(!1)}function bp(){lo(!1)}function yp(){ii||typeof window>"u"||(ii=!0,window.addEventListener("keydown",gp),window.addEventListener("keyup",xp),window.addEventListener("blur",bp))}function wp(e){return yp(),Wr.add(e),()=>{Wr.delete(e)}}function vp(){return Hr}function Sp(){return!1}function jp(){return Me.useSyncExternalStore(wp,vp,Sp)}const Cp=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=jp(),f=u?n:s,h=x=>{if(u||x.shiftKey){d(x);return}c(x)};return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:a,onMouseDown:l,onClick:h,onKeyDown:x=>x.stopPropagation(),children:t.jsx(D,{name:u?"delete-bin":"archive",className:o})})}),t.jsx(Oe,{side:"left",sideOffset:8,children:f})]})}),kp=i.memo(function({open:s,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,onExport:l}){return t.jsx(Kt,{open:s,onOpenChange:n,children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:"Export Markdown"}),t.jsx(fs,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} sub-agent tasks. Include them in the export?`})]}),t.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:o,onChange:c=>a(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Ns,{children:[t.jsx(Re,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Re,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function Np(e,s){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:a,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:h,handleOpenMiniChatWindow:x,handleDeleteSession:g,handleRestoreSession:m}=e,{Item:p,Separator:y}=s;return t.jsxs(t.Fragment,{children:[t.jsxs(p,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(p,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(p,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[a?t.jsx(D,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(D,{name:"pushpin",className:"mr-1 h-4 w-4"}),a?"Unpin session":"Pin session"]}),t.jsxs(p,{onClick:()=>{h()},className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?t.jsxs(p,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(y,{}),l?null:t.jsxs(p,{className:"[&>svg]:mr-1",onClick:()=>g(n,{archivedBucket:l}),children:[t.jsx(D,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?t.jsxs(p,{className:"[&>svg]:mr-1",onClick:()=>m(n),children:[t.jsx(D,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(p,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>g(n,{archivedBucket:l,hardDelete:!0}),children:[t.jsx(D,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Ap(e){const{renamingFolderId:s,editingIdRef:n}=e;return t.jsx(ta,{children:t.jsx(sa,{className:"app-region-no-drag z-50",children:t.jsx(na,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(s||n.current),style:{color:"var(--surface-elevated-foreground)"},className:z(Ri,"min-w-[180px]"),children:Np(e,{Item:({className:r,...o})=>t.jsx(ra,{className:z(Ei,r),...o}),Separator:({className:r,...o})=>t.jsx(oa,{className:z(Pi,r),...o})})})})})}const dr=new WeakMap,Ip=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;dr.get(n)?.();const r=s.getBoundingClientRect().top;let o=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,dr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(a||!s.isConnected||!n.isConnected){c();return}const u=s.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Ft("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),dr.set(n,c),l=window.requestAnimationFrame(d)};function Dp(e){if(typeof e!="number"||!Number.isFinite(e))return"";const s=new Date(e);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleString("en-US",{month:"short"}),r=s.getDate(),o=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${a}:${l}`}function Rp(e){if(e.info.role==="user")return"";const s=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return s&&n?`${s}/${n}`:n||s}function Ep(e){const s=e.info.role==="user"?"User":"Assistant",n=Dp(e.info.time?.created),r=Rp(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
|
|
13
|
-
|
|
14
|
-
*${o}*`:`**${s}**`}function Pp(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Ga(e){const s=Ep(e),n=Pp(e.parts).trim();return n?`${s}
|
|
15
|
-
|
|
16
|
-
${n}`:""}function Ka(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
`,a=e.records.map(Ga).filter(Boolean).join(`
|
|
21
|
-
|
|
22
|
-
---
|
|
23
|
-
|
|
24
|
-
`),l=[o+a];for(const c of e.children)l.push(Ka(c,s+1));return l.join(`
|
|
25
|
-
|
|
26
|
-
---
|
|
27
|
-
|
|
28
|
-
`)}function Ha(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
29
|
-
|
|
30
|
-
*Exported on ${o}*
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
`,l=e.map(Ga).filter(Boolean).join(`
|
|
35
|
-
|
|
36
|
-
---
|
|
37
|
-
|
|
38
|
-
`);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Ka(u,1)).join(`
|
|
39
|
-
|
|
40
|
-
---
|
|
41
|
-
|
|
42
|
-
`);c+=`
|
|
43
|
-
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
`+d}return c}function Wa(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function Ya(e,s){const n=await Yd(s,e);return n||null}async function Mp(e){const s=ss()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await qd(e)?!0:Hi(e)}function Tp(){return Vd()}function qa(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const Gn=e=>{const s=[],n=r=>{r.children.forEach(o=>{s.push(o.session.id),n(o)})};return n(e),s};function Fp(e,s){const n=Oi(),[r,o]=i.useState(!1),[a,l]=i.useState(!0),c=e.session,d=i.useMemo(()=>Gn(e).length,[e]),u=i.useCallback(async g=>{const m=[];let p=0;for(const y of g)try{if(!s)throw new Error("Session directory is required for export");const b=Ir(n.getState(),y.session.id).list,A=y.session.title||"Untitled Sub-agent",v=typeof y.session.agent=="string"?y.session.agent:void 0,C=await u(y.children);p+=C.skipped,m.push({title:A,agent:v,records:b,children:C.children})}catch{p+=Gn(y).length+1}return{children:m,skipped:p}},[n,s]),f=i.useCallback(g=>{g<=0||ie.warning(g===1?`Exported session, but skipped ${g} sub-agent task that could not be loaded.`:`Exported session, but skipped ${g} sub-agent tasks that could not be loaded.`)},[]),h=i.useCallback(async g=>{if(!s){ie.error("Nothing to export");return}const m=Ir(n.getState(),c.id).list;if(m.length===0){ie.error("Nothing to export");return}let p,y=0;if(g&&e.children.length>0){const C=await u(e.children);p=C.children,y=C.skipped}const b=Ha(m,c.title??null,p),A=qa(c.title??null),v=await Ya(b,A);if(v){ie.success("Session exported",{action:{label:Tp(),onClick:()=>{Mp(v).then(C=>{C||ie.error("Failed to reveal path")})}}}),f(y);return}Wa(b,A),ie.success("Session exported"),f(y)},[u,n,e.children,c.id,c.title,s,f]),x=i.useCallback(async()=>{if(e.children.length>0){l(!0),o(!0);return}await h(!1)},[h,e.children.length]);return{exportDialogOpen:r,setExportDialogOpen:o,exportIncludeSubtasks:a,setExportIncludeSubtasks:l,descendantCount:d,handleExportSession:x,doExportSession:h}}const Lp=(e,s)=>{if(!s)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const a=s.get(o);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},ct=hs()((e,s)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{s().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{s().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,o)=>{const a=s(),l=new Set(a.selectedIds);let c=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(l.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const x of f)l.delete(x);d===n&&(d=null)}else{for(const x of f)l.add(x);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,o,a,l)=>{const c=s();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),f=o.indexOf(r);if(u<0||f<0)return;const[h,x]=u<=f?[u,f]:[f,u],g=o.slice(h,x+1),m=Lp(g,l),y=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const b of m)y.add(b);e({selectedIds:y,scopeKey:a??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),ai=e=>ye(e.session.directory??null),Op=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),Bp=e=>{if(!e.openSidebarMenuKey)return null;const s=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${s}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},In=e=>e.menuOpenSessionId??Bp(e),Dn=(e,s,n)=>s?n.has(e.node.session.id)?!0:rs(e.node,s):!1,Yr=(e,s,n,r,o)=>{if(e.session.id!==s.session.id)return!0;const a=o(e);if(n.has(a)!==r.has(a)||e.children.length!==s.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(Yr(e.children[l],s.children[l],n,r,o))return!0;return!1},_p=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Yr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Yr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},zp=(e,s)=>{if(e.node.session.id!==s.node.session.id||e.node.session!==s.node.session||e.depth!==s.depth||e.groupDirectory!==s.groupDirectory||e.projectId!==s.projectId||e.archivedBucket!==s.archivedBucket||(e.renderContext??"project")!==(s.renderContext??"project")||e.mobileVariant!==s.mobileVariant||e.alwaysShowActions!==s.alwaysShowActions||e.allowQuickArchiveAction!==s.allowQuickArchiveAction||e.hasSessionSearchQuery!==s.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||e.notifyOnSubtasks!==s.notifyOnSubtasks||e.nodeStructureKey!==s.nodeStructureKey||ai(e.node)!==ai(s.node)||!Op(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Oa(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&_p(e,s)||e.editingId!==s.editingId&&(Dn(e,e.editingId,e.subtreeContainsEditing)||Dn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(Dn(e,e.editingId,e.subtreeContainsEditing)||Dn(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(rs(e.node,e.copiedSessionId)||rs(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=In(e),r=In(s);if(rs(e.node,n)||rs(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=In(e),r=In(s);if(rs(e.node,n)||rs(s.node,r))return!1}return e.setEditingId===s.setEditingId&&e.setEditTitle===s.setEditTitle&&e.handleSaveEdit===s.handleSaveEdit&&e.handleCancelEdit===s.handleCancelEdit&&e.toggleParent===s.toggleParent&&e.handleSessionSelect===s.handleSessionSelect&&e.handleSessionDoubleClick===s.handleSessionDoubleClick&&e.togglePinnedSession===s.togglePinnedSession&&e.handleShareSession===s.handleShareSession&&e.handleCopyShareUrl===s.handleCopyShareUrl&&e.handleCopySessionId===s.handleCopySessionId&&e.handleUnshareSession===s.handleUnshareSession&&e.setOpenSidebarMenuKey===s.setOpenSidebarMenuKey&&e.getFoldersForScope===s.getFoldersForScope&&e.getSessionFolderId===s.getSessionFolderId&&e.removeSessionFromFolder===s.removeSessionFromFolder&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.handleDeleteSession===s.handleDeleteSession&&e.handleRestoreSession===s.handleRestoreSession&&e.renderSessionNode===s.renderSessionNode};function Up({node:e,groupDirectory:s,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:a,expansionKey:l,hasSessionSearchQuery:c,notifyOnSubtasks:d}){const u=e.session,f=ye(u.directory??null)??ye(s??null),h=ve(Ce=>Ce.currentSessionId===u.id),x=Bi(f),g=Hc(f),m=dt(i.useCallback(Ce=>{if(r?.projectLabel||!n)return null;const Z=Ce.projects.find(ue=>ue.id===n);return Z?Z.label?.trim()||_s(ye(Z.path)??Z.path,null)||Z.path:null},[n,r?.projectLabel])),p=r?.projectLabel??(m?Yn(m):null),y=e.worktree,b=r?.branchLabel??y?.branch??(x&&x!=="HEAD"?x:null),A=b,v=g===!0||!!(b||y),C=e.children.length,S=u.agent;i.useMemo(()=>{const Ce=y?.branch?.trim()||b?.trim(),Z=ye(y?.path??f);return Ce&&Z?Ba():null},[b,f,y]);const I=_a(),k=void 0,w=i.useMemo(()=>null,[I]),j=n??f??null,E=ct(Ce=>Ce.enabled),T=ct(i.useCallback(Ce=>Ce.selectedIds.has(u.id),[u.id])),U=ct(Ce=>Ce.toggleSelected),_=ct(Ce=>Ce.setRange),$=Wc(i.useCallback(Ce=>!!Ce.sessionMemoryState.get(Yc(u.id))?.isZombie,[u.id])),P=_i(u.id)?.type??"idle",B=P==="busy"||P==="retry",R=qc(u.id,B),F=Vc(u.id),V=ds(u),G=e.children.length>0,M=Qc(o,f,u.id),ee=c?!0:a.has(l);i.useMemo(()=>Gh(e,ee,f),[ee,e,f]);const H=Xc(),we=!!u.parentID,ae=Jc(u.id)>0&&(!we||d),xe=u.time?.updated||u.time?.created||Date.now(),be=pu(xe),ge=i.useMemo(()=>Ma(e.forkColorId),[e.forkColorId]),Se=i.useMemo(()=>xh(e.forkColorId,{active:h||T}),[e.forkColorId,h,T]),je=r?.globalSession&&!h&&!T?"var(--surface-elevated)":null;return{session:u,sessionDirectory:f,isActive:h,tooltipProjectLabel:p,tooltipBranchLabel:A,isGitRepo:v,subtaskCount:C,agentName:S,prSummary:I,prIconColor:k,prStatusLabel:w,selectionScopeKey:j,selectionModeEnabled:E,isRowSelected:T,toggleRowSelected:U,setRowRange:_,isZombie:$,isStreaming:B,hasActivityDuration:R,sessionPermissions:F,sessionTitle:V,hasChildren:G,isPinnedSession:M,isExpanded:ee,pendingQuestionCount:H,needsAttention:ae,sessionCompactUpdatedLabel:be,forkSolid:ge,rowBackground:Se??je}}function $p(e){Ft("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:f,editingId:h,setEditingId:x,editTitle:g,setEditTitle:m,handleSaveEdit:p,handleCancelEdit:y,toggleParent:b,handleSessionSelect:A,handleSessionDoubleClick:v,togglePinnedSession:C,handleShareSession:S,copiedSessionId:I,handleCopyShareUrl:k,handleCopySessionId:w,handleUnshareSession:j,openSidebarMenuKey:E,setOpenSidebarMenuKey:T,renamingFolderId:U,getFoldersForScope:_,getSessionFolderId:$,removeSessionFromFolder:K,addSessionToFolder:P,createFolderAndStartRename:B,handleDeleteSession:R,handleRestoreSession:F,mobileVariant:V,alwaysShowActions:G,allowQuickArchiveAction:M,renderSessionNode:ee,secondaryMeta:H,renderContext:we="project",subtreeContainsEditing:ce,menuOpenSessionId:ae,childRenderExtrasFor:xe}=e,be=i.useMemo(()=>Wi(),[]),ge=!a&&M,Se=i.useRef(!1),je=i.useRef(h);je.current=h;const ke=i.useRef(null),Ce=i.useRef(p);Ce.current=p;const[Z,ue]=i.useState(g),L=i.useRef(Z);L.current=Z;const Y=i.useRef(null),le=i.useRef(null),X=`${we}:${a?"archived":"active"}:${s.session.id}`,{session:te,sessionDirectory:ne,isActive:Ae,tooltipProjectLabel:Ie,tooltipBranchLabel:Pe,isGitRepo:De,subtaskCount:Ge,agentName:de,prSummary:ze,selectionScopeKey:Ne,selectionModeEnabled:Ye,isRowSelected:J,toggleRowSelected:Be,setRowRange:We,isZombie:Ue,isStreaming:Ve,hasActivityDuration:gt,sessionPermissions:Wt,sessionTitle:ot,hasChildren:Je,isPinnedSession:xt,isExpanded:tt,pendingQuestionCount:st,needsAttention:St,sessionCompactUpdatedLabel:Yt,forkSolid:ut,rowBackground:qe}=Up({node:s,groupDirectory:r,projectId:o,secondaryMeta:H,pinnedSessionIds:l,expandedParents:c,expansionKey:X,hasSessionSearchQuery:d,notifyOnSubtasks:f}),{exportDialogOpen:bt,setExportDialogOpen:jt,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:ft,descendantCount:qt,handleExportSession:Ot,doExportSession:Ct}=Fp(s,ne),[Vt,Bt]=i.useState(!1),is=i.useCallback(()=>{ne&&nn("desktop_open_session_mini_chat_window",{sessionId:te.id,directory:ne,apiBaseUrl:Pr(),clientToken:Er()}).catch(oe=>{console.warn("[session-sidebar] failed to open mini chat window",oe)})},[te.id,ne]);i.useEffect(()=>{if(h!==te.id)return;const oe=et=>{const Nt=et.target?.closest?.(`[data-session-rename-form="${CSS.escape(te.id)}"]`);le.current&&!Nt&&Ce.current(L.current)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[h,te.id]),i.useLayoutEffect(()=>{if(h!==te.id){Y.current===te.id&&(Y.current=null);return}Y.current!==te.id&&(Y.current=te.id,ue(g))},[h,g,te.id]);const pe=Wt.length,_e=!Ve&&St&&!Ae,me=Ve&>,Te=xt,$e=t.jsx(D,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),Ze=Te?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:$e}):null,Qt=Je?t.jsx("button",{type:"button",onClick:oe=>{oe.stopPropagation(),b(X)},onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),oe.stopPropagation(),b(X))},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-label":tt?"Collapse subsessions":"Expand subsessions",children:tt?t.jsx(D,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(D,{name:"arrow-right-s",className:"h-3 w-3"})}):null,nt=Ue?t.jsx(D,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Jt=oe=>{if(!oe&&ke.current){const{id:et,title:pt}=ke.current;ke.current=null,x(et),m(pt)}},kt=oe=>{Bt(oe)},it=oe=>{oe.preventDefault(),oe.stopPropagation()},Xt=oe=>{oe.preventDefault(),oe.stopPropagation()},_t=oe=>{oe.preventDefault(),oe.stopPropagation(),T(null),R(te,{archivedBucket:a})},ps=oe=>{oe.preventDefault(),oe.stopPropagation(),T(null),R(te,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Zt=oe=>{if(Se.current){Se.current=!1;return}if(Ye){if(oe?.preventDefault(),oe?.stopPropagation(),oe?.shiftKey){const pt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(wt=>wt.getAttribute("data-session-row")).filter(wt=>typeof wt=="string"&&wt.length>0),Nt=ct.getState().anchorId,yt=new Map;yt.set(te.id,Gn(s)),We(Nt,te.id,pt,Ne,yt);return}Be(te.id,Ne,Gn(s));return}oe?.currentTarget&&Ip(oe.currentTarget),A(te.id,ne)},zt=oe=>{oe.defaultPrevented||oe.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Zt(oe)},ms=oe=>{(oe.button===2||oe.button===0&&oe.ctrlKey&&!Ye)&&(Se.current=!0)},ht={session:te,sessionTitle:ot,sessionDirectory:ne,isPinnedSession:xt,archivedBucket:a,isElectron:be,renamingFolderId:U,editingIdRef:je,pendingRenameRef:ke,handleCopySessionId:w,togglePinnedSession:C,handleExportSession:Ot,handleOpenMiniChatWindow:is,handleDeleteSession:R,handleRestoreSession:F},As=t.jsx(Ap,{...ht});return t.jsxs(i.Fragment,{children:[t.jsx(zh,{sessionId:te.id,sessionDirectory:ne??null,sessionTitle:ot,children:t.jsxs(Zi,{open:Vt,onOpenChange:kt,onOpenChangeComplete:Jt,children:[t.jsxs(ea,{render:t.jsx("div",{"data-session-row":te.id,"data-session-scope":Ne??"","data-session-archived":a?"1":"0","data-fork-color":ut?s.forkColorId:void 0,"data-global-session":H?.globalSession?"1":void 0,onClick:zt,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...qe?{backgroundColor:qe}:void 0},className:z("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!qe&&n>0?"bg-secondary/30 hover:bg-interactive-hover":qe?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!qe&&Ae&&!J&&"bg-interactive-selection",!qe&&J&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[Qt,Ze,h===te.id?t.jsxs("form",{ref:le,"data-session-rename-form":te.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:oe=>oe.stopPropagation(),onMouseDown:oe=>oe.stopPropagation(),onSubmit:oe=>{oe.preventDefault(),p(Z)},children:[t.jsx("input",{value:Z,onChange:oe=>ue(oe.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:oe=>{oe.stopPropagation(),oe.key==="Escape"&&y()}}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:y,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:ms,onClick:oe=>Zt(oe),onDoubleClick:oe=>{oe.stopPropagation(),v(te.id,ot)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:z("block min-w-0 flex-1 truncate font-normal typography-ui-label",St?"text-foreground":"text-foreground/90"),children:Tn(ot,u)})}),H?.showFolderLabel&&Ie||Pe||De||ze||Ge>0||de&&de!=="default"||me||pe>0||st>0?t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[H?.showFolderLabel&&Ie?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Ie}):null,Pe?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(D,{name:"git-branch",className:z("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Pe})]}):De?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(D,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,Ge>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(D,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:Ge})]}):null,de&&de!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:de}):null,me?t.jsx(mu,{sessionId:te.id,running:Ve,className:"text-muted-foreground/70"}):null,pe>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[t.jsx(D,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:pe})]}):null,null]}):null]})]}),xt?t.jsx(D,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,t.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[t.jsx("div",{className:z("flex items-center justify-end",ge&&(G||Vt)?"opacity-0":ge?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Ve?t.jsx($s,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):_e?t.jsx(gu,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:Yt})}),ge?t.jsx("div",{className:z("absolute inset-0 flex items-center justify-end",G||Vt?"opacity-100":"pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100"),children:t.jsx(Cp,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:it,onMouseDown:Xt,onArchive:_t,onDelete:ps})}):null]}),nt&&!V?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:nt}):null]}),As]})}),Je&&tt?s.children.map(oe=>{const et=xe?xe(oe):{subtreeContainsEditing:ce,menuOpenSessionId:ae,nodeStructureKey:""};return t.jsx(i.Fragment,{children:ee(oe,n+1,ne??r,o,a,H?.globalSession?{globalSession:!0}:void 0,we,et)},oe.session.id)}):null,t.jsx(kp,{open:bt,onOpenChange:jt,descendantCount:qt,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:ft,onExport:Ct})]},te.id)}const Gp=i.memo($p,zp),Kp=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(Kt,{open:e,onOpenChange:s,children:t.jsx(Ht,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(ys,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:t.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&n?t.jsx(eh,{project:n,onIdentitySave:r}):null})})})});function Va(e){const{showDeletionDialog:s,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:a}=e;return t.jsxs(Ns,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>n(!s),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!s,children:[s?t.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:()=>{o()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:a})]})]})}function Hp(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=c=>ds(c);return t.jsx(Kt,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(fs,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`\\"${l(s.session)}\\" and its ${s.descendantCount} sub-task will be permanently deleted.`:`\\"${l(s.session)}\\" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`\\"${l(s.session)}\\" and its ${s.descendantCount} sub-task will be archived.`:`\\"${l(s.session)}\\" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`\\"${s?.session?l(s.session):"Untitled Session"}\\" will be permanently deleted.`:`\\"${s?.session?l(s.session):"Untitled Session"}\\" will be archived.`})]}),t.jsx(Va,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:s?.archivedBucket?"Delete":"Archive"})]})})}function Wp(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=s?.archivedBucket===!0,c=s?.sessionCount??0,d=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=l?c===1?`${c} session will be permanently deleted.`:`${c} sessions will be permanently deleted.`:c===1?`${c} session will be archived.`:`${c} sessions will be archived.`;return t.jsx(Kt,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:d}),t.jsx(fs,{children:u})]}),t.jsx(Va,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:l?"Delete":"Archive"})]})})}function Yp(e){const{value:s,setValue:n,onConfirm:r}=e,{git:o}=Gs(),[a,l]=i.useState(null),[c,d]=i.useState(!1),[u,f]=i.useState(!1),[h,x]=i.useState(!1),g=s?.worktree.path??null;i.useEffect(()=>{let S=!1;return l(null),d(!1),f(!1),x(!1),!s||!g?()=>{S=!0}:(o.getGitStatus(g).then(I=>{if(!S){if(typeof I?.isClean!="boolean"){d(!0);return}l(I)}}).catch(()=>{S||d(!0)}),()=>{S=!0})},[o,s,g]);const m=a?.isClean===!1,p=(a?.ahead??0)>0,y=p&&!s?.worktree.branch,b=s?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",A=!!(s&&a&&!c&&!s.hasActiveSession&&(!m&&!y||u)&&!h),v=s?.worktree.branch||s?.worktree.name||s?.worktree.path||"",C=async()=>{if(A){x(!0);try{await r({force:m})}finally{x(!1)}}};return t.jsx(Kt,{open:!!s,onOpenChange:S=>{!S&&!h&&n(null)},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-md gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:"Close worktree?"}),t.jsx(fs,{children:`Closing "${v}" removes its worktree directory. ${b}`})]}),c?t.jsx("div",{role:"alert",className:"rounded-md bg-[var(--status-error-background)] p-3 typography-ui-label text-[var(--status-error-foreground)]",children:"Unable to check this worktree's status. Refresh and try again."}):a===null?t.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,s?.hasActiveSession?t.jsx("div",{role:"alert",className:"rounded-md bg-[var(--status-warning-background)] p-3 typography-ui-label text-[var(--status-warning-foreground)]",children:"Stop the active session before closing this worktree."}):null,m?t.jsxs("div",{className:"space-y-3 rounded-md bg-[var(--status-warning-background)] p-3 text-[var(--status-warning-foreground)]",children:[t.jsx("p",{className:"typography-ui-label",children:"This worktree has uncommitted changes. They will be permanently removed."}),t.jsxs("label",{className:"flex items-start gap-2 typography-ui-label",children:[t.jsx(Cr,{checked:u,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),t.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,p?t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:a?.ahead===1?`This worktree has 1 unpushed commit. ${b}`:`This worktree has ${a?.ahead} unpushed commits. ${b}`}),y?t.jsxs("div",{className:"space-y-3 rounded-md bg-[var(--status-warning-background)] p-3 text-[var(--status-warning-foreground)]",children:[t.jsx("p",{className:"typography-ui-label",children:"Because this worktree is detached, its unpushed commits may be lost."}),t.jsxs("label",{className:"flex items-start gap-2 typography-ui-label",children:[t.jsx(Cr,{checked:u,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),t.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,t.jsxs(Ns,{className:"sm:justify-end",children:[t.jsx(Re,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:h,children:"Cancel"}),t.jsx(Re,{variant:"destructive",size:"sm",onClick:()=>{C()},disabled:!A,children:h?"Closing…":"Close worktree"})]})]})})}function qp(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(Kt,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:"Delete folder?"}),t.jsx(fs,{children:s&&(s.subFolderCount>0||s.sessionCount>0)?s.subFolderCount>0?s.subFolderCount===1?`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted. Sessions inside will not be deleted.`:`\\"${s?.folderName??""}\\" will be permanently deleted.`})]}),t.jsxs(Ns,{children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})}const Vp=({updateDialogOpen:e,setUpdateDialogOpen:s,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:a,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:h,setDeleteFolderConfirm:x,confirmDeleteFolder:g,closeWorktreeConfirm:m,setCloseWorktreeConfirm:p,confirmCloseWorktree:y,bulkDeleteConfirm:b,setBulkDeleteConfirm:A,confirmBulkDelete:v})=>t.jsxs(t.Fragment,{children:[t.jsx(Sa,{open:e,onOpenChange:s,info:n.info,downloading:n.downloading,downloaded:n.downloaded,progress:n.progress,error:n.error,onDownload:n.downloadUpdate,onRestart:n.restartToUpdate,runtimeType:n.runtimeType}),t.jsx(Kp,{open:!!r,onOpenChange:C=>{C||o(null)},project:r,onSave:a}),t.jsx(Hp,{value:l,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),t.jsx(qp,{value:h,setValue:x,onConfirm:g}),t.jsx(Yp,{value:m,setValue:p,onConfirm:y}),t.jsx(Wp,{value:b,setValue:A,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:v})]}),Qp=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=ye(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return tn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=ye(o.directory)?.toLowerCase();if(a&&s.has(a))return!0}return!1},void 0,"catalog")?t.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:t.jsx($s,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},li={selected:0,"active-project":1,expanded:2,visible:3,background:4};function Jp(e){const s=new Map,n=(r,o,a)=>{const l=ye(r??null);if(!l)return;const c=s.get(l);c&&li[c.priority]<=li[o]||s.set(l,{directory:l,priority:o,reason:a})};for(const r of e.projectSections){const o=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":o&&(a="expanded"),n(r.project.normalizedPath,a,o?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=o&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":o&&(d="visible"),n(l.directory,d,c?"worktree-expanded":"known-worktree")}}return n(e.currentDirectory,"selected","current-directory"),n(e.currentSessionDirectory,"selected","selected-session"),[...s.values()]}const Xp=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l})=>{const c=ve(d=>d.currentSessionDirectory);return i.useEffect(()=>{s.setBootstrapDemand(e,Jp({projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,o,l,c,e,n]),i.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},Zp=e=>{let s=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(s+=r.sessions.length);return s},em=e=>{const s=new Map;for(const n of e){let r=0;for(const o of n.groups)o.isArchivedBucket||(r+=o.sessions.length);s.set(n.project.id,r)}return s},tm=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),sm=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),nm=(e,s)=>{const n=new Map;for(const r of e){const o=new Set;for(const a of r.groups){if(a.isArchivedBucket)continue;if(a.sessions.some(c=>s.has(c.session.id))&&a.directory){const c=ye(a.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},rm=e=>e.map(s=>s.groups.some(n=>n.isArchivedBucket)?{...s,groups:s.groups.filter(n=>!n.isArchivedBucket)}:s),om=(e,s,n,r)=>{if(!n)return s;const o=e.find(c=>c.project.id===n);if(!o)return[];const a=ye(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&ye(c.directory)===a);return l?[{...o,groups:[l]}]:[]},im=(e,s)=>{const n=new Map,r=new Map;return e.forEach(o=>{const a=Yn(o.project.label?.trim()||_s(o.project.normalizedPath,s)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==a?l.branch:null,d={projectLabel:a,branchLabel:c},u=f=>{f.forEach(h=>{const x=o.project.normalizedPath.length,g=r.get(h.session.id)??-1;x<g||(n.set(h.session.id,{node:h,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:d}),r.set(h.session.id,x),h.children.length>0&&u(h.children))})};u(l.sessions)})}),n};function am({projectSections:e,flatSectionsForRender:s,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:a,activeSessionIdSet:l,unreadSessionIdSet:c}){const d=i.useMemo(()=>im(e,a),[e,a]),u=i.useMemo(()=>rm(s),[s]),f=i.useMemo(()=>om(n,u,r,o),[n,u,r,o]),h=i.useMemo(()=>Zp(e),[e]),x=i.useMemo(()=>em(e),[e]),g=i.useCallback(y=>{const b=e.find(A=>A.project.id===y);return b?tm(b,l):!1},[l,e]),m=i.useMemo(()=>nm(e,l),[l,e]),p=i.useCallback(y=>{const b=e.find(A=>A.project.id===y);return b?sm(b,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:h,sessionCountByProject:x,hasActiveSessionByProject:g,activeDirectoriesByProject:m,hasUnseenByProject:p}}const lm=({selectedCount:e,archivedBucket:s,onRestore:n,onDelete:r,onDone:o})=>{const a=s?"Delete":"Archive",l="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";return t.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-3 py-1.5",children:[t.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),t.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[s?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(D,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(Oe,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:z("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":a,children:t.jsx(D,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Oe,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:t.jsx(D,{name:"close",className:"h-4 w-4"})})}),t.jsx(Oe,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},cm=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:h}=e,x=ct(B=>B.enabled),g=ct(B=>B.selectedIds.size),m=g>0,p=ct(B=>B.selectedIds),y=ct(B=>B.scopeKey),b=i.useCallback(()=>{ct.getState().toggleMode()},[]),A=i.useCallback(()=>{ct.getState().disable()},[]),v=i.useMemo(()=>{if(!m||typeof document>"u")return!1;let B=!1,R=!1;for(const F of p){const V=document.querySelectorAll(`[data-session-row="${CSS.escape(F)}"]`);for(const G of V)G.getAttribute("data-session-archived")==="1"?R=!0:B=!0}return R&&!B},[m,p]),C=i.useMemo(()=>{if(y)return y;if(!m||typeof document>"u")return null;for(const B of p){const F=document.querySelector(`[data-session-row="${CSS.escape(B)}"]`)?.getAttribute("data-session-scope");if(F&&F.length>0)return F}return null},[m,p,y]),S=i.useMemo(()=>{if(!C)return[];const B=o.get(C);return B&&B.length>0?B.map(R=>R.scopeKey):[C]},[C,o]),I=i.useMemo(()=>S.flatMap(B=>r[B]??[]),[r,S]),k=i.useCallback(B=>{for(const R of S)if((r[R]??[]).some(F=>F.id===B))return R;return null},[r,S]),w=i.useMemo(()=>{if(!m)return!1;for(const B of S)for(const R of r[B]??[])for(const F of R.sessionIds)if(p.has(F))return!0;return!1},[r,S,m,p]),j=i.useCallback((B,R)=>{const F=Array.from(p);for(const V of S)V!==B&&l(V,F);a(B,R,F)},[a,l,p,S]),E=i.useCallback(B=>{if(!m)return;const R=k(B);R&&j(R,B)},[m,j,k]),T=i.useCallback(()=>{const B=S[0];if(!B||!m)return;const R=c(B);R&&j(B,R.id)},[c,m,j,S]),U=i.useCallback(()=>{if(!m)return;const B=Array.from(p);for(const R of S)l(R,B)},[l,p,S,m]),_=i.useCallback(async()=>{const B=Array.from(p);if(B.length!==0){if(v){const{deletedIds:R,failedIds:F}=await f(B);R.length>0&&ie.success(R.length===1?`Deleted ${R.length} session`:`Deleted ${R.length} sessions`),F.length>0&&ie.error(F.length===1?`Failed to delete ${F.length} session`:`Failed to delete ${F.length} sessions`)}else{const{archivedIds:R,failedIds:F}=await d(B);R.length>0&&ie.success(R.length===1?`Archived ${R.length} session`:`Archived ${R.length} sessions`),F.length>0&&ie.error(F.length===1?`Failed to archive ${F.length} session`:`Failed to archive ${F.length} sessions`)}ct.getState().clear()}},[d,v,f,p]),$=i.useCallback(()=>{if(!m)return;const B=p.size;if(!n){_();return}h({sessionCount:B,archivedBucket:v})},[v,_,p,n,h,m]),K=i.useCallback(async()=>{if(!m||!v)return;const B=Array.from(p),{restoredIds:R,failedIds:F}=await u(B);R.length>0&&ie.success(R.length===1?`Restored ${R.length} session`:`Restored ${R.length} sessions`),F.length>0&&ie.error(F.length===1?`Failed to restore ${F.length} session`:`Failed to restore ${F.length} sessions`),ct.getState().clear()},[v,m,p,u]),P=i.useCallback(async()=>{h(null),await _()},[_]);return i.useEffect(()=>{if(!x)return;const B=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),R=F=>{if(s)return;const V=F.target;if(V&&(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.isContentEditable))return;const G=B?F.metaKey:F.ctrlKey;if(F.key==="Escape"){F.preventDefault(),ct.getState().disable();return}if(G&&F.key==="Backspace"){F.preventDefault(),$();return}if(G&&(F.key==="a"||F.key==="A")){const M=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(M.length===0)return;F.preventDefault();const H=ct.getState().scopeKey??M[0]?.getAttribute("data-session-scope")??null,we=ae=>H?ae.getAttribute("data-session-scope")===H:!0,ce=M.filter(we).map(ae=>ae.getAttribute("data-session-row")).filter(ae=>typeof ae=="string"&&ae.length>0);if(ce.length===0)return;ct.getState().replaceAll(ce,H||null)}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[$,s,x]),{selectionModeEnabled:x,hasSelection:m,selectedIdsSize:g,bulkScopeIsArchived:v,derivedSelectionScope:C,bulkScopeFolders:I,bulkCanRemoveFromFolder:w,handleToggleSelectionMode:b,handleExitSelectionMode:A,handleBulkMoveToFolder:E,handleBulkCreateFolderAndMove:T,handleBulkRemoveFromFolder:U,handleBulkDelete:$,handleBulkRestore:K,confirmBulkDelete:P}},dm=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},um=hs()(to(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(s=>({stickyZoneHeaders:!s.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:s=>e({showRecentSection:s}),setShowArchivedSessions:s=>e({showArchivedSessions:s}),toggleRecentSection:()=>e(s=>({showRecentSection:!s.showRecentSection})),toggleArchivedSessions:()=>e(s=>({showArchivedSessions:!s.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:dm})),ci="oc.sessions.projectCollapse",di="oc.sessions.groupOrder",ui="oc.sessions.groupCollapse",fi="oc.sessions.activeSessionByProject",hi="oc.sessions.expandedParents.v3",fm=new Set,ur=[],It=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},hm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Rr("react.session_sidebar_render"),Ft("ui.session_sidebar.render"),Ft(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Ft(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=i.useState(!1),[u,f]=i.useState(""),h=i.useRef(null),x=i.useRef(null),[g,m]=i.useState(null),[p,y]=i.useState(""),[b,A]=i.useState(null),[v,C]=i.useState(new Set),S=i.useMemo(()=>jn(),[]),[I,k]=i.useState(new Set),[w,j]=i.useState(null),[E,T]=i.useState(null),[U,_]=i.useState(new Map),[$,K]=i.useState(new Map),[P,B]=i.useState(!1),[R,F]=i.useState(null),[V,G]=i.useState(null),[M,ee]=i.useState(""),[H,we]=i.useState(null),[ce,ae]=i.useState(null),[xe,be]=i.useState(null),[ge,Se]=i.useState(null),je=Ar(N=>N.ids),ke=Zc(i.useCallback(N=>e?N.rankById:Li,[e])),Ce=tn(N=>e?ed(N.catalog):"",void 0,"catalog"),Z=i.useMemo(()=>Ce?Ce.split("|"):ur,[Ce]),ue=i.useMemo(()=>new Set(Z),[Z]),L=td(Lr(N=>e?Object.entries(N.index.session.unseenCount).filter(([,q])=>q>0).map(([q])=>q).sort():ur)),Y=i.useMemo(()=>new Set(L),[L]),le=Ar(N=>N.toggle),[W,X]=i.useState(()=>{try{const N=jn().getItem(ui);if(!N)return new Set;const q=JSON.parse(N);return new Set(Array.isArray(q)?q.filter(Q=>typeof Q=="string"):[])}catch{return new Set}}),[te,ne]=i.useState(()=>{try{const N=jn().getItem(di);if(!N)return new Map;const q=JSON.parse(N),Q=new Map;return Object.entries(q).forEach(([Ee,Ke])=>{Array.isArray(Ke)&&Q.set(Ee,Ke.filter(Qe=>typeof Qe=="string"))}),Q}catch{return new Map}}),Ae=i.useMemo(()=>{try{const N=jn().getItem(fi);if(!N)return new Map;const q=JSON.parse(N),Q=new Map;return Object.entries(q).forEach(([Ee,Ke])=>{typeof Ke=="string"&&Ke.length>0&&Q.set(Ee,Ke)}),Q}catch{return new Map}},[]),Ie=i.useCallback(N=>{try{S.setItem(fi,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[S]),[Pe,De]=i.useState(new Map),Ge=i.useRef(0),de=Bs(N=>N.homeDirectory),ze=Bs(N=>N.currentDirectory),Ne=dt(N=>N.projects),Ye=dt(N=>N.activeProjectId),J=dt(N=>N.removeProject),Be=dt(N=>N.setActiveProjectIdOnly),We=dt(N=>N.updateProjectMeta),Ue=dt(N=>N.reorderProjects),Ve=se(N=>N.setActiveMainTab),gt=se(N=>N.setSettingsDialogOpen),Wt=se(N=>N.setSettingsPage),ot=se(N=>N.toggleHelpDialog),Je=se(N=>N.setSessionSwitcherOpen),xt=se(N=>N.setArchivePageOpen),tt=se(N=>N.notifyOnSubtasks),st=se(N=>N.showDeletionDialog),St=se(N=>N.setShowDeletionDialog),Yt=sd(u,120),ut=i.useMemo(()=>Yt.trim().toLowerCase(),[Yt]),qe=ut.length>0,bt=lt(N=>N.collapsedFolderIds),jt=lt(N=>N.foldersMap),Lt=lt(N=>N.getFoldersForScope),ft=lt(N=>N.createFolder),qt=lt(N=>N.renameFolder),Ot=lt(N=>N.deleteFolder),Ct=lt(N=>N.addSessionToFolder),Vt=lt(N=>N.addSessionsToFolder),Bt=lt(N=>N.removeSessionFromFolder),is=lt(N=>N.removeSessionsFromFolders),pe=lt(N=>N.toggleFolderCollapse),_e=lt(N=>N.getSessionFolderId);wh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:h});const me=nd(e),Te=zi(),{git:$e}=Gs(),Ze=Fi(),Qt=tn(N=>N.connection,void 0,"chrome"),nt=tn(N=>{for(const q of N.catalog.listStatusByDirectory.values())if(q==="ready")return!0;return!1},void 0,"catalog"),Jt=Nr({archived:!1}),kt=Nr({archived:!0}),it=`session-sidebar:${i.useId()}`,Xt=ve(N=>N.setCurrentSession),_t=ve(N=>N.updateSessionTitle),ps=ve(N=>N.shareSession),Zt=ve(N=>N.unshareSession),zt=Dr(N=>N.projects),ms=Dr(N=>N.refreshProject),ht=i.useMemo(()=>rd(Ne,{projects:zt}),[Ne,zt]),As=i.useMemo(()=>{const N=new Map;for(const q of Ne){const Q=ye(q.path);if(!Q)continue;const Ee=zt.get(Q)?.error;Ee&&N.set(Q,Ee)}return N},[Ne,zt]);i.useEffect(()=>{if(!w)return;const N=Ne.find(Q=>Q.id===w);if(!N){j(null),T(null);return}if(!E)return;(ht.get(ye(N.path)??N.path)??[]).some(Q=>ye(Q.path)===ye(E))||(T(null),ie.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[ht,Ne,w,E]);const oe=ve(N=>N.openNewSessionDraft),et=i.useCallback(N=>{se.getState().closeMainSurfaces(),oe(N),r?.()},[r,oe]),pt=Mn(Lr(N=>({checkForUpdates:N.checkForUpdates,available:N.available,runtimeType:N.runtimeType,info:N.info,downloading:N.downloading,downloaded:N.downloaded,progress:N.progress,error:N.error,downloadUpdate:N.downloadUpdate,restartToUpdate:N.restartToUpdate}))),Nt=i.useMemo(()=>od(Ne,ht,{includeWorktrees:!0}),[ht,Ne]),yt=i.useMemo(()=>Jt.filter(N=>Fh(N,Nt,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:de})),[Jt,de,Nt]),wt=i.useMemo(()=>[...yt,...kt],[kt,yt]),gn=Wn(),xn=i.useMemo(()=>`${gn}|${Ne.map(N=>`${N.id}:${ye(N.path)??""}`).join("|")}`,[Ne,gn]),Ks=i.useMemo(()=>{const N=new Set;let q=!0;for(const Q of Ne){const Ee=ye(Q.path);if(!Ee)continue;const Ke=zt.get(Ee)?.status??"idle";Ke==="failed"&&N.add(Ee),(Ke==="idle"||Ke==="loading")&&(q=!1)}return{complete:q,unresolved:N}},[Ne,zt]),Vn=Ks.complete?xn:null,Qn=!Ks.complete,bn=Ks.unresolved,{isTablet:Hs}=ks(),Is=s||Hs,O=yh({mobileVariant:s,isTablet:Hs}),{buildGroupSearchText:re,filterSessionNodesForSearch:fe,buildGroupedSessions:He}=bh({homeDirectory:de,pinnedSessionIds:je,sessionOrderRanks:ke}),{scheduleCollapsedProjectsPersist:es}=Sh({safeStorage:S,keys:{sessionExpanded:hi,projectCollapse:ci,groupOrder:di,groupCollapse:ui},groupOrderByProject:te,collapsedGroups:W,setExpandedParents:C,setCollapsedProjects:k}),at=i.useMemo(()=>id(yt,je,ke),[je,ke,yt]),gs=i.useMemo(()=>at.map(N=>N.id).join("|"),[at]),Ut=i.useRef(null),co=i.useMemo(()=>{const N=Ut.current;if(N&&N.signature===gs)return N.map;const q=new Map(at.map((Q,Ee)=>[Q.id,Ee]));return Ut.current={signature:gs,map:q},q},[at,gs]),Za=i.useMemo(()=>{const N=new Map;return at.forEach(q=>{const Q=q.parentID;if(!Q)return;const Ee=N.get(Q)??[];Ee.push(q),N.set(Q,Ee)}),N.forEach(q=>q.sort((Q,Ee)=>Qr(Q,Ee,je,ke))),N},[at,je,ke]),el=i.useMemo(()=>t.jsx(js,{icon:"chat-new",mobileVariant:s,onClick:()=>et(),children:"New session"}),[s,et]),tl=i.useMemo(()=>Ne.find(N=>N.id===b)??null,[Ne,b]),sl=i.useCallback(N=>{b&&We(b,{label:N.label,defaultModel:N.defaultModel??null})},[b,We]),nl=i.useCallback(()=>{const N=Mn.getState();if(N.available&&N.info){B(!0);return}pt.checkForUpdates().then(()=>{const{available:q,error:Q}=Mn.getState();if(Q){ie.error("Failed to check for updates",{description:Q});return}if(!q){ie.success("You are on the latest version");return}B(!0)})},[pt]),Ds=ad(),uo=i.useCallback(()=>{if(s&&Je(!1),r?.(),Ds?.openSettings){Ds.openSettings();return}gt(!0)},[Ds,s,r,Je,gt]),rl=pt.available&&(pt.runtimeType==="desktop"||pt.runtimeType==="web"),ol=ve(N=>N.deleteSession),fo=ve(N=>N.deleteSessions),il=ve(N=>N.archiveSession),ho=ve(N=>N.archiveSessions),al=ve(N=>N.unarchiveSession),ll=ve(N=>N.unarchiveSessions),{copiedSessionId:cl,handleSessionSelect:dl,handleSessionDoubleClick:ul,handleSaveEdit:fl,handleCancelEdit:hl,handleShareSession:pl,handleCopyShareUrl:ml,handleCopySessionId:gl,handleUnshareSession:xl,handleDeleteSession:bl,handleRestoreSession:yl,confirmDeleteSession:wl}=vh({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:Ve,setSessionSwitcherOpen:Je,setCurrentSession:Xt,updateSessionTitle:_t,shareSession:ps,unshareSession:Zt,deleteSession:ol,deleteSessions:fo,archiveSession:il,archiveSessions:ho,unarchiveSession:al,childrenMap:Za,showDeletionDialog:st,setDeleteSessionConfirm:we,deleteSessionConfirm:H,setEditingId:m,setEditTitle:y,editingId:g,editTitle:p}),vl=i.useCallback(()=>{if(!ce)return;const{scopeKey:N,folderId:q}=ce;ae(null),Ot(N,q)},[ce,Ot]),po=i.useCallback(()=>{Cs.requestDirectoryDialog()},[]),Sl=i.useCallback(N=>{C(q=>{const Q=xu(q,N);try{S.setItem(hi,JSON.stringify(Array.from(Q)))}catch{}return Q})},[S]),mo=i.useCallback((N,q)=>{if(!N)return null;q&&bt.has(q)&&pe(q);const Q=ft(N,"New folder",q);return G(Q.id),ee(Q.name),Q},[bt,pe,ft]),Ws=It(dl),jl=It(ul),Cl=It(fl),kl=It(hl),Nl=It(pl),Al=It(ml),Il=It(gl),Dl=It(xl),Rl=It(bl),El=It(yl),Jn=It(mo),go=i.useCallback((N,q)=>{K(Q=>{const Ee=new Map(Q);return Ee.set(N,q+7),Ee})},[]),yn=i.useCallback(N=>{K(q=>{if(!q.has(N))return q;const Q=new Map(q);return Q.delete(N),Q})},[]),xo=i.useCallback(N=>{K(q=>{let Q=!1;const Ee=new Map(q),Ke=`${N}:`;for(const Qe of Ee.keys())Qe.startsWith(Ke)&&(Ee.delete(Qe),Q=!0);return Q?Ee:q})},[]),Pl=i.useCallback(N=>{Ge.current=Date.now()+150,xo(N),k(q=>{const Q=new Set(q);Q.has(N)?Q.delete(N):Q.add(N);try{S.setItem(ci,JSON.stringify(Array.from(Q)))}catch{}return es(Q),Q})},[xo,S,es]),as=i.useMemo(()=>Ne.map(N=>({...N,normalizedPath:ye(N.path)})).filter(N=>!!N.normalizedPath),[Ne]),Ml=i.useMemo(()=>as.map(N=>N.normalizedPath),[as]),bo=ld(e?Ml:ur);Ih({enabled:e,normalizedProjects:as,gitRepoStatus:bo,setProjectRepoStatus:_,setProjectRootBranches:De});const Tl=ve(N=>N.isLoading),yo=i.useMemo(()=>Oh(yt,as,ht,kt),[kt,ht,as,yt]);Mh({enabled:e,hasAuthoritativeGlobalSessions:nt,sessions:wt});const{getSessionsForProject:Fl,getArchivedSessionsForProject:Ll}=Dh({ownership:yo});dh({enabled:e,normalizedProjects:as,ownership:yo,isSessionsLoading:Tl,hasAuthoritativeGlobalSessions:nt,isWorktreeTopologyLoading:Qn,unresolvedWorktreeProjectPaths:bn,foldersMap:jt,createFolder:ft,addSessionToFolder:Ct});const wo=i.useRef(!1);Ye&&U.has(Ye)&&(wo.current=!!U.get(Ye));const Ol=um(N=>N.showArchivedSessions),Xn=dt(N=>N.manualProjectOrder),vo=i.useRef(new Set),wn=bu(vo.current,v,"project");vo.current=wn;const Zn={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:Hs,catalogSessions:Jt,archivedSessions:kt,projects:Ne,activeProjectId:Ye,manualProjectOrder:Xn,currentDirectory:ze,availableWorktreesByProject:ht,pinnedSessionIds:je,sessionOrderRanks:ke,foldersMap:jt,collapsedFolderIds:bt,gitBranches:me,gitRepoStatus:bo,updateStore:pt,showArchivedSessions:Ol,projectRepoStatus:U,projectRootBranches:Pe,resolvedWorktreeTopologyKey:Vn,unresolvedWorktreeProjectPaths:bn,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:g,editTitle:p,editingProjectDialogId:b,expandedParents:v,collapsedProjects:I,visibleSessionCountByGroup:$,updateDialogOpen:P,openSidebarMenuKey:R,renamingFolderId:V,renameFolderDraft:M,deleteSessionConfirm:H,deleteFolderConfirm:ce,bulkDeleteConfirm:ge,collapsedGroups:W},So=i.useRef(null),jo=So.current;if(jo){let N=!1;for(const q of Object.keys(Zn))Object.is(jo[q],Zn[q])||(Ft(`ui.session_sidebar.source.${q}`),N=!0);N||Ft("ui.session_sidebar.source.parent_or_context")}So.current=Zn;const Bl=i.useMemo(()=>{const N=new Map(Xn.map((q,Q)=>[q,Q]));return[...as].sort((q,Q)=>(N.get(q.id)??1/0)-(N.get(Q.id)??1/0))},[Xn,as]),{projectSections:At,groupSearchDataByGroup:Co,sectionsForRender:_l,flatSectionsForRender:er,searchMatchCount:zl}=fh({normalizedProjects:Bl,getSessionsForProject:Fl,getArchivedSessionsForProject:Ll,availableWorktreesByProject:ht,projectRepoStatus:U,projectRootBranches:Pe,lastRepoStatus:wo.current,buildGroupedSessions:He,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:ut,filterSessionNodesForSearch:fe,buildGroupSearchText:re,foldersMap:jt}),vn=i.useMemo(()=>{const N=yt.filter(Q=>Hn(Ts(Q),de));if(N.length===0)return null;const q=He(N,"~",[],null,!1).map(Q=>qe?{...Q,sessions:fe(Q.sessions,ut)}:Q).filter(Q=>Q.sessions.length>0&&!Q.isArchivedBucket);return q.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:q}},[He,fe,qe,de,ut,yt]),Ul=i.useMemo(()=>{if(!qe||!vn)return 0;const N=q=>q.reduce((Q,Ee)=>Q+1+N(Ee.children),0);return vn.groups.reduce((q,Q)=>q+N(Q.sessions),0)},[vn,qe]),$l=i.useMemo(()=>t.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[t.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),t.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Gl}=uh(te),ko=i.useRef(!1);i.useEffect(()=>{if(ko.current||At.length===0)return;const N=At.flatMap(q=>q.groups.filter(Q=>Q.isArchivedBucket).map(Q=>`${q.project.id}:${Q.id}`));N.length>0&&X(q=>new Set([...q,...N])),ko.current=!0},[At]);const{filteredSectionsForSidebarRender:Kl,totalSessionCount:Hl,sessionCountByProject:Wl,hasActiveSessionByProject:Yl,activeDirectoriesByProject:Ys,hasUnseenByProject:ql}=am({projectSections:At,flatSectionsForRender:er,sectionsForRender:_l,selectedSpaceId:w,selectedWorktreePath:E,homeDirectory:de,activeSessionIdSet:ue,unreadSessionIdSet:Y}),tr=i.useCallback(N=>{if(j(N),T(null),!N)return;Be(N);const q=At.find(Ke=>Ke.project.id===N),Q=q?.groups.find(Ke=>Ke.isMain),Ee=Q?.sessions[0]?.session;Ee?Ws(Ee.id,Q?.directory??q?.project.normalizedPath??null,{keepPanelOpen:!0}):q&&et({selectedProjectId:N,directoryOverride:q.project.normalizedPath})},[et,At,Be,Ws]),Vl=s?"flex size-10 shrink-0 items-center justify-center rounded-full leading-none text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Ql=s?"size-5":"h-4.5 w-4.5",Sn=It((N,q=0,Q,Ee,Ke=!1,Qe,$t="project",Rs)=>t.jsx(Gp,{node:N,depth:q,groupDirectory:Q,projectId:Ee,archivedBucket:Ke,pinnedSessionIds:je,expandedParents:wn,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:ut,notifyOnSubtasks:tt,editingId:g,setEditingId:m,editTitle:p,setEditTitle:y,handleSaveEdit:Cl,handleCancelEdit:kl,toggleParent:Sl,handleSessionSelect:Ws,handleSessionDoubleClick:jl,togglePinnedSession:le,handleShareSession:Nl,copiedSessionId:cl,handleCopyShareUrl:Al,handleCopySessionId:Il,handleUnshareSession:Dl,openSidebarMenuKey:R,setOpenSidebarMenuKey:F,renamingFolderId:V,getFoldersForScope:Lt,getSessionFolderId:_e,removeSessionFromFolder:Bt,addSessionToFolder:Ct,createFolderAndStartRename:Jn,handleDeleteSession:Rl,handleRestoreSession:El,mobileVariant:s,alwaysShowActions:Is,allowQuickArchiveAction:O,renderSessionNode:Sn,secondaryMeta:Qe,renderContext:$t,subtreeContainsEditing:Rs?.subtreeContainsEditing??fm,menuOpenSessionId:Rs?.menuOpenSessionId??null,nodeStructureKey:Rs?.nodeStructureKey??"",childRenderExtrasFor:Rs?.childRenderExtrasFor})),Jl=i.useMemo(()=>{const N=new Map;return er.forEach(q=>{const Q=q.groups.find(Ee=>!Ee.isArchivedBucket);Q?.folderScopes&&Q.folderScopes.length>0&&N.set(q.project.id,Q.folderScopes)}),N},[er]),Xl=i.useCallback((N,q)=>{const Q=[];return q.forEach(Ee=>{Ee.isArchivedBucket||(Q.push(Ee.directory),Ee.folderScopes?.forEach(Ke=>Q.push(Ke.directory)))}),t.jsx(Qp,{directories:Q})},[]),No=i.useCallback(N=>{yn(N),X(q=>{const Q=new Set(q);return Q.has(N)?Q.delete(N):Q.add(N),Q})},[yn]),Zl=i.useCallback((N,q,Q,Ee,Ke,Qe,$t)=>t.jsx(op,{group:N,groupKey:q,projectId:Q,hideGroupLabel:Ee,dragHandleProps:Ke,compactBodyPadding:Qe,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:ut,groupSearchDataByGroup:Co,visibleSessionCount:$.get(q),collapsedGroups:W,hideDirectoryControls:a,collapsedFolderIds:bt,toggleFolderCollapse:pe,renameFolder:qt,deleteFolder:Ot,showDeletionDialog:st,setDeleteFolderConfirm:ae,renderSessionNode:Sn,showMoreGroupSessions:go,resetGroupSessionLimit:yn,mobileVariant:s,alwaysShowActions:Is,activeProjectId:Ye,setActiveProjectIdOnly:Be,setActiveMainTab:Ve,setSessionSwitcherOpen:Je,openNewSessionDraft:et,addSessionToFolder:Ct,createFolderAndStartRename:Jn,renamingFolderId:V,renameFolderDraft:M,setRenameFolderDraft:ee,setRenamingFolderId:G,pinnedSessionIds:je,expandedParents:wn,sessionOrderIndex:co,editingId:g,editTitle:p,openSidebarMenuKey:R,activeActivitySessionIds:ue,unreadActivitySessionIds:Y,notifyOnSubtasks:tt,onToggleCollapsedGroup:No,scrollContainerRef:$t}),[qe,ut,Co,$,W,a,bt,pe,qt,Ot,st,Sn,go,yn,s,Is,Ye,Be,Ve,Je,et,Ct,Jn,V,M,je,wn,co,g,p,R,ue,Y,tt,No]),Ao=!!(V||g||b),{selectionModeEnabled:sr,hasSelection:Io,selectedIdsSize:ec,bulkScopeIsArchived:tc,derivedSelectionScope:sc,bulkScopeFolders:nc,bulkCanRemoveFromFolder:rc,handleToggleSelectionMode:oc,handleExitSelectionMode:ic,handleBulkMoveToFolder:ac,handleBulkCreateFolderAndMove:lc,handleBulkRemoveFromFolder:cc,handleBulkDelete:dc,handleBulkRestore:uc,confirmBulkDelete:fc}=cm({isInlineEditing:Ao,showDeletionDialog:st,foldersMap:jt,folderScopesByProject:Jl,addSessionsToFolder:Vt,removeSessionsFromFolders:is,createFolderAndStartRename:mo,archiveSessions:ho,unarchiveSessions:ll,deleteSessions:fo,setBulkDeleteConfirm:Se}),Do=i.useCallback(()=>{se.getState().closeMainSurfaces(),Ve("chat"),s&&Je(!1),oe(),r?.()},[s,r,oe,Ve,Je]),hc=i.useCallback((N,q)=>{const Q=Ne.find(Qe=>Qe.id===N);if(!Q)return;const Ee=ye(q.path)?.toLowerCase(),Ke=!!(Ee&&Ys.get(N)?.has(Ee));be({projectId:N,projectPath:Q.path,worktree:q,hasActiveSession:Ke})},[Ys,Ne]),pc=i.useCallback(async({force:N})=>{const q=xe;if(!q)return;const Q=ye(q.worktree.path)?.toLowerCase();if(!!(Q&&Ys.get(q.projectId)?.has(Q))){be({...q,hasActiveSession:!0}),ie.warning("Stop the active session before closing this worktree.");return}if(!$e.deleteGitWorktree){ie.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await $e.deleteGitWorktree(q.projectPath,{directory:q.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let Qe=await ms(q.projectPath,$e);const $t=ye(q.worktree.path);Qe!==null&&$t!==null&&Qe.some(gc=>ye(gc.path)===$t)&&(Qe=await ms(q.projectPath,$e));const Rs=$t!==null&&ye(ze)===$t,mc=$t!==null&&w===q.projectId&&ye(E)===$t;(Rs||mc)&&tr(q.projectId),be(null),Qe===null?ie.warning("Worktree closed, but the sidebar could not be refreshed."):ie.success("Worktree closed.")}catch(Ke){const Qe=Ke instanceof Error?Ke.message:"Try again.";ie.error("Failed to close worktree.",{description:Qe})}},[Ys,xe,ze,$e,tr,ms,w,E]);return t.jsx(cd,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:h,className:z("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(Xp,{owner:it,childStores:Ze,projectSections:At,activeProjectId:Ye,collapsedProjects:I,collapsedGroups:W,currentDirectory:ze}),t.jsx(ph,{projectSections:At,activeProjectId:Ye,initialActiveSessionByProject:Ae,persistActiveSessionByProject:Ie,handleSessionSelect:Ws,mobileVariant:s,openNewSessionDraft:oe,setActiveMainTab:Ve,setSessionSwitcherOpen:Je}),t.jsx(ch,{enabled:e,sortedSessions:at,prefetchSession:async N=>{await Te.syncSession(N)}}),!a&&!s?t.jsx(ap,{onNewSession:Do,showSidebarToggle:!0}):null,t.jsx(ip,{hideDirectoryControls:a,handleOpenDirectoryDialog:po,onOpenArchive:()=>{s&&Je(!1),xt(!0)},onOpenSettings:s?uo:void 0,onOpenInstances:s?Ds?.openInstances:void 0,instanceLabel:s?Ds?.instanceLabel:void 0,onOpenUpdate:s?Ds?.openUpdate:void 0,headerActionIconClass:Ql,headerActionButtonClass:Vl,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:qe,searchMatchCount:zl+(w===null?Ul:0),selectionModeEnabled:sr,onToggleSelectionMode:oc,mobileVariant:s}),Qt==="error"||Qt==="unavailable"?t.jsx("div",{role:"alert",className:"mx-3 mb-2 rounded bg-[var(--status-error-background)] p-2 text-xs text-[var(--status-error-foreground)]",children:"Unable to reach server"}):null,!a&&At.length>0?t.jsx(dp,{projects:At.map(N=>N.project),selectedProjectId:w,selectedWorktreePath:E,worktreesByProject:ht,worktreeErrorsByProject:As,onSelectProject:tr,onSelectWorktree:(N,q)=>{j(N),T(q),Be(N);const Ke=At.find(Qe=>Qe.project.id===N)?.groups.find(Qe=>ye(Qe.directory)===ye(q))?.sessions[0]?.session;Ke?Ws(Ke.id,q,{keepPanelOpen:!0}):et({selectedProjectId:N,directoryOverride:q})},onCloseWorktree:hc,onOpenDirectoryDialog:po,onOpenProjectEditDialog:A,onRemoveProject:J,totalSessionCount:Hl,getSessionCountForProject:N=>Wl.get(N)??0,hasActiveSessionByProject:Yl,activeDirectoriesByProject:Ys,hasUnseenByProject:ql,homeDirectory:de,mobileVariant:s}):null,t.jsx(pp,{sectionsForRender:Kl,allFoldersOnlySection:w===null?vn:null,projectSections:At,activeProjectId:Ye,showOnlyMainWorkspace:l,hasSessionSearchQuery:qe,emptyState:el,searchEmptyState:$l,isAllFoldersView:w===null,pinnedSessionIds:je,renderSessionNode:Sn,renderGroupSessions:Zl,homeDirectory:de,collapsedProjects:I,hideDirectoryControls:a,projectRepoStatus:U,mobileVariant:s,alwaysShowActions:Is,toggleProject:Pl,setActiveProjectIdOnly:Be,setActiveMainTab:Ve,setSessionSwitcherOpen:Je,openNewSessionDraft:et,openProjectEditDialog:A,removeProject:J,reorderProjects:Ue,getOrderedGroups:Gl,setGroupOrderByProject:ne,renderProjectStatusIndicator:Xl,openSidebarMenuKey:R,setOpenSidebarMenuKey:F,isInlineEditing:Ao}),s&&!(sr&&Io)?t.jsx("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-sidebar via-sidebar/85 to-transparent px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-10",children:t.jsx(Re,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:Do,"aria-label":"New session",children:t.jsx(D,{name:"chat-new",className:"size-4"})})}):null,sr&&Io?t.jsx(lm,{selectedCount:ec,scopeKey:sc,scopeFolders:nc,archivedBucket:tc,onMoveToFolder:ac,onCreateFolderAndMove:lc,onRemoveFromFolder:cc,canRemoveFromFolder:rc,onRestore:uc,onDelete:dc,onDone:ic}):null,s?null:t.jsx(up,{onOpenSettings:uo,onOpenShortcuts:ot,onOpenAbout:()=>{Wt("about"),gt(!0)},onOpenUpdate:nl,showRuntimeButtons:!0,showUpdateButton:rl}),t.jsx(Vp,{updateDialogOpen:P,setUpdateDialogOpen:B,updateStore:pt,editingProject:tl,setEditingProjectDialogId:A,handleSaveProjectEdit:sl,deleteSessionConfirm:H,setDeleteSessionConfirm:we,showDeletionDialog:st,setShowDeletionDialog:St,confirmDeleteSession:wl,deleteFolderConfirm:ce,setDeleteFolderConfirm:ae,confirmDeleteFolder:vl,closeWorktreeConfirm:xe,setCloseWorktreeConfirm:be,confirmCloseWorktree:pc,bulkDeleteConfirm:ge,setBulkDeleteConfirm:Se,confirmBulkDelete:fc})]})})},Rx=i.memo(hm),pi=6,Dt=.18,Zs=1.2,en=.38,Fn=48,pm=(e,s)=>e==="left"?s<0:s>0,Ex=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Px=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,mi=(e,s,n,r)=>e==="left"?s?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):s?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),Mx=e=>{const{side:s,dx:n,dy:r,dt:o,progress:a,isDragging:l}=e,c=n/Math.max(1,o);if(l){const d=s==="left"?c<-Dt:c>Dt,u=s==="left"?c>Dt:c<-Dt;return d||!u&&a<en}return Math.abs(n)>=Fn&&Math.abs(r)<=Math.abs(n)*Zs&&pm(s,n)},mm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:o,progress:a}=e,l=r/Math.max(1,o);return s==="left"?n?l<-Dt?!1:l>Dt?!0:a>en:l>Dt?!0:l<-Dt?!1:a>en:n?l>Dt?!1:l<-Dt?!0:a>en:l<-Dt?!0:l>Dt?!1:a>en},gm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',xm=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(gm);if(a&&s.contains(a))return!0}else{const a=e.closest("[data-no-drawer-swipe]");if(a&&s.contains(a))return!0}let o=e;for(;o&&o!==s;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const a=getComputedStyle(o).overflowX;if(a==="auto"||a==="scroll")return!0}o=o.parentElement}return!1},Ln=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),qr=512*1024,bm=new TextEncoder,ym=new TextDecoder,fr=e=>{const s=bm.encode(e);if(s.byteLength<=qr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-qr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:ym.decode(r),byteLength:r.byteLength}},Es=(e,s)=>`${e}\0${s}`,hr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},wm="terminal-store";let gi=!1,xi=0;const Rn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(xi+=1,`tab-${Date.now().toString(36)}-${xi.toString(36)}`),pr=e=>typeof e=="object"&&e!==null,vm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function rt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const Sm=/^Terminal(?: (\d+))?$/,jm=e=>{let s=0;for(const n of e){const r=Sm.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(s=Math.max(s,o))}return s===0?"Terminal":`Terminal ${s+1}`},mr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),gr=e=>({tabs:[e],activeTabId:e.id}),Tt=(e,s)=>e.tabs.findIndex(n=>n.id===s);let xr=null,br=null;const Cm=e=>{if(br&&xr?.sessions===e.sessions&&xr.nextTabId===e.nextTabId)return br;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return xr={sessions:e.sessions,nextTabId:e.nextTabId},br=s,s},km=()=>{const e=lu(()=>Qd());if(!e)return;let s=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==s)return s=r.state,e.setItem(n,r)},removeItem:n=>(s=null,e.removeItem(n))}},he=hs()(Vi(to((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=rt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=Rn(),c=mr(l,"Terminal");return a.set(r,gr(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=rt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=rt(n),o=s().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(l=>l.id===a)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>s().buffers.get(Es(rt(n),r))??Ln,createTab:n=>{const r=rt(n);if(!r)return"tab-invalid";const o=Rn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=jm(c?.tabs??[]),f=mr(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,gr(f)),{sessions:l,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=rt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Tt(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=rt(n),l=o.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=Tt(u,r);if(f<0||u.tabs[f]?.label===l)return c;const h=[...u.tabs];return h[f]={...h[f],label:l},d.set(a,{...u,tabs:h}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Tt(d,r);if(u<0)return l;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return l;const h=[...d.tabs];return h[u]={...h[u],iconKey:f},c.set(a,{...d,tabs:h}),{sessions:c}})},closeTab:(n,r)=>{const o=rt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Tt(c,r);if(d<0)return a;const u=c.tabs.filter(p=>p.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,p])=>!(p.directory===o&&p.tabId===r))),h=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,x=Es(o,r),g=a.buffers.has(x)?hr(a.buffers,p=>p===x):null;if(u.length===0){const p=Rn(),y=mr(p,"Terminal");return l.set(o,gr(y)),{sessions:l,nextTabId:a.nextTabId+1,...g?{buffers:g}:{},...h?{projectActionRuns:f}:{}}}let m=c.activeTabId;return c.activeTabId===r&&(m=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:m}),{sessions:l,...g?{buffers:g}:{},...h?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Tt(d,r);if(u<0)return l;const f=d.tabs[u],h=o!==null&&f.terminalSessionId!==o,x=o?"running":f.terminalSessionId?"exited":f.lifecycle,g={...f,terminalSessionId:o,lifecycle:x,isConnecting:!1},m=Es(a,r),p=h&&l.buffers.has(m)?hr(l.buffers,b=>b===m):null,y=[...d.tabs];return y[u]=g,c.set(a,{...d,tabs:y}),{sessions:c,...p?{buffers:p}:{}}})},setTabLifecycle:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Tt(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(a,{...d,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Tt(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(a,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,a)=>{const l=rt(n);e(c=>{const d=c.sessions.get(l);if(!d||Tt(d,r)<0)return c;const u=Es(l,r),f=c.buffers.get(u)??Ln;if(f.lastSequence>a)return c;const h=fr(o);if(f.lastSequence===a&&f.byteLength===h.byteLength&&f.chunks.map(m=>m.data).join("")===h.text)return c;const x=c.nextChunkId,g=new Map(c.buffers);return g.set(u,{chunks:h.text?[{id:x,data:h.text,byteLength:h.byteLength}]:[],byteLength:h.byteLength,lastSequence:a}),{buffers:g,nextChunkId:h.text?x+1:x}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=rt(n);e(d=>{const u=d.sessions.get(c);if(!u||Tt(u,r)<0)return d;const f=Es(c,r),h=d.buffers.get(f)??Ln;if(a!==void 0&&a<=h.lastSequence)return d;const x=d.nextChunkId,g=fr(o),m=l!==void 0&&l!==o?fr(l).text:void 0,p={id:x,data:g.text,...m!==void 0?{replayData:m}:{},byteLength:g.byteLength},y=[...h.chunks,p];let b=h.byteLength+p.byteLength;for(;b>qr&&y.length>1;){const v=y.shift();if(!v)break;b-=v.byteLength}const A=new Map(d.buffers);return A.set(f,{chunks:y,byteLength:b,lastSequence:a??h.lastSequence}),{buffers:A,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=rt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const f=Tt(u,r);if(f<0)return c;const h=u.tabs[f],x=a.autoOpened??h.previewAutoOpened,g=a.locked??h.previewUrlLocked;if(h.previewUrl===o&&h.previewAutoOpened===x&&h.previewUrlLocked===g)return c;const m=[...u.tabs];return m[f]={...h,previewUrl:o,previewAutoOpened:x,previewUrlLocked:g},d.set(l,{...u,tabs:m}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=rt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Tt(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const f=[...c.tabs];return f[d]={...u,previewAutoOpened:!0},l.set(o,{...c,tabs:f}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=rt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Es(r,""),c=hr(o.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:wm,storage:km(),partialize:Cm,merge:(e,s)=>{if(!pr(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!pr(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],h=[],x=new Map;for(const y of f){if(!pr(y))continue;const b=typeof y.id=="string"?y.id:null;if(!b)continue;const A=vm(b);A!==null&&(o=Math.max(o,A));const v=A===null?b:Rn();x.set(b,v),h.push({id:v,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(h.length===0)continue;const g=typeof u.activeTabId=="string"?u.activeTabId:null,m=g?x.get(g)??g:null,p=m?h.some(y=>y.id===m):!1;r.set(d,{tabs:h,activeTabId:p?m:h[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,o+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!gi){gi=!0;const e=he.persist,s=()=>{he.getState().hasHydrated||he.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Nm(e){const{colors:s}=e,n=s.syntax.base;return{background:s.surface.background,foreground:n.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:s.surface.elevatedForeground}}function Am(e,s,n,r,o=!1){const l=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",fontSize:s,fontFamily:l,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:o}}const yr=["\x1B[0m","\x1B[m"],Im=e=>{const s=e.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(s)?.[1];if(n){const a=n.length<=4?n.slice(0,3).split("").map(l=>l+l).join(""):n.slice(0,6);return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16)]}const r=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(s);if(!r)return null;const o=r.slice(1,4).map(Number);return o.some(a=>a<0||a>255)?null:o},bi=e=>{const s=Im(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},Dm=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let o=0;const a=Math.max(...yr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);yr.some(f=>f.length>u.length&&f.startsWith(u))&&(o=d)}const l=o>0?r.slice(-o):"";let c=o>0?r.slice(0,-o):r;for(const d of yr)c=c.replaceAll(d,n);return{data:c,carry:l}},Rm=(e,s,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(o-1,l))}},Em=(e,s)=>{const n=Math.max(0,Math.min(e.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,a=n;for(;o>0&&r(e[o-1]);)o-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:o,endColumn:a}};let Pm=null;const Mm=()=>Pm??=vs(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,24])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Tm=2e3,Fm=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(s=>setTimeout(s,Tm))]).then(()=>{})},Lm=(e,s,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${n}px ${s}`;const o=r.measureText("M"),a=Math.ceil(o.width),l=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(a<1||l<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/a)),rows:Math.max(1,Math.floor((e.clientHeight-u)/l))}},Qa=i.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},h)=>{const x=i.useRef(null),g=i.useRef(null),m=i.useRef(null),p=i.useRef(n),y=i.useRef(r),b=i.useRef(null),A=i.useRef(null),v=i.useRef(null),C=i.useRef(""),S=i.useRef(""),I=i.useRef(bi(o.background)),k=i.useRef(!1),w=i.useRef(0),j=i.useRef(f),E=i.useRef(!1),[T,U]=i.useState(0),[_,$]=i.useState(0);p.current=n,y.current=r,j.current=f,I.current=bi(o.background),i.useLayoutEffect(()=>{const R=x.current;if(!R)return;const F=Lm(R,a,l);A.current=F,F&&y.current(F.cols,F.rows)},[a,l]);const K=i.useCallback(()=>{const R=x.current,F=g.current;if(!R||!F||!m.current||!j.current)return;const V=R.getBoundingClientRect();if(!(V.width<24||V.height<24))try{m.current.fit();const G={cols:F.cols,rows:F.rows};(!b.current||b.current.cols!==G.cols||b.current.rows!==G.rows)&&(b.current=G,y.current(G.cols,G.rows)),E.current||(E.current=!0,U(M=>M+1))}catch{}},[]),P=i.useCallback(()=>{if(k.current||!C.current||!g.current)return;const R=g.current,F=C.current;C.current="";const V=Dm(F,S.current,I.current);if(S.current=V.carry,!V.data){C.current&&P();return}k.current=!0;const G=w.current;R.write(V.data,()=>{g.current!==R||w.current!==G||(k.current=!1,C.current&&P())})},[]),B=i.useCallback(()=>{v.current=null,C.current="",S.current="",k.current=!1,w.current+=1;const R=g.current;if(!R){$(F=>F+1);return}try{R.reset();const F=I.current;F&&R.write(`${F}\x1B[2J\x1B[H`)}catch{$(F=>F+1)}},[]);return i.useEffect(()=>{const R=x.current;if(!R)return;let F=!1,V=null,G=null,M=null,ee=null,H=[];const we=()=>{V&&j.current&&(V.options.cursorBlink=!0)},ce=be=>{be.relatedTarget instanceof Node&&R.contains(be.relatedTarget)||V&&(V.options.cursorBlink=!1)},ae=()=>{V&&j.current&&R.contains(document.activeElement)&&(V.options.cursorBlink=!0)},xe=()=>{V&&(V.options.cursorBlink=!1)};return R.addEventListener("focusin",we),R.addEventListener("focusout",ce),window.addEventListener("focus",ae),window.addEventListener("blur",xe),Promise.all([Mm(),Fm()]).then(([{module:be,ghostty:ge}])=>{if(F)return;V=new be.Terminal({...Am(a,l,o,ge,!1),...A.current??{}});const Se=new be.FitAddon;V.loadAddon(Se),V.open(R),g.current=V,m.current=Se,H=[V.onData(ke=>p.current(ke))],G=new ResizeObserver(()=>{M&&clearTimeout(M),M=setTimeout(K,80)}),G.observe(R),K();const je=I.current;je&&V.write(`${je}\x1B[2J\x1B[H`),ee=requestAnimationFrame(K)}),()=>{F=!0;const be=document.activeElement;be instanceof HTMLElement&&R.contains(be)&&(be.blur(),window.Capacitor?.getPlatform?.()==="android"&&vs(async()=>{const{Keyboard:Se}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:Se}},__vite__mapDeps([113,114])).then(({Keyboard:Se})=>Se.hide()).catch(()=>{})),G?.disconnect(),M&&clearTimeout(M),ee!==null&&cancelAnimationFrame(ee),R.removeEventListener("focusin",we),R.removeEventListener("focusout",ce),window.removeEventListener("focus",ae),window.removeEventListener("blur",xe),H.forEach(ge=>ge.dispose()),V?.dispose(),g.current=null,m.current=null,b.current=null,v.current=null,C.current="",S.current="",k.current=!1,w.current+=1,E.current=!1}},[K,a,l,_,o]),i.useEffect(()=>{const R=g.current,F=x.current;!R||!F||(R.options.cursorBlink=f&&document.hasFocus()&&F.contains(document.activeElement))},[f,T]),i.useEffect(()=>{if(!g.current)return;if(s.length===0){v.current!==null&&B();return}const F=v.current;let V=-1;if(F!==null){for(let ee=s.length-1;ee>=0;ee-=1){const H=s[ee].id;if(H===F){V=ee;break}if(H<F)break}if(V<0){B();return}}const G=V<0,M=V>=0?s.slice(V+1):s;C.current+=M.map(ee=>G?ee.replayData??ee.data:ee.data).join(""),v.current=s.at(-1)?.id??null,P()},[s,P,T,B]),i.useEffect(()=>{if(!u||!f)return;const R=requestAnimationFrame(()=>g.current?.focus());return()=>cancelAnimationFrame(R)},[u,f,T,e]),i.useEffect(()=>{const R=x.current;if(!d||!R)return;const F=V=>{const G=V;if(!G.isComposing)switch(G.inputType){case"insertText":G.data&&p.current(G.data);break;case"insertLineBreak":case"insertParagraph":p.current("\r");break;case"deleteContentBackward":p.current("");break}};return R.addEventListener("beforeinput",F),()=>R.removeEventListener("beforeinput",F)},[d,T]),i.useEffect(()=>{const R=x.current,F=g.current;if(!d||!R||!F)return;let V=null,G=null,M="idle",ee=0,H=0,we=0,ce=0,ae=null;const xe=Math.max(12,l+2),be=()=>{window.Capacitor?.getPlatform?.()==="android"&&vs(async()=>{const{Keyboard:le}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:le}},__vite__mapDeps([113,114])).then(({Keyboard:le})=>le.show()).catch(()=>{})},ge=()=>{G&&(clearTimeout(G),G=null)},Se=(Y,le)=>{const W=R.querySelector("canvas");return W?Rm(Y,le,W.getBoundingClientRect(),F.cols,F.rows):null},je=(Y,le)=>{const W=R.querySelector("canvas");if(!W)return;const X=W.getBoundingClientRect(),te=X.left+(le.column+.5)/F.cols*X.width,ne=X.top+(le.row+.5)/F.rows*X.height;W.dispatchEvent(new MouseEvent(Y,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:te,clientY:ne}))},ke=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},Ce=Y=>{Y.pointerType!=="touch"||V!==null||(V=Y.pointerId,M="pending",ee=Y.clientX,H=Y.clientY,we=Y.clientY,ce=0,ae=null,R.setPointerCapture(Y.pointerId),G=setTimeout(()=>{if(G=null,V!==Y.pointerId||M!=="pending")return;const le=Se(ee,H);if(!le)return;const W=F.buffer.active,X=Math.max(0,W.length-F.rows-W.viewportY+le.row),te=W.getLine(X),ne=Array.from({length:F.cols},(Pe,De)=>te?.getCell(De)?.getChars()??""),Ae=Em(ne,le.column),Ie={column:Ae.startColumn,row:le.row};ae={column:Ae.endColumn,row:le.row},M="selecting",je("mousedown",Ie),je("mousemove",ae)},350))},Z=Y=>{if(V!==Y.pointerId)return;if(M==="selecting"){const X=Se(Y.clientX,Y.clientY);X&&(!ae||X.column!==ae.column||X.row!==ae.row)&&(ae=X,je("mousemove",X)),Y.cancelable&&Y.preventDefault();return}if(M==="pending"){if(Math.hypot(Y.clientX-ee,Y.clientY-H)<8)return;ge(),M="scrolling"}if(M!=="scrolling")return;const le=we-Y.clientY;we=Y.clientY,ce+=le;const W=Math.trunc(ce/xe);W&&(F.scrollLines(W),ce-=W*xe),Y.cancelable&&Y.preventDefault()},ue=Y=>{if(V!==Y.pointerId)return;const le=M==="pending",W=M==="selecting";ge(),R.hasPointerCapture(Y.pointerId)&&R.releasePointerCapture(Y.pointerId),V=null,M="idle",W&&ke(),le&&(F.focus(),be())},L=Y=>{if(V!==Y.pointerId)return;const le=M==="selecting";ge(),R.hasPointerCapture(Y.pointerId)&&R.releasePointerCapture(Y.pointerId),V=null,M="idle",le&&ke()};return R.addEventListener("pointerdown",Ce),R.addEventListener("pointermove",Z,{passive:!1}),R.addEventListener("pointerup",ue),R.addEventListener("pointercancel",L),()=>{ge(),R.removeEventListener("pointerdown",Ce),R.removeEventListener("pointermove",Z),R.removeEventListener("pointerup",ue),R.removeEventListener("pointercancel",L)}},[d,l,T]),i.useImperativeHandle(h,()=>({focus:()=>g.current?.focus(),fit:K,getSelection:()=>{const R=g.current,F=R?.getSelectionPosition(),V=R?.getSelection()??"";return!F||!V.trim()?null:{text:V,startLine:F.start.y+1,endLine:F.end.y+1}}}),[K]),t.jsx("div",{ref:x,"data-terminal-owner":"main",className:z("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});Qa.displayName="TerminalViewport";const Om=280,yi=4,Bm=({transform:e})=>({...e,y:0}),_m=({id:e,children:s,className:n})=>{const{attributes:r,listeners:o,setNodeRef:a,transform:l,transition:c,isDragging:d}=ca({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:da.Transform.toString(l),transition:c},className:z("h-full rounded-md",n,d&&"opacity-50"),...r,...o,children:s})},zm=({id:e,children:s,className:n})=>t.jsx("div",{className:z("h-full",n),"data-sortable-tab-id":e,children:s}),Um=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:o,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:f,activePillLowercase:h=!0,nonCompositedIndicator:x=!1,className:g})=>{const m=se(L=>L.isMobile),{isTablet:p}=ks(),y=m||p,b=i.useRef(null),[A,v]=i.useState({left:!1,right:!1}),C=i.useMemo(()=>e.map(L=>L.id),[e]),S=a==="scrollable",I=l==="default",k=l==="active-pill",j=k||l==="animated",E=I,T=j||E,U=k&&S,_=j,$=f??j,K=typeof o=="function",P=K?_m:zm,B=i.useRef(new Map),[R,F]=i.useState(null),[V,G]=i.useState(!1),[M,ee]=i.useState(null),H=i.useRef(!1),we=i.useRef(0),ce=i.useRef(s),ae=i.useRef(null),xe=i.useMemo(()=>{if(!T||!M||!s||M===s)return 0;const L=e.findIndex(le=>le.id===M),Y=e.findIndex(le=>le.id===s);return L<0||Y<0?0:L>Y?yi:-yi},[s,e,M,T]),be=so(On(ia,{activationConstraint:{distance:8}})),ge=i.useCallback((L,Y)=>!L||!Y?L===Y:Math.abs(L.left-Y.left)<.5&&Math.abs(L.top-Y.top)<.5&&Math.abs(L.width-Y.width)<.5&&Math.abs(L.height-Y.height)<.5,[]),Se=i.useCallback((L,Y)=>{if(Y){B.current.set(L,Y);return}B.current.delete(L)},[]),je=i.useCallback(()=>{if(!T||!s){F(ne=>ne===null?ne:null);return}const L=b.current,Y=B.current.get(s);if(!L||!Y){F(ne=>ne===null?ne:null);return}let le=0,W=0,X=Y;for(;X&&X!==L;)le+=X.offsetLeft,W+=X.offsetTop,X=X.offsetParent;const te={left:le,top:W,width:Y.offsetWidth,height:Y.offsetHeight};F(ne=>ge(ne,te)?ne:te)},[s,ge,T]),ke=i.useCallback(()=>{if(!S){v({left:!1,right:!1});return}const L=b.current;if(!L){v({left:!1,right:!1});return}v({left:L.scrollLeft>2,right:L.scrollLeft+L.clientWidth<L.scrollWidth-2})},[S]);i.useEffect(()=>{if(!S){v({left:!1,right:!1});return}const L=b.current;if(!L)return;ke(),L.addEventListener("scroll",ke,{passive:!0});const Y=new ResizeObserver(ke);return Y.observe(L),()=>{L.removeEventListener("scroll",ke),Y.disconnect()}},[S,e.length,ke]),i.useEffect(()=>{if(!T){F(null);return}je();const L=b.current;if(!L)return;const Y=new ResizeObserver(()=>{performance.now()-we.current>Om&&G(!1),je()});if(Y.observe(L),s){const le=B.current.get(s);le&&Y.observe(le)}return()=>{Y.disconnect()}},[s,e.length,je,T]),i.useLayoutEffect(()=>{je()});const Ce=C.join("\0");i.useLayoutEffect(()=>{if(!T){H.current=!1,G(!1);return}const L=ae.current!==Ce;if(ae.current=Ce,!H.current){H.current=!0,ce.current=s;return}const Y=ce.current!==s;if(ce.current=s,!Y||L){G(!1);return}we.current=performance.now(),G(!0)},[s,Ce,T]),i.useEffect(()=>{if(!S||!s)return;const L=b.current;if(!L)return;const Y=window.requestAnimationFrame(()=>{const le=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),W=L.querySelector(`[data-sortable-tab-id="${le}"]`);W&&(W.scrollIntoView({block:"nearest",inline:"nearest"}),ke())});return()=>{window.cancelAnimationFrame(Y)}},[s,S,e.length,ke]);const Z=i.useCallback(L=>{if(!o)return;const{active:Y,over:le}=L;!le||Y.id===le.id||o(String(Y.id),String(le.id))},[o]),ue=t.jsxs("div",{className:z("relative flex h-full min-w-0 flex-1",g),children:[S&&A.left?t.jsx("div",{className:z("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",j?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,S&&A.right?t.jsx("div",{className:z("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",j?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:b,className:z("relative flex h-full min-w-0 flex-1",j?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",j&&"@container/pill-tabs",j&&"pill-tabs__track",j&&(c??"gap-0.5 py-0.5"),E&&"items-center overflow-y-hidden",_&&"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",S?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:S?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[j&&R?t.jsx("div",{className:z("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)]",$&&V&&(x?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:x?{left:`${R.left+xe}px`,top:`${R.top}px`,width:`${R.width}px`,height:`${R.height}px`}:{transform:`translate3d(${R.left+xe}px, ${R.top}px, 0)`,width:`${R.width}px`,height:`${R.height}px`}}):null,E&&R?t.jsx("div",{className:z("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",V&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${R.left+xe}px, 0, 0)`,width:`${R.width}px`},"aria-hidden":!0}):null,e.map(L=>{const Y=L.id===s,le=u&&j&&!Y&&!!L.icon,W=!le,X=!!L.icon,te=u&&j&&Y&&!S&&!U,ne=L.closable!==!1&&!!r,Ae=ne&&!!L.icon,Ie=S||U?void 0:j?te?"flex-none basis-auto":m?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",Pe=ne?de=>{de.button===1&&(de.preventDefault(),de.stopPropagation(),r?.(L.id))}:void 0,De=ne?de=>{de.button===1&&de.preventDefault()}:void 0,Ge=de=>X?t.jsxs("span",{className:de,children:[t.jsx("span",{className:z("flex items-center justify-center transition-opacity",Ae&&(y?"opacity-0":"group-hover:opacity-0")),children:L.icon}),Ae?t.jsx("span",{role:"button",tabIndex:-1,className:z("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",y?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:ze=>ze.stopPropagation(),onClick:ze=>{ze.stopPropagation(),r?.(L.id)},"aria-label":L.closeLabel??`Close ${L.label} tab`,title:L.closeLabel??`Close ${L.label} tab`,children:t.jsx(D,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return t.jsx(P,{id:L.id,className:Ie,children:t.jsxs("div",{ref:de=>Se(L.id,de),onAuxClick:Pe,onMouseDown:De,className:z("group flex h-full min-w-0 flex-nowrap items-center",S||U?"shrink-0":j?"w-full":"w-full min-w-0",j?"relative z-10 bg-transparent":Y?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":Y,"aria-label":le?L.title??L.label:void 0,onClick:()=>n(L.id),onPointerDown:T?()=>{G(!0),ee(L.id)}:void 0,onPointerUp:T?()=>ee(null):void 0,onPointerLeave:T?()=>ee(null):void 0,onPointerCancel:T?()=>ee(null):void 0,className:z(j?"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",j&&h?"lowercase":null,j&&(le?"gap-0":"gap-1.5"),j?U?"shrink-0 whitespace-nowrap px-3 text-center":S?"max-w-56 shrink-0 px-3 text-center":le?"px-2 !min-w-0 text-center":te?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":S?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",j?d??(k?m?"h-[38px]":"h-[31px]":"h-7"):null,j?Y?"text-foreground":"text-muted-foreground hover:text-foreground":null,j?"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:L.title??L.label,children:j?t.jsxs(t.Fragment,{children:[Ge("relative flex h-4 w-4 shrink-0 items-center justify-center"),W?t.jsx("span",{className:"animated-tabs__label truncate",children:L.label}):null]}):t.jsxs("span",{className:z("flex min-w-0 flex-nowrap items-center gap-1.5",!S&&"justify-center"),children:[Ge(z("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",Y?"text-[var(--primary-base)]":"text-muted-foreground")),t.jsx("span",{className:"truncate leading-[1.2]",children:L.label})]})}),ne&&!Ae?t.jsx("button",{type:"button",onPointerDown:de=>{de.stopPropagation()},onClick:de=>{de.stopPropagation(),r?.(L.id)},className:z("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",j?"-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",j?Y?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":Y?"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":L.closeLabel??`Close ${L.label} tab`,title:L.closeLabel??`Close ${L.label} tab`,children:t.jsx(D,{name:"close",className:"h-3 w-3"})}):null]})},L.id)})]})]});return K?t.jsxs(no,{sensors:be,collisionDetection:ro,onDragEnd:Z,modifiers:[Bm],children:[t.jsx(la,{items:C,strategy:Pu,children:ue}),t.jsx(aa,{dropAnimation:null})]}):ue},$m=({isTouchTerminal:e,activeModifier:s,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const a=e?"lg":"xs",l=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return t.jsxs(t.Fragment,{children:[t.jsx(Re,{type:"button",size:a,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[t.jsx(D,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Re,{type:"button",size:a,variant:"chip","aria-pressed":s==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Re,{type:"button",size:a,variant:"chip","aria-pressed":s==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[t.jsx(D,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[t.jsx(D,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[t.jsx(D,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[t.jsx(D,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[t.jsx(D,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Gm="\x1B",Km=new RegExp(`${Gm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Hm=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Wm=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Ym=/Serving HTTP on .*? port (\d{2,5})/i,qm=new Set([".",",",";",":","!","?"]),Vm=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=s.slice(0,-1),a=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=o;continue}if(qm.has(n)){s=s.slice(0,-1);continue}break}return s},wi=e=>{let s=Vm(e);return s=s.replace("0.0.0.0","127.0.0.1"),s=s.replace("[::1]","127.0.0.1"),s=s.replace("[::]","127.0.0.1"),s},Qm=e=>{if(!e)return null;const s=e.replace(Km,""),n=s.match(Ym);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=s.split(`
|
|
47
|
-
`);for(const o of r){if(!Wm.test(o))continue;const a=Array.from(o.matchAll(Hm));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(wi(c[1])).port}catch{return!1}});return wi((l??a[0])[1])}return null},Jm=async(e,s=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,a=window.setTimeout(()=>o.abort(),s);try{const l=await Mt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},Xm={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Zm=(e,s)=>{if(s&&e.startsWith("arrow-")){const n=s==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return Xm[e]},Ja=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},eg=(e,s)=>e&&(s==="ctrl"?Ja(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Xa={cols:80,rows:24},vi={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class tg{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(s,n,r,o){if(!r)return;const a=`${this.tail}${r}`.replace(/\r\n|\r/g,`
|
|
48
|
-
`),l=a.split(`
|
|
49
|
-
`),c=a.endsWith(`
|
|
50
|
-
`)?l.join(`
|
|
51
|
-
`):l.slice(0,-1).join(`
|
|
52
|
-
`);if(this.tail=a.endsWith(`
|
|
53
|
-
`)?"":(l[l.length-1]??"").slice(-1024),!c)return;const d=Qm(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Jm(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const h=he.getState().getDirectoryState(s)?.tabs.find(x=>x.id===n);!h||h.previewUrlLocked||h.previewUrl===d||o(s,n,d,{locked:!1,autoOpened:!1})})}}const sg=(e,s)=>{if(s!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Ja(o):null};function ng({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:h,focusTerminalWhenWindowActive:x}){const g=he(M=>M.ensureDirectory),m=he(M=>M.setTabSessionId),p=he(M=>M.setTabLifecycle),y=he(M=>M.setConnecting),b=he(M=>M.appendToBuffer),A=he(M=>M.replaceBuffer),v=he(M=>M.setTabPreviewUrl),[C,S]=i.useState(null),[I,k]=i.useState(!1),[w,j]=i.useState(!1),E=i.useRef(null),T=i.useRef(null),U=i.useRef(n),_=i.useRef(r),$=i.useRef(s),K=i.useRef(null),P=i.useRef(new Set),B=i.useRef(new tg),R=i.useCallback(()=>{B.current.reset()},[]);i.useEffect(()=>{_.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),i.useEffect(()=>{U.current=n,R()},[n,R]),i.useEffect(()=>{$.current=s},[s]);const F=i.useCallback(()=>{E.current?.(),E.current=null,T.current=null,j(!1)},[]);i.useEffect(()=>()=>{F(),_.current=null},[F]);const V=i.useCallback((M,ee,H)=>{B.current.scan(M,ee,H,v)},[v]),G=i.useCallback((M,ee,H)=>{if(T.current===H)return;F(),T.current=H;const we=e.connect(H,{onEvent:ce=>{if(T.current===H)switch(ce.type){case"snapshot":{y(M,ee,!1),S(null),k(!1),j(!1),x(),A(M,ee,ce.data??"",ce.sequence??0),V(M,ee,ce.data??""),ce.status==="exited"&&p(M,ee,"exited");break}case"reconnecting":{S(null),k(!1),j(!0);break}case"data":{ce.data&&(b(M,ee,ce.data,ce.sequence,ce.replayData),V(M,ee,ce.data));break}case"exit":{const ae=typeof ce.exitCode=="number"?ce.exitCode:null,xe=typeof ce.signal=="number"?ce.signal:null,ge=!!he.getState().getDirectoryState(M)?.tabs.find(Se=>Se.id===ee)?.label?.startsWith("Action:");b(M,ee,`\\r\\n[Process exited${ae!==null?` with code ${ae}`:""}${xe!==null?` (signal ${xe})`:""}]\\r\\n`),p(M,ee,"exited"),y(M,ee,!1),S(ge?null:"Terminal session ended"),k(!1),j(!1),F();break}}},onError:(ce,ae)=>{if(T.current===H){if(!ae){S(null),k(!1);return}if(j(!1),ce.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(M)?.tabs.find(be=>be.id===ee)?.label?.startsWith("Action:")){S(null),k(!1),y(M,ee,!1),m(M,ee,null),p(M,ee,"idle"),F();return}S(`Connection failed: ${ce.message}`),k(!0),y(M,ee,!1),p(M,ee,"exited"),m(M,ee,null),F()}}});E.current=()=>{we.close(),T.current=null}},[b,F,x,A,V,y,p,m,e]);return i.useEffect(()=>{let M=!1;if(!l||!a)return;if(!s){S(h?"No working directory available for terminal.":"Select a session to open the terminal."),F();return}return(async()=>{const H=s;if(!$.current||$.current!==H)return;if(!he.getState().getDirectoryState(H)){g(H);return}const ce=he.getState().getDirectoryState(H);if(!ce||ce.tabs.length===0)return;const ae=ce.activeTabId??ce.tabs[0]?.id??null;if(!ae)return;const xe=ce.tabs.find(Ce=>Ce.id===ae)??ce.tabs[0],be=xe?.terminalSessionId??null,ge=xe?.lifecycle??"idle",Se=!!xe?.label?.startsWith("Action:"),je=he.getState().getBuffer(H,ae),ke=je.byteLength>0||je.chunks.length>0;if(!be){if(ge==="exited"){y(H,ae,!1);return}if(Se&&ke){y(H,ae,!1);return}const Ce=`${H}\0${ae}`;if(P.current.has(Ce))return;const Z=K.current??Xa;P.current.add(Ce),S(null),k(!1),j(!1),y(H,ae,!0);try{const ue=await e.createSession({cwd:H,sessionId:ae,cols:Z.cols,rows:Z.rows,shell:c,loginShell:d,...u.current}),L=!M&&$.current===H&&U.current===ae;if(!he.getState().getDirectoryState(H)?.tabs.find(W=>W.id===ae)){try{await e.close(ue.sessionId)}catch{}return}if(m(H,ae,ue.sessionId),!L)return;const le=K.current;le&&(le.cols!==Z.cols||le.rows!==Z.rows)&&e.resize({sessionId:ue.sessionId,...le}).catch(()=>{});return}catch(ue){const L=he.getState().getDirectoryState(H)?.tabs.find(Y=>Y.id===ae);if(!L||L.terminalSessionId||(y(H,ae,!1),$.current!==H||U.current!==ae))return;S(ue instanceof Error?ue.message:"Failed to start terminal session"),k(!0),j(!1);return}finally{P.current.delete(Ce)}}!be||M||(_.current=be,G(H,ae,be))})(),()=>{M=!0,_.current=null,F()}},[h,s,r,o,n,a,f,l,g,y,p,m,G,F,e,d,c,u]),{connectionError:C,setConnectionError:S,isFatalError:I,setIsFatalError:k,isReconnectPending:w,setIsReconnectPending:j,terminalIdRef:_,lastViewportSizeRef:K,directoryRef:$,activeTabIdRef:U,disconnectStream:F,resetTerminalPreviewScan:R,startStream:G}}function rg({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=i.useState(null),h=i.useRef(null),x=i.useCallback(()=>{d||h.current?.focus()},[d]),g=i.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||h.current?.focus()},[d]);i.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),i.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const m=i.useCallback(v=>{if(!v||n)return;let C=v,S=!1;u&&v.length>0&&(C=eg(v,u),S=!0);const I=s.current;I&&(e.sendInput(I,C).catch(k=>{n||r(k instanceof Error?k.message:"Failed to send input")}),S&&(f(null),x()))},[u,x,n,r,e,s]),p=i.useCallback((v,C)=>{const S=l.current;if((!S||S.cols!==v||S.rows!==C)&&(l.current={cols:v,rows:C}),!a)return;const I=s.current;I&&e.resize({sessionId:I,cols:v,rows:C}).catch(()=>{})},[a,l,e,s]),y=i.useCallback(v=>{f(C=>C===v?null:v),x()},[x]),b=i.useCallback(v=>{const C=Zm(v,u);C&&(m(C),f(null),x())},[u,x,m]),A=i.useCallback(v=>{if(v.repeat)return;const C=v.key;if(!C||C==="Control"||C==="Meta"||C==="Alt"||C==="Shift")return;const S=C.length===1?C.toLowerCase():C;if(S in vi){v.preventDefault(),v.stopPropagation(),b(vi[S]);return}const I=sg(v,u);I&&(v.preventDefault(),v.stopPropagation(),m(I),f(null),x())},[u,x,b,m]);return i.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[u,A,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:h,focusTerminalController:x,focusTerminalWhenWindowActive:g,handleViewportInput:m,handleViewportResize:p,handleModifierToggle:y,handleMobileKeyPress:b}}function og({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,disconnectStream:h,resetTerminalPreviewScan:x,startStream:g,setConnectionError:m,setIsFatalError:p,setIsReconnectPending:y}){const b=he(_=>_.createTab),A=he(_=>_.setActiveTab),v=he(_=>_.closeTab),C=he(_=>_.setTabSessionId),S=he(_=>_.setTabLifecycle),[I,k]=i.useState(!1),w=i.useCallback(async()=>{if(!s||I)return;const _=he.getState().getDirectoryState(s),$=n??_?.activeTabId??_?.tabs[0]?.id??null;if(!$)return;const K=_?.tabs.find(P=>P.id===$)?.terminalSessionId??null;if(!(!K||!e.restartSession)){k(!0),m(null),p(!1),y(!1),h(),x();try{const P=c.current??Xa,B=await e.restartSession(K,{cwd:s,shell:o,loginShell:a,...P,...l.current});if(he.getState().getDirectoryState(s)?.tabs.find(F=>F.id===$)?.terminalSessionId!==K||(C(s,$,B.sessionId),S(s,$,"running"),d.current!==s||u.current!==$))return;f.current=B.sessionId,g(s,$,B.sessionId)}catch(P){if(he.getState().getDirectoryState(s)?.tabs.find(R=>R.id===$)?.terminalSessionId!==K||d.current!==s||u.current!==$)return;m(P instanceof Error?P.message:"Failed to restart terminal"),p(!1),y(!1),f.current=K,g(s,$,K)}finally{k(!1)}}},[n,u,d,h,s,r,I,c,x,m,p,y,S,C,g,e,l,f,a,o]),j=i.useCallback(async()=>{await w()},[w]),E=i.useCallback(()=>{if(!s)return;const _=b(s);A(s,_),m(null),p(!1),y(!1),h()},[b,h,s,A,m,p,y]),T=i.useCallback(_=>{s&&(A(s,_),m(null),p(!1),y(!1),h())},[h,s,A,m,p,y]),U=i.useCallback(_=>{if(!s)return;_===n&&h(),m(null),p(!1),y(!1);const $=he.getState().getDirectoryState(s)?.tabs.find(K=>K.id===_)?.terminalSessionId;(async()=>{$&&await e.close($),v(s,_)})().catch(K=>m(K instanceof Error?K.message:"Terminal session ended"))},[n,v,h,s,m,p,y,e]);return{isRestarting:I,handleRestart:w,handleHardRestart:j,handleCreateTab:E,handleSelectTab:T,handleCloseTab:U}}const Tx=({visible:e})=>{const{terminal:s,runtime:n}=Gs(),{currentTheme:r}=Ui(),o=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});o.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=dd(),l=se(J=>J.terminalFontSize),c=se(J=>J.terminalShell),d=se(J=>J.terminalLoginShells.includes(J.terminalShell)),{isMobile:u,isTablet:f,hasTouchOnlyPointer:h}=ks(),x=u||f,g=(x||h)&&n.platform==="web",m=!0,p=se(J=>J.showTerminalQuickKeysOnDesktop),y=x||p,b=ve(J=>J.currentSessionId),A=ve(J=>J.newSessionDraft),v=b!==null||A?.open===!0,C=ud()??null,S=he(J=>C?J.sessions.get(C):void 0),I=he(J=>J.hasHydrated),k=se(J=>J.openContextPreview),w=i.useMemo(()=>S?S.activeTabId??S.tabs[0]?.id??null:null,[S,m]),j=i.useMemo(()=>{if(S)return w?S.tabs.find(J=>J.id===w)??S.tabs[0]:S.tabs[0]},[S,w]),E=i.useMemo(()=>(S?.tabs??[]).map(J=>({icon:(()=>{const Be=J.iconKey?on[J.iconKey]??"terminal":"terminal";return t.jsx(D,{name:Be,className:"h-4 w-4"})})(),id:J.id,label:J.label,title:J.label,closeLabel:"Close tab"})),[S?.tabs]),T=j?.terminalSessionId??null,U=j?.lifecycle??"idle",_=he(J=>C&&w?J.getBuffer(C,w).chunks:Ln.chunks),$=j?.isConnecting??!1,K=j?.previewUrl??null,B=se(J=>J.activeMainTab)==="terminal",R=e??B,[F,V]=i.useState(R);i.useEffect(()=>{R&&V(!0)},[R]);const{connectionError:G,setConnectionError:M,isFatalError:ee,setIsFatalError:H,isReconnectPending:we,setIsReconnectPending:ce,terminalIdRef:ae,lastViewportSizeRef:xe,directoryRef:be,activeTabIdRef:ge,disconnectStream:Se,resetTerminalPreviewScan:je,startStream:ke}=ng({terminal:s,effectiveDirectory:C,activeTabId:w,terminalSessionId:T,terminalLifecycle:U,hasOpenedTerminalViewport:F,terminalHydrated:I,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:o,enableTabs:m,hasActiveContext:v,focusTerminalWhenWindowActive:()=>{!g&&typeof document<"u"&&document.hasFocus()&&Z.current?.focus()}}),{activeModifier:Ce,terminalControllerRef:Z,focusTerminalWhenWindowActive:ue,handleViewportInput:L,handleViewportResize:Y,handleModifierToggle:le,handleMobileKeyPress:W}=rg({terminal:s,terminalIdRef:ae,isReconnectPending:we,setConnectionError:M,showQuickKeys:y,isTerminalVisible:R,lastViewportSizeRef:xe,terminalSessionId:T,useTouchTerminalInput:g}),{isRestarting:X,handleRestart:te,handleHardRestart:ne,handleCreateTab:Ae,handleSelectTab:Ie,handleCloseTab:Pe}=og({terminal:s,effectiveDirectory:C,activeTabId:w,enableTabs:m,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:o,lastViewportSizeRef:xe,directoryRef:be,activeTabIdRef:ge,terminalIdRef:ae,disconnectStream:Se,resetTerminalPreviewScan:je,startStream:ke,setConnectionError:M,setIsFatalError:H,setIsReconnectPending:ce});i.useEffect(()=>{if(!R||g)return;if(typeof window>"u"){ue();return}const J=window.requestAnimationFrame(()=>{ue()});return()=>{window.cancelAnimationFrame(J)}},[w,ue,R,g]);const De=i.useMemo(()=>{const J=Qs[or].stack;if(typeof window>"u")return(Qs[a]??Qs[or]).stack;const We=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return We&&We.trim().length>0?We.trim():(Qs[a]??Qs[or]).stack??J},[a]),Ge=i.useMemo(()=>Nm(r),[r]),de=`${C??"no-dir"}::${w??"no-tab"}`;if(i.useEffect(()=>{if(!R||g)return;const J=Z.current;if(!J)return;const Be=()=>{J.fit()};if(typeof window<"u"){const We=window.requestAnimationFrame(()=>{Be(),ue()}),Ue=[220,400].map(Ve=>window.setTimeout(Be,Ve));return()=>{window.cancelAnimationFrame(We),Ue.forEach(Ve=>window.clearTimeout(Ve))}}Be()},[ue,R,g,Z,de,T]),i.useEffect(()=>{if(!R||!g)return;let J=null;const Be=()=>{J!==null&&window.cancelAnimationFrame(J),J=window.requestAnimationFrame(()=>{J=null,Z.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Be),()=>{window.removeEventListener("oc:keyboard-settled",Be),J!==null&&window.cancelAnimationFrame(J)}},[R,Z,de,g]),!v)return t.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!C)return t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{children:"No working directory available for this session."}),t.jsx("button",{onClick:te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ze=!T||$||X||we,Ne=F,Ye=t.jsx($m,{isTouchTerminal:x,activeModifier:Ce,disabled:ze,onKeyPress:W,onModifierToggle:le});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:z("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[S?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:z("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(Um,{items:E,activeId:w,onSelect:Ie,onClose:Pe,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Re,{type:"button",size:"xs",variant:"ghost",className:z("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ae,title:"New tab",children:t.jsx(D,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Re,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{te()},disabled:X,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(D,{name:"restart",className:"h-4 w-4"})}),K?t.jsxs(Re,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{C&&k(C,K)},title:"Open preview pane",children:[t.jsx(D,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&y&&m&&S?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Ye}):null,!x&&y&&!S?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Ye}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Ge.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Ne?t.jsx(Qa,{ref:J=>{Z.current=J},sessionKey:de,chunks:_,onInput:L,onResize:Y,theme:Ge,fontFamily:De,fontSize:l,enableTouchScroll:g,autoFocus:R,isVisible:R},de):null}),!we&&G&&t.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[t.jsx("span",{children:G}),ee&&x&&t.jsx(Re,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ne,disabled:X,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&y?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:Ye})}):null]})},ig=48,ag=96,mt=(e,...s)=>{try{e?.(...s)}catch{}},wr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Fx=(e,s)=>{const n=i.useRef(s);n.current=s;const r=s.enabled;i.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const a=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?ag:ig;let d=!1,u=!1,f=!1,h=null,x=!1,g=0,m=0,p=0,y=0;const b=()=>{d=!1,u=!1,f=!1,h=null},A=()=>{const j=n.current,E=h,T=x;u&&E&&(mt(E==="left"?j.onLeftProgress:j.onRightProgress,T?1:0),mt(j.onDragEnd,E,T)),b()},v=()=>{A(),u||b()},C=j=>{const E=n.current;if(E.enabled===!1){u&&h?A():b();return}if(j.touches.length!==1){u&&h?A():b();return}const T=j.touches[0],U=o.getBoundingClientRect(),_=o.clientWidth,$=!!E.leftOpen,K=!!E.rightOpen,P=B=>xm(B,o);if($||K){if(P(j.target)){b();return}if($&&K){const B=T.clientX<=U.left+c;T.clientX>=U.right-c?(h="right",x=!0):B?(h="left",x=!0):(h=$?"left":"right",x=!0)}else $?(h="left",x=!0):(h="right",x=!0);y=wr(h==="left"?E.leftWidth:E.rightWidth,_),y<10&&(y=_||window.innerWidth||320),y<10&&(y=320),d=!0}else{if(P(j.target)){b();return}h=null,x=!1,y=0,d=!0}g=T.clientX,m=T.clientY,p=Date.now(),u=!1,f=!1},S=j=>{if(!d)return;if(j.touches.length!==1){v();return}const E=j.touches[0],T=E.clientX-g,U=E.clientY-m;if(!f){if(Math.abs(T)<pi&&Math.abs(U)<pi)return;if(Math.abs(U)>Math.abs(T)*Zs){b();return}if(!h){const K=n.current;h=T>0?"left":"right",y=wr(h==="left"?K.leftWidth:K.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(h==="left"){if(!x&&T<=0){b();return}if(x&&T>=0){b();return}}else{if(!x&&T>=0){b();return}if(x&&T<=0){b();return}}f=!0,u=!0,mt(n.current.onDragStart,h)}if(!u)return;j.cancelable&&j.preventDefault();const _=n.current,$=mi(h,x,T,y);mt(h==="left"?_.onLeftProgress:_.onRightProgress,$)},I=(j,E)=>{if(!d){b();return}const T=j-g,U=E-m;if(!h&&!x&&Math.abs(T)>=Fn&&Math.abs(U)<=Math.abs(T)*Zs){const R=n.current;h=T>0?"left":"right",y=wr(h==="left"?R.leftWidth:R.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(!h){b();return}const _=Math.max(1,Date.now()-p),$=n.current;if(!u){const R=Math.abs(T),F=Math.abs(U);R>=Fn&&F<=R*Zs?h==="left"&&!x&&T>0?(mt($.onLeftProgress,1),mt($.onLeftOpen)):h==="right"&&!x&&T<0?(mt($.onRightProgress,1),mt($.onRightOpen)):mt(h==="left"?$.onLeftProgress:$.onRightProgress,x?1:0):mt(h==="left"?$.onLeftProgress:$.onRightProgress,x?1:0);const V=h;b(),mt($.onDragEnd,V);return}const K=mi(h,x,T,y),P=mm({side:h,isOpenAtStart:x,dx:T,dt:_,progress:K}),B=h;mt(B==="left"?P?$.onLeftOpen:$.onLeftClose:P?$.onRightOpen:$.onRightClose),b(),mt($.onDragEnd,B,P)},k=j=>{const E=j.changedTouches[0];if(!E){b();return}const T=E.clientX-g,U=E.clientY-m;d&&(u||Math.abs(T)>=Fn&&Math.abs(U)<=Math.abs(T)*Zs)&&j.cancelable&&j.preventDefault(),I(E.clientX,E.clientY)},w=()=>{v()};return o.addEventListener("touchstart",C,{passive:!0}),o.addEventListener("touchmove",S,{passive:!1}),o.addEventListener("touchend",k,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{u&&h&&A()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",C),o.removeEventListener("touchmove",S),o.removeEventListener("touchend",k),o.removeEventListener("touchcancel",w)}},[e,r])};function Lx({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(D,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Si({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const lg=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,cg=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Hn(s,n)?null:e,vr=()=>ws.filter(e=>Tr.has(e.id)).map(e=>({...Yi(e)})),dg=()=>{if(typeof window>"u")return Fr;const e=window.localStorage.getItem("openInAppId");return e&&Mr(e)?e:Fr};let Sr=!1,Ps=!1,ls=!1,cs=0,an=null;const ji=()=>{an&&(clearTimeout(an),an=null)},xs=hs()((e,s)=>({selectedAppId:dg(),availableApps:vr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Sr||typeof window>"u")return;Sr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:vr(),hasLoadedApps:u});return}const f=new Set(d.map(m=>m.name)),h=new Map(d.map(m=>[m.name,m.iconDataUrl??void 0])),g=ws.filter(m=>f.has(m.appName)||Tr.has(m.id)).map(m=>({...Yi(m),iconDataUrl:h.get(m.appName)}));e({availableApps:g,hasLoadedApps:!0})},r=async d=>{if(!Os()||!dn()||Ps||s().hasLoadedApps&&!d)return;const f=ws.map(h=>h.appName);ji(),Ps=!0,ls=!1,e({isScanning:!0});try{const{apps:h,success:x,hasCache:g,isCacheStale:m}=await _o(f,d),p=x&&!g&&h.length===0&&cs<3;if(e({isCacheStale:g?m:!1}),n(h,x?!p:!1),x){if(p){const b=[800,1600,3200][cs]??3200;cs+=1,ls=!0,an=setTimeout(()=>{r()},b);return}cs=0,ls=!1;return}if(cs<3){const b=[1e3,3e3,7e3][cs]??7e3;cs+=1,ls=!0,an=setTimeout(()=>{r()},b)}}finally{Ps=!1,ls||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Mr(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(cs=3,ls=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Sr||s().initialize(),!Os()||!dn()||Ps||s().hasLoadedApps&&!n)return;const o=ws.map(a=>a.appName);ji(),n&&e({hasLoadedApps:!1}),Ps=!0,ls=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await _o(o,n),d=new Set(a.map(x=>x.name)),u=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),h=ws.filter(x=>d.has(x.appName)||Tr.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:h.length>0?h:vr(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{Ps=!1,ls||e({isScanning:!1})}},selectApp:async n=>{Mr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Zr({openInAppId:n}))}})),ug="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",fg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",jr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?ug:e.id==="terminal"?fg:void 0}),Ci=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,o]=i.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):t.jsx("span",{className:z("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},hg=({directory:e,className:s})=>{const n=xs(m=>m.selectedAppId),r=xs(m=>m.availableApps),o=xs(m=>m.isCacheStale),a=xs(m=>m.isScanning),l=xs(m=>m.initialize),c=xs(m=>m.loadInstalledApps),d=xs(m=>m.selectApp);i.useEffect(()=>{l()},[l]);const u=Os()&&dn(),f=i.useMemo(()=>{const m=r.find(p=>p.id===n)??r.find(p=>p.id===Fr)??r[0]??ws[0];return jr(m||ws[0])},[r,n]);if(!u||!e||r.length===0)return null;const h=async m=>{await Jd(e,m.id,m.appName)||await Hi(e,m.appName)},x=async m=>{await d(m.id),await h(m)},g=async()=>{(await cn(e)).ok&&ie.success("Path copied to clipboard")};return t.jsxs("div",{className:z("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{h(f)},className:z("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:t.jsx(Ci,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Pt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g()},children:[t.jsx(D,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Ls,{}),r.map(m=>{const p=jr(m);return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[t.jsx(Ci,{label:m.label,iconDataUrl:m.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:m.label}),f.id===m.id?t.jsx(D,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(D,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},pg="\x1B",mg=new RegExp(`${pg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),gg=/https?:\/\/[^\s<>'"`]+/gi,vt="__pichamber_auto_discover_preview__",xg=15e3,bg=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},yg=e=>{const s=(e||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},wg=e=>{const n=e.replace(mg,"").match(gg);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&o.push({raw:a,parsed:l})}catch{}if(o.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",h=f.split("/").filter(Boolean).length,x=f==="/"||f==="",g=!!(c.search||c.hash);let m=0;return u&&(m+=50),x&&(m+=30),m-=Math.min(h*5,20),g&&(m-=10),m};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},vg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Sg=["dev","start","preview","serve"];async function jg(e,s,n){if(!e)return null;const r=Ng(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Ag(n);if(o){const a=await Ig(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await Cg(e)){const o=await kg(),a=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function Cg(e){const s=`${e}/index.html`,n=await Kn(s,e);return typeof n=="string"&&n.trim().length>0}async function kg(){try{const e=await Mt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Ng(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(Sg.some(o=>n.includes(o)))return s}return null}function Ag(e){for(const{pattern:s}of vg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Ig(e){const s=await Kn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Kn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Kn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Mt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=ss()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Mt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Dg(e){try{const s=await Kn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Rg=(e,s,n)=>new Promise(r=>{let o=!1,a=null,l=null;const c=d=>{o||(o=!0,l&&clearTimeout(l),a?.close(),r(d))};a=e.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?a.close():l=setTimeout(()=>c(!1),n)});function Eg({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=Ui(),{terminal:o}=Gs(),{isMobile:a}=ks(),l=se(W=>W.terminalShell),c=se(W=>W.terminalLoginShells.includes(W.terminalShell)),d=se(W=>W.setSettingsPage),u=se(W=>W.setSettingsDialogOpen),f=se(W=>W.setSettingsProjectsSelectedId),h=se(W=>W.openContextPreview),x=he(W=>W.ensureDirectory),g=he(W=>W.setTabLabel),m=he(W=>W.setTabIconKey),p=he(W=>W.setActiveTab),y=he(W=>W.setConnecting),b=he(W=>W.setTabSessionId),A=he(W=>W.setTabPreviewUrl),v=he(W=>W.projectActionRuns),C=he(W=>W.setProjectActionRun),S=he(W=>W.updateProjectActionRunStatus),I=he(W=>W.removeProjectActionRun),[k,w]=i.useState([]),[j,E]=i.useState(null),[T,U]=i.useState(!1),_=i.useRef({}),$=i.useRef({}),K=i.useRef({}),P=i.useRef({}),B=i.useRef(new Set),R=i.useRef(0),F=e?.id??null,V=e?.path??"",G=i.useMemo(()=>F?{id:F,path:V}:null,[F,V]),M=i.useCallback(async W=>{await Di(W)},[]),ee=i.useCallback(async()=>{if(!G)return;const W=R.current+1;R.current=W,U(!0);try{const X=await kr(G);if(R.current!==W)return;const te=X.actions;w(te),E(ne=>ne===vt||ne&&te.some(Ae=>Ae.id===ne)?ne:null)}catch{if(R.current!==W)return}finally{R.current===W&&U(!1)}},[G]),H=i.useMemo(()=>Aa(s||G?.path||""),[s,G?.path]),we=i.useMemo(()=>j?k.find(W=>W.id===j)??null:null,[k,j]),ce=i.useMemo(()=>({id:vt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),ae=!a,xe=i.useMemo(()=>ae?[ce,...k]:k,[k,ce,ae]);i.useEffect(()=>{ee()},[ee]),i.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const te=X.detail;F&&(te?.projectId&&te.projectId!==F||ee())};return window.addEventListener(Ur,W),()=>{window.removeEventListener(Ur,W)}},[ee,F]),i.useEffect(()=>{j&&(j===vt&&ae||k.some(W=>W.id===j)||E(null))},[k,ae,j]),i.useEffect(()=>{const W=()=>{const X=he.getState(),te=X.sessions,ne=X.projectActionRuns;for(const[Ae,Ie]of Object.entries(ne)){const De=te.get(Ie.directory)?.tabs.find(Ue=>Ue.id===Ie.tabId);if(!De||De.terminalSessionId!==Ie.sessionId){I(Ae);continue}const Ge=$.current[Ae]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};$.current[Ae]=Ge;const de=xe.find(Ue=>Ue.id===Ie.actionId),ze=X.getBuffer(Ie.directory,Ie.tabId).chunks;if(!de||ze.length===0)continue;const Ne=ze.filter(Ue=>Ge.lastSeenChunkId===null||Ue.id>Ge.lastSeenChunkId);if(Ne.length===0)continue;const Ye=Ne.map(Ue=>Ue.data).join(""),J=`${Ge.tail}${Ye}`,Be=!Ge.openedUrl&&de.autoOpenUrl===!0?wg(J):null,We=Ne[Ne.length-1]?.id??Ge.lastSeenChunkId;if(Ge.lastSeenChunkId=We,Ge.tail=J.slice(-512),Be)if(Ge.openedUrl=!0,Ge.openInPreview){const Ue=ne[Ae];Ue&&(A(Ue.directory,Ue.tabId,Be,{locked:!1,autoOpened:!1}),Ue.status==="waiting-for-preview"&&S(Ae,"running"),window.clearTimeout(P.current[Ae]),delete P.current[Ae],h(Ue.directory,Be))}else M(Be),ie.success("Opened URL from action output");$.current[Ae]=Ge}for(const Ae of Object.keys($.current))ne[Ae]||(delete $.current[Ae],window.clearTimeout(P.current[Ae]),delete P.current[Ae])};return W(),he.subscribe((X,te)=>{(X.sessions!==te.sessions||X.buffers!==te.buffers)&&W()})},[xe,h,M,v,I,A,S]);const be=i.useCallback(async(W,X={})=>{if(!H)throw new Error("No active directory");const te=ns(H,W.id);x(H);const ne=he.getState(),Ae=ne.getDirectoryState(H);let Ie=_.current[te]||null;const Pe=Ie?!!Ae?.tabs.some(de=>de.id===Ie):!1;(!Ie||!Pe)&&(Ie=ne.createTab(H),_.current[te]=Ie),g(H,Ie,`Action: ${W.name}`),m(H,Ie,W.icon||"play"),p(H,Ie),X.revealTerminal!==!1&&se.getState().openContextPanelTab(H,{mode:"terminal"});const Ge=he.getState().getDirectoryState(H)?.tabs.find(de=>de.id===Ie);return{key:te,tabId:Ie,sessionId:Ge?.terminalSessionId??null}},[x,H,p,m,g]),ge=i.useCallback(async W=>{if(!n&&a)return;if(!H){ie.error("No active directory for action");return}const X=ns(H,W.id),te=v[X];if(!(te&&te.status==="running")&&!B.current.has(X)){B.current.add(X);try{const ne=W.id===vt?await(async()=>{const[J,Be]=await Promise.all([kr({id:G?.id??"",path:H}),Dg(H)]),We=await jg(H,J.actions,Be);if(!We)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:vt,name:"Auto-discover",command:We.command,icon:"scan-2",autoOpenUrl:!0,openUrl:We.previewUrlHint||""}})():W,Ae=ne.autoOpenUrl===!0&&(ne.openUrl||"").trim().length>0,Ie=!Ae&&W.id!==vt,{key:Pe,tabId:De,sessionId:Ge}=await be(ne,{revealTerminal:Ie});let de=Ge;if(!de){y(H,De,!0);try{de=(await o.createSession({cwd:H,sessionId:De,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,b(H,De,de)}finally{y(H,De,!1)}}if(!de)throw new Error("Failed to create terminal session");K.current[Pe]?.(),y(H,De,!0);const ze=o.connect(de,{onEvent:J=>{J.type==="snapshot"&&(he.getState().replaceBuffer(H,De,J.data??"",J.sequence??0),he.getState().setConnecting(H,De,!1)),J.type==="data"&&typeof J.data=="string"&&J.data.length>0&&he.getState().appendToBuffer(H,De,J.data,J.sequence,J.replayData),J.type==="exit"&&(he.getState().setTabLifecycle(H,De,"exited"),he.getState().setConnecting(H,De,!1),he.getState().removeProjectActionRun(Pe),delete $.current[Pe],K.current[Pe]?.(),delete K.current[Pe],window.clearTimeout(P.current[Pe]),delete P.current[Pe])},onError:(J,Be)=>{he.getState().setConnecting(H,De,!1),Be&&(he.getState().setTabLifecycle(H,De,"exited"),he.getState().setTabSessionId(H,De,null),he.getState().removeProjectActionRun(Pe))}});K.current[Pe]=ze.close;const Ne=ne.autoOpenUrl?yg(ne.openUrl):null;C({key:Pe,directory:H,actionId:ne.id,tabId:De,sessionId:de,status:ne.id===vt&&!Ne?"waiting-for-preview":"running"}),window.clearTimeout(P.current[Pe]),delete P.current[Pe],ne.id===vt&&!Ne&&(P.current[Pe]=window.setTimeout(()=>{const J=he.getState(),Be=J.projectActionRuns[Pe];J.updateProjectActionRunStatus(Pe,"running"),Be&&(J.setActiveTab(Be.directory,Be.tabId),se.getState().openContextPanelTab(Be.directory,{mode:"terminal"})),delete P.current[Pe]},xg)),$.current[Pe]={lastSeenChunkId:null,openedUrl:!!Ne||Ae,tail:"",openInPreview:ne.id===vt};const Ye=bg(ne.command.trim().replace(/\r\n|\r/g,`
|
|
54
|
-
`));await o.sendInput(de,`${Ye}\r`),Ne?(A(H,De,Ne,{locked:!0,autoOpened:!0}),h(H,Ne),ie.success("Opened action URL")):Ae?(A(H,De,null,{locked:!0}),ie.error("Invalid custom URL format")):A(H,De,null,{locked:!1,autoOpened:!1})}catch(ne){I(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X],ie.error(ne instanceof Error?ne.message:"Failed to run action")}finally{B.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,be,n,a,H,c,l,h,v,I,y,C,A,b,G?.id,o]),Se=i.useCallback(async W=>{const X=ns(H,W.id),te=v[X];if(!te)return;S(X,"stopping");const ne=Rg(o,te.sessionId,1e3);try{await o.sendInput(te.sessionId,"")}catch{}const Ae=await ne;if(he.getState().getDirectoryState(te.directory)?.tabs.find(De=>De.id===te.tabId)?.terminalSessionId===te.sessionId&&!Ae){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:te.sessionId})}catch{}else try{await o.close(te.sessionId)}catch{}b(te.directory,te.tabId,null)}I(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X]},[H,v,I,b,o,S]),je=i.useCallback(()=>{const W=we??xe[0];if(!W)return;const X=ns(H,W.id),te=v[X];if(te?.status!=="stopping"){if(te){Se(W);return}ge(W)}},[xe,H,ge,v,we,Se]),ke=i.useCallback((W,X=!1)=>{if(E(W.id),!X){ge(W);return}const te=ns(H,W.id),ne=v[te];if(ne?.status!=="stopping"){if(ne){Se(W);return}ge(W)}},[H,ge,v,Se]),Ce=i.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),Z=we??xe[0]??null,ue=Z?v[ns(H,Z.id)]:null,L=he(W=>ue?W.sessions.get(ue.directory)?.tabs.find(X=>X.id===ue.tabId)?.previewUrl??null:null),Y=!!((n||!a)&&G&&H),le=we??xe[0]??null;return{shouldRender:Y,isLoading:T,normalizedDirectory:H,resolvedSelected:le,displayActions:xe,projectActionRuns:v,selectedRunPreviewUrl:L,handlePrimaryClick:je,handleSelectAction:ke,openProjectActionsSettings:Ce,openContextPreview:h}}const ki=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:h,handlePrimaryClick:x,handleSelectAction:g,openProjectActionsSettings:m,openContextPreview:p}=Eg({projectRef:e,directory:s,allowMobile:o});if(!a||!d)return null;const y=d.icon||"play",b=d.id===vt?"scan-2":on[y]||"play",A=ns(c,d.id),v=f[A],C=v?.status==="stopping",S=v?.status==="waiting-for-preview",I=!!(v&&h),k=()=>{!v||!h||p(v.directory,h)},w=d.id===vt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||C,className:z("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:C||S?t.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?t.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(D,{name:b,className:"h-5 w-5"})})}),w?t.jsx(Oe,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:k,children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(Oe,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Pt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ls,{}),u.map(j=>{const E=j.icon||"play",T=j.id===vt?"scan-2":on[E]||"play",U=ns(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(D,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]}):t.jsxs("div",{className:z("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:x,disabled:l||C,className:z("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:C||S?t.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?t.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(D,{name:b,className:"h-4 w-4"})})})}),w?t.jsx(Oe,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:k,className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(Oe,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Pt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Xe,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ls,{}),u.map(j=>{const E=j.icon||"play",T=j.id===vt?"scan-2":on[E]||"play",U=ns(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Xe,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(D,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]})},qn="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Pg="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Mg=i.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:o,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:z(a??qn,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:n})})]}):null}),Tg=i.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:o,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Rt,{children:[t.jsx(Et,{asChild:!0,children:t.jsx("button",{type:"button",className:z(qn,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Pt,{align:"end",className:"w-64",children:[t.jsx(fd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ls,{}),r.map(d=>{const u=d.user,f=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(Xe,{className:"gap-2",disabled:l,onSelect:()=>{f||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(D,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:h})]}):null]}),f?t.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Fg=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:f,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(Rt,{open:a,onOpenChange:g=>{l(g),g&&c()},children:[t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx(Et,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:z(qn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(D,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Pt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[o?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:f?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(hd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Lg=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Kt,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Ht,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(os,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(fs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ns,{children:[t.jsx(Re,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Re,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Og=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},Js=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Bg=i.lazy(()=>vs(()=>import("./SessionSwitcherDropdown-v_8TaIZm.js"),__vite__mapDeps([115,24,3,4,1,2,5,6,7,8,9,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])).then(e=>({default:e.SessionSwitcherDropdown}))),Ox=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Ft("ui.header.render");const l=se(O=>O.setSessionSwitcherOpen),c=se(O=>O.toggleSidebar),d=se(O=>O.isSidebarOpen),u=se(O=>O.activeMainTab),f=se(O=>O.setActiveMainTab),h=se(O=>O.shortcutOverrides);se(O=>O.timeFormatPreference),Gs();const x=ve(O=>!!O.newSessionDraft?.open),g=ve(O=>O.currentSessionId),m=_i(g??""),p=pd(g),y=i.useMemo(()=>{if(!p)return null;const O=p;return{title:p.title??null,directory:O.directory??null,created:p.time?.created??null,slug:O.slug??null,shareUrl:p.share?.url??null,parentId:p.parentID??null}},[p]),b=dt(Lr(O=>{if(!O.activeProjectId)return null;const re=O.projects.find(fe=>fe.id===O.activeProjectId);return re?{id:re.id,path:re.path,label:re.label}:null})),A=Bs(O=>O.homeDirectory),v=i.useMemo(()=>{if(!b)return null;const O=b.label?.trim();if(O)return O;const re=b.path.split(/[\\/]/).filter(Boolean);return re[re.length-1]??null},[b]),{isMobile:C}=ks(),{enabled:S}=Vr(),I=!!(S&&a&&o!==void 0),k=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[w,j]=i.useState(!1),E=null,T=i.useRef(null),[U,_]=i.useState(()=>typeof window>"u"?!1:Os()),$=i.useMemo(()=>Wi(),[]),K=md(),[P,B]=i.useState(!1),R=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:F,side:V}=$i(),G=i.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const re=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!re)return null;const fe=Number.parseInt(re[1],10),He=Number.parseInt(re[2],10);return Number.isNaN(fe)?null:fe===10?He:fe},[]);Me.useEffect(()=>{typeof window>"u"||_(Os())},[]);const M=se(O=>O.isSessionSwitcherOpen),ee=null,H=null,we=[],[ce,ae]=i.useState(!1),[xe,be]=i.useState(!1),[ge,Se]=i.useState("Local"),[je,ke]=i.useState(!0),[Ce,Z]=i.useState(!1),[ue,L]=i.useState(null),[Y,le]=i.useState(!1),[W,X]=i.useState(null),te=i.useMemo(()=>Og(ge),[ge]),ne=i.useCallback(async()=>{if(!(typeof window>"u"||!U))try{if(dn()){Se("Local"),ke(!0);return}ke(!1);const O=await Xd(),re=Zd(),fe=eu([tu(re),...O.hosts]);if(fe.id===su){Se("Local"),ke(!0);return}Se(nu(fe.label.trim()||"Instance"))}catch{Se("Local"),ke(!0)}},[U]);Me.useEffect(()=>(ne(),ru(()=>{ne()})),[ne]);const Ae=i.useCallback(async()=>{if(je){L(null),X(null);return}le(!0),X(null);try{const O=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await Mt(`/api/pi/update-check?${O.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const fe=await re.json();L({available:fe.available??!1,version:fe.version,currentVersion:fe.currentVersion??"unknown",body:fe.body,nextSuggestedCheckInSec:typeof fe.nextSuggestedCheckInSec=="number"?fe.nextSuggestedCheckInSec:void 0,packageManager:fe.packageManager,updateCommand:fe.updateCommand})}catch(O){L(null),X(O instanceof Error?O.message:"Failed to check remote instance updates")}finally{le(!1)}},[je]);i.useEffect(()=>{L(null),X(null),Z(!1)},[je,ge]),i.useEffect(()=>{if(!U||je)return;const O=3e3,re=3600*1e3;let fe=!1,He=null;const es=at=>{He=window.setTimeout(()=>{if(fe||typeof document<"u"&&document.visibilityState!=="visible"){es(re);return}Ae().finally(()=>{fe||es(re)})},at)};return es(O),()=>{fe=!0,He!==null&&window.clearTimeout(He)}},[Ae,je,ge,U]);const Ie=i.useCallback(()=>{if(ue?.available){Z(!0);return}Ae()},[Ae,ue?.available]),Pe=g?y??null:null,De=i.useRef(null),[Ge,de]=i.useState(0);i.useEffect(()=>{if(!g){De.current&&(De.current=null,de(He=>He+1));return}if(Pe){De.current={sessionId:g,session:Pe,expiresAt:Date.now()+2e3};return}const O=De.current;if(!O||O.sessionId!==g)return;const re=O.expiresAt-Date.now();if(re<=0){De.current=null,de(He=>He+1);return}const fe=window.setTimeout(()=>{De.current?.sessionId===g&&(De.current=null),de(He=>He+1)},re);return()=>{window.clearTimeout(fe)}},[g,Pe]);const ze=(()=>{if(Pe)return Pe;if(!g)return null;const O=De.current;return O&&O.sessionId===g&&O.expiresAt>Date.now()?O.session:null})(),Ne=i.useMemo(()=>{const O=typeof ze?.directory=="string"?ze.directory:"";return Js(O||"")},[ze?.directory]),Ye=ve(O=>O.newSessionDraft?.open?Js(O.newSessionDraft.directoryOverride??""):""),J=i.useMemo(()=>lg({sessionDirectory:Ne,draftDirectory:Ye,isNewSessionDraftOpen:x}),[Ye,x,Ne]),We=Bi(J||null),Ue=i.useMemo(()=>cg({activeProjectLabel:v,openDirectory:J,homeDirectory:A}),[v,A,J]),Ve=!!(Ue||We),gt=i.useMemo(()=>g?ds(ze):Ue??"PiChamber",[ze,g,Ue]),Wt=Oi(),ot=zi(),Je=ve(O=>O.updateSessionTitle),xt=ve(O=>O.archiveSessions),tt=ve(O=>O.deleteSessions),[st,St]=i.useState(!1),[Yt,ut]=i.useState(!1),qe=i.useRef(!1),[bt,jt]=i.useState(""),[Lt,ft]=i.useState(null),qt=i.useRef(null);i.useEffect(()=>{qe.current=!1,ut(!1),St(!1),jt(""),ft(null)},[g]);const Ot=i.useCallback(()=>{g&&(jt(ze?.title?.trim()||gt),St(!0))},[ze?.title,g,gt]),Ct=i.useCallback(async()=>{if(!g)return;const O=bt.trim();O&&O!==ze?.title?.trim()&&await Je(g,O),St(!1)},[ze?.title,g,bt,Je]);i.useEffect(()=>{if(!st)return;const O=re=>{const fe=re.target;(!fe||!qt.current?.contains(fe))&&Ct()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[st,Ct]);const Vt=i.useCallback(()=>{g&&cn(g).then(O=>{ie[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[g]),Bt=i.useCallback(async()=>{if(!g||!J){ie.error("Nothing to export");return}try{await ot.syncSession(g)}catch{ie.error("Failed to load the complete session history");return}const O=Ir(Wt.getState()).list;if(O.length===0){ie.error("Nothing to export");return}const re=Ha(O,ze?.title??null),fe=qa(ze?.title??null);await Ya(re,fe)||Wa(re,fe),ie.success("Session exported")},[ze?.title,g,Wt,J,ot]);m?.type==="busy"||m?.type;const is=i.useCallback(async()=>{if(!g||!Lt)return;const O=gd(),re=[g];for(let at=0;at<re.length;at+=1){const gs=re[at];for(const Ut of O)Ut.parentID===gs&&!re.includes(Ut.id)&&re.push(Ut.id)}const fe=Lt;if(ft(null),(fe==="archive"?await xt(re):await tt(re)).failedIds.length>0){ie.error(fe==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(fe==="archive"?"Session archived":"Session deleted")},[xt,g,tt,Lt]),pe=se(O=>O.isArchivePageOpen),_e=i.useMemo(()=>pe?{title:"Archive",subtitle:null}:null,[pe]),me=i.useMemo(()=>Js(J||b?.path||""),[b?.path,J]),Te=i.useMemo(()=>b?{id:b.id,path:b.path}:null,[b]),$e=i.useRef(null);i.useEffect(()=>{!Te||!me||($e.current={projectRef:Te,directory:me})},[me,Te]);const Ze=i.useMemo(()=>Te&&me?{projectRef:Te,directory:me}:$e.current,[me,Te]),Qt=i.useCallback(async O=>{},[]),nt=i.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const re=O.tagName;(re==="INPUT"||re==="TEXTAREA"||re==="SELECT"||O.isContentEditable)&&O.blur()},[]),Jt=i.useCallback(()=>{if(C){nt(),l(!M);return}c()},[nt,C,M,l,c]),kt=i.useCallback(()=>{nn("desktop_open_draft_mini_chat_window",{directory:Js(J||b?.path||""),projectId:b?.id??null,apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[b?.id,b?.path,J]),it=i.useCallback(()=>{if(x){kt();return}g&&nn("desktop_open_session_mini_chat_window",{sessionId:g,directory:Js(J||b?.path||""),apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[b?.path,g,kt,x,J]),Xt=qn,_t=Pg,ps=i.useMemo(()=>n?"sessions":I?r&&o?o:null:r?"git":u,[u,I,n,r,o]),Zt=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&M&&l(!1)},[M,n,e,s,r,l]),zt=i.useCallback(()=>{e?.()},[e]),ms=i.useCallback(()=>{s?.()},[s]),ht=i.useMemo(()=>U&&R&&!P?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!U||F?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[U,P,R,K,F]);Me.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ht)},[ht]);const As=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",oe=d?"0px":U&&F?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":S?"2.75rem":"2.5rem";Me.useEffect(()=>{if(!U||!R){B(!1);return}let O=!1;const re=async()=>{try{const He=await nn("desktop_is_window_fullscreen");O||B(He===!0)}catch{O||B(!1)}},fe=()=>{re()};return re(),window.addEventListener("pichamber:window-resized",fe),()=>{O=!0,window.removeEventListener("pichamber:window-resized",fe)}},[U,R]);const et=i.useMemo(()=>!U||!R||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[U,R,G]),pt=i.useMemo(()=>{if(!(U&&!F))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[U,F]),Nt=i.useCallback(()=>{if(typeof document>"u")return;const O=T.current?.getBoundingClientRect().height;O&&document.documentElement.style.setProperty("--oc-header-height",`${O}px`)},[]);Me.useEffect(()=>{if(typeof window>"u")return;Nt();const O=T.current;if(!O||typeof ResizeObserver>"u")return()=>{};let re=0;const fe=()=>{re||(re=requestAnimationFrame(()=>{re=0,Nt()}))},He=new ResizeObserver(fe);return He.observe(O),window.addEventListener("resize",fe),window.addEventListener("orientationchange",fe),()=>{re&&cancelAnimationFrame(re),He.disconnect(),window.removeEventListener("resize",fe),window.removeEventListener("orientationchange",fe)}},[Nt]),Me.useEffect(()=>{Nt()},[Nt,C,et]);const yt=i.useCallback(async O=>{const re=O.target;re.closest(".app-region-no-drag")||re.closest("button, a, input, select, textarea")||O.button===0&&U&&await xd()},[U]),wt=i.useMemo(()=>C?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[C]),gn=i.useCallback(O=>eo(sn(O,h)),[h]);Me.useEffect(()=>{!C&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&f("chat")},[u,C,f]);const xn=i.useMemo(()=>{const O=[];return U&&O.push({value:"instance",label:"Instance",icon:t.jsx(D,{name:"server",className:"h-3.5 w-3.5"})}),O},[U]);Me.useEffect(()=>{const O=re=>{if(ou(re)&&!re.shiftKey&&!re.altKey){const fe=parseInt(re.key,10);fe>=1&&fe<=wt.length&&(re.preventDefault(),C&&(nt(),Zt()),f(wt[fe-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[nt,Zt,C,f,wt]),Me.useEffect(()=>{const O=re=>{const fe=sn("toggle_services_menu",h);if(zo(re,fe)){re.preventDefault(),xe?be(!1):(be(!0),ne());return}const He=sn("cycle_services_tab",h);if(zo(re,He)){if(re.preventDefault(),xn.length===0)return;be(!0),ne();return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[h,xe,xn,ne]);const Ks=O=>{const re=u===O.id,fe=O.icon==="diff",He=fe?null:O.icon,es=O.id==="chat",at=Ut=>fe?t.jsx(Si,{size:Ut}):He?t.jsx(D,{name:He,className:`h-${Ut/4} w-${Ut/4}`}):null,gs=t.jsxs("button",{type:"button",onClick:()=>f(O.id),className:z("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",re?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",es&&!C&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":re,role:"tab",children:[C?at(20):t.jsxs(t.Fragment,{children:[at(16),t.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return t.jsx(i.Fragment,{children:gs},O.id)},Vn=t.jsxs(t.Fragment,{children:[t.jsx(hg,{directory:me,className:"mr-1"}),U?t.jsx(Fg,{isDesktopApp:U,currentInstanceLabel:ge,compactCurrentInstanceLabel:te,currentInstanceIsLocal:je,isDesktopServicesOpen:xe,setIsDesktopServicesOpen:be,refreshCurrentInstanceLabel:ne,shortcutLabel:gn,remoteUpdateInfo:ue,remoteUpdateChecking:Y,remoteUpdateError:W,onOpenRemoteUpdate:Ie}):null,t.jsx(Tg,{isMobile:C,githubAuthStatus:E,githubAccounts:we,githubAvatarUrl:ee,githubLogin:H,isSwitchingGitHubAccount:ce,handleGitHubAccountSwitch:Qt})]}),Qn=$&&(x||!!g),bn=()=>t.jsxs("div",{onMouseDown:yt,className:z("app-region-drag relative flex h-12 select-none items-center pr-3",et),style:pt,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:As}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:oe}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[_e?t.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:_e.title}),_e.subtitle?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:_e.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Xt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Bg,{align:"start",children:t.jsx("button",{type:"button",className:Xt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[st?t.jsxs("form",{ref:qt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),Ct()},children:[t.jsx("input",{value:bt,onChange:O=>jt(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&St(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>St(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:x?"New session":gt}),Ve?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[Ue?t.jsx("span",{className:"truncate",children:Ue}):null,We?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:We})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:g&&!x&&!st?t.jsxs(Rt,{open:Yt,onOpenChange:ut,onOpenChangeComplete:O=>{!O&&qe.current&&(qe.current=!1,Ot())},children:[t.jsx(Et,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(D,{name:"more",className:"size-4"})})}),t.jsxs(Pt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(Xe,{onClick:()=>{qe.current=!0},children:[t.jsx(D,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(Xe,{onClick:Vt,children:[t.jsx(D,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Ls,{}),t.jsxs(Xe,{onClick:()=>{Bt()},children:[t.jsx(D,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ls,{}),t.jsxs(Xe,{onClick:()=>ft("archive"),children:[t.jsx(D,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(Xe,{className:"text-destructive focus:text-destructive",onClick:()=>ft("delete"),children:[t.jsx(D,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),wt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:wt.map(O=>Ks(O))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[Ze?t.jsx(ki,{projectRef:Ze.projectRef,directory:Ze.directory,className:"mr-1"}):null,t.jsx(Mg,{visible:Qn,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:it,className:z(Xt,"mr-1"),Icon:"picture-in-picture-2"}),Vn,t.jsx(Gi,{visible:F&&V==="right",position:"right"})]})]})]}),Hs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[S&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:As}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:oe}})]}),!S&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:zt,className:z(_t,ps==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(D,{name:"layout-left",className:"h-5 w-5"})}):M?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(D,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Jt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(D,{name:"play-list-add",className:"h-5 w-5"})}),!e&&M&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!M||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!I&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:wt.map(O=>{const re=u===O.id,fe=O.icon==="diff",He=fe?null:O.icon;return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{C&&(nt(),Zt()),f(O.id)},"aria-label":O.label,"aria-selected":re,role:"tab",className:z(_t,"relative rounded-lg",ps===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[fe?t.jsx(Si,{className:"h-5 w-5"}):He?t.jsx(D,{name:He,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(Oe,{children:t.jsx("p",{children:O.label})})]},O.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:k.map(O=>{const re=r&&o===O.id;return t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{C&&(nt(),Zt()),j(!1),a?.(O.id)},"aria-label":O.label,"aria-selected":re,role:"tab",className:z(_t,"relative rounded-lg",re&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:O.icon,className:"h-5 w-5"})})}),t.jsx(Oe,{children:t.jsx("p",{children:O.label})})]},O.id)})}),t.jsx(oh,{open:w,onOpenChange:j,currentSessionId:g,effectiveDirectory:J||null,isNewSessionDraftOpen:x})]}),Ze&&t.jsx(ki,{projectRef:Ze.projectRef,directory:Ze.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!I?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ms,className:z(_t,"relative",ps==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Oe,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Is=z("header-safe-area relative z-10 bg-background",C&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:T,className:Is,style:{"--padding-scale":"1"},children:C?Hs():bn()}),t.jsx(Lg,{action:Lt,onClose:()=>ft(null),sessionTitle:gt,onConfirm:()=>{is()}}),t.jsx(Sa,{open:Ce,onOpenChange:Z,info:ue,downloading:!1,downloaded:!1,progress:null,error:W,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ni="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",_g="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Bx=()=>{const e=se(p=>p.isSidebarOpen),s=se(p=>p.toggleSidebar),n=se(p=>p.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=eo(sn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=$i(),{enabled:d}=Vr(),u=!e,f=l&&c==="left",h=l,x=u||f||h,g=f||h,m=i.useCallback(()=>{nn("desktop_show_app_menu").catch(p=>{console.warn("[titlebar] failed to open app menu",p)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const p=S=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(S)}px`)},y=S=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(S)}px`)};if(!g)return;const b=o.current,A=r.current;if(!b||!A){p(0),y(0);return}const v=()=>{const S=Math.max(b.getBoundingClientRect().width,b.scrollWidth);p(S),y(A.getBoundingClientRect().width)};if(v(),typeof ResizeObserver>"u")return;const C=new ResizeObserver(v);return C.observe(b),C.observe(A),()=>{C.disconnect()}},[g]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[f?t.jsx(Gi,{visible:!0,position:"left"}):null,h?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:m,"aria-label":"Open PiChamber menu",className:z(Ni,"shrink-0"),children:t.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(Fe,{children:[t.jsx(Le,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:z(d?_g:Ni,"shrink-0"),children:t.jsx(D,{name:"layout-left",className:d?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Oe,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Ai=200,zg="cubic-bezier(0.22, 1, 0.36, 1)",_x=e=>{const s=i.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=i.useState(e),[o,a]=i.useState(e);return i.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),Ai);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${Ai}ms ${zg}`}},Ug=hs(()=>({statusById:new Map})),zx=()=>{qi(),Ki()},Ux=e=>{ve.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),se.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),qi(),he.getState().clearAll(),Bs.getState().resetForRuntimeSwitch(),bd.getState().resetForRuntimeSwitch(),yd.getState().resetForRuntimeSwitch(),wd(),vd.getState().resetForRuntimeSwitch(),Gt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),dt.getState().resetForRuntimeSwitch(),Sd.getState().resetForRuntimeSwitch(),Ug.setState({statusById:new Map}),jd(),Cd(),Mu.getState().reset(),iu.getState().resetForRuntimeSwitch(),Ti.getState().resetForRuntimeSwitch(e.runtimeKey),Dr.getState().resetForRuntimeSwitch(e.runtimeKey),Xs.getState().resetForRuntimeSwitch(e.runtimeKey),Wh.getState().resetForRuntimeSwitch(),lt.getState().resetForRuntimeSwitch(e.runtimeKey),au.getState().resetForRuntimeSwitch(e.runtimeKey),ve.getState().restoreForRuntimeSwitch(e.runtimeKey),se.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=se.getState();Or({sessionId:ve.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),Ki()};export{pn as $,Dx as A,Ex as B,Da as C,Lx as D,Fn as E,dx as F,ix as G,Ox as H,Mx as I,zx as J,Qu as K,bs as L,Pa as M,ux as N,rx as O,wx as P,Ff as Q,io as R,Um as S,Tx as T,Sa as U,bx as V,Tf as W,ka as X,eh as Y,Df as Z,Lf as _,Ra as a,ja as a0,mn as a1,rn as a2,Ef as a3,px as a4,jx as a5,Rf as a6,hx as a7,Pf as a8,Sx as a9,Nx as aa,kx as ab,Of as ac,vx as ad,Cx as ae,Ax as af,fx as ag,mx as ah,gx as ai,xx as aj,Vf as ak,yx as al,pf as am,Mf as an,mf as ao,Ea as b,Gr as c,th as d,xs as e,_x as f,ff as g,ax as h,Fx as i,sx as j,cx as k,ox as l,Ix as m,Rx as n,Bx as o,lx as p,Mn as q,Ux as r,nh as s,oh as t,nx as u,xm as v,pi as w,Zs as x,pm as y,Px as z};
|