@pi-chamber/web 1.0.0 → 1.0.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/README.md +3 -1
- package/bin/cli.js +7 -32
- package/bin/dev-server.js +185 -0
- package/bin/dev-server.test.js +252 -0
- package/bin/lib/DOCUMENTATION.md +19 -0
- package/bin/lib/cli-startup.js +9 -1
- package/bin/lib/cli-startup.test.js +30 -0
- package/bin/lib/commands-serve.js +9 -5
- package/bin/lib/server-runtime.js +6 -0
- package/bin/lib/server-runtime.test.js +313 -0
- package/dist/assets/{DiagramView-CbSxUe1D.js → DiagramView-COHSzZ9Z.js} +1 -1
- package/dist/assets/{DiffView-VyBf4ilo.js → DiffView-BA4LWExp.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-BCvbQ234.js → FileSaveConflictDialog-hRumcJ2e.js} +1 -1
- package/dist/assets/{FilesView-DasA5EU2.js → FilesView-CIx6Bq8l.js} +1 -1
- package/dist/assets/{GitView-DU3mOECp.js → GitView-3Hgk_pVS.js} +3 -3
- package/dist/assets/{JsonTreeView-xZiWDwua.js → JsonTreeView-CVLGj7jk.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-BBwdI2OF.js → MarkdownRendererImpl-CWeQW9_O.js} +1 -1
- package/dist/assets/{PatchDiff-BhKm_JPT.js → PatchDiff-367QPDDL.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DTGSP_RB.js → SessionSwitcherContent-CbgywSHr.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CedOB-xC.js → SessionSwitcherDropdown-BAHhqkBZ.js} +2 -2
- package/dist/assets/{SessionUnreadDot-CZSNKram.js → SessionUnreadDot-CvIWGgIi.js} +1 -1
- package/dist/assets/SettingsView-BpGtnBKt.js +2 -0
- package/dist/assets/{SettingsWindow-y33YrpBE.js → SettingsWindow-CN0wm-Fv.js} +1 -1
- package/dist/assets/{ToolOutputDialog-JqIXJWAH.js → ToolOutputDialog-Bkh0DWJn.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CRi_33jE.js → ToolPartDiffPreview-C_V9k2ob.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-ehLQSR5W.js → VirtualizedFileDiff-CFToyUp4.js} +1 -1
- package/dist/assets/{collapsible-Vypq-nMP.js → collapsible-BXBoS1M4.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BTfrj_fR.js → computeVirtualFileMetrics-BpbB2xiE.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-Dl6mFfD1.js → contextFileOpenGuard-DsdrIBIY.js} +1 -1
- package/dist/assets/{gitStatusPredicates-LAsJAhCL.js → gitStatusPredicates-KYx0Vs9h.js} +1 -1
- package/dist/assets/{index-OveFsNBm.js → index-CVZfC79h.js} +1 -1
- package/dist/assets/{index-BXX8l7mM.css → index-Ci9OMaKW.css} +1 -1
- package/dist/assets/{index-DvNeSFO9.js → index-DyeT2dc_.js} +7 -7
- package/dist/assets/{isDiffPlainText-CNZohQ4q.js → isDiffPlainText-dBQiDlRy.js} +1 -1
- package/dist/assets/{isFilePlainText-Dz8UubRT.js → isFilePlainText-DWMzO-Ms.js} +1 -1
- package/dist/assets/{main-BsDkATRV.js → main-DkXvFwTR.js} +3 -3
- package/dist/assets/{main-C393Ywhx.js → main-DukaBOy3.js} +2 -2
- package/dist/assets/{markdownCore-Bz9-Y75q.js → markdownCore-BH61OrJ2.js} +1 -1
- package/dist/assets/{miniChat-CWEerp3c.js → miniChat-B1uBoxSn.js} +2 -2
- package/dist/assets/{mobile-YxV9KcxF.js → mobile-DV_RYy3x.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-GrLmBQRb.js → renderElectronMiniChatApp-CA6co_Lh.js} +2 -2
- package/dist/assets/renderMobileApp-CyhFZ_4g.js +11 -0
- package/dist/assets/runtimeEndpointReset-CVoKFaRw.js +53 -0
- package/dist/assets/{runtimeSurface-DUXw4-oa.js → runtimeSurface-CxbVCK7k.js} +1 -1
- package/dist/assets/{useAppFontEffects-ad-lZJ6o.js → useAppFontEffects-HCEusnq7.js} +77 -77
- package/dist/assets/{useFilesViewSearch-C4oOHPml.js → useFilesViewSearch-Cq7IOB7l.js} +1 -1
- package/dist/assets/{usePushVisibilityBeacon-xd8Q10cI.js → usePushVisibilityBeacon-Tvi9uL7v.js} +1 -1
- package/dist/assets/{useSwitcherItems-B6VC7tug.js → useSwitcherItems-DLA7kskG.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B4j3gkaT.js → vendor-codemirror-language-data-zF3O85ti.js} +2 -2
- package/dist/assets/{web-components-B0RFakat.js → web-components-C7g3Hi85.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +8 -3
- package/server/index.js +40 -6
- package/server/lib/notifications/DOCUMENTATION.md +39 -0
- package/server/lib/notifications/delivery-runtime.js +314 -0
- package/server/lib/notifications/delivery-runtime.test.js +85 -0
- package/server/lib/notifications/pi-notification-watcher.js +154 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +84 -0
- package/server/lib/notifications/routes.js +74 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
- package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
- package/server/lib/pi/ui-settings-store.js +3 -2
- package/server/lib/server/runtime-requirements.js +193 -0
- package/server/lib/server/runtime-requirements.test.js +295 -0
- package/dist/assets/SettingsView-B5nmu8x4.js +0 -2
- package/dist/assets/renderMobileApp-C29wquBe.js +0 -11
- package/dist/assets/runtimeEndpointReset-DHARMv9w.js +0 -53
|
@@ -1,53 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-OveFsNBm.js","assets/useAppFontEffects-ad-lZJ6o.js","assets/index-DvNeSFO9.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-BXX8l7mM.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-DUXw4-oa.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-B4j3gkaT.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-BTfrj_fR.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-Dz8UubRT.js","assets/isDiffPlainText-CNZohQ4q.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-CedOB-xC.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as ls}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ie,j as t,R as i,b as Zl}from"./vendor-react-B5Z1Mdn3.js";import{aQ as Ps,aR as ec,a2 as Pt,a3 as ze,a4 as $e,a5 as Tt,B as Me,I as R,a6 as Ge,a7 as Ft,a9 as rt,t as ae,a as pt,f as Ee,_ as zs,ae as dn,aS as yi,ag as Ht,ah as Yt,ai as ds,aj as ss,ak as us,al as Ss,aG as xs,aT as ys,g as Ms,aU as or,aV as No,aW as Io,aX as nn,e as Dn,o as wi,af as ps,aY as Ro,a8 as ws,aZ as Cr,a_ as tc,a$ as sc,b0 as nc,b1 as rc,b2 as oc,b3 as kr,b4 as ic,y as Kt,b5 as ac,b6 as lc,b7 as cc,b8 as vi,b9 as dc,ba as uc,bb as Si,bc as ji,bd as Ci,aD as Ar,r as rn,n as qr,ap as fc,az as hc,aC as ki,L as js,d as Qr,ab as $s,ay as Ai,be as Yn,bf as Eo,bg as ht,aE as Ni,bh as Ii,au as pc,h as Ri,j as mc,bi as gc,i as bc,bj as Rs,b as Do,c as xc,bk as yc,u as wc,aF as vc,aI as Sc,bl as Nr,bm as jc,bn as Cc,aH as kc,bo as Ac,bp as Nc,T as Ic,aa as vs,am as Ei,w as Rc,ac as Ec,bq as Dc,br as Mc,k as Pc,bs as Tc,bt as Di,bu as Fc,bv as Oc,bw as Lc,bx as Bc,by as _c,bz as Uc,bA as zc,bB as $c,bC as Gc,bD as Kc}from"./useAppFontEffects-ad-lZJ6o.js";import{Z as Mo,_ as Wc,R as Os,$ as Mi,a0 as Pi,a1 as Hc,a2 as Yc,q as Ls,K as qc,a3 as Qc,a4 as Vc,a5 as Jc,a6 as Xt,v as Zt,a7 as Xc,a8 as Zc,a9 as ed,aa as Vr,m as Ot,ab as td,ac as sd,ad as nd,u as le,o as U,ae as rd,f as Xe,B as Ne,af as Bs,ag as Mt,ah as Po,ai as Ir,a as Jr,T as Xr,U as Ln,aj as od,ak as id,al as Ti,F as ad,Q as Fi,C as on,am as Rr,h as Er,d as jn,an as ld,ao as cd,ap as To,aq as Xs,ar as ir,as as Dr,at as Bn,au as ms,av as Fo,aw as Mr,ax as Oi,ay as Pr,az as dd,aA as ud,aB as fd,aC as hd,aD as pd,aE as md,aF as gd,z as bd,aG as xd,aH as yd,Y as Li,P as wd,J as vd}from"./index-DvNeSFO9.js";import{c as Gs,d as Bi,p as Zr,u as Tr,a as Sd}from"./vendor-zustand-GVb4H8HE.js";import{g as cs,b as jd,c as _i,r as Cd,d as Ui,s as Mn,e as zi,h as un,i as fn,j as kd,k as Ad,l as Nd,m as Oo,n as qn,f as Id,a as Rd,S as Ed,t as Dd,o as Md}from"./SessionUnreadDot-CZSNKram.js";import{C as $i,a as Gi,M as Ki,b as Wi,c as Hi,d as Yi,S as qi,D as Pd,e as Td,f as Fd,g as Od,h as Ld,i as Bd,j as _d}from"./vendor-base-ui-DXSHfszQ.js";import{c as Qi,d as Fr,P as Ud,D as Vi,e as Ji,f as zd,b as $d,a as Gd,T as Kd,M as Wd}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{u as Hd}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as Yd,v as qd,u as Qd}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as Vd}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-xterm-xterm-CrXqRur4.js";import{usePermissionStore as Jd}from"./permissionStore-iKN1K2_x.js";const Xd="chat";function Xi(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ps.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ps.SETTINGS,n),s}return e.tab!==Xd&&s.set(Ps.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ps.FILE,e.diffFile),s}function Zd(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 eu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Xi(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ps.SESSION)&&s.set(Ps.SESSION,o);const a=[...s.entries()].sort((c,u)=>c[0].localeCompare(u[0])),l=[...n.entries()].sort((c,u)=>c[0].localeCompare(u[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Or(e,s={}){if(!(typeof window>"u")&&!(!s.force&&eu(e)))try{const n=Xi(e),r=Zd(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const tu=["typescript","javascript","tsx","jsx","json","markdown"],Zi={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Lo=null;const ea=()=>(Lo??=Promise.all([ls(()=>import("./index-OveFsNBm.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])),ls(()=>import("./workerFactory-tw7cIdmV.js"),[]),ls(()=>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})),Lo),hn={},Bo=new Set,Lr=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const su=()=>{for(const e of Lr)e()},ta=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:Zi[e].lineDiffType})},Br=e=>{typeof window>"u"||Bo.has(e)||(Bo.add(e),ea().then(s=>{if(hn[e])return;const n=Zi[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:tu,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),hn[e]=r,ta(e,r),su()}))},nu=e=>(Lr.add(e),()=>Lr.delete(e)),ru=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(hn)){const n=hn[s];n&&ta(s,n)}}},tg=({children:e})=>{const s=ec(),n=Mo(!1),r=Mo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(u=>u.metadata.id===o)??n,c=s?.availableThemes.find(u=>u.metadata.id===a)??r;return Ie.useEffect(()=>{let u=!1;return ea().then(d=>{u||(d.ensurePierreThemeRegistered(l),d.ensurePierreThemeRegistered(c),ru({light:l.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,l]),Ie.useEffect(()=>{if(typeof window>"u")return;const u=()=>{Br("unified"),Br("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(u,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const d=window.setTimeout(u,2e3);return()=>window.clearTimeout(d)},[]),t.jsx(t.Fragment,{children:e})},sg=(e="unified")=>{const s=Ie.useSyncExternalStore(nu,()=>hn[e],()=>{});return Ie.useEffect(()=>{Br(e)},[e]),s},ou={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},iu={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 sa(e){return e&&iu[e]||"var(--primary)"}const _o=({icon:e,className:s,colorToken:n})=>{const r=ou[e??"branch"]??"user-3";return t.jsx(R,{name:r,className:s,style:{color:sa(n)}})},au=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Pt,{children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Tt,{asChild:!0,children:t.jsxs(Me,{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:sa(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(Ge,{sideOffset:8,children:"Git identity"})]}),t.jsx(Ft,{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(rt,{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)})})]})},lu=e=>e==="/",_s=e=>e.replace(/\\/g,"/"),Us=e=>{if(!e||lu(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Ts=e=>e.endsWith("/"),_n=e=>{const s=e.trim();return!s||Ts(s)?s:`${s}/`},eo=e=>e.lastIndexOf("/"),na=e=>{if(Ts(e))return e;const s=eo(e);return s<0?e:e.slice(0,s+1)},ra=e=>{const s=eo(e);return e.slice(s+1)},oa=e=>{const s=Us(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=eo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},ia=e=>Ts(e)&&oa(e)!==null,cu=e=>{if(!ia(e))return null;const s=Us(e.trim());return ra(s)||s},du=(e,s)=>`${na(e)}${s}/`,gs=e=>{if(!e)return null;const s=Us(_s(e.trim()));return s?s.toLowerCase():null},Uo=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},uu=(e,s)=>{const n=Us(_s(e.trim())),r=Us(_s(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)},fu=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},hu=async()=>Wc(),pu=()=>{const[e,s]=Ie.useState(!1),[n,r]=Ie.useState(!1);Ie.useEffect(()=>{s(Os()),r(Mi())},[]);const o=Ie.useCallback(async c=>e?await Pi(c):{success:!0,path:c},[e]),a=Ie.useCallback(async c=>e?await Hc():{success:!0},[e]),l=Ie.useCallback(async c=>e?await Yc():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function mu({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=Ls(ne=>ne.homeDirectory),{canRequestAccess:o,startAccessing:a}=pu(),l=i.useRef(null),c=i.useRef(new Map),[u,d]=i.useState(""),[f,p]=i.useState("~/"),[b,m]=i.useState([]),[g,h]=i.useState(!1),[v,x]=i.useState(!1),[I,w]=i.useState(null),[A,N]=i.useState(0),[k,j]=i.useState(0),[y,C]=i.useState(!1),[E,P]=i.useState(!1),[B,L]=i.useState("right"),z=i.useRef("~/"),Q=u||r;i.useEffect(()=>{if(!e)return;p("~/"),m([]),j(0),C(!1),P(!1),z.current="~/",L("right"),n||requestAnimationFrame(()=>_r(l.current));let ne=!1;return(async()=>{const q=await hu();ne||(d(q||r||""),n||requestAnimationFrame(()=>_r(l.current)))})(),()=>{ne=!0}},[r,e,n]);const O=i.useMemo(()=>na(f),[f]),T=i.useMemo(()=>Ts(f)?"":ra(f),[f]),M=i.useMemo(()=>Q?Uo(O,Q):"",[O,Q]);i.useEffect(()=>{const ne=z.current;ne!==O&&(L(O.length>=ne.length?"right":"left"),z.current=O)},[O]),i.useEffect(()=>{if(!e||!M){m([]),w(null);return}let ne=!1;return h(!0),x(!1),w(null),qc(M).then(ce=>{if(ne)return;x(!1),w(null);const q=ce.filter(fe=>fe.isDirectory).map(fe=>({name:fe.name,path:_s(fe.path)})).sort((fe,_e)=>fe.name.localeCompare(_e.name));m(q)}).catch(ce=>{if(!ne){m([]);const q=Qc(ce)?ce.reason:"unknown";w(q),x(q==="not-found")}}).finally(()=>{ne||h(!1)}),()=>{ne=!0}},[M,A,e]);const _=i.useMemo(()=>{const ne=T.toLowerCase(),ce=E||T.startsWith(".");return b.filter(q=>q.name.toLowerCase().startsWith(ne)&&(ce||!q.name.startsWith(".")))},[T,b,E]),se=i.useMemo(()=>cu(f),[f]),$=i.useMemo(()=>oa(f),[f]),G=i.useMemo(()=>{const ne=[],ce=gs(M);ia(f)&&se&&$&&ne.push({type:"parent",value:"browse:up",name:se,path:$,alreadyAdded:!!(ce&&s.has(ce))});for(const q of _){const fe=gs(q.path);ne.push({type:"directory",value:`browse:${q.path}`,name:q.name,path:q.path,alreadyAdded:!!(fe&&s.has(fe))})}return ne},[s,M,se,_,$,f]);i.useEffect(()=>{j(0)},[f,G.length]);const Ae=i.useMemo(()=>Q?Us(Uo(f,Q)):"",[Q,f]),te=gs(Ae),Pe=!!(te&&s.has(te)),Be=i.useMemo(()=>T?_.find(ne=>ne.name===T)??null:null,[T,_]),Y=!!(Ae&&!Pe&&(I===null||I==="not-found")&&(Ts(f)&&v||!Ts(f)&&T.trim().length>0&&Be===null)),F=G[k]??null,K=!!F,J=i.useCallback(ne=>{p(_n(ne))},[]),Z=i.useCallback(ne=>{p(du(f,ne.name))},[f]),pe=i.useCallback(ne=>{if(ne){if(ne.type==="parent"){J(ne.path);return}Z(ne)}},[J,Z]),Se=i.useCallback(async ne=>{const ce=await a(ne);if(!ce.success)return ae.error("Failed to open directory",{description:ce.error||"Desktop could not grant file access."}),!1;const q=Q?uu(ne,Q):_n(_s(ne));return J(q),!0},[J,Q,a]),xe=i.useCallback(async()=>{if(!y){C(!0);try{if(Mi()){const ce=await Pi(Ae);if(!ce.success||!ce.path){ce.error&&ce.error!=="Directory selection cancelled"&&ae.error("Failed to select directory",{description:ce.error});return}await Se(ce.path);return}const ne=await Vc(Ae);if(ne.status==="cancelled")return;if(ne.status!=="picked"){ae.error("Couldn't open a folder picker",{description:ne.error});return}await Se(ne.path)}catch(ne){ae.error("Failed to select directory",{description:ne instanceof Error?ne.message:"Unknown error occurred."})}finally{C(!1)}}},[Se,y,Ae]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:g,isBrowseDirectoryMissing:v,browseErrorReason:I,browseReloadKey:A,setBrowseReloadKey:N,highlightedIndex:k,setHighlightedIndex:j,isPickingLocation:y,showHidden:E,setShowHidden:P,folderEnterFrom:B,explorerRootDirectory:Q,browseDirectoryDisplayPath:O,browseDirectoryAbsolutePath:M,browseFilterQuery:T,filteredEntries:_,rows:G,targetPath:Ae,isAlreadyAdded:Pe,shouldCreateTarget:Y,highlightedRow:F,hasHighlightedBrowseItem:K,canRequestAccess:o,browseToDisplayPath:J,browseToEntry:Z,executeRow:pe,applyPickedLocation:Se,handleBrowseLocation:xe}}const hs=Gs()(Bi(Zr((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=Zt()?.git,o=r?await r.getGitIdentities():await nd();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=Zt()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await sd();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=Zt()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await td();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=Zt()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Ot("/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 Vr({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"};Xt("saving");const o=Zt()?.git;return o?await o.createGitIdentity(r):await ed(r),Xt("saved"),await s().loadProfiles(),!0}catch(r){return Xt("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};Xt("saving");const l=Zt()?.git;return l?await l.updateGitIdentity(n,a):await Zc(n,a),Xt("saved"),await s().loadProfiles(),!0}catch(o){return Xt("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{Xt("saving");const r=Zt()?.git;return r?await r.deleteGitIdentity(n):await Xc(n),Xt("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return Xt("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:Jc(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=hs);function gu({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:u,isPickingLocation:d}){const f=pt($=>$.addProject),p=le($=>$.setActiveMainTab),b=le($=>$.setSessionSwitcherOpen),m=Ee($=>$.openNewSessionDraft),g=hs($=>$.profiles),h=hs($=>$.globalIdentity),v=hs($=>$.defaultGitIdentityId),x=hs($=>$.loadProfiles),I=hs($=>$.loadGlobalIdentity),w=hs($=>$.loadDefaultGitIdentityId),[A,N]=i.useState(!1),[k,j]=i.useState(!1),[y,C]=i.useState(""),[E,P]=i.useState(null);i.useEffect(()=>{e&&(N(!1),j(!1),C(""),P(null))},[e]),i.useEffect(()=>{e&&(x(),I(),w())},[w,x,I,e]);const B=i.useMemo(()=>{const $=new Map;h&&$.set(h.id,h);for(const G of g)$.set(G.id,G);return Array.from($.values())},[g,h]);i.useEffect(()=>{if(!e||!k||E!==null)return;const $=typeof v=="string"?v.trim():"";if($&&B.some(Ae=>Ae.id===$)){P($);return}const G=B.find(Ae=>Ae.authType==="ssh"||Ae.sshKey);G&&P(G.id)},[B,v,k,e,E]);const L=i.useMemo(()=>B.find($=>$.id===E)??null,[B,E]),z=i.useCallback(($,G)=>{p("chat"),n&&b(!1),m({selectedProjectId:$,directoryOverride:G}),s()},[n,s,m,p,b]),Q=i.useCallback(async $=>{if(!$||A)return;const G=gs($);if(G&&r.has(G))return;let Ae=$;N(!0);try{const te=!k&&a&&gs($)===gs(o);if(k){const Be=y.trim();if(!Be){ae.error("Enter a repository URL before cloning.");return}const Y=await Ot("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:Be,destinationPath:$,gitIdentityId:L?.id??null})});if(!Y.ok)throw new Error("Failed to clone git repository");Ae=(await Y.json()).path||$}else if(te&&!(await Ot("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:$})})).ok)throw new Error("Failed to select directory");const Pe=f(Ae);if(!Pe){ae.error("Failed to add folder",{description:"Please select a valid directory path."});return}z(Pe.id,Pe.path)}catch(te){ae.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{N(!1)}},[f,r,c,y,k,A,z,L?.id,a,o]),O=!A&&!d&&!u&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,T=O&&y.trim().length>0,M=k?T:O,_=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:A,isCloneMode:k,setIsCloneMode:j,cloneRemoteUrl:y,setCloneRemoteUrl:C,selectedGitIdentityId:E,setSelectedGitIdentityId:P,availableGitIdentities:B,selectedGitIdentity:L,canSubmit:M,submitActionLabel:u?"Already added":k?A?"Cloning...":"Clone & add":A?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:_,finalizeSelection:Q}}const bu=({open:e,onOpenChange:s})=>{const n=pt(q=>q.projects),{isMobile:r,isTablet:o}=zs(),a=r||o,l=i.useMemo(()=>new Set(n.map(q=>gs(q.path)).filter(q=>!!q)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:u,rowRefs:d,query:f,setQuery:p,isLoading:b,browseErrorReason:m,setBrowseReloadKey:g,highlightedIndex:h,setHighlightedIndex:v,isPickingLocation:x,showHidden:I,setShowHidden:w,folderEnterFrom:A,browseDirectoryDisplayPath:N,browseDirectoryAbsolutePath:k,rows:j,targetPath:y,isAlreadyAdded:C,shouldCreateTarget:E,highlightedRow:P,hasHighlightedBrowseItem:B,canRequestAccess:L,executeRow:z,handleBrowseLocation:Q}=mu({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:O,isCloneMode:T,setIsCloneMode:M,cloneRemoteUrl:_,setCloneRemoteUrl:se,setSelectedGitIdentityId:$,availableGitIdentities:G,selectedGitIdentity:Ae,canSubmit:te,submitActionLabel:Pe,submitModifierLabel:Be,finalizeSelection:Y}=gu({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:y,shouldCreateTarget:E,browseErrorReason:m,browseDirectoryAbsolutePath:k,isAlreadyAdded:C,isPickingLocation:x});i.useLayoutEffect(()=>{const q=u.current;q&&(q.scrollLeft=q.scrollWidth)},[u,f]),i.useLayoutEffect(()=>{!e||a||_r(u.current)},[u,e,a]),i.useLayoutEffect(()=>{const q=j[h];q&&d.current.get(q.value)?.scrollIntoView({block:"nearest"})},[h,d,j]);const F=i.useCallback(q=>{if(q.key==="ArrowDown"){q.preventDefault(),v(fe=>Math.min(j.length-1,fe+1));return}if(q.key==="ArrowUp"){q.preventDefault(),v(fe=>Math.max(0,fe-1));return}if(q.key==="Enter"){if(q.preventDefault(),fu(q)){Y(y);return}B&&z(P);return}q.key==="Backspace"&&f===""&&(q.preventDefault(),c())},[z,Y,c,B,P,f,j.length,v,y]),K=t.jsxs("button",{type:"button",onClick:()=>w(q=>!q),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"]}),J=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(dn,{ref:u,value:f,onChange:q=>p(_s(q.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(Me,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:O||x,onMouseDown:q=>q.preventDefault(),onClick:()=>{Q()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(R,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),Z=j.some(q=>q.type==="parent"),pe=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(Me,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":T,disabled:O||x,onClick:()=>M(q=>!q),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(dn,{value:_,onChange:q=>se(q.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(au,{activeProfile:Ae,identities:G,onSelect:q=>$(q.id),isApplying:O,iconOnly:!0})]})]}):null,C?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:U("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..."}):m&&m!=="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:m==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[m==="os-permission"&&L?t.jsx(Me,{size:"xs",onClick:()=>{Q()},disabled:x,children:"Grant access"}):null,t.jsx(Me,{variant:"outline",size:"xs",onClick:()=>g(q=>q+1),children:"Try again"})]})]}):j.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:j.map((q,fe)=>{const _e=fe===h,W=q.type==="directory"&&Z;return t.jsxs("button",{ref:X=>{X?d.current.set(q.value,X):d.current.delete(q.value)},type:"button","aria-label":q.type==="parent"?q.alreadyAdded?`Go back from ${q.name}, already added`:`Go back from ${q.name}`:q.alreadyAdded?`Open ${q.name}, already added`:`Open ${q.name}`,onMouseEnter:()=>v(fe),onMouseDown:X=>X.preventDefault(),onClick:()=>z(q),className:U("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",_e&&"bg-interactive-selection text-interactive-selection-foreground",!_e&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:U("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[q.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:q.name})]}),q.alreadyAdded?t.jsx("span",{className:U("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",_e?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,q.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"})]},q.value)})})},N)]})}),Se=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[J,pe]}),xe=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:Be}),t.jsx(R,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),ne=t.jsx(Me,{size:r?"xs":"default",onClick:()=>{Y(y)},disabled:!te,className:U(r&&"w-full flex-1"),children:Pe}),ce=()=>t.jsxs(t.Fragment,{children:[r?null:xe,t.jsx("div",{className:U("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:ne})]});return r?t.jsx(yi,{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:ce()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:K}),Se]})}):t.jsx(Ht,{open:e,onOpenChange:s,children:t.jsxs(Yt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(ds,{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(ss,{children:"Add folder"}),t.jsx(us,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),K]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Se}),t.jsx(Ss,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ce()})]})})},Cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,ng=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=Ee(k=>k.deleteSession),c=Ee(k=>k.deleteSessions),u=le(k=>k.showDeletionDialog),d=le(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:b}=zs(),m=f||p||b;i.useEffect(()=>rd(()=>{s(!1)}),[]);const g=i.useCallback(k=>{r({sessions:k.sessions,dateLabel:k.dateLabel})},[]),h=i.useCallback(()=>{r(null),a(!1)},[]),v=i.useCallback(async k=>{if(k.sessions.length===0)return;if(k.sessions.length===1){const E=k.sessions[0];await l(E.id)?ae.success("Session deleted"):ae.error("Failed to delete session");return}const j=k.sessions.map(E=>E.id),{deletedIds:y,failedIds:C}=await c(j);if(y.length>0){const E=C.length>0?C.length===1?`${C.length} session could not be deleted.`:`${C.length} sessions could not be deleted.`:k.dateLabel?`Removed all sessions from ${k.dateLabel}.`:void 0;ae.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:Cn(E)})}C.length>0&&ae.error(C.length===1?`Failed to delete ${C.length} session`:`Failed to delete ${C.length} sessions`,{description:Cn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>xs.onDeleteRequest(k=>{if(!u){v(k);return}g(k)}),[g,u,v]),i.useEffect(()=>xs.onDirectoryRequest(()=>{s(!0)}),[]);const x=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const k=n.sessions[0];if(!await l(k.id)){ae.error("Failed to delete session"),a(!1);return}ae.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=n.sessions.map(E=>E.id),j=await c(k),y=j.deletedIds,C=j.failedIds;if(y.length>0){const E=C.length>0?C.length===1?`${C.length} session could not be deleted.`:`${C.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ae.success(y.length===1?"Deleted {count} session":`Deleted ${y.length} sessions`,{description:Cn(E),action:{label:"OK",onClick:()=>{}}})}if(C.length>0&&(ae.error(C.length===1?`Failed to delete ${C.length} session`:`Failed to delete ${C.length} sessions`,{description:Cn("Please try again in a moment.")}),y.length===0)){a(!1);return}}h()}finally{a(!1)}}},[n,l,c,h]),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.`:"",w=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(k=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:cs(k)})},k.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:()=>d(!u),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":!u,children:[u?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(Me,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),t.jsx(Me,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),N=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(yi,{open:!!n,onClose:()=>{o||h()},title:N,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}),w]})}):t.jsx(Ht,{open:!!n,onOpenChange:k=>{if(!k){if(o)return;h()}},children:t.jsxs(Yt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:N}),I&&t.jsx(us,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),t.jsx(Ss,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),t.jsx(bu,{open:e,onOpenChange:s})]})},rg=()=>{const e=ys(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(ys.getState().markNotificationSent(s.key),ae.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},xu=[{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"]}],yu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function wu(e){const s=e.trim().toLowerCase();return xu.find(n=>n.slug===s)??null}function vu(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=yu[s];if(n)return n;const r=wu(s);return r?r.slug:"home"}function og(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"snippets":return"chat-thread";case"prompt-templates":return"terminal";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}function ig(){const e=i.useRef(!1),s=i.useRef(!1),n=Ee(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),a=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=Ee.getState().currentSessionId,b=Ms().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==b){const m=Ee.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,m)}}if(f.settingsPath){a(vu(f.settingsPath)),o(!0);return}le.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]),u=i.useCallback(()=>{const f=Ee.getState(),p=Ms().getState(),b=le.getState();return{sessionId:or({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),d=i.useCallback((f={})=>{if(s.current)return;const p=u();Or(p,f)},[u]);i.useEffect(()=>{if(e.current||(e.current=!0,!No()))return;const f=Io();(async()=>(await c(f),Or({...u(),sessionId:f.sessionId??or({currentSessionId:Ee.getState().currentSessionId,piSelectedSessionId:Ms().getState().selectedSessionId,draft:Ee.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),i.useEffect(()=>{const f=()=>{const v=Ee.getState(),x=Ms().getState();return or({currentSessionId:v.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:v.newSessionDraft})};let p=f(),b=Ee.getState().newSessionDraft?.open===!0;const m=()=>{const v=Ee.getState(),x=f(),I=v.newSessionDraft?.open===!0;x===p&&I===b||s.current||(p=x,b=I,d({replace:!0}))},g=Ee.subscribe(()=>{m()}),h=Ms().subscribe(()=>{m()});return()=>{g(),h()}},[d]),i.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,b=le.getState().settingsPage,m=le.getState().pendingDiffFile;return le.subscribe(h=>{if(s.current)return;const v=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==p,I=h.settingsPage!==b,w=h.pendingDiffFile!==m&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,b=h.settingsPage,m=h.pendingDiffFile,(v||x||I||w)&&d()})},[d]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Io();if(No())c(p);else{const b=le.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function Su(e=!0){const s=Dn(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,u=null;const d=p=>{const b=Math.round(p*1e3);return Math.max(a,Math.min(l,b))},f=p=>{c||(u=window.setTimeout(async()=>{const b=await n.current(),m=typeof b=="number"&&Number.isFinite(b)?d(b):o;f(m)},p))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function ag(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return Su(e),null}const zo=12,ju=[{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"}],Cu=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=ju,onComplete:a})=>{const l=Ie.useRef(!1);Ie.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ie.useMemo(()=>Array.from({length:zo},(u,d)=>{const f=Math.PI*2*d/zo;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?t.jsx("div",{className:U("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(u=>{const d={"--burst-delay":`${u.delay}ms`,"--burst-x":`${u.x}%`,"--burst-y":`${u.y}%`,"--firework-color":`var(${u.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:d,children:c.map((f,p)=>{const b=f.x*u.radius,m=f.y*u.radius,g={"--translate-x":`${b}px`,"--translate-y":`${m}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return t.jsx("span",{className:"firework-particle",style:g},`${u.id}-${p}-${s}`)})},`${u.id}-${s}`)})}):null},ku=({durationMs:e=3400}={})=>{const[s,n]=Ie.useState({isActive:!1,cycle:0}),r=Ie.useRef(null),o=Ie.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ie.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ie.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 Ie.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},aa=i.createContext(void 0),lg=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=ku(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(aa.Provider,{value:a,children:[e,t.jsx(Cu,{isActive:s,burstKey:n})]})},Au={triggerFireworks:()=>{},dismissFireworks:()=>{}},cg=()=>i.useContext(aa)??Au,Un=2e3,la=600*1e3;async function Nu(){try{const e=await Ot("/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 Iu(e,s=Math.ceil(la/Un),n=Un,r=Xe()){for(let o=0;o<s;o++){if(Xe()!==r)return{applied:!1,stale:!0};try{const a=await Ot("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==r)return{applied:!1,stale:!0};if(a.ok){const l=await a.json().catch(()=>null);if(Xe()!==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(Xe()!==r)return{applied:!1,stale:!0}}await new Promise(a=>setTimeout(a,n))}return{applied:!1}}async function Ru(e,s,n=Math.ceil(la/Un),r=Un,o=Xe()){for(let a=0;a<n;a++){if(Xe()!==o)return{applied:!1,stale:!0};try{const l=await Ot(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Xe()!==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(Xe()!==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(Xe()!==o)return{applied:!1,stale:!0};s("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const $o="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 Du(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Go(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 Pu(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 ca=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,p]=Ie.useState(null),[b,m]=Ie.useState("idle"),[g,h]=Ie.useState(null),[v,x]=Ie.useState(null),[I,w]=Ie.useState({}),A=n?.version?n.releaseUrl||`${$o}/tag/v${n.version}`:$o,N=n?.downloadUrl||A,k=a?.total?Math.round(a.downloaded/a.total*100):0,j=d==="web",y=d==="mobile",C=n?.updateCommand||"pichamber update",E=I.version||n?.version,P=I.channel||n?.channel;Ie.useEffect(()=>{e||(m("idle"),h(null),x(null),w({}))},[e]);const B=async(M=C)=>{(await ws(M)).ok&&(p(M),setTimeout(()=>p(null),2e3))},L=Ie.useCallback(async M=>{await wi(M)},[]),z=Ie.useCallback(async()=>{const M=Xe();m("updating"),h(null),x(null),w({});const _=await Nu();if(Xe()!==M)return;if(!_.success){m("error"),h(_.error||"Update failed"),x(_.commands??null);return}if(w({version:_.targetVersion,channel:_.channel}),_.jobId){const $=await Ru(_.jobId,G=>{Xe()===M&&m(G)},void 0,void 0,M);if($.stale||Xe()!==M)return;if($.applied){window.location.reload();return}m("error"),h($.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}m(_.autoRestart?"restarting":"reconnecting");const se=await Iu(n?.currentVersion,void 0,void 0,M);if(!(se.stale||Xe()!==M)){if(se.applied){window.location.reload();return}m("error"),h(se.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),Q=Ie.useCallback(()=>{L(N)},[L,N]),O=b!=="idle"&&b!=="error",T=Ie.useMemo(()=>{if(!n?.body)return null;const M=n.body.trim();if(!M)return null;const _=Pu(M);return _.length===0?{kind:"raw",title:"What's new",content:Go(M)}:{kind:"sections",title:"What's new",sections:[..._].sort(($,G)=>Mu($.version,G.version)).map($=>({version:$.version,dateLabel:Eu($.date),content:Go(Du($.raw)||M)}))}},[n?.body]);return t.jsx(Ht,{open:e,onOpenChange:O?void 0:s,children:t.jsxs(Yt,{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(ss,{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||E)&&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&&E&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),E&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:E})]}),j&&P&&t.jsx("span",{className:"ml-3 typography-meta text-muted-foreground",children:P==="rc"?"RC subscription":"Stable subscription"})]}),t.jsxs("div",{className:"space-y-2",children:[j&&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(ps,{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:M=>{const se=M.target.closest("a");se&&se.href&&(M.preventDefault(),M.stopPropagation(),L(se.href))},children:t.jsx(Ro,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(M=>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",M.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:M.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:_=>{const $=_.target.closest("a");$&&$.href&&(_.preventDefault(),_.stopPropagation(),L($.href))},children:t.jsx(Ro,{content:M.content,disableLinkSafety:!0,enableFileReferences:!1})})]},M.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})}),j&&b==="error"&&(v??[C]).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:v?"Run these commands:":"Or update via terminal:"})]}),(v??[C]).map(M=>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:M}),t.jsx(Me,{variant:"ghost",size:"icon",onClick:()=>{B(M)},className:f===M?"text-[var(--status-success)]":void 0,title:f===M?"Copied!":"Copy command","aria-label":f===M?"Copied!":"Copy command",children:f===M?t.jsx(R,{name:"check",className:"h-4 w-4"}):t.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},M))]}),!j&&!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:[k,"%"]})]}),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:`${k}%`}})})]})]}),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:[!j&&!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"]}),!j&&!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..."]}),!j&&!y&&o&&t.jsxs("button",{onClick:u,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(Me,{onClick:Q,size:"default",children:[t.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!O&&t.jsxs("button",{onClick:z,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"]}),j&&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..."]})]})]})]})})},Tu=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(d=>{d.preventDefault(),d.stopPropagation(),!r&&!s&&n()},[s,r,n]),u=i.useCallback(d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:u,disabled:r,"aria-checked":s,"aria-label":o,className:U("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:U("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),pn=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const u=a.current;u&&c.target instanceof Node&&u.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(ze,{open:r,onOpenChange:o,children:[t.jsx($e,{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:U("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(Ge,{sideOffset:8,className:U("max-w-sm",n),children:e})]})},dg="w-full min-w-40 max-w-48",ug="settings",Fu="w-full min-w-40 max-w-48",fg="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ou="w-full max-w-[24rem]",hg="min-w-0 flex-1",pg="flex w-full min-w-0 items-center gap-2",mg="typography-meta shrink-0 text-muted-foreground tabular-nums",da="space-y-3.5",Lu="space-y-1.5",gg="typography-settings-page-title text-muted-foreground",Bu="typography-settings-section-title text-foreground",ua="typography-settings-group-title text-foreground",to="typography-settings-field-label text-foreground",_u="typography-settings-description text-muted-foreground",mn="typography-meta text-muted-foreground",bg="typography-meta font-medium text-foreground",xg="typography-settings-section-title text-foreground",Uu=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:u,settingsItem:d})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":d,className:U("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:Bu,children:e}):e,n,r!=null?t.jsx(pn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:_u,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:U(u),children:a})]})},yg=({children:e,className:s})=>t.jsx("div",{className:U("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),zu=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:U(ua,s),children:e}),wg=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:U("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(zu,{children:e}),n!=null?t.jsx(pn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:mn,children:s}):null]}):null,t.jsx("div",{className:U(a),children:r})]}),an=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const u=s!=null?t.jsx("p",{className:mn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:U("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:to,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),r==="before"?u:null]}),t.jsx("div",{className:U("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},vg=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,labelClassName:l,controlClassName:c,alignEnd:u=!0})=>t.jsxs("div",{"data-settings-item":o,className:U("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:U("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:to,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),s!=null?t.jsx("p",{className:U(mn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:U("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",u&&"@xl:justify-end",c),children:r})]}),Sg=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:U("pt-4",s),children:e}),$u=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:u,info:d})=>{const f=()=>{o||s(!e)},p=r!=null;return t.jsxs("div",{"data-settings-item":l,className:U("group flex cursor-pointer gap-2 py-0.5",p?"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(Cr,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:to,children:n}),u,d!=null?t.jsx(pn,{children:d}):null]}),p?t.jsx("span",{className:mn,children:r}):null]})]})},jg=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:U("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(Tu,{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:U("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:mn,children:r}):null]})]}),Cg=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:U(Lu,n),children:s});function kg({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:U("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Me,{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 Ur="pichamber:server-update-channel-changed",Ag=()=>{typeof window<"u"&&window.dispatchEvent(new Event(Ur))},Gu=e=>typeof window>"u"?()=>{}:(window.addEventListener(Ur,e),()=>window.removeEventListener(Ur,e));class Ku 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(tc,{className:"w-full max-w-md",children:[t.jsx(sc,{className:"text-center",children:t.jsxs(nc,{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(rc,{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(Me,{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 Wu(e){return t.jsx(Ku,{...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 Ng=({active:e=!0})=>{const s=Ee(n=>n.currentSessionId);return t.jsx(Wu,{sessionId:s||void 0,children:t.jsx(oc,{active:e},s??"no-session")})};function Hu({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 fa=Ie.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:p,...b},m)=>{const g=Ie.useRef(null),h=Ie.useRef(null),[v,x]=Ie.useState(null),I=c??v,w=Ie.useCallback(N=>{const k=g.current;if(!k)return;h.current={startY:N.clientY,startHeight:k.getBoundingClientRect().height};const j=N.currentTarget;j.setPointerCapture(N.pointerId);const y=E=>{const P=h.current;if(!P)return;const B=P.startHeight+(E.clientY-P.startY),L=Math.max(82,B);u?u(L):x(L)},C=()=>{h.current=null,j.removeEventListener("pointermove",y),j.removeEventListener("pointerup",C),j.removeEventListener("pointercancel",C)};j.addEventListener("pointermove",y),j.addEventListener("pointerup",C),j.addEventListener("pointercancel",C),N.preventDefault()},[u]),A=Ie.useCallback(N=>{if(N.target.closest('textarea, button, [role="separator"]'))return;const j=g.current?.querySelector("textarea");j&&document.activeElement!==j&&(N.preventDefault(),j.focus())},[]);return f?t.jsx(ps,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:U("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:d,...b}):t.jsx("div",{ref:g,onPointerDown:A,style:I!==null?{height:`${I}px`}:void 0,className:U("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:m,className:U("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",!d&&["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"],d&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,t.jsx(Hu,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});fa.displayName="Textarea";const ha=[{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"}],ln=Object.fromEntries(ha.map(e=>[e.key,e.Icon])),zr="pichamber:project-actions-updated",pa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},es=(e,s)=>`${pa(e)}::${s}`,ma=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:u,divider:d=!0})=>t.jsx(Uu,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:d,className:c,contentClassName:u,children:l}),$r=e=>e.name.trim().length>0&&e.command.trim().length>0,Yu=e=>e.name.trim().length===0&&e.command.trim().length===0,qu=e=>!$r(e)&&!Yu(e),Qu=(e,s)=>e.some(r=>s.has(r.id)&&!$r(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter($r)},Vu=450,Ju=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Xu=()=>({id:Ju(),name:"",command:"",icon:"play"}),Zu=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,u]=i.useState(new Set),d=i.useRef(!1);i.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const I=await kr(e);if(x)return;n(I.actions),l(JSON.stringify({actions:I.actions})),u(new Set(I.actions.map(w=>w.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),u(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=i.useMemo(()=>Qu(s,c),[s,c]),p=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=a!==null&&f.canPersist&&p!==a,m=i.useCallback(async x=>await ic(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),u(new Set(x.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(zr,{detail:{projectId:e.id}})),!0):(ae.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!b||r||d.current)return;const x=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await m(f.actions)}finally{d.current=!1}})())},Vu);return()=>{window.clearTimeout(x)}},[b,r,m,f.actions]);const g=i.useCallback(()=>{const x=Xu();n(I=>[...I,x])},[]),h=i.useCallback(x=>{n(I=>I.filter(w=>w.id!==x))},[]),v=i.useCallback((x,I)=>{n(w=>w.map(A=>A.id===x?I(A):A))},[]);return t.jsx(ma,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Me,{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:U("space-y-6",Ou),children:s.map((x,I)=>{const w=x.icon||"play",A=ln[w]||"play",N=x.name.trim()||`Action ${I+1}`,k=qu(x);return t.jsxs("div",{className:da,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:ua,children:N}),t.jsx(Me,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${N}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(an,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Pt,{children:[t.jsx(Tt,{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(Ft,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:ha.map(j=>{const y=j.Icon,C=(x.icon||"play")===j.key;return t.jsx("button",{type:"button",onClick:()=>v(x.id,E=>({...E,icon:j.key})),className:U("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",C&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:t.jsx(R,{name:y,className:"h-4 w-4"})},j.key)})})})]}),t.jsx(dn,{value:x.name,onChange:j=>v(x.id,y=>({...y,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(an,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(fa,{value:x.command,onChange:j=>v(x.id,y=>({...y,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),k?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx($u,{checked:x.autoOpenUrl===!0,onChange:j=>v(x.id,y=>({...y,...j?{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 ${N}`}),x.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(an,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(dn,{value:x.openUrl||"",onChange:j=>v(x.id,y=>({...y,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},ef={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)"},tf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Kt(y=>y.providers),u=Kt(y=>y.modelsMetadata),d=le(y=>y.hiddenModels),f=le(y=>y.isFavoriteModel),p=le(y=>y.toggleFavoriteModel),b=le(y=>y.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:g}=ac(),[h,v]=i.useState(!1),[x,I]=i.useState("");i.useEffect(()=>{h||I("")},[h]);const w=e?c.find(y=>y.id===e.providerId):void 0,A=e&&w?(Array.isArray(w.models)?w.models:[]).find(y=>y.id===e.modelId):void 0,N=e?lc(A,e.modelId):s,k=i.useMemo(()=>e?d.filter(y=>!(y.providerID===e.providerId&&y.modelID===e.modelId)):d,[d,e]),j=i.useCallback(y=>{l({providerId:y.providerID,modelId:y.modelID}),v(!1)},[l]);return t.jsxs(Pt,{modal:!1,open:h,onOpenChange:y=>{r||v(y)},children:[t.jsx(Tt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:U(vi({size:"default"}),Fu,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(cc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:U("truncate",e?"text-foreground":"text-muted-foreground"),children:N})]}),t.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Ft,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(dc,{providers:c,favoriteModels:m,recentModels:g,modelsMetadata:u,searchQuery:x,onSearchQueryChange:I,onSelect:j,labels:{...ef,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:k,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),v(!1)},disabled:r,autoFocus:!0,onEscape:()=>v(!1),isFavorite:y=>f(y.providerID,y.modelID),onToggleFavorite:y=>p(y.providerID,y.modelID),onReorderFavorite:(y,C)=>b(y.providerID,y.modelID,C.providerID,C.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",sf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Kt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(ma,{title:"Project",divider:!1,children:t.jsxs("div",{className:da,children:[t.jsx(an,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(dn,{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(an,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ar,children:t.jsx(tf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ar,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},nf=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(()=>uc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((d,f)=>{o(d&&f?`${d}/${f}`:void 0)},[]),u=i.useCallback(async()=>{if(!e)return null;const d=s.trim();return d?{label:d,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:u,project:e}},rf=450,of=(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 u=await a();if(u)try{await s(u)}catch{ae.error("Failed to save project settings")}}finally{l.current=!1}})())},rf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},af=({project:e,onIdentitySave:s})=>{const n=nf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return of(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(sf,{form:n}),t.jsx(Zu,{projectRef:r})]})};function so({...e}){return t.jsx($i,{...e})}function no({...e}){return t.jsx(Gi,{...e})}function ro({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(Ki,{children:t.jsx(Wi,{className:U("app-region-no-drag z-50",s),children:t.jsx(Hi,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:U(Si,e),...o,children:n})})})}function Fs({className:e,...s}){return t.jsx(Yi,{className:U(ji,e),...s})}function ga({className:e,...s}){return t.jsx(qi,{className:U(Ci,e),...s})}const kn=100;function Ig(){const e=le(y=>y.isArchivePageOpen),s=le(y=>y.setArchivePageOpen),n=le(y=>y.setActiveMainTab),r=Ee(y=>y.setCurrentSession),o=Ee(y=>y.unarchiveSession),a=Ls(y=>y.homeDirectory),l=Ar({archived:!0}),[c,u]=i.useState(""),[d,f]=i.useState(null),[p,b]=i.useState(kn),m=c.trim().toLowerCase(),g=i.useMemo(()=>e?[...l].sort((y,C)=>(C.time?.archived??0)-(y.time?.archived??0)):[],[l,e]),h=i.useMemo(()=>{const y=new Map;for(const C of g){const E=Ne(rn(C))??"",P=y.get(E);if(P){P.sessions.push(C);continue}y.set(E,{directory:E,label:E?Bs(E,a)||E:"other projects",sessions:[C]})}return[...y.values()].sort((C,E)=>E.sessions.length-C.sessions.length)},[a,g]),v=i.useMemo(()=>m?g.filter(y=>(y.title??"").toLowerCase().includes(m)):d===null?g:h.find(y=>y.directory===d)?.sessions??[],[h,m,d,g]),x=v.slice(0,p),I=v.length-x.length,w=l.length,A=i.useCallback(y=>{f(y),b(kn)},[]),N=i.useCallback(y=>{const C=Ne(rn(y));r(y.id,C??void 0),n("chat"),s(!1)},[n,r,s]),k=i.useCallback(y=>{o(y.id).then(C=>{C?ae.success("Session restored"):ae.error("Failed to restore session")})},[o]);if(!e)return null;const j=(y,C,E,P,B,L,z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:B,title:L,className:U("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",z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"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:C}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),z?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>xs.requestDelete({sessions:z,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 ${C}`,children:t.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},y);return t.jsx(Pd,{open:e,onOpenChange:s,children:t.jsxs(Td,{children:[t.jsx(Fd,{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(Od,{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(Ld,{className:"sr-only",children:"Archived sessions"}),t.jsx(Bd,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(_d,{"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:[j("__all__","All directories",w,d===null,()=>A(null)),h.map(y=>j(y.directory||"__none__",y.label,y.sessions.length,d===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=>{u(y.target.value),b(kn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:v.length===1?`${v.length} archived session`:`${v.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:m?"No matching archived sessions":"No archived sessions"})}):x.map(y=>{const C=Ne(rn(y))??"",E=C?Bs(C,a)||C: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:()=>N(y),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),N(y))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:cs(y)}),m&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:C,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:jd(y.time?.archived??y.time?.updated??y.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),k(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 ${cs(y)}`,children:t.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),xs.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 ${cs(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+kn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const lf=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}},cf=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},Wt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,df=e=>{if(!e||typeof e!="object")return null;const s=Wt(e.input),n=Wt(e.output),r=Wt(e.cacheRead),o=Wt(e.cacheWrite);return{input:s,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:s+n+r+o}},Ko=e=>{const s=df(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:Wt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,a=Wt(o.input),l=Wt(o.output),c=Wt(o.reasoning),u=Wt(o.cache?.read),d=Wt(o.cache?.write);return{input:a,output:l,reasoning:c,cacheRead:u,cacheWrite:d,total:a+l+c+u+d}},ba=380,lr=8,uf=140;function ff({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[u,d]=i.useState(!1),[f,p]=i.useState(null),{enabled:b}=qr();return i.useLayoutEffect(()=>{if(!e||!b||!l)return;const m=()=>{const v=n.current?.getBoundingClientRect(),x=a.current?.getBoundingClientRect();if(!v||!x){p(null);return}const I=v.left-x.left;p(Math.min(Math.max(I,lr),Math.max(lr,x.width-ba-lr)))};m();const g=a.current;if(typeof ResizeObserver>"u"||!g)return;const h=new ResizeObserver(m);return h.observe(g),()=>h.disconnect()},[n,b,e,l]),i.useEffect(()=>{if(e){c(!0),d(!1);return}if(!l)return;d(!0);const m=window.setTimeout(()=>{c(!1),d(!1)},uf);return()=>window.clearTimeout(m)},[e,l]),i.useEffect(()=>{if(!e)return;const m=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[s,e]),i.useEffect(()=>{if(!e)return;const m=g=>{const h=g.target;if(!(h instanceof Node)){s();return}o.current?.contains(h)||n.current?.contains(h)||s()};return document.addEventListener("pointerdown",m,!0),r&&document.addEventListener("wheel",m,!0),()=>{document.removeEventListener("pointerdown",m,!0),r&&document.removeEventListener("wheel",m,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:u,anchorLeft:f,isPopover:b&&f!==null}}const Wo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},zn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),An=({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})]}),hf=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:u,isPopover:d}=ff({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:U("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",d?"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))",...d?{top:8,left:u??8,width:`min(${ba}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(An,{iconNode:t.jsx(ki,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:U("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(An,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:zn(r.cacheRead)})}),t.jsx(An,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:zn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(An,{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},pf=i.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:a}){const l=i.useRef(null),c=fc(r??""),u=Kt(O=>O.providers),d=Kt(O=>O.currentProviderId),f=Kt(O=>O.currentModelId),p=Kt(O=>O.getCurrentModel()),b=Kt(O=>O.getModelMetadata);Kt(O=>O.modelsMetadata.size);const m=hc(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 M=T.model,_=M?.providerID??M?.providerId,se=M?.modelID??M?.modelId,$=typeof _=="string"&&_.trim().length>0?_:void 0,G=typeof se=="string"&&se.trim().length>0?se:void 0;if($&&G)return{providerID:$,modelID:G}}return null},[c]),h=i.useMemo(()=>{for(let O=c.length-1;O>=0;O-=1){const T=c[O];if(T?.info.role==="assistant"&&Ko(T).total>0)return T}return null},[c]),v=g??(()=>{const O=h?.info.model,T=O?.providerID??O?.providerId,M=O?.modelID??O?.modelId;return T&&M?{providerID:T,modelID:M}:null})()??(m?{providerID:m.providerId,modelID:m.modelId}:null)??(d&&f?{providerID:d,modelID:f}:null),I=(v?u.find(O=>O.id===v.providerID):void 0)?.models.find(O=>O.id===v?.modelID),w=v?b(v.providerID,v.modelID):void 0,A=Wo(I?.limit,"context")??w?.limit?.context??Wo(p?.limit,"context")??0,N=h?Ko(h):null,k=h?.info?.usage,j=k?cf(k):N?.total??0,y=!a&&j>0&&A>0?Math.min(j/A*100,999):null,C=y!==null?`${zn(j)}/${zn(A)}`:null,E=y===null?"":y>=90?"text-[var(--status-error)]":y>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",P=N?.cacheRead??null,B=N?.cacheWrite??null,L=N?lf({input:N.input,cache:{read:N.cacheRead,write:N.cacheWrite}}):{percent:0,hasInput:!1},z=L.hasInput?L.percent:null,Q=y!==null&&C?{percentage:y,tokens:C,colorClass:E,cacheRead:P,cacheWrite:B,cacheHitPercent:z}: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(ki,{percentage:Q?.percentage??0,size:20,className:"size-5 -rotate-90"})}),t.jsx(hf,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:Q})]})}),gn="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",mf="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",gf=i.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:o,className:a,Icon:l,iconClassName:c,pressed:u=!1}){return s?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":u,className:U(a??gn,u&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:n})})]}):null}),xa=({variant:e="desktop"})=>{const s=ys(f=>f.entries),[n,r]=i.useState(!1),o=i.useRef(null),a=i.useMemo(()=>[...s.values()].sort((f,p)=>p.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)},[]),u=i.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(i.useEffect(()=>()=>c(),[c]),a.length===0)return null;const d=f=>{const p=f.receipt;if(!p)return;const b=Ee.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:p.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:p.path}),ys.getState().clearEntry(f.key),le.getState().setActiveMainTab("chat"),r(!1)};return t.jsxs(Pt,{open:n,onOpenChange:r,children:[t.jsx(Tt,{asChild:!0,children:t.jsxs("button",{type:"button",className:U(e==="desktop"?gn:"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"&&u()},children:[l>0?t.jsx(js,{variant:"inline",text:null,animationType:"spinner"}):t.jsx(R,{name:"task",className:"size-[18px]"}),t.jsx("span",{children:"Background tasks"})]})}),t.jsxs(Ft,{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:u,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(bf,{entry:f,onOpen:()=>d(f)},f.key))})]})]})},bf=({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(js,{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(Me,{type:"button",variant:"ghost",size:"xs",onClick:()=>ys.getState().dismissFailed(e.key),children:"Dismiss"}):null,o?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Me,{type:"button",size:"xs",onClick:s,children:"Open"}),t.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>ys.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:t.jsx(R,{name:"close",className:"size-3.5"})})]}):null]})},xf=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:a,unresolvedWorktreeProjectPaths:l,foldersMap:c,createFolder:u,addSessionToFolder:d}=e;i.useEffect(()=>{!n||!o||a||s.forEach(f=>{if(l.has(f.normalizedPath))return;const p=_i(f.normalizedPath),b=r.archivedSessionsByProject.get(f.id)??[],m=c[p]??[],g=new Map(m.map(h=>[h.name.toLowerCase(),h]));b.forEach(h=>{const v=Cd(h,f.normalizedPath),x=v.toLowerCase();let I=g.get(x);I||(I=u(p,v),g.set(x,I)),I.sessionIds.includes(h.id)||d(p,I.id,h.id)})})},[s,n,r,o,a,l,c,u,d])},yf=e=>({getOrderedGroups:i.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const a=new Map(r.map(d=>[d.id,d])),l=[];o.forEach(d=>{const f=a.get(d);f&&(l.push(f),a.delete(d))});const c=[],u=[];return r.forEach(d=>{a.has(d.id)&&(d.isArchivedBucket?u.push(d):c.push(d))}),[...c,...l,...u]},[e])}),wf=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:u,hasSessionSearchQuery:d,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:b,foldersMap:m}=e,g=i.useRef(new Map),h=i.useMemo(()=>{const j=g.current,y=new Map;let C=0,E=0;const P=(L,z)=>L.length===z.length&&L.every((Q,O)=>Q===z[O]),B=s.map(L=>{const z=n(L.id),Q=r(L.id),O=a.has(L.id)?!!a.get(L.id):c,T=l.get(L.id)??null,M=o.get(L.normalizedPath)??[],_=j.get(L.id);if(_&&_.project===L&&P(_.activeSessions,z)&&P(_.archivedSessions,Q)&&_.rootBranch===T&&_.isRepo===O&&_.worktrees===M&&_.buildGroupedSessions===u)return C+=1,y.set(L.id,_),_.section;E+=1;const se=Ui([...z,...Q]),$=u(se,L.normalizedPath,M,T,O),G={project:L,groups:$};return y.set(L.id,{project:L,activeSessions:z,archivedSessions:Q,rootBranch:T,isRepo:O,worktrees:M,buildGroupedSessions:u,section:G}),G});return g.current=y,C>0&&Mt("ui.sidebar.project_section.reused",C),E>0&&Mt("ui.sidebar.project_section.rebuilt",E),B},[s,n,r,o,a,c,u,l]),v=i.useMemo(()=>h,[h]),x=i.useMemo(()=>{const j=new WeakMap;if(!d)return j;const y=C=>C.reduce((E,P)=>E+1+y(P.children),0);return v.forEach(C=>{C.groups.forEach(E=>{const P=p(E.sessions,f),B=y(P),L=b(E).includes(f),z=Ne(E.directory??null),O=(z?m[z]??[]:[]).filter(T=>T.name.toLowerCase().includes(f)).length;j.set(E,{filteredNodes:P,matchedSessionCount:B,folderNameMatchCount:O,groupMatches:L,hasMatch:L||B>0||O>0})})}),j},[d,v,p,f,b,m]),I=i.useMemo(()=>d?v.map(j=>({...j,groups:j.groups.filter(y=>x.get(y)?.hasMatch===!0)})).filter(j=>j.groups.length>0):v,[d,v,x]),w=d?I:v,A=i.useRef(new WeakMap),N=i.useMemo(()=>{const j=A.current;return w.map(y=>{const C=j.get(y);if(C&&C.query===f)return C.section;const E=y.groups.filter(T=>!T.isArchivedBucket),P=y.groups.filter(T=>T.isArchivedBucket),B=E.flatMap(T=>d?x.get(T)?.filteredNodes??[]:T.sessions),L=E.map(T=>({scopeKey:T.folderScopeKey??Ne(T.directory??null),directory:T.directory??null})).filter(T=>!!T.scopeKey),z=E.find(T=>T.isMain)??null,Q={id:"flat",label:z?.label??"",branch:z?.branch??null,description:z?.description??null,isMain:!0,isArchivedBucket:!1,directory:z?.directory??y.project.normalizedPath,folderScopeKey:z?.folderScopeKey??y.project.normalizedPath,folderScopes:L,sessions:B};if(d){const T=E.map(M=>x.get(M)).filter(M=>!!M);x.set(Q,{filteredNodes:B,matchedSessionCount:T.reduce((M,_)=>M+_.matchedSessionCount,0),folderNameMatchCount:T.reduce((M,_)=>M+_.folderNameMatchCount,0),groupMatches:T.some(M=>M.groupMatches),hasMatch:T.some(M=>M.hasMatch)})}const O={project:y.project,groups:[Q,...P]};return j.set(y,{query:f,section:O}),O})},[x,d,f,w]),k=i.useMemo(()=>d?w.reduce((j,y)=>j+y.groups.reduce((C,E)=>{const P=x.get(E);if(!P)return C;const B=P.folderNameMatchCount+(P.groupMatches?1:0);return C+P.matchedSessionCount+B},0),0):0,[d,w,x]);return{projectSections:h,visibleProjectSections:v,groupSearchDataByGroup:x,searchableProjectSections:I,sectionsForRender:w,flatSectionsForRender:N,searchMatchCount:k}},vf=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:u,openNewSessionDraft:d,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,b=i.useMemo(()=>{const g=new Map,h=new Map,v=(x,I,w,A)=>{g.has(x)||g.set(x,new Map);const N=g.get(x);A.forEach(k=>{const j=Ne(k.session.directory??w??I);N.set(k.session.id,{directory:j}),h.has(x)||h.set(x,{id:k.session.id,directory:j}),k.children.length>0&&v(x,I,j,k.children)})};return s.forEach(x=>{x.groups.forEach(I=>{v(x.project.id,x.project.normalizedPath,I.directory,I.sessions)})}),{metaByProject:g,firstSessionByProject:h}},[s]),m=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){m.current=n;return}if(m.current===n)return;const g=s.find(k=>k.project.id===n);if(!g)return;m.current=n;const h=b.metaByProject.get(n);if(a&&h&&h.has(a)){o(k=>{if(k.get(n)===a)return k;const j=new Map(k);return j.set(n,a),j});return}const v=a?Array.from(b.metaByProject.entries()).some(([k,j])=>k!==n&&j.has(a)):!1;if(a&&h&&!v)return;if(!h||h.size===0){f("chat"),u&&p(!1),d({selectedProjectId:g.project.id,directoryOverride:g.project.normalizedPath});return}const x=r.get(n),I=x&&h.has(x)?x:null,w=b.firstSessionByProject.get(n)?.id??null,A=I??w;if(!A||A===a)return;const N=h.get(A)?.directory??null;l(A,N,{keepPanelOpen:!0})},[n,r,a,l,c,u,d,s,b,f,p,o]),i.useEffect(()=>{if(!n||!a)return;const g=b.metaByProject.get(n);!g||!g.has(a)||o(h=>{if(h.get(n)===a)return h;const v=new Map(h);return v.set(n,a),v})},[n,a,b,o])},Sf=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Ee(c=>c.currentSessionId),o=Ee(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return vf({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},Ho=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],jf=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},Cf=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,ya=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=jf(e.trim())%Ho.length;return Ho[s]},kf=(e,s)=>{const n=ya(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Yo=e=>!!e.time?.archived,Af=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=Ne(a.directory??null)??"";return`${cs(a)} ${l}`.toLowerCase()},[]),r=i.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const d=r(c.children,l);return d.length===0?[]:[{...c,children:d}]}):a,[n]),o=i.useCallback((a,l,c=[],u,d)=>{const f=Ne(l??null),p=Ui(a).sort((j,y)=>Qr(j,y,e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(p.map(j=>[j.id,j])),m=new Map,g=new Map;p.forEach(j=>{const y=j.parentID??null,C=y?b.get(y):null,E=C&&Yo(C)===Yo(j)?y:null;m.set(j.id,E),E&&g.set(E,(g.get(E)??0)+1)});const h=c.map(j=>({worktree:j,directory:Ne(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,y)=>y.directory.length-j.directory.length),v=(j,y)=>y===j||y.startsWith(`${j}/`),x=j=>{const y=Ne(j.directory??null);return y?h.find(C=>v(C.directory,y))?.worktree??null:null},I=(j,y)=>{const C=Cf(j.id,m,g);return{session:j,children:[],worktree:y,forkColorId:C}},w=[],A=new Map,N=[];for(const j of h)A.set(j.directory,[]);p.forEach(j=>{const y=x(j),C=I(j,y);j.time?.archived?N.push(C):y?A.get(Ne(y.path)??"")?.push(C):w.push(C)});const k=[{id:"root",label:d&&u&&u!=="HEAD"?`project root: ${u}`:"project root",branch:u??null,description:f?Po(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:w}];for(const{worktree:j,directory:y}of h)k.push({id:`worktree:${y}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:Po(y,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:j,directory:y,folderScopeKey:y,sessions:A.get(y)??[]});return N.length>0&&k.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?_i(f):null,sessions:N}),k},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Nf=({mobileVariant:e,isTablet:s})=>!e&&!s,If=({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])},Rf=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((w,A,N)=>{Ir("navigation.session_select"),le.getState().closeMainSurfaces();const k=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},j=N?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),w===Ee.getState().currentSessionId){e.allowReselect&&j&&e.onSessionSelected?.(w),k();return}Ir("navigation.session_state_set"),e.setCurrentSession(w,A??null),j&&e.onSessionSelected?.(w),k()},[e]),a=i.useCallback((w,A)=>{e.setEditingId(w),e.setEditTitle(A)},[e]),l=i.useCallback(async w=>{if(!e.editingId)return;const A=(w??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]),u=i.useCallback(async(w,A)=>{try{return(await ws(w)).ok?(n(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),d=i.useCallback(async w=>{const A=await e.shareSession(w.id);if(!A?.share?.url){ae.error("Unable to share session");return}const N=await u(A.share.url,w.id);ae[N?"success":"warning"]("Session shared",{description:N?"Share link copied to clipboard.":"Failed to copy URL"})},[e,u]),f=i.useCallback((w,A)=>{u(w,A).then(N=>{N||ae.error("Failed to copy URL")})},[u]),p=i.useCallback(w=>{ws(w).then(A=>{if(A.ok){ae.success("Session ID copied");return}ae.error("Failed to copy session ID")}).catch(()=>ae.error("Failed to copy session ID"))},[]),b=i.useCallback(async w=>{await e.unshareSession(w)?ae.success("Session unshared"):ae.error("Unable to unshare session")},[e]),m=i.useCallback(w=>{const A=[],N=k=>{(e.childrenMap.get(k)??[]).forEach(y=>{A.push(y),N(y.id)})};return N(w),A},[e.childrenMap]),g=i.useCallback((w,A)=>A?w:w.filter(N=>!N.time?.archived),[]),h=i.useCallback(async(w,A,N)=>{const k=A?.archivedBucket===!0||A?.hardDelete===!0,j=N?.descendantIds??g(m(w.id),k).map(P=>P.id);if(j.length===0){(k?await e.deleteSession(w.id):await e.archiveSession(w.id))?ae.success(k?"Session deleted":"Session archived"):ae.error(k?"Failed to delete session":"Failed to archive session");return}const y=[w.id,...j];if(k){const{deletedIds:P,failedIds:B}=await e.deleteSessions(y);if(B.length===0){const L=P.length;ae.success(L===1?`Deleted ${L} session`:`Deleted ${L} sessions`)}else ae.error("Failed to delete session");return}const{archivedIds:C,failedIds:E}=await e.archiveSessions(y);C.length>0&&ae.success(C.length===1?`Archived ${C.length} session`:`Archived ${C.length} sessions`),E.length>0&&ae.error(E.length===1?`Failed to archive ${E.length} session`:`Failed to archive ${E.length} sessions`)},[e,m,g]),v=i.useCallback((w,A)=>{const N=A?.archivedBucket===!0||A?.hardDelete===!0,k=g(m(w.id),N).map(j=>j.id);if(!e.showDeletionDialog||A?.skipConfirm===!0){h(w,A,{descendantIds:k});return}e.setDeleteSessionConfirm({session:w,descendantCount:k.length,descendantIds:k,archivedBucket:N})},[e,m,h,g]),x=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:w,archivedBucket:A,descendantIds:N}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(w,{archivedBucket:A},{descendantIds:N})},[e,h]),I=i.useCallback(async w=>{await e.unarchiveSession(w.id)?ae.success("Session restored"):ae.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:d,handleCopyShareUrl:f,handleCopySessionId:p,handleUnshareSession:b,handleDeleteSession:v,handleRestoreSession:I,confirmDeleteSession:x}},Ef=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:a,setCollapsedProjects:l}=e,c=i.useRef(null),u=i.useRef(null),d=i.useCallback(()=>{const p=u.current;if(u.current=null,c.current=null,!p)return;const{projects:b}=pt.getState(),m=b.map(g=>({...g,sidebarCollapsed:p.has(g.id)}));Vr({projects:m}).catch(()=>{})},[]),f=i.useCallback(p=>{typeof window>"u"||(u.current=p,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{d()},700))},[d]);return i.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,u.current=null},[]),i.useEffect(()=>{try{const p=s.getItem(n.sessionExpanded);if(p){const m=JSON.parse(p);Array.isArray(m)&&a(new Set(m.filter(g=>typeof g=="string")))}const b=s.getItem(n.projectCollapse);if(b){const m=JSON.parse(b);Array.isArray(m)&&l(new Set(m.filter(g=>typeof g=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const p=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(p))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:f}},Df=3;let $n=0;const wa=[],Mf=()=>$n<Df?($n+=1,Promise.resolve()):new Promise(e=>{wa.push(e)}),Pf=()=>{const e=wa.shift();if(e){e();return}$n=Math.max(0,$n-1)},Tf=async e=>{await Mf();try{return await e()}finally{Pf()}},Ff=5*6e4,Of=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=$s(),c=Ai(p=>p.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(p=>{Tf(()=>c(p.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const p=new Map;s.forEach(b=>{p.set(b.id,r.get(b.normalizedPath)?.isGitRepo??null)}),o(p)},[n,s,r,o]);const u=i.useMemo(()=>s.map(p=>{const b=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${b}`}).join("|"),[s,r]),d=i.useRef(new Map),f=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let p=!1;const b=setTimeout(()=>{(async()=>{const g=new Set(s.map(w=>w.id));for(const w of d.current.keys())g.has(w)||(d.current.delete(w),f.current.delete(w));const h=Date.now();if(s.filter(w=>{const A=r.get(w.normalizedPath);if(A?.isGitRepo===!1)return d.current.delete(w.id),f.current.delete(w.id),!1;if(A?.isGitRepo!==!0||A.branch===null)return!1;const N=A.branch.trim(),k=`${w.normalizedPath}\0${N}`,j=d.current.get(w.id);if(j===k){const y=f.current.get(w.id);return y&&(y.at=h),!1}return!(j!==void 0&&h-(f.current.get(w.id)?.at??0)<Ff)}).length===0)return;const x=[];if(s.forEach(w=>{const A=r.get(w.normalizedPath)?.branch?.trim()??"",N=`${w.normalizedPath}\0${A}`;A&&x.push({id:w.id,inputKey:N,branch:A})}),p||x.length===0)return;const I=Date.now();a(w=>{const A=new Map(w);return x.forEach(({id:N,branch:k})=>{k&&A.set(N,k)}),A}),x.forEach(({id:w,inputKey:A,branch:N})=>{d.current.set(w,A),N&&f.current.set(w,{branch:N,at:I})})})()},150);return()=>{p=!0,clearTimeout(b)}},[n,s,u,r,a])},Lf=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}},Bf=e=>{const s=new Map;for(const n of e){const r=rn(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},_f=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},Uf=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Jr(),l=Bf(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const u of _f(c,l))Ms().commitMissedDeletion(u.sessionId,u.directory);o.current={runtimeKey:a,identities:l}},[s,n,r])},zf=(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,qo=(e,s,n)=>{zf(e.get(s),n)&&e.set(s,n)},va=e=>{const s=e;return Ne(s.directory)??Ne(s.project?.worktree)},$f=(e,s,n)=>{if(e.time?.archived)return!0;const r=va(e);if(!r)return n?.allowUnknownDirectory??!0;if(Yn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const a of s)if(Ne(a)?.toLowerCase()===o)return!0;return!1},Gf=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)},Kf=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const m of s){const g=Ne(m.normalizedPath);if(!g)continue;const h=a.get(g);(!h||m.id.localeCompare(h.id)<0)&&a.set(g,m),qo(o,g,{projectId:m.id,projectRoot:g,scopeDirectory:g,kind:"project"})}if(n)for(const[m,g]of n){const h=Ne(m),v=h?a.get(h):void 0;if(!(!v||!h))for(const x of g||[]){const I=Ne(x?.path);I&&qo(o,I,{projectId:v.id,projectRoot:h,scopeDirectory:I,kind:"worktree"})}}const l=new Map,c=new Map,u=new Map,d=new Map,f=new Map,p=m=>{if(!m)return null;if(l.has(m))return l.get(m)??null;const g=[];let h=m,v=null;for(;h;){if(l.has(h)){v=l.get(h)??null;break}if(g.push(h),v=o.get(h)??null,v)break;h=Gf(h)}for(const x of g)l.set(x,v);return v},b=(m,g,h)=>{for(const v of m){const x=va(v);if(Yn(x))continue;const I=p(x);if(!I)continue;c.set(v.id,I);const w=g.get(I.projectId);if(w?w.push(v):g.set(I.projectId,[v]),!h)continue;const A=h.get(I.scopeDirectory);A?A.add(v.id):h.set(I.scopeDirectory,new Set([v.id]))}};return b(e,u,f),b(r,d),{bySessionId:c,sessionsByProject:u,archivedSessionsByProject:d,sessionsByScope:f,directoryResolutions:l.size}};function Sa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:U("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:U("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Wf=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:u,renderSessionNode:d,getRenderExtras:f,groupDirectory:p,projectId:b,mobileVariant:m=!1,alwaysShowActions:g=m,isRenaming:h=!1,renameDraft:v="",onRenameDraftChange:x,onRenameSave:I,onRenameCancel:w,droppableRef:A,isDropTarget:N=!1,onNewSession:k,depth:j=0,hideActions:y=!1,archivedBucket:C=!1})=>{const[E,P]=i.useState(!1),[B,L]=i.useState(""),z=i.useRef(null),Q=h||E,O=h?v:B,T=i.useCallback(()=>{L(e.name),P(!0)},[e.name]),M=i.useCallback(()=>{const G=O.trim();G&&G!==e.name&&c(G),h&&I&&I(),P(!1),L("")},[O,e.name,h,c,I]),_=i.useCallback(()=>{h&&w&&w(),P(!1),L("")},[h,w]),se=i.useCallback(G=>{h&&x?x(G):L(G)},[h,x]);i.useEffect(()=>{if(!h)return;const G=()=>{const Pe=z.current;Pe&&(Pe.focus(),Pe.select())},Ae=requestAnimationFrame(G),te=window.setTimeout(G,0);return()=>{cancelAnimationFrame(Ae),window.clearTimeout(te)}},[h]);const $=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:A,className:U("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",N&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:Q?void 0:G=>{G.currentTarget.blur(),l()},role:Q?void 0:"button",tabIndex:Q?void 0:0,onKeyDown:Q?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:U("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",C?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:$,className:U(Mn,N?"text-primary":"text-muted-foreground")}),Q?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(),M()},children:[t.jsx("input",{ref:z,value:O,onChange:G=>se(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(),_();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(),_()},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(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("span",{className:U(zi,N?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(Ge,{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(Sa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(R,{name:"arrow-right-s",className:U(Mn,"text-muted-foreground")}):t.jsx(R,{name:"arrow-down-s",className:U(Mn,"text-muted-foreground")})]})]}),!Q&&(!y||C)?t.jsx("div",{className:U("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:[!C&&k?t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),k()},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,C?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(),u()},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":C?`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:d(G,0,p??null,b??null,C,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"})]})]})},Hf=i.memo(Wf),Yf=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=$d({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),u=i.useCallback(d=>{d.stopPropagation(),a?.onPointerDown&&a.onPointerDown(d)},[a]);return t.jsx("div",{ref:l,...o,onPointerDown:u,className:c?"opacity-30":void 0,children:r})},qf=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Gd({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},Qf=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=Qi(Fr(Ud,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,u]=i.useState("Session"),[d,f]=i.useState(null),[p,b]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const m=g=>{l(null),f(null),b(null);const{active:h,over:v}=g;if(!v)return;const x=h.data.current,I=v.data.current;x?.type==="session"&&x.sessionId&&I?.type==="folder"&&I.folderId&&n(x.sessionId,I.folderId)};return t.jsxs(Vi,{sensors:o,collisionDetection:Ji,onDragStart:g=>{const h=g.active.data.current;if(h?.type==="session"&&h.sessionId){l(h.sessionId),u(h.sessionTitle??"Session");const v=g.active.rect.current.initial?.width,x=g.active.rect.current.initial?.height;f(typeof v=="number"?v:null),b(typeof x=="number"?x:null)}},onDragCancel:()=>{l(null),f(null),b(null)},onDragEnd:m,children:[r,t.jsx(zd,{children:a&&s?t.jsxs("div",{style:{width:d?`${d}px`:"auto",height:p?`${p}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})]})},bs=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:U(o?kd:Ad,r),children:[t.jsx(R,{name:e,className:U(un(o),"text-muted-foreground")}),t.jsx("span",{className:U(fn(o),"flex-1 text-muted-foreground"),children:s})]}),Qo=(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)},ts=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(ts(n,s))return!0;return!1},Vf=(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})},Vo=new WeakMap;let Jo=1;const Jf=e=>{const s=Vo.get(e);if(s!==void 0)return s;const n=Jo;return Jo+=1,Vo.set(e,n),n},Gr=e=>e.children.length===0?"":e.children.map(n=>{const r=Jf(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Gr(n)}`}).join("|"),ja=(e,s,n,r,o,a)=>{const l=Jr(),c=(u,d)=>{if(u.session.id!==d.session.id||u.children.length!==d.children.length)return!0;const f=u.session.directory??o,p=d.session.directory??a,b=Eo(l,f??"",u.session.id),m=Eo(l,p??"",d.session.id);return(b?n.has(b):!1)!==(m?r.has(m):!1)?!0:u.children.some((g,h)=>c(g,d.children[h]))};return c(e,s)},Gn=(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 d of c.children)if(l(d))return!0;return!1};return e.forEach(c=>l(c)),a},Ca=(e,s)=>"",Xf=Gs(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),ka=e=>null,oo=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Aa=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let o=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(o="unread");for(const l of e.children)if(o=oo(o,Aa(l,s,n,r)),o==="active")return o;return o},Na=(e,s,n,r)=>{let o=null;for(const a of e)if(o=oo(o,Aa(a,s,n,r)),o==="active")return o;return o},Zf=50,eh=28;function th({visibleSessions:e,shouldVirtualize:s,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:a,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:u}){const d=i.useRef(null),[f,p]=i.useState(null),[b,m]=i.useState(0),[,g]=i.useState(0);i.useEffect(()=>{if(!s)return;const x=d.current;if(!x||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>g(w=>w+1));return I.observe(x),()=>I.disconnect()},[s]),i.useLayoutEffect(()=>{if(!s){f!==null&&p(null),b!==0&&m(0);return}const x=d.current;if(!x)return;let I=f;const w=r?.current??null;if(w&&w.contains(x)){if(I=w,I!==f){p(I);return}}else if(!I||!I.contains(x)){let N=x.parentElement;for(;N;){const k=window.getComputedStyle(N);if(k.overflowY==="auto"||k.overflowY==="scroll"){I=N;break}N=N.parentElement}if(I!==f){p(I);return}}if(!I)return;const A=x.getBoundingClientRect().top-I.getBoundingClientRect().top+I.scrollTop;m(N=>Math.abs(N-A)<1?N:A)},[f,b,r,s]);const h=s&&f!==null,v=Hd({count:e.length,enabled:h,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>eh,overscan:n?20:8,scrollMargin:b,getItemKey:x=>e[x]?.session.id??x});return t.jsx("div",{ref:d,children:s?t.jsx("div",{style:{height:v.getTotalSize(),position:"relative"},children:v.getVirtualItems().map(x=>{const I=e[x.index];return I?t.jsx("div",{"data-index":x.index,ref:v.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",u(I))},I.session.id):null})}):e.map(x=>t.jsx(i.Fragment,{children:c(x,0,o,a,l,void 0,"project",u(x))},x.session.id))})}const Tn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),o=r.length;if(o===0)return e;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(e.slice(l,c));const u=e.slice(c,c+o);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:u},`${c}-${u}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e};function sh({group:e,groupKey:s,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:a,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:u,groupPrSummary:d,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:b,allGroupSessions:m,projectId:g,activeProjectId:h,setActiveProjectIdOnly:v,setActiveMainTab:x,mobileVariant:I,setSessionSwitcherOpen:w,openNewSessionDraft:A}){return t.jsxs("div",{className:U("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:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),r(s))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[t.jsx("div",{ref:c?.setActivatorNodeRef,className:U("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:U("size-4 shrink-0 text-muted-foreground",a?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:U("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:Tn(e.label,o)}),f]}):!e.isMain||e.worktree?t.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(R,{name:"git-branch",className:U("size-4 shrink-0",!u&&"text-muted-foreground",a?"hidden":"group-hover/gh:hidden"),style:u?{color:u}:void 0}),t.jsx("span",{className:U("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:Tn(e.label,o)}),f,d?t.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:u?{color:u}:void 0,children:["#",d.number]}):null]}):t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"min-w-0 truncate",children:Tn(e.label,o)}),f]})}),p&&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&&m.length>0?t.jsx("div",{className:U("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(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),xs.requestDelete({sessions:m,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(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?t.jsx("div",{className:U("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(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),g&&g!==h&&v(g),x("chat"),I&&w(!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(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]})}const Nn=(e,s)=>s?e.sessions.some(n=>ts(n,s)):!1,nh=(e,s,n)=>e.sessions.some(r=>ja(r,r,s,n,e.directory,e.directory)),rh=(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)},Xo=(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)},oh=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},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&&nh(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&ih(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&rh(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(Nn(e.group,e.editingId)||Nn(s.group,s.editingId))||e.editTitle!==s.editTitle&&(Nn(e.group,e.editingId)||Nn(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Gn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Gn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Xo(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Xo(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&oh(s.group,s.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===s.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===s.normalizedSessionSearchQuery&&e.hideDirectoryControls===s.hideDirectoryControls&&e.collapsedFolderIds===s.collapsedFolderIds&&e.toggleFolderCollapse===s.toggleFolderCollapse&&e.renameFolder===s.renameFolder&&e.deleteFolder===s.deleteFolder&&e.showDeletionDialog===s.showDeletionDialog&&e.setDeleteFolderConfirm===s.setDeleteFolderConfirm&&e.renderSessionNode===s.renderSessionNode&&e.showMoreGroupSessions===s.showMoreGroupSessions&&e.resetGroupSessionLimit===s.resetGroupSessionLimit&&e.mobileVariant===s.mobileVariant&&e.alwaysShowActions===s.alwaysShowActions&&e.activeProjectId===s.activeProjectId&&e.setActiveProjectIdOnly===s.setActiveProjectIdOnly&&e.setActiveMainTab===s.setActiveMainTab&&e.setSessionSwitcherOpen===s.setSessionSwitcherOpen&&e.openNewSessionDraft===s.openNewSessionDraft&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.renamingFolderId===s.renamingFolderId&&e.renameFolderDraft===s.renameFolderDraft&&e.setRenameFolderDraft===s.setRenameFolderDraft&&e.setRenamingFolderId===s.setRenamingFolderId&&e.onToggleCollapsedGroup===s.onToggleCollapsedGroup&&e.dragHandleProps===s.dragHandleProps&&e.scrollContainerRef===s.scrollContainerRef};function lh({group:e,sourceGroupNodes:s,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:a,unreadActivitySessionIds:l,notifyOnSubtasks:c,collectGroupSessions:u}){const d=ht(k=>k.foldersMap),f=e.folderScopeKey??Ne(e.directory??null),p=i.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),b=i.useMemo(()=>p.flatMap(({scopeKey:k,directory:j})=>(d[k]??[]).map(y=>({folder:y,scopeKey:k,scopeDirectory:j}))),[p,d]),m=i.useMemo(()=>{const k=new Map,j=y=>{y.forEach(C=>{k.set(C.session.id,C),C.children.length>0&&j(C.children)})};return j(s),k},[s]),g=i.useMemo(()=>b.map(({folder:k,scopeKey:j,scopeDirectory:y})=>{const C=Vf(k.sessionIds,m).sort(o);return{folder:k,scopeKey:j,scopeDirectory:y,nodes:C}}),[b,m,o]),h=i.useMemo(()=>{const k=new Map(g.map(E=>[E.folder.id,E])),j=new Map;for(const{folder:E}of g){if(!E.parentId)continue;const P=j.get(E.parentId);P?P.push(E.id):j.set(E.parentId,[E.id])}const y=new Map,C=E=>{const P=y.get(E);if(P!==void 0)return P;const B=k.get(E);if(!B)return y.set(E,!1),!1;const L=j.get(E)??[];if(e.isArchivedBucket&&B.nodes.length===0){const O=L.some(T=>C(T));return y.set(E,O),O}if(!n||B.folder.name.toLowerCase().includes(r)||B.nodes.length>0)return y.set(E,!0),!0;const Q=L.some(O=>C(O));return y.set(E,Q),Q};return g.filter(({folder:E})=>C(E.id))},[g,e.isArchivedBucket,n,r]),v=i.useMemo(()=>new Set(h.flatMap(k=>k.folder.sessionIds)),[h]),x=i.useMemo(()=>s.filter(k=>!v.has(k.session.id)),[s,v]),I=i.useMemo(()=>h.filter(({folder:k})=>!k.parentId),[h]),w=i.useMemo(()=>{const k=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const y=k.get(j.folder.parentId)??[];y.push(j),k.set(j.folder.parentId,y)}),k},[h]),A=i.useMemo(()=>{const k=new Map(h.map(C=>[C.folder.id,C])),j=new Map,y=(C,E)=>{const P=j.get(C);if(P!==void 0)return P;if(E.has(C))return null;E.add(C);const B=k.get(C);let L=B?Na(B.nodes,a,l,c):null;for(const z of w.get(C)??[])if(L=oo(L,y(z.folder.id,E)),L==="active")break;return j.set(C,L),L};return h.forEach(({folder:C})=>y(C.id,new Set)),j},[a,h,w,c,l]),N=i.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const k=new Map,j=new Map;for(const{folder:C}of h){if(!C.parentId)continue;const E=j.get(C.parentId)??[];E.push(C.id),j.set(C.parentId,E)}const y=(C,E)=>{if(E.has(C))return[];E.add(C);const P=h.find(({folder:z})=>z.id===C),B=P?u(P.nodes):[],L=j.get(C)??[];for(const z of L)B.push(...y(z,E));return B};for(const{folder:C}of h)k.set(C.id,y(C.id,new Set));return k},[h,u,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:p,allFoldersForGroup:h,rootFolders:I,ungroupedSessions:x,folderActivityStateById:A,folderSessionsForDeleteById:N}}function ch(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:u,collapsedGroups:d,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:b,renameFolder:m,deleteFolder:g,showDeletionDialog:h,setDeleteFolderConfirm:v,renderSessionNode:x,showMoreGroupSessions:I,resetGroupSessionLimit:w,mobileVariant:A,alwaysShowActions:N,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:y,setSessionSwitcherOpen:C,openNewSessionDraft:E,addSessionToFolder:P,createFolderAndStartRename:B,renamingFolderId:L,renameFolderDraft:z,setRenameFolderDraft:Q,setRenamingFolderId:O,pinnedSessionIds:T,expandedParents:M,sessionOrderIndex:_,editingId:se,openSidebarMenuKey:$,activeActivitySessionIds:G,unreadActivitySessionIds:Ae,notifyOnSubtasks:te,onToggleCollapsedGroup:Pe,dragHandleProps:Be,compactBodyPadding:Y=!1,scrollContainerRef:F}=e,K=i.useCallback((we,Oe)=>{const ke=_.get(we.session.id),Le=_.get(Oe.session.id);if(ke!==void 0||Le!==void 0){if(ke===void 0)return 1;if(Le===void 0)return-1;if(ke!==Le)return ke-Le}return Qr(we.session,Oe.session,T,Ni)},[T,_]),J=a?c.get(s):null,Z=a?!1:d.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const we=Ne(s.directory??null),Oe=s.branch?.trim();return we&&Oe?Ca():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const pe=ka(),Se=void 0,xe=f?10:5,ne=Math.max(xe,u??xe),ce=a?J?.groupMatches===!0:!1,q=a,fe=i.useMemo(()=>[...q?J?.filteredNodes??[]:s.sessions].sort(K),[K,s.sessions,J?.filteredNodes,q]),_e=i.useCallback(we=>{const Oe=[],ke=Le=>{Le.forEach(Ye=>{Oe.push(Ye.session),Ye.children.length>0&&ke(Ye.children)})};return ke(we),Oe},[]),{folderScopeKey:W,folderScopes:X,allFoldersForGroup:ie,rootFolders:ge,ungroupedSessions:be,folderActivityStateById:Te,folderSessionsForDeleteById:je}=lh({group:s,sourceGroupNodes:fe,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,compareSessionNodes:K,activeActivitySessionIds:G,unreadActivitySessionIds:Ae,notifyOnSubtasks:te,collectGroupSessions:_e}),ee="project",me=i.useMemo(()=>{const we=new Set;return Qo(fe,se,we),ie.forEach(({nodes:Oe})=>{Qo(Oe,se,we)}),we},[fe,ie,se]),de=i.useMemo(()=>{if(!$)return null;const we=Gn(fe,$,ee,!!s.isArchivedBucket);if(we)return we;for(const{nodes:Oe}of ie){const ke=Gn(Oe,$,ee,!!s.isArchivedBucket);if(ke)return ke}return null},[$,fe,ie,s.isArchivedBucket]),Ce=i.useCallback(we=>{const Oe=new WeakMap,ke=Le=>{Oe.set(Le,Gr(Le));for(const Ye of Le.children)ke(Ye)};return we.forEach(ke),Oe},[]),We=i.useMemo(()=>Ce(fe),[Ce,fe]),He=i.useMemo(()=>{const we=new WeakMap;return ie.forEach(({nodes:Oe})=>{Oe.forEach(ke=>we.set(ke,Gr(ke)))}),we},[ie]),ye=i.useCallback(we=>We.get(we)??He.get(we)??"",[We,He]),re=i.useCallback(we=>({subtreeContainsEditing:me,menuOpenSessionId:de,nodeStructureKey:ye(we)}),[me,de,ye]),Fe=be.length,De=s.isArchivedBucket||a?be:be.slice(0,ne),ot=Fe-De.length,it=!s.isArchivedBucket&&!a&&Fe>xe&&ot===0,Ve=s.isArchivedBucket===!0&&!a&&De.length>=Zf,Lt=s.isArchivedBucket?"archived":"active",Nt=Ve&&De.some(we=>{if(we.children.length===0)return!1;const Oe=`project:${Lt}:${we.session.id}`;return M.has(Oe)}),jt=i.useMemo(()=>_e(fe),[_e,fe]);if(a&&!ce&&ge.length===0&&be.length===0)return null;const Bt=!s.isMain&&!!s.branch,et=s.branch&&Nd(s.branch,s.label)?{label:s.branch,color:null}:null,mt=Z?Na(fe,G,Ae,te):null,tt=mt?t.jsx(Sa,{state:mt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,gt=(we,Oe)=>{const{folder:ke,scopeKey:Le,scopeDirectory:Ye,nodes:ut}=we,It=je.get(ke.id)??[],Rt=a?!1:p.has(ke.id);return t.jsx(qf,{folderId:ke.id,children:(_t,qe)=>t.jsx(Hf,{folder:ke,displayName:Oe,sessions:ut,isCollapsed:Rt,collapsedActivityState:Rt?Te.get(ke.id)??null:null,onToggle:()=>b(ke.id),onRename:st=>{m(Le,ke.id,st)},onDelete:()=>{if(s.isArchivedBucket){xs.requestDelete({sessions:It,mode:"session"});return}if(!h){g(Le,ke.id);return}const st=ie.filter(({folder:Ut})=>Ut.parentId===ke.id).length,wt=ut.length;v({scopeKey:Le,folderId:ke.id,folderName:ke.name,subFolderCount:st,sessionCount:wt})},renderSessionNode:x,getRenderExtras:ye?st=>({subtreeContainsEditing:me,menuOpenSessionId:de,nodeStructureKey:ye(st),childRenderExtrasFor:re}):void 0,groupDirectory:Ye??s.directory,projectId:r,mobileVariant:A,alwaysShowActions:N,isRenaming:L===ke.id,renameDraft:L===ke.id?z:void 0,onRenameDraftChange:st=>Q(st),onRenameSave:()=>{const st=z.trim();st&&m(Le,ke.id,st),O(null),Q("")},onRenameCancel:()=>{O(null),Q("")},droppableRef:_t,isDropTarget:qe,depth:0,onNewSession:()=>{r&&r!==k&&j(r),y("chat"),A&&C(!1),E({selectedProjectId:r,directoryOverride:Ye??s.directory,targetFolderId:ke.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},ke.id)},Ct=()=>{const we=new Map;for(const Le of ie){const Ye=Le.folder.parentId;if(!Ye)continue;const ut=we.get(Ye);ut?ut.push(Le):we.set(Ye,[Le])}const Oe=[],ke=(Le,Ye)=>{const ut=Ye?`${Ye} / ${Le.folder.name}`:Le.folder.name;Oe.push(gt(Le,ut)),!(!a&&p.has(Le.folder.id))&&(we.get(Le.folder.id)??[]).forEach(Rt=>ke(Rt,ut))};return ge.forEach(Le=>ke(Le,"")),Oe},qt=N?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",yt=t.jsxs(Qf,{scopeKey:X[0]?.scopeKey??W,hasFolders:ie.length>0,onSessionDroppedOnFolder:(we,Oe)=>{const ke=ie.find(({folder:Ye})=>Ye.id===Oe);if(!ke)return;const Le=ht.getState();for(const{scopeKey:Ye}of X)Ye!==ke.scopeKey&&Le.getSessionFolderId(Ye,we)&&Le.removeSessionFromFolder(Ye,we);P(ke.scopeKey,Oe,we)},children:[Ct(),s.isArchivedBucket?t.jsx(th,{visibleSessions:De,shouldVirtualize:Ve,hasExpandedParent:Nt,scrollContainerRef:F,groupDirectory:s.directory,projectId:r,isArchivedBucket:s.isArchivedBucket===!0,renderSessionNode:x,getRenderExtras:we=>({subtreeContainsEditing:me,menuOpenSessionId:de,nodeStructureKey:ye(we),childRenderExtrasFor:re})}):De.map(we=>t.jsx(i.Fragment,{children:x(we,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:me,menuOpenSessionId:de,nodeStructureKey:ye(we),childRenderExtrasFor:re})},we.session.id)),Fe===0&&ie.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(bs,{icon:"chat-new",onClick:()=>{E({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,ot>0?t.jsx(bs,{icon:"arrow-down-s",onClick:()=>I(n,De.length),children:ot===1?"Show 1 more session":`Show ${ot} more sessions`}):null,it?t.jsx(bs,{icon:"arrow-up-s",onClick:()=>w(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:yt})}):t.jsxs("div",{className:"oc-group",children:[t.jsx(sh,{group:s,groupKey:n,isCollapsed:Z,onToggleCollapsedGroup:Pe,normalizedSessionSearchQuery:l,alwaysShowActions:N,groupHeaderRightPadding:qt,dragHandleProps:Be,groupPrColor:Se,groupPrSummary:pe,groupActivityIndicator:tt,showBranchSubtitle:Bt,statusLine:et,allGroupSessions:jt,projectId:r,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:y,mobileVariant:A,setSessionSwitcherOpen:C,openNewSessionDraft:E}),Z?null:t.jsx("div",{className:"oc-group-body",children:yt})]})}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:u,headerActionButtonClass:d,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:b,sessionSearchQuery:m,setSessionSearchQuery:g,hasSessionSearchQuery:h,searchMatchCount:v,selectionModeEnabled:x,onToggleSelectionMode:I,mobileVariant:w=!1}=e;if(s)return null;const A=U(d,"text-muted-foreground hover:text-foreground",!w&&"hover:bg-transparent");return t.jsx("div",{className:U("select-none flex-shrink-0",w?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:U("flex flex-col",w?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:U("flex items-center justify-between",w?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:U("flex min-w-0 items-center",w?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":w?"true":void 0,children:[o?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:A,"aria-label":"Settings",children:t.jsx(R,{name:"settings-3",className:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!w&&a?t.jsxs(ze,{children:[t.jsx($e,{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:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:A,"aria-label":"Update",children:t.jsx(R,{name:"download",className:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,w?null:t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:A,"aria-label":"Add project",children:t.jsx(R,{name:"folder-add",className:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),w?null:t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:A,"aria-label":"Archive",children:t.jsx(R,{name:"archive",className:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:U("flex shrink-0 items-center",w?"gap-1":"gap-1.5"),children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>p(N=>!N),className:A,"aria-label":"Search sessions","aria-expanded":f,children:t.jsx(R,{name:"search",className:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:I,className:U(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:u})})}),t.jsx(Ge,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:x?"Exit selection":"Select sessions"})})]})]})]}),f?t.jsxs("div",{className:U(w?"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:h?t.jsx("span",{children:v===1?`${v} match`:`${v} 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:m,onChange:N=>g(N.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:N=>{N.key==="Escape"&&(N.stopPropagation(),h?g(""):p(!1))}}),m.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=le(o=>o.toggleSidebar),n=le(o=>o.shortcutOverrides),r=Xr(Ln("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, ${Oo})`}}),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, ${Oo})))`}}),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:U("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:U(Mn,"text-current")}),t.jsx("span",{className:zi,children:"New session"})]}),e.showSidebarToggle?t.jsxs(ze,{children:[t.jsx($e,{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(Ge,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Ia=500,hh=({projectId:e,worktree:s,isSelected:n,hasActive:r,onSelect:o,onClose:a,mobileVariant:l=!1})=>{const[c,u]=i.useState(!1),d=i.useRef(null),f=s.branch||(s.detached?"Detached HEAD":s.name),p=i.useCallback(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]);i.useEffect(()=>()=>p(),[p]);const b=i.useCallback(()=>{p(),d.current=window.setTimeout(()=>{d.current=null,u(!0)},Ia)},[p]);return t.jsxs(so,{open:c,onOpenChange:u,children:[t.jsxs(no,{render:t.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:U(Kn(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:U(un(l),"text-muted-foreground")}),t.jsx("span",{className:fn(l),children:f})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(js,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsx(ro,{className:"min-w-[160px]",children:t.jsxs(Fs,{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"})]})})]})},Kn=(e,s)=>U("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:u,onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:b,setNodeRef:m,transform:g,transition:h,isDragging:v}=Qd({id:e.id,disabled:!c}),[x,I]=i.useState(!1),w=i.useRef(null),A=i.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]);i.useEffect(()=>()=>A(),[A]);const N=i.useCallback(()=>{A(),w.current=window.setTimeout(()=>{w.current=null,I(!0)},Ia)},[A]);return t.jsx("div",{ref:m,style:{transform:Vd.Translate.toString(g),transition:h},className:U(v&&"opacity-60"),children:t.jsxs(so,{open:x,onOpenChange:I,children:[t.jsxs(no,{render:t.jsx("button",{type:"button",onClick:()=>{x||u()},onTouchStart:N,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Kn(p,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:U("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:U(un(p),"text-muted-foreground")})}),t.jsx("span",{className:fn(p),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(js,{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(ro,{className:"min-w-[160px]",children:[t.jsxs(Fs,{onClick:()=>d(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(ga,{}),t.jsxs(Fs,{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:u,onOpenProjectEditDialog:d,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:b,homeDirectory:m,className:g,mobileVariant:h=!1})=>{const v=s===null,x=pt(N=>N.reorderProjects),I=e.length>1,w=Qi(Fr(Wd,{activationConstraint:{distance:8}}),Fr(Kd,{activationConstraint:{delay:200,tolerance:6}})),A=i.useCallback(N=>{const{active:k,over:j}=N;if(!j||k.id===j.id)return;const y=pt.getState().projects,C=y.findIndex(P=>P.id===k.id),E=y.findIndex(P=>P.id===j.id);C<0||E<0||x(C,E)},[x]);return t.jsxs("div",{className:U("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:Kn(h,v),"aria-pressed":v,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(R,{name:"chat-history",className:un(h)}),t.jsx("span",{className:fn(h),children:"All sessions"})]})}),t.jsx(Vi,{sensors:w,collisionDetection:Ji,onDragEnd:A,children:t.jsx(Yd,{items:e.map(N=>N.id),strategy:qd,children:e.map(N=>{const k=s===N.id,j=k&&!n,y=r.get(N.normalizedPath)??[],C=qn(N.label?.trim()||Bs(N.normalizedPath,m)||N.normalizedPath),E=b?.get(N.id),P=Ne(N.normalizedPath)?.toLowerCase()??"",B=P?E?.has(P)??!1:!1,L=(E?.size??0)>0,z=p?.(N.id)??!1,Q=b?k?B:L:z;return t.jsxs(i.Fragment,{children:[t.jsx(ph,{project:N,label:C,isSelected:j,hasActive:Q,hasWorktrees:y.length>0,worktreeError:o.get(N.normalizedPath),isExpanded:k,canDrag:I,onSelect:()=>a(N.id),onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:h}),k?y.map(O=>{const T=n===O.path,M=Ne(O.path)?.toLowerCase()??"",_=M?E?.has(M)??!1:!1,se=b?_:!1;return t.jsx(hh,{projectId:N.id,worktree:O,isSelected:T,hasActive:se,onSelect:()=>l?.(N.id,O.path),onClose:c,mobileVariant:h},O.path)}):null]},N.id)})})}),t.jsxs("button",{type:"button",onClick:u,className:Kn(h,!1),children:[t.jsx(R,{name:"add",className:un(h)}),t.jsx("span",{className:fn(h),children:"Add folder"})]})]})},cr="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function 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(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:cr,"aria-label":"Settings",children:t.jsx(R,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:cr,"aria-label":"Shortcuts",children:t.jsx(R,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:cr,"aria-label":"About PiChamber",children:t.jsx(R,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Me,{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)=>qn(e.label?.trim()||Bs(e.normalizedPath,s)||e.normalizedPath);function xh(e){Mt("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=(p,b)=>{const m=s.current,g=m.get(p);if(g&&g.groups===b)return g.ordered;const h=e.getOrderedGroups(p,b);if(m.set(p,{groups:b,ordered:h}),m.size>256){const v=m.keys().next().value;v!==void 0&&m.delete(v)}return h},o=i.useRef(null),a=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const p=[],b=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const m of b){const g=bh(m.project,e.homeDirectory);for(const h of m.groups)if(!h.isArchivedBucket)for(const v of h.sessions){const x=!!e.pinnedSessionIds?.has(v.session.id),I=v.session.time?.updated||v.session.time?.created||0;p.push({node:v,project:m.project,projectLabel:g,isPinned:x,timestamp:I,globalSession:m===e.allFoldersOnlySection})}}return p.sort((m,g)=>m.isPinned!==g.isPinned?m.isPinned?-1:1:g.timestamp-m.timestamp),p},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=i.useState(30);i.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const u=a.slice(0,l),d=a.length-u.length;if(e.sharedSessionsOnly)return t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:U("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(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:U("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(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:U("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(ps,{ref:o,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:U("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 p=e.sectionsForRender.find(h=>h.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!p)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=p.groups.find(h=>h.isMain&&h.sessions.length>0)??p.groups.find(h=>h.sessions.length>0)??p.groups.find(h=>h.isMain)??p.groups[0];if(!b)return t.jsx(bs,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath}),children:"New session"});const m=p.groups.find(h=>h.isArchivedBucket);return[b,...m&&m.id!==b.id?[m]:[]].map(h=>{const v=`${p.project.id}:${h.id}`,x=h.id===b.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(h,v,p.project.id,x,null,!0,o)},v)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[u.map(({node:p,project:b,projectLabel:m,globalSession:g})=>{const h=p.session.directory??b.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(p,0,h,b.id,!1,{projectLabel:m,showFolderLabel:!0,globalSession:g},"project")},p.session.id)}),d>0?t.jsx(bs,{icon:"arrow-down-s",onClick:()=>c(p=>p+30),children:d===1?"Show 1 more session":`Show ${d} more sessions`}):null,l>30&&a.length>30?t.jsx(bs,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(p=>{const b=p.project.id,m=r(b,p.groups),g=m.find(v=>v.isMain)??null,h=g?m.filter(v=>v.id!==g.id):m;return t.jsxs("div",{children:[g?e.renderGroupSessions(g,`${b}:${g.id}`,b,!0,null,void 0,o):null,h.map(v=>{const x=`${b}:${v.id}`,I=m.length===1;return t.jsx(i.Fragment,{children:e.renderGroupSessions(v,x,b,I,null,void 0,o)},v.id)})]},b)})})]})})})}const yh=i.memo(xh);let Kr=!1;const Wr=new Set;let Zo=!1;function wh(){for(const e of Wr)e()}function io(e){Kr!==e&&(Kr=e,wh())}function vh(e){e.key==="Shift"&&io(!0)}function Sh(e){e.key==="Shift"&&io(!1)}function jh(){io(!1)}function Ch(){Zo||typeof window>"u"||(Zo=!0,window.addEventListener("keydown",vh),window.addEventListener("keyup",Sh),window.addEventListener("blur",jh))}function kh(e){return Ch(),Wr.add(e),()=>{Wr.delete(e)}}function Ah(){return Kr}function Nh(){return!1}function Ih(){return Ie.useSyncExternalStore(kh,Ah,Nh)}const Rh=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:u}){const d=Ih(),f=d?n:s,p=b=>{if(d||b.shiftKey){u(b);return}c(b)};return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",className:U("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:a,onMouseDown:l,onClick:p,onKeyDown:b=>b.stopPropagation(),children:t.jsx(R,{name:d?"delete-bin":"archive",className:o})})}),t.jsx(Ge,{side:"left",sideOffset:8,children:f})]})}),Eh=i.memo(function({open:s,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,onExport:l}){return t.jsx(Ht,{open:s,onOpenChange:n,children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:"Export Markdown"}),t.jsx(us,{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(Ss,{children:[t.jsx(Me,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Me,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function Dh(e,s){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:a,archivedBucket:l,isElectron:c,pendingRenameRef:u,handleCopySessionId:d,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:b,handleDeleteSession:m,handleRestoreSession:g}=e,{Item:h,Separator:v}=s;return t.jsxs(t.Fragment,{children:[t.jsxs(h,{onClick:()=>{u.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(h,{onClick:()=>d(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(h,{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(h,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[t.jsx(R,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?t.jsxs(h,{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(v,{}),l?null:t.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>m(n,{archivedBucket:l}),children:[t.jsx(R,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?t.jsxs(h,{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(h,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>m(n,{archivedBucket:l,hardDelete:!0}),children:[t.jsx(R,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Mh(e){const{renamingFolderId:s,editingIdRef:n}=e;return t.jsx(Ki,{children:t.jsx(Wi,{className:"app-region-no-drag z-50",children:t.jsx(Hi,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(s||n.current),style:{color:"var(--surface-elevated-foreground)"},className:U(Si,"min-w-[180px]"),children:Dh(e,{Item:({className:r,...o})=>t.jsx(Yi,{className:U(ji,r),...o}),Separator:({className:r,...o})=>t.jsx(qi,{className:U(Ci,r),...o})})})})})}const dr=new WeakMap,Ph=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;dr.get(n)?.();const r=s.getBoundingClientRect().top;let o=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,dr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},u=()=>{if(a||!s.isConnected||!n.isConnected){c();return}const d=s.getBoundingClientRect().top-r;if(Math.abs(d)>.5&&(n.scrollTop+=d,Mt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(u)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),dr.set(n,c),l=window.requestAnimationFrame(u)};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 Ra(e){const s=Oh(e),n=Lh(e.parts).trim();return n?`${s}
|
|
14
|
-
|
|
15
|
-
${n}`:""}function Ea(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(Ra).filter(Boolean).join(`
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
`),l=[o+a];for(const c of e.children)l.push(Ea(c,s+1));return l.join(`
|
|
24
|
-
|
|
25
|
-
---
|
|
26
|
-
|
|
27
|
-
`)}function Da(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(Ra).filter(Boolean).join(`
|
|
34
|
-
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
`);let c=a+l;if(n&&n.length>0){const u=n.map(d=>Ea(d,1)).join(`
|
|
38
|
-
|
|
39
|
-
---
|
|
40
|
-
|
|
41
|
-
`);c+=`
|
|
42
|
-
|
|
43
|
-
---
|
|
44
|
-
|
|
45
|
-
`+u}return c}function Ma(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 Pa(e,s){const n=await od(s,e);return n||null}async function Bh(e){const s=Zt()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await id(e)?!0:Ti(e)}function _h(){return ad()}function Ta(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 Wn=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(()=>Wn(e).length,[e]),u=i.useCallback(async b=>{const m=[];let g=0;for(const h of b)try{if(!s)throw new Error("Session directory is required for export");const v=[],x=h.session.title||"Untitled Sub-agent",I=typeof h.session.agent=="string"?h.session.agent:void 0,w=await u(h.children);g+=w.skipped,m.push({title:x,agent:I,records:v,children:w.children})}catch{g+=Wn(h).length+1}return{children:m,skipped:g}},[s]),d=i.useCallback(b=>{b<=0||ae.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){ae.error("Nothing to export");return}const m=[];if(m.length===0){ae.error("Nothing to export");return}let g,h=0;if(b&&e.children.length>0){const w=await u(e.children);g=w.children,h=w.skipped}const v=Da(m,l.title??null,g),x=Ta(l.title??null),I=await Pa(v,x);if(I){ae.success("Session exported",{action:{label:_h(),onClick:()=>{Bh(I).then(w=>{w||ae.error("Failed to reveal path")})}}}),d(h);return}Ma(v,x),ae.success("Session exported"),d(h)},[u,e.children,l.title,s,d]),p=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:p,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},dt=Gs()((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,u=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(l.clear(),c=r,u=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);u===n&&(u=null)}else{for(const b of f)l.add(b);u=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:u})},setRange:(n,r,o,a,l)=>{const c=s();if(o.length===0)return;const u=n&&o.includes(n)?n:o[0],d=o.indexOf(u),f=o.indexOf(r);if(d<0||f<0)return;const[p,b]=d<=f?[d,f]:[f,d],m=o.slice(p,b+1),g=zh(m,l),v=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of g)v.add(x);e({selectedIds:v,scopeKey:a??c.scopeKey,anchorId:u})},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}))}})),ei=e=>Ne(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},In=e=>e.menuOpenSessionId??Gh(e),Rn=(e,s,n)=>s?n.has(e.node.session.id)?!0:ts(e.node,s):!1,Hr=(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(Hr(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 Hr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Hr(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.notifyOnSubtasks!==s.notifyOnSubtasks||e.nodeStructureKey!==s.nodeStructureKey||ei(e.node)!==ei(s.node)||!$h(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&ja(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&Kh(e,s)||e.editingId!==s.editingId&&(Rn(e,e.editingId,e.subtreeContainsEditing)||Rn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(Rn(e,e.editingId,e.subtreeContainsEditing)||Rn(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(ts(e.node,e.copiedSessionId)||ts(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=In(e),r=In(s);if(ts(e.node,n)||ts(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=In(e),r=In(s);if(ts(e.node,n)||ts(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,notifyOnSubtasks:u}){const d=e.session,f=Ne(d.directory??null)??Ne(s??null),p=Ee(Z=>Z.currentSessionId===d.id),b=Ii(f),m=pc(f),g=pt(i.useCallback(Z=>{if(r?.projectLabel||!n)return null;const pe=Z.projects.find(Se=>Se.id===n);return pe?pe.label?.trim()||Bs(Ne(pe.path)??pe.path,null)||pe.path:null},[n,r?.projectLabel])),h=r?.projectLabel??(g?qn(g):null),v=e.worktree,x=r?.branchLabel??v?.branch??(b&&b!=="HEAD"?b:null),I=x,w=m===!0||!!(x||v),A=e.children.length,N=d.agent;i.useMemo(()=>{const Z=v?.branch?.trim()||x?.trim(),pe=Ne(v?.path??f);return Z&&pe?Ca():null},[x,f,v]);const k=ka(),j=void 0,y=i.useMemo(()=>null,[k]),C=n??f??null,E=dt(Z=>Z.enabled),P=dt(i.useCallback(Z=>Z.selectedIds.has(d.id),[d.id])),B=dt(Z=>Z.toggleSelected),L=dt(Z=>Z.setRange),Q=Ri(d.id)?.type??"idle",O=Q==="busy"||Q==="retry",T=mc(d.id,O),M=cs(d),_=e.children.length>0,se=gc(o,f,d.id),$=c?!0:a.has(l),G=!!d.parentID,te=bc(d.id)>0&&(!G||u),Pe=d.time?.updated||d.time?.created||Date.now(),Be=Id(Pe),Y=i.useMemo(()=>ya(e.forkColorId),[e.forkColorId]),F=i.useMemo(()=>kf(e.forkColorId,{active:p||P}),[e.forkColorId,p,P]),K=r?.globalSession&&!p&&!P?"var(--surface-elevated)":null;return{session:d,sessionDirectory:f,isActive:p,tooltipProjectLabel:h,tooltipBranchLabel:I,isGitRepo:w,subtaskCount:A,agentName:N,prSummary:k,prIconColor:j,prStatusLabel:y,selectionScopeKey:C,selectionModeEnabled:E,isRowSelected:P,toggleRowSelected:B,setRowRange:L,isStreaming:O,hasActivityDuration:T,sessionTitle:M,hasChildren:_,isPinnedSession:se,isExpanded:$,needsAttention:te,sessionCompactUpdatedLabel:Be,forkSolid:Y,rowBackground:F??K}}function Yh(e){Mt("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:u,normalizedSessionSearchQuery:d,notifyOnSubtasks:f,editingId:p,setEditingId:b,editTitle:m,setEditTitle:g,handleSaveEdit:h,handleCancelEdit:v,toggleParent:x,handleSessionSelect:I,handleSessionDoubleClick:w,togglePinnedSession:A,handleShareSession:N,copiedSessionId:k,handleCopyShareUrl:j,handleCopySessionId:y,handleUnshareSession:C,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,renamingFolderId:B,getFoldersForScope:L,getSessionFolderId:z,removeSessionFromFolder:Q,addSessionToFolder:O,createFolderAndStartRename:T,handleDeleteSession:M,handleRestoreSession:_,alwaysShowActions:se,allowQuickArchiveAction:$,renderSessionNode:G,secondaryMeta:Ae,renderContext:te="project",subtreeContainsEditing:Pe,menuOpenSessionId:Be,childRenderExtrasFor:Y}=e,F=i.useMemo(()=>Fi(),[]),K=!a&&$,J=i.useRef(!1),Z=i.useRef(p);Z.current=p;const pe=i.useRef(null),Se=i.useRef(h);Se.current=h;const[xe,ne]=i.useState(m),ce=i.useRef(xe);ce.current=xe;const q=i.useRef(null),fe=i.useRef(null),W=`${te}:${a?"archived":"active"}:${s.session.id}`,{session:X,sessionDirectory:ie,isActive:ge,tooltipProjectLabel:be,tooltipBranchLabel:Te,isGitRepo:je,subtaskCount:ee,agentName:me,prSummary:de,selectionScopeKey:Ce,selectionModeEnabled:We,isRowSelected:He,toggleRowSelected:ye,setRowRange:re,isStreaming:Fe,hasActivityDuration:De,sessionTitle:ot,hasChildren:it,isPinnedSession:Ve,isExpanded:Lt,needsAttention:Nt,sessionCompactUpdatedLabel:jt,forkSolid:Bt,rowBackground:et}=Hh({node:s,groupDirectory:r,projectId:o,secondaryMeta:Ae,pinnedSessionIds:l,expandedParents:c,expansionKey:W,hasSessionSearchQuery:u,notifyOnSubtasks:f}),{exportDialogOpen:mt,setExportDialogOpen:tt,exportIncludeSubtasks:gt,setExportIncludeSubtasks:Ct,descendantCount:qt,handleExportSession:yt,doExportSession:we}=Uh(s,ie),[Oe,ke]=i.useState(!1),Le=i.useCallback(()=>{ie&&on("desktop_open_session_mini_chat_window",{sessionId:X.id,directory:ie,apiBaseUrl:Er(),clientToken:Rr()}).catch(ue=>{console.warn("[session-sidebar] failed to open mini chat window",ue)})},[X.id,ie]);i.useEffect(()=>{if(p!==X.id)return;const ue=Ze=>{const vt=Ze.target?.closest?.(`[data-session-rename-form="${CSS.escape(X.id)}"]`);fe.current&&!vt&&Se.current(ce.current)};return document.addEventListener("mousedown",ue),()=>document.removeEventListener("mousedown",ue)},[p,X.id]),i.useLayoutEffect(()=>{if(p!==X.id){q.current===X.id&&(q.current=null);return}q.current!==X.id&&(q.current=X.id,ne(m))},[p,m,X.id]);const Ye=!Fe&&Nt&&!ge,ut=Fe&&De,It=Ve,Rt=t.jsx(R,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),_t=It?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:Rt}):null,qe=it?t.jsx("button",{type:"button",onClick:ue=>{ue.stopPropagation(),x(W)},onKeyDown:ue=>{(ue.key==="Enter"||ue.key===" ")&&(ue.preventDefault(),ue.stopPropagation(),x(W))},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":Lt?"Collapse subsessions":"Expand subsessions",children:Lt?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,st=ue=>{if(!ue&&pe.current){const{id:Ze,title:ft}=pe.current;pe.current=null,b(Ze),g(ft)}},wt=ue=>{ke(ue)},Ut=ue=>{ue.preventDefault(),ue.stopPropagation()},bt=ue=>{ue.preventDefault(),ue.stopPropagation()},Ks=ue=>{ue.preventDefault(),ue.stopPropagation(),P(null),M(X,{archivedBucket:a})},zt=ue=>{ue.preventDefault(),ue.stopPropagation(),P(null),M(X,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Cs=ue=>{if(J.current){J.current=!1;return}if(We){if(ue?.preventDefault(),ue?.stopPropagation(),ue?.shiftKey){const ft=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(lt=>lt.getAttribute("data-session-row")).filter(lt=>typeof lt=="string"&<.length>0),vt=dt.getState().anchorId,ns=new Map;ns.set(X.id,Wn(s)),re(vt,X.id,ft,Ce,ns);return}ye(X.id,Ce,Wn(s));return}ue?.currentTarget&&Ph(ue.currentTarget),I(X.id,ie)},ks=ue=>{ue.defaultPrevented||ue.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Cs(ue)},$t=ue=>{(ue.button===2||ue.button===0&&ue.ctrlKey&&!We)&&(J.current=!0)},Qt={session:X,sessionTitle:ot,sessionDirectory:ie,isPinnedSession:Ve,archivedBucket:a,isElectron:F,renamingFolderId:B,editingIdRef:Z,pendingRenameRef:pe,handleCopySessionId:y,togglePinnedSession:A,handleExportSession:yt,handleOpenMiniChatWindow:Le,handleDeleteSession:M,handleRestoreSession:_},at=t.jsx(Mh,{...Qt});return t.jsxs(i.Fragment,{children:[t.jsx(Yf,{sessionId:X.id,sessionDirectory:ie??null,sessionTitle:ot,children:t.jsxs($i,{open:Oe,onOpenChange:wt,onOpenChangeComplete:st,children:[t.jsxs(Gi,{render:t.jsx("div",{"data-session-row":X.id,"data-session-scope":Ce??"","data-session-archived":a?"1":"0","data-fork-color":Bt?s.forkColorId:void 0,"data-global-session":Ae?.globalSession?"1":void 0,onClick:ks,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...et?{backgroundColor:et}:void 0},className:U("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!et&&n>0?"bg-secondary/30 hover:bg-interactive-hover":et?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!et&&ge&&!He&&"bg-interactive-selection",!et&&He&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[qe,_t,p===X.id?t.jsxs("form",{ref:fe,"data-session-rename-form":X.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:ue=>ue.stopPropagation(),onMouseDown:ue=>ue.stopPropagation(),onSubmit:ue=>{ue.preventDefault(),h(xe)},children:[t.jsx("input",{value:xe,onChange:ue=>ne(ue.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:ue=>{ue.stopPropagation(),ue.key==="Escape"&&v()}}),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:v,"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:$t,onClick:ue=>Cs(ue),onDoubleClick:ue=>{ue.stopPropagation(),w(X.id,ot)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:U("block min-w-0 flex-1 truncate font-normal typography-ui-label",Nt?"text-foreground":"text-foreground/90"),children:Tn(ot,d)})}),Ae?.showFolderLabel&&be||Te||je||de||ee>0||me&&me!=="default"||ut?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:[Ae?.showFolderLabel&&be?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:be}):null,Te?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:U("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Te})]}):je?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,ee>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:ee})]}):null,me&&me!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:me}):null,ut?t.jsx(Rd,{sessionId:X.id,running:Fe,className:"text-muted-foreground/70"}):null]}):null]})]}),Ve?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:U("flex items-center justify-end",K&&(se||Oe)?"opacity-0":K?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Fe?t.jsx(js,{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:jt})}),K?t.jsx("div",{className:U("absolute inset-0 flex items-center justify-end",se||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:Ut,onMouseDown:bt,onArchive:Ks,onDelete:zt})}):null]})]}),at]})}),it&&Lt?s.children.map(ue=>{const Ze=Y?Y(ue):{subtreeContainsEditing:Pe,menuOpenSessionId:Be,nodeStructureKey:""};return t.jsx(i.Fragment,{children:G(ue,n+1,ie??r,o,a,Ae?.globalSession?{globalSession:!0}:void 0,te,Ze)},ue.session.id)}):null,t.jsx(Eh,{open:mt,onOpenChange:tt,descendantCount:qt,exportIncludeSubtasks:gt,setExportIncludeSubtasks:Ct,onExport:we})]},X.id)}const qh=i.memo(Yh,Wh),Qh=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(Ht,{open:e,onOpenChange:s,children:t.jsx(Yt,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(ps,{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(af,{project:n,onIdentitySave:r}):null})})})});function Fa(e){const{showDeletionDialog:s,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:a}=e;return t.jsxs(Ss,{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=>cs(c);return t.jsx(Ht,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(us,{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(Fa,{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,u=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",d=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(Ht,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:u}),t.jsx(us,{children:d})]}),t.jsx(Fa,{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}=$s(),[a,l]=i.useState(null),[c,u]=i.useState(!1),[d,f]=i.useState(!1),[p,b]=i.useState(!1),m=s?.worktree.path??null;i.useEffect(()=>{let N=!1;return l(null),u(!1),f(!1),b(!1),!s||!m?()=>{N=!0}:(o.getGitStatus(m).then(k=>{if(!N){if(typeof k?.isClean!="boolean"){u(!0);return}l(k)}}).catch(()=>{N||u(!0)}),()=>{N=!0})},[o,s,m]);const g=a?.isClean===!1,h=(a?.ahead??0)>0,v=h&&!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&&!v||d)&&!p),w=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(Ht,{open:!!s,onOpenChange:N=>{!N&&!p&&n(null)},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-md gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:"Close worktree?"}),t.jsx(us,{children:`Closing "${w}" 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(Cr,{checked:d,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,h?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}`}),v?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(Cr,{checked:d,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(Ss,{className:"sm:justify-end",children:[t.jsx(Me,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:p,children:"Cancel"}),t.jsx(Me,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!I,children:p?"Closing…":"Close worktree"})]})]})})}function Zh(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(Ht,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:"Delete folder?"}),t.jsx(us,{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(Ss,{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:u,setShowDeletionDialog:d,confirmDeleteSession:f,deleteFolderConfirm:p,setDeleteFolderConfirm:b,confirmDeleteFolder:m,closeWorktreeConfirm:g,setCloseWorktreeConfirm:h,confirmCloseWorktree:v,bulkDeleteConfirm:x,setBulkDeleteConfirm:I,confirmBulkDelete:w})=>t.jsxs(t.Fragment,{children:[t.jsx(ca,{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:u,setShowDeletionDialog:d,onConfirm:f}),t.jsx(Zh,{value:p,setValue:b,onConfirm:m}),t.jsx(Xh,{value:g,setValue:h,onConfirm:v}),t.jsx(Jh,{value:x,setValue:I,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:w})]}),tp=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=Ne(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return nn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=Ne(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(js,{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=Ne(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=Ne(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&Ne(c.directory)===a);return l?[{...o,groups:[l]}]:[]},cp=(e,s)=>{const n=new Map,r=new Map;return e.forEach(o=>{const a=qn(o.project.label?.trim()||Bs(o.project.normalizedPath,s)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==a?l.branch:null,u={projectLabel:a,branchLabel:c},d=f=>{f.forEach(p=>{const b=o.project.normalizedPath.length,m=r.get(p.session.id)??-1;b<m||(n.set(p.session.id,{node:p,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:u}),r.set(p.session.id,b),p.children.length>0&&d(p.children))})};d(l.sessions)})}),n};function dp({projectSections:e,flatSectionsForRender:s,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:a,activeSessionIdSet:l,unreadSessionIdSet:c}){const u=i.useMemo(()=>cp(e,a),[e,a]),d=i.useMemo(()=>ap(s),[s]),f=i.useMemo(()=>lp(n,d,r,o),[n,d,r,o]),p=i.useMemo(()=>sp(e),[e]),b=i.useMemo(()=>np(e),[e]),m=i.useCallback(v=>{const x=e.find(I=>I.project.id===v);return x?rp(x,l):!1},[l,e]),g=i.useMemo(()=>ip(e,l),[l,e]),h=i.useCallback(v=>{const x=e.find(I=>I.project.id===v);return x?op(x,c):!1},[e,c]);return{sessionSidebarMetaById:u,sectionsForSidebarRender:d,filteredSectionsForSidebarRender:f,totalSessionCount:p,sessionCountByProject:b,hasActiveSessionByProject:m,activeDirectoriesByProject:g,hasUnseenByProject:h}}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(ze,{children:[t.jsx($e,{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(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:U("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(Ge,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(ze,{children:[t.jsx($e,{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(Ge,{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:u,unarchiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:p}=e,b=dt(T=>T.enabled),m=dt(T=>T.selectedIds.size),g=m>0,h=dt(T=>T.selectedIds),v=dt(T=>T.scopeKey),x=i.useCallback(()=>{dt.getState().toggleMode()},[]),I=i.useCallback(()=>{dt.getState().disable()},[]),w=i.useMemo(()=>{if(!g||typeof document>"u")return!1;let T=!1,M=!1;for(const _ of h){const se=document.querySelectorAll(`[data-session-row="${CSS.escape(_)}"]`);for(const $ of se)$.getAttribute("data-session-archived")==="1"?M=!0:T=!0}return M&&!T},[g,h]),A=i.useMemo(()=>{if(v)return v;if(!g||typeof document>"u")return null;for(const T of h){const _=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(_&&_.length>0)return _}return null},[g,h,v]),N=i.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(M=>M.scopeKey):[A]},[A,o]),k=i.useMemo(()=>N.flatMap(T=>r[T]??[]),[r,N]),j=i.useCallback(T=>{for(const M of N)if((r[M]??[]).some(_=>_.id===T))return M;return null},[r,N]),y=i.useMemo(()=>{if(!g)return!1;for(const T of N)for(const M of r[T]??[])for(const _ of M.sessionIds)if(h.has(_))return!0;return!1},[r,N,g,h]),C=i.useCallback((T,M)=>{const _=Array.from(h);for(const se of N)se!==T&&l(se,_);a(T,M,_)},[a,l,h,N]),E=i.useCallback(T=>{if(!g)return;const M=j(T);M&&C(M,T)},[g,C,j]),P=i.useCallback(()=>{const T=N[0];if(!T||!g)return;const M=c(T);M&&C(T,M.id)},[c,g,C,N]),B=i.useCallback(()=>{if(!g)return;const T=Array.from(h);for(const M of N)l(M,T)},[l,h,N,g]),L=i.useCallback(async()=>{const T=Array.from(h);if(T.length!==0){if(w){const{deletedIds:M,failedIds:_}=await f(T);M.length>0&&ae.success(M.length===1?`Deleted ${M.length} session`:`Deleted ${M.length} sessions`),_.length>0&&ae.error(_.length===1?`Failed to delete ${_.length} session`:`Failed to delete ${_.length} sessions`)}else{const{archivedIds:M,failedIds:_}=await u(T);M.length>0&&ae.success(M.length===1?`Archived ${M.length} session`:`Archived ${M.length} sessions`),_.length>0&&ae.error(_.length===1?`Failed to archive ${_.length} session`:`Failed to archive ${_.length} sessions`)}dt.getState().clear()}},[u,w,f,h]),z=i.useCallback(()=>{if(!g)return;const T=h.size;if(!n){L();return}p({sessionCount:T,archivedBucket:w})},[w,L,h,n,p,g]),Q=i.useCallback(async()=>{if(!g||!w)return;const T=Array.from(h),{restoredIds:M,failedIds:_}=await d(T);M.length>0&&ae.success(M.length===1?`Restored ${M.length} session`:`Restored ${M.length} sessions`),_.length>0&&ae.error(_.length===1?`Failed to restore ${_.length} session`:`Failed to restore ${_.length} sessions`),dt.getState().clear()},[w,g,h,d]),O=i.useCallback(async()=>{p(null),await L()},[L]);return i.useEffect(()=>{if(!b)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),M=_=>{if(s)return;const se=_.target;if(se&&(se.tagName==="INPUT"||se.tagName==="TEXTAREA"||se.isContentEditable))return;const $=T?_.metaKey:_.ctrlKey;if(_.key==="Escape"){_.preventDefault(),dt.getState().disable();return}if($&&_.key==="Backspace"){_.preventDefault(),z();return}if($&&(_.key==="a"||_.key==="A")){const G=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(G.length===0)return;_.preventDefault();const te=dt.getState().scopeKey??G[0]?.getAttribute("data-session-scope")??null,Pe=Y=>te?Y.getAttribute("data-session-scope")===te:!0,Be=G.filter(Pe).map(Y=>Y.getAttribute("data-session-row")).filter(Y=>typeof Y=="string"&&Y.length>0);if(Be.length===0)return;dt.getState().replaceAll(Be,te||null)}};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[z,s,b]),{selectionModeEnabled:b,hasSelection:g,selectedIdsSize:m,bulkScopeIsArchived:w,derivedSelectionScope:A,bulkScopeFolders:k,bulkCanRemoveFromFolder:y,handleToggleSelectionMode:x,handleExitSelectionMode:I,handleBulkMoveToFolder:E,handleBulkCreateFolderAndMove:P,handleBulkRemoveFromFolder:B,handleBulkDelete:z,handleBulkRestore:Q,confirmBulkDelete:O}},hp=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},pp=Gs()(Zr(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})),ti="oc.sessions.projectCollapse",si="oc.sessions.groupOrder",ni="oc.sessions.groupCollapse",ri="oc.sessions.activeSessionByProject",oi="oc.sessions.expandedParents.v3",mp=new Set,ur=[],kt=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})=>{Ir("react.session_sidebar_render"),Mt("ui.session_sidebar.render"),Mt(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Mt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,u]=i.useState(!1),[d,f]=i.useState(""),p=i.useRef(null),b=i.useRef(null),[m,g]=i.useState(null),[h,v]=i.useState(""),[x,I]=i.useState(null),[w,A]=i.useState(new Set),N=i.useMemo(()=>jn(),[]),[k,j]=i.useState(new Set),y=Rs(S=>S.selectedSpaceId),C=Rs(S=>S.selectedWorktreePath),[E,P]=i.useState(new Map),[B,L]=i.useState(new Map),[z,Q]=i.useState(!1),[O,T]=i.useState(null),[M,_]=i.useState(null),[se,$]=i.useState(""),[G,Ae]=i.useState(null),[te,Pe]=i.useState(null),[Be,Y]=i.useState(null),[F,K]=i.useState(null),J=Do(S=>S.ids),Z=xc(i.useCallback(S=>e?S.rankById:Ni,[e])),pe=nn(S=>e?yc(S.catalog):"",void 0,"catalog"),Se=i.useMemo(()=>pe?pe.split("|"):ur,[pe]),xe=i.useMemo(()=>new Set(Se),[Se]),ne=wc(Tr(S=>e?Object.entries(S.index.session.unseenCount).filter(([,H])=>H>0).map(([H])=>H).sort():ur)),ce=i.useMemo(()=>new Set(ne),[ne]),q=Do(S=>S.toggle),[fe,_e]=i.useState(()=>{try{const S=jn().getItem(ni);if(!S)return new Set;const H=JSON.parse(S);return new Set(Array.isArray(H)?H.filter(V=>typeof V=="string"):[])}catch{return new Set}}),[W,X]=i.useState(()=>{try{const S=jn().getItem(si);if(!S)return new Map;const H=JSON.parse(S),V=new Map;return Object.entries(H).forEach(([Re,Ke])=>{Array.isArray(Ke)&&V.set(Re,Ke.filter(Qe=>typeof Qe=="string"))}),V}catch{return new Map}}),ie=i.useMemo(()=>{try{const S=jn().getItem(ri);if(!S)return new Map;const H=JSON.parse(S),V=new Map;return Object.entries(H).forEach(([Re,Ke])=>{typeof Ke=="string"&&Ke.length>0&&V.set(Re,Ke)}),V}catch{return new Map}},[]),ge=i.useCallback(S=>{try{N.setItem(ri,JSON.stringify(Object.fromEntries(S.entries())))}catch{}},[N]),[be,Te]=i.useState(new Map),je=i.useRef(0),ee=Ls(S=>S.homeDirectory),me=Ls(S=>S.currentDirectory),de=pt(S=>S.projects),Ce=pt(S=>S.activeProjectId),We=pt(S=>S.removeProject),He=pt(S=>S.setActiveProjectIdOnly),ye=pt(S=>S.updateProjectMeta),re=pt(S=>S.reorderProjects),Fe=le(S=>S.setActiveMainTab),De=le(S=>S.setSettingsDialogOpen),ot=le(S=>S.setSettingsPage),it=le(S=>S.toggleHelpDialog),Ve=le(S=>S.setSessionSwitcherOpen),Lt=le(S=>S.setArchivePageOpen),Nt=le(S=>S.notifyOnSubtasks),jt=le(S=>S.showDeletionDialog),Bt=le(S=>S.setShowDeletionDialog),et=vc(d,120),mt=i.useMemo(()=>et.trim().toLowerCase(),[et]),tt=mt.length>0,gt=ht(S=>S.collapsedFolderIds),Ct=ht(S=>S.foldersMap),qt=ht(S=>S.getFoldersForScope),yt=ht(S=>S.createFolder),we=ht(S=>S.renameFolder),Oe=ht(S=>S.deleteFolder),ke=ht(S=>S.addSessionToFolder),Le=ht(S=>S.addSessionsToFolder),Ye=ht(S=>S.removeSessionFromFolder),ut=ht(S=>S.removeSessionsFromFolders),It=ht(S=>S.toggleFolderCollapse),Rt=ht(S=>S.getSessionFolderId);If({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchContainerRef:p});const _t=Sc(e),{git:qe}=$s(),st=nn(S=>S.connection,void 0,"chrome"),wt=nn(S=>{for(const H of S.catalog.listStatusByDirectory.values())if(H==="ready")return!0;return!1},void 0,"catalog"),Ut=Ar({archived:!1}),bt=Ar({archived:!0}),Ks=Ee(S=>S.setCurrentSession),zt=Ee(S=>S.updateSessionTitle),Cs=Ee(S=>S.shareSession),ks=Ee(S=>S.unshareSession),$t=Nr(S=>S.projects),Qt=Nr(S=>S.refreshProject),at=i.useMemo(()=>jc(de,{projects:$t}),[de,$t]),ue=i.useMemo(()=>{const S=new Map;for(const H of de){const V=Ne(H.path);if(!V)continue;const Re=$t.get(V)?.error;Re&&S.set(V,Re)}return S},[de,$t]);i.useEffect(()=>{if(!y)return;const S=de.find(V=>V.id===y);if(!S){Rs.getState().clearSpaceSelection();return}if(!C)return;(at.get(Ne(S.path)??S.path)??[]).some(V=>Ne(V.path)===Ne(C))||(Rs.getState().clearSelectedWorktree(),ae.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[at,de,y,C]);const Ze=Ee(S=>S.openNewSessionDraft),ft=i.useCallback(S=>{le.getState().closeMainSurfaces(),Ze(S),r?.()},[r,Ze]),vt=Dn(Tr(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}))),ns=i.useMemo(()=>Cc(de,at,{includeWorktrees:!0}),[at,de]),lt=i.useMemo(()=>Ut.filter(S=>$f(S,ns,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:ee})),[Ut,ee,ns]),bn=i.useMemo(()=>[...lt,...bt],[bt,lt]),Ws=Jr(),Qn=i.useMemo(()=>`${Ws}|${de.map(S=>`${S.id}:${Ne(S.path)??""}`).join("|")}`,[de,Ws]),Vt=i.useMemo(()=>{const S=new Set;let H=!0;for(const V of de){const Re=Ne(V.path);if(!Re)continue;const Ke=$t.get(Re)?.status??"idle";Ke==="failed"&&S.add(Re),(Ke==="idle"||Ke==="loading")&&(H=!1)}return{complete:H,unresolved:S}},[de,$t]),Vn=Vt.complete?Qn:null,rs=!Vt.complete,xn=Vt.unresolved,{isTablet:Hs}=zs(),As=s||Hs,Jn=Nf({mobileVariant:s,isTablet:Hs}),{buildGroupSearchText:Xn,filterSessionNodesForSearch:Ys,buildGroupedSessions:qs}=Af({homeDirectory:ee,pinnedSessionIds:J,sessionOrderRanks:Z}),{scheduleCollapsedProjectsPersist:D}=Ef({safeStorage:N,keys:{sessionExpanded:oi,projectCollapse:ti,groupOrder:si,groupCollapse:ni},groupOrderByProject:W,collapsedGroups:fe,setExpandedParents:A,setCollapsedProjects:j}),oe=i.useMemo(()=>kc(lt,J,Z),[J,Z,lt]),ve=i.useMemo(()=>oe.map(S=>S.id).join("|"),[oe]),Ue=i.useRef(null),ct=i.useMemo(()=>{const S=Ue.current;if(S&&S.signature===ve)return S.map;const H=new Map(oe.map((V,Re)=>[V.id,Re]));return Ue.current={signature:ve,map:H},H},[oe,ve]),Je=i.useMemo(()=>{const S=new Map;return oe.forEach(H=>{const V=H.parentID;if(!V)return;const Re=S.get(V)??[];Re.push(H),S.set(V,Re)}),S.forEach(H=>H.sort((V,Re)=>Qr(V,Re,J,Z))),S},[oe,J,Z]),Qs=i.useMemo(()=>t.jsx(bs,{icon:"chat-new",mobileVariant:s,onClick:()=>ft(),children:"New session"}),[s,ft]),Jt=i.useMemo(()=>de.find(S=>S.id===x)??null,[de,x]),_a=i.useCallback(S=>{x&&ye(x,{label:S.label,defaultModel:S.defaultModel??null})},[x,ye]),Ua=i.useCallback(()=>{const S=Dn.getState();if(S.available&&S.info){Q(!0);return}vt.checkForUpdates().then(()=>{const{available:H,error:V}=Dn.getState();if(V){ae.error("Failed to check for updates",{description:V});return}if(!H){ae.success("You are on the latest version");return}Q(!0)})},[vt]),Ns=Ac(),ao=i.useCallback(()=>{if(s&&Ve(!1),r?.(),Ns?.openSettings){Ns.openSettings();return}De(!0)},[Ns,s,r,Ve,De]),za=vt.available&&(vt.runtimeType==="desktop"||vt.runtimeType==="web"),$a=Ee(S=>S.deleteSession),lo=Ee(S=>S.deleteSessions),Ga=Ee(S=>S.archiveSession),co=Ee(S=>S.archiveSessions),Ka=Ee(S=>S.unarchiveSession),Wa=Ee(S=>S.unarchiveSessions),{copiedSessionId:Ha,handleSessionSelect:Ya,handleSessionDoubleClick:qa,handleSaveEdit:Qa,handleCancelEdit:Va,handleShareSession:Ja,handleCopyShareUrl:Xa,handleCopySessionId:Za,handleUnshareSession:el,handleDeleteSession:tl,handleRestoreSession:sl,confirmDeleteSession:nl}=Rf({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:u,setActiveMainTab:Fe,setSessionSwitcherOpen:Ve,setCurrentSession:Ks,updateSessionTitle:zt,shareSession:Cs,unshareSession:ks,deleteSession:$a,deleteSessions:lo,archiveSession:Ga,archiveSessions:co,unarchiveSession:Ka,childrenMap:Je,showDeletionDialog:jt,setDeleteSessionConfirm:Ae,deleteSessionConfirm:G,setEditingId:g,setEditTitle:v,editingId:m,editTitle:h}),rl=i.useCallback(()=>{if(!te)return;const{scopeKey:S,folderId:H}=te;Pe(null),Oe(S,H)},[te,Oe]),uo=i.useCallback(()=>{xs.requestDirectoryDialog()},[]),ol=i.useCallback(S=>{A(H=>{const V=Dd(H,S);try{N.setItem(oi,JSON.stringify(Array.from(V)))}catch{}return V})},[N]),fo=i.useCallback((S,H)=>{if(!S)return null;H&>.has(H)&&It(H);const V=yt(S,"New folder",H);return _(V.id),$(V.name),V},[gt,It,yt]),Vs=kt(Ya),il=kt(qa),al=kt(Qa),ll=kt(Va),cl=kt(Ja),dl=kt(Xa),ul=kt(Za),fl=kt(el),hl=kt(tl),pl=kt(sl),Zn=kt(fo),ho=i.useCallback((S,H)=>{L(V=>{const Re=new Map(V);return Re.set(S,H+7),Re})},[]),yn=i.useCallback(S=>{L(H=>{if(!H.has(S))return H;const V=new Map(H);return V.delete(S),V})},[]),po=i.useCallback(S=>{L(H=>{let V=!1;const Re=new Map(H),Ke=`${S}:`;for(const Qe of Re.keys())Qe.startsWith(Ke)&&(Re.delete(Qe),V=!0);return V?Re:H})},[]),ml=i.useCallback(S=>{je.current=Date.now()+150,po(S),j(H=>{const V=new Set(H);V.has(S)?V.delete(S):V.add(S);try{N.setItem(ti,JSON.stringify(Array.from(V)))}catch{}return D(V),V})},[po,N,D]),os=i.useMemo(()=>de.map(S=>({...S,normalizedPath:Ne(S.path)})).filter(S=>!!S.normalizedPath),[de]),gl=i.useMemo(()=>os.map(S=>S.normalizedPath),[os]),mo=Nc(e?gl:ur);Of({enabled:e,normalizedProjects:os,gitRepoStatus:mo,setProjectRepoStatus:P,setProjectRootBranches:Te});const go=i.useMemo(()=>Kf(lt,os,at,bt),[bt,at,os,lt]);Uf({enabled:e,hasAuthoritativeGlobalSessions:wt,sessions:bn});const{getSessionsForProject:bl,getArchivedSessionsForProject:xl}=Lf({ownership:go});xf({enabled:e,normalizedProjects:os,ownership:go,hasAuthoritativeGlobalSessions:wt,isWorktreeTopologyLoading:rs,unresolvedWorktreeProjectPaths:xn,foldersMap:Ct,createFolder:yt,addSessionToFolder:ke});const bo=i.useRef(!1);Ce&&E.has(Ce)&&(bo.current=!!E.get(Ce));const yl=pp(S=>S.showArchivedSessions),er=pt(S=>S.manualProjectOrder),xo=i.useRef(new Set),wn=Md(xo.current,w,"project");xo.current=wn;const tr={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:Hs,catalogSessions:Ut,archivedSessions:bt,projects:de,activeProjectId:Ce,manualProjectOrder:er,currentDirectory:me,availableWorktreesByProject:at,pinnedSessionIds:J,sessionOrderRanks:Z,foldersMap:Ct,collapsedFolderIds:gt,gitBranches:_t,gitRepoStatus:mo,updateStore:vt,showArchivedSessions:yl,projectRepoStatus:E,projectRootBranches:be,resolvedWorktreeTopologyKey:Vn,unresolvedWorktreeProjectPaths:xn,isSessionSearchOpen:c,sessionSearchQuery:d,editingId:m,editTitle:h,editingProjectDialogId:x,expandedParents:w,collapsedProjects:k,visibleSessionCountByGroup:B,updateDialogOpen:z,openSidebarMenuKey:O,renamingFolderId:M,renameFolderDraft:se,deleteSessionConfirm:G,deleteFolderConfirm:te,bulkDeleteConfirm:F,collapsedGroups:fe},yo=i.useRef(null),wo=yo.current;if(wo){let S=!1;for(const H of Object.keys(tr))Object.is(wo[H],tr[H])||(Mt(`ui.session_sidebar.source.${H}`),S=!0);S||Mt("ui.session_sidebar.source.parent_or_context")}yo.current=tr;const wl=i.useMemo(()=>{const S=new Map(er.map((H,V)=>[H,V]));return[...os].sort((H,V)=>(S.get(H.id)??1/0)-(S.get(V.id)??1/0))},[er,os]),{projectSections:Et,groupSearchDataByGroup:vo,sectionsForRender:vl,flatSectionsForRender:sr,searchMatchCount:Sl}=wf({normalizedProjects:wl,getSessionsForProject:bl,getArchivedSessionsForProject:xl,availableWorktreesByProject:at,projectRepoStatus:E,projectRootBranches:be,lastRepoStatus:bo.current,buildGroupedSessions:qs,hasSessionSearchQuery:tt,normalizedSessionSearchQuery:mt,filterSessionNodesForSearch:Ys,buildGroupSearchText:Xn,foldersMap:Ct}),vn=i.useMemo(()=>{const S=lt.filter(V=>Yn(rn(V),ee));if(S.length===0)return null;const H=qs(S,"~",[],null,!1).map(V=>tt?{...V,sessions:Ys(V.sessions,mt)}:V).filter(V=>V.sessions.length>0&&!V.isArchivedBucket);return H.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:H}},[qs,Ys,tt,ee,mt,lt]),jl=i.useMemo(()=>{if(!tt||!vn)return 0;const S=H=>H.reduce((V,Re)=>V+1+S(Re.children),0);return vn.groups.reduce((H,V)=>H+S(V.sessions),0)},[vn,tt]),Cl=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:kl}=yf(W),So=i.useRef(!1);i.useEffect(()=>{if(So.current||Et.length===0)return;const S=Et.flatMap(H=>H.groups.filter(V=>V.isArchivedBucket).map(V=>`${H.project.id}:${V.id}`));S.length>0&&_e(H=>new Set([...H,...S])),So.current=!0},[Et]);const{filteredSectionsForSidebarRender:Al,totalSessionCount:Nl,sessionCountByProject:Il,hasActiveSessionByProject:Rl,activeDirectoriesByProject:Js,hasUnseenByProject:El}=dp({projectSections:Et,flatSectionsForRender:sr,sectionsForRender:vl,selectedSpaceId:y,selectedWorktreePath:C,homeDirectory:ee,activeSessionIdSet:xe,unreadSessionIdSet:ce}),nr=i.useCallback(S=>{if(Rs.getState().selectSpace(S),!S)return;He(S);const H=Et.find(Ke=>Ke.project.id===S),V=H?.groups.find(Ke=>Ke.isMain),Re=V?.sessions[0]?.session;Re?Vs(Re.id,V?.directory??H?.project.normalizedPath??null,{keepPanelOpen:!0}):H&&ft({selectedProjectId:S,directoryOverride:H.project.normalizedPath})},[ft,Et,He,Vs]),Dl=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",Ml=s?"size-5":"h-4.5 w-4.5",Sn=kt((S,H=0,V,Re,Ke=!1,Qe,Gt="project",Is)=>t.jsx(qh,{node:S,depth:H,groupDirectory:V,projectId:Re,archivedBucket:Ke,pinnedSessionIds:J,expandedParents:wn,hasSessionSearchQuery:tt,normalizedSessionSearchQuery:mt,notifyOnSubtasks:Nt,editingId:m,setEditingId:g,editTitle:h,setEditTitle:v,handleSaveEdit:al,handleCancelEdit:ll,toggleParent:ol,handleSessionSelect:Vs,handleSessionDoubleClick:il,togglePinnedSession:q,handleShareSession:cl,copiedSessionId:Ha,handleCopyShareUrl:dl,handleCopySessionId:ul,handleUnshareSession:fl,openSidebarMenuKey:O,setOpenSidebarMenuKey:T,renamingFolderId:M,getFoldersForScope:qt,getSessionFolderId:Rt,removeSessionFromFolder:Ye,addSessionToFolder:ke,createFolderAndStartRename:Zn,handleDeleteSession:hl,handleRestoreSession:pl,mobileVariant:s,alwaysShowActions:As,allowQuickArchiveAction:Jn,renderSessionNode:Sn,secondaryMeta:Qe,renderContext:Gt,subtreeContainsEditing:Is?.subtreeContainsEditing??mp,menuOpenSessionId:Is?.menuOpenSessionId??null,nodeStructureKey:Is?.nodeStructureKey??"",childRenderExtrasFor:Is?.childRenderExtrasFor})),Pl=i.useMemo(()=>{const S=new Map;return sr.forEach(H=>{const V=H.groups.find(Re=>!Re.isArchivedBucket);V?.folderScopes&&V.folderScopes.length>0&&S.set(H.project.id,V.folderScopes)}),S},[sr]),Tl=i.useCallback((S,H)=>{const V=[];return H.forEach(Re=>{Re.isArchivedBucket||(V.push(Re.directory),Re.folderScopes?.forEach(Ke=>V.push(Ke.directory)))}),t.jsx(tp,{directories:V})},[]),jo=i.useCallback(S=>{yn(S),_e(H=>{const V=new Set(H);return V.has(S)?V.delete(S):V.add(S),V})},[yn]),Fl=i.useCallback((S,H,V,Re,Ke,Qe,Gt)=>t.jsx(dh,{group:S,groupKey:H,projectId:V,hideGroupLabel:Re,dragHandleProps:Ke,compactBodyPadding:Qe,hasSessionSearchQuery:tt,normalizedSessionSearchQuery:mt,groupSearchDataByGroup:vo,visibleSessionCount:B.get(H),collapsedGroups:fe,hideDirectoryControls:a,collapsedFolderIds:gt,toggleFolderCollapse:It,renameFolder:we,deleteFolder:Oe,showDeletionDialog:jt,setDeleteFolderConfirm:Pe,renderSessionNode:Sn,showMoreGroupSessions:ho,resetGroupSessionLimit:yn,mobileVariant:s,alwaysShowActions:As,activeProjectId:Ce,setActiveProjectIdOnly:He,setActiveMainTab:Fe,setSessionSwitcherOpen:Ve,openNewSessionDraft:ft,addSessionToFolder:ke,createFolderAndStartRename:Zn,renamingFolderId:M,renameFolderDraft:se,setRenameFolderDraft:$,setRenamingFolderId:_,pinnedSessionIds:J,expandedParents:wn,sessionOrderIndex:ct,editingId:m,editTitle:h,openSidebarMenuKey:O,activeActivitySessionIds:xe,unreadActivitySessionIds:ce,notifyOnSubtasks:Nt,onToggleCollapsedGroup:jo,scrollContainerRef:Gt}),[tt,mt,vo,B,fe,a,gt,It,we,Oe,jt,Sn,ho,yn,s,As,Ce,He,Fe,Ve,ft,ke,Zn,M,se,J,wn,ct,m,h,O,xe,ce,Nt,jo]),Co=!!(M||m||x),{selectionModeEnabled:rr,hasSelection:ko,selectedIdsSize:Ol,bulkScopeIsArchived:Ll,derivedSelectionScope:Bl,bulkScopeFolders:_l,bulkCanRemoveFromFolder:Ul,handleToggleSelectionMode:zl,handleExitSelectionMode:$l,handleBulkMoveToFolder:Gl,handleBulkCreateFolderAndMove:Kl,handleBulkRemoveFromFolder:Wl,handleBulkDelete:Hl,handleBulkRestore:Yl,confirmBulkDelete:ql}=fp({isInlineEditing:Co,showDeletionDialog:jt,foldersMap:Ct,folderScopesByProject:Pl,addSessionsToFolder:Le,removeSessionsFromFolders:ut,createFolderAndStartRename:fo,archiveSessions:co,unarchiveSessions:Wa,deleteSessions:lo,setBulkDeleteConfirm:K}),Ao=i.useCallback(()=>{le.getState().closeMainSurfaces(),Fe("chat"),s&&Ve(!1),Ze(),r?.()},[s,r,Ze,Fe,Ve]),Ql=i.useCallback((S,H)=>{const V=de.find(Qe=>Qe.id===S);if(!V)return;const Re=Ne(H.path)?.toLowerCase(),Ke=!!(Re&&Js.get(S)?.has(Re));Y({projectId:S,projectPath:V.path,worktree:H,hasActiveSession:Ke})},[Js,de]),Vl=i.useCallback(async({force:S})=>{const H=Be;if(!H)return;const V=Ne(H.worktree.path)?.toLowerCase();if(!!(V&&Js.get(H.projectId)?.has(V))){Y({...H,hasActiveSession:!0}),ae.warning("Stop the active session before closing this worktree.");return}if(!qe.deleteGitWorktree){ae.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await qe.deleteGitWorktree(H.projectPath,{directory:H.worktree.path,force:S}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let Qe=await Qt(H.projectPath,qe);const Gt=Ne(H.worktree.path);Qe!==null&&Gt!==null&&Qe.some(Xl=>Ne(Xl.path)===Gt)&&(Qe=await Qt(H.projectPath,qe));const Is=Gt!==null&&Ne(me)===Gt,Jl=Gt!==null&&y===H.projectId&&Ne(C)===Gt;(Is||Jl)&&nr(H.projectId),Y(null),Qe===null?ae.warning("Worktree closed, but the sidebar could not be refreshed."):ae.success("Worktree closed.")}catch(Ke){const Qe=Ke instanceof Error?Ke.message:"Try again.";ae.error("Failed to close worktree.",{description:Qe})}},[Js,Be,me,qe,nr,Qt,y,C]);return t.jsx(Ic,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:p,className:U("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(Sf,{projectSections:Et,activeProjectId:Ce,initialActiveSessionByProject:ie,persistActiveSessionByProject:ge,handleSessionSelect:Vs,mobileVariant:s,openNewSessionDraft:Ze,setActiveMainTab:Fe,setSessionSwitcherOpen:Ve}),!a&&!s?t.jsx(fh,{onNewSession:Ao,showSidebarToggle:!0}):null,t.jsx(uh,{hideDirectoryControls:a,handleOpenDirectoryDialog:uo,onOpenArchive:()=>{s&&Ve(!1),Lt(!0)},onOpenSettings:s?ao:void 0,onOpenInstances:s?Ns?.openInstances:void 0,instanceLabel:s?Ns?.instanceLabel:void 0,onOpenUpdate:s?Ns?.openUpdate:void 0,headerActionIconClass:Ml,headerActionButtonClass:Dl,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:tt,searchMatchCount:Sl+(y===null?jl:0),selectionModeEnabled:rr,onToggleSelectionMode:zl,mobileVariant:s}),st==="error"||st==="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&&Et.length>0?t.jsx(mh,{projects:Et.map(S=>S.project),selectedProjectId:y,selectedWorktreePath:C,worktreesByProject:at,worktreeErrorsByProject:ue,onSelectProject:nr,onSelectWorktree:(S,H)=>{Rs.getState().selectWorktree(S,H),He(S);const Ke=Et.find(Qe=>Qe.project.id===S)?.groups.find(Qe=>Ne(Qe.directory)===Ne(H))?.sessions[0]?.session;Ke?Vs(Ke.id,H,{keepPanelOpen:!0}):ft({selectedProjectId:S,directoryOverride:H})},onCloseWorktree:Ql,onOpenDirectoryDialog:uo,onOpenProjectEditDialog:I,onRemoveProject:We,totalSessionCount:Nl,getSessionCountForProject:S=>Il.get(S)??0,hasActiveSessionByProject:Rl,activeDirectoriesByProject:Js,hasUnseenByProject:El,homeDirectory:ee,mobileVariant:s}):null,t.jsx(yh,{sectionsForRender:Al,allFoldersOnlySection:y===null?vn:null,projectSections:Et,activeProjectId:Ce,showOnlyMainWorkspace:l,hasSessionSearchQuery:tt,emptyState:Qs,searchEmptyState:Cl,isAllFoldersView:y===null,pinnedSessionIds:J,renderSessionNode:Sn,renderGroupSessions:Fl,homeDirectory:ee,collapsedProjects:k,hideDirectoryControls:a,projectRepoStatus:E,mobileVariant:s,alwaysShowActions:As,toggleProject:ml,setActiveProjectIdOnly:He,setActiveMainTab:Fe,setSessionSwitcherOpen:Ve,openNewSessionDraft:ft,openProjectEditDialog:I,removeProject:We,reorderProjects:re,getOrderedGroups:kl,setGroupOrderByProject:X,renderProjectStatusIndicator:Tl,openSidebarMenuKey:O,setOpenSidebarMenuKey:T,isInlineEditing:Co}),s&&!(rr&&ko)?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(xa,{variant:"mobile"}),t.jsx(Me,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:Ao,"aria-label":"New session",children:t.jsx(R,{name:"chat-new",className:"size-4"})})]}):null,rr&&ko?t.jsx(up,{selectedCount:Ol,scopeKey:Bl,scopeFolders:_l,archivedBucket:Ll,onMoveToFolder:Gl,onCreateFolderAndMove:Kl,onRemoveFromFolder:Wl,canRemoveFromFolder:Ul,onRestore:Yl,onDelete:Hl,onDone:$l}):null,s?null:t.jsx(gh,{onOpenSettings:ao,onOpenShortcuts:it,onOpenAbout:()=>{ot("about"),De(!0)},onOpenUpdate:Ua,showRuntimeButtons:!0,showUpdateButton:za}),t.jsx(ep,{updateDialogOpen:z,setUpdateDialogOpen:Q,updateStore:vt,editingProject:Jt,setEditingProjectDialogId:I,handleSaveProjectEdit:_a,deleteSessionConfirm:G,setDeleteSessionConfirm:Ae,showDeletionDialog:jt,setShowDeletionDialog:Bt,confirmDeleteSession:nl,deleteFolderConfirm:te,setDeleteFolderConfirm:Pe,confirmDeleteFolder:rl,closeWorktreeConfirm:Be,setCloseWorktreeConfirm:Y,confirmCloseWorktree:Vl,bulkDeleteConfirm:F,setBulkDeleteConfirm:K,confirmBulkDelete:ql})]})})},Rg=i.memo(gp),ii=6,At=.18,en=1.2,tn=.38,Fn=48,bp=(e,s)=>e==="left"?s<0:s>0,Eg=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Dg=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,ai=(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)),Mg=e=>{const{side:s,dx:n,dy:r,dt:o,progress:a,isDragging:l}=e,c=n/Math.max(1,o);if(l){const u=s==="left"?c<-At:c>At,d=s==="left"?c>At:c<-At;return u||!d&&a<tn}return Math.abs(n)>=Fn&&Math.abs(r)<=Math.abs(n)*en&&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<-At?!1:l>At?!0:a>tn:l>At?!0:l<-At?!1:a>tn:n?l>At?!1:l<-At?!0:a>tn:l<-At?!0:l>At?!1:a>tn},yp='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',wp=(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},On=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Yr=512*1024,vp=new TextEncoder,Sp=new TextDecoder,fr=e=>{const s=vp.encode(e);if(s.byteLength<=Yr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-Yr;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}`,hr=(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 li=!1,ci=0;const En=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(ci+=1,`tab-${Date.now().toString(36)}-${ci.toString(36)}`),pr=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 nt(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}`},mr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),gr=e=>({tabs:[e],activeTabId:e.id}),Dt=(e,s)=>e.tabs.findIndex(n=>n.id===s);let br=null,xr=null;const Np=e=>{if(xr&&br?.sessions===e.sessions&&br.nextTabId===e.nextTabId)return xr;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 br={sessions:e.sessions,nextTabId:e.nextTabId},xr=s,s},Ip=()=>{const e=Sd(()=>ld());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=Gs()(Bi(Zr((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=nt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=En(),c=mr(l,"Terminal");return a.set(r,gr(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=nt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=nt(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(nt(n),r))??On,createTab:n=>{const r=nt(n);if(!r)return"tab-invalid";const o=En();return e(a=>{const l=new Map(a.sessions),c=l.get(r),u=a.nextTabId+1,d=Ap(c?.tabs??[]),f=mr(o,d);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,gr(f)),{sessions:l,nextTabId:u}}),o},setActiveTab:(n,r)=>{const o=nt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Dt(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=nt(n),l=o.trim();l&&e(c=>{const u=new Map(c.sessions),d=u.get(a);if(!d)return c;const f=Dt(d,r);if(f<0||d.tabs[f]?.label===l)return c;const p=[...d.tabs];return p[f]={...p[f],label:l},u.set(a,{...d,tabs:p}),{sessions:u}})},setTabIconKey:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Dt(u,r);if(d<0)return l;const f=o?.trim()||null;if(u.tabs[d]?.iconKey===f)return l;const p=[...u.tabs];return p[d]={...p[d],iconKey:f},c.set(a,{...u,tabs:p}),{sessions:c}})},closeTab:(n,r)=>{const o=nt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const u=Dt(c,r);if(u<0)return a;const d=c.tabs.filter(h=>h.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,h])=>!(h.directory===o&&h.tabId===r))),p=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,b=Es(o,r),m=a.buffers.has(b)?hr(a.buffers,h=>h===b):null;if(d.length===0){const h=En(),v=mr(h,"Terminal");return l.set(o,gr(v)),{sessions:l,nextTabId:a.nextTabId+1,...m?{buffers:m}:{},...p?{projectActionRuns:f}:{}}}let g=c.activeTabId;return c.activeTabId===r&&(g=d[Math.min(u,d.length-1)]?.id??d[0]?.id??null),l.set(o,{...c,tabs:d,activeTabId:g}),{sessions:l,...m?{buffers:m}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Dt(u,r);if(d<0)return l;const f=u.tabs[d],p=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,m={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},g=Es(a,r),h=p&&l.buffers.has(g)?hr(l.buffers,x=>x===g):null,v=[...u.tabs];return v[d]=m,c.set(a,{...u,tabs:v}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Dt(u,r);if(d<0)return l;const f=[...u.tabs];return f[d]={...f[d],lifecycle:o,isConnecting:!1},c.set(a,{...u,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const a=nt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Dt(u,r);if(d<0)return l;const f=[...u.tabs];return f[d]={...f[d],isConnecting:o},c.set(a,{...u,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,a)=>{const l=nt(n);e(c=>{const u=c.sessions.get(l);if(!u||Dt(u,r)<0)return c;const d=Es(l,r),f=c.buffers.get(d)??On;if(f.lastSequence>a)return c;const p=fr(o);if(f.lastSequence===a&&f.byteLength===p.byteLength&&f.chunks.map(g=>g.data).join("")===p.text)return c;const b=c.nextChunkId,m=new Map(c.buffers);return m.set(d,{chunks:p.text?[{id:b,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:a}),{buffers:m,nextChunkId:p.text?b+1:b}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=nt(n);e(u=>{const d=u.sessions.get(c);if(!d||Dt(d,r)<0)return u;const f=Es(c,r),p=u.buffers.get(f)??On;if(a!==void 0&&a<=p.lastSequence)return u;const b=u.nextChunkId,m=fr(o),g=l!==void 0&&l!==o?fr(l).text:void 0,h={id:b,data:m.text,...g!==void 0?{replayData:g}:{},byteLength:m.byteLength},v=[...p.chunks,h];let x=p.byteLength+h.byteLength;for(;x>Yr&&v.length>1;){const w=v.shift();if(!w)break;x-=w.byteLength}const I=new Map(u.buffers);return I.set(f,{chunks:v,byteLength:x,lastSequence:a??p.lastSequence}),{buffers:I,nextChunkId:b+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=nt(n);e(c=>{const u=new Map(c.sessions),d=u.get(l);if(!d)return c;const f=Dt(d,r);if(f<0)return c;const p=d.tabs[f],b=a.autoOpened??p.previewAutoOpened,m=a.locked??p.previewUrlLocked;if(p.previewUrl===o&&p.previewAutoOpened===b&&p.previewUrlLocked===m)return c;const g=[...d.tabs];return g[f]={...p,previewUrl:o,previewAutoOpened:b,previewUrlLocked:m},u.set(l,{...d,tabs:g}),{sessions:u}})},markPreviewAutoOpened:(n,r)=>{const o=nt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const u=Dt(c,r);if(u<0)return a;const d=c.tabs[u];if(!d.previewUrl||d.previewAutoOpened)return a;const f=[...c.tabs];return f[u]={...d,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=nt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Es(r,""),c=hr(o.buffers,d=>d.startsWith(l)),u=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,d])=>d.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:u}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:jp,storage:Ip(),partialize:Np,merge:(e,s)=>{if(!pr(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[u,d]=c;if(typeof u!="string"||!pr(d))continue;const f=Array.isArray(d.tabs)?d.tabs:[],p=[],b=new Map;for(const v of f){if(!pr(v))continue;const x=typeof v.id=="string"?v.id:null;if(!x)continue;const I=Cp(x);I!==null&&(o=Math.max(o,I));const w=I===null?x:En();b.set(x,w),p.push({id:w,label:typeof v.label=="string"?v.label:"Terminal",iconKey:typeof v.iconKey=="string"?v.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof v.createdAt=="number"?v.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const m=typeof d.activeTabId=="string"?d.activeTabId:null,g=m?b.get(m)??m:null,h=g?p.some(v=>v.id===g):!1;r.set(u,{tabs:p,activeTabId:h?g:p[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"&&!li){li=!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 yr(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 Ep=(e,s)=>{const n=`${e??""} ${s??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},Dp=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),Mp=(e,s,n)=>{if(e.altKey)return null;const r=Dp(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},sn=e=>typeof e=="string"&&e.trim().length>0;async function di(e){return sn(e)?(await ws(e)).ok:!1}async function Pp(){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([ls(()=>import("./vendor-xterm-xterm-CrXqRur4.js"),__vite__mapDeps([112,113])),ls(()=>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),u=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),d=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-u-15)/a)),rows:Math.max(1,Math.floor((e.clientHeight-d)/l))}},Oa=i.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:u=!1,autoFocus:d=!0,isVisible:f=!0},p)=>{const b=i.useRef(null),m=i.useRef(null),g=i.useRef(null),h=i.useRef(n),v=i.useRef(r),x=i.useRef(o),I=i.useRef(a),w=i.useRef(l),A=i.useRef(null),N=i.useRef(null),k=i.useRef(null),j=i.useRef(""),y=i.useRef(!1),C=i.useRef(0),E=i.useRef(f),P=i.useRef(!1),[B,L]=i.useState(0),[z,Q]=i.useState(0),[O,T]=i.useState(!1),[M,_]=i.useState(!1);h.current=n,v.current=r,E.current=f,x.current=o,I.current=a,w.current=l,i.useLayoutEffect(()=>{const Y=b.current;if(!Y)return;const F=Up(Y,a,l);N.current=F,F&&v.current(F.cols,F.rows)},[a,l]);const se=i.useCallback(()=>{const Y=b.current,F=m.current;if(!Y||!F||!g.current||!E.current)return;const K=Y.getBoundingClientRect();if(!(K.width<24||K.height<24))try{g.current.fit();const J={cols:F.cols,rows:F.rows};(!A.current||A.current.cols!==J.cols||A.current.rows!==J.rows)&&(A.current=J,v.current(J.cols,J.rows)),P.current||(P.current=!0,L(Z=>Z+1))}catch{}},[]),$=i.useCallback(()=>{if(y.current||!j.current||!m.current)return;const Y=m.current,F=j.current;if(j.current="",!F)return;y.current=!0;const K=C.current;Y.write(F,()=>{m.current!==Y||C.current!==K||(y.current=!1,j.current&&$())})},[]),G=i.useCallback(()=>{k.current=null,j.current="",y.current=!1,C.current+=1;const Y=m.current;if(!Y){Q(F=>F+1);return}try{Y.reset()}catch{Q(F=>F+1)}},[]),Ae=i.useCallback(Y=>{Y?.preventDefault(),_(sn(m.current?.getSelection())),T(!0)},[]),te=i.useCallback(Y=>{Y.stopPropagation();const F=m.current,K=F?.getSelection()??"";F?.focus(),sn(K)&&di(K)},[]),Pe=i.useCallback(Y=>{Y.stopPropagation();const F=m.current;F?.focus(),Pp().then(K=>{K&&m.current===F&&F&&F.paste(K)})},[]),Be=i.useCallback(Y=>{Y.stopPropagation();const F=m.current;F?.focus();try{F?.selectAll()}catch{}_(sn(F?.getSelection()))},[]);return i.useEffect(()=>{const Y=b.current;if(!Y)return;let F=!1,K=null,J=null,Z=null,pe=null,Se=[];const xe=()=>{K&&E.current&&(K.options.cursorBlink=!0)},ne=fe=>{fe.relatedTarget instanceof Node&&Y.contains(fe.relatedTarget)||K&&(K.options.cursorBlink=!1)},ce=()=>{K&&E.current&&Y.contains(document.activeElement)&&(K.options.cursorBlink=!0)},q=()=>{K&&(K.options.cursorBlink=!1)};return Y.addEventListener("focusin",xe),Y.addEventListener("focusout",ne),window.addEventListener("focus",ce),window.addEventListener("blur",q),Promise.all([Lp(),_p()]).then(([{Xterm:fe,Fit:_e}])=>{if(F)return;const W=x.current,X=I.current,ie=w.current;K=new fe.Terminal({...yr(X,ie,W),...N.current??{}});const ge=new _e.FitAddon;K.loadAddon(ge),K.open(Y),m.current=K,g.current=ge;const be=typeof navigator>"u"?"other":Ep(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Te=K;K.attachCustomKeyEventHandler(je=>{if(je.type!=="keydown")return!0;const ee=Te.getSelection(),me=Mp({key:je.key,code:je.code,ctrlKey:je.ctrlKey,shiftKey:je.shiftKey,metaKey:je.metaKey,altKey:je.altKey},be,sn(ee));return me==="copy"?(di(ee),!1):me!=="ignore"}),Se=[K.onData(je=>h.current(je))],J=new ResizeObserver(()=>{Z&&clearTimeout(Z),Z=setTimeout(se,80)}),J.observe(Y),se(),pe=requestAnimationFrame(se)}),()=>{F=!0;const fe=document.activeElement;fe instanceof HTMLElement&&Y.contains(fe)&&(fe.blur(),window.Capacitor?.getPlatform?.()==="android"&&ls(async()=>{const{Keyboard:W}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:W}},__vite__mapDeps([114,115])).then(({Keyboard:W})=>W.hide()).catch(()=>{})),J?.disconnect(),Z&&clearTimeout(Z),pe!==null&&cancelAnimationFrame(pe),Y.removeEventListener("focusin",xe),Y.removeEventListener("focusout",ne),window.removeEventListener("focus",ce),window.removeEventListener("blur",q),Se.forEach(_e=>_e.dispose()),K?.dispose(),m.current=null,g.current=null,A.current=null,k.current=null,j.current="",y.current=!1,C.current+=1,P.current=!1}},[se,z]),i.useEffect(()=>{const Y=m.current;Y&&(Y.options.theme=yr(a,l,o).theme,Y.options.fontFamily=yr(a,l,o).fontFamily,Y.options.fontSize=l)},[a,l,o]),i.useEffect(()=>{const Y=m.current,F=b.current;!Y||!F||(Y.options.cursorBlink=f&&document.hasFocus()&&F.contains(document.activeElement))},[f,B]),i.useEffect(()=>{if(!m.current)return;if(s.length===0){k.current!==null&&G();return}const F=k.current;let K=-1;if(F!==null){for(let pe=s.length-1;pe>=0;pe-=1){const Se=s[pe].id;if(Se===F){K=pe;break}if(Se<F)break}if(K<0){G();return}}const J=K<0,Z=K>=0?s.slice(K+1):s;j.current+=Z.map(pe=>J?pe.replayData??pe.data:pe.data).join(""),k.current=s.at(-1)?.id??null,$()},[s,$,B,G]),i.useEffect(()=>{if(!d||!f)return;const Y=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(Y)},[d,f,B,e]),i.useEffect(()=>{const Y=b.current,F=m.current;if(!u||!Y||!F)return;let K=null,J=null,Z="idle",pe=0,Se=0,xe=0,ne=0,ce=null;const q=Math.max(12,l+2),fe=()=>{window.Capacitor?.getPlatform?.()==="android"&&ls(async()=>{const{Keyboard:me}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:me}},__vite__mapDeps([114,115])).then(({Keyboard:me})=>me.show()).catch(()=>{})},_e=()=>{J&&(clearTimeout(J),J=null)},W=(ee,me)=>{const de=Y.querySelector("canvas");return de?Tp(ee,me,de.getBoundingClientRect(),F.cols,F.rows):null},X=(ee,me)=>{const de=Y.querySelector("canvas");if(!de)return;const Ce=de.getBoundingClientRect(),We=Ce.left+(me.column+.5)/F.cols*Ce.width,He=Ce.top+(me.row+.5)/F.rows*Ce.height;de.dispatchEvent(new MouseEvent(ee,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:We,clientY:He}))},ie=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ge=ee=>{ee.pointerType!=="touch"||K!==null||(K=ee.pointerId,Z="pending",pe=ee.clientX,Se=ee.clientY,xe=ee.clientY,ne=0,ce=null,Y.setPointerCapture(ee.pointerId),J=setTimeout(()=>{if(J=null,K!==ee.pointerId||Z!=="pending")return;const me=W(pe,Se);if(!me)return;const de=F.buffer.active,Ce=Math.max(0,de.length-F.rows-de.viewportY+me.row),We=de.getLine(Ce),He=Array.from({length:F.cols},(Fe,De)=>We?.getCell(De)?.getChars()??""),ye=Fp(He,me.column),re={column:ye.startColumn,row:me.row};ce={column:ye.endColumn,row:me.row},Z="selecting",X("mousedown",re),X("mousemove",ce)},350))},be=ee=>{if(K!==ee.pointerId)return;if(Z==="selecting"){const Ce=W(ee.clientX,ee.clientY);Ce&&(!ce||Ce.column!==ce.column||Ce.row!==ce.row)&&(ce=Ce,X("mousemove",Ce)),ee.cancelable&&ee.preventDefault();return}if(Z==="pending"){if(Math.hypot(ee.clientX-pe,ee.clientY-Se)<8)return;_e(),Z="scrolling"}if(Z!=="scrolling")return;const me=xe-ee.clientY;xe=ee.clientY,ne+=me;const de=Math.trunc(ne/q);de&&(F.scrollLines(de),ne-=de*q),ee.cancelable&&ee.preventDefault()},Te=ee=>{if(K!==ee.pointerId)return;const me=Z==="pending",de=Z==="selecting";_e(),Y.hasPointerCapture(ee.pointerId)&&Y.releasePointerCapture(ee.pointerId),K=null,Z="idle",de&&ie(),me&&(F.focus(),fe())},je=ee=>{if(K!==ee.pointerId)return;const me=Z==="selecting";_e(),Y.hasPointerCapture(ee.pointerId)&&Y.releasePointerCapture(ee.pointerId),K=null,Z="idle",me&&ie()};return Y.addEventListener("pointerdown",ge),Y.addEventListener("pointermove",be,{passive:!1}),Y.addEventListener("pointerup",Te),Y.addEventListener("pointercancel",je),()=>{_e(),Y.removeEventListener("pointerdown",ge),Y.removeEventListener("pointermove",be),Y.removeEventListener("pointerup",Te),Y.removeEventListener("pointercancel",je)}},[u,l,B]),i.useImperativeHandle(p,()=>({focus:()=>m.current?.focus(),fit:se,getSelection:()=>{const Y=m.current,F=Y?.getSelectionPosition(),K=Y?.getSelection()??"";return!F||!K.trim()?null:{text:K,startLine:F.start.y+1,endLine:F.end.y+1}}}),[se]),t.jsxs(so,{open:O,onOpenChange:T,children:[t.jsx(no,{render:t.jsx("div",{ref:b,"data-terminal-owner":"main",className:U("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:Ae})}),t.jsxs(ro,{className:"min-w-[180px]",children:[t.jsxs(Fs,{disabled:!M,onClick:te,children:[t.jsx(R,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),t.jsxs(Fs,{onClick:Pe,children:[t.jsx(R,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),t.jsx(ga,{}),t.jsx(Fs,{onClick:Be,children:"Select All"})]})]})});Oa.displayName="TerminalViewport";const zp=({directory:e,tabId:s,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:a,terminal:l,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,lastViewportSizeRef:p,onInput:b,controllerRef:m})=>{const g=he(w=>e&&s?w.getBuffer(e,s).chunks:On.chunks),h=i.useRef(null),v=o&&a,x=i.useCallback(w=>{h.current=w,m&&(m.current=o?w:m.current),!o&&m&&m.current===w&&(m.current=null)},[m,o]);i.useEffect(()=>{if(!o||!a)return;const w=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(w)},[o,a,r,n]);const I=i.useCallback((w,A)=>{if(!o)return;const N=p.current;(!N||N.cols!==w||N.rows!==A)&&(p.current={cols:w,rows:A}),n&&l.resize({sessionId:n,cols:w,rows:A}).catch(()=>{})},[o,p,n,l]);return t.jsx("div",{className:U("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:t.jsx(Oa,{ref:x,sessionKey:r,chunks:g,onInput:b,onResize:I,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,autoFocus:v,isVisible:v},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(Pt,{modal:!1,children:[t.jsx(Tt,{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:U(vi({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(Ft,{align:"start",className:"w-64",children:[e.map(c=>{const u=c.id===(l?.id??s);return t.jsxs(rt,{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})]}),u?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:d=>{d.preventDefault(),d.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(vs,{}),t.jsxs(rt,{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=u=>{e&&u.preventDefault()};return t.jsxs(t.Fragment,{children:[t.jsx(Me,{type:"button",size:a,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),t.jsxs(Me,{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(Me,{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(Me,{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(Me,{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(Me,{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(Me,{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(Me,{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(Me,{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},ui=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(ui(c[1])).port}catch{return!1}});return ui((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 Ot("/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]},La=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"?La(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Ba={cols:80,rows:24},fi={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 u=Jp(c);if(!u||this.pendingUrls.has(u))return;const d=this.probeGeneration;this.pendingUrls.add(u),Xp(u).then(f=>{if(this.pendingUrls.delete(u),!f||this.probeGeneration!==d)return;const p=he.getState().getDirectoryState(s)?.tabs.find(b=>b.id===n);!p||p.previewUrlLocked||p.previewUrl===u||o(s,n,u,{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"?La(o):null};function rm({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:d,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:b,tabs:m}){const g=he(F=>F.ensureDirectory),h=he(F=>F.setTabSessionId),v=he(F=>F.setTabLifecycle),x=he(F=>F.setConnecting),I=he(F=>F.appendToBuffer),w=he(F=>F.replaceBuffer),A=he(F=>F.setTabPreviewUrl),[N,k]=i.useState(null),[j,y]=i.useState(!1),[C,E]=i.useState(!1),P=i.useRef(new Map),B=i.useRef(null),L=i.useRef(n),z=i.useRef(r),Q=i.useRef(s),O=i.useRef(null),T=i.useRef(new Set),M=i.useRef(new Map),_=i.useRef(m),se=i.useRef(l),$=i.useRef(a),G=i.useRef(e);_.current=m,se.current=l,$.current=a,G.current=e;const Ae=i.useCallback(()=>{const F=L.current;F&&M.current.get(F)?.reset()},[]);i.useEffect(()=>{z.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,d.current).catch(()=>{})},[d,e,r]),i.useEffect(()=>{L.current=n},[n]),i.useEffect(()=>{Q.current=s},[s]);const te=i.useCallback(()=>{for(const F of P.current.values())try{F()}catch{}P.current.clear(),B.current=null,E(!1)},[]);i.useEffect(()=>()=>{te(),z.current=null},[te]);const Pe=i.useCallback((F,K,J)=>{let Z=M.current.get(K);Z||(Z=new sm,M.current.set(K,Z)),Z.scan(F,K,J,A)},[A]),Be=i.useCallback((F,K,J)=>{if(P.current.has(J)){B.current=J;return}const Z=To(),pe=()=>To()===Z&&Q.current===F&&he.getState().getDirectoryState(F)?.tabs.find(xe=>xe.id===K)?.terminalSessionId===J,Se=e.connect(J,{onEvent:xe=>{if(pe())switch(xe.type){case"snapshot":{L.current===K&&z.current===J?(x(F,K,!1),k(null),y(!1),E(!1),b()):x(F,K,!1),w(F,K,xe.data??"",xe.sequence??0),Pe(F,K,xe.data??""),xe.status==="exited"&&v(F,K,"exited");break}case"reconnecting":{L.current===K&&(k(null),y(!1),E(!0));break}case"data":{xe.data&&(I(F,K,xe.data,xe.sequence,xe.replayData),Pe(F,K,xe.data));break}case"exit":{const ne=typeof xe.exitCode=="number"?xe.exitCode:null,ce=typeof xe.signal=="number"?xe.signal:null,fe=!!he.getState().getDirectoryState(F)?.tabs.find(_e=>_e.id===K)?.label?.startsWith("Action:");I(F,K,`\\r\\n[Process exited${ne!==null?` with code ${ne}`:""}${ce!==null?` (signal ${ce})`:""}]\\r\\n`),v(F,K,"exited"),L.current===K&&(x(F,K,!1),k(fe?null:"Terminal session ended"),y(!1),E(!1));break}}},onError:(xe,ne)=>{if(!pe())return;const ce=L.current===K;if(!ne){ce&&(k(null),y(!1));return}if(xe.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(F)?.tabs.find(fe=>fe.id===K)?.label?.startsWith("Action:")){ce&&(k(null),y(!1),x(F,K,!1),E(!1)),h(F,K,null),v(F,K,"idle");return}ce&&(E(!1),k(`Connection failed: ${xe.message}`),y(!0),x(F,K,!1),v(F,K,"exited"),h(F,K,null))}});P.current.set(J,()=>Se.close()),B.current=J},[I,b,w,Pe,x,v,h,e]),Y=i.useMemo(()=>m.map(F=>`${F.id}:${F.terminalSessionId??""}`).join(","),[m]);return i.useEffect(()=>{if(!l||!a||!s)return;const F=s,K=new Set;for(const J of m)J.terminalSessionId&&(K.add(J.terminalSessionId),Be(F,J.id,J.terminalSessionId));for(const[J,Z]of P.current)if(!K.has(J)){try{Z()}catch{}P.current.delete(J)}},[Y,m,s,l,a,Be]),i.useEffect(()=>cd(()=>{if(!se.current||!$.current)return;const F=Q.current;if(!F)return;const K=[];for(const Z of _.current){if(!Z.terminalSessionId)continue;he.getState().getDirectoryState(F)?.tabs.find(Se=>Se.id===Z.id)?.terminalSessionId===Z.terminalSessionId&&K.push({id:Z.id,terminalSessionId:Z.terminalSessionId})}if(P.current.clear(),B.current=null,K.length===0)return;E(!0),k(null),y(!1);for(const Z of K)Be(F,Z.id,Z.terminalSessionId);const J=O.current;if(J)for(const Z of K)G.current.resize({sessionId:Z.terminalSessionId,...J}).catch(()=>{})}),[Be]),i.useEffect(()=>{let F=!1;if(!l||!a)return;if(!s){k(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const J=s;if(!Q.current||Q.current!==J)return;if(!he.getState().getDirectoryState(J)){g(J);return}const pe=he.getState().getDirectoryState(J);if(!pe||pe.tabs.length===0)return;const Se=pe.activeTabId??pe.tabs[0]?.id??null;if(!Se)return;const xe=pe.tabs.find(W=>W.id===Se)??pe.tabs[0],ne=xe?.terminalSessionId??null,ce=xe?.lifecycle??"idle",q=!!xe?.label?.startsWith("Action:"),fe=he.getState().getBuffer(J,Se),_e=fe.byteLength>0||fe.chunks.length>0;if(!ne){if(ce==="exited"){x(J,Se,!1);return}if(q&&_e){x(J,Se,!1);return}const W=`${J}\0${Se}`;if(T.current.has(W))return;const X=O.current??Ba;T.current.add(W),k(null),y(!1),E(!1),x(J,Se,!0);try{const ie=await e.createSession({cwd:J,sessionId:Se,cols:X.cols,rows:X.rows,shell:c,loginShell:u,...d.current});if(!he.getState().getDirectoryState(J)?.tabs.find(Te=>Te.id===Se)){try{await e.close(ie.sessionId)}catch{}return}h(J,Se,ie.sessionId);const be=O.current;be&&(be.cols!==X.cols||be.rows!==X.rows)&&e.resize({sessionId:ie.sessionId,...be}).catch(()=>{});return}catch(ie){const ge=he.getState().getDirectoryState(J)?.tabs.find(be=>be.id===Se);if(!ge||ge.terminalSessionId||(x(J,Se,!1),Q.current!==J||L.current!==Se))return;k(ie instanceof Error?ie.message:"Failed to start terminal session"),y(!0),E(!1);return}finally{T.current.delete(W)}}!ne||F||(z.current=ne)})(),()=>{F=!0}},[p,s,r,o,n,a,f,l,g,x,v,h,e,u,c,d]),{connectionError:N,setConnectionError:k,isFatalError:j,setIsFatalError:y,isReconnectPending:C,setIsReconnectPending:E,terminalIdRef:z,lastViewportSizeRef:O,directoryRef:Q,activeTabIdRef:L,disconnectStream:te,resetTerminalPreviewScan:Ae,startStream:Be}}function om({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:u}){const[d,f]=i.useState(null),p=i.useRef(null),b=i.useCallback(()=>{u||p.current?.focus()},[u]),m=i.useCallback(()=>{u||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[u]);i.useEffect(()=>{!o&&d!==null&&f(null)},[o,d]),i.useEffect(()=>{!c&&d!==null&&f(null)},[c,d]);const g=i.useCallback(w=>{if(!w||n)return;let A=w,N=!1;d&&w.length>0&&(A=tm(w,d),N=!0);const k=s.current;k&&(e.sendInput(k,A).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),N&&(f(null),b()))},[d,b,n,r,e,s]),h=i.useCallback((w,A)=>{const N=l.current;if((!N||N.cols!==w||N.rows!==A)&&(l.current={cols:w,rows:A}),!a)return;const k=s.current;k&&e.resize({sessionId:k,cols:w,rows:A}).catch(()=>{})},[a,l,e,s]),v=i.useCallback(w=>{f(A=>A===w?null:w),b()},[b]),x=i.useCallback(w=>{const A=em(w,d);A&&(g(A),f(null),b())},[d,b,g]),I=i.useCallback(w=>{if(w.repeat)return;const A=w.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const N=A.length===1?A.toLowerCase():A;if(N in fi){w.preventDefault(),w.stopPropagation(),x(fi[N]);return}const k=nm(w,d);k&&(w.preventDefault(),w.stopPropagation(),g(k),f(null),b())},[d,b,x,g]);return i.useEffect(()=>{if(!(!o||!d||!c))return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[d,I,o,c]),{activeModifier:d,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:b,focusTerminalWhenWindowActive:m,handleViewportInput:g,handleViewportResize:h,handleModifierToggle:v,handleMobileKeyPress:x}}function im({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:u,activeTabIdRef:d,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:b,setConnectionError:m,setIsFatalError:g,setIsReconnectPending:h}){const v=he(B=>B.createTab),x=he(B=>B.setActiveTab),I=he(B=>B.closeTab),w=he(B=>B.setTabSessionId),A=he(B=>B.setTabLifecycle),[N,k]=i.useState(!1),j=i.useCallback(async()=>{if(!s||N)return;const B=he.getState().getDirectoryState(s),L=n??B?.activeTabId??B?.tabs[0]?.id??null;if(!L)return;const z=B?.tabs.find(Q=>Q.id===L)?.terminalSessionId??null;if(!(!z||!e.restartSession)){k(!0),m(null),g(!1),h(!1),p();try{const Q=c.current??Ba,O=await e.restartSession(z,{cwd:s,shell:o,loginShell:a,...Q,...l.current});if(he.getState().getDirectoryState(s)?.tabs.find(M=>M.id===L)?.terminalSessionId!==z||(w(s,L,O.sessionId),A(s,L,"running"),u.current!==s||d.current!==L))return;f.current=O.sessionId,b(s,L,O.sessionId)}catch(Q){if(he.getState().getDirectoryState(s)?.tabs.find(T=>T.id===L)?.terminalSessionId!==z||u.current!==s||d.current!==L)return;m(Q instanceof Error?Q.message:"Failed to restart terminal"),g(!1),h(!1),f.current=z,b(s,L,z)}finally{k(!1)}}},[n,d,u,s,r,N,c,p,m,g,h,A,w,b,e,l,f,a,o]),y=i.useCallback(async()=>{await j()},[j]),C=i.useCallback(()=>{if(!s)return;const B=v(s);x(s,B),m(null),g(!1),h(!1)},[v,s,x,m,g,h]),E=i.useCallback(B=>{s&&(x(s,B),m(null),g(!1),h(!1))},[s,x,m,g,h]),P=i.useCallback(B=>{if(!s)return;m(null),g(!1),h(!1);const L=he.getState().getDirectoryState(s)?.tabs.find(z=>z.id===B)?.terminalSessionId;(async()=>{L&&await e.close(L),I(s,B)})().catch(z=>m(z instanceof Error?z.message:"Terminal session ended"))},[I,s,m,g,h,e]);return{isRestarting:N,handleRestart:j,handleHardRestart:y,handleCreateTab:C,handleSelectTab:E,handleCloseTab:P}}const Pg=({visible:e,onCloseView:s,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=$s(),{currentTheme:a}=Ei(),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}=Rc(),u=le(re=>re.terminalFontSize),d=le(re=>re.terminalShell),f=le(re=>re.terminalLoginShells.includes(re.terminalShell)),{isMobile:p,isTablet:b,hasTouchOnlyPointer:m}=zs(),g=p||b,h=(g||m)&&o.platform==="web",v=!0,x=le(re=>re.showTerminalQuickKeysOnDesktop),I=g||x,w=Ee(re=>re.currentSessionId),A=Ee(re=>re.newSessionDraft),N=w!==null||A?.open===!0,k=Ec()??null,j=he(re=>k?re.sessions.get(k):void 0),y=he(re=>re.hasHydrated),C=le(re=>re.openContextPreview),E=i.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,v]),P=i.useMemo(()=>{if(j)return E?j.tabs.find(re=>re.id===E)??j.tabs[0]:j.tabs[0]},[j,E]),B=i.useMemo(()=>(j?.tabs??[]).map(re=>({icon:(()=>{const Fe=re.iconKey?ln[re.iconKey]??"terminal":"terminal";return t.jsx(R,{name:Fe,className:"h-4 w-4"})})(),id:re.id,label:re.label,title:re.label,closeLabel:"Close tab"})),[j?.tabs]),L=P?.terminalSessionId??null,z=P?.lifecycle??"idle",Q=i.useMemo(()=>(j?.tabs??[]).map(re=>({id:re.id,terminalSessionId:re.terminalSessionId,label:re.label})),[j?.tabs]),O=P?.isConnecting??!1,T=P?.previewUrl??null,_=le(re=>re.activeMainTab)==="terminal",se=e??_,[$,G]=i.useState(se);i.useEffect(()=>{se&&G(!0)},[se]);const{connectionError:Ae,setConnectionError:te,isFatalError:Pe,setIsFatalError:Be,isReconnectPending:Y,setIsReconnectPending:F,terminalIdRef:K,lastViewportSizeRef:J,directoryRef:Z,activeTabIdRef:pe,resetTerminalPreviewScan:Se,startStream:xe}=rm({terminal:r,effectiveDirectory:k,activeTabId:E,terminalSessionId:L,terminalLifecycle:z,hasOpenedTerminalViewport:$,terminalHydrated:y,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:v,hasActiveContext:N,tabs:Q,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ce.current?.focus()}}),{activeModifier:ne,terminalControllerRef:ce,focusTerminalWhenWindowActive:q,handleViewportInput:fe,handleModifierToggle:_e,handleMobileKeyPress:W}=om({terminal:r,terminalIdRef:K,isReconnectPending:Y,setConnectionError:te,showQuickKeys:I,isTerminalVisible:se,lastViewportSizeRef:J,terminalSessionId:L,useTouchTerminalInput:h}),{isRestarting:X,handleRestart:ie,handleHardRestart:ge,handleCreateTab:be,handleSelectTab:Te,handleCloseTab:je}=im({terminal:r,effectiveDirectory:k,activeTabId:E,enableTabs:v,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:J,directoryRef:Z,activeTabIdRef:pe,terminalIdRef:K,resetTerminalPreviewScan:Se,startStream:xe,setConnectionError:te,setIsFatalError:Be,setIsReconnectPending:F});i.useEffect(()=>{if(!se||h)return;if(typeof window>"u"){q();return}const re=window.requestAnimationFrame(()=>{q()});return()=>{window.cancelAnimationFrame(re)}},[E,q,se,h]);const ee=i.useMemo(()=>{const re=Xs[ir].stack;if(typeof window>"u")return(Xs[c]??Xs[ir]).stack;const De=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return De&&De.trim().length>0?De.trim():(Xs[c]??Xs[ir]).stack??re},[c]),me=i.useMemo(()=>Rp(a),[a]),de=`${k??"no-dir"}::${E??"no-tab"}`;if(i.useEffect(()=>{if(!se||h)return;const re=ce.current;if(!re)return;const Fe=()=>{re.fit()};if(typeof window<"u"){const De=window.requestAnimationFrame(()=>{Fe(),q()}),ot=[220,400].map(it=>window.setTimeout(Fe,it));return()=>{window.cancelAnimationFrame(De),ot.forEach(it=>window.clearTimeout(it))}}Fe()},[q,se,h,ce,de,L]),i.useEffect(()=>{if(!se||!h)return;let re=null;const Fe=()=>{re!==null&&window.cancelAnimationFrame(re),re=window.requestAnimationFrame(()=>{re=null,ce.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Fe),()=>{window.removeEventListener("oc:keyboard-settled",Fe),re!==null&&window.cancelAnimationFrame(re)}},[se,ce,de,h]),!N)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(!k)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:ie,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Ce=!L||O||X||Y,We=$,He=j?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx($p,{items:B,activeId:E,onSelect:Te,onClose:je,onCreate:be})}),t.jsx(Me,{type:"button",size:"xs",variant:"ghost",className:U("shrink-0",g?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:be,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(Me,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ie()},disabled:X,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(R,{name:"restart",className:"h-4 w-4"})}),T?t.jsxs(Me,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{k&&C(k,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,ye=t.jsx(Gp,{isTouchTerminal:g,activeModifier:ne,disabled:Ce,onKeyPress:W,onModifierToggle:_e});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:U("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:[He?n?Zl.createPortal(t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:He}),n):t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[He,s?t.jsx(Me,{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&&v&&j?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:ye}):null,!g&&I&&!j?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:ye}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:me.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:We&&k&&j?j.tabs.map(re=>{const Fe=re.id===E;return t.jsx(zp,{directory:k,tabId:re.id,sessionId:re.terminalSessionId,sessionKey:`${k}::${re.id}`,isActive:Fe,isTerminalVisible:se,terminal:r,theme:me,fontFamily:ee,fontSize:u,enableTouchScroll:h,lastViewportSizeRef:J,onInput:fe,controllerRef:ce},re.id)}):null}),!Y&&Ae&&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:Ae}),Pe&&g&&t.jsx(Me,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ge,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:ye})}):null]})},am=48,lm=96,xt=(e,...s)=>{try{e?.(...s)}catch{}},wr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Tg=(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 u=!1,d=!1,f=!1,p=null,b=!1,m=0,g=0,h=0,v=0;const x=()=>{u=!1,d=!1,f=!1,p=null},I=()=>{const C=n.current,E=p,P=b;d&&E&&(xt(E==="left"?C.onLeftProgress:C.onRightProgress,P?1:0),xt(C.onDragEnd,E,P)),x()},w=()=>{I(),d||x()},A=C=>{const E=n.current;if(E.enabled===!1){d&&p?I():x();return}if(C.touches.length!==1){d&&p?I():x();return}const P=C.touches[0],B=o.getBoundingClientRect(),L=o.clientWidth,z=!!E.leftOpen,Q=!!E.rightOpen,O=T=>wp(T,o);if(z||Q){if(O(C.target)){x();return}if(z&&Q){const T=P.clientX<=B.left+c;P.clientX>=B.right-c?(p="right",b=!0):T?(p="left",b=!0):(p=z?"left":"right",b=!0)}else z?(p="left",b=!0):(p="right",b=!0);v=wr(p==="left"?E.leftWidth:E.rightWidth,L),v<10&&(v=L||window.innerWidth||320),v<10&&(v=320),u=!0}else{if(O(C.target)){x();return}p=null,b=!1,v=0,u=!0}m=P.clientX,g=P.clientY,h=Date.now(),d=!1,f=!1},N=C=>{if(!u)return;if(C.touches.length!==1){w();return}const E=C.touches[0],P=E.clientX-m,B=E.clientY-g;if(!f){if(Math.abs(P)<ii&&Math.abs(B)<ii)return;if(Math.abs(B)>Math.abs(P)*en){x();return}if(!p){const Q=n.current;p=P>0?"left":"right",v=wr(p==="left"?Q.leftWidth:Q.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(p==="left"){if(!b&&P<=0){x();return}if(b&&P>=0){x();return}}else{if(!b&&P>=0){x();return}if(b&&P<=0){x();return}}f=!0,d=!0,xt(n.current.onDragStart,p)}if(!d)return;C.cancelable&&C.preventDefault();const L=n.current,z=ai(p,b,P,v);xt(p==="left"?L.onLeftProgress:L.onRightProgress,z)},k=(C,E)=>{if(!u){x();return}const P=C-m,B=E-g;if(!p&&!b&&Math.abs(P)>=Fn&&Math.abs(B)<=Math.abs(P)*en){const M=n.current;p=P>0?"left":"right",v=wr(p==="left"?M.leftWidth:M.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(!p){x();return}const L=Math.max(1,Date.now()-h),z=n.current;if(!d){const M=Math.abs(P),_=Math.abs(B);M>=Fn&&_<=M*en?p==="left"&&!b&&P>0?(xt(z.onLeftProgress,1),xt(z.onLeftOpen)):p==="right"&&!b&&P<0?(xt(z.onRightProgress,1),xt(z.onRightOpen)):xt(p==="left"?z.onLeftProgress:z.onRightProgress,b?1:0):xt(p==="left"?z.onLeftProgress:z.onRightProgress,b?1:0);const se=p;x(),xt(z.onDragEnd,se);return}const Q=ai(p,b,P,v),O=xp({side:p,isOpenAtStart:b,dx:P,dt:L,progress:Q}),T=p;xt(T==="left"?O?z.onLeftOpen:z.onLeftClose:O?z.onRightOpen:z.onRightClose),x(),xt(z.onDragEnd,T,O)},j=C=>{const E=C.changedTouches[0];if(!E){x();return}const P=E.clientX-m,B=E.clientY-g;u&&(d||Math.abs(P)>=Fn&&Math.abs(B)<=Math.abs(P)*en)&&C.cancelable&&C.preventDefault(),k(E.clientX,E.clientY)},y=()=>{w()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",N,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",y,{passive:!0}),()=>{try{d&&p&&I()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",N),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",y)}},[e,r])};function Fg({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 hi({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})=>Yn(s,n)?null:e,vr=()=>ms.filter(e=>Mr.has(e.id)).map(e=>({...Oi(e)})),um=()=>{if(typeof window>"u")return Pr;const e=window.localStorage.getItem("openInAppId");return e&&Dr(e)?e:Pr};let Sr=!1,Ds=!1,is=!1,as=0,cn=null;const pi=()=>{cn&&(clearTimeout(cn),cn=null)},fs=Gs()((e,s)=>({selectedAppId:um(),availableApps:vr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Sr||typeof window>"u")return;Sr=!0;const n=(u,d=!0)=>{if(!Array.isArray(u)||u.length===0){e({availableApps:vr(),hasLoadedApps:d});return}const f=new Set(u.map(g=>g.name)),p=new Map(u.map(g=>[g.name,g.iconDataUrl??void 0])),m=ms.filter(g=>f.has(g.appName)||Mr.has(g.id)).map(g=>({...Oi(g),iconDataUrl:p.get(g.appName)}));e({availableApps:m,hasLoadedApps:!0})},r=async u=>{if(!Os()||!Bn()||Ds||s().hasLoadedApps&&!u)return;const f=ms.map(p=>p.appName);pi(),Ds=!0,is=!1,e({isScanning:!0});try{const{apps:p,success:b,hasCache:m,isCacheStale:g}=await Fo(f,u),h=b&&!m&&p.length===0&&as<3;if(e({isCacheStale:m?g:!1}),n(p,b?!h:!1),b){if(h){const x=[800,1600,3200][as]??3200;as+=1,is=!0,cn=setTimeout(()=>{r()},x);return}as=0,is=!1;return}if(as<3){const x=[1e3,3e3,7e3][as]??7e3;as+=1,is=!0,cn=setTimeout(()=>{r()},x)}}finally{Ds=!1,is||e({isScanning:!1})}};r();const o=u=>{const d=u.detail,f=d&&typeof d.openInAppId=="string"&&d.openInAppId.length>0&&Dr(d.openInAppId)?d.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=u=>{const d=u.detail;Array.isArray(d)&&(as=3,is=!1,e({isScanning:!1,isCacheStale:!1}),n(d))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Sr||s().initialize(),!Os()||!Bn()||Ds||s().hasLoadedApps&&!n)return;const o=ms.map(a=>a.appName);pi(),n&&e({hasLoadedApps:!1}),Ds=!0,is=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await Fo(o,n),u=new Set(a.map(b=>b.name)),d=new Map(a.map(b=>[b.name,b.iconDataUrl??void 0])),p=ms.filter(b=>u.has(b.appName)||Mr.has(b.id)).map(b=>({...b,iconDataUrl:d.get(b.appName)}));e({availableApps:p.length>0?p:vr(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Ds=!1,is||e({isScanning:!1})}},selectApp:async n=>{Dr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Vr({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",jr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?fm:e.id==="terminal"?hm:void 0}),mi=({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:U("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=fs(g=>g.selectedAppId),r=fs(g=>g.availableApps),o=fs(g=>g.isCacheStale),a=fs(g=>g.isScanning),l=fs(g=>g.initialize),c=fs(g=>g.loadInstalledApps),u=fs(g=>g.selectApp);i.useEffect(()=>{l()},[l]);const d=Os()&&Bn(),f=i.useMemo(()=>{const g=r.find(h=>h.id===n)??r.find(h=>h.id===Pr)??r[0]??ms[0];return jr(g||ms[0])},[r,n]);if(!d||!e||r.length===0)return null;const p=async g=>{await dd(e,g.id,g.appName)||await Ti(e,g.appName)},b=async g=>{await u(g.id),await p(g)},m=async()=>{(await ws(e)).ok&&ae.success("Path copied to clipboard")};return t.jsxs("div",{className:U("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:()=>{p(f)},className:U("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(mi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Pt,{children:[t.jsx(Tt,{asChild:!0,children:t.jsx("button",{type:"button",className:U("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(Ft,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m()},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(vs,{}),r.map(g=>{const h=jr(g);return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{b(g)},children:[t.jsx(mi,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:h.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(rt,{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,St="__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},wm=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}},vm=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,u=c.hostname.toLowerCase(),d=u==="localhost"||u==="127.0.0.1"||u==="0.0.0.0"||u==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,b=f==="/"||f==="",m=!!(c.search||c.hash);let g=0;return d&&(g+=50),b&&(g+=30),g-=Math.min(p*5,20),m&&(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 Hn(s,e);return typeof n=="string"&&n.trim().length>0}async function Am(){try{const e=await Ot("/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 Hn(`${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 Hn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Hn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Ot(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Zt()?.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 Ot(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Em(e){try{const s=await Hn(`${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 Dm=(e,s,n)=>new Promise(r=>{let o=!1,a=null,l=null;const c=u=>{o||(o=!0,l&&clearTimeout(l),a?.close(),r(u))};a=e.connect(s,{onEvent:u=>{(u.type==="exit"||u.type==="snapshot"&&u.status==="exited")&&c(!0)},onError:(u,d)=>{d&&c(!0)}}),o?a.close():l=setTimeout(()=>c(!1),n)});function Mm({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=Ei(),{terminal:o}=$s(),{isMobile:a}=zs(),l=le(W=>W.terminalShell),c=le(W=>W.terminalLoginShells.includes(W.terminalShell)),u=le(W=>W.setSettingsPage),d=le(W=>W.setSettingsDialogOpen),f=le(W=>W.setSettingsProjectsSelectedId),p=le(W=>W.openContextPreview),b=he(W=>W.ensureDirectory),m=he(W=>W.setTabLabel),g=he(W=>W.setTabIconKey),h=he(W=>W.setActiveTab),v=he(W=>W.setConnecting),x=he(W=>W.setTabSessionId),I=he(W=>W.setTabPreviewUrl),w=he(W=>W.projectActionRuns),A=he(W=>W.setProjectActionRun),N=he(W=>W.updateProjectActionRunStatus),k=he(W=>W.removeProjectActionRun),[j,y]=i.useState([]),[C,E]=i.useState(null),[P,B]=i.useState(!1),L=i.useRef({}),z=i.useRef({}),Q=i.useRef({}),O=i.useRef({}),T=i.useRef(new Set),M=i.useRef(0),_=e?.id??null,se=e?.path??"",$=i.useMemo(()=>_?{id:_,path:se}:null,[_,se]),G=i.useCallback(async W=>{await wi(W)},[]),Ae=i.useCallback(async()=>{if(!$)return;const W=M.current+1;M.current=W,B(!0);try{const X=await kr($);if(M.current!==W)return;const ie=X.actions;y(ie),E(ge=>ge===St||ge&&ie.some(be=>be.id===ge)?ge:null)}catch{if(M.current!==W)return}finally{M.current===W&&B(!1)}},[$]),te=i.useMemo(()=>pa(s||$?.path||""),[s,$?.path]),Pe=i.useMemo(()=>C?j.find(W=>W.id===C)??null:null,[j,C]),Be=i.useMemo(()=>({id:St,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Y=!a,F=i.useMemo(()=>Y?[Be,...j]:j,[j,Be,Y]);i.useEffect(()=>{Ae()},[Ae]),i.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const ie=X.detail;_&&(ie?.projectId&&ie.projectId!==_||Ae())};return window.addEventListener(zr,W),()=>{window.removeEventListener(zr,W)}},[Ae,_]),i.useEffect(()=>{C&&(C===St&&Y||j.some(W=>W.id===C)||E(null))},[j,Y,C]),i.useEffect(()=>{const W=()=>{const X=he.getState(),ie=X.sessions,ge=X.projectActionRuns;for(const[be,Te]of Object.entries(ge)){const ee=ie.get(Te.directory)?.tabs.find(De=>De.id===Te.tabId);if(!ee||ee.terminalSessionId!==Te.sessionId){k(be);continue}const me=z.current[be]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};z.current[be]=me;const de=F.find(De=>De.id===Te.actionId),Ce=X.getBuffer(Te.directory,Te.tabId).chunks;if(!de||Ce.length===0)continue;const We=Ce.filter(De=>me.lastSeenChunkId===null||De.id>me.lastSeenChunkId);if(We.length===0)continue;const He=We.map(De=>De.data).join(""),ye=`${me.tail}${He}`,re=!me.openedUrl&&de.autoOpenUrl===!0?vm(ye):null,Fe=We[We.length-1]?.id??me.lastSeenChunkId;if(me.lastSeenChunkId=Fe,me.tail=ye.slice(-512),re)if(me.openedUrl=!0,me.openInPreview){const De=ge[be];De&&(I(De.directory,De.tabId,re,{locked:!1,autoOpened:!1}),De.status==="waiting-for-preview"&&N(be,"running"),window.clearTimeout(O.current[be]),delete O.current[be],p(De.directory,re))}else G(re),ae.success("Opened URL from action output");z.current[be]=me}for(const be of Object.keys(z.current))ge[be]||(delete z.current[be],window.clearTimeout(O.current[be]),delete O.current[be])};return W(),he.subscribe((X,ie)=>{(X.sessions!==ie.sessions||X.buffers!==ie.buffers)&&W()})},[F,p,G,w,k,I,N]);const K=i.useCallback(async(W,X={})=>{if(!te)throw new Error("No active directory");const ie=es(te,W.id);b(te);const ge=he.getState(),be=ge.getDirectoryState(te);let Te=L.current[ie]||null;const je=Te?!!be?.tabs.some(de=>de.id===Te):!1;(!Te||!je)&&(Te=ge.createTab(te),L.current[ie]=Te),m(te,Te,`Action: ${W.name}`),g(te,Te,W.icon||"play"),h(te,Te),X.revealTerminal!==!1&&le.getState().openContextPanelTab(te,{mode:"terminal"});const me=he.getState().getDirectoryState(te)?.tabs.find(de=>de.id===Te);return{key:ie,tabId:Te,sessionId:me?.terminalSessionId??null}},[b,te,h,g,m]),J=i.useCallback(async W=>{if(!n&&a)return;if(!te){ae.error("No active directory for action");return}const X=es(te,W.id),ie=w[X];if(!(ie&&ie.status==="running")&&!T.current.has(X)){T.current.add(X);try{const ge=W.id===St?await(async()=>{const[ye,re]=await Promise.all([kr({id:$?.id??"",path:te}),Em(te)]),Fe=await Cm(te,ye.actions,re);if(!Fe)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:St,name:"Auto-discover",command:Fe.command,icon:"scan-2",autoOpenUrl:!0,openUrl:Fe.previewUrlHint||""}})():W,be=ge.autoOpenUrl===!0&&(ge.openUrl||"").trim().length>0,Te=!be&&W.id!==St,{key:je,tabId:ee,sessionId:me}=await K(ge,{revealTerminal:Te});let de=me;if(!de){v(te,ee,!0);try{de=(await o.createSession({cwd:te,sessionId:ee,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(te,ee,de)}finally{v(te,ee,!1)}}if(!de)throw new Error("Failed to create terminal session");Q.current[je]?.(),v(te,ee,!0);const Ce=o.connect(de,{onEvent:ye=>{ye.type==="snapshot"&&(he.getState().replaceBuffer(te,ee,ye.data??"",ye.sequence??0),he.getState().setConnecting(te,ee,!1)),ye.type==="data"&&typeof ye.data=="string"&&ye.data.length>0&&he.getState().appendToBuffer(te,ee,ye.data,ye.sequence,ye.replayData),ye.type==="exit"&&(he.getState().setTabLifecycle(te,ee,"exited"),he.getState().setConnecting(te,ee,!1),he.getState().removeProjectActionRun(je),delete z.current[je],Q.current[je]?.(),delete Q.current[je],window.clearTimeout(O.current[je]),delete O.current[je])},onError:(ye,re)=>{he.getState().setConnecting(te,ee,!1),re&&(he.getState().setTabLifecycle(te,ee,"exited"),he.getState().setTabSessionId(te,ee,null),he.getState().removeProjectActionRun(je))}});Q.current[je]=Ce.close;const We=ge.autoOpenUrl?wm(ge.openUrl):null;A({key:je,directory:te,actionId:ge.id,tabId:ee,sessionId:de,status:ge.id===St&&!We?"waiting-for-preview":"running"}),window.clearTimeout(O.current[je]),delete O.current[je],ge.id===St&&!We&&(O.current[je]=window.setTimeout(()=>{const ye=he.getState(),re=ye.projectActionRuns[je];ye.updateProjectActionRunStatus(je,"running"),re&&(ye.setActiveTab(re.directory,re.tabId),le.getState().openContextPanelTab(re.directory,{mode:"terminal"})),delete O.current[je]},xm)),z.current[je]={lastSeenChunkId:null,openedUrl:!!We||be,tail:"",openInPreview:ge.id===St};const He=ym(ge.command.trim().replace(/\r\n|\r/g,`
|
|
53
|
-
`));await o.sendInput(de,`${He}\r`),We?(I(te,ee,We,{locked:!0,autoOpened:!0}),p(te,We),ae.success("Opened action URL")):be?(I(te,ee,null,{locked:!0}),ae.error("Invalid custom URL format")):I(te,ee,null,{locked:!1,autoOpened:!1})}catch(ge){k(X),delete z.current[X],Q.current[X]?.(),delete Q.current[X],window.clearTimeout(O.current[X]),delete O.current[X],ae.error(ge instanceof Error?ge.message:"Failed to run action")}finally{T.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,K,n,a,te,c,l,p,w,k,v,A,I,x,$?.id,o]),Z=i.useCallback(async W=>{const X=es(te,W.id),ie=w[X];if(!ie)return;N(X,"stopping");const ge=Dm(o,ie.sessionId,1e3);try{await o.sendInput(ie.sessionId,"")}catch{}const be=await ge;if(he.getState().getDirectoryState(ie.directory)?.tabs.find(ee=>ee.id===ie.tabId)?.terminalSessionId===ie.sessionId&&!be){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ie.sessionId})}catch{}else try{await o.close(ie.sessionId)}catch{}x(ie.directory,ie.tabId,null)}k(X),delete z.current[X],Q.current[X]?.(),delete Q.current[X],window.clearTimeout(O.current[X]),delete O.current[X]},[te,w,k,x,o,N]),pe=i.useCallback(()=>{const W=Pe??F[0];if(!W)return;const X=es(te,W.id),ie=w[X];if(ie?.status!=="stopping"){if(ie){Z(W);return}J(W)}},[F,te,J,w,Pe,Z]),Se=i.useCallback((W,X=!1)=>{if(E(W.id),!X){J(W);return}const ie=es(te,W.id),ge=w[ie];if(ge?.status!=="stopping"){if(ge){Z(W);return}J(W)}},[te,J,w,Z]),xe=i.useCallback(()=>{$?.id&&(f($.id),u("projects"),d(!0))},[d,u,f,$?.id]),ne=Pe??F[0]??null,ce=ne?w[es(te,ne.id)]:null,q=he(W=>ce?W.sessions.get(ce.directory)?.tabs.find(X=>X.id===ce.tabId)?.previewUrl??null:null),fe=!!((n||!a)&&$&&te),_e=Pe??F[0]??null;return{shouldRender:fe,isLoading:P,normalizedDirectory:te,resolvedSelected:_e,displayActions:F,projectActionRuns:w,selectedRunPreviewUrl:q,handlePrimaryClick:pe,handleSelectAction:Se,openProjectActionsSettings:xe,openContextPreview:p}}const gi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:u,displayActions:d,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:b,handleSelectAction:m,openProjectActionsSettings:g,openContextPreview:h}=Mm({projectRef:e,directory:s,allowMobile:o});if(!a||!u)return null;const v=u.icon||"play",x=u.id===St?"scan-2":ln[v]||"play",I=es(c,u.id),w=f[I],A=w?.status==="stopping",N=w?.status==="waiting-for-preview",k=!!(w&&p),j=()=>{!w||!p||h(w.directory,p)},y=u.id===St;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||A,className:U("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":w?`Stop ${u.name}`:`Run ${u.name}`,children:A||N?t.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?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(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?t.jsxs(ze,{children:[t.jsx($e,{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:j,children:t.jsx(R,{name:"global",className:"h-4 w-4"})})}),t.jsx(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Pt,{children:[t.jsx(Tt,{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(Ft,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{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(vs,{}),d.map(C=>{const E=C.icon||"play",P=C.id===St?"scan-2":ln[E]||"play",B=es(c,C.id),L=f[B],z=!!L,Q=L?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m(C,!0)},children:[t.jsx(R,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:C.name}),Q||L?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):z?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},C.id)})]})]})]}):t.jsxs("div",{className:U("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(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,disabled:l||A,className:U("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":w?`Stop ${u.name}`:`Run ${u.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||N?t.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?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(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j,className:U(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(Ge,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Pt,{children:[t.jsx(Tt,{asChild:!0,children:t.jsx("button",{type:"button",className:U(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(Ft,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(rt,{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(vs,{}),d.map(C=>{const E=C.icon||"play",P=C.id===St?"scan-2":ln[E]||"play",B=es(c,C.id),L=f[B],z=!!L,Q=L?.status==="stopping";return t.jsxs(rt,{className:"flex items-center gap-2",onClick:()=>{m(C,!0)},children:[t.jsx(R,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:C.name}),Q||L?.status==="waiting-for-preview"?t.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):z?t.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},C.id)})]})]})]})},Pm=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(Pt,{children:[t.jsx(Tt,{asChild:!0,children:t.jsx("button",{type:"button",className:U(gn,"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(Ft,{align:"end",className:"w-64",children:[t.jsx(Dc,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(vs,{}),r.map(u=>{const d=u.user,f=!!u.current,p=u.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(rt,{className:"gap-2",disabled:l,onSelect:()=>{f||c(u.id)},children:[d?.avatarUrl?t.jsx("img",{src:d.avatarUrl,alt:d.login?`${d.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:d?.name?.trim()||d?.login||"GitHub"}),d?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:d.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:p})]}):null]}),f?t.jsx(R,{name:"check",className:"h-4 w-4 text-primary"}):null]},u.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"})})}),Tm=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:u,remoteUpdateInfo:d,remoteUpdateChecking:f,remoteUpdateError:p,onOpenRemoteUpdate:b}){return t.jsxs(Pt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx(Tt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:U(gn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(R,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),t.jsx(Ft,{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:d?.available?`Version ${d.version||""} is available for this instance.`:f?"Looking for updates...":p||"This instance is up to date."})]}),d?.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:b,children:"Update"}):null]})}),t.jsx(Mc,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Fm=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Ht,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Yt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(ds,{children:[t.jsx(ss,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(us,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Ss,{children:[t.jsx(Me,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Me,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Om=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},Zs=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Lm=i.lazy(()=>ls(()=>import("./SessionSwitcherDropdown-CedOB-xC.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}))),Og=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Mt("ui.header.render");const l=le(D=>D.setSessionSwitcherOpen),c=le(D=>D.toggleSidebar),u=le(D=>D.isSidebarOpen),d=le(D=>D.activeMainTab),f=le(D=>D.setActiveMainTab),p=le(D=>D.shortcutOverrides);le(D=>D.timeFormatPreference),$s();const b=Ee(D=>!!D.newSessionDraft?.open),m=Ee(D=>D.currentSessionId),g=Ri(m??""),h=Pc(m),v=i.useMemo(()=>{if(!h)return null;const D=h;return{title:h.title??null,directory:D.directory??null,created:h.time?.created??null,slug:D.slug??null,shareUrl:h.share?.url??null,parentId:h.parentID??null}},[h]),x=pt(Tr(D=>{if(!D.activeProjectId)return null;const oe=D.projects.find(ve=>ve.id===D.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),I=Ls(D=>D.homeDirectory),w=i.useMemo(()=>{if(!x)return null;const D=x.label?.trim();if(D)return D;const oe=x.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[x]),{isMobile:A}=zs(),{enabled:N}=qr(),k=!!(N&&a&&o!==void 0),j=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[y,C]=i.useState(!1),E=null,P=i.useRef(null),[B,L]=i.useState(()=>typeof window>"u"?!1:Os()),z=i.useMemo(()=>Fi(),[]),Q=Tc(),[O,T]=i.useState(!1),M=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),_=Di(),se=i.useMemo(()=>{if(typeof window>"u")return null;const D=window.__PICHAMBER_MACOS_MAJOR__;if(typeof D=="number"&&Number.isFinite(D)&&D>0)return D;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const ve=Number.parseInt(oe[1],10),Ue=Number.parseInt(oe[2],10);return Number.isNaN(ve)?null:ve===10?Ue:ve},[]);Ie.useEffect(()=>{typeof window>"u"||L(Os())},[]);const $=le(D=>D.isSessionSwitcherOpen),G=null,Ae=null,te=[],[Pe,Be]=i.useState(!1),[Y,F]=i.useState(!1),[K,J]=i.useState("Local"),[Z,pe]=i.useState(!0),[Se,xe]=i.useState(!1),[ne,ce]=i.useState(null),[q,fe]=i.useState(!1),[_e,W]=i.useState(null),X=i.useRef(0),ie=i.useMemo(()=>Om(K),[K]),ge=i.useCallback(async()=>{if(typeof window>"u"||!B)return;const D=Xe(),oe=()=>Xe()===D;try{if(Bn()){J("Local"),pe(!0);return}pe(!1);const ve=await ud();if(!oe())return;const Ue=fd(),ct=hd([pd(Ue),...ve.hosts]);if(ct.id===md){J("Local"),pe(!0);return}J(gd(ct.label.trim()||"Instance"))}catch{oe()&&(J("Local"),pe(!0))}},[B]);Ie.useEffect(()=>(ge(),bd(()=>{X.current+=1,ce(null),W(null),fe(!1),xe(!1),ge()})),[ge]);const be=i.useCallback(async()=>{const D=X.current+1;X.current=D;const oe=Xe(),ve=()=>X.current===D&&Xe()===oe;if(Z){ce(null),W(null);return}fe(!0),W(null);try{const Ue=new URLSearchParams({appType:"web",instanceMode:"remote"}),ct=await Ot(`/api/pi/update-check?${Ue.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ct.ok)throw new Error(`Server responded with ${ct.status}`);const Je=await ct.json();if(!ve())return;ce({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch(Ue){if(!ve())return;ce(null),W(Ue instanceof Error?Ue.message:"Failed to check remote instance updates")}finally{ve()&&fe(!1)}},[Z]);i.useEffect(()=>Gu(()=>{Z||be()}),[be,Z]),i.useEffect(()=>{X.current+=1,ce(null),W(null),fe(!1),xe(!1)},[Z,K]),i.useEffect(()=>{if(!B||Z)return;const D=3e3,oe=3600*1e3;let ve=!1,Ue=null;const ct=Je=>{Ue=window.setTimeout(()=>{if(ve||typeof document<"u"&&document.visibilityState!=="visible"){ct(oe);return}be().finally(()=>{ve||ct(oe)})},Je)};return ct(D),()=>{ve=!0,Ue!==null&&window.clearTimeout(Ue)}},[be,Z,K,B]);const Te=i.useCallback(()=>{if(ne?.available){xe(!0);return}be()},[be,ne?.available]),je=m?v??null:null,ee=i.useRef(null),[me,de]=i.useState(0);i.useEffect(()=>{if(!m){ee.current&&(ee.current=null,de(Ue=>Ue+1));return}if(je){ee.current={sessionId:m,session:je,expiresAt:Date.now()+2e3};return}const D=ee.current;if(!D||D.sessionId!==m)return;const oe=D.expiresAt-Date.now();if(oe<=0){ee.current=null,de(Ue=>Ue+1);return}const ve=window.setTimeout(()=>{ee.current?.sessionId===m&&(ee.current=null),de(Ue=>Ue+1)},oe);return()=>{window.clearTimeout(ve)}},[m,je]);const Ce=(()=>{if(je)return je;if(!m)return null;const D=ee.current;return D&&D.sessionId===m&&D.expiresAt>Date.now()?D.session:null})(),We=i.useMemo(()=>{const D=typeof Ce?.directory=="string"?Ce.directory:"";return Zs(D||"")},[Ce?.directory]),He=Ee(D=>D.newSessionDraft?.open?Zs(D.newSessionDraft.directoryOverride??""):""),ye=i.useMemo(()=>cm({sessionDirectory:We,draftDirectory:He,isNewSessionDraftOpen:b}),[He,b,We]),Fe=Ii(ye||null),De=i.useMemo(()=>dm({activeProjectLabel:w,openDirectory:ye,homeDirectory:I}),[w,I,ye]),ot=!!(De||Fe),it=i.useMemo(()=>m?cs(Ce):De??"PiChamber",[Ce,m,De]),Ve=Fc(),Lt=Ee(D=>D.updateSessionTitle),Nt=Ee(D=>D.archiveSessions),jt=Ee(D=>D.deleteSessions),[Bt,et]=i.useState(!1),[mt,tt]=i.useState(!1),gt=i.useRef(!1),[Ct,qt]=i.useState(""),[yt,we]=i.useState(null),Oe=i.useRef(null);i.useEffect(()=>{gt.current=!1,tt(!1),et(!1),qt(""),we(null)},[m]);const ke=i.useCallback(()=>{m&&(qt(Ce?.title?.trim()||it),et(!0))},[Ce?.title,m,it]),Le=i.useCallback(async()=>{if(!m)return;const D=Ct.trim();D&&D!==Ce?.title?.trim()&&await Lt(m,D),et(!1)},[Ce?.title,m,Ct,Lt]);i.useEffect(()=>{if(!Bt)return;const D=oe=>{const ve=oe.target;(!ve||!Oe.current?.contains(ve))&&Le()};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[Bt,Le]);const Ye=i.useCallback(()=>{m&&ws(m).then(D=>{ae[D.ok?"success":"error"](D.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ae.error("Failed to copy session ID"))},[m]),ut=i.useCallback(async()=>{if(!m||!ye){ae.error("Nothing to export");return}try{await Ve.syncSession(m)}catch{ae.error("Failed to load the complete session history");return}const D=[];if(D.length===0){ae.error("Nothing to export");return}const oe=Da(D,Ce?.title??null),ve=Ta(Ce?.title??null);await Pa(oe,ve)||Ma(oe,ve),ae.success("Session exported")},[Ce?.title,m,ye,Ve]);g?.type==="busy"||g?.type;const It=i.useCallback(async()=>{if(!m||!yt)return;const D=Oc(),oe=[m];for(let Je=0;Je<oe.length;Je+=1){const Qs=oe[Je];for(const Jt of D)Jt.parentID===Qs&&!oe.includes(Jt.id)&&oe.push(Jt.id)}const ve=yt;if(we(null),(ve==="archive"?await Nt(oe):await jt(oe)).failedIds.length>0){ae.error(ve==="archive"?"Failed to archive session":"Failed to delete session");return}ae.success(ve==="archive"?"Session archived":"Session deleted")},[Nt,m,jt,yt]),Rt=le(D=>D.isArchivePageOpen),_t=i.useMemo(()=>Rt?{title:"Archive",subtitle:null}:null,[Rt]),qe=i.useMemo(()=>Zs(ye||x?.path||""),[x?.path,ye]),st=i.useCallback(()=>{qe&&ws(qe).then(D=>{ae[D.ok?"success":"error"](D.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ae.error("Failed to copy working directory"))},[qe]),wt=i.useMemo(()=>x?{id:x.id,path:x.path}:null,[x]),Ut=i.useRef(null);i.useEffect(()=>{!wt||!qe||(Ut.current={projectRef:wt,directory:qe})},[qe,wt]);const bt=i.useMemo(()=>wt&&qe?{projectRef:wt,directory:qe}:Ut.current,[qe,wt]),Ks=i.useCallback(async D=>{},[]),zt=i.useCallback(()=>{if(typeof document>"u")return;const D=document.activeElement;if(!D)return;const oe=D.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||D.isContentEditable)&&D.blur()},[]),Cs=i.useCallback(()=>{if(A){zt(),l(!$);return}c()},[zt,A,$,l,c]),ks=i.useCallback(()=>{on("desktop_open_draft_mini_chat_window",{directory:Zs(ye||x?.path||""),projectId:x?.id??null,apiBaseUrl:Er(),clientToken:Rr()}).catch(D=>{console.warn("[header] failed to open draft mini chat window",D)})},[x?.id,x?.path,ye]),$t=i.useCallback(()=>{if(b){ks();return}m&&on("desktop_open_session_mini_chat_window",{sessionId:m,directory:Zs(ye||x?.path||""),apiBaseUrl:Er(),clientToken:Rr()}).catch(D=>{console.warn("[header] failed to open session mini chat window",D)})},[x?.path,m,ks,b,ye]),Qt=gn,at=mf,ue=i.useMemo(()=>n?"sessions":k?r&&o?o:null:r?"git":d,[d,k,n,r,o]),Ze=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&$&&l(!1)},[$,n,e,s,r,l]),ft=i.useCallback(()=>{e?.()},[e]),vt=i.useCallback(()=>{s?.()},[s]),ns=i.useMemo(()=>B&&M&&!O?"5.5rem":Q?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!B||_?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[B,O,M,Q,_]);Ie.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ns)},[ns]);const lt=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",bn=u?"0px":B&&_?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":N?"2.75rem":"2.5rem";Ie.useEffect(()=>{if(!B||!M){T(!1);return}let D=!1;const oe=async()=>{try{const Ue=await on("desktop_is_window_fullscreen");D||T(Ue===!0)}catch{D||T(!1)}},ve=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",ve),()=>{D=!0,window.removeEventListener("pichamber:window-resized",ve)}},[B,M]);const Ws=i.useMemo(()=>!B||!M||se===null?"":se>=26?"h-12":se<=15?"h-14":"",[B,M,se]),Qn=i.useMemo(()=>{if(!(B&&!_))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,_]),Vt=i.useCallback(()=>{if(typeof document>"u")return;const D=P.current?.getBoundingClientRect().height;D&&document.documentElement.style.setProperty("--oc-header-height",`${D}px`)},[]);Ie.useEffect(()=>{if(typeof window>"u")return;Vt();const D=P.current;if(!D||typeof ResizeObserver>"u")return()=>{};let oe=0;const ve=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,Vt()}))},Ue=new ResizeObserver(ve);return Ue.observe(D),window.addEventListener("resize",ve),window.addEventListener("orientationchange",ve),()=>{oe&&cancelAnimationFrame(oe),Ue.disconnect(),window.removeEventListener("resize",ve),window.removeEventListener("orientationchange",ve)}},[Vt]),Ie.useEffect(()=>{Vt()},[Vt,A,Ws]);const Vn=i.useCallback(async D=>{const oe=D.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||D.button===0&&B&&await Lc()},[B]),rs=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]),xn=i.useCallback(D=>Xr(Ln(D,p)),[p]);Ie.useEffect(()=>{!A&&d!=="chat"&&d!=="terminal"&&d!=="diagram"&&f("chat")},[d,A,f]),Ie.useEffect(()=>{const D=oe=>{if(xd(oe)&&!oe.shiftKey&&!oe.altKey){const ve=parseInt(oe.key,10);ve>=1&&ve<=rs.length&&(oe.preventDefault(),A&&(zt(),Ze()),f(rs[ve-1].id))}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[zt,Ze,A,f,rs]),Ie.useEffect(()=>{const D=oe=>{const ve=Ln("toggle_services_menu",p);if(yd(oe,ve)){oe.preventDefault(),Y?F(!1):(F(!0),ge());return}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[p,Y,ge]);const Hs=D=>{const oe=d===D.id,ve=D.icon==="diff",Ue=ve?null:D.icon,ct=D.id==="chat",Je=Jt=>ve?t.jsx(hi,{size:Jt}):Ue?t.jsx(R,{name:Ue,className:`h-${Jt/4} w-${Jt/4}`}):null,Qs=t.jsxs("button",{type:"button",onClick:()=>f(D.id),className:U("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",oe?"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",ct&&!A&&"min-w-[100px] justify-center"),"aria-label":D.label,"aria-selected":oe,role:"tab",children:[A?Je(20):t.jsxs(t.Fragment,{children:[Je(16),t.jsx("span",{className:"header-tab-label",children:D.label})]}),D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:D.badge})]});return t.jsx(i.Fragment,{children:Qs},D.id)},As=t.jsxs(t.Fragment,{children:[t.jsx(pm,{directory:qe,className:"mr-1"}),B?t.jsx(Tm,{isDesktopApp:B,currentInstanceLabel:K,compactCurrentInstanceLabel:ie,currentInstanceIsLocal:Z,isDesktopServicesOpen:Y,setIsDesktopServicesOpen:F,refreshCurrentInstanceLabel:ge,shortcutLabel:xn,remoteUpdateInfo:ne,remoteUpdateChecking:q,remoteUpdateError:_e,onOpenRemoteUpdate:Te}):null,t.jsx(Pm,{isMobile:A,githubAuthStatus:E,githubAccounts:te,githubAvatarUrl:G,githubLogin:Ae,isSwitchingGitHubAccount:Pe,handleGitHubAccountSwitch:Ks})]}),Jn=z&&(b||!!m),Xn=()=>t.jsxs("div",{onMouseDown:Vn,className:U("app-region-drag relative flex h-12 select-none items-center pr-3",Ws),style:Qn,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:lt}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:bn}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[_t?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:_t.title}),_t.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:_t.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:[u?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Qt,"aria-label":"Open session switcher",children:t.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Lm,{align:"start",children:t.jsx("button",{type:"button",className:Qt,"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:[Bt?t.jsxs("form",{ref:Oe,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:D=>{D.preventDefault(),Le()},children:[t.jsx("input",{value:Ct,onChange:D=>qt(D.target.value),autoFocus:!0,onKeyDown:D=>{D.stopPropagation(),D.key==="Escape"&&et(!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:()=>et(!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":it}),ot?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:[De?t.jsx("span",{className:"truncate",children:De}):null,Fe?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:Fe})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!b&&!Bt?t.jsxs(Pt,{open:mt,onOpenChange:tt,onOpenChangeComplete:D=>{!D&>.current&&(gt.current=!1,ke())},children:[t.jsx(Tt,{asChild:!0,children:t.jsx(Me,{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(Ft,{align:"end",className:"min-w-[190px]",children:[t.jsxs(rt,{onClick:()=>{gt.current=!0},children:[t.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(rt,{onClick:Ye,children:[t.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(rt,{onClick:st,disabled:!qe,children:[t.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>{ut()},children:[t.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(vs,{}),t.jsxs(rt,{onClick:()=>we("archive"),children:[t.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(rt,{className:"text-destructive focus:text-destructive",onClick:()=>we("delete"),children:[t.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),rs.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:rs.map(D=>Hs(D))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(xa,{}),bt?t.jsx(gi,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,t.jsx(gf,{visible:Jn,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:$t,className:U(Qt,"mr-1"),Icon:"picture-in-picture-2"}),As,t.jsx(Bc,{visible:_})]})]})]}),Ys=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:lt}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:bn}})]}),!N&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:ft,className:U(at,ue==="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"})}):$?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:Cs,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&&$&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!$||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!k&&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:rs.map(D=>{const oe=d===D.id,ve=D.icon==="diff",Ue=ve?null:D.icon;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{A&&(zt(),Ze()),f(D.id)},"aria-label":D.label,"aria-selected":oe,role:"tab",className:U(at,"relative rounded-lg",ue===D.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ve?t.jsx(hi,{className:"h-5 w-5"}):Ue?t.jsx(R,{name:Ue,className:"h-5 w-5"}):null,D.badge!==void 0&&D.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:D.badge}),D.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(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[k&&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:j.map(D=>{const oe=r&&o===D.id;return t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{A&&(zt(),Ze()),C(!1),a?.(D.id)},"aria-label":D.label,"aria-selected":oe,role:"tab",className:U(at,"relative rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(R,{name:D.icon,className:"h-5 w-5"})})}),t.jsx(Ge,{children:t.jsx("p",{children:D.label})})]},D.id)})}),t.jsx(pf,{open:y,onOpenChange:C,currentSessionId:m,effectiveDirectory:ye||null,isNewSessionDraftOpen:b})]}),bt&&t.jsx(gi,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!k?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:vt,className:U(at,"relative",ue==="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(Ge,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),qs=U("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:qs,style:{"--padding-scale":"1"},children:A?Ys():Xn()}),t.jsx(Fm,{action:yt,onClose:()=>we(null),sessionTitle:it,onConfirm:()=>{It()}}),t.jsx(ca,{open:Se,onOpenChange:xe,info:ne,downloading:!1,downloaded:!1,progress:null,error:_e,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},bi="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",Bm="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",Lg=()=>{const e=le(m=>m.isSidebarOpen),s=le(m=>m.toggleSidebar),n=le(m=>m.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=Xr(Ln("toggle_sidebar",n)),l=Di(),{enabled:c}=qr(),u=!e,d=l,f=u||d,p=d,b=i.useCallback(()=>{on("desktop_show_app_menu").catch(m=>{console.warn("[titlebar] failed to open app menu",m)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const m=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},g=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const h=o.current,v=r.current;if(!h||!v){m(0),g(0);return}const x=()=>{const w=Math.max(h.getBoundingClientRect().width,h.scrollWidth);m(w),g(v.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const I=new ResizeObserver(x);return I.observe(h),I.observe(v),()=>{I.disconnect()}},[p]),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:[d?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:U(bi,"shrink-0"),children:t.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(ze,{children:[t.jsx($e,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:U(c?Bm:bi,"shrink-0"),children:t.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Ge,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},xi=200,_m="cubic-bezier(0.22, 1, 0.36, 1)",Bg=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 u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),xi);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${xi}ms ${_m}`}},_g=()=>{Li()},Ug=e=>{Ee.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),Li(),Ls.getState().resetForRuntimeSwitch(),_c.getState().resetForRuntimeSwitch(),Uc.getState().resetForRuntimeSwitch(),zc(),$c.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),pt.getState().resetForRuntimeSwitch(),Gc(),Kc(),Jd.getState().reset(),wd.getState().resetForRuntimeSwitch(),Ai.getState().resetForRuntimeSwitch(e.runtimeKey),Nr.getState().resetForRuntimeSwitch(e.runtimeKey),ys.getState().resetForRuntimeSwitch(e.runtimeKey),Xf.getState().resetForRuntimeSwitch(),ht.getState().resetForRuntimeSwitch(e.runtimeKey),vd.getState().resetForRuntimeSwitch(e.runtimeKey),Ee.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=le.getState();Or({sessionId:Ee.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0})};export{af as $,Ig as A,Fg as B,Ng as C,ii as D,xu as E,lg as F,og as G,Og as H,fs as I,au as J,hs as K,cg as L,ba as M,Uu as N,vg as O,Fu as P,ug as Q,Ag as R,Rg as S,Pg as T,xg as U,ca as V,rg as W,to as X,gg as Y,_u as Z,fa as _,pf as a,Tu as a0,zu as a1,pn as a2,da as a3,mn as a4,an as a5,Ou as a6,fg as a7,Lu as a8,wg as a9,Cg as aa,jg as ab,$u as ac,yg as ad,Sg as ae,kg as af,dg as ag,hg as ah,pg as ai,mg as aj,tf as ak,bg as al,wu as am,Bu as an,vu as ao,sg as ap,en as b,bp as c,Eg as d,Fn as e,Bg as f,Dg as g,Tg as h,wp as i,Lg as j,Ug as k,ig as l,ag as m,ng as n,tg as o,so as p,no as q,_g as r,Mg as s,ro as t,ff as u,Fs as v,ga as w,lf as x,cf as y,Ko as z};
|