@pi-chamber/web 1.0.2 → 1.0.3-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView-C3jwAdba.js → DiagramView-CXjieF51.js} +1 -1
- package/dist/assets/DiffView-CXg8TAtI.js +18 -0
- package/dist/assets/{FileSaveConflictDialog-BDHl1ERM.js → FileSaveConflictDialog-a-HOCgyP.js} +1 -1
- package/dist/assets/{FilesView-DjD5jjcd.js → FilesView-Dcd9ltOX.js} +1 -1
- package/dist/assets/{GitView-D_TzczhS.js → GitView-DF2nsuSA.js} +3 -3
- package/dist/assets/{JsonTreeView-BTMtZylb.js → JsonTreeView-BRU2mRTd.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-DnZhLsfY.js → MarkdownRendererImpl-CeYMkg1A.js} +5 -5
- package/dist/assets/{PatchDiff-D4jQKTZA.js → PatchDiff-kSTpjhu6.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-BX6P7l8U.js → SessionSwitcherContent-BsXDFt24.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DGvRKfRw.js → SessionSwitcherDropdown-D8fSObHr.js} +2 -2
- package/dist/assets/{SessionUnreadDot-CPTTyo0r.js → SessionUnreadDot-BpsHyrri.js} +1 -1
- package/dist/assets/SettingsView-OEl7QmXC.js +6 -0
- package/dist/assets/{SettingsWindow-MrdvHysy.js → SettingsWindow-BMBCj_L_.js} +1 -1
- package/dist/assets/{ToolOutputDialog-9UTlcthG.js → ToolOutputDialog-KOVdmTqm.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-D_HifNve.js → ToolPartDiffPreview-B9xuVvkm.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CvqZNzUR.js → VirtualizedFileDiff-CV_Cpmqu.js} +4 -4
- package/dist/assets/{collapsible-BencOwkW.js → collapsible-BH1vXEAI.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-B1Zc3P5v.js → computeVirtualFileMetrics-yHZbtf5H.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-CJZHfvjH.js → contextFileOpenGuard-BA2pkQY_.js} +1 -1
- package/dist/assets/{gitStatusPredicates-C7tetvAB.js → gitStatusPredicates-CpGQLvMK.js} +1 -1
- package/dist/assets/index-5fyXnZFi.css +1 -0
- package/dist/assets/{index-CpSdU-d4.js → index-C-sV_9sb.js} +3 -3
- package/dist/assets/{index-DYXaDVnz.js → index-D_FGGnQQ.js} +1 -1
- package/dist/assets/{isDiffPlainText-DMMH-XmY.js → isDiffPlainText-BNyusJZz.js} +1 -1
- package/dist/assets/{isFilePlainText-DcCgFOGI.js → isFilePlainText-CMAUe7qD.js} +1 -1
- package/dist/assets/{main-BZu7VLeY.js → main-BMLgZ5yn.js} +2 -2
- package/dist/assets/{main-DvtT25LM.js → main-DNq1n9F_.js} +3 -3
- package/dist/assets/{markdownCore-D6HZ46BO.js → markdownCore-CZWcaNr2.js} +2 -2
- package/dist/assets/{miniChat-CLS1HbGi.js → miniChat-B2AgUZqL.js} +2 -2
- package/dist/assets/{mobile-BuCJ5Obm.js → mobile-BsGiRUUg.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-BtREv0kE.js → renderElectronMiniChatApp-UV9dnnbf.js} +2 -2
- package/dist/assets/renderMobileApp-BMifduGA.js +11 -0
- package/dist/assets/runtimeEndpointReset-CkvC02dQ.js +53 -0
- package/dist/assets/{runtimeSurface-Bm6cRkok.js → runtimeSurface-BdndJV2m.js} +1 -1
- package/dist/assets/{useAppFontEffects-SHxBpd4f.js → useAppFontEffects-CclUs9KY.js} +98 -98
- package/dist/assets/{useFilesViewSearch-CJ6yYAoc.js → useFilesViewSearch-CI5Gy1cp.js} +1 -1
- package/dist/assets/{usePushVisibilityBeacon-mnTxlkQZ.js → usePushVisibilityBeacon-aDmGZrTW.js} +3 -3
- package/dist/assets/{useSwitcherItems-DWUNXYMV.js → useSwitcherItems-BZKyNjhp.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B4enwgcI.js → vendor-codemirror-language-data-C6LBD7qA.js} +2 -2
- package/dist/assets/{web-components-ldhQxnFE.js → web-components-Cdnmh4Xb.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/pi/model-config-store.js +146 -20
- package/server/lib/pi/model-config-store.test.js +153 -21
- package/server/lib/pi/routes.js +42 -1
- package/server/lib/pi/routes.test.js +104 -2
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -2
- package/server/lib/pi/session-daemon/session-daemon.js +322 -58
- package/server/lib/pi/session-daemon/session-daemon.test.js +335 -0
- package/server/lib/pi/session-daemon/session-failed-create-cleanup.test.js +372 -0
- package/server/lib/pi/session-persistence-gap.test.js +731 -0
- package/dist/assets/DiffView-CqPv7nw1.js +0 -18
- package/dist/assets/SettingsView-CD0EfMno.js +0 -2
- package/dist/assets/index-Dwz16owi.css +0 -1
- package/dist/assets/renderMobileApp-UF8ITb8A.js +0 -11
- package/dist/assets/runtimeEndpointReset-BcdDES-U.js +0 -53
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DYXaDVnz.js","assets/useAppFontEffects-SHxBpd4f.js","assets/index-CpSdU-d4.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-Dwz16owi.css","assets/vendor-base-ui-DXSHfszQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.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-Bm6cRkok.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-B4enwgcI.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-CNlncqrr.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-B1Zc3P5v.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-DcCgFOGI.js","assets/isDiffPlainText-DMMH-XmY.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-DGvRKfRw.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as cs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ae,j as t,R as i,b as tc}from"./vendor-react-B5Z1Mdn3.js";import{aQ as Ts,aR as sc,a2 as It,a3 as $e,a4 as Ge,a5 as Rt,B as Te,I as R,a6 as Ke,a7 as Dt,a9 as ot,t as oe,a as pt,f as De,_ as $s,ae as fn,aS as Si,ag as Yt,ah as qt,ai as fs,aj as es,ak as hs,al as ks,aG as Ss,aT as js,g as Ms,aU as lr,aV as Do,aW as Eo,aX as on,e as Mn,o as ji,af as xs,aY as Po,a8 as us,aZ as Nr,a_ as nc,a$ as rc,b0 as oc,b1 as ic,b2 as ac,b3 as Ir,b4 as lc,y as Wt,b5 as cc,b6 as dc,b7 as uc,b8 as Ci,b9 as fc,ba as hc,bb as ki,bc as Ai,bd as Ni,aD as Rr,r as an,n as Jr,ap as pc,az as mc,aC as Ii,L as As,d as Xr,ab as Gs,ay as Ri,be as Vn,bf as Mo,bg as ht,aE as Di,bh as Ei,au as gc,h as Pi,j as bc,bi as xc,i as yc,bj as Ds,b as To,c as vc,bk as wc,u as Sc,aF as jc,aI as Cc,bl as Dr,bm as kc,bn as Ac,aH as Nc,bo as Ic,bp as Rc,T as Dc,aa as Cs,am as Mi,w as Ec,ac as Pc,bq as Mc,br as Tc,k as Fc,bs as Oc,bt as Ti,bu as Lc,bv as Bc,bw as _c,bx as Uc,by as zc,bz as $c,bA as Gc,bB as Kc,bC as Wc,bD as Hc}from"./useAppFontEffects-SHxBpd4f.js";import{Z as Fo,_ as Yc,R as Ls,$ as Fi,a0 as Oi,a1 as qc,a2 as Qc,u as Bs,K as Vc,a3 as Jc,a4 as Xc,a5 as Zc,a6 as Vt,v as Jt,a7 as ed,a8 as td,a9 as sd,aa as Zr,m as Ct,ab as nd,ac as rd,ad as od,t as ce,o as $,ae as id,f as qe,B as ke,af as _s,ag as _t,ah as Oo,ai as Er,a as eo,T as to,U as Un,aj as ad,ak as ld,al as Li,F as cd,Q as Bi,C as ln,am as Pr,h as Mr,d as kn,an as dd,ao as ud,ap as Lo,aq as en,ar as cr,as as Tr,at as zn,au as ys,av as Bo,aw as Fr,ax as _i,ay as Or,az as fd,z as Ui,aA as hd,aB as pd,aC as md,aD as gd,aE as bd,aF as xd,aG as yd,aH as vd,Y as zi,P as wd,J as Sd}from"./index-CpSdU-d4.js";import{c as Ks,d as $i,p as so,u as Lr,a as jd}from"./vendor-zustand-GVb4H8HE.js";import{g as ds,b as Cd,c as Gi,r as kd,d as Ki,s as Tn,e as Wi,h as hn,i as pn,j as Ad,k as Nd,l as Id,m as _o,n as Jn,f as Rd,a as Dd,S as Ed,t as Pd,o as Md}from"./SessionUnreadDot-CPTTyo0r.js";import{C as Hi,a as Yi,M as qi,b as Qi,c as Vi,d as Ji,S as Xi,D as Td,e as Fd,f as Od,g as Ld,h as Bd,i as _d,j as Ud}from"./vendor-base-ui-DXSHfszQ.js";import{c as Zi,d as Br,P as zd,D as ea,e as ta,f as $d,b as Gd,a as Kd,T as Wd,M as Hd}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{u as Yd}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as qd,v as Qd,u as Vd}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as Jd}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-xterm-xterm-CrXqRur4.js";import{usePermissionStore as Xd}from"./permissionStore-iKN1K2_x.js";const Zd="chat";function sa(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ts.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ts.SETTINGS,n),s}return e.tab!==Zd&&s.set(Ts.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ts.FILE,e.diffFile),s}function eu(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 tu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=sa(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ts.SESSION)&&s.set(Ts.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 _r(e,s={}){if(!(typeof window>"u")&&!(!s.force&&tu(e)))try{const n=sa(e),r=eu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const su=["typescript","javascript","tsx","jsx","json","markdown"],na={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Uo=null;const ra=()=>(Uo??=Promise.all([cs(()=>import("./index-DYXaDVnz.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])),cs(()=>import("./workerFactory-tw7cIdmV.js"),[]),cs(()=>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})),Uo),mn={},zo=new Set,Ur=new Set;let Fn={light:"pierre-light",dark:"pierre-dark"};const nu=()=>{for(const e of Ur)e()},oa=(e,s)=>{s.setRenderOptions({theme:Fn,lineDiffType:na[e].lineDiffType})},zr=e=>{typeof window>"u"||zo.has(e)||(zo.add(e),ra().then(s=>{if(mn[e])return;const n=na[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:su,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),mn[e]=r,oa(e,r),nu()}))},ru=e=>(Ur.add(e),()=>Ur.delete(e)),ou=e=>{if(!(Fn.light===e.light&&Fn.dark===e.dark)){Fn=e;for(const s of Object.keys(mn)){const n=mn[s];n&&oa(s,n)}}},ng=({children:e})=>{const s=sc(),n=Fo(!1),r=Fo(!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 Ae.useEffect(()=>{let d=!1;return ra().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),ou({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ae.useEffect(()=>{if(typeof window>"u")return;const d=()=>{zr("unified"),zr("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})},rg=(e="unified")=>{const s=Ae.useSyncExternalStore(ru,()=>mn[e],()=>{});return Ae.useEffect(()=>{zr(e)},[e]),s},iu={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},au={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 ia(e){return e&&au[e]||"var(--primary)"}const $o=({icon:e,className:s,colorToken:n})=>{const r=iu[e??"branch"]??"user-3";return t.jsx(R,{name:r,className:s,style:{color:ia(n)}})},lu=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(It,{children:[t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx(Rt,{asChild:!0,children:t.jsxs(Te,{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:ia(e?.color)},disabled:a,children:[r?t.jsx(R,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx($o,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(R,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Ke,{sideOffset:8,children:"Git identity"})]}),t.jsx(Dt,{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(ot,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx($o,{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(R,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},cu=e=>e==="/",Us=e=>e.replace(/\\/g,"/"),zs=e=>{if(!e||cu(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),$n=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},no=e=>e.lastIndexOf("/"),aa=e=>{if(Fs(e))return e;const s=no(e);return s<0?e:e.slice(0,s+1)},la=e=>{const s=no(e);return e.slice(s+1)},ca=e=>{const s=zs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=no(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},da=e=>Fs(e)&&ca(e)!==null,du=e=>{if(!da(e))return null;const s=zs(e.trim());return la(s)||s},uu=(e,s)=>`${aa(e)}${s}/`,vs=e=>{if(!e)return null;const s=zs(Us(e.trim()));return s?s.toLowerCase():null},Go=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},fu=(e,s)=>{const n=zs(Us(e.trim())),r=zs(Us(s.trim()));if(!n)return"";if(!r)return $n(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:$n(n)},hu=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,$r=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},pu=async()=>Yc(),mu=()=>{const[e,s]=Ae.useState(!1),[n,r]=Ae.useState(!1);Ae.useEffect(()=>{s(Ls()),r(Fi())},[]);const o=Ae.useCallback(async c=>e?await Oi(c):{success:!0,path:c},[e]),a=Ae.useCallback(async c=>e?await qc():{success:!0},[e]),l=Ae.useCallback(async c=>e?await Qc():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function gu({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Bs(re=>re.homeDirectory),{canRequestAccess:o,startAccessing:a}=mu(),l=i.useRef(null),c=i.useRef(new Map),[d,u]=i.useState(""),[f,h]=i.useState("~/"),[b,p]=i.useState([]),[g,m]=i.useState(!1),[w,x]=i.useState(!1),[I,v]=i.useState(null),[A,j]=i.useState(0),[N,C]=i.useState(0),[y,k]=i.useState(!1),[D,M]=i.useState(!1),[B,_]=i.useState("right"),K=i.useRef("~/"),V=d||r;i.useEffect(()=>{if(!e)return;h("~/"),p([]),C(0),k(!1),M(!1),K.current="~/",_("right"),n||requestAnimationFrame(()=>$r(l.current));let re=!1;return(async()=>{const H=await pu();re||(u(H||r||""),n||requestAnimationFrame(()=>$r(l.current)))})(),()=>{re=!0}},[r,e,n]);const O=i.useMemo(()=>aa(f),[f]),T=i.useMemo(()=>Fs(f)?"":la(f),[f]),P=i.useMemo(()=>V?Go(O,V):"",[O,V]);i.useEffect(()=>{const re=K.current;re!==O&&(_(O.length>=re.length?"right":"left"),K.current=O)},[O]),i.useEffect(()=>{if(!e||!P){p([]),v(null);return}let re=!1;return m(!0),x(!1),v(null),Vc(P).then(ae=>{if(re)return;x(!1),v(null);const H=ae.filter(me=>me.isDirectory).map(me=>({name:me.name,path:Us(me.path)})).sort((me,Ue)=>me.name.localeCompare(Ue.name));p(H)}).catch(ae=>{if(!re){p([]);const H=Jc(ae)?ae.reason:"unknown";v(H),x(H==="not-found")}}).finally(()=>{re||m(!1)}),()=>{re=!0}},[P,A,e]);const U=i.useMemo(()=>{const re=T.toLowerCase(),ae=D||T.startsWith(".");return b.filter(H=>H.name.toLowerCase().startsWith(re)&&(ae||!H.name.startsWith(".")))},[T,b,D]),ne=i.useMemo(()=>du(f),[f]),W=i.useMemo(()=>ca(f),[f]),G=i.useMemo(()=>{const re=[],ae=vs(P);da(f)&&ne&&W&&re.push({type:"parent",value:"browse:up",name:ne,path:W,alreadyAdded:!!(ae&&s.has(ae))});for(const H of U){const me=vs(H.path);re.push({type:"directory",value:`browse:${H.path}`,name:H.name,path:H.path,alreadyAdded:!!(me&&s.has(me))})}return re},[s,P,ne,U,W,f]);i.useEffect(()=>{C(0)},[f,G.length]);const Ne=i.useMemo(()=>V?zs(Go(f,V)):"",[V,f]),ee=vs(Ne),Fe=!!(ee&&s.has(ee)),_e=i.useMemo(()=>T?U.find(re=>re.name===T)??null:null,[T,U]),q=!!(Ne&&!Fe&&(I===null||I==="not-found")&&(Fs(f)&&w||!Fs(f)&&T.trim().length>0&&_e===null)),F=G[N]??null,z=!!F,Q=i.useCallback(re=>{h($n(re))},[]),se=i.useCallback(re=>{h(uu(f,re.name))},[f]),Se=i.useCallback(re=>{if(re){if(re.type==="parent"){Q(re.path);return}se(re)}},[Q,se]),ge=i.useCallback(async re=>{const ae=await a(re);if(!ae.success)return oe.error("Failed to open directory",{description:ae.error||"Desktop could not grant file access."}),!1;const H=V?fu(re,V):$n(Us(re));return Q(H),!0},[Q,V,a]),we=i.useCallback(async()=>{if(!y){k(!0);try{if(Fi()){const ae=await Oi(Ne);if(!ae.success||!ae.path){ae.error&&ae.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:ae.error});return}await ge(ae.path);return}const re=await Xc(Ne);if(re.status==="cancelled")return;if(re.status!=="picked"){oe.error("Couldn't open a folder picker",{description:re.error});return}await ge(re.path)}catch(re){oe.error("Failed to select directory",{description:re instanceof Error?re.message:"Unknown error occurred."})}finally{k(!1)}}},[ge,y,Ne]);return{inputRef:l,rowRefs:c,query:f,setQuery:h,isLoading:g,isBrowseDirectoryMissing:w,browseErrorReason:I,browseReloadKey:A,setBrowseReloadKey:j,highlightedIndex:N,setHighlightedIndex:C,isPickingLocation:y,showHidden:D,setShowHidden:M,folderEnterFrom:B,explorerRootDirectory:V,browseDirectoryDisplayPath:O,browseDirectoryAbsolutePath:P,browseFilterQuery:T,filteredEntries:U,rows:G,targetPath:Ne,isAlreadyAdded:Fe,shouldCreateTarget:q,highlightedRow:F,hasHighlightedBrowseItem:z,canRequestAccess:o,browseToDisplayPath:Q,browseToEntry:se,executeRow:Se,applyPickedLocation:ge,handleBrowseLocation:we}}const bs=Ks()($i(so((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=Jt()?.git,o=r?await r.getGitIdentities():await od();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=Jt()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await rd();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=Jt()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await nd();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=Jt()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Ct("/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"};Vt("saving");const o=Jt()?.git;return o?await o.createGitIdentity(r):await sd(r),Vt("saved"),await s().loadProfiles(),!0}catch(r){return Vt("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};Vt("saving");const l=Jt()?.git;return l?await l.updateGitIdentity(n,a):await td(n,a),Vt("saved"),await s().loadProfiles(),!0}catch(o){return Vt("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{Vt("saving");const r=Jt()?.git;return r?await r.deleteGitIdentity(n):await ed(n),Vt("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return Vt("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:Zc(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=bs);function bu({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=pt(W=>W.addProject),h=ce(W=>W.setActiveMainTab),b=ce(W=>W.setSessionSwitcherOpen),p=De(W=>W.openNewSessionDraft),g=bs(W=>W.profiles),m=bs(W=>W.globalIdentity),w=bs(W=>W.defaultGitIdentityId),x=bs(W=>W.loadProfiles),I=bs(W=>W.loadGlobalIdentity),v=bs(W=>W.loadDefaultGitIdentityId),[A,j]=i.useState(!1),[N,C]=i.useState(!1),[y,k]=i.useState(""),[D,M]=i.useState(null);i.useEffect(()=>{e&&(j(!1),C(!1),k(""),M(null))},[e]),i.useEffect(()=>{e&&(x(),I(),v())},[v,x,I,e]);const B=i.useMemo(()=>{const W=new Map;m&&W.set(m.id,m);for(const G of g)W.set(G.id,G);return Array.from(W.values())},[g,m]);i.useEffect(()=>{if(!e||!N||D!==null)return;const W=typeof w=="string"?w.trim():"";if(W&&B.some(Ne=>Ne.id===W)){M(W);return}const G=B.find(Ne=>Ne.authType==="ssh"||Ne.sshKey);G&&M(G.id)},[B,w,N,e,D]);const _=i.useMemo(()=>B.find(W=>W.id===D)??null,[B,D]),K=i.useCallback((W,G)=>{h("chat"),n&&b(!1),p({selectedProjectId:W,directoryOverride:G}),s()},[n,s,p,h,b]),V=i.useCallback(async W=>{if(!W||A)return;const G=vs(W);if(G&&r.has(G))return;let Ne=W;j(!0);try{const ee=!N&&a&&vs(W)===vs(o);if(N){const _e=y.trim();if(!_e){oe.error("Enter a repository URL before cloning.");return}const q=await Ct("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:_e,destinationPath:W,gitIdentityId:_?.id??null})});if(!q.ok)throw new Error("Failed to clone git repository");Ne=(await q.json()).path||W}else if(ee&&!(await Ct("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:W})})).ok)throw new Error("Failed to select directory");const Fe=f(Ne);if(!Fe){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}K(Fe.id,Fe.path)}catch(ee){oe.error("Failed to select directory",{description:ee instanceof Error?ee.message:"Unknown error occurred."})}finally{j(!1)}},[f,r,c,y,N,A,K,_?.id,a,o]),O=!A&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,T=O&&y.trim().length>0,P=N?T:O,U=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:A,isCloneMode:N,setIsCloneMode:C,cloneRemoteUrl:y,setCloneRemoteUrl:k,selectedGitIdentityId:D,setSelectedGitIdentityId:M,availableGitIdentities:B,selectedGitIdentity:_,canSubmit:P,submitActionLabel:d?"Already added":N?A?"Cloning...":"Clone & add":A?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:U,finalizeSelection:V}}const xu=({open:e,onOpenChange:s})=>{const n=pt(H=>H.projects),{isMobile:r,isTablet:o}=$s(),a=r||o,l=i.useMemo(()=>new Set(n.map(H=>vs(H.path)).filter(H=>!!H)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:d,rowRefs:u,query:f,setQuery:h,isLoading:b,browseErrorReason:p,setBrowseReloadKey:g,highlightedIndex:m,setHighlightedIndex:w,isPickingLocation:x,showHidden:I,setShowHidden:v,folderEnterFrom:A,browseDirectoryDisplayPath:j,browseDirectoryAbsolutePath:N,rows:C,targetPath:y,isAlreadyAdded:k,shouldCreateTarget:D,highlightedRow:M,hasHighlightedBrowseItem:B,canRequestAccess:_,executeRow:K,handleBrowseLocation:V}=gu({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:O,isCloneMode:T,setIsCloneMode:P,cloneRemoteUrl:U,setCloneRemoteUrl:ne,setSelectedGitIdentityId:W,availableGitIdentities:G,selectedGitIdentity:Ne,canSubmit:ee,submitActionLabel:Fe,submitModifierLabel:_e,finalizeSelection:q}=bu({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:y,shouldCreateTarget:D,browseErrorReason:p,browseDirectoryAbsolutePath:N,isAlreadyAdded:k,isPickingLocation:x});i.useLayoutEffect(()=>{const H=d.current;H&&(H.scrollLeft=H.scrollWidth)},[d,f]),i.useLayoutEffect(()=>{!e||a||$r(d.current)},[d,e,a]),i.useLayoutEffect(()=>{const H=C[m];H&&u.current.get(H.value)?.scrollIntoView({block:"nearest"})},[m,u,C]);const F=i.useCallback(H=>{if(H.key==="ArrowDown"){H.preventDefault(),w(me=>Math.min(C.length-1,me+1));return}if(H.key==="ArrowUp"){H.preventDefault(),w(me=>Math.max(0,me-1));return}if(H.key==="Enter"){if(H.preventDefault(),hu(H)){q(y);return}B&&K(M);return}H.key==="Backspace"&&f===""&&(H.preventDefault(),c())},[K,q,c,B,M,f,C.length,w,y]),z=t.jsxs("button",{type:"button",onClick:()=>v(H=>!H),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:[I?t.jsx(R,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Q=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(R,{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(fn,{ref:d,value:f,onChange:H=>h(Us(H.target.value)),onKeyDown:F,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(Te,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:O||x,onMouseDown:H=>H.preventDefault(),onClick:()=>{V()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(R,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),se=C.some(H=>H.type==="parent"),Se=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(Te,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":T,disabled:O||x,onClick:()=>P(H=>!H),children:[t.jsx(R,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),T?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(fn,{value:U,onChange:H=>ne(H.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(lu,{activeProfile:Ne,identities:G,onSelect:H=>W(H.id),isApplying:O,iconOnly:!0})]})]}):null,k?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:$("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",A==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:b?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):p&&p!=="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:p==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[p==="os-permission"&&_?t.jsx(Te,{size:"xs",onClick:()=>{V()},disabled:x,children:"Grant access"}):null,t.jsx(Te,{variant:"outline",size:"xs",onClick:()=>g(H=>H+1),children:"Try again"})]})]}):C.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:C.map((H,me)=>{const Ue=me===m,L=H.type==="directory"&&se;return t.jsxs("button",{ref:X=>{X?u.current.set(H.value,X):u.current.delete(H.value)},type:"button","aria-label":H.type==="parent"?H.alreadyAdded?`Go back from ${H.name}, already added`:`Go back from ${H.name}`:H.alreadyAdded?`Open ${H.name}, already added`:`Open ${H.name}`,onMouseEnter:()=>w(me),onMouseDown:X=>X.preventDefault(),onClick:()=>K(H),className:$("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",Ue&&"bg-interactive-selection text-interactive-selection-foreground",!Ue&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:$("flex min-w-0 flex-1 items-center gap-2",L&&"pl-4"),children:[H.type==="parent"?t.jsx(R,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(R,{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:H.name})]}),H.alreadyAdded?t.jsx("span",{className:$("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Ue?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,H.type==="parent"?t.jsx(R,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(R,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},H.value)})})},j)]})}),ge=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Q,Se]}),we=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(R,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(R,{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(R,{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:_e}),t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),re=t.jsx(Te,{size:r?"xs":"default",onClick:()=>{q(y)},disabled:!ee,className:$(r&&"w-full flex-1"),children:Fe}),ae=()=>t.jsxs(t.Fragment,{children:[r?null:we,t.jsx("div",{className:$("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:re})]});return r?t.jsx(Si,{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:ae()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:z}),ge]})}):t.jsx(Yt,{open:e,onOpenChange:s,children:t.jsxs(qt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(fs,{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(es,{children:"Add folder"}),t.jsx(hs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),z]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:ge}),t.jsx(ks,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ae()})]})})},An=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,og=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=De(N=>N.deleteSession),c=De(N=>N.deleteSessions),d=ce(N=>N.showDeletionDialog),u=ce(N=>N.setShowDeletionDialog),{isMobile:f,isTablet:h,hasTouchInput:b}=$s(),p=f||h||b;i.useEffect(()=>id(()=>{s(!1)}),[]);const g=i.useCallback(N=>{r({sessions:N.sessions,dateLabel:N.dateLabel})},[]),m=i.useCallback(()=>{r(null),a(!1)},[]),w=i.useCallback(async N=>{if(N.sessions.length===0)return;if(N.sessions.length===1){const D=N.sessions[0];await l(D.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const C=N.sessions.map(D=>D.id),{deletedIds:y,failedIds:k}=await c(C);if(y.length>0){const D=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:N.dateLabel?`Removed all sessions from ${N.dateLabel}.`:void 0;oe.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:An(D)})}k.length>0&&oe.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:An("Please try again in a moment.")})},[l,c]);i.useEffect(()=>Ss.onDeleteRequest(N=>{if(!d){w(N);return}g(N)}),[g,d,w]),i.useEffect(()=>Ss.onDirectoryRequest(()=>{s(!0)}),[]);const x=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const N=n.sessions[0];if(!await l(N.id)){oe.error("Failed to delete session"),a(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const N=n.sessions.map(D=>D.id),C=await c(N),y=C.deletedIds,k=C.failedIds;if(y.length>0){const D=k.length>0?k.length===1?`${k.length} session could not be deleted.`:`${k.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;oe.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:An(D),action:{label:"OK",onClick:()=>{}}})}if(k.length>0&&(oe.error(k.length===1?`Failed to delete ${k.length} session`:`Failed to delete ${k.length} sessions`,{description:An("Please try again in a moment.")}),y.length===0)){a(!1);return}}m()}finally{a(!1)}}},[n,l,c,m]),I=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(N=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:ds(N)})},N.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,A=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(R,{name:"checkbox-blank",className:"size-4"}):t.jsx(R,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Te,{variant:"ghost",onClick:m,disabled:o,children:"Cancel"}),t.jsx(Te,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),j=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[p?t.jsx(Si,{open:!!n,onClose:()=>{o||m()},title:j,footer:t.jsx("div",{className:"flex justify-end gap-2",children:A}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),v]})}):t.jsx(Yt,{open:!!n,onOpenChange:N=>{if(!N){if(o)return;m()}},children:t.jsxs(qt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(fs,{children:[t.jsx(es,{children:j}),I&&t.jsx(hs,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(ks,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),t.jsx(xu,{open:e,onOpenChange:s})]})},ig=()=>{const e=js(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(js.getState().markNotificationSent(s.key),oe.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},yu=[{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","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"]}],vu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function wu(e){const s=e.trim().toLowerCase();return yu.find(n=>n.slug===s)??null}function Su(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=vu[s];if(n)return n;const r=wu(s);return r?r.slug:"home"}function ag(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function lg(){const e=i.useRef(!1),s=i.useRef(!1),n=De(f=>f.setCurrentSession),r=ce(f=>f.setActiveMainTab),o=ce(f=>f.setSettingsDialogOpen),a=ce(f=>f.setSettingsPage),l=ce(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const h=De.getState().currentSessionId,b=Ms().getState().selectedSessionId;if(f.sessionId!==h||f.sessionId!==b){const p=De.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,p)}}if(f.settingsPath){a(Su(f.settingsPath)),o(!0);return}ce.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=De.getState(),h=Ms().getState(),b=ce.getState();return{sessionId:lr({currentSessionId:f.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),u=i.useCallback((f={})=>{if(s.current)return;const h=d();_r(h,f)},[d]);i.useEffect(()=>{if(e.current||(e.current=!0,!Do()))return;const f=Eo();(async()=>(await c(f),_r({...d(),sessionId:f.sessionId??lr({currentSessionId:De.getState().currentSessionId,piSelectedSessionId:Ms().getState().selectedSessionId,draft:De.getState().newSessionDraft}),tab:f.tab??ce.getState().activeMainTab,settingsPath:f.settingsPath??ce.getState().settingsPage,diffFile:f.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),i.useEffect(()=>{const f=()=>{const w=De.getState(),x=Ms().getState();return lr({currentSessionId:w.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:w.newSessionDraft})};let h=f(),b=De.getState().newSessionDraft?.open===!0;const p=()=>{const w=De.getState(),x=f(),I=w.newSessionDraft?.open===!0;x===h&&I===b||s.current||(h=x,b=I,u({replace:!0}))},g=De.subscribe(()=>{p()}),m=Ms().subscribe(()=>{p()});return()=>{g(),m()}},[u]),i.useEffect(()=>{let f=ce.getState().activeMainTab,h=ce.getState().isSettingsDialogOpen,b=ce.getState().settingsPage,p=ce.getState().pendingDiffFile;return ce.subscribe(m=>{if(s.current)return;const w=m.activeMainTab!==f,x=m.isSettingsDialogOpen!==h,I=m.settingsPage!==b,v=m.pendingDiffFile!==p&&m.activeMainTab==="diff";f=m.activeMainTab,h=m.isSettingsDialogOpen,b=m.settingsPage,p=m.pendingDiffFile,(w||x||I||v)&&u()})},[u]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const h=Eo();if(Do())c(h);else{const b=ce.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function ju(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 b=Math.round(h*1e3);return Math.max(a,Math.min(l,b))},f=h=>{c||(d=window.setTimeout(async()=>{const b=await n.current(),p=typeof b=="number"&&Number.isFinite(b)?u(b):o;f(p)},h))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function cg(){const e=on(s=>s.connection==="ready",void 0,"chrome");return ju(e),null}const Ko=12,Cu=[{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"}],ku=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=Cu,onComplete:a})=>{const l=Ae.useRef(!1);Ae.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ae.useMemo(()=>Array.from({length:Ko},(d,u)=>{const f=Math.PI*2*u/Ko;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:$("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 b=f.x*d.radius,p=f.y*d.radius,g={"--translate-x":`${b}px`,"--translate-y":`${p}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:g},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},Au=({durationMs:e=3400}={})=>{const[s,n]=Ae.useState({isActive:!1,cycle:0}),r=Ae.useRef(null),o=Ae.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ae.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ae.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 Ae.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},ua=i.createContext(void 0),dg=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Au(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(ua.Provider,{value:a,children:[e,t.jsx(ku,{isActive:s,burstKey:n})]})},Nu={triggerFireworks:()=>{},dismissFireworks:()=>{}},ug=()=>i.useContext(ua)??Nu,Gn=2e3,fa=600*1e3;async function Iu(){try{const e=await Ct("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const s=await e.json().catch(()=>({}));return{success:!0,autoRestart:s.autoRestart!==!1,jobId:typeof s.jobId=="string"?s.jobId:void 0,channel:s.channel==="rc"?"rc":s.channel==="stable"?"stable":void 0,targetVersion:typeof s.targetVersion=="string"?s.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Ru(e,s=Math.ceil(fa/Gn),n=Gn,r=qe()){for(let o=0;o<s;o++){if(qe()!==r)return{applied:!1,stale:!0};try{const a=await Ct("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(qe()!==r)return{applied:!1,stale:!0};if(a.ok){const l=await a.json().catch(()=>null);if(qe()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(qe()!==r)return{applied:!1,stale:!0}}await new Promise(a=>setTimeout(a,n))}return{applied:!1}}async function Du(e,s,n=Math.ceil(fa/Gn),r=Gn,o=qe()){for(let a=0;a<n;a++){if(qe()!==o)return{applied:!1,stale:!0};try{const l=await Ct(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(qe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(qe()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?s("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&s("updating")}else{if(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(qe()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};s("reconnecting")}else s("reconnecting")}}catch{if(qe()!==o)return{applied:!1,stale:!0};s("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Wo="https://github.com/RyderAsKing/PiChamber/releases";function Eu(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 Pu(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Ho(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Mu(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 Tu(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 ha=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,h]=Ae.useState(null),[b,p]=Ae.useState("idle"),[g,m]=Ae.useState(null),[w,x]=Ae.useState(null),[I,v]=Ae.useState({}),A=n?.version?n.releaseUrl||`${Wo}/tag/v${n.version}`:Wo,j=n?.downloadUrl||A,N=a?.total?Math.round(a.downloaded/a.total*100):0,C=u==="web",y=u==="mobile",k=n?.updateCommand||"pichamber update",D=I.version||n?.version,M=I.channel||n?.channel;Ae.useEffect(()=>{e||(p("idle"),m(null),x(null),v({}))},[e]);const B=async(P=k)=>{(await us(P)).ok&&(h(P),setTimeout(()=>h(null),2e3))},_=Ae.useCallback(async P=>{await ji(P)},[]),K=Ae.useCallback(async()=>{const P=qe();p("updating"),m(null),x(null),v({});const U=await Iu();if(qe()!==P)return;if(!U.success){p("error"),m(U.error||"Update failed"),x(U.commands??null);return}if(v({version:U.targetVersion,channel:U.channel}),U.jobId){const W=await Du(U.jobId,G=>{qe()===P&&p(G)},void 0,void 0,P);if(W.stale||qe()!==P)return;if(W.applied){window.location.reload();return}p("error"),m(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}p(U.autoRestart?"restarting":"reconnecting");const ne=await Ru(n?.currentVersion,void 0,void 0,P);if(!(ne.stale||qe()!==P)){if(ne.applied){window.location.reload();return}p("error"),m(ne.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),V=Ae.useCallback(()=>{_(j)},[_,j]),O=b!=="idle"&&b!=="error",T=Ae.useMemo(()=>{if(!n?.body)return null;const P=n.body.trim();if(!P)return null;const U=Tu(P);return U.length===0?{kind:"raw",title:"What's new",content:Ho(P)}:{kind:"sections",title:"What's new",sections:[...U].sort((W,G)=>Mu(W.version,G.version)).map(W=>({version:W.version,dateLabel:Eu(W.date),content:Ho(Pu(W.raw)||P)}))}},[n?.body]);return t.jsx(Yt,{open:e,onOpenChange:O?void 0:s,children:t.jsxs(qt,{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(es,{className:"flex items-center gap-2.5",children:[t.jsx(R,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||D)&&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&&D&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),D&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:D})]}),C&&M&&t.jsx("span",{className:"ml-3 typography-meta text-muted-foreground",children:M==="rc"?"RC subscription":"Stable subscription"})]}),t.jsxs("div",{className:"space-y-2",children:[C&&O&&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(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="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&&!O&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(xs,{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:P=>{const ne=P.target.closest("a");ne&&ne.href&&(P.preventDefault(),P.stopPropagation(),_(ne.href))},children:t.jsx(Po,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(P=>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",P.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:P.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:U=>{const W=U.target.closest("a");W&&W.href&&(U.preventDefault(),U.stopPropagation(),_(W.href))},children:t.jsx(Po,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})})]},P.version))})})}),(l||g)&&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||g})}),C&&b==="error"&&(w??[k]).length>0&&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(R,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:w?"Run these commands:":"Or update via terminal:"})]}),(w??[k]).map(P=>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:P}),t.jsx(Te,{variant:"ghost",size:"icon",onClick:()=>{B(P)},className:f===P?"text-[var(--status-success)]":void 0,title:f===P?"Copied!":"Copy command","aria-label":f===P?"Copied!":"Copy command",children:f===P?t.jsx(R,{name:"check",className:"h-4 w-4"}):t.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},P))]}),!C&&!y&&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:[N,"%"]})]}),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:`${N}%`}})})]})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:A,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(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!C&&!y&&!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(R,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!C&&!y&&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(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!C&&!y&&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(R,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),y&&t.jsxs(Te,{onClick:V,size:"default",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),C&&!O&&t.jsxs("button",{onClick:K,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(R,{name:"download",className:"h-4 w-4"}),"Update Now"]}),C&&O&&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(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Fu=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:$("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:$("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),gn=({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($e,{open:r,onOpenChange:o,children:[t.jsx(Ge,{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:$("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(R,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Ke,{sideOffset:8,className:$("max-w-sm",n),children:e})]})},fg="w-full min-w-40 max-w-48",hg="settings",Ou="w-full min-w-40 max-w-48",pg="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Lu="w-full max-w-[24rem]",mg="min-w-0 flex-1",gg="flex w-full min-w-0 items-center gap-2",bg="typography-meta shrink-0 text-muted-foreground tabular-nums",pa="space-y-3.5",Bu="space-y-1.5",xg="typography-settings-page-title text-muted-foreground",_u="typography-settings-section-title text-foreground",ma="typography-settings-group-title text-foreground",ro="typography-settings-field-label text-foreground",Uu="typography-settings-description text-muted-foreground",bn="typography-meta text-muted-foreground",yg="typography-meta font-medium text-foreground",vg="typography-settings-section-title text-foreground",zu=({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:$("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:_u,children:e}):e,n,r!=null?t.jsx(gn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Uu,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:$(d),children:a})]})},wg=({children:e,className:s})=>t.jsx("div",{className:$("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),$u=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:$(ma,s),children:e}),Sg=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:$("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($u,{children:e}),n!=null?t.jsx(gn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:bn,children:s}):null]}):null,t.jsx("div",{className:$(a),children:r})]}),cn=({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:bn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:$("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:ro,children:e}),n!=null?t.jsx(gn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:$("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},jg=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,labelClassName:l,controlClassName:c,alignEnd:d=!0})=>t.jsxs("div",{"data-settings-item":o,className:$("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",l),children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:ro,children:e}),n!=null?t.jsx(gn,{children:n}):null]}),s!=null?t.jsx("p",{className:$(bn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:$("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",d&&"@xl:justify-end",c),children:r})]}),Cg=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:$("pt-4",s),children:e}),Gu=({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:$("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:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[t.jsx(Nr,{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:ro,children:n}),d,u!=null?t.jsx(gn,{children:u}):null]}),h?t.jsx("span",{className:bn,children:r}):null]})]})},kg=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:$("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(Fu,{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:$("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:bn,children:r}):null]})]}),Ag=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:$(Bu,n),children:s});function Ng({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:$("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Te,{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))})}const Gr="pichamber:server-update-channel-changed",Ig=()=>{typeof window<"u"&&window.dispatchEvent(new Event(Gr))},Ku=e=>typeof window>"u"?()=>{}:(window.addEventListener(Gr,e),()=>window.removeEventListener(Gr,e));class Wu 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(nc,{className:"w-full max-w-md",children:[t.jsx(rc,{className:"text-center",children:t.jsxs(oc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(R,{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(Te,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(R,{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 Hu(e){return t.jsx(Wu,{...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 Rg=({active:e=!0})=>{const s=De(n=>n.currentSessionId);return t.jsx(Hu,{sessionId:s||void 0,children:t.jsx(ac,{active:e},s??"no-session")})};function Yu({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 ga=Ae.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,...b},p)=>{const g=Ae.useRef(null),m=Ae.useRef(null),[w,x]=Ae.useState(null),I=c??w,v=Ae.useCallback(j=>{const N=g.current;if(!N)return;m.current={startY:j.clientY,startHeight:N.getBoundingClientRect().height};const C=j.currentTarget;C.setPointerCapture(j.pointerId);const y=D=>{const M=m.current;if(!M)return;const B=M.startHeight+(D.clientY-M.startY),_=Math.max(82,B);d?d(_):x(_)},k=()=>{m.current=null,C.removeEventListener("pointermove",y),C.removeEventListener("pointerup",k),C.removeEventListener("pointercancel",k)};C.addEventListener("pointermove",y),C.addEventListener("pointerup",k),C.addEventListener("pointercancel",k),j.preventDefault()},[d]),A=Ae.useCallback(j=>{if(j.target.closest('textarea, button, [role="separator"]'))return;const C=g.current?.querySelector("textarea");C&&document.activeElement!==C&&(j.preventDefault(),C.focus())},[]);return f?t.jsx(xs,{as:"textarea",ref:p,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:$("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,...b}):t.jsx("div",{ref:g,onPointerDown:A,style:I!==null?{height:`${I}px`}:void 0,className:$("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:p,className:$("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,...b}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(Yu,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ga.displayName="Textarea";const ba=[{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"}],dn=Object.fromEntries(ba.map(e=>[e.key,e.Icon])),Kr="pichamber:project-actions-updated",xa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},Xt=(e,s)=>`${xa(e)}::${s}`,ya=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(zu,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Wr=e=>e.name.trim().length>0&&e.command.trim().length>0,qu=e=>e.name.trim().length===0&&e.command.trim().length===0,Qu=e=>!Wr(e)&&!qu(e),Vu=(e,s)=>e.some(r=>s.has(r.id)&&!Wr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Wr)},Ju=450,Xu=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Zu=()=>({id:Xu(),name:"",command:"",icon:"play"}),ef=({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 x=!1;return o(!0),(async()=>{try{const I=await Ir(e);if(x)return;n(I.actions),l(JSON.stringify({actions:I.actions})),d(new Set(I.actions.map(v=>v.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=i.useMemo(()=>Vu(s,c),[s,c]),h=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=a!==null&&f.canPersist&&h!==a,p=i.useCallback(async x=>await lc(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),d(new Set(x.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Kr,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!b||r||u.current)return;const x=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await p(f.actions)}finally{u.current=!1}})())},Ju);return()=>{window.clearTimeout(x)}},[b,r,p,f.actions]);const g=i.useCallback(()=>{const x=Zu();n(I=>[...I,x])},[]),m=i.useCallback(x=>{n(I=>I.filter(v=>v.id!==x))},[]),w=i.useCallback((x,I)=>{n(v=>v.map(A=>A.id===x?I(A):A))},[]);return t.jsx(ya,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Te,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:g,children:[t.jsx(R,{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:$("space-y-6",Lu),children:s.map((x,I)=>{const v=x.icon||"play",A=dn[v]||"play",j=x.name.trim()||`Action ${I+1}`,N=Qu(x);return t.jsxs("div",{className:pa,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:ma,children:j}),t.jsx(Te,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>m(x.id),"aria-label":`Delete ${j}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(cn,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(It,{children:[t.jsx(Rt,{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(R,{name:A,className:"h-4 w-4"})})}),t.jsx(Dt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:ba.map(C=>{const y=C.Icon,k=(x.icon||"play")===C.key;return t.jsx("button",{type:"button",onClick:()=>w(x.id,D=>({...D,icon:C.key})),className:$("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",k&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${C.label}`,children:t.jsx(R,{name:y,className:"h-4 w-4"})},C.key)})})})]}),t.jsx(fn,{value:x.name,onChange:C=>w(x.id,y=>({...y,name:C.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(cn,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ga,{value:x.command,onChange:C=>w(x.id,y=>({...y,command:C.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),N?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Gu,{checked:x.autoOpenUrl===!0,onChange:C=>w(x.id,y=>({...y,...C?{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 ${j}`}),x.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(cn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(fn,{value:x.openUrl||"",onChange:C=>w(x.id,y=>({...y,openUrl:C.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},tf={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)"},sf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Wt(y=>y.providers),d=Wt(y=>y.modelsMetadata),u=ce(y=>y.hiddenModels),f=ce(y=>y.isFavoriteModel),h=ce(y=>y.toggleFavoriteModel),b=ce(y=>y.reorderFavoriteModel),{favoriteModelsList:p,recentModelsList:g}=cc(),[m,w]=i.useState(!1),[x,I]=i.useState("");i.useEffect(()=>{m||I("")},[m]);const v=e?c.find(y=>y.id===e.providerId):void 0,A=e&&v?(Array.isArray(v.models)?v.models:[]).find(y=>y.id===e.modelId):void 0,j=e?dc(A,e.modelId):s,N=i.useMemo(()=>e?u.filter(y=>!(y.providerID===e.providerId&&y.modelID===e.modelId)):u,[u,e]),C=i.useCallback(y=>{l({providerId:y.providerID,modelId:y.modelID}),w(!1)},[l]);return t.jsxs(It,{modal:!1,open:m,onOpenChange:y=>{r||w(y)},children:[t.jsx(Rt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:$(Ci({size:"default"}),Ou,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(uc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:$("truncate",e?"text-foreground":"text-muted-foreground"),children:j})]}),t.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Dt,{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:p,recentModels:g,modelsMetadata:d,searchQuery:x,onSearchQueryChange:I,onSelect:C,labels:{...tf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:N,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),w(!1)},disabled:r,autoFocus:!0,onEscape:()=>w(!1),isFavorite:y=>f(y.providerID,y.modelID),onToggleFavorite:y=>h(y.providerID,y.modelID),onReorderFavorite:(y,k)=>b(y.providerID,y.modelID,k.providerID,k.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},dr="w-full max-w-none",nf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Wt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(ya,{title:"Project",divider:!1,children:t.jsxs("div",{className:pa,children:[t.jsx(cn,{label:"Name",settingsItem:"projects.name",controlClassName:dr,children:t.jsx(fn,{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(cn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:dr,children:t.jsx(sf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:dr,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},rf=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(()=>hc(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}},of=450,af=(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{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},of);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},lf=({project:e,onIdentitySave:s})=>{const n=rf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return af(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(nf,{form:n}),t.jsx(ef,{projectRef:r})]})};function oo({...e}){return t.jsx(Hi,{...e})}function io({...e}){return t.jsx(Yi,{...e})}function ao({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(qi,{children:t.jsx(Qi,{className:$("app-region-no-drag z-50",s),children:t.jsx(Vi,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:$(ki,e),...o,children:n})})})}function Os({className:e,...s}){return t.jsx(Ji,{className:$(Ai,e),...s})}function va({className:e,...s}){return t.jsx(Xi,{className:$(Ni,e),...s})}const Nn=100;function Dg(){const e=ce(y=>y.isArchivePageOpen),s=ce(y=>y.setArchivePageOpen),n=ce(y=>y.setActiveMainTab),r=De(y=>y.setCurrentSession),o=De(y=>y.unarchiveSession),a=Bs(y=>y.homeDirectory),l=Rr({archived:!0}),[c,d]=i.useState(""),[u,f]=i.useState(null),[h,b]=i.useState(Nn),p=c.trim().toLowerCase(),g=i.useMemo(()=>e?[...l].sort((y,k)=>(k.time?.archived??0)-(y.time?.archived??0)):[],[l,e]),m=i.useMemo(()=>{const y=new Map;for(const k of g){const D=ke(an(k))??"",M=y.get(D);if(M){M.sessions.push(k);continue}y.set(D,{directory:D,label:D?_s(D,a)||D:"other projects",sessions:[k]})}return[...y.values()].sort((k,D)=>D.sessions.length-k.sessions.length)},[a,g]),w=i.useMemo(()=>p?g.filter(y=>(y.title??"").toLowerCase().includes(p)):u===null?g:m.find(y=>y.directory===u)?.sessions??[],[m,p,u,g]),x=w.slice(0,h),I=w.length-x.length,v=l.length,A=i.useCallback(y=>{f(y),b(Nn)},[]),j=i.useCallback(y=>{const k=ke(an(y));r(y.id,k??void 0),n("chat"),s(!1)},[n,r,s]),N=i.useCallback(y=>{o(y.id).then(k=>{k?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const C=(y,k,D,M,B,_,K)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:B,title:_,className:$("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",K?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",M?"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:k}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:D})]}),K?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Ss.requestDelete({sessions:K,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 ${k}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},y);return t.jsx(Td,{open:e,onOpenChange:s,children:t.jsxs(Fd,{children:[t.jsx(Od,{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(Ld,{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(Bd,{className:"sr-only",children:"Archived sessions"}),t.jsx(_d,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Ud,{"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(R,{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:[C("__all__","All directories",v,u===null,()=>A(null)),m.map(y=>C(y.directory||"__none__",y.label,y.sessions.length,u===y.directory,()=>A(y.directory),y.directory||void 0,y.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(R,{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:y=>{d(y.target.value),b(Nn)},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:w.length===1?`${w.length} archived session`:`${w.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:[x.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:p?"No matching archived sessions":"No archived sessions"})}):x.map(y=>{const k=ke(an(y))??"",D=k?_s(k,a)||k: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:()=>j(y),role:"button",tabIndex:0,onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),j(y))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:ds(y)}),p&&D?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:k,children:D}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Cd(y.time?.archived??y.time?.updated??y.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),N(y)},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(y)}`,children:t.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),Ss.requestDelete({sessions:[y],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(y)}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},y.id)}),I>0?t.jsx("button",{type:"button",onClick:()=>b(y=>y+Nn),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 cf=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const s=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=s+n+r;if(o<=0)return{percent:0,hasInput:!1};const a=Math.max(0,n);return{percent:Math.min(100,Math.max(0,a/o*100)),hasInput:!0}},df=e=>{if(!e||typeof e!="object")return 0;const s=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return s+n+r},Ht=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,uf=e=>{if(!e||typeof e!="object")return null;const s=Ht(e.input),n=Ht(e.output),r=Ht(e.cacheRead),o=Ht(e.cacheWrite);return{input:s,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:s+n+r+o}},Yo=e=>{const s=uf(e.info.usage);if(s)return s;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Ht(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,a=Ht(o.input),l=Ht(o.output),c=Ht(o.reasoning),d=Ht(o.cache?.read),u=Ht(o.cache?.write);return{input:a,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:a+l+c+d+u}},wa=380,ur=8,ff=140;function hf({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:b}=Jr();return i.useLayoutEffect(()=>{if(!e||!b||!l)return;const p=()=>{const w=n.current?.getBoundingClientRect(),x=a.current?.getBoundingClientRect();if(!w||!x){h(null);return}const I=w.left-x.left;h(Math.min(Math.max(I,ur),Math.max(ur,x.width-wa-ur)))};p();const g=a.current;if(typeof ResizeObserver>"u"||!g)return;const m=new ResizeObserver(p);return m.observe(g),()=>m.disconnect()},[n,b,e,l]),i.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const p=window.setTimeout(()=>{c(!1),u(!1)},ff);return()=>window.clearTimeout(p)},[e,l]),i.useEffect(()=>{if(!e)return;const p=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[s,e]),i.useEffect(()=>{if(!e)return;const p=g=>{const m=g.target;if(!(m instanceof Node)){s();return}o.current?.contains(m)||n.current?.contains(m)||s()};return document.addEventListener("pointerdown",p,!0),r&&document.addEventListener("wheel",p,!0),()=>{document.removeEventListener("pointerdown",p,!0),r&&document.removeEventListener("wheel",p,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:b&&f!==null}}const qo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Kn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),In=({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(R,{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})]}),pf=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=hf({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:$("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(${wa}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(In,{iconNode:t.jsx(Ii,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:$("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(In,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Kn(r.cacheRead)})}),t.jsx(In,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Kn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(In,{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},mf=i.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:a}){const l=i.useRef(null),c=pc(r??""),d=Wt(O=>O.providers),u=Wt(O=>O.currentProviderId),f=Wt(O=>O.currentModelId),h=Wt(O=>O.getCurrentModel()),b=Wt(O=>O.getModelMetadata);Wt(O=>O.modelsMetadata.size);const p=mc(i.useCallback(O=>r?O.sessionModelSelections.get(r)??null:null,[r])),g=i.useMemo(()=>{for(let O=c.length-1;O>=0;O-=1){const T=c[O]?.info;if(T.role!=="user")continue;const P=T.model,U=P?.providerID??P?.providerId,ne=P?.modelID??P?.modelId,W=typeof U=="string"&&U.trim().length>0?U:void 0,G=typeof ne=="string"&&ne.trim().length>0?ne:void 0;if(W&&G)return{providerID:W,modelID:G}}return null},[c]),m=i.useMemo(()=>{for(let O=c.length-1;O>=0;O-=1){const T=c[O];if(T?.info.role==="assistant"&&Yo(T).total>0)return T}return null},[c]),w=g??(()=>{const O=m?.info.model,T=O?.providerID??O?.providerId,P=O?.modelID??O?.modelId;return T&&P?{providerID:T,modelID:P}:null})()??(p?{providerID:p.providerId,modelID:p.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),I=(w?d.find(O=>O.id===w.providerID):void 0)?.models.find(O=>O.id===w?.modelID),v=w?b(w.providerID,w.modelID):void 0,A=qo(I?.limit,"context")??v?.limit?.context??qo(h?.limit,"context")??0,j=m?Yo(m):null,N=m?.info?.usage,C=N?df(N):j?.total??0,y=!a&&C>0&&A>0?Math.min(C/A*100,999):null,k=y!==null?`${Kn(C)}/${Kn(A)}`:null,D=y===null?"":y>=90?"text-[var(--status-error)]":y>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",M=j?.cacheRead??null,B=j?.cacheWrite??null,_=j?cf({input:j.input,cache:{read:j.cacheRead,write:j.cacheWrite}}):{percent:0,hasInput:!1},K=_.hasInput?_.percent:null,V=y!==null&&k?{percentage:y,tokens:k,colorClass:D,cacheRead:M,cacheWrite:B,cacheHitPercent:K}: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(O=>!O),style:{touchAction:"manipulation"},children:t.jsx(Ii,{percentage:V?.percentage??0,size:20,className:"size-5 -rotate-90"})}),t.jsx(pf,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:V})]})}),Ws="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",gf="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",bf=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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:$(a??Ws,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Ke,{children:t.jsx("p",{children:n})})]}):null}),Sa=({variant:e="desktop"})=>{const s=js(f=>f.entries),[n,r]=i.useState(!1),o=i.useRef(null),a=i.useMemo(()=>[...s.values()].sort((f,h)=>h.startedAt-f.startedAt),[s]),l=a.filter(f=>f.state&&f.state.phase!=="failed").length,c=i.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=i.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(i.useEffect(()=>()=>c(),[c]),a.length===0)return null;const u=f=>{const h=f.receipt;if(!h)return;const b=De.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:h.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:h.path}),js.getState().clearEntry(f.key),ce.getState().setActiveMainTab("chat"),r(!1)};return t.jsxs(It,{open:n,onOpenChange:r,children:[t.jsx(Rt,{asChild:!0,children:t.jsxs("button",{type:"button",className:$(e==="desktop"?Ws:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&d()},children:[l>0?t.jsx(As,{variant:"inline",text:null,animationType:"spinner"}):t.jsx(R,{name:"task",className:"size-[18px]"}),t.jsx("span",{children:"Background tasks"})]})}),t.jsxs(Dt,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:d,children:[t.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[t.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:l===1?"1 worktree is being created":`${l} worktrees are being created`})]}),t.jsx("div",{className:"divide-y divide-border",children:a.map(f=>t.jsx(xf,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},xf=({entry:e,onOpen:s})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=!!(e.receipt&&!e.state),a=n?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return t.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[t.jsx("div",{className:"mt-0.5 shrink-0",children:r?t.jsx(As,{variant:"inline",text:null,animationType:"spinner"}):n?t.jsx(R,{name:"alert",className:"size-4 text-[var(--status-error)]"}):t.jsx(R,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),t.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:n?e.state?.error:e.path??e.intent.sourceDirectory})]}),n?t.jsx(Te,{type:"button",variant:"ghost",size:"xs",onClick:()=>js.getState().dismissFailed(e.key),children:"Dismiss"}):null,o?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Te,{type:"button",size:"xs",onClick:s,children:"Open"}),t.jsx(Te,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>js.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:t.jsx(R,{name:"close",className:"size-3.5"})})]}):null]})},yf=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:a,unresolvedWorktreeProjectPaths:l,foldersMap:c,createFolder:d,addSessionToFolder:u}=e;i.useEffect(()=>{!n||!o||a||s.forEach(f=>{if(l.has(f.normalizedPath))return;const h=Gi(f.normalizedPath),b=r.archivedSessionsByProject.get(f.id)??[],p=c[h]??[],g=new Map(p.map(m=>[m.name.toLowerCase(),m]));b.forEach(m=>{const w=kd(m,f.normalizedPath),x=w.toLowerCase();let I=g.get(x);I||(I=d(h,w),g.set(x,I)),I.sessionIds.includes(m.id)||u(h,I.id,m.id)})})},[s,n,r,o,a,l,c,d,u])},vf=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])}),wf=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:b,foldersMap:p}=e,g=i.useRef(new Map),m=i.useMemo(()=>{const C=g.current,y=new Map;let k=0,D=0;const M=(_,K)=>_.length===K.length&&_.every((V,O)=>V===K[O]),B=s.map(_=>{const K=n(_.id),V=r(_.id),O=a.has(_.id)?!!a.get(_.id):c,T=l.get(_.id)??null,P=o.get(_.normalizedPath)??[],U=C.get(_.id);if(U&&U.project===_&&M(U.activeSessions,K)&&M(U.archivedSessions,V)&&U.rootBranch===T&&U.isRepo===O&&U.worktrees===P&&U.buildGroupedSessions===d)return k+=1,y.set(_.id,U),U.section;D+=1;const ne=Ki([...K,...V]),W=d(ne,_.normalizedPath,P,T,O),G={project:_,groups:W};return y.set(_.id,{project:_,activeSessions:K,archivedSessions:V,rootBranch:T,isRepo:O,worktrees:P,buildGroupedSessions:d,section:G}),G});return g.current=y,k>0&&_t("ui.sidebar.project_section.reused",k),D>0&&_t("ui.sidebar.project_section.rebuilt",D),B},[s,n,r,o,a,c,d,l]),w=i.useMemo(()=>m,[m]),x=i.useMemo(()=>{const C=new WeakMap;if(!u)return C;const y=k=>k.reduce((D,M)=>D+1+y(M.children),0);return w.forEach(k=>{k.groups.forEach(D=>{const M=h(D.sessions,f),B=y(M),_=b(D).includes(f),K=ke(D.directory??null),O=(K?p[K]??[]:[]).filter(T=>T.name.toLowerCase().includes(f)).length;C.set(D,{filteredNodes:M,matchedSessionCount:B,folderNameMatchCount:O,groupMatches:_,hasMatch:_||B>0||O>0})})}),C},[u,w,h,f,b,p]),I=i.useMemo(()=>u?w.map(C=>({...C,groups:C.groups.filter(y=>x.get(y)?.hasMatch===!0)})).filter(C=>C.groups.length>0):w,[u,w,x]),v=u?I:w,A=i.useRef(new WeakMap),j=i.useMemo(()=>{const C=A.current;return v.map(y=>{const k=C.get(y);if(k&&k.query===f)return k.section;const D=y.groups.filter(T=>!T.isArchivedBucket),M=y.groups.filter(T=>T.isArchivedBucket),B=D.flatMap(T=>u?x.get(T)?.filteredNodes??[]:T.sessions),_=D.map(T=>({scopeKey:T.folderScopeKey??ke(T.directory??null),directory:T.directory??null})).filter(T=>!!T.scopeKey),K=D.find(T=>T.isMain)??null,V={id:"flat",label:K?.label??"",branch:K?.branch??null,description:K?.description??null,isMain:!0,isArchivedBucket:!1,directory:K?.directory??y.project.normalizedPath,folderScopeKey:K?.folderScopeKey??y.project.normalizedPath,folderScopes:_,sessions:B};if(u){const T=D.map(P=>x.get(P)).filter(P=>!!P);x.set(V,{filteredNodes:B,matchedSessionCount:T.reduce((P,U)=>P+U.matchedSessionCount,0),folderNameMatchCount:T.reduce((P,U)=>P+U.folderNameMatchCount,0),groupMatches:T.some(P=>P.groupMatches),hasMatch:T.some(P=>P.hasMatch)})}const O={project:y.project,groups:[V,...M]};return C.set(y,{query:f,section:O}),O})},[x,u,f,v]),N=i.useMemo(()=>u?v.reduce((C,y)=>C+y.groups.reduce((k,D)=>{const M=x.get(D);if(!M)return k;const B=M.folderNameMatchCount+(M.groupMatches?1:0);return k+M.matchedSessionCount+B},0),0):0,[u,v,x]);return{projectSections:m,visibleProjectSections:w,groupSearchDataByGroup:x,searchableProjectSections:I,sectionsForRender:v,flatSectionsForRender:j,searchMatchCount:N}},Sf=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,b=i.useMemo(()=>{const g=new Map,m=new Map,w=(x,I,v,A)=>{g.has(x)||g.set(x,new Map);const j=g.get(x);A.forEach(N=>{const C=ke(N.session.directory??v??I);j.set(N.session.id,{directory:C}),m.has(x)||m.set(x,{id:N.session.id,directory:C}),N.children.length>0&&w(x,I,C,N.children)})};return s.forEach(x=>{x.groups.forEach(I=>{w(x.project.id,x.project.normalizedPath,I.directory,I.sessions)})}),{metaByProject:g,firstSessionByProject:m}},[s]),p=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){p.current=n;return}if(p.current===n)return;const g=s.find(N=>N.project.id===n);if(!g)return;p.current=n;const m=b.metaByProject.get(n);if(a&&m&&m.has(a)){o(N=>{if(N.get(n)===a)return N;const C=new Map(N);return C.set(n,a),C});return}const w=a?Array.from(b.metaByProject.entries()).some(([N,C])=>N!==n&&C.has(a)):!1;if(a&&m&&!w)return;if(!m||m.size===0){f("chat"),d&&h(!1),u({selectedProjectId:g.project.id,directoryOverride:g.project.normalizedPath});return}const x=r.get(n),I=x&&m.has(x)?x:null,v=b.firstSessionByProject.get(n)?.id??null,A=I??v;if(!A||A===a)return;const j=m.get(A)?.directory??null;l(A,j,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,b,f,h,o]),i.useEffect(()=>{if(!n||!a)return;const g=b.metaByProject.get(n);!g||!g.has(a)||o(m=>{if(m.get(n)===a)return m;const w=new Map(m);return w.set(n,a),w})},[n,a,b,o])},jf=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=De(c=>c.currentSessionId),o=De(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return Sf({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},Qo=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Cf=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},kf=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,ja=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=Cf(e.trim())%Qo.length;return Qo[s]},Af=(e,s)=>{const n=ja(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Vo=e=>!!e.time?.archived,Nf=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=ke(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=ke(l??null),h=Ki(a).sort((C,y)=>Xr(C,y,e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(h.map(C=>[C.id,C])),p=new Map,g=new Map;h.forEach(C=>{const y=C.parentID??null,k=y?b.get(y):null,D=k&&Vo(k)===Vo(C)?y:null;p.set(C.id,D),D&&g.set(D,(g.get(D)??0)+1)});const m=c.map(C=>({worktree:C,directory:ke(C.path)})).filter(C=>!!C.directory&&!C.worktree.isPrimary).sort((C,y)=>y.directory.length-C.directory.length),w=(C,y)=>y===C||y.startsWith(`${C}/`),x=C=>{const y=ke(C.directory??null);return y?m.find(k=>w(k.directory,y))?.worktree??null:null},I=(C,y)=>{const k=kf(C.id,p,g);return{session:C,children:[],worktree:y,forkColorId:k}},v=[],A=new Map,j=[];for(const C of m)A.set(C.directory,[]);h.forEach(C=>{const y=x(C),k=I(C,y);C.time?.archived?j.push(k):y?A.get(ke(y.path)??"")?.push(k):v.push(k)});const N=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?Oo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:v}];for(const{worktree:C,directory:y}of m)N.push({id:`worktree:${y}`,label:C.branch||(C.detached?"Detached HEAD":C.name),branch:C.branch,description:Oo(y,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:C,directory:y,folderScopeKey:y,sessions:A.get(y)??[]});return j.length>0&&N.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?Gi(f):null,sessions:j}),N},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},If=({mobileVariant:e,isTablet:s})=>!e&&!s,Rf=({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])},Df=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((v,A,j)=>{Er("navigation.session_select"),ce.getState().closeMainSurfaces();const N=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},C=j?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===De.getState().currentSessionId){e.allowReselect&&C&&e.onSessionSelected?.(v),N();return}Er("navigation.session_state_set"),e.setCurrentSession(v,A??null),C&&e.onSessionSelected?.(v),N()},[e]),a=i.useCallback((v,A)=>{e.setEditingId(v),e.setEditTitle(A)},[e]),l=i.useCallback(async v=>{if(!e.editingId)return;const A=(v??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=i.useCallback(async(v,A)=>{try{return(await us(v)).ok?(n(A),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 A=await e.shareSession(v.id);if(!A?.share?.url){oe.error("Unable to share session");return}const j=await d(A.share.url,v.id);oe[j?"success":"warning"]("Session shared",{description:j?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=i.useCallback((v,A)=>{d(v,A).then(j=>{j||oe.error("Failed to copy URL")})},[d]),h=i.useCallback(v=>{us(v).then(A=>{if(A.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),b=i.useCallback(async v=>{await e.unshareSession(v)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),p=i.useCallback(v=>{const A=[],j=N=>{(e.childrenMap.get(N)??[]).forEach(y=>{A.push(y),j(y.id)})};return j(v),A},[e.childrenMap]),g=i.useCallback((v,A)=>A?v:v.filter(j=>!j.time?.archived),[]),m=i.useCallback(async(v,A,j)=>{const N=A?.archivedBucket===!0||A?.hardDelete===!0,C=j?.descendantIds??g(p(v.id),N).map(M=>M.id);if(C.length===0){(N?await e.deleteSession(v.id):await e.archiveSession(v.id))?oe.success(N?"Session deleted":"Session archived"):oe.error(N?"Failed to delete session":"Failed to archive session");return}const y=[v.id,...C];if(N){const{deletedIds:M,failedIds:B}=await e.deleteSessions(y);if(B.length===0){const _=M.length;oe.success(_===1?`Deleted ${_} session`:`Deleted ${_} sessions`)}else oe.error("Failed to delete session");return}const{archivedIds:k,failedIds:D}=await e.archiveSessions(y);k.length>0&&oe.success(k.length===1?`Archived ${k.length} session`:`Archived ${k.length} sessions`),D.length>0&&oe.error(D.length===1?`Failed to archive ${D.length} session`:`Failed to archive ${D.length} sessions`)},[e,p,g]),w=i.useCallback((v,A)=>{const j=A?.archivedBucket===!0||A?.hardDelete===!0,N=g(p(v.id),j).map(C=>C.id);if(!e.showDeletionDialog||A?.skipConfirm===!0){m(v,A,{descendantIds:N});return}e.setDeleteSessionConfirm({session:v,descendantCount:N.length,descendantIds:N,archivedBucket:j})},[e,p,m,g]),x=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,archivedBucket:A,descendantIds:j}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await m(v,{archivedBucket:A},{descendantIds:j})},[e,m]),I=i.useCallback(async v=>{await e.unarchiveSession(v.id)?oe.success("Session restored"):oe.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:h,handleUnshareSession:b,handleDeleteSession:w,handleRestoreSession:I,confirmDeleteSession:x}},Ef=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:b}=pt.getState(),p=b.map(g=>({...g,sidebarCollapsed:h.has(g.id)}));Zr({projects:p}).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 p=JSON.parse(h);Array.isArray(p)&&a(new Set(p.filter(g=>typeof g=="string")))}const b=s.getItem(n.projectCollapse);if(b){const p=JSON.parse(b);Array.isArray(p)&&l(new Set(p.filter(g=>typeof g=="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}},Pf=3;let Wn=0;const Ca=[],Mf=()=>Wn<Pf?(Wn+=1,Promise.resolve()):new Promise(e=>{Ca.push(e)}),Tf=()=>{const e=Ca.shift();if(e){e();return}Wn=Math.max(0,Wn-1)},Ff=async e=>{await Mf();try{return await e()}finally{Tf()}},Of=5*6e4,Lf=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=Gs(),c=Ri(h=>h.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(h=>{Ff(()=>c(h.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const h=new Map;s.forEach(b=>{h.set(b.id,r.get(b.normalizedPath)?.isGitRepo??null)}),o(h)},[n,s,r,o]);const d=i.useMemo(()=>s.map(h=>{const b=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${b}`}).join("|"),[s,r]),u=i.useRef(new Map),f=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let h=!1;const b=setTimeout(()=>{(async()=>{const g=new Set(s.map(v=>v.id));for(const v of u.current.keys())g.has(v)||(u.current.delete(v),f.current.delete(v));const m=Date.now();if(s.filter(v=>{const A=r.get(v.normalizedPath);if(A?.isGitRepo===!1)return u.current.delete(v.id),f.current.delete(v.id),!1;if(A?.isGitRepo!==!0||A.branch===null)return!1;const j=A.branch.trim(),N=`${v.normalizedPath}\0${j}`,C=u.current.get(v.id);if(C===N){const y=f.current.get(v.id);return y&&(y.at=m),!1}return!(C!==void 0&&m-(f.current.get(v.id)?.at??0)<Of)}).length===0)return;const x=[];if(s.forEach(v=>{const A=r.get(v.normalizedPath)?.branch?.trim()??"",j=`${v.normalizedPath}\0${A}`;A&&x.push({id:v.id,inputKey:j,branch:A})}),h||x.length===0)return;const I=Date.now();a(v=>{const A=new Map(v);return x.forEach(({id:j,branch:N})=>{N&&A.set(j,N)}),A}),x.forEach(({id:v,inputKey:A,branch:j})=>{u.current.set(v,A),j&&f.current.set(v,{branch:j,at:I})})})()},150);return()=>{h=!0,clearTimeout(b)}},[n,s,d,r,a])},Bf=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}},_f=e=>{const s=new Map;for(const n of e){const r=an(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Uf=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},zf=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=eo(),l=_f(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const d of Uf(c,l))Ms().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:a,identities:l}},[s,n,r])},$f=(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,Jo=(e,s,n)=>{$f(e.get(s),n)&&e.set(s,n)},ka=e=>{const s=e;return ke(s.directory)??ke(s.project?.worktree)},Gf=(e,s,n)=>{if(e.time?.archived)return!0;const r=ka(e);if(!r)return n?.allowUnknownDirectory??!0;if(Vn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const a of s)if(ke(a)?.toLowerCase()===o)return!0;return!1},Kf=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)},Wf=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const p of s){const g=ke(p.normalizedPath);if(!g)continue;const m=a.get(g);(!m||p.id.localeCompare(m.id)<0)&&a.set(g,p),Jo(o,g,{projectId:p.id,projectRoot:g,scopeDirectory:g,kind:"project"})}if(n)for(const[p,g]of n){const m=ke(p),w=m?a.get(m):void 0;if(!(!w||!m))for(const x of g||[]){const I=ke(x?.path);I&&Jo(o,I,{projectId:w.id,projectRoot:m,scopeDirectory:I,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,f=new Map,h=p=>{if(!p)return null;if(l.has(p))return l.get(p)??null;const g=[];let m=p,w=null;for(;m;){if(l.has(m)){w=l.get(m)??null;break}if(g.push(m),w=o.get(m)??null,w)break;m=Kf(m)}for(const x of g)l.set(x,w);return w},b=(p,g,m)=>{for(const w of p){const x=ka(w);if(Vn(x))continue;const I=h(x);if(!I)continue;c.set(w.id,I);const v=g.get(I.projectId);if(v?v.push(w):g.set(I.projectId,[w]),!m)continue;const A=m.get(I.scopeDirectory);A?A.add(w.id):m.set(I.scopeDirectory,new Set([w.id]))}};return b(e,d,f),b(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:l.size}};function Aa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:$("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:$("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(As,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Hf=({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:b,mobileVariant:p=!1,alwaysShowActions:g=p,isRenaming:m=!1,renameDraft:w="",onRenameDraftChange:x,onRenameSave:I,onRenameCancel:v,droppableRef:A,isDropTarget:j=!1,onNewSession:N,depth:C=0,hideActions:y=!1,archivedBucket:k=!1})=>{const[D,M]=i.useState(!1),[B,_]=i.useState(""),K=i.useRef(null),V=m||D,O=m?w:B,T=i.useCallback(()=>{_(e.name),M(!0)},[e.name]),P=i.useCallback(()=>{const G=O.trim();G&&G!==e.name&&c(G),m&&I&&I(),M(!1),_("")},[O,e.name,m,c,I]),U=i.useCallback(()=>{m&&v&&v(),M(!1),_("")},[m,v]),ne=i.useCallback(G=>{m&&x?x(G):_(G)},[m,x]);i.useEffect(()=>{if(!m)return;const G=()=>{const Fe=K.current;Fe&&(Fe.focus(),Fe.select())},Ne=requestAnimationFrame(G),ee=window.setTimeout(G,0);return()=>{cancelAnimationFrame(Ne),window.clearTimeout(ee)}},[m]);const W=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:A,className:$("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",j&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:V?void 0:G=>{G.currentTarget.blur(),l()},role:V?void 0:"button",tabIndex:V?void 0:0,onKeyDown:V?void 0:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:$("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",k?g?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":g?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(R,{name:W,className:$(Tn,j?"text-primary":"text-muted-foreground")}),V?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),onSubmit:G=>{G.preventDefault(),P()},children:[t.jsx("input",{ref:K,value:O,onChange:G=>ne(G.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:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),onKeyDown:G=>{if(G.key==="Escape"){G.stopPropagation(),U();return}(G.key===" "||G.key==="Enter")&&G.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:G=>G.stopPropagation(),onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),children:t.jsx(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),U()},onPointerDown:G=>G.stopPropagation(),onMouseDown:G=>G.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("span",{className:$(Wi,j?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(Ke,{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(Aa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(R,{name:"arrow-right-s",className:$(Tn,"text-muted-foreground")}):t.jsx(R,{name:"arrow-down-s",className:$(Tn,"text-muted-foreground")})]})]}),!V&&(!y||k)?t.jsx("div",{className:$("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",g?"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:[!k&&N?t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),N()},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(R,{name:"add",className:"size-4"})}):null,k?null:t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),T()},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(R,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:G=>{G.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":k?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(R,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(G=>t.jsx(i.Fragment,{children:u(G,0,h??null,b??null,k,void 0,"project",f?.(G))},G.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Yf=i.memo(Hf),qf=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=Gd({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})},Qf=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Kd({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},Vf=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=Zi(Br(zd,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,d]=i.useState("Session"),[u,f]=i.useState(null),[h,b]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const p=g=>{l(null),f(null),b(null);const{active:m,over:w}=g;if(!w)return;const x=m.data.current,I=w.data.current;x?.type==="session"&&x.sessionId&&I?.type==="folder"&&I.folderId&&n(x.sessionId,I.folderId)};return t.jsxs(ea,{sensors:o,collisionDetection:ta,onDragStart:g=>{const m=g.active.data.current;if(m?.type==="session"&&m.sessionId){l(m.sessionId),d(m.sessionTitle??"Session");const w=g.active.rect.current.initial?.width,x=g.active.rect.current.initial?.height;f(typeof w=="number"?w:null),b(typeof x=="number"?x:null)}},onDragCancel:()=>{l(null),f(null),b(null)},onDragEnd:p,children:[r,t.jsx($d,{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(R,{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})]})},ws=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:$(o?Ad:Nd,r),children:[t.jsx(R,{name:e,className:$(hn(o),"text-muted-foreground")}),t.jsx("span",{className:$(pn(o),"flex-1 text-muted-foreground"),children:s})]}),Xo=(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)},Zt=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(Zt(n,s))return!0;return!1},Jf=(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})},Zo=new WeakMap;let ei=1;const Xf=e=>{const s=Zo.get(e);if(s!==void 0)return s;const n=ei;return ei+=1,Zo.set(e,n),n},Hr=e=>e.children.length===0?"":e.children.map(n=>{const r=Xf(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Hr(n)}`}).join("|"),Na=(e,s,n,r,o,a)=>{const l=eo(),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,b=Mo(l,f??"",d.session.id),p=Mo(l,h??"",u.session.id);return(b?n.has(b):!1)!==(p?r.has(p):!1)?!0:d.children.some((g,m)=>c(g,u.children[m]))};return c(e,s)},Hn=(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},Ia=(e,s)=>"",Zf=Ks(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),Ra=e=>null,lo=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Da=(e,s,n)=>{if(s.has(e.session.id))return"active";let r=n.has(e.session.id)?"unread":null;for(const o of e.children)if(r=lo(r,Da(o,s,n)),r==="active")return r;return r},Ea=(e,s,n)=>{let r=null;for(const o of e)if(r=lo(r,Da(o,s,n)),r==="active")return r;return r},eh=50,th=28;function sh({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),[b,p]=i.useState(0),[,g]=i.useState(0);i.useEffect(()=>{if(!s)return;const x=u.current;if(!x||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>g(v=>v+1));return I.observe(x),()=>I.disconnect()},[s]),i.useLayoutEffect(()=>{if(!s){f!==null&&h(null),b!==0&&p(0);return}const x=u.current;if(!x)return;let I=f;const v=r?.current??null;if(v&&v.contains(x)){if(I=v,I!==f){h(I);return}}else if(!I||!I.contains(x)){let j=x.parentElement;for(;j;){const N=window.getComputedStyle(j);if(N.overflowY==="auto"||N.overflowY==="scroll"){I=j;break}j=j.parentElement}if(I!==f){h(I);return}}if(!I)return;const A=x.getBoundingClientRect().top-I.getBoundingClientRect().top+I.scrollTop;p(j=>Math.abs(j-A)<1?j:A)},[f,b,r,s]);const m=s&&f!==null,w=Yd({count:e.length,enabled:m,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>th,overscan:n?20:8,scrollMargin:b,getItemKey:x=>e[x]?.session.id??x});return t.jsx("div",{ref:u,children:s?t.jsx("div",{style:{height:w.getTotalSize(),position:"relative"},children:w.getVirtualItems().map(x=>{const I=e[x.index];return I?t.jsx("div",{"data-index":x.index,ref:w.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${x.start-b}px)`},children:c(I,0,o,a,l,void 0,"project",d(I))},I.session.id):null})}):e.map(x=>t.jsx(i.Fragment,{children:c(x,0,o,a,l,void 0,"project",d(x))},x.session.id))})}const On=(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 nh({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:b,allGroupSessions:p,projectId:g,activeProjectId:m,setActiveProjectIdOnly:w,setActiveMainTab:x,mobileVariant:I,setSessionSwitcherOpen:v,openNewSessionDraft:A}){return t.jsxs("div",{className:$("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:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),r(s))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[t.jsx("div",{ref:c?.setActivatorNodeRef,className:$("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(R,{name:"archive",className:$("size-4 shrink-0 text-muted-foreground",a?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:$("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(R,{name:"arrow-right-s",className:"size-4"}):t.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:On(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(R,{name:"git-branch",className:$("size-4 shrink-0",!d&&"text-muted-foreground",a?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),t.jsx("span",{className:$("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(R,{name:"arrow-right-s",className:"size-4"}):t.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:On(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:On(e.label,o)}),f]})}),h&&b?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?t.jsx(R,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(R,{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:b.label})]}):null]})}),e.isArchivedBucket&&p.length>0?t.jsx("div",{className:$("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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),Ss.requestDelete({sessions:p,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(R,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?t.jsx("div",{className:$("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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),g&&g!==m&&w(g),x("chat"),I&&v(!1),A({selectedProjectId:g,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(R,{name:"add",className:"h-4 w-4"})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]})}const Rn=(e,s)=>s?e.sessions.some(n=>Zt(n,s)):!1,rh=(e,s,n)=>e.sessions.some(r=>Na(r,r,s,n,e.directory,e.directory)),oh=(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)},ti=(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)},ih=(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)},ah=(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&&rh(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&ih(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&oh(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(Rn(e.group,e.editingId)||Rn(s.group,s.editingId))||e.editTitle!==s.editTitle&&(Rn(e.group,e.editingId)||Rn(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Hn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Hn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&ti(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&ti(s.group,e.unreadActivitySessionIds,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 lh({group:e,sourceGroupNodes:s,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:a,unreadActivitySessionIds:l,collectGroupSessions:c}){const d=ht(j=>j.foldersMap),u=e.folderScopeKey??ke(e.directory??null),f=i.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),h=i.useMemo(()=>f.flatMap(({scopeKey:j,directory:N})=>(d[j]??[]).map(C=>({folder:C,scopeKey:j,scopeDirectory:N}))),[f,d]),b=i.useMemo(()=>{const j=new Map,N=C=>{C.forEach(y=>{j.set(y.session.id,y),y.children.length>0&&N(y.children)})};return N(s),j},[s]),p=i.useMemo(()=>h.map(({folder:j,scopeKey:N,scopeDirectory:C})=>{const y=Jf(j.sessionIds,b).sort(o);return{folder:j,scopeKey:N,scopeDirectory:C,nodes:y}}),[h,b,o]),g=i.useMemo(()=>{const j=new Map(p.map(k=>[k.folder.id,k])),N=new Map;for(const{folder:k}of p){if(!k.parentId)continue;const D=N.get(k.parentId);D?D.push(k.id):N.set(k.parentId,[k.id])}const C=new Map,y=k=>{const D=C.get(k);if(D!==void 0)return D;const M=j.get(k);if(!M)return C.set(k,!1),!1;const B=N.get(k)??[];if(e.isArchivedBucket&&M.nodes.length===0){const V=B.some(O=>y(O));return C.set(k,V),V}if(!n||M.folder.name.toLowerCase().includes(r)||M.nodes.length>0)return C.set(k,!0),!0;const K=B.some(V=>y(V));return C.set(k,K),K};return p.filter(({folder:k})=>y(k.id))},[p,e.isArchivedBucket,n,r]),m=i.useMemo(()=>new Set(g.flatMap(j=>j.folder.sessionIds)),[g]),w=i.useMemo(()=>s.filter(j=>!m.has(j.session.id)),[s,m]),x=i.useMemo(()=>g.filter(({folder:j})=>!j.parentId),[g]),I=i.useMemo(()=>{const j=new Map;return g.forEach(N=>{if(!N.folder.parentId)return;const C=j.get(N.folder.parentId)??[];C.push(N),j.set(N.folder.parentId,C)}),j},[g]),v=i.useMemo(()=>{const j=new Map(g.map(y=>[y.folder.id,y])),N=new Map,C=(y,k)=>{const D=N.get(y);if(D!==void 0)return D;if(k.has(y))return null;k.add(y);const M=j.get(y);let B=M?Ea(M.nodes,a,l):null;for(const _ of I.get(y)??[])if(B=lo(B,C(_.folder.id,k)),B==="active")break;return N.set(y,B),B};return g.forEach(({folder:y})=>C(y.id,new Set)),N},[a,g,I,l]),A=i.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const j=new Map,N=new Map;for(const{folder:y}of g){if(!y.parentId)continue;const k=N.get(y.parentId)??[];k.push(y.id),N.set(y.parentId,k)}const C=(y,k)=>{if(k.has(y))return[];k.add(y);const D=g.find(({folder:_})=>_.id===y),M=D?c(D.nodes):[],B=N.get(y)??[];for(const _ of B)M.push(...C(_,k));return M};for(const{folder:y}of g)j.set(y.id,C(y.id,new Set));return j},[g,c,e.isArchivedBucket]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:g,rootFolders:x,ungroupedSessions:w,folderActivityStateById:v,folderSessionsForDeleteById:A}}function ch(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:b,renameFolder:p,deleteFolder:g,showDeletionDialog:m,setDeleteFolderConfirm:w,renderSessionNode:x,showMoreGroupSessions:I,resetGroupSessionLimit:v,mobileVariant:A,alwaysShowActions:j,activeProjectId:N,setActiveProjectIdOnly:C,setActiveMainTab:y,setSessionSwitcherOpen:k,openNewSessionDraft:D,addSessionToFolder:M,createFolderAndStartRename:B,renamingFolderId:_,renameFolderDraft:K,setRenameFolderDraft:V,setRenamingFolderId:O,pinnedSessionIds:T,expandedParents:P,sessionOrderIndex:U,editingId:ne,openSidebarMenuKey:W,activeActivitySessionIds:G,unreadActivitySessionIds:Ne,onToggleCollapsedGroup:ee,dragHandleProps:Fe,compactBodyPadding:_e=!1,scrollContainerRef:q}=e,F=i.useCallback((ve,Oe)=>{const xe=U.get(ve.session.id),Me=U.get(Oe.session.id);if(xe!==void 0||Me!==void 0){if(xe===void 0)return 1;if(Me===void 0)return-1;if(xe!==Me)return xe-Me}return Xr(ve.session,Oe.session,T,Di)},[T,U]),z=a?c.get(s):null,Q=a?!1:u.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const ve=ke(s.directory??null),Oe=s.branch?.trim();return ve&&Oe?Ia():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const se=Ra(),Se=void 0,ge=f?10:5,we=Math.max(ge,d??ge),re=a?z?.groupMatches===!0:!1,ae=a,H=i.useMemo(()=>[...ae?z?.filteredNodes??[]:s.sessions].sort(F),[F,s.sessions,z?.filteredNodes,ae]),me=i.useCallback(ve=>{const Oe=[],xe=Me=>{Me.forEach(Ye=>{Oe.push(Ye.session),Ye.children.length>0&&xe(Ye.children)})};return xe(ve),Oe},[]),{folderScopeKey:Ue,folderScopes:L,allFoldersForGroup:X,rootFolders:ue,ungroupedSessions:fe,folderActivityStateById:je,folderSessionsForDeleteById:Re}=lh({group:s,sourceGroupNodes:H,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,compareSessionNodes:F,activeActivitySessionIds:G,unreadActivitySessionIds:Ne,collectGroupSessions:me}),be="project",Z=i.useMemo(()=>{const ve=new Set;return Xo(H,ne,ve),X.forEach(({nodes:Oe})=>{Xo(Oe,ne,ve)}),ve},[H,X,ne]),pe=i.useMemo(()=>{if(!W)return null;const ve=Hn(H,W,be,!!s.isArchivedBucket);if(ve)return ve;for(const{nodes:Oe}of X){const xe=Hn(Oe,W,be,!!s.isArchivedBucket);if(xe)return xe}return null},[W,H,X,s.isArchivedBucket]),le=i.useCallback(ve=>{const Oe=new WeakMap,xe=Me=>{Oe.set(Me,Hr(Me));for(const Ye of Me.children)xe(Ye)};return ve.forEach(xe),Oe},[]),Le=i.useMemo(()=>le(H),[le,H]),He=i.useMemo(()=>{const ve=new WeakMap;return X.forEach(({nodes:Oe})=>{Oe.forEach(xe=>ve.set(xe,Hr(xe)))}),ve},[X]),Ee=i.useCallback(ve=>Le.get(ve)??He.get(ve)??"",[Le,He]),Pe=i.useCallback(ve=>({subtreeContainsEditing:Z,menuOpenSessionId:pe,nodeStructureKey:Ee(ve)}),[Z,pe,Ee]),te=fe.length,Ce=s.isArchivedBucket||a?fe:fe.slice(0,we),Be=te-Ce.length,vt=!s.isArchivedBucket&&!a&&te>ge&&Be===0,Je=s.isArchivedBucket===!0&&!a&&Ce.length>=eh,et=s.isArchivedBucket?"archived":"active",Et=Je&&Ce.some(ve=>{if(ve.children.length===0)return!1;const Oe=`project:${et}:${ve.session.id}`;return P.has(Oe)}),kt=i.useMemo(()=>me(H),[me,H]);if(a&&!re&&ue.length===0&&fe.length===0)return null;const ts=!s.isMain&&!!s.branch,mt=s.branch&&Id(s.branch,s.label)?{label:s.branch,color:null}:null,at=Q?Ea(H,G,Ne):null,Xe=at?t.jsx(Aa,{state:at,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,lt=(ve,Oe)=>{const{folder:xe,scopeKey:Me,scopeDirectory:Ye,nodes:ct}=ve,St=Re.get(xe.id)??[],zt=a?!1:h.has(xe.id);return t.jsx(Qf,{folderId:xe.id,children:(ps,Pt)=>t.jsx(Yf,{folder:xe,displayName:Oe,sessions:ct,isCollapsed:zt,collapsedActivityState:zt?je.get(xe.id)??null:null,onToggle:()=>b(xe.id),onRename:tt=>{p(Me,xe.id,tt)},onDelete:()=>{if(s.isArchivedBucket){Ss.requestDelete({sessions:St,mode:"session"});return}if(!m){g(Me,xe.id);return}const tt=X.filter(({folder:Ze})=>Ze.parentId===xe.id).length,Mt=ct.length;w({scopeKey:Me,folderId:xe.id,folderName:xe.name,subFolderCount:tt,sessionCount:Mt})},renderSessionNode:x,getRenderExtras:Ee?tt=>({subtreeContainsEditing:Z,menuOpenSessionId:pe,nodeStructureKey:Ee(tt),childRenderExtrasFor:Pe}):void 0,groupDirectory:Ye??s.directory,projectId:r,mobileVariant:A,alwaysShowActions:j,isRenaming:_===xe.id,renameDraft:_===xe.id?K:void 0,onRenameDraftChange:tt=>V(tt),onRenameSave:()=>{const tt=K.trim();tt&&p(Me,xe.id,tt),O(null),V("")},onRenameCancel:()=>{O(null),V("")},droppableRef:ps,isDropTarget:Pt,depth:0,onNewSession:()=>{r&&r!==N&&C(r),y("chat"),A&&k(!1),D({selectedProjectId:r,directoryOverride:Ye??s.directory,targetFolderId:xe.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},xe.id)},Ut=()=>{const ve=new Map;for(const Me of X){const Ye=Me.folder.parentId;if(!Ye)continue;const ct=ve.get(Ye);ct?ct.push(Me):ve.set(Ye,[Me])}const Oe=[],xe=(Me,Ye)=>{const ct=Ye?`${Ye} / ${Me.folder.name}`:Me.folder.name;Oe.push(lt(Me,ct)),!(!a&&h.has(Me.folder.id))&&(ve.get(Me.folder.id)??[]).forEach(zt=>xe(zt,ct))};return ue.forEach(Me=>xe(Me,"")),Oe},ss=j?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",wt=t.jsxs(Vf,{scopeKey:L[0]?.scopeKey??Ue,hasFolders:X.length>0,onSessionDroppedOnFolder:(ve,Oe)=>{const xe=X.find(({folder:Ye})=>Ye.id===Oe);if(!xe)return;const Me=ht.getState();for(const{scopeKey:Ye}of L)Ye!==xe.scopeKey&&Me.getSessionFolderId(Ye,ve)&&Me.removeSessionFromFolder(Ye,ve);M(xe.scopeKey,Oe,ve)},children:[Ut(),s.isArchivedBucket?t.jsx(sh,{visibleSessions:Ce,shouldVirtualize:Je,hasExpandedParent:Et,scrollContainerRef:q,groupDirectory:s.directory,projectId:r,isArchivedBucket:s.isArchivedBucket===!0,renderSessionNode:x,getRenderExtras:ve=>({subtreeContainsEditing:Z,menuOpenSessionId:pe,nodeStructureKey:Ee(ve),childRenderExtrasFor:Pe})}):Ce.map(ve=>t.jsx(i.Fragment,{children:x(ve,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Z,menuOpenSessionId:pe,nodeStructureKey:Ee(ve),childRenderExtrasFor:Pe})},ve.session.id)),te===0&&X.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."}):t.jsx(ws,{icon:"chat-new",onClick:()=>{D({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,Be>0?t.jsx(ws,{icon:"arrow-down-s",onClick:()=>I(n,Ce.length),children:Be===1?"Show 1 more session":`Show ${Be} more sessions`}):null,vt?t.jsx(ws,{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:wt})}):t.jsxs("div",{className:"oc-group",children:[t.jsx(nh,{group:s,groupKey:n,isCollapsed:Q,onToggleCollapsedGroup:ee,normalizedSessionSearchQuery:l,alwaysShowActions:j,groupHeaderRightPadding:ss,dragHandleProps:Fe,groupPrColor:Se,groupPrSummary:se,groupActivityIndicator:Xe,showBranchSubtitle:ts,statusLine:mt,allGroupSessions:kt,projectId:r,activeProjectId:N,setActiveProjectIdOnly:C,setActiveMainTab:y,mobileVariant:A,setSessionSwitcherOpen:k,openNewSessionDraft:D}),Q?null:t.jsx("div",{className:"oc-group-body",children:wt})]})}const dh=i.memo(ch,ah);function uh(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:b,sessionSearchQuery:p,setSessionSearchQuery:g,hasSessionSearchQuery:m,searchMatchCount:w,selectionModeEnabled:x,onToggleSelectionMode:I,mobileVariant:v=!1}=e;if(s)return null;const A=$(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return t.jsx("div",{className:$("select-none flex-shrink-0",v?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:$("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:$("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:$("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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:A,"aria-label":"Settings",children:t.jsx(R,{name:"settings-3",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!v&&a?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:A,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(R,{name:"server",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:A,"aria-label":"Update",children:t.jsx(R,{name:"download",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,v?null:t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:A,"aria-label":"Add project",children:t.jsx(R,{name:"folder-add",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),v?null:t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:A,"aria-label":"Archive",children:t.jsx(R,{name:"archive",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:$("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>h(j=>!j),className:A,"aria-label":"Search sessions","aria-expanded":f,children:t.jsx(R,{name:"search",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:I,className:$(A,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:t.jsx(R,{name:"checkbox-multiple",className:d})})}),t.jsx(Ke,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:x?"Exit selection":"Select sessions"})})]})]})]}),f?t.jsxs("div",{className:$(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:m?t.jsx("span",{children:w===1?`${w} match`:`${w} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(R,{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:b,value:p,onChange:j=>g(j.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:j=>{j.key==="Escape"&&(j.stopPropagation(),m?g(""):h(!1))}}),p.length>0?t.jsx("button",{type:"button",onClick:()=>g(""),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(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function fh(e){const s=ce(o=>o.toggleSidebar),n=ce(o=>o.shortcutOverrides),r=to(Un("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, ${_o})`}}),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, ${_o})))`}}),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:$("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(R,{name:"chat-new",className:$(Tn,"text-current")}),t.jsx("span",{className:Wi,children:"New session"})]}),e.showSidebarToggle?t.jsxs($e,{children:[t.jsx(Ge,{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(R,{name:"layout-left",className:"size-4"})})}),t.jsx(Ke,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Pa=500,hh=({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 b=i.useCallback(()=>{h(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},Pa)},[h]);return t.jsxs(oo,{open:c,onOpenChange:d,children:[t.jsxs(io,{render:t.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:h,onTouchEnd:h,onTouchCancel:h,style:{touchAction:"manipulation"},className:$(Yn(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(R,{name:"git-branch",className:$(hn(l),"text-muted-foreground")}),t.jsx("span",{className:pn(l),children:f})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(As,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsx(ao,{className:"min-w-[160px]",children:t.jsxs(Os,{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(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close worktree"})]})})]})},Yn=(e,s)=>$("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"),ph=({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:b,setNodeRef:p,transform:g,transition:m,isDragging:w}=Vd({id:e.id,disabled:!c}),[x,I]=i.useState(!1),v=i.useRef(null),A=i.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);i.useEffect(()=>()=>A(),[A]);const j=i.useCallback(()=>{A(),v.current=window.setTimeout(()=>{v.current=null,I(!0)},Pa)},[A]);return t.jsx("div",{ref:p,style:{transform:Jd.Translate.toString(g),transition:m},className:$(w&&"opacity-60"),children:t.jsxs(oo,{open:x,onOpenChange:I,children:[t.jsxs(io,{render:t.jsx("button",{type:"button",onClick:()=>{x||d()},onTouchStart:j,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Yn(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:$("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?b:{},children:t.jsx(R,{name:"folder",className:$(hn(h),"text-muted-foreground")})}),t.jsx("span",{className:pn(h),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(As,{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(R,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?t.jsx(R,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(ao,{className:"min-w-[160px]",children:[t.jsxs(Os,{onClick:()=>u(e.id),children:[t.jsx(R,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(va,{}),t.jsxs(Os,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},mh=({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:b,homeDirectory:p,className:g,mobileVariant:m=!1})=>{const w=s===null,x=pt(j=>j.reorderProjects),I=e.length>1,v=Zi(Br(Hd,{activationConstraint:{distance:8}}),Br(Wd,{activationConstraint:{delay:200,tolerance:6}})),A=i.useCallback(j=>{const{active:N,over:C}=j;if(!C||N.id===C.id)return;const y=pt.getState().projects,k=y.findIndex(M=>M.id===N.id),D=y.findIndex(M=>M.id===C.id);k<0||D<0||x(k,D)},[x]);return t.jsxs("div",{className:$("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",g),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:Yn(m,w),"aria-pressed":w,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(R,{name:"chat-history",className:hn(m)}),t.jsx("span",{className:pn(m),children:"All sessions"})]})}),t.jsx(ea,{sensors:v,collisionDetection:ta,onDragEnd:A,children:t.jsx(qd,{items:e.map(j=>j.id),strategy:Qd,children:e.map(j=>{const N=s===j.id,C=N&&!n,y=r.get(j.normalizedPath)??[],k=Jn(j.label?.trim()||_s(j.normalizedPath,p)||j.normalizedPath),D=b?.get(j.id),M=ke(j.normalizedPath)?.toLowerCase()??"",B=M?D?.has(M)??!1:!1,_=(D?.size??0)>0,K=h?.(j.id)??!1,V=b?N?B:_:K;return t.jsxs(i.Fragment,{children:[t.jsx(ph,{project:j,label:k,isSelected:C,hasActive:V,hasWorktrees:y.length>0,worktreeError:o.get(j.normalizedPath),isExpanded:N,canDrag:I,onSelect:()=>a(j.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:m}),N?y.map(O=>{const T=n===O.path,P=ke(O.path)?.toLowerCase()??"",U=P?D?.has(P)??!1:!1,ne=b?U:!1;return t.jsx(hh,{projectId:j.id,worktree:O,isSelected:T,hasActive:ne,onSelect:()=>l?.(j.id,O.path),onClose:c,mobileVariant:m},O.path)}):null]},j.id)})})}),t.jsxs("button",{type:"button",onClick:d,className:Yn(m,!1),children:[t.jsx(R,{name:"add",className:hn(m)}),t.jsx("span",{className:pn(m),children:"Add folder"})]})]})},fr="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 gh({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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:fr,"aria-label":"Settings",children:t.jsx(R,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(Ke,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:fr,"aria-label":"Shortcuts",children:t.jsx(R,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(Ke,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:fr,"aria-label":"About PiChamber",children:t.jsx(R,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(Ke,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Te,{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 bh=(e,s)=>Jn(e.label?.trim()||_s(e.normalizedPath,s)||e.normalizedPath);function xh(e){_t("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,b)=>{const p=s.current,g=p.get(h);if(g&&g.groups===b)return g.ordered;const m=e.getOrderedGroups(h,b);if(p.set(h,{groups:b,ordered:m}),p.size>256){const w=p.keys().next().value;w!==void 0&&p.delete(w)}return m},o=i.useRef(null),a=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const h=[],b=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const p of b){const g=bh(p.project,e.homeDirectory);for(const m of p.groups)if(!m.isArchivedBucket)for(const w of m.sessions){const x=!!e.pinnedSessionIds?.has(w.session.id),I=w.session.time?.updated||w.session.time?.created||0;h.push({node:w,project:p.project,projectLabel:g,isPinned:x,timestamp:I,globalSession:p===e.allFoldersOnlySection})}}return h.sort((p,g)=>p.isPinned!==g.isPinned?p.isPinned?-1:1:g.timestamp-p.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(xs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("pt-2 pb-1",e.mobileVariant&&"pb-32"),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(xs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0&&!f?t.jsx(xs,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("pt-2 pb-1",e.mobileVariant&&"pb-32"),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(xs,{ref:o,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:$("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),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(m=>m.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!h)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=h.groups.find(m=>m.isMain&&m.sessions.length>0)??h.groups.find(m=>m.sessions.length>0)??h.groups.find(m=>m.isMain)??h.groups[0];if(!b)return t.jsx(ws,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath}),children:"New session"});const p=h.groups.find(m=>m.isArchivedBucket);return[b,...p&&p.id!==b.id?[p]:[]].map(m=>{const w=`${h.project.id}:${m.id}`,x=m.id===b.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(m,w,h.project.id,x,null,!0,o)},w)})})()}):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:b,projectLabel:p,globalSession:g})=>{const m=h.session.directory??b.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(h,0,m,b.id,!1,{projectLabel:p,showFolderLabel:!0,globalSession:g},"project")},h.session.id)}),u>0?t.jsx(ws,{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(ws,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(h=>{const b=h.project.id,p=r(b,h.groups),g=p.find(w=>w.isMain)??null,m=g?p.filter(w=>w.id!==g.id):p;return t.jsxs("div",{children:[g?e.renderGroupSessions(g,`${b}:${g.id}`,b,!0,null,void 0,o):null,m.map(w=>{const x=`${b}:${w.id}`,I=p.length===1;return t.jsx(i.Fragment,{children:e.renderGroupSessions(w,x,b,I,null,void 0,o)},w.id)})]},b)})})]})})})}const yh=i.memo(xh);let Yr=!1;const qr=new Set;let si=!1;function vh(){for(const e of qr)e()}function co(e){Yr!==e&&(Yr=e,vh())}function wh(e){e.key==="Shift"&&co(!0)}function Sh(e){e.key==="Shift"&&co(!1)}function jh(){co(!1)}function Ch(){si||typeof window>"u"||(si=!0,window.addEventListener("keydown",wh),window.addEventListener("keyup",Sh),window.addEventListener("blur",jh))}function kh(e){return Ch(),qr.add(e),()=>{qr.delete(e)}}function Ah(){return Yr}function Nh(){return!1}function Ih(){return Ae.useSyncExternalStore(kh,Ah,Nh)}const Rh=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Ih(),f=u?n:s,h=b=>{if(u||b.shiftKey){d(b);return}c(b)};return t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",className:$("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:b=>b.stopPropagation(),children:t.jsx(R,{name:u?"delete-bin":"archive",className:o})})}),t.jsx(Ke,{side:"left",sideOffset:8,children:f})]})}),Dh=i.memo(function({open:s,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,onExport:l}){return t.jsx(Yt,{open:s,onOpenChange:n,children:t.jsxs(qt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(es,{children:"Export Markdown"}),t.jsx(hs,{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(ks,{children:[t.jsx(Te,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Te,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function Eh(e,s){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:a,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:h,handleOpenMiniChatWindow:b,handleDeleteSession:p,handleRestoreSession:g}=e,{Item:m,Separator:w}=s;return t.jsxs(t.Fragment,{children:[t.jsxs(m,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(m,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(m,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[a?t.jsx(R,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(R,{name:"pushpin",className:"mr-1 h-4 w-4"}),a?"Unpin session":"Pin session"]}),t.jsxs(m,{onClick:()=>{h()},className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?t.jsxs(m,{disabled:!o,onClick:b,className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(w,{}),l?null:t.jsxs(m,{className:"[&>svg]:mr-1",onClick:()=>p(n,{archivedBucket:l}),children:[t.jsx(R,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?t.jsxs(m,{className:"[&>svg]:mr-1",onClick:()=>g(n),children:[t.jsx(R,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(m,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>p(n,{archivedBucket:l,hardDelete:!0}),children:[t.jsx(R,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Ph(e){const{renamingFolderId:s,editingIdRef:n}=e;return t.jsx(qi,{children:t.jsx(Qi,{className:"app-region-no-drag z-50",children:t.jsx(Vi,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(s||n.current),style:{color:"var(--surface-elevated-foreground)"},className:$(ki,"min-w-[180px]"),children:Eh(e,{Item:({className:r,...o})=>t.jsx(Ji,{className:$(Ai,r),...o}),Separator:({className:r,...o})=>t.jsx(Xi,{className:$(Ni,r),...o})})})})})}const hr=new WeakMap,Mh=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;hr.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,hr.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,_t("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}),hr.set(n,c),l=window.requestAnimationFrame(d)};function Th(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 Fh(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 Oh(e){const s=e.info.role==="user"?"User":"Assistant",n=Th(e.info.time?.created),r=Fh(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
|
|
12
|
-
|
|
13
|
-
*${o}*`:`**${s}**`}function Lh(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Ma(e){const s=Oh(e),n=Lh(e.parts).trim();return n?`${s}
|
|
14
|
-
|
|
15
|
-
${n}`:""}function Ta(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
16
|
-
|
|
17
|
-
---
|
|
18
|
-
|
|
19
|
-
`,a=e.records.map(Ma).filter(Boolean).join(`
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
`),l=[o+a];for(const c of e.children)l.push(Ta(c,s+1));return l.join(`
|
|
24
|
-
|
|
25
|
-
---
|
|
26
|
-
|
|
27
|
-
`)}function Fa(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
28
|
-
|
|
29
|
-
*Exported on ${o}*
|
|
30
|
-
|
|
31
|
-
---
|
|
32
|
-
|
|
33
|
-
`,l=e.map(Ma).filter(Boolean).join(`
|
|
34
|
-
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
`);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Ta(u,1)).join(`
|
|
38
|
-
|
|
39
|
-
---
|
|
40
|
-
|
|
41
|
-
`);c+=`
|
|
42
|
-
|
|
43
|
-
---
|
|
44
|
-
|
|
45
|
-
`+d}return c}function Oa(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 La(e,s){const n=await ad(s,e);return n||null}async function Bh(e){const s=Jt()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await ld(e)?!0:Li(e)}function _h(){return cd()}function Ba(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 qn=e=>{const s=[],n=r=>{r.children.forEach(o=>{s.push(o.session.id),n(o)})};return n(e),s};function Uh(e,s){const[n,r]=i.useState(!1),[o,a]=i.useState(!0),l=e.session,c=i.useMemo(()=>qn(e).length,[e]),d=i.useCallback(async b=>{const p=[];let g=0;for(const m of b)try{if(!s)throw new Error("Session directory is required for export");const w=[],x=m.session.title||"Untitled Sub-agent",I=typeof m.session.agent=="string"?m.session.agent:void 0,v=await d(m.children);g+=v.skipped,p.push({title:x,agent:I,records:w,children:v.children})}catch{g+=qn(m).length+1}return{children:p,skipped:g}},[s]),u=i.useCallback(b=>{b<=0||oe.warning(b===1?`Exported session, but skipped ${b} sub-agent task that could not be loaded.`:`Exported session, but skipped ${b} sub-agent tasks that could not be loaded.`)},[]),f=i.useCallback(async b=>{if(!s){oe.error("Nothing to export");return}const p=[];if(p.length===0){oe.error("Nothing to export");return}let g,m=0;if(b&&e.children.length>0){const v=await d(e.children);g=v.children,m=v.skipped}const w=Fa(p,l.title??null,g),x=Ba(l.title??null),I=await La(w,x);if(I){oe.success("Session exported",{action:{label:_h(),onClick:()=>{Bh(I).then(v=>{v||oe.error("Failed to reveal path")})}}}),u(m);return}Oa(w,x),oe.success("Session exported"),u(m)},[d,e.children,l.title,s,u]),h=i.useCallback(async()=>{if(e.children.length>0){a(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:n,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,descendantCount:c,handleExportSession:h,doExportSession:f}}const zh=(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},it=Ks()((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 b of f)l.delete(b);d===n&&(d=null)}else{for(const b of f)l.add(b);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,b]=u<=f?[u,f]:[f,u],p=o.slice(h,b+1),g=zh(p,l),w=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of g)w.add(x);e({selectedIds:w,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}))}})),ni=e=>ke(e.session.directory??null),$h=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),Gh=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},Dn=e=>e.menuOpenSessionId??Gh(e),En=(e,s,n)=>s?n.has(e.node.session.id)?!0:Zt(e.node,s):!1,Qr=(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(Qr(e.children[l],s.children[l],n,r,o))return!0;return!1},Kh=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Qr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Qr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},Wh=(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.nodeStructureKey!==s.nodeStructureKey||ni(e.node)!==ni(s.node)||!$h(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Na(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&Kh(e,s)||e.editingId!==s.editingId&&(En(e,e.editingId,e.subtreeContainsEditing)||En(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(En(e,e.editingId,e.subtreeContainsEditing)||En(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(Zt(e.node,e.copiedSessionId)||Zt(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Dn(e),r=Dn(s);if(Zt(e.node,n)||Zt(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=Dn(e),r=Dn(s);if(Zt(e.node,n)||Zt(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 Hh({node:e,groupDirectory:s,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:a,expansionKey:l,hasSessionSearchQuery:c}){const d=e.session,u=ke(d.directory??null)??ke(s??null),f=De(z=>z.currentSessionId===d.id),h=Ei(u),b=gc(u),p=pt(i.useCallback(z=>{if(r?.projectLabel||!n)return null;const Q=z.projects.find(se=>se.id===n);return Q?Q.label?.trim()||_s(ke(Q.path)??Q.path,null)||Q.path:null},[n,r?.projectLabel])),g=r?.projectLabel??(p?Jn(p):null),m=e.worktree,w=r?.branchLabel??m?.branch??(h&&h!=="HEAD"?h:null),x=w,I=b===!0||!!(w||m),v=e.children.length,A=d.agent;i.useMemo(()=>{const z=m?.branch?.trim()||w?.trim(),Q=ke(m?.path??u);return z&&Q?Ia():null},[w,u,m]);const j=Ra(),N=void 0,C=i.useMemo(()=>null,[j]),y=n??u??null,k=it(z=>z.enabled),D=it(i.useCallback(z=>z.selectedIds.has(d.id),[d.id])),M=it(z=>z.toggleSelected),B=it(z=>z.setRange),K=Pi(d.id)?.type??"idle",V=K==="busy"||K==="retry",O=bc(d.id,V),T=ds(d),P=e.children.length>0,U=xc(o,u,d.id),ne=c?!0:a.has(l),G=yc(d.id)>0,Ne=d.time?.updated||d.time?.created||Date.now(),ee=Rd(Ne),Fe=i.useMemo(()=>ja(e.forkColorId),[e.forkColorId]),_e=i.useMemo(()=>Af(e.forkColorId,{active:f||D}),[e.forkColorId,f,D]),q=r?.globalSession&&!f&&!D?"var(--surface-elevated)":null;return{session:d,sessionDirectory:u,isActive:f,tooltipProjectLabel:g,tooltipBranchLabel:x,isGitRepo:I,subtaskCount:v,agentName:A,prSummary:j,prIconColor:N,prStatusLabel:C,selectionScopeKey:y,selectionModeEnabled:k,isRowSelected:D,toggleRowSelected:M,setRowRange:B,isStreaming:V,hasActivityDuration:O,sessionTitle:T,hasChildren:P,isPinnedSession:U,isExpanded:ne,needsAttention:G,sessionCompactUpdatedLabel:ee,forkSolid:Fe,rowBackground:_e??q}}function Yh(e){_t("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,editingId:f,setEditingId:h,editTitle:b,setEditTitle:p,handleSaveEdit:g,handleCancelEdit:m,toggleParent:w,handleSessionSelect:x,handleSessionDoubleClick:I,togglePinnedSession:v,handleShareSession:A,copiedSessionId:j,handleCopyShareUrl:N,handleCopySessionId:C,handleUnshareSession:y,openSidebarMenuKey:k,setOpenSidebarMenuKey:D,renamingFolderId:M,getFoldersForScope:B,getSessionFolderId:_,removeSessionFromFolder:K,addSessionToFolder:V,createFolderAndStartRename:O,handleDeleteSession:T,handleRestoreSession:P,alwaysShowActions:U,allowQuickArchiveAction:ne,renderSessionNode:W,secondaryMeta:G,renderContext:Ne="project",subtreeContainsEditing:ee,menuOpenSessionId:Fe,childRenderExtrasFor:_e}=e,q=i.useMemo(()=>Bi(),[]),F=!a&&ne,z=i.useRef(!1),Q=i.useRef(f);Q.current=f;const se=i.useRef(null),Se=i.useRef(g);Se.current=g;const[ge,we]=i.useState(b),re=i.useRef(ge);re.current=ge;const ae=i.useRef(null),H=i.useRef(null),Ue=`${Ne}:${a?"archived":"active"}:${s.session.id}`,{session:L,sessionDirectory:X,isActive:ue,tooltipProjectLabel:fe,tooltipBranchLabel:je,isGitRepo:Re,subtaskCount:be,agentName:Z,prSummary:pe,selectionScopeKey:le,selectionModeEnabled:Le,isRowSelected:He,toggleRowSelected:Ee,setRowRange:Pe,isStreaming:te,hasActivityDuration:Ce,sessionTitle:Be,hasChildren:vt,isPinnedSession:Je,isExpanded:et,needsAttention:Et,sessionCompactUpdatedLabel:kt,forkSolid:ts,rowBackground:mt}=Hh({node:s,groupDirectory:r,projectId:o,secondaryMeta:G,pinnedSessionIds:l,expandedParents:c,expansionKey:Ue,hasSessionSearchQuery:d}),{exportDialogOpen:at,setExportDialogOpen:Xe,exportIncludeSubtasks:lt,setExportIncludeSubtasks:Ut,descendantCount:ss,handleExportSession:wt,doExportSession:ve}=Uh(s,X),[Oe,xe]=i.useState(!1),Me=i.useCallback(()=>{X&&ln("desktop_open_session_mini_chat_window",{sessionId:L.id,directory:X,apiBaseUrl:Mr(),clientToken:Pr()}).catch(de=>{console.warn("[session-sidebar] failed to open mini chat window",de)})},[L.id,X]);i.useEffect(()=>{if(f!==L.id)return;const de=nt=>{const ut=nt.target?.closest?.(`[data-session-rename-form="${CSS.escape(L.id)}"]`);H.current&&!ut&&Se.current(re.current)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[f,L.id]),i.useLayoutEffect(()=>{if(f!==L.id){ae.current===L.id&&(ae.current=null);return}ae.current!==L.id&&(ae.current=L.id,we(b))},[f,b,L.id]);const Ye=!te&&Et&&!ue,ct=te&&Ce,St=Je,zt=t.jsx(R,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),ps=St?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:zt}):null,Pt=vt?t.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),w(Ue)},onKeyDown:de=>{(de.key==="Enter"||de.key===" ")&&(de.preventDefault(),de.stopPropagation(),w(Ue))},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":et?"Collapse subsessions":"Expand subsessions",children:et?t.jsx(R,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(R,{name:"arrow-right-s",className:"h-3 w-3"})}):null,tt=de=>{if(!de&&se.current){const{id:nt,title:st}=se.current;se.current=null,h(nt),p(st)}},Mt=de=>{xe(de)},Ze=de=>{de.preventDefault(),de.stopPropagation()},Qt=de=>{de.preventDefault(),de.stopPropagation()},$t=de=>{de.preventDefault(),de.stopPropagation(),D(null),T(L,{archivedBucket:a})},Ns=de=>{de.preventDefault(),de.stopPropagation(),D(null),T(L,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Tt=de=>{if(z.current){z.current=!1;return}if(Le){if(de?.preventDefault(),de?.stopPropagation(),de?.shiftKey){const st=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(ft=>ft.getAttribute("data-session-row")).filter(ft=>typeof ft=="string"&&ft.length>0),ut=it.getState().anchorId,Gt=new Map;Gt.set(L.id,qn(s)),Pe(ut,L.id,st,le,Gt);return}Ee(L.id,le,qn(s));return}de?.currentTarget&&Mh(de.currentTarget),x(L.id,X)},Hs=de=>{de.defaultPrevented||de.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Tt(de)},dt=de=>{(de.button===2||de.button===0&&de.ctrlKey&&!Le)&&(z.current=!0)},ms={session:L,sessionTitle:Be,sessionDirectory:X,isPinnedSession:Je,archivedBucket:a,isElectron:q,renamingFolderId:M,editingIdRef:Q,pendingRenameRef:se,handleCopySessionId:C,togglePinnedSession:v,handleExportSession:wt,handleOpenMiniChatWindow:Me,handleDeleteSession:T,handleRestoreSession:P},gt=t.jsx(Ph,{...ms});return t.jsxs(i.Fragment,{children:[t.jsx(qf,{sessionId:L.id,sessionDirectory:X??null,sessionTitle:Be,children:t.jsxs(Hi,{open:Oe,onOpenChange:Mt,onOpenChangeComplete:tt,children:[t.jsxs(Yi,{render:t.jsx("div",{"data-session-row":L.id,"data-session-scope":le??"","data-session-archived":a?"1":"0","data-fork-color":ts?s.forkColorId:void 0,"data-global-session":G?.globalSession?"1":void 0,onClick:Hs,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...mt?{backgroundColor:mt}:void 0},className:$("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!mt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":mt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!mt&&ue&&!He&&"bg-interactive-selection",!mt&&He&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[Pt,ps,f===L.id?t.jsxs("form",{ref:H,"data-session-rename-form":L.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:de=>de.stopPropagation(),onMouseDown:de=>de.stopPropagation(),onSubmit:de=>{de.preventDefault(),g(ge)},children:[t.jsx("input",{value:ge,onChange:de=>we(de.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:de=>{de.stopPropagation(),de.key==="Escape"&&m()}}),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(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:m,"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(R,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:dt,onClick:de=>Tt(de),onDoubleClick:de=>{de.stopPropagation(),I(L.id,Be)},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:$("block min-w-0 flex-1 truncate font-normal typography-ui-label",Et?"text-foreground":"text-foreground/90"),children:On(Be,u)})}),G?.showFolderLabel&&fe||je||Re||pe||be>0||Z&&Z!=="default"||ct?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:[G?.showFolderLabel&&fe?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:fe}):null,je?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(R,{name:"git-branch",className:$("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:je})]}):Re?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(R,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,be>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(R,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:be})]}):null,Z&&Z!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:Z}):null,ct?t.jsx(Dd,{sessionId:L.id,running:te,className:"text-muted-foreground/70"}):null]}):null]})]}),Je?t.jsx(R,{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:$("flex items-center justify-end",F&&(U||Oe)?"opacity-0":F?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:te?t.jsx(As,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):Ye?t.jsx(Ed,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:kt})}),F?t.jsx("div",{className:$("absolute inset-0 flex items-center justify-end",U||Oe?"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(Rh,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Ze,onMouseDown:Qt,onArchive:$t,onDelete:Ns})}):null]})]}),gt]})}),vt&&et?s.children.map(de=>{const nt=_e?_e(de):{subtreeContainsEditing:ee,menuOpenSessionId:Fe,nodeStructureKey:""};return t.jsx(i.Fragment,{children:W(de,n+1,X??r,o,a,G?.globalSession?{globalSession:!0}:void 0,Ne,nt)},de.session.id)}):null,t.jsx(Dh,{open:at,onOpenChange:Xe,descendantCount:ss,exportIncludeSubtasks:lt,setExportIncludeSubtasks:Ut,onExport:ve})]},L.id)}const qh=i.memo(Yh,Wh),Qh=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(Yt,{open:e,onOpenChange:s,children:t.jsx(qt,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(xs,{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(lf,{project:n,onIdentitySave:r}):null})})})});function _a(e){const{showDeletionDialog:s,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:a}=e;return t.jsxs(ks,{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(R,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(R,{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 Vh(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=c=>ds(c);return t.jsx(Yt,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(qt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(es,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(hs,{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(_a,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:s?.archivedBucket?"Delete":"Archive"})]})})}function Jh(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(Yt,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(qt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(es,{children:d}),t.jsx(hs,{children:u})]}),t.jsx(_a,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:l?"Delete":"Archive"})]})})}function Xh(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,b]=i.useState(!1),p=s?.worktree.path??null;i.useEffect(()=>{let j=!1;return l(null),d(!1),f(!1),b(!1),!s||!p?()=>{j=!0}:(o.getGitStatus(p).then(N=>{if(!j){if(typeof N?.isClean!="boolean"){d(!0);return}l(N)}}).catch(()=>{j||d(!0)}),()=>{j=!0})},[o,s,p]);const g=a?.isClean===!1,m=(a?.ahead??0)>0,w=m&&!s?.worktree.branch,x=s?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",I=!!(s&&a&&!c&&!s.hasActiveSession&&(!g&&!w||u)&&!h),v=s?.worktree.branch||s?.worktree.name||s?.worktree.path||"",A=async()=>{if(I){b(!0);try{await r({force:g})}finally{b(!1)}}};return t.jsx(Yt,{open:!!s,onOpenChange:j=>{!j&&!h&&n(null)},children:t.jsxs(qt,{showCloseButton:!1,className:"max-w-md gap-5",children:[t.jsxs(fs,{children:[t.jsx(es,{children:"Close worktree?"}),t.jsx(hs,{children:`Closing "${v}" removes its worktree directory. ${x}`})]}),c?t.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3",children:[t.jsx(R,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),t.jsx("p",{className:"typography-ui-label text-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.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,g?t.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),t.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[t.jsx(Nr,{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,m?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. ${x}`:`This worktree has ${a?.ahead} unpushed commits. ${x}`}),w?t.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),t.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[t.jsx(Nr,{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(ks,{className:"sm:justify-end",children:[t.jsx(Te,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:h,children:"Cancel"}),t.jsx(Te,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!I,children:h?"Closing…":"Close worktree"})]})]})})}function Zh(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(Yt,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(qt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(es,{children:"Delete folder?"}),t.jsx(hs,{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(ks,{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 ep=({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:b,confirmDeleteFolder:p,closeWorktreeConfirm:g,setCloseWorktreeConfirm:m,confirmCloseWorktree:w,bulkDeleteConfirm:x,setBulkDeleteConfirm:I,confirmBulkDelete:v})=>t.jsxs(t.Fragment,{children:[t.jsx(ha,{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(Qh,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:a}),t.jsx(Vh,{value:l,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),t.jsx(Zh,{value:h,setValue:b,onConfirm:p}),t.jsx(Xh,{value:g,setValue:m,onConfirm:w}),t.jsx(Jh,{value:x,setValue:I,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:v})]}),tp=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=ke(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return on(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=ke(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(As,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},sp=e=>{let s=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(s+=r.sessions.length);return s},np=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},rp=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),op=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),ip=(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=ke(a.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},ap=e=>e.map(s=>s.groups.some(n=>n.isArchivedBucket)?{...s,groups:s.groups.filter(n=>!n.isArchivedBucket)}:s),lp=(e,s,n,r)=>{if(!n)return s;const o=e.find(c=>c.project.id===n);if(!o)return[];const a=ke(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&ke(c.directory)===a);return l?[{...o,groups:[l]}]:[]},cp=(e,s)=>{const n=new Map,r=new Map;return e.forEach(o=>{const a=Jn(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 b=o.project.normalizedPath.length,p=r.get(h.session.id)??-1;b<p||(n.set(h.session.id,{node:h,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:d}),r.set(h.session.id,b),h.children.length>0&&u(h.children))})};u(l.sessions)})}),n};function dp({projectSections:e,flatSectionsForRender:s,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:a,activeSessionIdSet:l,unreadSessionIdSet:c}){const d=i.useMemo(()=>cp(e,a),[e,a]),u=i.useMemo(()=>ap(s),[s]),f=i.useMemo(()=>lp(n,u,r,o),[n,u,r,o]),h=i.useMemo(()=>sp(e),[e]),b=i.useMemo(()=>np(e),[e]),p=i.useCallback(w=>{const x=e.find(I=>I.project.id===w);return x?rp(x,l):!1},[l,e]),g=i.useMemo(()=>ip(e,l),[l,e]),m=i.useCallback(w=>{const x=e.find(I=>I.project.id===w);return x?op(x,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:h,sessionCountByProject:b,hasActiveSessionByProject:p,activeDirectoriesByProject:g,hasUnseenByProject:m}}const up=({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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(R,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(Ke,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:$("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(R,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Ke,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:t.jsx(R,{name:"close",className:"h-4 w-4"})})}),t.jsx(Ke,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},fp=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,b=it(T=>T.enabled),p=it(T=>T.selectedIds.size),g=p>0,m=it(T=>T.selectedIds),w=it(T=>T.scopeKey),x=i.useCallback(()=>{it.getState().toggleMode()},[]),I=i.useCallback(()=>{it.getState().disable()},[]),v=i.useMemo(()=>{if(!g||typeof document>"u")return!1;let T=!1,P=!1;for(const U of m){const ne=document.querySelectorAll(`[data-session-row="${CSS.escape(U)}"]`);for(const W of ne)W.getAttribute("data-session-archived")==="1"?P=!0:T=!0}return P&&!T},[g,m]),A=i.useMemo(()=>{if(w)return w;if(!g||typeof document>"u")return null;for(const T of m){const U=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(U&&U.length>0)return U}return null},[g,m,w]),j=i.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(P=>P.scopeKey):[A]},[A,o]),N=i.useMemo(()=>j.flatMap(T=>r[T]??[]),[r,j]),C=i.useCallback(T=>{for(const P of j)if((r[P]??[]).some(U=>U.id===T))return P;return null},[r,j]),y=i.useMemo(()=>{if(!g)return!1;for(const T of j)for(const P of r[T]??[])for(const U of P.sessionIds)if(m.has(U))return!0;return!1},[r,j,g,m]),k=i.useCallback((T,P)=>{const U=Array.from(m);for(const ne of j)ne!==T&&l(ne,U);a(T,P,U)},[a,l,m,j]),D=i.useCallback(T=>{if(!g)return;const P=C(T);P&&k(P,T)},[g,k,C]),M=i.useCallback(()=>{const T=j[0];if(!T||!g)return;const P=c(T);P&&k(T,P.id)},[c,g,k,j]),B=i.useCallback(()=>{if(!g)return;const T=Array.from(m);for(const P of j)l(P,T)},[l,m,j,g]),_=i.useCallback(async()=>{const T=Array.from(m);if(T.length!==0){if(v){const{deletedIds:P,failedIds:U}=await f(T);P.length>0&&oe.success(P.length===1?`Deleted ${P.length} session`:`Deleted ${P.length} sessions`),U.length>0&&oe.error(U.length===1?`Failed to delete ${U.length} session`:`Failed to delete ${U.length} sessions`)}else{const{archivedIds:P,failedIds:U}=await d(T);P.length>0&&oe.success(P.length===1?`Archived ${P.length} session`:`Archived ${P.length} sessions`),U.length>0&&oe.error(U.length===1?`Failed to archive ${U.length} session`:`Failed to archive ${U.length} sessions`)}it.getState().clear()}},[d,v,f,m]),K=i.useCallback(()=>{if(!g)return;const T=m.size;if(!n){_();return}h({sessionCount:T,archivedBucket:v})},[v,_,m,n,h,g]),V=i.useCallback(async()=>{if(!g||!v)return;const T=Array.from(m),{restoredIds:P,failedIds:U}=await u(T);P.length>0&&oe.success(P.length===1?`Restored ${P.length} session`:`Restored ${P.length} sessions`),U.length>0&&oe.error(U.length===1?`Failed to restore ${U.length} session`:`Failed to restore ${U.length} sessions`),it.getState().clear()},[v,g,m,u]),O=i.useCallback(async()=>{h(null),await _()},[_]);return i.useEffect(()=>{if(!b)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),P=U=>{if(s)return;const ne=U.target;if(ne&&(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.isContentEditable))return;const W=T?U.metaKey:U.ctrlKey;if(U.key==="Escape"){U.preventDefault(),it.getState().disable();return}if(W&&U.key==="Backspace"){U.preventDefault(),K();return}if(W&&(U.key==="a"||U.key==="A")){const G=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(G.length===0)return;U.preventDefault();const ee=it.getState().scopeKey??G[0]?.getAttribute("data-session-scope")??null,Fe=q=>ee?q.getAttribute("data-session-scope")===ee:!0,_e=G.filter(Fe).map(q=>q.getAttribute("data-session-row")).filter(q=>typeof q=="string"&&q.length>0);if(_e.length===0)return;it.getState().replaceAll(_e,ee||null)}};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[K,s,b]),{selectionModeEnabled:b,hasSelection:g,selectedIdsSize:p,bulkScopeIsArchived:v,derivedSelectionScope:A,bulkScopeFolders:N,bulkCanRemoveFromFolder:y,handleToggleSelectionMode:x,handleExitSelectionMode:I,handleBulkMoveToFolder:D,handleBulkCreateFolderAndMove:M,handleBulkRemoveFromFolder:B,handleBulkDelete:K,handleBulkRestore:V,confirmBulkDelete:O}},hp=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},pp=Ks()(so(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:hp})),ri="oc.sessions.projectCollapse",oi="oc.sessions.groupOrder",ii="oc.sessions.groupCollapse",ai="oc.sessions.activeSessionByProject",li="oc.sessions.expandedParents.v3",mp=new Set,pr=[],At=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},gp=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Er("react.session_sidebar_render"),_t("ui.session_sidebar.render"),_t(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),_t(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=i.useState(!1),[u,f]=i.useState(""),h=i.useRef(null),b=i.useRef(null),[p,g]=i.useState(null),[m,w]=i.useState(""),[x,I]=i.useState(null),[v,A]=i.useState(new Set),j=i.useMemo(()=>kn(),[]),[N,C]=i.useState(new Set),y=Ds(S=>S.selectedSpaceId),k=Ds(S=>S.selectedWorktreePath),[D,M]=i.useState(new Map),[B,_]=i.useState(new Map),[K,V]=i.useState(!1),[O,T]=i.useState(null),[P,U]=i.useState(null),[ne,W]=i.useState(""),[G,Ne]=i.useState(null),[ee,Fe]=i.useState(null),[_e,q]=i.useState(null),[F,z]=i.useState(null),Q=To(S=>S.ids),se=vc(i.useCallback(S=>e?S.rankById:Di,[e])),Se=on(S=>e?wc(S.catalog):"",void 0,"catalog"),ge=i.useMemo(()=>Se?Se.split("|"):pr,[Se]),we=i.useMemo(()=>new Set(ge),[ge]),re=Sc(Lr(S=>e?Object.entries(S.index.session.unseenCount).filter(([,Y])=>Y>0).map(([Y])=>Y).sort():pr)),ae=i.useMemo(()=>new Set(re),[re]),H=To(S=>S.toggle),[me,Ue]=i.useState(()=>{try{const S=kn().getItem(ii);if(!S)return new Set;const Y=JSON.parse(S);return new Set(Array.isArray(Y)?Y.filter(J=>typeof J=="string"):[])}catch{return new Set}}),[L,X]=i.useState(()=>{try{const S=kn().getItem(oi);if(!S)return new Map;const Y=JSON.parse(S),J=new Map;return Object.entries(Y).forEach(([Ie,We])=>{Array.isArray(We)&&J.set(Ie,We.filter(Ve=>typeof Ve=="string"))}),J}catch{return new Map}}),ue=i.useMemo(()=>{try{const S=kn().getItem(ai);if(!S)return new Map;const Y=JSON.parse(S),J=new Map;return Object.entries(Y).forEach(([Ie,We])=>{typeof We=="string"&&We.length>0&&J.set(Ie,We)}),J}catch{return new Map}},[]),fe=i.useCallback(S=>{try{j.setItem(ai,JSON.stringify(Object.fromEntries(S.entries())))}catch{}},[j]),[je,Re]=i.useState(new Map),be=i.useRef(0),Z=Bs(S=>S.homeDirectory),pe=Bs(S=>S.currentDirectory),le=pt(S=>S.projects),Le=pt(S=>S.activeProjectId),He=pt(S=>S.removeProject),Ee=pt(S=>S.setActiveProjectIdOnly),Pe=pt(S=>S.updateProjectMeta),te=pt(S=>S.reorderProjects),Ce=ce(S=>S.setActiveMainTab),Be=ce(S=>S.setSettingsDialogOpen),vt=ce(S=>S.setSettingsPage),Je=ce(S=>S.toggleHelpDialog),et=ce(S=>S.setSessionSwitcherOpen),Et=ce(S=>S.setArchivePageOpen),kt=ce(S=>S.showDeletionDialog),ts=ce(S=>S.setShowDeletionDialog),mt=jc(u,120),at=i.useMemo(()=>mt.trim().toLowerCase(),[mt]),Xe=at.length>0,lt=ht(S=>S.collapsedFolderIds),Ut=ht(S=>S.foldersMap),ss=ht(S=>S.getFoldersForScope),wt=ht(S=>S.createFolder),ve=ht(S=>S.renameFolder),Oe=ht(S=>S.deleteFolder),xe=ht(S=>S.addSessionToFolder),Me=ht(S=>S.addSessionsToFolder),Ye=ht(S=>S.removeSessionFromFolder),ct=ht(S=>S.removeSessionsFromFolders),St=ht(S=>S.toggleFolderCollapse),zt=ht(S=>S.getSessionFolderId);Rf({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:b,sessionSearchContainerRef:h});const ps=Cc(e),{git:Pt}=Gs(),tt=on(S=>S.connection,void 0,"chrome"),Mt=on(S=>{for(const Y of S.catalog.listStatusByDirectory.values())if(Y==="ready")return!0;return!1},void 0,"catalog"),Ze=Rr({archived:!1}),Qt=Rr({archived:!0}),$t=De(S=>S.setCurrentSession),Ns=De(S=>S.updateSessionTitle),Tt=De(S=>S.shareSession),Hs=De(S=>S.unshareSession),dt=Dr(S=>S.projects),ms=Dr(S=>S.refreshProject),gt=i.useMemo(()=>kc(le,{projects:dt}),[le,dt]),de=i.useMemo(()=>{const S=new Map;for(const Y of le){const J=ke(Y.path);if(!J)continue;const Ie=dt.get(J)?.error;Ie&&S.set(J,Ie)}return S},[le,dt]);i.useEffect(()=>{if(!y)return;const S=le.find(J=>J.id===y);if(!S){Ds.getState().clearSpaceSelection();return}if(!k)return;(gt.get(ke(S.path)??S.path)??[]).some(J=>ke(J.path)===ke(k))||(Ds.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[gt,le,y,k]);const nt=De(S=>S.openNewSessionDraft),st=i.useCallback(S=>{ce.getState().closeMainSurfaces(),nt(S),r?.()},[r,nt]),ut=Mn(Lr(S=>({checkForUpdates:S.checkForUpdates,available:S.available,runtimeType:S.runtimeType,info:S.info,downloading:S.downloading,downloaded:S.downloaded,progress:S.progress,error:S.error,downloadUpdate:S.downloadUpdate,restartToUpdate:S.restartToUpdate}))),Gt=i.useMemo(()=>Ac(le,gt,{includeWorktrees:!0}),[gt,le]),ft=i.useMemo(()=>Ze.filter(S=>Gf(S,Gt,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:Z})),[Ze,Z,Gt]),Xn=i.useMemo(()=>[...ft,...Qt],[Qt,ft]),Ys=eo(),xn=i.useMemo(()=>`${Ys}|${le.map(S=>`${S.id}:${ke(S.path)??""}`).join("|")}`,[le,Ys]),Is=i.useMemo(()=>{const S=new Set;let Y=!0;for(const J of le){const Ie=ke(J.path);if(!Ie)continue;const We=dt.get(Ie)?.status??"idle";We==="failed"&&S.add(Ie),(We==="idle"||We==="loading")&&(Y=!1)}return{complete:Y,unresolved:S}},[le,dt]),yn=Is.complete?xn:null,Zn=!Is.complete,ns=Is.unresolved,{isTablet:qs}=$s(),Ft=s||qs,er=If({mobileVariant:s,isTablet:qs}),{buildGroupSearchText:tr,filterSessionNodesForSearch:Qs,buildGroupedSessions:Vs}=Nf({homeDirectory:Z,pinnedSessionIds:Q,sessionOrderRanks:se}),{scheduleCollapsedProjectsPersist:vn}=Ef({safeStorage:j,keys:{sessionExpanded:li,projectCollapse:ri,groupOrder:oi,groupCollapse:ii},groupOrderByProject:L,collapsedGroups:me,setExpandedParents:A,setCollapsedProjects:C}),rs=i.useMemo(()=>Nc(ft,Q,se),[Q,se,ft]),Js=i.useMemo(()=>rs.map(S=>S.id).join("|"),[rs]),E=i.useRef(null),ie=i.useMemo(()=>{const S=E.current;if(S&&S.signature===Js)return S.map;const Y=new Map(rs.map((J,Ie)=>[J.id,Ie]));return E.current={signature:Js,map:Y},Y},[rs,Js]),ye=i.useMemo(()=>{const S=new Map;return rs.forEach(Y=>{const J=Y.parentID;if(!J)return;const Ie=S.get(J)??[];Ie.push(Y),S.set(J,Ie)}),S.forEach(Y=>Y.sort((J,Ie)=>Xr(J,Ie,Q,se))),S},[rs,Q,se]),ze=i.useMemo(()=>t.jsx(ws,{icon:"chat-new",mobileVariant:s,onClick:()=>st(),children:"New session"}),[s,st]),bt=i.useMemo(()=>le.find(S=>S.id===x)??null,[le,x]),Qe=i.useCallback(S=>{x&&Pe(x,{label:S.label,defaultModel:S.defaultModel??null})},[x,Pe]),os=i.useCallback(()=>{const S=Mn.getState();if(S.available&&S.info){V(!0);return}ut.checkForUpdates().then(()=>{const{available:Y,error:J}=Mn.getState();if(J){oe.error("Failed to check for updates",{description:J});return}if(!Y){oe.success("You are on the latest version");return}V(!0)})},[ut]),xt=Ic(),uo=i.useCallback(()=>{if(s&&et(!1),r?.(),xt?.openSettings){xt.openSettings();return}Be(!0)},[xt,s,r,et,Be]),Ga=ut.available&&(ut.runtimeType==="desktop"||ut.runtimeType==="web"),Ka=De(S=>S.deleteSession),fo=De(S=>S.deleteSessions),Wa=De(S=>S.archiveSession),ho=De(S=>S.archiveSessions),Ha=De(S=>S.unarchiveSession),Ya=De(S=>S.unarchiveSessions),{copiedSessionId:qa,handleSessionSelect:Qa,handleSessionDoubleClick:Va,handleSaveEdit:Ja,handleCancelEdit:Xa,handleShareSession:Za,handleCopyShareUrl:el,handleCopySessionId:tl,handleUnshareSession:sl,handleDeleteSession:nl,handleRestoreSession:rl,confirmDeleteSession:ol}=Df({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:Ce,setSessionSwitcherOpen:et,setCurrentSession:$t,updateSessionTitle:Ns,shareSession:Tt,unshareSession:Hs,deleteSession:Ka,deleteSessions:fo,archiveSession:Wa,archiveSessions:ho,unarchiveSession:Ha,childrenMap:ye,showDeletionDialog:kt,setDeleteSessionConfirm:Ne,deleteSessionConfirm:G,setEditingId:g,setEditTitle:w,editingId:p,editTitle:m}),il=i.useCallback(()=>{if(!ee)return;const{scopeKey:S,folderId:Y}=ee;Fe(null),Oe(S,Y)},[ee,Oe]),po=i.useCallback(()=>{Ss.requestDirectoryDialog()},[]),al=i.useCallback(S=>{A(Y=>{const J=Pd(Y,S);try{j.setItem(li,JSON.stringify(Array.from(J)))}catch{}return J})},[j]),mo=i.useCallback((S,Y)=>{if(!S)return null;Y&<.has(Y)&&St(Y);const J=wt(S,"New folder",Y);return U(J.id),W(J.name),J},[lt,St,wt]),Xs=At(Qa),ll=At(Va),cl=At(Ja),dl=At(Xa),ul=At(Za),fl=At(el),hl=At(tl),pl=At(sl),ml=At(nl),gl=At(rl),sr=At(mo),go=i.useCallback((S,Y)=>{_(J=>{const Ie=new Map(J);return Ie.set(S,Y+7),Ie})},[]),wn=i.useCallback(S=>{_(Y=>{if(!Y.has(S))return Y;const J=new Map(Y);return J.delete(S),J})},[]),bo=i.useCallback(S=>{_(Y=>{let J=!1;const Ie=new Map(Y),We=`${S}:`;for(const Ve of Ie.keys())Ve.startsWith(We)&&(Ie.delete(Ve),J=!0);return J?Ie:Y})},[]),bl=i.useCallback(S=>{be.current=Date.now()+150,bo(S),C(Y=>{const J=new Set(Y);J.has(S)?J.delete(S):J.add(S);try{j.setItem(ri,JSON.stringify(Array.from(J)))}catch{}return vn(J),J})},[bo,j,vn]),is=i.useMemo(()=>le.map(S=>({...S,normalizedPath:ke(S.path)})).filter(S=>!!S.normalizedPath),[le]),xl=i.useMemo(()=>is.map(S=>S.normalizedPath),[is]),xo=Rc(e?xl:pr);Lf({enabled:e,normalizedProjects:is,gitRepoStatus:xo,setProjectRepoStatus:M,setProjectRootBranches:Re});const yo=i.useMemo(()=>Wf(ft,is,gt,Qt),[Qt,gt,is,ft]);zf({enabled:e,hasAuthoritativeGlobalSessions:Mt,sessions:Xn});const{getSessionsForProject:yl,getArchivedSessionsForProject:vl}=Bf({ownership:yo});yf({enabled:e,normalizedProjects:is,ownership:yo,hasAuthoritativeGlobalSessions:Mt,isWorktreeTopologyLoading:Zn,unresolvedWorktreeProjectPaths:ns,foldersMap:Ut,createFolder:wt,addSessionToFolder:xe});const vo=i.useRef(!1);Le&&D.has(Le)&&(vo.current=!!D.get(Le));const wl=pp(S=>S.showArchivedSessions),nr=pt(S=>S.manualProjectOrder),wo=i.useRef(new Set),Sn=Md(wo.current,v,"project");wo.current=Sn;const rr={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:qs,catalogSessions:Ze,archivedSessions:Qt,projects:le,activeProjectId:Le,manualProjectOrder:nr,currentDirectory:pe,availableWorktreesByProject:gt,pinnedSessionIds:Q,sessionOrderRanks:se,foldersMap:Ut,collapsedFolderIds:lt,gitBranches:ps,gitRepoStatus:xo,updateStore:ut,showArchivedSessions:wl,projectRepoStatus:D,projectRootBranches:je,resolvedWorktreeTopologyKey:yn,unresolvedWorktreeProjectPaths:ns,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:p,editTitle:m,editingProjectDialogId:x,expandedParents:v,collapsedProjects:N,visibleSessionCountByGroup:B,updateDialogOpen:K,openSidebarMenuKey:O,renamingFolderId:P,renameFolderDraft:ne,deleteSessionConfirm:G,deleteFolderConfirm:ee,bulkDeleteConfirm:F,collapsedGroups:me},So=i.useRef(null),jo=So.current;if(jo){let S=!1;for(const Y of Object.keys(rr))Object.is(jo[Y],rr[Y])||(_t(`ui.session_sidebar.source.${Y}`),S=!0);S||_t("ui.session_sidebar.source.parent_or_context")}So.current=rr;const Sl=i.useMemo(()=>{const S=new Map(nr.map((Y,J)=>[Y,J]));return[...is].sort((Y,J)=>(S.get(Y.id)??1/0)-(S.get(J.id)??1/0))},[nr,is]),{projectSections:Ot,groupSearchDataByGroup:Co,sectionsForRender:jl,flatSectionsForRender:or,searchMatchCount:Cl}=wf({normalizedProjects:Sl,getSessionsForProject:yl,getArchivedSessionsForProject:vl,availableWorktreesByProject:gt,projectRepoStatus:D,projectRootBranches:je,lastRepoStatus:vo.current,buildGroupedSessions:Vs,hasSessionSearchQuery:Xe,normalizedSessionSearchQuery:at,filterSessionNodesForSearch:Qs,buildGroupSearchText:tr,foldersMap:Ut}),jn=i.useMemo(()=>{const S=ft.filter(J=>Vn(an(J),Z));if(S.length===0)return null;const Y=Vs(S,"~",[],null,!1).map(J=>Xe?{...J,sessions:Qs(J.sessions,at)}:J).filter(J=>J.sessions.length>0&&!J.isArchivedBucket);return Y.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Y}},[Vs,Qs,Xe,Z,at,ft]),kl=i.useMemo(()=>{if(!Xe||!jn)return 0;const S=Y=>Y.reduce((J,Ie)=>J+1+S(Ie.children),0);return jn.groups.reduce((Y,J)=>Y+S(J.sessions),0)},[jn,Xe]),Al=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:Nl}=vf(L),ko=i.useRef(!1);i.useEffect(()=>{if(ko.current||Ot.length===0)return;const S=Ot.flatMap(Y=>Y.groups.filter(J=>J.isArchivedBucket).map(J=>`${Y.project.id}:${J.id}`));S.length>0&&Ue(Y=>new Set([...Y,...S])),ko.current=!0},[Ot]);const{filteredSectionsForSidebarRender:Il,totalSessionCount:Rl,sessionCountByProject:Dl,hasActiveSessionByProject:El,activeDirectoriesByProject:Zs,hasUnseenByProject:Pl}=dp({projectSections:Ot,flatSectionsForRender:or,sectionsForRender:jl,selectedSpaceId:y,selectedWorktreePath:k,homeDirectory:Z,activeSessionIdSet:we,unreadSessionIdSet:ae}),ir=i.useCallback(S=>{if(Ds.getState().selectSpace(S),!S)return;Ee(S);const Y=Ot.find(We=>We.project.id===S),J=Y?.groups.find(We=>We.isMain),Ie=J?.sessions[0]?.session;Ie?Xs(Ie.id,J?.directory??Y?.project.normalizedPath??null,{keepPanelOpen:!0}):Y&&st({selectedProjectId:S,directoryOverride:Y.project.normalizedPath})},[st,Ot,Ee,Xs]),Ml=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",Tl=s?"size-5":"h-4.5 w-4.5",Cn=At((S,Y=0,J,Ie,We=!1,Ve,Kt="project",Rs)=>t.jsx(qh,{node:S,depth:Y,groupDirectory:J,projectId:Ie,archivedBucket:We,pinnedSessionIds:Q,expandedParents:Sn,hasSessionSearchQuery:Xe,normalizedSessionSearchQuery:at,editingId:p,setEditingId:g,editTitle:m,setEditTitle:w,handleSaveEdit:cl,handleCancelEdit:dl,toggleParent:al,handleSessionSelect:Xs,handleSessionDoubleClick:ll,togglePinnedSession:H,handleShareSession:ul,copiedSessionId:qa,handleCopyShareUrl:fl,handleCopySessionId:hl,handleUnshareSession:pl,openSidebarMenuKey:O,setOpenSidebarMenuKey:T,renamingFolderId:P,getFoldersForScope:ss,getSessionFolderId:zt,removeSessionFromFolder:Ye,addSessionToFolder:xe,createFolderAndStartRename:sr,handleDeleteSession:ml,handleRestoreSession:gl,mobileVariant:s,alwaysShowActions:Ft,allowQuickArchiveAction:er,renderSessionNode:Cn,secondaryMeta:Ve,renderContext:Kt,subtreeContainsEditing:Rs?.subtreeContainsEditing??mp,menuOpenSessionId:Rs?.menuOpenSessionId??null,nodeStructureKey:Rs?.nodeStructureKey??"",childRenderExtrasFor:Rs?.childRenderExtrasFor})),Fl=i.useMemo(()=>{const S=new Map;return or.forEach(Y=>{const J=Y.groups.find(Ie=>!Ie.isArchivedBucket);J?.folderScopes&&J.folderScopes.length>0&&S.set(Y.project.id,J.folderScopes)}),S},[or]),Ol=i.useCallback((S,Y)=>{const J=[];return Y.forEach(Ie=>{Ie.isArchivedBucket||(J.push(Ie.directory),Ie.folderScopes?.forEach(We=>J.push(We.directory)))}),t.jsx(tp,{directories:J})},[]),Ao=i.useCallback(S=>{wn(S),Ue(Y=>{const J=new Set(Y);return J.has(S)?J.delete(S):J.add(S),J})},[wn]),Ll=i.useCallback((S,Y,J,Ie,We,Ve,Kt)=>t.jsx(dh,{group:S,groupKey:Y,projectId:J,hideGroupLabel:Ie,dragHandleProps:We,compactBodyPadding:Ve,hasSessionSearchQuery:Xe,normalizedSessionSearchQuery:at,groupSearchDataByGroup:Co,visibleSessionCount:B.get(Y),collapsedGroups:me,hideDirectoryControls:a,collapsedFolderIds:lt,toggleFolderCollapse:St,renameFolder:ve,deleteFolder:Oe,showDeletionDialog:kt,setDeleteFolderConfirm:Fe,renderSessionNode:Cn,showMoreGroupSessions:go,resetGroupSessionLimit:wn,mobileVariant:s,alwaysShowActions:Ft,activeProjectId:Le,setActiveProjectIdOnly:Ee,setActiveMainTab:Ce,setSessionSwitcherOpen:et,openNewSessionDraft:st,addSessionToFolder:xe,createFolderAndStartRename:sr,renamingFolderId:P,renameFolderDraft:ne,setRenameFolderDraft:W,setRenamingFolderId:U,pinnedSessionIds:Q,expandedParents:Sn,sessionOrderIndex:ie,editingId:p,editTitle:m,openSidebarMenuKey:O,activeActivitySessionIds:we,unreadActivitySessionIds:ae,onToggleCollapsedGroup:Ao,scrollContainerRef:Kt}),[Xe,at,Co,B,me,a,lt,St,ve,Oe,kt,Cn,go,wn,s,Ft,Le,Ee,Ce,et,st,xe,sr,P,ne,Q,Sn,ie,p,m,O,we,ae,Ao]),No=!!(P||p||x),{selectionModeEnabled:ar,hasSelection:Io,selectedIdsSize:Bl,bulkScopeIsArchived:_l,derivedSelectionScope:Ul,bulkScopeFolders:zl,bulkCanRemoveFromFolder:$l,handleToggleSelectionMode:Gl,handleExitSelectionMode:Kl,handleBulkMoveToFolder:Wl,handleBulkCreateFolderAndMove:Hl,handleBulkRemoveFromFolder:Yl,handleBulkDelete:ql,handleBulkRestore:Ql,confirmBulkDelete:Vl}=fp({isInlineEditing:No,showDeletionDialog:kt,foldersMap:Ut,folderScopesByProject:Fl,addSessionsToFolder:Me,removeSessionsFromFolders:ct,createFolderAndStartRename:mo,archiveSessions:ho,unarchiveSessions:Ya,deleteSessions:fo,setBulkDeleteConfirm:z}),Ro=i.useCallback(()=>{ce.getState().closeMainSurfaces(),Ce("chat"),s&&et(!1),nt(),r?.()},[s,r,nt,Ce,et]),Jl=i.useCallback((S,Y)=>{const J=le.find(Ve=>Ve.id===S);if(!J)return;const Ie=ke(Y.path)?.toLowerCase(),We=!!(Ie&&Zs.get(S)?.has(Ie));q({projectId:S,projectPath:J.path,worktree:Y,hasActiveSession:We})},[Zs,le]),Xl=i.useCallback(async({force:S})=>{const Y=_e;if(!Y)return;const J=ke(Y.worktree.path)?.toLowerCase();if(!!(J&&Zs.get(Y.projectId)?.has(J))){q({...Y,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!Pt.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Pt.deleteGitWorktree(Y.projectPath,{directory:Y.worktree.path,force:S}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let Ve=await ms(Y.projectPath,Pt);const Kt=ke(Y.worktree.path);Ve!==null&&Kt!==null&&Ve.some(ec=>ke(ec.path)===Kt)&&(Ve=await ms(Y.projectPath,Pt));const Rs=Kt!==null&&ke(pe)===Kt,Zl=Kt!==null&&y===Y.projectId&&ke(k)===Kt;(Rs||Zl)&&ir(Y.projectId),q(null),Ve===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(We){const Ve=We instanceof Error?We.message:"Try again.";oe.error("Failed to close worktree.",{description:Ve})}},[Zs,_e,pe,Pt,ir,ms,y,k]);return t.jsx(Dc,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:h,className:$("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(jf,{projectSections:Ot,activeProjectId:Le,initialActiveSessionByProject:ue,persistActiveSessionByProject:fe,handleSessionSelect:Xs,mobileVariant:s,openNewSessionDraft:nt,setActiveMainTab:Ce,setSessionSwitcherOpen:et}),!a&&!s?t.jsx(fh,{onNewSession:Ro,showSidebarToggle:!0}):null,t.jsx(uh,{hideDirectoryControls:a,handleOpenDirectoryDialog:po,onOpenArchive:()=>{s&&et(!1),Et(!0)},onOpenSettings:s?uo:void 0,onOpenInstances:s?xt?.openInstances:void 0,instanceLabel:s?xt?.instanceLabel:void 0,onOpenUpdate:s?xt?.openUpdate:void 0,headerActionIconClass:Tl,headerActionButtonClass:Ml,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:b,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:Xe,searchMatchCount:Cl+(y===null?kl:0),selectionModeEnabled:ar,onToggleSelectionMode:Gl,mobileVariant:s}),tt==="error"||tt==="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&&Ot.length>0?t.jsx(mh,{projects:Ot.map(S=>S.project),selectedProjectId:y,selectedWorktreePath:k,worktreesByProject:gt,worktreeErrorsByProject:de,onSelectProject:ir,onSelectWorktree:(S,Y)=>{Ds.getState().selectWorktree(S,Y),Ee(S);const We=Ot.find(Ve=>Ve.project.id===S)?.groups.find(Ve=>ke(Ve.directory)===ke(Y))?.sessions[0]?.session;We?Xs(We.id,Y,{keepPanelOpen:!0}):st({selectedProjectId:S,directoryOverride:Y})},onCloseWorktree:Jl,onOpenDirectoryDialog:po,onOpenProjectEditDialog:I,onRemoveProject:He,totalSessionCount:Rl,getSessionCountForProject:S=>Dl.get(S)??0,hasActiveSessionByProject:El,activeDirectoriesByProject:Zs,hasUnseenByProject:Pl,homeDirectory:Z,mobileVariant:s}):null,t.jsx(yh,{sectionsForRender:Il,allFoldersOnlySection:y===null?jn:null,projectSections:Ot,activeProjectId:Le,showOnlyMainWorkspace:l,hasSessionSearchQuery:Xe,emptyState:ze,searchEmptyState:Al,isAllFoldersView:y===null,pinnedSessionIds:Q,renderSessionNode:Cn,renderGroupSessions:Ll,homeDirectory:Z,collapsedProjects:N,hideDirectoryControls:a,projectRepoStatus:D,mobileVariant:s,alwaysShowActions:Ft,toggleProject:bl,setActiveProjectIdOnly:Ee,setActiveMainTab:Ce,setSessionSwitcherOpen:et,openNewSessionDraft:st,openProjectEditDialog:I,removeProject:He,reorderProjects:te,getOrderedGroups:Nl,setGroupOrderByProject:X,renderProjectStatusIndicator:Ol,openSidebarMenuKey:O,setOpenSidebarMenuKey:T,isInlineEditing:No}),s&&!(ar&&Io)?t.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex flex-col gap-2 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(Sa,{variant:"mobile"}),t.jsx(Te,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:Ro,"aria-label":"New session",children:t.jsx(R,{name:"chat-new",className:"size-4"})})]}):null,ar&&Io?t.jsx(up,{selectedCount:Bl,scopeKey:Ul,scopeFolders:zl,archivedBucket:_l,onMoveToFolder:Wl,onCreateFolderAndMove:Hl,onRemoveFromFolder:Yl,canRemoveFromFolder:$l,onRestore:Ql,onDelete:ql,onDone:Kl}):null,s?null:t.jsx(gh,{onOpenSettings:uo,onOpenShortcuts:Je,onOpenAbout:()=>{vt("about"),Be(!0)},onOpenUpdate:os,showRuntimeButtons:!0,showUpdateButton:Ga}),t.jsx(ep,{updateDialogOpen:K,setUpdateDialogOpen:V,updateStore:ut,editingProject:bt,setEditingProjectDialogId:I,handleSaveProjectEdit:Qe,deleteSessionConfirm:G,setDeleteSessionConfirm:Ne,showDeletionDialog:kt,setShowDeletionDialog:ts,confirmDeleteSession:ol,deleteFolderConfirm:ee,setDeleteFolderConfirm:Fe,confirmDeleteFolder:il,closeWorktreeConfirm:_e,setCloseWorktreeConfirm:q,confirmCloseWorktree:Xl,bulkDeleteConfirm:F,setBulkDeleteConfirm:z,confirmBulkDelete:Vl})]})})},Eg=i.memo(gp),ci=6,Nt=.18,sn=1.2,nn=.38,Ln=48,bp=(e,s)=>e==="left"?s<0:s>0,Pg=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Mg=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,di=(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)),Tg=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<-Nt:c>Nt,u=s==="left"?c>Nt:c<-Nt;return d||!u&&a<nn}return Math.abs(n)>=Ln&&Math.abs(r)<=Math.abs(n)*sn&&bp(s,n)},xp=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:o,progress:a}=e,l=r/Math.max(1,o);return s==="left"?n?l<-Nt?!1:l>Nt?!0:a>nn:l>Nt?!0:l<-Nt?!1:a>nn:n?l>Nt?!1:l<-Nt?!0:a>nn:l<-Nt?!0:l>Nt?!1:a>nn},yp='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',vp=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(yp);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},Bn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Vr=512*1024,wp=new TextEncoder,Sp=new TextDecoder,mr=e=>{const s=wp.encode(e);if(s.byteLength<=Vr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-Vr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:Sp.decode(r),byteLength:r.byteLength}},Es=(e,s)=>`${e}\0${s}`,gr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},jp="terminal-store";let ui=!1,fi=0;const Pn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(fi+=1,`tab-${Date.now().toString(36)}-${fi.toString(36)}`),br=e=>typeof e=="object"&&e!==null,Cp=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 kp=/^Terminal(?: (\d+))?$/,Ap=e=>{let s=0;for(const n of e){const r=kp.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}`},xr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),yr=e=>({tabs:[e],activeTabId:e.id}),Lt=(e,s)=>e.tabs.findIndex(n=>n.id===s);let vr=null,wr=null;const Np=e=>{if(wr&&vr?.sessions===e.sessions&&vr.nextTabId===e.nextTabId)return wr;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 vr={sessions:e.sessions,nextTabId:e.nextTabId},wr=s,s},Ip=()=>{const e=jd(()=>dd());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=Ks()($i(so((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=Pn(),c=xr(l,"Terminal");return a.set(r,yr(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))??Bn,createTab:n=>{const r=rt(n);if(!r)return"tab-invalid";const o=Pn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Ap(c?.tabs??[]),f=xr(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,yr(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||Lt(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=Lt(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=Lt(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=Lt(c,r);if(d<0)return a;const u=c.tabs.filter(m=>m.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,m])=>!(m.directory===o&&m.tabId===r))),h=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,b=Es(o,r),p=a.buffers.has(b)?gr(a.buffers,m=>m===b):null;if(u.length===0){const m=Pn(),w=xr(m,"Terminal");return l.set(o,yr(w)),{sessions:l,nextTabId:a.nextTabId+1,...p?{buffers:p}:{},...h?{projectActionRuns:f}:{}}}let g=c.activeTabId;return c.activeTabId===r&&(g=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:g}),{sessions:l,...p?{buffers:p}:{},...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=Lt(d,r);if(u<0)return l;const f=d.tabs[u],h=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,p={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},g=Es(a,r),m=h&&l.buffers.has(g)?gr(l.buffers,x=>x===g):null,w=[...d.tabs];return w[u]=p,c.set(a,{...d,tabs:w}),{sessions:c,...m?{buffers:m}:{}}})},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=Lt(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=Lt(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||Lt(d,r)<0)return c;const u=Es(l,r),f=c.buffers.get(u)??Bn;if(f.lastSequence>a)return c;const h=mr(o);if(f.lastSequence===a&&f.byteLength===h.byteLength&&f.chunks.map(g=>g.data).join("")===h.text)return c;const b=c.nextChunkId,p=new Map(c.buffers);return p.set(u,{chunks:h.text?[{id:b,data:h.text,byteLength:h.byteLength}]:[],byteLength:h.byteLength,lastSequence:a}),{buffers:p,nextChunkId:h.text?b+1:b}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=rt(n);e(d=>{const u=d.sessions.get(c);if(!u||Lt(u,r)<0)return d;const f=Es(c,r),h=d.buffers.get(f)??Bn;if(a!==void 0&&a<=h.lastSequence)return d;const b=d.nextChunkId,p=mr(o),g=l!==void 0&&l!==o?mr(l).text:void 0,m={id:b,data:p.text,...g!==void 0?{replayData:g}:{},byteLength:p.byteLength},w=[...h.chunks,m];let x=h.byteLength+m.byteLength;for(;x>Vr&&w.length>1;){const v=w.shift();if(!v)break;x-=v.byteLength}const I=new Map(d.buffers);return I.set(f,{chunks:w,byteLength:x,lastSequence:a??h.lastSequence}),{buffers:I,nextChunkId:b+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=Lt(u,r);if(f<0)return c;const h=u.tabs[f],b=a.autoOpened??h.previewAutoOpened,p=a.locked??h.previewUrlLocked;if(h.previewUrl===o&&h.previewAutoOpened===b&&h.previewUrlLocked===p)return c;const g=[...u.tabs];return g[f]={...h,previewUrl:o,previewAutoOpened:b,previewUrlLocked:p},d.set(l,{...u,tabs:g}),{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=Lt(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=gr(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:jp,storage:Ip(),partialize:Np,merge:(e,s)=>{if(!br(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"||!br(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],h=[],b=new Map;for(const w of f){if(!br(w))continue;const x=typeof w.id=="string"?w.id:null;if(!x)continue;const I=Cp(x);I!==null&&(o=Math.max(o,I));const v=I===null?x:Pn();b.set(x,v),h.push({id:v,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof w.createdAt=="number"?w.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(h.length===0)continue;const p=typeof u.activeTabId=="string"?u.activeTabId:null,g=p?b.get(p)??p:null,m=g?h.some(w=>w.id===g):!1;r.set(d,{tabs:h,activeTabId:m?g: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"&&!ui){ui=!0;const e=he.persist,s=()=>{he.getState().hasHydrated||he.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Rp(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 Sr(e,s,n){const o=`${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",cursorInactiveStyle:"none",fontSize:s,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,selectionInactiveBackground:n.selectionInactiveBackground,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}}}const Dp=(e,s)=>{const n=`${e??""} ${s??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},Ep=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),Pp=(e,s,n)=>{if(e.altKey)return null;const r=Ep(e);return s==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?n?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?n?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?n?"copy":"ignore":null},rn=e=>typeof e=="string"&&e.trim().length>0;async function hi(e){return rn(e)?(await us(e)).ok:!1}async function Mp(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const Tp=(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))}},Fp=(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 Op=null;const Lp=()=>Op??=Promise.all([cs(()=>import("./vendor-xterm-xterm-CrXqRur4.js"),__vite__mapDeps([112,113])),cs(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,s])=>({Xterm:e,Fit:s})),Bp=2e3,_p=()=>{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,Bp))]).then(()=>{})},Up=(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))}},Ua=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 b=i.useRef(null),p=i.useRef(null),g=i.useRef(null),m=i.useRef(n),w=i.useRef(r),x=i.useRef(o),I=i.useRef(a),v=i.useRef(l),A=i.useRef(null),j=i.useRef(null),N=i.useRef(null),C=i.useRef(""),y=i.useRef(!1),k=i.useRef(0),D=i.useRef(f),M=i.useRef(!1),[B,_]=i.useState(0),[K,V]=i.useState(0),[O,T]=i.useState(!1),[P,U]=i.useState(!1);m.current=n,w.current=r,D.current=f,x.current=o,I.current=a,v.current=l,i.useLayoutEffect(()=>{const q=b.current;if(!q)return;const F=Up(q,a,l);j.current=F,F&&w.current(F.cols,F.rows)},[a,l]);const ne=i.useCallback(()=>{const q=b.current,F=p.current;if(!q||!F||!g.current||!D.current)return;const z=q.getBoundingClientRect();if(!(z.width<24||z.height<24))try{g.current.fit();const Q={cols:F.cols,rows:F.rows};(!A.current||A.current.cols!==Q.cols||A.current.rows!==Q.rows)&&(A.current=Q,w.current(Q.cols,Q.rows)),M.current||(M.current=!0,_(se=>se+1))}catch{}},[]),W=i.useCallback(()=>{if(y.current||!C.current||!p.current)return;const q=p.current,F=C.current;if(C.current="",!F)return;y.current=!0;const z=k.current;q.write(F,()=>{p.current!==q||k.current!==z||(y.current=!1,C.current&&W())})},[]),G=i.useCallback(()=>{N.current=null,C.current="",y.current=!1,k.current+=1;const q=p.current;if(!q){V(F=>F+1);return}try{q.reset()}catch{V(F=>F+1)}},[]),Ne=i.useCallback(q=>{q?.preventDefault(),U(rn(p.current?.getSelection())),T(!0)},[]),ee=i.useCallback(q=>{q.stopPropagation();const F=p.current,z=F?.getSelection()??"";F?.focus(),rn(z)&&hi(z)},[]),Fe=i.useCallback(q=>{q.stopPropagation();const F=p.current;F?.focus(),Mp().then(z=>{z&&p.current===F&&F&&F.paste(z)})},[]),_e=i.useCallback(q=>{q.stopPropagation();const F=p.current;F?.focus();try{F?.selectAll()}catch{}U(rn(F?.getSelection()))},[]);return i.useEffect(()=>{const q=b.current;if(!q)return;let F=!1,z=null,Q=null,se=null,Se=null,ge=[];const we=()=>{z&&D.current&&(z.options.cursorBlink=!0)},re=me=>{me.relatedTarget instanceof Node&&q.contains(me.relatedTarget)||z&&(z.options.cursorBlink=!1)},ae=()=>{z&&D.current&&q.contains(document.activeElement)&&(z.options.cursorBlink=!0)},H=()=>{z&&(z.options.cursorBlink=!1)};return q.addEventListener("focusin",we),q.addEventListener("focusout",re),window.addEventListener("focus",ae),window.addEventListener("blur",H),Promise.all([Lp(),_p()]).then(([{Xterm:me,Fit:Ue}])=>{if(F)return;const L=x.current,X=I.current,ue=v.current;z=new me.Terminal({...Sr(X,ue,L),...j.current??{}});const fe=new Ue.FitAddon;z.loadAddon(fe),z.open(q),p.current=z,g.current=fe;const je=typeof navigator>"u"?"other":Dp(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Re=z;z.attachCustomKeyEventHandler(be=>{if(be.type!=="keydown")return!0;const Z=Re.getSelection(),pe=Pp({key:be.key,code:be.code,ctrlKey:be.ctrlKey,shiftKey:be.shiftKey,metaKey:be.metaKey,altKey:be.altKey},je,rn(Z));return pe==="copy"?(hi(Z),!1):pe!=="ignore"}),ge=[z.onData(be=>m.current(be))],Q=new ResizeObserver(()=>{se&&clearTimeout(se),se=setTimeout(ne,80)}),Q.observe(q),ne(),Se=requestAnimationFrame(ne)}),()=>{F=!0;const me=document.activeElement;me instanceof HTMLElement&&q.contains(me)&&(me.blur(),window.Capacitor?.getPlatform?.()==="android"&&cs(async()=>{const{Keyboard:L}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:L}},__vite__mapDeps([114,115])).then(({Keyboard:L})=>L.hide()).catch(()=>{})),Q?.disconnect(),se&&clearTimeout(se),Se!==null&&cancelAnimationFrame(Se),q.removeEventListener("focusin",we),q.removeEventListener("focusout",re),window.removeEventListener("focus",ae),window.removeEventListener("blur",H),ge.forEach(Ue=>Ue.dispose()),z?.dispose(),p.current=null,g.current=null,A.current=null,N.current=null,C.current="",y.current=!1,k.current+=1,M.current=!1}},[ne,K]),i.useEffect(()=>{const q=p.current;q&&(q.options.theme=Sr(a,l,o).theme,q.options.fontFamily=Sr(a,l,o).fontFamily,q.options.fontSize=l)},[a,l,o]),i.useEffect(()=>{const q=p.current,F=b.current;!q||!F||(q.options.cursorBlink=f&&document.hasFocus()&&F.contains(document.activeElement))},[f,B]),i.useEffect(()=>{if(!p.current)return;if(s.length===0){N.current!==null&&G();return}const F=N.current;let z=-1;if(F!==null){for(let Se=s.length-1;Se>=0;Se-=1){const ge=s[Se].id;if(ge===F){z=Se;break}if(ge<F)break}if(z<0){G();return}}const Q=z<0,se=z>=0?s.slice(z+1):s;C.current+=se.map(Se=>Q?Se.replayData??Se.data:Se.data).join(""),N.current=s.at(-1)?.id??null,W()},[s,W,B,G]),i.useEffect(()=>{if(!u||!f)return;const q=requestAnimationFrame(()=>p.current?.focus());return()=>cancelAnimationFrame(q)},[u,f,B,e]),i.useEffect(()=>{const q=b.current,F=p.current;if(!d||!q||!F)return;let z=null,Q=null,se="idle",Se=0,ge=0,we=0,re=0,ae=null;const H=Math.max(12,l+2),me=()=>{window.Capacitor?.getPlatform?.()==="android"&&cs(async()=>{const{Keyboard:pe}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:pe}},__vite__mapDeps([114,115])).then(({Keyboard:pe})=>pe.show()).catch(()=>{})},Ue=()=>{Q&&(clearTimeout(Q),Q=null)},L=(Z,pe)=>{const le=q.querySelector("canvas");return le?Tp(Z,pe,le.getBoundingClientRect(),F.cols,F.rows):null},X=(Z,pe)=>{const le=q.querySelector("canvas");if(!le)return;const Le=le.getBoundingClientRect(),He=Le.left+(pe.column+.5)/F.cols*Le.width,Ee=Le.top+(pe.row+.5)/F.rows*Le.height;le.dispatchEvent(new MouseEvent(Z,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:He,clientY:Ee}))},ue=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},fe=Z=>{Z.pointerType!=="touch"||z!==null||(z=Z.pointerId,se="pending",Se=Z.clientX,ge=Z.clientY,we=Z.clientY,re=0,ae=null,q.setPointerCapture(Z.pointerId),Q=setTimeout(()=>{if(Q=null,z!==Z.pointerId||se!=="pending")return;const pe=L(Se,ge);if(!pe)return;const le=F.buffer.active,Le=Math.max(0,le.length-F.rows-le.viewportY+pe.row),He=le.getLine(Le),Ee=Array.from({length:F.cols},(Ce,Be)=>He?.getCell(Be)?.getChars()??""),Pe=Fp(Ee,pe.column),te={column:Pe.startColumn,row:pe.row};ae={column:Pe.endColumn,row:pe.row},se="selecting",X("mousedown",te),X("mousemove",ae)},350))},je=Z=>{if(z!==Z.pointerId)return;if(se==="selecting"){const Le=L(Z.clientX,Z.clientY);Le&&(!ae||Le.column!==ae.column||Le.row!==ae.row)&&(ae=Le,X("mousemove",Le)),Z.cancelable&&Z.preventDefault();return}if(se==="pending"){if(Math.hypot(Z.clientX-Se,Z.clientY-ge)<8)return;Ue(),se="scrolling"}if(se!=="scrolling")return;const pe=we-Z.clientY;we=Z.clientY,re+=pe;const le=Math.trunc(re/H);le&&(F.scrollLines(le),re-=le*H),Z.cancelable&&Z.preventDefault()},Re=Z=>{if(z!==Z.pointerId)return;const pe=se==="pending",le=se==="selecting";Ue(),q.hasPointerCapture(Z.pointerId)&&q.releasePointerCapture(Z.pointerId),z=null,se="idle",le&&ue(),pe&&(F.focus(),me())},be=Z=>{if(z!==Z.pointerId)return;const pe=se==="selecting";Ue(),q.hasPointerCapture(Z.pointerId)&&q.releasePointerCapture(Z.pointerId),z=null,se="idle",pe&&ue()};return q.addEventListener("pointerdown",fe),q.addEventListener("pointermove",je,{passive:!1}),q.addEventListener("pointerup",Re),q.addEventListener("pointercancel",be),()=>{Ue(),q.removeEventListener("pointerdown",fe),q.removeEventListener("pointermove",je),q.removeEventListener("pointerup",Re),q.removeEventListener("pointercancel",be)}},[d,l,B]),i.useImperativeHandle(h,()=>({focus:()=>p.current?.focus(),fit:ne,getSelection:()=>{const q=p.current,F=q?.getSelectionPosition(),z=q?.getSelection()??"";return!F||!z.trim()?null:{text:z,startLine:F.start.y+1,endLine:F.end.y+1}}}),[ne]),t.jsxs(oo,{open:O,onOpenChange:T,children:[t.jsx(io,{render:t.jsx("div",{ref:b,"data-terminal-owner":"main",className:$("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:Ne})}),t.jsxs(ao,{className:"min-w-[180px]",children:[t.jsxs(Os,{disabled:!P,onClick:ee,children:[t.jsx(R,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),t.jsxs(Os,{onClick:Fe,children:[t.jsx(R,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),t.jsx(va,{}),t.jsx(Os,{onClick:_e,children:"Select All"})]})]})});Ua.displayName="TerminalViewport";const zp=({directory:e,tabId:s,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:a,terminal:l,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:h,onInput:b,controllerRef:p})=>{const g=he(v=>e&&s?v.getBuffer(e,s).chunks:Bn.chunks),m=i.useRef(null),w=o&&a,x=i.useCallback(v=>{m.current=v,p&&(p.current=o?v:p.current),!o&&p&&p.current===v&&(p.current=null)},[p,o]);i.useEffect(()=>{if(!o||!a)return;const v=requestAnimationFrame(()=>{m.current?.fit()});return()=>cancelAnimationFrame(v)},[o,a,r,n]);const I=i.useCallback((v,A)=>{if(!o)return;const j=h.current;(!j||j.cols!==v||j.rows!==A)&&(h.current={cols:v,rows:A}),n&&l.resize({sessionId:n,cols:v,rows:A}).catch(()=>{})},[o,h,n,l]);return t.jsx("div",{className:$("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:t.jsx(Ua,{ref:x,sessionKey:r,chunks:g,onInput:b,onResize:I,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:w,isVisible:w},r)})},$p=({items:e,activeId:s,onSelect:n,onClose:r,onCreate:o,disabled:a=!1})=>{const l=e.find(c=>c.id===s)??e[0]??null;return t.jsxs(It,{modal:!1,children:[t.jsx(Rt,{asChild:!0,children:t.jsxs("button",{type:"button",disabled:a,title:l?`Switch terminal, current: ${l.label}`:"Switch terminal","aria-label":l?`Switch terminal, current: ${l.label}`:"Switch terminal",className:$(Ci({size:"sm"}),"min-w-0 max-w-full"),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l?.icon??t.jsx(R,{name:"terminal",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:l?.label??"Terminal"})]}),t.jsx(R,{name:"arrow-down-s",className:"size-3.5 shrink-0"})]})}),t.jsxs(Dt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(l?.id??s);return t.jsxs(ot,{title:c.title??c.label,onClick:()=>n(c.id),className:"group/tab min-w-0",children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,t.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),d?t.jsx(R,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,t.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:u=>{u.preventDefault(),u.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:t.jsx(R,{name:"close",className:"size-3"})})]},c.id)}),t.jsx(Cs,{}),t.jsxs(ot,{onClick:o,children:[t.jsx(R,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},Gp=({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(Te,{type:"button",size:a,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[t.jsx(R,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Te,{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(Te,{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(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[t.jsx(R,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[t.jsx(R,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[t.jsx(R,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[t.jsx(R,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[t.jsx(R,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Kp="\x1B",Wp=new RegExp(`${Kp}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Hp=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Yp=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,qp=/Serving HTTP on .*? port (\d{2,5})/i,Qp=new Set([".",",",";",":","!","?"]),Vp=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(Qp.has(n)){s=s.slice(0,-1);continue}break}return s},pi=e=>{let s=Vp(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},Jp=e=>{if(!e)return null;const s=e.replace(Wp,""),n=s.match(qp);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(`
|
|
46
|
-
`);for(const o of r){if(!Yp.test(o))continue;const a=Array.from(o.matchAll(Hp));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(pi(c[1])).port}catch{return!1}});return pi((l??a[0])[1])}return null},Xp=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 Ct("/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)}},Zp={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},em=(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 Zp[e]},za=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},tm=(e,s)=>e&&(s==="ctrl"?za(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),$a={cols:80,rows:24},mi={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class sm{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,`
|
|
47
|
-
`),l=a.split(`
|
|
48
|
-
`),c=a.endsWith(`
|
|
49
|
-
`)?l.join(`
|
|
50
|
-
`):l.slice(0,-1).join(`
|
|
51
|
-
`);if(this.tail=a.endsWith(`
|
|
52
|
-
`)?"":(l[l.length-1]??"").slice(-1024),!c)return;const d=Jp(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Xp(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const h=he.getState().getDirectoryState(s)?.tabs.find(b=>b.id===n);!h||h.previewUrlLocked||h.previewUrl===d||o(s,n,d,{locked:!1,autoOpened:!1})})}}const nm=(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"?za(o):null};function rm({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:b,tabs:p}){const g=he(F=>F.ensureDirectory),m=he(F=>F.setTabSessionId),w=he(F=>F.setTabLifecycle),x=he(F=>F.setConnecting),I=he(F=>F.appendToBuffer),v=he(F=>F.replaceBuffer),A=he(F=>F.setTabPreviewUrl),[j,N]=i.useState(null),[C,y]=i.useState(!1),[k,D]=i.useState(!1),M=i.useRef(new Map),B=i.useRef(null),_=i.useRef(n),K=i.useRef(r),V=i.useRef(s),O=i.useRef(null),T=i.useRef(new Set),P=i.useRef(new Map),U=i.useRef(p),ne=i.useRef(l),W=i.useRef(a),G=i.useRef(e);U.current=p,ne.current=l,W.current=a,G.current=e;const Ne=i.useCallback(()=>{const F=_.current;F&&P.current.get(F)?.reset()},[]);i.useEffect(()=>{K.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),i.useEffect(()=>{_.current=n},[n]),i.useEffect(()=>{V.current=s},[s]);const ee=i.useCallback(()=>{for(const F of M.current.values())try{F()}catch{}M.current.clear(),B.current=null,D(!1)},[]);i.useEffect(()=>()=>{ee(),K.current=null},[ee]);const Fe=i.useCallback((F,z,Q)=>{let se=P.current.get(z);se||(se=new sm,P.current.set(z,se)),se.scan(F,z,Q,A)},[A]),_e=i.useCallback((F,z,Q)=>{if(M.current.has(Q)){B.current=Q;return}const se=Lo(),Se=()=>Lo()===se&&V.current===F&&he.getState().getDirectoryState(F)?.tabs.find(we=>we.id===z)?.terminalSessionId===Q,ge=e.connect(Q,{onEvent:we=>{if(Se())switch(we.type){case"snapshot":{_.current===z&&K.current===Q?(x(F,z,!1),N(null),y(!1),D(!1),b()):x(F,z,!1),v(F,z,we.data??"",we.sequence??0),Fe(F,z,we.data??""),we.status==="exited"&&w(F,z,"exited");break}case"reconnecting":{_.current===z&&(N(null),y(!1),D(!0));break}case"data":{we.data&&(I(F,z,we.data,we.sequence,we.replayData),Fe(F,z,we.data));break}case"exit":{const re=typeof we.exitCode=="number"?we.exitCode:null,ae=typeof we.signal=="number"?we.signal:null,me=!!he.getState().getDirectoryState(F)?.tabs.find(Ue=>Ue.id===z)?.label?.startsWith("Action:");I(F,z,`\\r\\n[Process exited${re!==null?` with code ${re}`:""}${ae!==null?` (signal ${ae})`:""}]\\r\\n`),w(F,z,"exited"),_.current===z&&(x(F,z,!1),N(me?null:"Terminal session ended"),y(!1),D(!1));break}}},onError:(we,re)=>{if(!Se())return;const ae=_.current===z;if(!re){ae&&(N(null),y(!1));return}if(we.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(F)?.tabs.find(me=>me.id===z)?.label?.startsWith("Action:")){ae&&(N(null),y(!1),x(F,z,!1),D(!1)),m(F,z,null),w(F,z,"idle");return}ae&&(D(!1),N(`Connection failed: ${we.message}`),y(!0),x(F,z,!1),w(F,z,"exited"),m(F,z,null))}});M.current.set(Q,()=>ge.close()),B.current=Q},[I,b,v,Fe,x,w,m,e]),q=i.useMemo(()=>p.map(F=>`${F.id}:${F.terminalSessionId??""}`).join(","),[p]);return i.useEffect(()=>{if(!l||!a||!s)return;const F=s,z=new Set;for(const Q of p)Q.terminalSessionId&&(z.add(Q.terminalSessionId),_e(F,Q.id,Q.terminalSessionId));for(const[Q,se]of M.current)if(!z.has(Q)){try{se()}catch{}M.current.delete(Q)}},[q,p,s,l,a,_e]),i.useEffect(()=>ud(()=>{if(!ne.current||!W.current)return;const F=V.current;if(!F)return;const z=[];for(const se of U.current){if(!se.terminalSessionId)continue;he.getState().getDirectoryState(F)?.tabs.find(ge=>ge.id===se.id)?.terminalSessionId===se.terminalSessionId&&z.push({id:se.id,terminalSessionId:se.terminalSessionId})}if(M.current.clear(),B.current=null,z.length===0)return;D(!0),N(null),y(!1);for(const se of z)_e(F,se.id,se.terminalSessionId);const Q=O.current;if(Q)for(const se of z)G.current.resize({sessionId:se.terminalSessionId,...Q}).catch(()=>{})}),[_e]),i.useEffect(()=>{let F=!1;if(!l||!a)return;if(!s){N(h?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const Q=s;if(!V.current||V.current!==Q)return;if(!he.getState().getDirectoryState(Q)){g(Q);return}const Se=he.getState().getDirectoryState(Q);if(!Se||Se.tabs.length===0)return;const ge=Se.activeTabId??Se.tabs[0]?.id??null;if(!ge)return;const we=Se.tabs.find(L=>L.id===ge)??Se.tabs[0],re=we?.terminalSessionId??null,ae=we?.lifecycle??"idle",H=!!we?.label?.startsWith("Action:"),me=he.getState().getBuffer(Q,ge),Ue=me.byteLength>0||me.chunks.length>0;if(!re){if(ae==="exited"){x(Q,ge,!1);return}if(H&&Ue){x(Q,ge,!1);return}const L=`${Q}\0${ge}`;if(T.current.has(L))return;const X=O.current??$a;T.current.add(L),N(null),y(!1),D(!1),x(Q,ge,!0);try{const ue=await e.createSession({cwd:Q,sessionId:ge,cols:X.cols,rows:X.rows,shell:c,loginShell:d,...u.current});if(!he.getState().getDirectoryState(Q)?.tabs.find(Re=>Re.id===ge)){try{await e.close(ue.sessionId)}catch{}return}m(Q,ge,ue.sessionId);const je=O.current;je&&(je.cols!==X.cols||je.rows!==X.rows)&&e.resize({sessionId:ue.sessionId,...je}).catch(()=>{});return}catch(ue){const fe=he.getState().getDirectoryState(Q)?.tabs.find(je=>je.id===ge);if(!fe||fe.terminalSessionId||(x(Q,ge,!1),V.current!==Q||_.current!==ge))return;N(ue instanceof Error?ue.message:"Failed to start terminal session"),y(!0),D(!1);return}finally{T.current.delete(L)}}!re||F||(K.current=re)})(),()=>{F=!0}},[h,s,r,o,n,a,f,l,g,x,w,m,e,d,c,u]),{connectionError:j,setConnectionError:N,isFatalError:C,setIsFatalError:y,isReconnectPending:k,setIsReconnectPending:D,terminalIdRef:K,lastViewportSizeRef:O,directoryRef:V,activeTabIdRef:_,disconnectStream:ee,resetTerminalPreviewScan:Ne,startStream:_e}}function om({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),b=i.useCallback(()=>{d||h.current?.focus()},[d]),p=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 g=i.useCallback(v=>{if(!v||n)return;let A=v,j=!1;u&&v.length>0&&(A=tm(v,u),j=!0);const N=s.current;N&&(e.sendInput(N,A).catch(C=>{n||r(C instanceof Error?C.message:"Failed to send input")}),j&&(f(null),b()))},[u,b,n,r,e,s]),m=i.useCallback((v,A)=>{const j=l.current;if((!j||j.cols!==v||j.rows!==A)&&(l.current={cols:v,rows:A}),!a)return;const N=s.current;N&&e.resize({sessionId:N,cols:v,rows:A}).catch(()=>{})},[a,l,e,s]),w=i.useCallback(v=>{f(A=>A===v?null:v),b()},[b]),x=i.useCallback(v=>{const A=em(v,u);A&&(g(A),f(null),b())},[u,b,g]),I=i.useCallback(v=>{if(v.repeat)return;const A=v.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const j=A.length===1?A.toLowerCase():A;if(j in mi){v.preventDefault(),v.stopPropagation(),x(mi[j]);return}const N=nm(v,u);N&&(v.preventDefault(),v.stopPropagation(),g(N),f(null),b())},[u,b,x,g]);return i.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[u,I,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:h,focusTerminalController:b,focusTerminalWhenWindowActive:p,handleViewportInput:g,handleViewportResize:m,handleModifierToggle:w,handleMobileKeyPress:x}}function im({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:h,startStream:b,setConnectionError:p,setIsFatalError:g,setIsReconnectPending:m}){const w=he(B=>B.createTab),x=he(B=>B.setActiveTab),I=he(B=>B.closeTab),v=he(B=>B.setTabSessionId),A=he(B=>B.setTabLifecycle),[j,N]=i.useState(!1),C=i.useCallback(async()=>{if(!s||j)return;const B=he.getState().getDirectoryState(s),_=n??B?.activeTabId??B?.tabs[0]?.id??null;if(!_)return;const K=B?.tabs.find(V=>V.id===_)?.terminalSessionId??null;if(!(!K||!e.restartSession)){N(!0),p(null),g(!1),m(!1),h();try{const V=c.current??$a,O=await e.restartSession(K,{cwd:s,shell:o,loginShell:a,...V,...l.current});if(he.getState().getDirectoryState(s)?.tabs.find(P=>P.id===_)?.terminalSessionId!==K||(v(s,_,O.sessionId),A(s,_,"running"),d.current!==s||u.current!==_))return;f.current=O.sessionId,b(s,_,O.sessionId)}catch(V){if(he.getState().getDirectoryState(s)?.tabs.find(T=>T.id===_)?.terminalSessionId!==K||d.current!==s||u.current!==_)return;p(V instanceof Error?V.message:"Failed to restart terminal"),g(!1),m(!1),f.current=K,b(s,_,K)}finally{N(!1)}}},[n,u,d,s,r,j,c,h,p,g,m,A,v,b,e,l,f,a,o]),y=i.useCallback(async()=>{await C()},[C]),k=i.useCallback(()=>{if(!s)return;const B=w(s);x(s,B),p(null),g(!1),m(!1)},[w,s,x,p,g,m]),D=i.useCallback(B=>{s&&(x(s,B),p(null),g(!1),m(!1))},[s,x,p,g,m]),M=i.useCallback(B=>{if(!s)return;p(null),g(!1),m(!1);const _=he.getState().getDirectoryState(s)?.tabs.find(K=>K.id===B)?.terminalSessionId;(async()=>{_&&await e.close(_),I(s,B)})().catch(K=>p(K instanceof Error?K.message:"Terminal session ended"))},[I,s,p,g,m,e]);return{isRestarting:j,handleRestart:C,handleHardRestart:y,handleCreateTab:k,handleSelectTab:D,handleCloseTab:M}}const Fg=({visible:e,onCloseView:s,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Gs(),{currentTheme:a}=Mi(),l=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground};const{monoFont:c}=Ec(),d=ce(te=>te.terminalFontSize),u=ce(te=>te.terminalShell),f=ce(te=>te.terminalLoginShells.includes(te.terminalShell)),{isMobile:h,isTablet:b,hasTouchOnlyPointer:p}=$s(),g=h||b,m=(g||p)&&o.platform==="web",w=!0,x=ce(te=>te.showTerminalQuickKeysOnDesktop),I=g||x,v=De(te=>te.currentSessionId),A=De(te=>te.newSessionDraft),j=v!==null||A?.open===!0,N=Pc()??null,C=he(te=>N?te.sessions.get(N):void 0),y=he(te=>te.hasHydrated),k=ce(te=>te.openContextPreview),D=i.useMemo(()=>C?C.activeTabId??C.tabs[0]?.id??null:null,[C,w]),M=i.useMemo(()=>{if(C)return D?C.tabs.find(te=>te.id===D)??C.tabs[0]:C.tabs[0]},[C,D]),B=i.useMemo(()=>(C?.tabs??[]).map(te=>({icon:(()=>{const Ce=te.iconKey?dn[te.iconKey]??"terminal":"terminal";return t.jsx(R,{name:Ce,className:"h-4 w-4"})})(),id:te.id,label:te.label,title:te.label,closeLabel:"Close tab"})),[C?.tabs]),_=M?.terminalSessionId??null,K=M?.lifecycle??"idle",V=i.useMemo(()=>(C?.tabs??[]).map(te=>({id:te.id,terminalSessionId:te.terminalSessionId,label:te.label})),[C?.tabs]),O=M?.isConnecting??!1,T=M?.previewUrl??null,U=ce(te=>te.activeMainTab)==="terminal",ne=e??U,[W,G]=i.useState(ne);i.useEffect(()=>{ne&&G(!0)},[ne]);const{connectionError:Ne,setConnectionError:ee,isFatalError:Fe,setIsFatalError:_e,isReconnectPending:q,setIsReconnectPending:F,terminalIdRef:z,lastViewportSizeRef:Q,directoryRef:se,activeTabIdRef:Se,resetTerminalPreviewScan:ge,startStream:we}=rm({terminal:r,effectiveDirectory:N,activeTabId:D,terminalSessionId:_,terminalLifecycle:K,hasOpenedTerminalViewport:W,terminalHydrated:y,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:w,hasActiveContext:j,tabs:V,focusTerminalWhenWindowActive:()=>{!m&&typeof document<"u"&&document.hasFocus()&&ae.current?.focus()}}),{activeModifier:re,terminalControllerRef:ae,focusTerminalWhenWindowActive:H,handleViewportInput:me,handleModifierToggle:Ue,handleMobileKeyPress:L}=om({terminal:r,terminalIdRef:z,isReconnectPending:q,setConnectionError:ee,showQuickKeys:I,isTerminalVisible:ne,lastViewportSizeRef:Q,terminalSessionId:_,useTouchTerminalInput:m}),{isRestarting:X,handleRestart:ue,handleHardRestart:fe,handleCreateTab:je,handleSelectTab:Re,handleCloseTab:be}=im({terminal:r,effectiveDirectory:N,activeTabId:D,enableTabs:w,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:Q,directoryRef:se,activeTabIdRef:Se,terminalIdRef:z,resetTerminalPreviewScan:ge,startStream:we,setConnectionError:ee,setIsFatalError:_e,setIsReconnectPending:F});i.useEffect(()=>{if(!ne||m)return;if(typeof window>"u"){H();return}const te=window.requestAnimationFrame(()=>{H()});return()=>{window.cancelAnimationFrame(te)}},[D,H,ne,m]);const Z=i.useMemo(()=>{const te=en[cr].stack;if(typeof window>"u")return(en[c]??en[cr]).stack;const Be=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Be&&Be.trim().length>0?Be.trim():(en[c]??en[cr]).stack??te},[c]),pe=i.useMemo(()=>Rp(a),[a]),le=`${N??"no-dir"}::${D??"no-tab"}`;if(i.useEffect(()=>{if(!ne||m)return;const te=ae.current;if(!te)return;const Ce=()=>{te.fit()};if(typeof window<"u"){const Be=window.requestAnimationFrame(()=>{Ce(),H()}),vt=[220,400].map(Je=>window.setTimeout(Ce,Je));return()=>{window.cancelAnimationFrame(Be),vt.forEach(Je=>window.clearTimeout(Je))}}Ce()},[H,ne,m,ae,le,_]),i.useEffect(()=>{if(!ne||!m)return;let te=null;const Ce=()=>{te!==null&&window.cancelAnimationFrame(te),te=window.requestAnimationFrame(()=>{te=null,ae.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Ce),()=>{window.removeEventListener("oc:keyboard-settled",Ce),te!==null&&window.cancelAnimationFrame(te)}},[ne,ae,le,m]),!j)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(!N)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:ue,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Le=!_||O||X||q,He=W,Ee=C?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx($p,{items:B,activeId:D,onSelect:Re,onClose:be,onCreate:je})}),t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:$("shrink-0",g?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:je,title:"New tab","aria-label":"New tab",children:t.jsx(R,{name:"add",className:`${g?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ue()},disabled:X,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(R,{name:"restart",className:"h-4 w-4"})}),T?t.jsxs(Te,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{N&&k(N,T)},title:"Open preview pane",children:[t.jsx(R,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,Pe=t.jsx(Gp,{isTouchTerminal:g,activeModifier:re,disabled:Le,onKeyPress:L,onModifierToggle:Ue});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:$("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",g?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[Ee?n?tc.createPortal(t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ee}),n):t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ee,s?t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:s,title:"Close terminal view","aria-label":"Close terminal view",children:t.jsx(R,{name:"close",className:"h-4 w-4"})}):null]}):null,!g&&I&&w&&C?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Pe}):null,!g&&I&&!C?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Pe}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:pe.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:He&&N&&C?C.tabs.map(te=>{const Ce=te.id===D;return t.jsx(zp,{directory:N,tabId:te.id,sessionId:te.terminalSessionId,sessionKey:`${N}::${te.id}`,isActive:Ce,isTerminalVisible:ne,terminal:r,theme:pe,fontFamily:Z,fontSize:d,enableTouchScroll:m,lastViewportSizeRef:Q,onInput:me,controllerRef:ae},te.id)}):null}),!q&&Ne&&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:Ne}),Fe&&g&&t.jsx(Te,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:fe,disabled:X,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),g&&I?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:Pe})}):null]})},am=48,lm=96,yt=(e,...s)=>{try{e?.(...s)}catch{}},jr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Og=(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"?lm:am;let d=!1,u=!1,f=!1,h=null,b=!1,p=0,g=0,m=0,w=0;const x=()=>{d=!1,u=!1,f=!1,h=null},I=()=>{const k=n.current,D=h,M=b;u&&D&&(yt(D==="left"?k.onLeftProgress:k.onRightProgress,M?1:0),yt(k.onDragEnd,D,M)),x()},v=()=>{I(),u||x()},A=k=>{const D=n.current;if(D.enabled===!1){u&&h?I():x();return}if(k.touches.length!==1){u&&h?I():x();return}const M=k.touches[0],B=o.getBoundingClientRect(),_=o.clientWidth,K=!!D.leftOpen,V=!!D.rightOpen,O=T=>vp(T,o);if(K||V){if(O(k.target)){x();return}if(K&&V){const T=M.clientX<=B.left+c;M.clientX>=B.right-c?(h="right",b=!0):T?(h="left",b=!0):(h=K?"left":"right",b=!0)}else K?(h="left",b=!0):(h="right",b=!0);w=jr(h==="left"?D.leftWidth:D.rightWidth,_),w<10&&(w=_||window.innerWidth||320),w<10&&(w=320),d=!0}else{if(O(k.target)){x();return}h=null,b=!1,w=0,d=!0}p=M.clientX,g=M.clientY,m=Date.now(),u=!1,f=!1},j=k=>{if(!d)return;if(k.touches.length!==1){v();return}const D=k.touches[0],M=D.clientX-p,B=D.clientY-g;if(!f){if(Math.abs(M)<ci&&Math.abs(B)<ci)return;if(Math.abs(B)>Math.abs(M)*sn){x();return}if(!h){const V=n.current;h=M>0?"left":"right",w=jr(h==="left"?V.leftWidth:V.rightWidth,o.clientWidth),w<10&&(w=window.innerWidth||320)}if(h==="left"){if(!b&&M<=0){x();return}if(b&&M>=0){x();return}}else{if(!b&&M>=0){x();return}if(b&&M<=0){x();return}}f=!0,u=!0,yt(n.current.onDragStart,h)}if(!u)return;k.cancelable&&k.preventDefault();const _=n.current,K=di(h,b,M,w);yt(h==="left"?_.onLeftProgress:_.onRightProgress,K)},N=(k,D)=>{if(!d){x();return}const M=k-p,B=D-g;if(!h&&!b&&Math.abs(M)>=Ln&&Math.abs(B)<=Math.abs(M)*sn){const P=n.current;h=M>0?"left":"right",w=jr(h==="left"?P.leftWidth:P.rightWidth,o.clientWidth),w<10&&(w=window.innerWidth||320)}if(!h){x();return}const _=Math.max(1,Date.now()-m),K=n.current;if(!u){const P=Math.abs(M),U=Math.abs(B);P>=Ln&&U<=P*sn?h==="left"&&!b&&M>0?(yt(K.onLeftProgress,1),yt(K.onLeftOpen)):h==="right"&&!b&&M<0?(yt(K.onRightProgress,1),yt(K.onRightOpen)):yt(h==="left"?K.onLeftProgress:K.onRightProgress,b?1:0):yt(h==="left"?K.onLeftProgress:K.onRightProgress,b?1:0);const ne=h;x(),yt(K.onDragEnd,ne);return}const V=di(h,b,M,w),O=xp({side:h,isOpenAtStart:b,dx:M,dt:_,progress:V}),T=h;yt(T==="left"?O?K.onLeftOpen:K.onLeftClose:O?K.onRightOpen:K.onRightClose),x(),yt(K.onDragEnd,T,O)},C=k=>{const D=k.changedTouches[0];if(!D){x();return}const M=D.clientX-p,B=D.clientY-g;d&&(u||Math.abs(M)>=Ln&&Math.abs(B)<=Math.abs(M)*sn)&&k.cancelable&&k.preventDefault(),N(D.clientX,D.clientY)},y=()=>{v()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",j,{passive:!1}),o.addEventListener("touchend",C,{passive:!1}),o.addEventListener("touchcancel",y,{passive:!0}),()=>{try{u&&h&&I()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",j),o.removeEventListener("touchend",C),o.removeEventListener("touchcancel",y)}},[e,r])};function Lg({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(R,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function gi({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 cm=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,dm=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Vn(s,n)?null:e,Cr=()=>ys.filter(e=>Fr.has(e.id)).map(e=>({..._i(e)})),um=()=>{if(typeof window>"u")return Or;const e=window.localStorage.getItem("openInAppId");return e&&Tr(e)?e:Or};let kr=!1,Ps=!1,as=!1,ls=0,un=null;const bi=()=>{un&&(clearTimeout(un),un=null)},gs=Ks()((e,s)=>({selectedAppId:um(),availableApps:Cr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(kr||typeof window>"u")return;kr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Cr(),hasLoadedApps:u});return}const f=new Set(d.map(g=>g.name)),h=new Map(d.map(g=>[g.name,g.iconDataUrl??void 0])),p=ys.filter(g=>f.has(g.appName)||Fr.has(g.id)).map(g=>({..._i(g),iconDataUrl:h.get(g.appName)}));e({availableApps:p,hasLoadedApps:!0})},r=async d=>{if(!Ls()||!zn()||Ps||s().hasLoadedApps&&!d)return;const f=ys.map(h=>h.appName);bi(),Ps=!0,as=!1,e({isScanning:!0});try{const{apps:h,success:b,hasCache:p,isCacheStale:g}=await Bo(f,d),m=b&&!p&&h.length===0&&ls<3;if(e({isCacheStale:p?g:!1}),n(h,b?!m:!1),b){if(m){const x=[800,1600,3200][ls]??3200;ls+=1,as=!0,un=setTimeout(()=>{r()},x);return}ls=0,as=!1;return}if(ls<3){const x=[1e3,3e3,7e3][ls]??7e3;ls+=1,as=!0,un=setTimeout(()=>{r()},x)}}finally{Ps=!1,as||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Tr(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)&&(ls=3,as=!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(kr||s().initialize(),!Ls()||!zn()||Ps||s().hasLoadedApps&&!n)return;const o=ys.map(a=>a.appName);bi(),n&&e({hasLoadedApps:!1}),Ps=!0,as=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await Bo(o,n),d=new Set(a.map(b=>b.name)),u=new Map(a.map(b=>[b.name,b.iconDataUrl??void 0])),h=ys.filter(b=>d.has(b.appName)||Fr.has(b.id)).map(b=>({...b,iconDataUrl:u.get(b.appName)}));e({availableApps:h.length>0?h:Cr(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{Ps=!1,as||e({isScanning:!1})}},selectApp:async n=>{Tr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Zr({openInAppId:n}))}})),fm="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",hm="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",Ar=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?fm:e.id==="terminal"?hm:void 0}),xi=({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:$("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},pm=({directory:e,className:s})=>{const n=gs(g=>g.selectedAppId),r=gs(g=>g.availableApps),o=gs(g=>g.isCacheStale),a=gs(g=>g.isScanning),l=gs(g=>g.initialize),c=gs(g=>g.loadInstalledApps),d=gs(g=>g.selectApp);i.useEffect(()=>{l()},[l]);const u=Ls()&&zn(),f=i.useMemo(()=>{const g=r.find(m=>m.id===n)??r.find(m=>m.id===Or)??r[0]??ys[0];return Ar(g||ys[0])},[r,n]);if(!u||!e||r.length===0)return null;const h=async g=>{await fd(e,g.id,g.appName)||await Li(e,g.appName)},b=async g=>{await d(g.id),await h(g)},p=async()=>{(await us(e)).ok&&oe.success("Path copied to clipboard")};return t.jsxs("div",{className:$("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:$("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(xi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(It,{children:[t.jsx(Rt,{asChild:!0,children:t.jsx("button",{type:"button",className:$("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(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Dt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(ot,{className:"flex items-center gap-2",onClick:()=>{p()},children:[t.jsx(R,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Cs,{}),r.map(g=>{const m=Ar(g);return t.jsxs(ot,{className:"flex items-center gap-2",onClick:()=>{b(g)},children:[t.jsx(xi,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:m.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:g.label}),f.id===g.id?t.jsx(R,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},g.id)}),o?t.jsxs(ot,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(R,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},mm="\x1B",gm=new RegExp(`${mm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),bm=/https?:\/\/[^\s<>'"`]+/gi,jt="__pichamber_auto_discover_preview__",xm=15e3,ym=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},vm=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}},wm=e=>{const n=e.replace(gm,"").match(bm);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,b=f==="/"||f==="",p=!!(c.search||c.hash);let g=0;return u&&(g+=50),b&&(g+=30),g-=Math.min(h*5,20),p&&(g-=10),g};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},Sm=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],jm=["dev","start","preview","serve"];async function Cm(e,s,n){if(!e)return null;const r=Nm(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Im(n);if(o){const a=await Rm(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 km(e)){const o=await Am(),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 km(e){const s=`${e}/index.html`,n=await Qn(s,e);return typeof n=="string"&&n.trim().length>0}async function Am(){try{const e=await Ct("/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 Nm(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(jm.some(o=>n.includes(o)))return s}return null}function Im(e){for(const{pattern:s}of Sm)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Rm(e){const s=await Qn(`${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 Qn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Qn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Ct(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Jt()?.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 Ct(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Dm(e){try{const s=await Qn(`${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 Em=(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 Pm({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=Mi(),{terminal:o}=Gs(),{isMobile:a}=$s(),l=ce(L=>L.terminalShell),c=ce(L=>L.terminalLoginShells.includes(L.terminalShell)),d=ce(L=>L.setSettingsPage),u=ce(L=>L.setSettingsDialogOpen),f=ce(L=>L.setSettingsProjectsSelectedId),h=ce(L=>L.openContextPreview),b=he(L=>L.ensureDirectory),p=he(L=>L.setTabLabel),g=he(L=>L.setTabIconKey),m=he(L=>L.setActiveTab),w=he(L=>L.setConnecting),x=he(L=>L.setTabSessionId),I=he(L=>L.setTabPreviewUrl),v=he(L=>L.projectActionRuns),A=he(L=>L.setProjectActionRun),j=he(L=>L.updateProjectActionRunStatus),N=he(L=>L.removeProjectActionRun),[C,y]=i.useState([]),[k,D]=i.useState(null),[M,B]=i.useState(!1),_=i.useRef({}),K=i.useRef({}),V=i.useRef({}),O=i.useRef({}),T=i.useRef(new Set),P=i.useRef(0),U=e?.id??null,ne=e?.path??"",W=i.useMemo(()=>U?{id:U,path:ne}:null,[U,ne]),G=i.useCallback(async L=>{await ji(L)},[]),Ne=i.useCallback(async()=>{if(!W)return;const L=P.current+1;P.current=L,B(!0);try{const X=await Ir(W);if(P.current!==L)return;const ue=X.actions;y(ue),D(fe=>fe===jt||fe&&ue.some(je=>je.id===fe)?fe:null)}catch{if(P.current!==L)return}finally{P.current===L&&B(!1)}},[W]),ee=i.useMemo(()=>xa(s||W?.path||""),[s,W?.path]),Fe=i.useMemo(()=>k?C.find(L=>L.id===k)??null:null,[C,k]),_e=i.useMemo(()=>({id:jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),q=!a,F=i.useMemo(()=>q?[_e,...C]:C,[C,_e,q]);i.useEffect(()=>{Ne()},[Ne]),i.useEffect(()=>{if(typeof window>"u")return;const L=X=>{const ue=X.detail;U&&(ue?.projectId&&ue.projectId!==U||Ne())};return window.addEventListener(Kr,L),()=>{window.removeEventListener(Kr,L)}},[Ne,U]),i.useEffect(()=>{k&&(k===jt&&q||C.some(L=>L.id===k)||D(null))},[C,q,k]),i.useEffect(()=>{const L=()=>{const X=he.getState(),ue=X.sessions,fe=X.projectActionRuns;for(const[je,Re]of Object.entries(fe)){const Z=ue.get(Re.directory)?.tabs.find(Be=>Be.id===Re.tabId);if(!Z||Z.terminalSessionId!==Re.sessionId){N(je);continue}const pe=K.current[je]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};K.current[je]=pe;const le=F.find(Be=>Be.id===Re.actionId),Le=X.getBuffer(Re.directory,Re.tabId).chunks;if(!le||Le.length===0)continue;const He=Le.filter(Be=>pe.lastSeenChunkId===null||Be.id>pe.lastSeenChunkId);if(He.length===0)continue;const Ee=He.map(Be=>Be.data).join(""),Pe=`${pe.tail}${Ee}`,te=!pe.openedUrl&&le.autoOpenUrl===!0?wm(Pe):null,Ce=He[He.length-1]?.id??pe.lastSeenChunkId;if(pe.lastSeenChunkId=Ce,pe.tail=Pe.slice(-512),te)if(pe.openedUrl=!0,pe.openInPreview){const Be=fe[je];Be&&(I(Be.directory,Be.tabId,te,{locked:!1,autoOpened:!1}),Be.status==="waiting-for-preview"&&j(je,"running"),window.clearTimeout(O.current[je]),delete O.current[je],h(Be.directory,te))}else G(te),oe.success("Opened URL from action output");K.current[je]=pe}for(const je of Object.keys(K.current))fe[je]||(delete K.current[je],window.clearTimeout(O.current[je]),delete O.current[je])};return L(),he.subscribe((X,ue)=>{(X.sessions!==ue.sessions||X.buffers!==ue.buffers)&&L()})},[F,h,G,v,N,I,j]);const z=i.useCallback(async(L,X={})=>{if(!ee)throw new Error("No active directory");const ue=Xt(ee,L.id);b(ee);const fe=he.getState(),je=fe.getDirectoryState(ee);let Re=_.current[ue]||null;const be=Re?!!je?.tabs.some(le=>le.id===Re):!1;(!Re||!be)&&(Re=fe.createTab(ee),_.current[ue]=Re),p(ee,Re,`Action: ${L.name}`),g(ee,Re,L.icon||"play"),m(ee,Re),X.revealTerminal!==!1&&ce.getState().openContextPanelTab(ee,{mode:"terminal"});const pe=he.getState().getDirectoryState(ee)?.tabs.find(le=>le.id===Re);return{key:ue,tabId:Re,sessionId:pe?.terminalSessionId??null}},[b,ee,m,g,p]),Q=i.useCallback(async L=>{if(!n&&a)return;if(!ee){oe.error("No active directory for action");return}const X=Xt(ee,L.id),ue=v[X];if(!(ue&&ue.status==="running")&&!T.current.has(X)){T.current.add(X);try{const fe=L.id===jt?await(async()=>{const[Pe,te]=await Promise.all([Ir({id:W?.id??"",path:ee}),Dm(ee)]),Ce=await Cm(ee,Pe.actions,te);if(!Ce)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:jt,name:"Auto-discover",command:Ce.command,icon:"scan-2",autoOpenUrl:!0,openUrl:Ce.previewUrlHint||""}})():L,je=fe.autoOpenUrl===!0&&(fe.openUrl||"").trim().length>0,Re=!je&&L.id!==jt,{key:be,tabId:Z,sessionId:pe}=await z(fe,{revealTerminal:Re});let le=pe;if(!le){w(ee,Z,!0);try{le=(await o.createSession({cwd:ee,sessionId:Z,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(ee,Z,le)}finally{w(ee,Z,!1)}}if(!le)throw new Error("Failed to create terminal session");V.current[be]?.(),w(ee,Z,!0);const Le=o.connect(le,{onEvent:Pe=>{Pe.type==="snapshot"&&(he.getState().replaceBuffer(ee,Z,Pe.data??"",Pe.sequence??0),he.getState().setConnecting(ee,Z,!1)),Pe.type==="data"&&typeof Pe.data=="string"&&Pe.data.length>0&&he.getState().appendToBuffer(ee,Z,Pe.data,Pe.sequence,Pe.replayData),Pe.type==="exit"&&(he.getState().setTabLifecycle(ee,Z,"exited"),he.getState().setConnecting(ee,Z,!1),he.getState().removeProjectActionRun(be),delete K.current[be],V.current[be]?.(),delete V.current[be],window.clearTimeout(O.current[be]),delete O.current[be])},onError:(Pe,te)=>{he.getState().setConnecting(ee,Z,!1),te&&(he.getState().setTabLifecycle(ee,Z,"exited"),he.getState().setTabSessionId(ee,Z,null),he.getState().removeProjectActionRun(be))}});V.current[be]=Le.close;const He=fe.autoOpenUrl?vm(fe.openUrl):null;A({key:be,directory:ee,actionId:fe.id,tabId:Z,sessionId:le,status:fe.id===jt&&!He?"waiting-for-preview":"running"}),window.clearTimeout(O.current[be]),delete O.current[be],fe.id===jt&&!He&&(O.current[be]=window.setTimeout(()=>{const Pe=he.getState(),te=Pe.projectActionRuns[be];Pe.updateProjectActionRunStatus(be,"running"),te&&(Pe.setActiveTab(te.directory,te.tabId),ce.getState().openContextPanelTab(te.directory,{mode:"terminal"})),delete O.current[be]},xm)),K.current[be]={lastSeenChunkId:null,openedUrl:!!He||je,tail:"",openInPreview:fe.id===jt};const Ee=ym(fe.command.trim().replace(/\r\n|\r/g,`
|
|
53
|
-
`));await o.sendInput(le,`${Ee}\r`),He?(I(ee,Z,He,{locked:!0,autoOpened:!0}),h(ee,He),oe.success("Opened action URL")):je?(I(ee,Z,null,{locked:!0}),oe.error("Invalid custom URL format")):I(ee,Z,null,{locked:!1,autoOpened:!1})}catch(fe){N(X),delete K.current[X],V.current[X]?.(),delete V.current[X],window.clearTimeout(O.current[X]),delete O.current[X],oe.error(fe instanceof Error?fe.message:"Failed to run action")}finally{T.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,z,n,a,ee,c,l,h,v,N,w,A,I,x,W?.id,o]),se=i.useCallback(async L=>{const X=Xt(ee,L.id),ue=v[X];if(!ue)return;j(X,"stopping");const fe=Em(o,ue.sessionId,1e3);try{await o.sendInput(ue.sessionId,"")}catch{}const je=await fe;if(he.getState().getDirectoryState(ue.directory)?.tabs.find(Z=>Z.id===ue.tabId)?.terminalSessionId===ue.sessionId&&!je){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ue.sessionId})}catch{}else try{await o.close(ue.sessionId)}catch{}x(ue.directory,ue.tabId,null)}N(X),delete K.current[X],V.current[X]?.(),delete V.current[X],window.clearTimeout(O.current[X]),delete O.current[X]},[ee,v,N,x,o,j]),Se=i.useCallback(()=>{const L=Fe??F[0];if(!L)return;const X=Xt(ee,L.id),ue=v[X];if(ue?.status!=="stopping"){if(ue){se(L);return}Q(L)}},[F,ee,Q,v,Fe,se]),ge=i.useCallback((L,X=!1)=>{if(D(L.id),!X){Q(L);return}const ue=Xt(ee,L.id),fe=v[ue];if(fe?.status!=="stopping"){if(fe){se(L);return}Q(L)}},[ee,Q,v,se]),we=i.useCallback(()=>{W?.id&&(f(W.id),d("projects"),u(!0))},[u,d,f,W?.id]),re=Fe??F[0]??null,ae=re?v[Xt(ee,re.id)]:null,H=he(L=>ae?L.sessions.get(ae.directory)?.tabs.find(X=>X.id===ae.tabId)?.previewUrl??null:null),me=!!((n||!a)&&W&&ee),Ue=Fe??F[0]??null;return{shouldRender:me,isLoading:M,normalizedDirectory:ee,resolvedSelected:Ue,displayActions:F,projectActionRuns:v,selectedRunPreviewUrl:H,handlePrimaryClick:Se,handleSelectAction:ge,openProjectActionsSettings:we,openContextPreview:h}}const yi=({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:b,handleSelectAction:p,openProjectActionsSettings:g,openContextPreview:m}=Pm({projectRef:e,directory:s,allowMobile:o});if(!a||!d)return null;const w=d.icon||"play",x=d.id===jt?"scan-2":dn[w]||"play",I=Xt(c,d.id),v=f[I],A=v?.status==="stopping",j=v?.status==="waiting-for-preview",N=!!(v&&h),C=()=>{!v||!h||m(v.directory,h)},y=d.id===jt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||A,className:$("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:b,"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:A||j?t.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?t.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-5 w-5"})})}),y?t.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),N?t.jsxs($e,{children:[t.jsx(Ge,{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:C,children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(It,{children:[t.jsx(Rt,{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(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Dt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(ot,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Cs,{}),u.map(k=>{const D=k.icon||"play",M=k.id===jt?"scan-2":dn[D]||"play",B=Xt(c,k.id),_=f[B],K=!!_,V=_?.status==="stopping";return t.jsxs(ot,{className:"flex items-center gap-2",onClick:()=>{p(k,!0)},children:[t.jsx(R,{name:M,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),V||_?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]}):t.jsxs("div",{className:$("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($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,disabled:l||A,className:$("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:A||j?t.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?t.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(R,{name:x,className:"h-4 w-4"})})})}),y?t.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),N?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:C,className:$(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(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(It,{children:[t.jsx(Rt,{asChild:!0,children:t.jsx("button",{type:"button",className:$(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(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Dt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(ot,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(R,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Cs,{}),u.map(k=>{const D=k.icon||"play",M=k.id===jt?"scan-2":dn[D]||"play",B=Xt(c,k.id),_=f[B],K=!!_,V=_?.status==="stopping";return t.jsxs(ot,{className:"flex items-center gap-2",onClick:()=>{p(k,!0)},children:[t.jsx(R,{name:M,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:k.name}),V||_?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},k.id)})]})]})]})},Bt={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function _n(e){return e?.deploymentKind==="docker"?{name:Bt.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:Bt.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:Bt.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:Bt.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:Bt.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:Bt.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:Bt.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:Bt.centos,color:"#932279"}:{name:Bt.linux}:e?.serverPlatform==="darwin"?{name:Bt.darwin}:{name:Bt.unknown}}const Mm=e=>e?.deploymentKind==="docker"?"Docker":e?.serverPlatform==="win32"?"Windows":e?.serverPlatform==="darwin"?"macOS":e?.serverPlatform==="linux"?typeof e.serverDistribution=="string"&&e.serverDistribution.trim()?{ubuntu:"Ubuntu",arch:"Arch Linux",nixos:"NixOS",fedora:"Fedora",debian:"Debian",centos:"CentOS"}[e.serverDistribution]??"Linux":"Linux":"Server";function Tm({open:e,onOpenChange:s}){const[n,r]=i.useState(null),o=i.useCallback(async()=>{const u=qe();try{const f=await Ct("/api/version");if(!f.ok)throw new Error("Version request failed");const h=await f.json().catch(()=>null);u===qe()&&r(h)}catch{u===qe()&&r(null)}},[]);i.useEffect(()=>(o(),Ui(()=>{o()})),[o]);const a=_n(n),l=Mm(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return t.jsxs(It,{open:e,onOpenChange:u=>{s(u),u&&o()},children:[t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx(Rt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":"Show connected server information",className:$(Ws,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[t.jsx(R,{name:a.name,className:"h-[18px] w-[18px] shrink-0",style:a.color?{color:a.color}:void 0}),t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),t.jsx(Ke,{children:t.jsx("p",{children:"Connected server information"})})]}),t.jsxs(Dt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-4",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[t.jsx(R,{name:a.name,className:"size-5 shrink-0",style:a.color?{color:a.color}:void 0}),t.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:l})]}),c?t.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),t.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:t.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[t.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),t.jsxs("button",{type:"button",className:"ml-auto flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:`Copy ${d}`,"aria-label":"Copy server address",onClick:()=>{us(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[t.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),t.jsx(R,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const Fm=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(It,{children:[t.jsx(Rt,{asChild:!0,children:t.jsx("button",{type:"button",className:$(Ws,"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(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Dt,{align:"end",className:"w-64",children:[t.jsx(Mc,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Cs,{}),r.map(d=>{const u=d.user,f=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(ot,{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(R,{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(R,{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(R,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Om=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:a,isDesktopServicesOpen:l,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:h,remoteUpdateError:b,onOpenRemoteUpdate:p}){return t.jsxs(It,{open:l,onOpenChange:g=>{c(g),g&&d()},children:[t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx(Rt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:$(Ws,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(R,{name:a.name,className:"h-[18px] w-[18px]",style:a.color?{color:a.color}:void 0}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Ke,{children:t.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),t.jsx(Dt,{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:f?.available?`Version ${f.version||""} is available for this instance.`:h?"Looking for updates...":b||"This instance is up to date."})]}),f?.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:p,children:"Update"}):null]})}),t.jsx(Tc,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),Lm=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Yt,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(qt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(es,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(hs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(ks,{children:[t.jsx(Te,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Te,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Bm=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},tn=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},_m=i.lazy(()=>cs(()=>import("./SessionSwitcherDropdown-DGvRKfRw.js"),__vite__mapDeps([116,24,4,5,1,2,3,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}))),Bg=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{_t("ui.header.render");const l=ce(E=>E.setSessionSwitcherOpen),c=ce(E=>E.toggleSidebar),d=ce(E=>E.isSidebarOpen),u=ce(E=>E.activeMainTab),f=ce(E=>E.setActiveMainTab),h=ce(E=>E.shortcutOverrides);ce(E=>E.timeFormatPreference),Gs();const b=De(E=>!!E.newSessionDraft?.open),p=De(E=>E.currentSessionId),g=Pi(p??""),m=Fc(p),w=i.useMemo(()=>{if(!m)return null;const E=m;return{title:m.title??null,directory:E.directory??null,created:m.time?.created??null,slug:E.slug??null,shareUrl:m.share?.url??null,parentId:m.parentID??null}},[m]),x=pt(Lr(E=>{if(!E.activeProjectId)return null;const ie=E.projects.find(ye=>ye.id===E.activeProjectId);return ie?{id:ie.id,path:ie.path,label:ie.label}:null})),I=Bs(E=>E.homeDirectory),v=i.useMemo(()=>{if(!x)return null;const E=x.label?.trim();if(E)return E;const ie=x.path.split(/[\\/]/).filter(Boolean);return ie[ie.length-1]??null},[x]),{isMobile:A}=$s(),{enabled:j}=Jr(),N=!!(j&&a&&o!==void 0),C=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[y,k]=i.useState(!1),D=null,M=i.useRef(null),[B,_]=i.useState(()=>typeof window>"u"?!1:Ls()),K=i.useMemo(()=>Bi(),[]),V=Oc(),[O,T]=i.useState(!1),P=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),U=Ti(),ne=i.useMemo(()=>{if(typeof window>"u")return null;const E=window.__PICHAMBER_MACOS_MAJOR__;if(typeof E=="number"&&Number.isFinite(E)&&E>0)return E;if(typeof navigator>"u")return null;const ie=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ie)return null;const ye=Number.parseInt(ie[1],10),ze=Number.parseInt(ie[2],10);return Number.isNaN(ye)?null:ye===10?ze:ye},[]);Ae.useEffect(()=>{typeof window>"u"||_(Ls())},[]);const W=ce(E=>E.isSessionSwitcherOpen),G=null,Ne=null,ee=[],[Fe,_e]=i.useState(!1),[q,F]=i.useState(!1),[z,Q]=i.useState("Local"),[se,Se]=i.useState(!0),[ge,we]=i.useState(()=>_n(null)),[re,ae]=i.useState(!1),[H,me]=i.useState(null),[Ue,L]=i.useState(!1),[X,ue]=i.useState(null),fe=i.useRef(0),je=i.useMemo(()=>Bm(z),[z]),Re=i.useCallback(async()=>{if(typeof window>"u"||!B)return;const E=qe(),ie=()=>qe()===E;try{const ye=await Ct("/api/version");if(!ie())return;const ze=ye.ok?await ye.json().catch(()=>null):null;if(!ie())return;if(we(_n(ze)),zn()){Q("Local"),Se(!0);return}Se(!1);const bt=await hd();if(!ie())return;const Qe=pd(),os=md([gd(Qe),...bt.hosts]);if(os.id===bd){Q("Local"),Se(!0);return}Q(xd(os.label.trim()||"Instance"))}catch{ie()&&(Q("Local"),Se(!0),we(_n(null)))}},[B]);Ae.useEffect(()=>(Re(),Ui(()=>{fe.current+=1,me(null),ue(null),L(!1),ae(!1),Re()})),[Re]);const be=i.useCallback(async()=>{const E=fe.current+1;fe.current=E;const ie=qe(),ye=()=>fe.current===E&&qe()===ie;if(se){me(null),ue(null);return}L(!0),ue(null);try{const ze=new URLSearchParams({appType:"web",instanceMode:"remote"}),bt=await Ct(`/api/pi/update-check?${ze.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!bt.ok)throw new Error(`Server responded with ${bt.status}`);const Qe=await bt.json();if(!ye())return;me({available:Qe.available??!1,version:Qe.version,currentVersion:Qe.currentVersion??"unknown",body:Qe.body,nextSuggestedCheckInSec:typeof Qe.nextSuggestedCheckInSec=="number"?Qe.nextSuggestedCheckInSec:void 0,packageManager:Qe.packageManager,updateCommand:Qe.updateCommand,channel:Qe.channel==="rc"?"rc":"stable"})}catch(ze){if(!ye())return;me(null),ue(ze instanceof Error?ze.message:"Failed to check remote instance updates")}finally{ye()&&L(!1)}},[se]);i.useEffect(()=>Ku(()=>{se||be()}),[be,se]),i.useEffect(()=>{fe.current+=1,me(null),ue(null),L(!1),ae(!1)},[se,z]),i.useEffect(()=>{if(!B||se)return;const E=3e3,ie=3600*1e3;let ye=!1,ze=null;const bt=Qe=>{ze=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){bt(ie);return}be().finally(()=>{ye||bt(ie)})},Qe)};return bt(E),()=>{ye=!0,ze!==null&&window.clearTimeout(ze)}},[be,se,z,B]);const Z=i.useCallback(()=>{if(H?.available){ae(!0);return}be()},[be,H?.available]),pe=p?w??null:null,le=i.useRef(null),[Le,He]=i.useState(0);i.useEffect(()=>{if(!p){le.current&&(le.current=null,He(ze=>ze+1));return}if(pe){le.current={sessionId:p,session:pe,expiresAt:Date.now()+2e3};return}const E=le.current;if(!E||E.sessionId!==p)return;const ie=E.expiresAt-Date.now();if(ie<=0){le.current=null,He(ze=>ze+1);return}const ye=window.setTimeout(()=>{le.current?.sessionId===p&&(le.current=null),He(ze=>ze+1)},ie);return()=>{window.clearTimeout(ye)}},[p,pe]);const Ee=(()=>{if(pe)return pe;if(!p)return null;const E=le.current;return E&&E.sessionId===p&&E.expiresAt>Date.now()?E.session:null})(),Pe=i.useMemo(()=>{const E=typeof Ee?.directory=="string"?Ee.directory:"";return tn(E||"")},[Ee?.directory]),te=De(E=>E.newSessionDraft?.open?tn(E.newSessionDraft.directoryOverride??""):""),Ce=i.useMemo(()=>cm({sessionDirectory:Pe,draftDirectory:te,isNewSessionDraftOpen:b}),[te,b,Pe]),vt=Ei(Ce||null),Je=i.useMemo(()=>dm({activeProjectLabel:v,openDirectory:Ce,homeDirectory:I}),[v,I,Ce]),et=!!(Je||vt),Et=i.useMemo(()=>p?ds(Ee):Je??"PiChamber",[Ee,p,Je]),kt=Lc(),ts=De(E=>E.updateSessionTitle),mt=De(E=>E.archiveSessions),at=De(E=>E.deleteSessions),[Xe,lt]=i.useState(!1),[Ut,ss]=i.useState(!1),wt=i.useRef(!1),[ve,Oe]=i.useState(""),[xe,Me]=i.useState(null),Ye=i.useRef(null);i.useEffect(()=>{wt.current=!1,ss(!1),lt(!1),Oe(""),Me(null)},[p]);const ct=i.useCallback(()=>{p&&(Oe(Ee?.title?.trim()||Et),lt(!0))},[Ee?.title,p,Et]),St=i.useCallback(async()=>{if(!p)return;const E=ve.trim();E&&E!==Ee?.title?.trim()&&await ts(p,E),lt(!1)},[Ee?.title,p,ve,ts]);i.useEffect(()=>{if(!Xe)return;const E=ie=>{const ye=ie.target;(!ye||!Ye.current?.contains(ye))&&St()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[Xe,St]);const zt=i.useCallback(()=>{p&&us(p).then(E=>{oe[E.ok?"success":"error"](E.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[p]),ps=i.useCallback(async()=>{if(!p||!Ce){oe.error("Nothing to export");return}try{await kt.syncSession(p)}catch{oe.error("Failed to load the complete session history");return}const E=[];if(E.length===0){oe.error("Nothing to export");return}const ie=Fa(E,Ee?.title??null),ye=Ba(Ee?.title??null);await La(ie,ye)||Oa(ie,ye),oe.success("Session exported")},[Ee?.title,p,Ce,kt]);g?.type==="busy"||g?.type;const Pt=i.useCallback(async()=>{if(!p||!xe)return;const E=Bc(),ie=[p];for(let Qe=0;Qe<ie.length;Qe+=1){const os=ie[Qe];for(const xt of E)xt.parentID===os&&!ie.includes(xt.id)&&ie.push(xt.id)}const ye=xe;if(Me(null),(ye==="archive"?await mt(ie):await at(ie)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[mt,p,at,xe]),tt=ce(E=>E.isArchivePageOpen),Mt=i.useMemo(()=>tt?{title:"Archive",subtitle:null}:null,[tt]),Ze=i.useMemo(()=>tn(Ce||x?.path||""),[x?.path,Ce]),Qt=i.useCallback(()=>{Ze&&us(Ze).then(E=>{oe[E.ok?"success":"error"](E.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[Ze]),$t=i.useMemo(()=>x?{id:x.id,path:x.path}:null,[x]),Ns=i.useRef(null);i.useEffect(()=>{!$t||!Ze||(Ns.current={projectRef:$t,directory:Ze})},[Ze,$t]);const Tt=i.useMemo(()=>$t&&Ze?{projectRef:$t,directory:Ze}:Ns.current,[Ze,$t]),Hs=i.useCallback(async E=>{},[]),dt=i.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const ie=E.tagName;(ie==="INPUT"||ie==="TEXTAREA"||ie==="SELECT"||E.isContentEditable)&&E.blur()},[]),ms=i.useCallback(()=>{if(A){dt(),l(!W);return}c()},[dt,A,W,l,c]),gt=i.useCallback(()=>{ln("desktop_open_draft_mini_chat_window",{directory:tn(Ce||x?.path||""),projectId:x?.id??null,apiBaseUrl:Mr(),clientToken:Pr()}).catch(E=>{console.warn("[header] failed to open draft mini chat window",E)})},[x?.id,x?.path,Ce]),de=i.useCallback(()=>{if(b){gt();return}p&&ln("desktop_open_session_mini_chat_window",{sessionId:p,directory:tn(Ce||x?.path||""),apiBaseUrl:Mr(),clientToken:Pr()}).catch(E=>{console.warn("[header] failed to open session mini chat window",E)})},[x?.path,p,gt,b,Ce]),nt=Ws,st=gf,ut=i.useMemo(()=>n?"sessions":N?r&&o?o:null:r?"git":u,[u,N,n,r,o]),Gt=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&W&&l(!1)},[W,n,e,s,r,l]),ft=i.useCallback(()=>{e?.()},[e]),Xn=i.useCallback(()=>{s?.()},[s]),Ys=i.useMemo(()=>B&&P&&!O?"5.5rem":V?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!B||U?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[B,O,P,V,U]);Ae.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Ys)},[Ys]);const xn=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Is=d?"0px":B&&U?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":j?"2.75rem":"2.5rem";Ae.useEffect(()=>{if(!B||!P){T(!1);return}let E=!1;const ie=async()=>{try{const ze=await ln("desktop_is_window_fullscreen");E||T(ze===!0)}catch{E||T(!1)}},ye=()=>{ie()};return ie(),window.addEventListener("pichamber:window-resized",ye),()=>{E=!0,window.removeEventListener("pichamber:window-resized",ye)}},[B,P]);const yn=i.useMemo(()=>!B||!P||ne===null?"":ne>=26?"h-12":ne<=15?"h-14":"",[B,P,ne]),Zn=i.useMemo(()=>{if(!(B&&!U))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))"}},[B,U]),ns=i.useCallback(()=>{if(typeof document>"u")return;const E=M.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Ae.useEffect(()=>{if(typeof window>"u")return;ns();const E=M.current;if(!E||typeof ResizeObserver>"u")return()=>{};let ie=0;const ye=()=>{ie||(ie=requestAnimationFrame(()=>{ie=0,ns()}))},ze=new ResizeObserver(ye);return ze.observe(E),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{ie&&cancelAnimationFrame(ie),ze.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[ns]),Ae.useEffect(()=>{ns()},[ns,A,yn]);const qs=i.useCallback(async E=>{const ie=E.target;ie.closest(".app-region-no-drag")||ie.closest("button, a, input, select, textarea")||E.button===0&&B&&await _c()},[B]),Ft=i.useMemo(()=>A?[{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"}]:[],[A]),er=i.useCallback(E=>to(Un(E,h)),[h]);Ae.useEffect(()=>{!A&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&f("chat")},[u,A,f]),Ae.useEffect(()=>{const E=ie=>{if(yd(ie)&&!ie.shiftKey&&!ie.altKey){const ye=parseInt(ie.key,10);ye>=1&&ye<=Ft.length&&(ie.preventDefault(),A&&(dt(),Gt()),f(Ft[ye-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[dt,Gt,A,f,Ft]),Ae.useEffect(()=>{const E=ie=>{const ye=Un("toggle_services_menu",h);if(vd(ie,ye)){ie.preventDefault(),q?F(!1):(F(!0),Re());return}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[h,q,Re]);const tr=E=>{const ie=u===E.id,ye=E.icon==="diff",ze=ye?null:E.icon,bt=E.id==="chat",Qe=xt=>ye?t.jsx(gi,{size:xt}):ze?t.jsx(R,{name:ze,className:`h-${xt/4} w-${xt/4}`}):null,os=t.jsxs("button",{type:"button",onClick:()=>f(E.id),className:$("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ie?"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",bt&&!A&&"min-w-[100px] justify-center"),"aria-label":E.label,"aria-selected":ie,role:"tab",children:[A?Qe(20):t.jsxs(t.Fragment,{children:[Qe(16),t.jsx("span",{className:"header-tab-label",children:E.label})]}),E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:E.badge})]});return t.jsx(i.Fragment,{children:os},E.id)},Qs=t.jsxs(t.Fragment,{children:[t.jsx(pm,{directory:Ze,className:"mr-1"}),B?t.jsx(Om,{isDesktopApp:B,currentInstanceLabel:z,compactCurrentInstanceLabel:je,currentInstanceIsLocal:se,currentInstanceIcon:ge,isDesktopServicesOpen:q,setIsDesktopServicesOpen:F,refreshCurrentInstanceLabel:Re,shortcutLabel:er,remoteUpdateInfo:H,remoteUpdateChecking:Ue,remoteUpdateError:X,onOpenRemoteUpdate:Z}):t.jsx(Tm,{open:q,onOpenChange:F}),t.jsx(Fm,{isMobile:A,githubAuthStatus:D,githubAccounts:ee,githubAvatarUrl:G,githubLogin:Ne,isSwitchingGitHubAccount:Fe,handleGitHubAccountSwitch:Hs})]}),Vs=K&&(b||!!p),vn=()=>t.jsxs("div",{onMouseDown:qs,className:$("app-region-drag relative flex h-12 select-none items-center pr-3",yn),style:Zn,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:xn}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Is}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Mt?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:Mt.title}),Mt.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:Mt.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:nt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(_m,{align:"start",children:t.jsx("button",{type:"button",className:nt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Xe?t.jsxs("form",{ref:Ye,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:E=>{E.preventDefault(),St()},children:[t.jsx("input",{value:ve,onChange:E=>Oe(E.target.value),autoFocus:!0,onKeyDown:E=>{E.stopPropagation(),E.key==="Escape"&<(!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(R,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>lt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(R,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":Et}),et?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:[Je?t.jsx("span",{className:"truncate",children:Je}):null,vt?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:vt})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:p&&!b&&!Xe?t.jsxs(It,{open:Ut,onOpenChange:ss,onOpenChangeComplete:E=>{!E&&wt.current&&(wt.current=!1,ct())},children:[t.jsx(Rt,{asChild:!0,children:t.jsx(Te,{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(R,{name:"more",className:"size-4"})})}),t.jsxs(Dt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(ot,{onClick:()=>{wt.current=!0},children:[t.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(ot,{onClick:zt,children:[t.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(ot,{onClick:Qt,disabled:!Ze,children:[t.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(Cs,{}),t.jsxs(ot,{onClick:()=>{ps()},children:[t.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Cs,{}),t.jsxs(ot,{onClick:()=>Me("archive"),children:[t.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(ot,{className:"text-destructive focus:text-destructive",onClick:()=>Me("delete"),children:[t.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Ft.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ft.map(E=>tr(E))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Sa,{}),Tt?t.jsx(yi,{projectRef:Tt.projectRef,directory:Tt.directory,className:"mr-1"}):null,t.jsx(bf,{visible:Vs,title:b?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:de,className:$(nt,"mr-1"),Icon:"picture-in-picture-2"}),Qs,t.jsx(Uc,{visible:U})]})]})]}),rs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[j&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:xn}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Is}})]}),!j&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:ft,className:$(st,ut==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):W?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(R,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:ms,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(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&W&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!W||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!N&&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:Ft.map(E=>{const ie=u===E.id,ye=E.icon==="diff",ze=ye?null:E.icon;return t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{A&&(dt(),Gt()),f(E.id)},"aria-label":E.label,"aria-selected":ie,role:"tab",className:$(st,"relative rounded-lg",ut===E.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?t.jsx(gi,{className:"h-5 w-5"}):ze?t.jsx(R,{name:ze,className:"h-5 w-5"}):null,E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:E.badge}),E.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(Ke,{children:t.jsx("p",{children:E.label})})]},E.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[N&&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:C.map(E=>{const ie=r&&o===E.id;return t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{A&&(dt(),Gt()),k(!1),a?.(E.id)},"aria-label":E.label,"aria-selected":ie,role:"tab",className:$(st,"relative rounded-lg",ie&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:E.icon,className:"h-5 w-5"})})}),t.jsx(Ke,{children:t.jsx("p",{children:E.label})})]},E.id)})}),t.jsx(mf,{open:y,onOpenChange:k,currentSessionId:p,effectiveDirectory:Ce||null,isNewSessionDraftOpen:b})]}),Tt&&t.jsx(yi,{projectRef:Tt.projectRef,directory:Tt.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!N?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Xn,className:$(st,"relative",ut==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Ke,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Js=$("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:M,className:Js,style:{"--padding-scale":"1"},children:A?rs():vn()}),t.jsx(Lm,{action:xe,onClose:()=>Me(null),sessionTitle:Et,onConfirm:()=>{Pt()}}),t.jsx(ha,{open:re,onOpenChange:ae,info:H,downloading:!1,downloaded:!1,progress:null,error:X,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},vi="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",Um="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",_g=()=>{const e=ce(p=>p.isSidebarOpen),s=ce(p=>p.toggleSidebar),n=ce(p=>p.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=to(Un("toggle_sidebar",n)),l=Ti(),{enabled:c}=Jr(),d=!e,u=l,f=d||u,h=u,b=i.useCallback(()=>{ln("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=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},g=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!h)return;const m=o.current,w=r.current;if(!m||!w){p(0),g(0);return}const x=()=>{const v=Math.max(m.getBoundingClientRect().width,m.scrollWidth);p(v),g(w.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const I=new ResizeObserver(x);return I.observe(m),I.observe(w),()=>{I.disconnect()}},[h]),f?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:[u?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:$(vi,"shrink-0"),children:t.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Ke,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,d?t.jsxs($e,{children:[t.jsx(Ge,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:$(c?Um:vi,"shrink-0"),children:t.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Ke,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},wi=200,zm="cubic-bezier(0.22, 1, 0.36, 1)",Ug=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),wi);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${wi}ms ${zm}`}},zg=()=>{zi()},$g=e=>{De.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ce.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),zi(),Bs.getState().resetForRuntimeSwitch(),zc.getState().resetForRuntimeSwitch(),$c.getState().resetForRuntimeSwitch(),Gc(),Kc.getState().resetForRuntimeSwitch(),Wt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),pt.getState().resetForRuntimeSwitch(),Wc(),Hc(),Xd.getState().reset(),wd.getState().resetForRuntimeSwitch(),Ri.getState().resetForRuntimeSwitch(e.runtimeKey),Dr.getState().resetForRuntimeSwitch(e.runtimeKey),js.getState().resetForRuntimeSwitch(e.runtimeKey),Zf.getState().resetForRuntimeSwitch(),ht.getState().resetForRuntimeSwitch(e.runtimeKey),Sd.getState().resetForRuntimeSwitch(e.runtimeKey),De.getState().restoreForRuntimeSwitch(e.runtimeKey),ce.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=ce.getState();_r({sessionId:De.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0})};export{lf as $,Dg as A,Lg as B,Rg as C,ci as D,yu as E,dg as F,ag as G,Bg as H,gs as I,lu as J,bs as K,ug as L,wa as M,zu as N,jg as O,Ou as P,hg as Q,Ig as R,Eg as S,Fg as T,vg as U,ha as V,ig as W,ro as X,xg as Y,Uu as Z,ga as _,mf as a,Fu as a0,$u as a1,gn as a2,pa as a3,bn as a4,cn as a5,Lu as a6,pg as a7,Bu as a8,Sg as a9,Ag as aa,kg as ab,Gu as ac,wg as ad,Cg as ae,Ng as af,fg as ag,mg as ah,gg as ai,bg as aj,sf as ak,yg as al,wu as am,_u as an,Su as ao,rg as ap,sn as b,bp as c,Pg as d,Ln as e,Ug as f,Mg as g,Og as h,vp as i,_g as j,$g as k,lg as l,cg as m,og as n,ng as o,oo as p,io as q,zg as r,Tg as s,ao as t,hf as u,Os as v,va as w,cf as x,df as y,Yo as z};
|