@pi-chamber/web 0.8.2 → 0.9.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 +22 -6
- package/bin/cli.js +16 -3
- package/bin/cli.test.js +62 -0
- package/bin/lib/DOCUMENTATION.md +6 -6
- package/bin/lib/cli-args.js +26 -7
- package/bin/lib/cli-lifecycle.js +3 -0
- package/bin/lib/cli-paths.js +6 -0
- package/bin/lib/cli-process.js +1 -0
- package/bin/lib/cli-tunnel-profiles.js +15 -10
- package/bin/lib/commands-connect-url.js +9 -1
- package/bin/lib/commands-lifecycle.js +14 -0
- package/bin/lib/commands-logs.js +24 -5
- package/bin/lib/commands-serve.js +176 -4
- package/bin/lib/commands-tunnel.js +35 -0
- package/bin/lib/commands-update.js +107 -39
- package/bin/lib/commands-update.test.js +97 -1
- package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-DoEOH0hY.js} +1 -1
- package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-y9Ystuhv.js} +1 -1
- package/dist/assets/DiffView-ScM4XoqZ.js +18 -0
- package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-CjkhMFqJ.js} +3 -3
- package/dist/assets/GitView-Bqi6H8I-.js +8 -0
- package/dist/assets/JsonTreeView-DWhlH6NK.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-CEOKZ1qH.js} +1 -1
- package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-ClnfJJ2J.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-e6JzUXD_.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-C4etG8dv.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-BVTSwRiG.js} +1 -1
- package/dist/assets/SettingsView-C0S0Sx-S.js +2 -0
- package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-Cy9tmnMg.js} +1 -1
- package/dist/assets/ToolOutputDialog-Csrc0Uk2.js +8 -0
- package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-6oH6KD44.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-DJNcTQNp.js} +4 -4
- package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-DxgVLhi9.js} +1 -1
- package/dist/assets/computeVirtualFileMetrics-B-WoeBMW.js +3 -0
- package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-DQ4U9xRH.js} +1 -1
- package/dist/assets/gitStatusPredicates-CIFSGjJs.js +134 -0
- package/dist/assets/index-D2C3q2xD.js +8 -0
- package/dist/assets/index-DNoEeZ2U.css +1 -0
- package/dist/assets/{index-CMfiVUIr.js → index-DmNPBaSo.js} +1 -1
- package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-CrvpUauF.js} +1 -1
- package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-CKvhS32g.js} +1 -1
- package/dist/assets/{main-zZrKd3hZ.js → main-BFv8slLp.js} +2 -2
- package/dist/assets/main-CjM7g4Gq.js +135 -0
- package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-DKrraAqT.js} +1 -1
- package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-hQnLS5mt.js} +2 -2
- package/dist/assets/{mobile-VU_G_SgX.js → mobile-DuXOBGs_.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-ClJBZVGy.js +2 -0
- package/dist/assets/renderMobileApp-DofX2wjB.js +11 -0
- package/dist/assets/runtimeEndpointReset-BZeYg6eN.js +54 -0
- package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C7CBxDbh.js} +1 -1
- package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-Cs0f1dKn.js} +102 -102
- package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-D1hcbBEc.js} +1 -1
- package/dist/assets/usePushVisibilityBeacon-DqHkuVS5.js +10 -0
- package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-BEoW7LlC.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-B8Ac62S_.js} +2 -2
- package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
- package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
- package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
- package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
- package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
- package/dist/assets/{web-components-C9ENH49P.js → web-components-Dy-Tz_LJ.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +3 -4
- package/server/index.js +26 -7
- package/server/lib/client-auth/pairing.js +13 -2
- package/server/lib/client-auth/remote-clients.js +13 -2
- package/server/lib/fs/DOCUMENTATION.md +3 -1
- package/server/lib/fs/routes.test.js +74 -0
- package/server/lib/git/DOCUMENTATION.md +1 -1
- package/server/lib/git/identity-storage.js +10 -1
- package/server/lib/package-manager.js +1 -1
- package/server/lib/package-manager.test.js +11 -0
- package/server/lib/pi/archive-store.js +3 -2
- package/server/lib/pi/model-config-store.js +6 -2
- package/server/lib/pi/routes.js +11 -2
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +12 -6
- package/server/lib/pi/session-daemon/daemon-process.js +48 -13
- package/server/lib/pi/session-daemon/session-daemon.js +226 -40
- package/server/lib/pi/session-daemon/session-daemon.test.js +207 -0
- package/server/lib/pi/session-daemon/session-lease.js +151 -0
- package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
- package/server/lib/pi/session-daemon/supervisor.js +244 -54
- package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
- package/server/lib/pi/session-folders-store.js +20 -2
- package/server/lib/pi/session-folders-store.test.js +17 -0
- package/server/lib/pi/settings-store.js +3 -2
- package/server/lib/pi/snippets-store.js +4 -1
- package/server/lib/pi/ui-settings-store.js +3 -2
- package/server/lib/server/cross-process-lock.js +112 -0
- package/server/lib/server/cross-process-lock.test.js +70 -0
- package/server/lib/server/server-profile.js +110 -0
- package/server/lib/server/server-profile.test.js +58 -0
- package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
- package/server/lib/server/tunnel-service.js +8 -1
- package/server/lib/stt/DOCUMENTATION.md +1 -1
- package/server/lib/stt/config-store.js +3 -2
- package/server/lib/terminal/DOCUMENTATION.md +3 -3
- package/server/lib/tunnels/DOCUMENTATION.md +38 -18
- package/server/lib/ui-auth/ui-auth.js +9 -2
- package/server/lib/ui-auth/ui-passkeys.js +9 -1
- package/dist/assets/DiffView-Gh9wjthp.js +0 -18
- package/dist/assets/GitView-BmNCkkoC.js +0 -8
- package/dist/assets/JsonTreeView-CxXRXXzk.js +0 -1
- package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
- package/dist/assets/ToolOutputDialog-C_7vJLEq.js +0 -8
- package/dist/assets/computeVirtualFileMetrics-D0mQcleY.js +0 -3
- package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
- package/dist/assets/index-CzO3ooje.css +0 -1
- package/dist/assets/index-ivrh3jfy.js +0 -8
- package/dist/assets/main-BoVfUG73.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-Bi1927c8.js +0 -2
- package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
- package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
- package/dist/assets/usePushVisibilityBeacon-zYd3ppNh.js +0 -10
- package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CMfiVUIr.js","assets/useAppFontEffects-8ZU-TTIW.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-ivrh3jfy.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-CzO3ooje.css","assets/vendor-base-ui-vkqQ2P9o.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CBaS2Ank.js","assets/vendor-dnd-kit-core-CP8ck10N.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-B-Icjoj4.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-B_0wrsbo.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-D0mQcleY.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-bQAPxqO9.js","assets/isDiffPlainText-MmBA1REG.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-Cgw2mQIO.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as Ss}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Me,j as t,R as i}from"./vendor-react-B5Z1Mdn3.js";import{cV as Ls,i as xc,cc as bc,D as jt,E as Te,F as Fe,a as kt,U as Re,I as A,G as Le,b as Ct,bM as yc,bN as wc,bO as vc,bP as Sc,bQ as nr,bR as Js,ck as Ro,bm as Je,t as se,c as ut,k as Ne,b9 as As,bg as cn,M as Ai,aQ as Gt,aR as Kt,bi as fs,bj as ss,bk as hs,bl as Is,cW as jc,be as Cs,cX as Ns,Z as Xs,cY as rr,cZ as Eo,c_ as Po,c$ as nn,aw as Ii,ao as ws,aL as Mo,af as _s,ci as kr,d0 as kc,d1 as Cc,d2 as Nc,d3 as Ac,K as Ic,d4 as Cr,d5 as Dc,L as $t,d6 as Rc,d7 as Ec,cw as Pc,cj as Mc,d8 as Tc,cS as Fc,as as Di,at as Ri,d9 as Ei,u as Nr,r as Os,bZ as Qr,bd as Lc,Y as Oc,bB as To,bA as Bc,bz as _c,bJ as Pi,ca as Ds,da as zc,g as Vr,j as Ws,Q as Mi,db as at,d as Ar,dc as Uc,dd as $c,bv as Gc,de as Hn,df as Fo,dg as Ti,bK as Fi,dh as Ir,di as Li,S as Oi,ba as Kc,dj as Hc,dk as Wc,l as Bi,bW as Yc,dl as qc,dm as Qc,m as Vc,dn as Jc,e as Xc,dp as Zc,bV as ed,s as td,f as sd,a7 as _i,dq as Dr,dr as nd,ds as rd,bL as od,cU as id,dt as ad,a3 as ld,aN as zi,c3 as cd,aB as dd,bn as zs,du as ud,dv as fd,bX as hd,dw as pd,R as Ui,ah as md,dx as gd,W as $i,dy as Gi,cC as xd,cD as bd,dz as yd,cu as wd,bU as vd,dA as Sd,dB as jd}from"./useAppFontEffects-8ZU-TTIW.js";import{g as Lo,aW as kd,aX as Oo,aY as Cd,i as Nd,h as Ad,A as Id,r as Mt,C as dn,B as Dd,c as z,aZ as Rd,b as Us,a_ as Jr,a$ as Xr,b0 as Ed,b1 as Pd,f as $s,M as Md,b2 as Td,b3 as Fd,b4 as Ld,as as Xt,p as Zt,b5 as Od,b6 as Bd,b7 as _d,y as Zr,b8 as zd,b9 as Ud,ba as $d,u as re,z as Gd,n as be,bb as Gs,D as Lt,bc as Bo,bd as Rr,w as Wn,be as Kd,aA as Hd,$ as eo,m as Ln,bf as Wd,bg as Yd,T as Ki,G as qd,l as Hi,j as rn,bh as Er,H as Pr,a4 as Sn,bi as Qd,bj as Zs,ay as or,bk as Mr,bl as vs,bm as _o,bn as Tr,bo as Wi,bp as Fr,bq as Vd,ah as Jd,br as Xd,bs as Zd,bt as eu,bu as tu,ak as su,a3 as nu,V as ru,k as ou,bv as Yi,d as iu,L as au}from"./index-ivrh3jfy.js";import{c as ps,d as qi,p as to,u as Lr,a as lu}from"./vendor-zustand-GVb4H8HE.js";import{g as us,d as cu,e as Qi,r as du,h as Vi,i as Rn,j as Ji,b as un,c as fn,s as uu,k as fu,l as hu,m as zo,n as Yn,f as pu,S as mu,a as gu,t as xu,o as bu}from"./SessionUnreadDot-BxtTkvHB.js";import{i as Xi,j as Zi,k as ea,l as ta,m as sa,M as na,S as ra,D as yu,c as wu,d as vu,e as Su,f as ju,g as ku,h as Cu}from"./vendor-base-ui-vkqQ2P9o.js";import{c as so,d as On,P as oa,D as no,e as ro,f as ia,b as Nu,a as Au,T as Iu,M as Du}from"./vendor-dnd-kit-core-CP8ck10N.js";import{u as Ru}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as aa,v as Eu,u as la,h as Pu}from"./vendor-dnd-kit-sortable-B-Icjoj4.js";import{C as ca}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import{usePermissionStore as Mu}from"./permissionStore-iKN1K2_x.js";const Tu="chat";function da(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ls.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ls.SETTINGS,n),s}return e.tab!==Tu&&s.set(Ls.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ls.FILE,e.diffFile),s}function Fu(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Lu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=da(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ls.SESSION)&&s.set(Ls.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&&Lu(e)))try{const n=da(e),r=Fu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ou=["typescript","javascript","tsx","jsx","json","markdown"],ua={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Uo=null;const fa=()=>(Uo??=Promise.all([Ss(()=>import("./index-CMfiVUIr.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])),Ss(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ss(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([110,111,97,98,24,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),Uo),hn={},$o=new Set,Br=new Set;let En={light:"pierre-light",dark:"pierre-dark"};const Bu=()=>{for(const e of Br)e()},ha=(e,s)=>{s.setRenderOptions({theme:En,lineDiffType:ua[e].lineDiffType})},_r=e=>{typeof window>"u"||$o.has(e)||($o.add(e),fa().then(s=>{if(hn[e])return;const n=ua[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ou,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),hn[e]=r,ha(e,r),Bu()}))},_u=e=>(Br.add(e),()=>Br.delete(e)),zu=e=>{if(!(En.light===e.light&&En.dark===e.dark)){En=e;for(const s of Object.keys(hn)){const n=hn[s];n&&ha(s,n)}}},sx=({children:e})=>{const s=xc(),n=Lo(!1),r=Lo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(u=>u.metadata.id===o)??n,c=s?.availableThemes.find(u=>u.metadata.id===a)??r;return Me.useEffect(()=>{let u=!1;return fa().then(d=>{u||(d.ensurePierreThemeRegistered(l),d.ensurePierreThemeRegistered(c),zu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,l]),Me.useEffect(()=>{if(typeof window>"u")return;const u=()=>{_r("unified"),_r("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})},nx=(e="unified")=>{const s=Me.useSyncExternalStore(_u,()=>hn[e],()=>{});return Me.useEffect(()=>{_r(e)},[e]),s};function Uu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=bc();return e}catch{return"unknown"}}function $u(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function Gu(){const e=Dd();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function Ku(e){const s=new URLSearchParams;return s.set("deviceClass",Uu()),s.set("arch",$u()),s.set("platform",Gu()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",dn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ir(e,s){try{const n=Ku(e);s&&n.set("currentVersion",s);const r=await Mt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Hu(){return Nd()?"mobile":Ad()?"desktop":Id()?"web":null}const Go={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Pn=ps()((e,s)=>({...Go,checkForUpdates:async()=>{const n=Hu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.8.2",[l,c]=await Promise.allSettled([Oo(),ir("desktop",a)]),u=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:u?.available??!1,info:u,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ir("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ir("mobile","0.8.2"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await Oo();if(!o?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await Cd(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await kd())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(Go)}})),Wu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Yu=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[u,d]=i.useState(!1),[f,h]=i.useState(""),[x,g]=i.useState(!1),[m,p]=i.useState(!1),[y,b]=i.useState(""),[I,v]=i.useState(!1),k=i.useRef(null),S=i.useCallback(P=>{P.stopPropagation()},[]),D=l.length>1,C=i.useMemo(()=>Wu(y),[y]),w=i.useMemo(()=>{const P=f.toLowerCase();return P?s.filter(B=>B.toLowerCase().includes(P)):s},[f,s]),j=i.useMemo(()=>{const P=f.toLowerCase();return P?n.filter(B=>B.toLowerCase().includes(P)):n},[f,n]),E=P=>{if(P===e){d(!1);return}o(P),d(!1),h("")},T=()=>{g(!0),setTimeout(()=>k.current?.focus(),50)},U=async()=>{if(!(!C||I)){if(D){p(!0);return}v(!0);try{await a(C,l[0]),b(""),g(!1),d(!1)}finally{v(!1)}}},_=async P=>{if(!(!C||I)){v(!0);try{await a(C,P),b(""),g(!1),p(!1),d(!1)}finally{v(!1)}}},$=()=>{p(!1)},K=()=>{b(""),g(!1),p(!1)};return i.useEffect(()=>{u||(h(""),g(!1),p(!1),b(""))},[u]),t.jsxs(jt,{open:u,onOpenChange:d,children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx(kt,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(A,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(A,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Le,{sideOffset:8,children:"Current branch"})]}),t.jsx(Ct,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(yc,{className:"h-full min-h-0",children:[t.jsx(wc,{placeholder:"Search branches...",value:f,onValueChange:h,onKeyDown:S}),t.jsxs(vc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Sc,{children:"No branches found."}),t.jsx(nr,{children:m?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:$,disabled:I,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(A,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:C})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(P=>t.jsxs("button",{type:"button",onClick:()=>_(P),disabled:I,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[I?t.jsx(A,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,P.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:P.pushUrl})]},P.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:k,placeholder:"New branch name",value:y,onChange:P=>b(P.target.value),onClick:P=>P.stopPropagation(),onKeyDown:P=>{S(P),P.key==="Enter"?(P.preventDefault(),U()):P.key==="Escape"&&(P.preventDefault(),K())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:U,disabled:!C||I,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:I?t.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(A,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:K,disabled:I,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(A,{name:"close",className:"size-4"})})]}):t.jsxs(Js,{onSelect:T,children:[t.jsx(A,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Local branches",children:[w.map(P=>t.jsxs(Js,{onSelect:()=>E(P),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:P}),(r?.[P]?.ahead||r?.[P]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[P].ahead||0," ahead ·"," ",r[P].behind||0," behind"]})]}),e===P&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${P}`)),w.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ro,{}),t.jsxs(nr,{heading:"Remote branches",children:[j.map(P=>t.jsx(Js,{onSelect:()=>E(P),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:P})},`remote-${P}`)),j.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},qu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Qu=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,o]=i.useState(!1),[a,l]=i.useState(e||""),[c,u]=i.useState(!1),d=i.useRef(null),f=()=>{!e||!s||(l(e),o(!0),setTimeout(()=>d.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const m=qu(a);if(m===e){o(!1);return}u(!0);try{await s(e,m),o(!1),l("")}finally{u(!1)}},x=()=>{o(!1),l("")},g=m=>{m.key==="Enter"?(m.preventDefault(),h()):m.key==="Escape"&&(m.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:m=>{m.preventDefault(),h()},children:[t.jsx(A,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:d,value:a,onChange:m=>l(m.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:g,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(A,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(A,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(A,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Re,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:f,title:"Rename branch",children:t.jsx(A,{name:"edit",className:"size-4"})})]})]})},Vu=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:o,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:u=0,trackingRemoteName:d,hasUncommittedChanges:f=!1})=>{const h=i.useRef(!1),x=!!l,g=s.find(S=>S.name===d)??s[0],m=u>0&&f,p=a||e!==null||x||!g||m,y=a||e!==null||x||s.length===0,b=c>0||u>0,I=["sync",u>0?`↓${u}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),v=m?"Commit or stash your changes before syncing":g?b?`Sync Changes (${u} down, ${c} up)`:"Sync Changes":"No remotes configured",k=()=>{g&&r(g)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:m?0:void 0,children:t.jsxs("button",{type:"button",onClick:k,disabled:p,className:z("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(A,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:I})]})})}),t.jsx(Le,{sideOffset:8,children:v})]}),t.jsxs(jt,{children:[t.jsx(kt,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:y,"aria-label":"More sync actions",children:t.jsx(A,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Ct,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(S=>t.jsx(Je,{onSelect:D=>{if(h.current){D.preventDefault(),h.current=!1;return}n(S)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(A,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${S.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:S.fetchUrl})]})}),o&&S.name!==d?t.jsx(Re,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:D=>{h.current=!0,D.preventDefault(),D.stopPropagation()},onClick:D=>{h.current=!0,D.preventDefault(),D.stopPropagation(),o(S)},"aria-label":`Remove remote ${S.name}`,title:`Remove remote ${S.name}`,children:l===S.name?t.jsx(A,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(A,{name:"close",className:"size-3.5"})}):null]})},S.name))})]})]})},Ju={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Xu={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function pa(e){return e&&Xu[e]||"var(--primary)"}const Ko=({icon:e,className:s,colorToken:n})=>{const r=Ju[e??"branch"]??"user-3";return t.jsx(A,{name:r,className:s,style:{color:pa(n)}})},ma=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(jt,{children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx(kt,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:pa(e?.color)},disabled:a,children:[r?t.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(Ko,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(A,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(Le,{sideOffset:8,children:"Git identity"})]}),t.jsx(Ct,{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(Je,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(Ko,{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(A,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},Zu=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,o=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(Te,{delayDuration:n,children:[t.jsx(Fe,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(A,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),o?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(Le,{sideOffset:8,children:a})]})},rx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:u,removingRemoteName:d,onCheckoutBranch:f,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:g,availableIdentities:m,onSelectIdentity:p,isApplyingIdentity:y,isWorktreeMode:b,onOpenHistory:I,onOpenGraph:v,onOpenStashes:k,onOpenUpdateBranch:S,onOpenReintegrateCommits:D,pullRequest:C,prChecks:w,onOpenPullRequest:j})=>{if(!e)return null;const E=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:I||v||k||S?t.jsxs(jt,{children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx(kt,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(A,{name:"more-fill",className:"size-4"})})})}),t.jsx(Le,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Ct,{align:"end",children:[I?t.jsxs(Je,{onSelect:I,children:[t.jsx(A,{name:"history",className:"size-4"}),"History"]}):null,v?t.jsxs(Je,{onSelect:v,children:[t.jsx(A,{name:"git-branch",className:"size-4"}),"Graph"]}):null,k?t.jsxs(Je,{onSelect:k,children:[t.jsx(A,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,S?t.jsxs(Je,{onSelect:S,children:[t.jsx(A,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,D?t.jsxs(Je,{onSelect:D,children:[t.jsx(A,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),T=w?w.state==="success"?"var(--status-success)":w.state==="failure"?"var(--status-error)":"var(--status-warning)":null,U=C?C.state==="merged"?"merged":C.state==="closed"?"closed":C.draft?"draft":w?.state==="failure"||C.mergeable===!1||C.mergeableState==="blocked"||C.mergeableState==="dirty"?"blocked":"open":null,_=C&&j?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsxs(Re,{variant:"ghost",size:"sm",onClick:j,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(A,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${U})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${C.number}`}),T?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:T}}):null]})}),t.jsx(Le,{sideOffset:8,children:"Open pull request"})]}):null,$=t.jsx(Vu,{syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:u,removingRemoteName:d,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),K=e.upstreamComparison?t.jsx(Zu,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,P=t.jsx(ma,{activeProfile:g,identities:m,onSelect:p,isApplying:y,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:b?t.jsx(Qu,{currentBranch:e.current,onRename:x}):t.jsx(Yu,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:P})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[_?t.jsx("div",{className:"shrink-0",children:_}):null,t.jsx("div",{className:"min-w-0 flex-1"}),K?t.jsx("div",{className:"min-w-0 shrink",children:K}):null,E,t.jsx("div",{className:"shrink-0",children:$})]})]})},ef=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Hs=e=>{if(!e||ef(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Bs=e=>e.endsWith("/"),Bn=e=>{const s=e.trim();return!s||Bs(s)?s:`${s}/`},oo=e=>e.lastIndexOf("/"),ga=e=>{if(Bs(e))return e;const s=oo(e);return s<0?e:e.slice(0,s+1)},xa=e=>{const s=oo(e);return e.slice(s+1)},ba=e=>{const s=Hs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=oo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},ya=e=>Bs(e)&&ba(e)!==null,tf=e=>{if(!ya(e))return null;const s=Hs(e.trim());return xa(s)||s},sf=(e,s)=>`${ga(e)}${s}/`,js=e=>{if(!e)return null;const s=Hs(Ks(e.trim()));return s?s.toLowerCase():null},Ho=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},nf=(e,s)=>{const n=Hs(Ks(e.trim())),r=Hs(Ks(s.trim()));if(!n)return"";if(!r)return Bn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Bn(n)},rf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,zr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},of=async()=>Rd(),af=()=>{const[e,s]=Me.useState(!1),[n,r]=Me.useState(!1);Me.useEffect(()=>{s(Us()),r(Jr())},[]);const o=Me.useCallback(async c=>e?await Xr(c):{success:!0,path:c},[e]),a=Me.useCallback(async c=>e?await Ed():{success:!0},[e]),l=Me.useCallback(async c=>e?await Pd():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function lf({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=$s(Z=>Z.homeDirectory),{canRequestAccess:o,startAccessing:a}=af(),l=i.useRef(null),c=i.useRef(new Map),[u,d]=i.useState(""),[f,h]=i.useState("~/"),[x,g]=i.useState([]),[m,p]=i.useState(!1),[y,b]=i.useState(!1),[I,v]=i.useState(null),[k,S]=i.useState(0),[D,C]=i.useState(0),[w,j]=i.useState(!1),[E,T]=i.useState(!1),[U,_]=i.useState("right"),$=i.useRef("~/"),K=u||r;i.useEffect(()=>{if(!e)return;h("~/"),g([]),C(0),j(!1),T(!1),$.current="~/",_("right"),n||requestAnimationFrame(()=>zr(l.current));let Z=!1;return(async()=>{const L=await of();Z||(d(L||r||""),n||requestAnimationFrame(()=>zr(l.current)))})(),()=>{Z=!0}},[r,e,n]);const P=i.useMemo(()=>ga(f),[f]),B=i.useMemo(()=>Bs(f)?"":xa(f),[f]),R=i.useMemo(()=>K?Ho(P,K):"",[P,K]);i.useEffect(()=>{const Z=$.current;Z!==P&&(_(P.length>=Z.length?"right":"left"),$.current=P)},[P]),i.useEffect(()=>{if(!e||!R){g([]),v(null);return}let Z=!1;return p(!0),b(!1),v(null),Md(R).then(ue=>{if(Z)return;b(!1),v(null);const L=ue.filter(Y=>Y.isDirectory).map(Y=>({name:Y.name,path:Ks(Y.path)})).sort((Y,le)=>Y.name.localeCompare(le.name));g(L)}).catch(ue=>{if(!Z){g([]);const L=Td(ue)?ue.reason:"unknown";v(L),b(L==="not-found")}}).finally(()=>{Z||p(!1)}),()=>{Z=!0}},[R,k,e]);const F=i.useMemo(()=>{const Z=B.toLowerCase(),ue=E||B.startsWith(".");return x.filter(L=>L.name.toLowerCase().startsWith(Z)&&(ue||!L.name.startsWith(".")))},[B,x,E]),Q=i.useMemo(()=>tf(f),[f]),G=i.useMemo(()=>ba(f),[f]),M=i.useMemo(()=>{const Z=[],ue=js(R);ya(f)&&Q&&G&&Z.push({type:"parent",value:"browse:up",name:Q,path:G,alreadyAdded:!!(ue&&s.has(ue))});for(const L of F){const Y=js(L.path);Z.push({type:"directory",value:`browse:${L.path}`,name:L.name,path:L.path,alreadyAdded:!!(Y&&s.has(Y))})}return Z},[s,R,Q,F,G,f]);i.useEffect(()=>{C(0)},[f,M.length]);const ee=i.useMemo(()=>K?Hs(Ho(f,K)):"",[K,f]),H=js(ee),ye=!!(H&&s.has(H)),ce=i.useMemo(()=>B?F.find(Z=>Z.name===B)??null:null,[B,F]),ae=!!(ee&&!ye&&(I===null||I==="not-found")&&(Bs(f)&&y||!Bs(f)&&B.trim().length>0&&ce===null)),xe=M[D]??null,we=!!xe,ge=i.useCallback(Z=>{h(Bn(Z))},[]),ve=i.useCallback(Z=>{h(sf(f,Z.name))},[f]),Se=i.useCallback(Z=>{if(Z){if(Z.type==="parent"){ge(Z.path);return}ve(Z)}},[ge,ve]),ke=i.useCallback(async Z=>{const ue=await a(Z);if(!ue.success)return se.error("Failed to open directory",{description:ue.error||"Desktop could not grant file access."}),!1;const L=K?nf(Z,K):Bn(Ks(Z));return ge(L),!0},[ge,K,a]),je=i.useCallback(async()=>{if(!w){j(!0);try{if(Jr()){const ue=await Xr(ee);if(!ue.success||!ue.path){ue.error&&ue.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:ue.error});return}await ke(ue.path);return}const Z=await Fd(ee);if(Z.status==="cancelled")return;if(Z.status!=="picked"){se.error("Couldn't open a folder picker",{description:Z.error});return}await ke(Z.path)}catch(Z){se.error("Failed to select directory",{description:Z instanceof Error?Z.message:"Unknown error occurred."})}finally{j(!1)}}},[ke,w,ee]);return{inputRef:l,rowRefs:c,query:f,setQuery:h,isLoading:m,isBrowseDirectoryMissing:y,browseErrorReason:I,browseReloadKey:k,setBrowseReloadKey:S,highlightedIndex:D,setHighlightedIndex:C,isPickingLocation:w,showHidden:E,setShowHidden:T,folderEnterFrom:U,explorerRootDirectory:K,browseDirectoryDisplayPath:P,browseDirectoryAbsolutePath:R,browseFilterQuery:B,filteredEntries:F,rows:M,targetPath:ee,isAlreadyAdded:ye,shouldCreateTarget:ae,highlightedRow:xe,hasHighlightedBrowseItem:we,canRequestAccess:o,browseToDisplayPath:ge,browseToEntry:ve,executeRow:Se,applyPickedLocation:ke,handleBrowseLocation:je}}const ys=ps()(qi(to((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=Zt()?.git,o=r?await r.getGitIdentities():await $d();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 Ud();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 zd();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 Mt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Zr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};Xt("saving");const o=Zt()?.git;return o?await o.createGitIdentity(r):await _d(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 Bd(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 Od(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:Ld(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ys);function cf({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:u,isPickingLocation:d}){const f=ut(G=>G.addProject),h=re(G=>G.setActiveMainTab),x=re(G=>G.setSessionSwitcherOpen),g=Ne(G=>G.openNewSessionDraft),m=ys(G=>G.profiles),p=ys(G=>G.globalIdentity),y=ys(G=>G.defaultGitIdentityId),b=ys(G=>G.loadProfiles),I=ys(G=>G.loadGlobalIdentity),v=ys(G=>G.loadDefaultGitIdentityId),[k,S]=i.useState(!1),[D,C]=i.useState(!1),[w,j]=i.useState(""),[E,T]=i.useState(null);i.useEffect(()=>{e&&(S(!1),C(!1),j(""),T(null))},[e]),i.useEffect(()=>{e&&(b(),I(),v())},[v,b,I,e]);const U=i.useMemo(()=>{const G=new Map;p&&G.set(p.id,p);for(const M of m)G.set(M.id,M);return Array.from(G.values())},[m,p]);i.useEffect(()=>{if(!e||!D||E!==null)return;const G=typeof y=="string"?y.trim():"";if(G&&U.some(ee=>ee.id===G)){T(G);return}const M=U.find(ee=>ee.authType==="ssh"||ee.sshKey);M&&T(M.id)},[U,y,D,e,E]);const _=i.useMemo(()=>U.find(G=>G.id===E)??null,[U,E]),$=i.useCallback((G,M)=>{h("chat"),n&&x(!1),g({selectedProjectId:G,directoryOverride:M}),s()},[n,s,g,h,x]),K=i.useCallback(async G=>{if(!G||k)return;const M=js(G);if(M&&r.has(M))return;let ee=G;S(!0);try{const H=!D&&a&&js(G)===js(o);if(D){const ce=w.trim();if(!ce){se.error("Enter a repository URL before cloning.");return}const ae=await Mt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ce,destinationPath:G,gitIdentityId:_?.id??null})});if(!ae.ok)throw new Error("Failed to clone git repository");ee=(await ae.json()).path||G}else if(H&&!(await Mt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:G})})).ok)throw new Error("Failed to select directory");const ye=f(ee);if(!ye){se.error("Failed to add folder",{description:"Please select a valid directory path."});return}$(ye.id,ye.path)}catch(H){se.error("Failed to select directory",{description:H instanceof Error?H.message:"Unknown error occurred."})}finally{S(!1)}},[f,r,c,w,D,k,$,_?.id,a,o]),P=!k&&!d&&!u&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,B=P&&w.trim().length>0,R=D?B:P,F=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:k,isCloneMode:D,setIsCloneMode:C,cloneRemoteUrl:w,setCloneRemoteUrl:j,selectedGitIdentityId:E,setSelectedGitIdentityId:T,availableGitIdentities:U,selectedGitIdentity:_,canSubmit:R,submitActionLabel:u?"Already added":D?k?"Cloning...":"Clone & add":k?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:F,finalizeSelection:K}}const df=({open:e,onOpenChange:s})=>{const n=ut(L=>L.projects),{isMobile:r,isTablet:o}=As(),a=r||o,l=i.useMemo(()=>new Set(n.map(L=>js(L.path)).filter(L=>!!L)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:u,rowRefs:d,query:f,setQuery:h,isLoading:x,browseErrorReason:g,setBrowseReloadKey:m,highlightedIndex:p,setHighlightedIndex:y,isPickingLocation:b,showHidden:I,setShowHidden:v,folderEnterFrom:k,browseDirectoryDisplayPath:S,browseDirectoryAbsolutePath:D,rows:C,targetPath:w,isAlreadyAdded:j,shouldCreateTarget:E,highlightedRow:T,hasHighlightedBrowseItem:U,canRequestAccess:_,executeRow:$,handleBrowseLocation:K}=lf({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:P,isCloneMode:B,setIsCloneMode:R,cloneRemoteUrl:F,setCloneRemoteUrl:Q,setSelectedGitIdentityId:G,availableGitIdentities:M,selectedGitIdentity:ee,canSubmit:H,submitActionLabel:ye,submitModifierLabel:ce,finalizeSelection:ae}=cf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:E,browseErrorReason:g,browseDirectoryAbsolutePath:D,isAlreadyAdded:j,isPickingLocation:b});i.useLayoutEffect(()=>{const L=u.current;L&&(L.scrollLeft=L.scrollWidth)},[u,f]),i.useLayoutEffect(()=>{!e||a||zr(u.current)},[u,e,a]),i.useLayoutEffect(()=>{const L=C[p];L&&d.current.get(L.value)?.scrollIntoView({block:"nearest"})},[p,d,C]);const xe=i.useCallback(L=>{if(L.key==="ArrowDown"){L.preventDefault(),y(Y=>Math.min(C.length-1,Y+1));return}if(L.key==="ArrowUp"){L.preventDefault(),y(Y=>Math.max(0,Y-1));return}if(L.key==="Enter"){if(L.preventDefault(),rf(L)){ae(w);return}U&&$(T);return}L.key==="Backspace"&&f===""&&(L.preventDefault(),c())},[$,ae,c,U,T,f,C.length,y,w]),we=t.jsxs("button",{type:"button",onClick:()=>v(L=>!L),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[I?t.jsx(A,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(A,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),ge=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(A,{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(cn,{ref:u,value:f,onChange:L=>h(Ks(L.target.value)),onKeyDown:xe,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Re,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:P||b,onMouseDown:L=>L.preventDefault(),onClick:()=>{K()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(A,{name:"folder-open",className:"h-3.5 w-3.5"}),b?"Opening...":"Browse"]})]})}),ve=C.some(L=>L.type==="parent"),Se=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Re,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":B,disabled:P||b,onClick:()=>R(L=>!L),children:[t.jsx(A,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),B?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(cn,{value:F,onChange:L=>Q(L.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(ma,{activeProfile:ee,identities:M,onSelect:L=>G(L.id),isApplying:P,iconOnly:!0})]})]}):null,j?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:z("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",k==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):g&&g!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:g==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[g==="os-permission"&&_?t.jsx(Re,{size:"xs",onClick:()=>{K()},disabled:b,children:"Grant access"}):null,t.jsx(Re,{variant:"outline",size:"xs",onClick:()=>m(L=>L+1),children:"Try again"})]})]}):C.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:C.map((L,Y)=>{const le=Y===p,W=L.type==="directory"&&ve;return t.jsxs("button",{ref:X=>{X?d.current.set(L.value,X):d.current.delete(L.value)},type:"button","aria-label":L.type==="parent"?L.alreadyAdded?`Go back from ${L.name}, already added`:`Go back from ${L.name}`:L.alreadyAdded?`Open ${L.name}, already added`:`Open ${L.name}`,onMouseEnter:()=>y(Y),onMouseDown:X=>X.preventDefault(),onClick:()=>$(L),className:z("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",le&&"bg-interactive-selection text-interactive-selection-foreground",!le&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:z("flex min-w-0 flex-1 items-center gap-2",W&&"pl-4"),children:[L.type==="parent"?t.jsx(A,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(A,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:L.name})]}),L.alreadyAdded?t.jsx("span",{className:z("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",le?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,L.type==="parent"?t.jsx(A,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(A,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},L.value)})})},S)]})}),ke=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[ge,Se]}),je=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(A,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(A,{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(A,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:ce}),t.jsx(A,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Z=t.jsx(Re,{size:r?"xs":"default",onClick:()=>{ae(w)},disabled:!H,className:z(r&&"w-full flex-1"),children:ye}),ue=()=>t.jsxs(t.Fragment,{children:[r?null:je,t.jsx("div",{className:z("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:Z})]});return r?t.jsx(Ai,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ue()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:we}),ke]})}):t.jsx(Gt,{open:e,onOpenChange:s,children:t.jsxs(Kt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(fs,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(ss,{children:"Add folder"}),t.jsx(hs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),we]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:ke}),t.jsx(Is,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ue()})]})})},jn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,ox=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=jc,c=Ne(D=>D.deleteSessions),u=re(D=>D.showDeletionDialog),d=re(D=>D.setShowDeletionDialog),{isMobile:f,isTablet:h,hasTouchInput:x}=As(),g=f||h||x;i.useEffect(()=>Gd(()=>{s(!1)}),[]);const m=i.useCallback(D=>{r({sessions:D.sessions,dateLabel:D.dateLabel})},[]),p=i.useCallback(()=>{r(null),a(!1)},[]),y=i.useCallback(async D=>{if(D.sessions.length===0)return;if(D.sessions.length===1){const E=D.sessions[0];await l(E.id)?se.success("Session deleted"):se.error("Failed to delete session");return}const C=D.sessions.map(E=>E.id),{deletedIds:w,failedIds:j}=await c(C);if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:D.dateLabel?`Removed all sessions from ${D.dateLabel}.`:void 0;se.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:jn(E)})}j.length>0&&se.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:jn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>Cs.onDeleteRequest(D=>{if(!u){y(D);return}m(D)}),[m,u,y]),i.useEffect(()=>Cs.onDirectoryRequest(()=>{s(!0)}),[]);const b=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const D=n.sessions[0];if(!await l(D.id)){se.error("Failed to delete session"),a(!1);return}se.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const D=n.sessions.map(E=>E.id),C=await c(D),w=C.deletedIds,j=C.failedIds;if(w.length>0){const E=j.length>0?j.length===1?`${j.length} session could not be deleted.`:`${j.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;se.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:jn(E),action:{label:"OK",onClick:()=>{}}})}if(j.length>0&&(se.error(j.length===1?`Failed to delete ${j.length} session`:`Failed to delete ${j.length} sessions`,{description:jn("Please try again in a moment.")}),w.length===0)){a(!1);return}}p()}finally{a(!1)}}},[n,l,c,p]),I=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(D=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:us(D)})},D.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,k=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(A,{name:"checkbox-blank",className:"size-4"}):t.jsx(A,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Re,{variant:"ghost",onClick:p,disabled:o,children:"Cancel"}),t.jsx(Re,{variant:"destructive",onClick:b,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),S=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[g?t.jsx(Ai,{open:!!n,onClose:()=>{o||p()},title:S,footer:t.jsx("div",{className:"flex justify-end gap-2",children:k}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),v]})}):t.jsx(Gt,{open:!!n,onOpenChange:D=>{if(!D){if(o)return;p()}},children:t.jsxs(Kt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:S}),I&&t.jsx(hs,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),t.jsx(Is,{className:"mt-2 gap-2 pt-1 pb-1",children:k})]})}),t.jsx(df,{open:e,onOpenChange:s})]})},ix=()=>{const e=Ns(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(Ns.getState().markNotificationSent(s.key),se.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},uf=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],ff={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function hf(e){const s=e.trim().toLowerCase();return uf.find(n=>n.slug===s)??null}function pf(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=ff[s];if(n)return n;const r=hf(s);return r?r.slug:"home"}function ax(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"snippets":return"chat-thread";case"prompt-templates":return"terminal";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}function lx(){const e=i.useRef(!1),s=i.useRef(!1),n=Ne(f=>f.setCurrentSession),r=re(f=>f.setActiveMainTab),o=re(f=>f.setSettingsDialogOpen),a=re(f=>f.setSettingsPage),l=re(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const h=Ne.getState().currentSessionId,x=Xs().getState().selectedSessionId;if(f.sessionId!==h||f.sessionId!==x){const g=Ne.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,g)}}if(f.settingsPath){a(pf(f.settingsPath)),o(!0);return}re.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=Ne.getState(),h=Xs().getState(),x=re.getState();return{sessionId:rr({currentSessionId:f.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),d=i.useCallback((f={})=>{if(s.current)return;const h=u();Or(h,f)},[u]);i.useEffect(()=>{if(e.current||(e.current=!0,!Eo()))return;const f=Po();(async()=>(await c(f),Or({...u(),sessionId:f.sessionId??rr({currentSessionId:Ne.getState().currentSessionId,piSelectedSessionId:Xs().getState().selectedSessionId,draft:Ne.getState().newSessionDraft}),tab:f.tab??re.getState().activeMainTab,settingsPath:f.settingsPath??re.getState().settingsPage,diffFile:f.diffFile??re.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),i.useEffect(()=>{const f=()=>{const y=Ne.getState(),b=Xs().getState();return rr({currentSessionId:y.currentSessionId,piSelectedSessionId:b.selectedSessionId,draft:y.newSessionDraft})};let h=f(),x=Ne.getState().newSessionDraft?.open===!0;const g=()=>{const y=Ne.getState(),b=f(),I=y.newSessionDraft?.open===!0;b===h&&I===x||s.current||(h=b,x=I,d({replace:!0}))},m=Ne.subscribe(()=>{g()}),p=Xs().subscribe(()=>{g()});return()=>{m(),p()}},[d]),i.useEffect(()=>{let f=re.getState().activeMainTab,h=re.getState().isSettingsDialogOpen,x=re.getState().settingsPage,g=re.getState().pendingDiffFile;return re.subscribe(p=>{if(s.current)return;const y=p.activeMainTab!==f,b=p.isSettingsDialogOpen!==h,I=p.settingsPage!==x,v=p.pendingDiffFile!==g&&p.activeMainTab==="diff";f=p.activeMainTab,h=p.isSettingsDialogOpen,x=p.settingsPage,g=p.pendingDiffFile,(y||b||I||v)&&d()})},[d]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const h=Po();if(Eo())c(h);else{const x=re.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function mf(e=!0){const s=Pn(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=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},f=h=>{c||(u=window.setTimeout(async()=>{const x=await n.current(),g=typeof x=="number"&&Number.isFinite(x)?d(x):o;f(g)},h))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function cx(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return mf(e),null}const Wo=12,gf=[{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"}],xf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=gf,onComplete:a})=>{const l=Me.useRef(!1);Me.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Me.useMemo(()=>Array.from({length:Wo},(u,d)=>{const f=Math.PI*2*d/Wo;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?t.jsx("div",{className:z("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,h)=>{const x=f.x*u.radius,g=f.y*u.radius,m={"--translate-x":`${x}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return t.jsx("span",{className:"firework-particle",style:m},`${u.id}-${h}-${s}`)})},`${u.id}-${s}`)})}):null},bf=({durationMs:e=3400}={})=>{const[s,n]=Me.useState({isActive:!1,cycle:0}),r=Me.useRef(null),o=Me.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Me.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Me.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Me.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},wa=i.createContext(void 0),dx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=bf(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(wa.Provider,{value:a,children:[e,t.jsx(xf,{isActive:s,burstKey:n})]})},yf={triggerFireworks:()=>{},dismissFireworks:()=>{}},ux=()=>i.useContext(wa)??yf,Yo="https://github.com/RyderAsKing/PiChamber/releases";function wf(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 vf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function qo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Sf(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 jf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const Qo=2e3,kf=600*1e3;async function Cf(){try{const e=await Mt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Nf(){try{return(await Mt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function Af(e,s=Math.ceil(kf/Qo),n=Qo){for(let r=0;r<s;r++){try{const o=await Mt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await Nf())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const va=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,h]=Me.useState(!1),[x,g]=Me.useState("idle"),[m,p]=Me.useState(null),y=n?.version?n.releaseUrl||`${Yo}/tag/v${n.version}`:Yo,b=n?.downloadUrl||y,I=a?.total?Math.round(a.downloaded/a.total*100):0,v=d==="web",k=d==="mobile",S=n?.updateCommand||"pichamber update";Me.useEffect(()=>{e||(g("idle"),p(null))},[e]);const D=async()=>{(await _s(S)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},C=Me.useCallback(async U=>{await Ii(U)},[]),w=Me.useCallback(async()=>{g("updating"),p(null);const U=await Cf();if(!U.success){g("error"),p(U.error||"Update failed");return}U.autoRestart&&(g("restarting"),await new Promise($=>setTimeout($,2e3))),g("reconnecting"),await Af(n?.currentVersion)?window.location.reload():(g("error"),p("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),j=Me.useCallback(()=>{C(b)},[C,b]),E=x!=="idle"&&x!=="error",T=Me.useMemo(()=>{if(!n?.body)return null;const U=n.body.trim();if(!U)return null;const _=jf(U);return _.length===0?{kind:"raw",title:"What's new",content:qo(U)}:{kind:"sections",title:"What's new",sections:[..._].sort((K,P)=>Sf(K.version,P.version)).map(K=>({version:K.version,dateLabel:wf(K.date),content:qo(vf(K.raw)||U)}))}},[n?.body]);return t.jsx(Gt,{open:e,onOpenChange:E?void 0:s,children:t.jsxs(Kt,{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(A,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[v&&E&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(A,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!E&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ws,{className:"max-h-[400px] p-0",fillContainer:!1,children:T.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:U=>{const $=U.target.closest("a");$&&$.href&&(U.preventDefault(),U.stopPropagation(),C($.href))},children:t.jsx(Mo,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(U=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",U.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:U.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:_=>{const K=_.target.closest("a");K&&K.href&&(_.preventDefault(),_.stopPropagation(),C(K.href))},children:t.jsx(Mo,{content:U.content,disableLinkSafety:!0,enableFileReferences:!1})})]},U.version))})})}),v&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(A,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:S}),t.jsx("button",{onClick:D,className:z("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(A,{name:"check",className:"h-4 w-4"}):t.jsx(A,{name:"clipboard",className:"h-4 w-4"})})]})]}),!v&&!k&&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:[I,"%"]})]}),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:`${I}%`}})})]}),(l||m)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||m})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(A,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!k&&!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(A,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!v&&!k&&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(A,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!k&&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(A,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),k&&t.jsxs(Re,{onClick:j,size:"default",children:[t.jsx(A,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!E&&t.jsxs("button",{onClick:w,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(A,{name:"download",className:"h-4 w-4"}),"Update Now"]}),v&&E&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(A,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},If=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:z("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:z("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),pn=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const 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(Te,{open:r,onOpenChange:o,children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:z("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(A,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(Le,{sideOffset:8,className:z("max-w-sm",n),children:e})]})},fx="w-full min-w-40 max-w-48",hx="settings",Df="w-full min-w-40 max-w-48",px="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Rf="w-full max-w-[24rem]",mx="min-w-0 flex-1",gx="flex w-full min-w-0 items-center gap-2",xx="typography-meta shrink-0 text-muted-foreground tabular-nums",Sa="space-y-3.5",Ef="space-y-1.5",bx="typography-settings-page-title text-muted-foreground",Pf="typography-settings-section-title text-foreground",ja="typography-settings-group-title text-foreground",io="typography-settings-field-label text-foreground",Mf="typography-settings-description text-muted-foreground",mn="typography-meta text-muted-foreground",yx="typography-meta font-medium text-foreground",wx="typography-settings-section-title text-foreground",Tf=({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:z("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Pf,children:e}):e,n,r!=null?t.jsx(pn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Mf,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:z(u),children:a})]})},vx=({children:e,className:s})=>t.jsx("div",{className:z("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Ff=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:z(ja,s),children:e}),Sx=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:z("space-y-2",o),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ff,{children:e}),n!=null?t.jsx(pn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:mn,children:s}):null]}):null,t.jsx("div",{className:z(a),children:r})]}),on=({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:z("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),r==="before"?u:null]}),t.jsx("div",{className:z("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},jx=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:z("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:io,children:e}),n!=null?t.jsx(pn,{children:n}):null]}),s!=null?t.jsx("p",{className:z(mn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:z("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),kx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:z("pt-4",s),children:e}),Lf=({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)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:z("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[t.jsx(kr,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:io,children:n}),u,d!=null?t.jsx(pn,{children:d}):null]}),h?t.jsx("span",{className:mn,children:r}):null]})]})},Cx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:z("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(If,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:z("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:mn,children:r}):null]})]}),Nx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:z(Ef,n),children:s});function Ax({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:z("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Re,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Of extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(kc,{className:"w-full max-w-md",children:[t.jsx(Cc,{className:"text-center",children:t.jsxs(Nc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(A,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Ac,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Re,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(A,{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 Bf(e){return t.jsx(Of,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const Ix=({active:e=!0})=>{const s=Ne(n=>n.currentSessionId);return t.jsx(Bf,{sessionId:s||void 0,children:t.jsx(Ic,{active:e},s??"no-session")})};function _f({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ka=Me.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:h,...x},g)=>{const m=Me.useRef(null),p=Me.useRef(null),[y,b]=Me.useState(null),I=c??y,v=Me.useCallback(S=>{const D=m.current;if(!D)return;p.current={startY:S.clientY,startHeight:D.getBoundingClientRect().height};const C=S.currentTarget;C.setPointerCapture(S.pointerId);const w=E=>{const T=p.current;if(!T)return;const U=T.startHeight+(E.clientY-T.startY),_=Math.max(82,U);u?u(_):b(_)},j=()=>{p.current=null,C.removeEventListener("pointermove",w),C.removeEventListener("pointerup",j),C.removeEventListener("pointercancel",j)};C.addEventListener("pointermove",w),C.addEventListener("pointerup",j),C.addEventListener("pointercancel",j),S.preventDefault()},[u]),k=Me.useCallback(S=>{if(S.target.closest('textarea, button, [role="separator"]'))return;const C=m.current?.querySelector("textarea");C&&document.activeElement!==C&&(S.preventDefault(),C.focus())},[]);return f?t.jsx(ws,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:z("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...x}):t.jsx("div",{ref:m,onPointerDown:k,style:I!==null?{height:`${I}px`}:void 0,className:z("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:g,className:z("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!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,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(_f,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});ka.displayName="Textarea";const Ca=[{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"}],an=Object.fromEntries(Ca.map(e=>[e.key,e.Icon])),Ur="pichamber:project-actions-updated",Na=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},es=(e,s)=>`${Na(e)}::${s}`,Aa=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:u,divider:d=!0})=>t.jsx(Tf,{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,zf=e=>e.name.trim().length===0&&e.command.trim().length===0,Uf=e=>!$r(e)&&!zf(e),$f=(e,s)=>e.some(r=>s.has(r.id)&&!$r(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter($r)},Gf=450,Kf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Hf=()=>({id:Kf(),name:"",command:"",icon:"play"}),Wf=({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 b=!1;return o(!0),(async()=>{try{const I=await Cr(e);if(b)return;n(I.actions),l(JSON.stringify({actions:I.actions})),u(new Set(I.actions.map(v=>v.id)))}catch{if(b)return;n([]),l(JSON.stringify({actions:[]})),u(new Set)}finally{b||o(!1)}})(),()=>{b=!0}},[e]);const f=i.useMemo(()=>$f(s,c),[s,c]),h=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=a!==null&&f.canPersist&&h!==a,g=i.useCallback(async b=>await Dc(e,{actions:b,primaryActionId:null})?(l(JSON.stringify({actions:b})),u(new Set(b.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ur,{detail:{projectId:e.id}})),!0):(se.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!x||r||d.current)return;const b=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await g(f.actions)}finally{d.current=!1}})())},Gf);return()=>{window.clearTimeout(b)}},[x,r,g,f.actions]);const m=i.useCallback(()=>{const b=Hf();n(I=>[...I,b])},[]),p=i.useCallback(b=>{n(I=>I.filter(v=>v.id!==b))},[]),y=i.useCallback((b,I)=>{n(v=>v.map(k=>k.id===b?I(k):k))},[]);return t.jsx(Aa,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Re,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[t.jsx(A,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:z("space-y-6",Rf),children:s.map((b,I)=>{const v=b.icon||"play",k=an[v]||"play",S=b.name.trim()||`Action ${I+1}`,D=Uf(b);return t.jsxs("div",{className:Sa,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:ja,children:S}),t.jsx(Re,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>p(b.id),"aria-label":`Delete ${S}`,children:t.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(on,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(jt,{children:[t.jsx(kt,{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(A,{name:k,className:"h-4 w-4"})})}),t.jsx(Ct,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ca.map(C=>{const w=C.Icon,j=(b.icon||"play")===C.key;return t.jsx("button",{type:"button",onClick:()=>y(b.id,E=>({...E,icon:C.key})),className:z("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",j&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${C.label}`,children:t.jsx(A,{name:w,className:"h-4 w-4"})},C.key)})})})]}),t.jsx(cn,{value:b.name,onChange:C=>y(b.id,w=>({...w,name:C.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(on,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ka,{value:b.command,onChange:C=>y(b.id,w=>({...w,command:C.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),D?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Lf,{checked:b.autoOpenUrl===!0,onChange:C=>y(b.id,w=>({...w,...C?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${S}`}),b.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(on,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(cn,{value:b.openUrl||"",onChange:C=>y(b.id,w=>({...w,openUrl:C.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},b.id)})})})},Yf={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)"},qf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=$t(w=>w.providers),u=$t(w=>w.modelsMetadata),d=re(w=>w.hiddenModels),f=re(w=>w.isFavoriteModel),h=re(w=>w.toggleFavoriteModel),x=re(w=>w.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:m}=Rc(),[p,y]=i.useState(!1),[b,I]=i.useState("");i.useEffect(()=>{p||I("")},[p]);const v=e?c.find(w=>w.id===e.providerId):void 0,k=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,S=e?Ec(k,e.modelId):s,D=i.useMemo(()=>e?d.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):d,[d,e]),C=i.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),y(!1)},[l]);return t.jsxs(jt,{modal:!1,open:p,onOpenChange:w=>{r||y(w)},children:[t.jsx(kt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:z(Mc({size:"default"}),Df,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Pc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:z("truncate",e?"text-foreground":"text-muted-foreground"),children:S})]}),t.jsx(A,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Ct,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Tc,{providers:c,favoriteModels:g,recentModels:m,modelsMetadata:u,searchQuery:b,onSearchQueryChange:I,onSelect:C,labels:{...Yf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:D,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>h(w.providerID,w.modelID),onReorderFavorite:(w,j)=>x(w.providerID,w.modelID,j.providerID,j.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",Qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=$t(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Aa,{title:"Project",divider:!1,children:t.jsxs("div",{className:Sa,children:[t.jsx(on,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(cn,{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(on,{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(qf,{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},Vf=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(()=>Fc(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}},Jf=450,Xf=(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{se.error("Failed to save project settings")}}finally{l.current=!1}})())},Jf);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},Zf=({project:e,onIdentitySave:s})=>{const n=Vf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Xf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Qf,{form:n}),t.jsx(Wf,{projectRef:r})]})};function Ia({...e}){return t.jsx(Xi,{...e})}function Da({...e}){return t.jsx(Zi,{...e})}function Ra({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(ea,{children:t.jsx(ta,{className:z("app-region-no-drag z-50",s),children:t.jsx(sa,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:z(Di,e),...o,children:n})})})}function Gr({className:e,...s}){return t.jsx(na,{className:z(Ri,e),...s})}function eh({className:e,...s}){return t.jsx(ra,{className:z(Ei,e),...s})}const kn=100;function Dx(){const e=re(w=>w.isArchivePageOpen),s=re(w=>w.setArchivePageOpen),n=re(w=>w.setActiveMainTab),r=Ne(w=>w.setCurrentSession),o=Ne(w=>w.unarchiveSession),a=$s(w=>w.homeDirectory),l=Nr({archived:!0}),[c,u]=i.useState(""),[d,f]=i.useState(null),[h,x]=i.useState(kn),g=c.trim().toLowerCase(),m=i.useMemo(()=>e?[...l].sort((w,j)=>(j.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),p=i.useMemo(()=>{const w=new Map;for(const j of m){const E=be(Os(j))??"",T=w.get(E);if(T){T.sessions.push(j);continue}w.set(E,{directory:E,label:E?Gs(E,a)||E:"other projects",sessions:[j]})}return[...w.values()].sort((j,E)=>E.sessions.length-j.sessions.length)},[a,m]),y=i.useMemo(()=>g?m.filter(w=>(w.title??"").toLowerCase().includes(g)):d===null?m:p.find(w=>w.directory===d)?.sessions??[],[p,g,d,m]),b=y.slice(0,h),I=y.length-b.length,v=l.length,k=i.useCallback(w=>{f(w),x(kn)},[]),S=i.useCallback(w=>{const j=be(Os(w));r(w.id,j??void 0),n("chat"),s(!1)},[n,r,s]),D=i.useCallback(w=>{o(w.id).then(j=>{j?se.success("Session restored"):se.error("Failed to restore session")})},[o]);if(!e)return null;const C=(w,j,E,T,U,_,$)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:U,title:_,className:z("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",$?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",T?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:j}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:E})]}),$?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Cs.requestDelete({sessions:$,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${j}`,children:t.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return t.jsx(yu,{open:e,onOpenChange:s,children:t.jsxs(wu,{children:[t.jsx(vu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(Su,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(ju,{className:"sr-only",children:"Archived sessions"}),t.jsx(ku,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Cu,{"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(A,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[C("__all__","All directories",v,d===null,()=>k(null)),p.map(w=>C(w.directory||"__none__",w.label,w.sessions.length,d===w.directory,()=>k(w.directory),w.directory||void 0,w.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(A,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:w=>{u(w.target.value),x(kn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:y.length===1?`${y.length} archived session`:`${y.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[b.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):b.map(w=>{const j=be(Os(w))??"",E=j?Gs(j,a)||j:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>S(w),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),S(w))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:us(w)}),g&&E?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:j,children:E}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:cu(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),D(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${us(w)}`,children:t.jsx(A,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:T=>{T.stopPropagation(),Cs.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${us(w)}`,children:t.jsx(A,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),I>0?t.jsx("button",{type:"button",onClick:()=>x(w=>w+kn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const Ea=380,lr=8,th=140;function sh({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,h]=i.useState(null),{enabled:x}=Qr();return i.useLayoutEffect(()=>{if(!e||!x||!l)return;const g=()=>{const y=n.current?.getBoundingClientRect(),b=a.current?.getBoundingClientRect();if(!y||!b){h(null);return}const I=y.left-b.left;h(Math.min(Math.max(I,lr),Math.max(lr,b.width-Ea-lr)))};g();const m=a.current;if(typeof ResizeObserver>"u"||!m)return;const p=new ResizeObserver(g);return p.observe(m),()=>p.disconnect()},[n,x,e,l]),i.useEffect(()=>{if(e){c(!0),d(!1);return}if(!l)return;d(!0);const g=window.setTimeout(()=>{c(!1),d(!1)},th);return()=>window.clearTimeout(g)},[e,l]),i.useEffect(()=>{if(!e)return;const g=m=>{m.key==="Escape"&&s()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[s,e]),i.useEffect(()=>{if(!e)return;const g=m=>{const p=m.target;if(!(p instanceof Node)){s();return}o.current?.contains(p)||n.current?.contains(p)||s()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:u,anchorLeft:f,isPopover:x&&f!==null}}const Vo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},_n=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Cn=({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(A,{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})]}),nh=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:u,isPopover:d}=sh({open:e,onClose:s,anchorRef:n,closeOnWheel:!0});return l?t.jsxs("div",{ref:a,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:z("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",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(${Ea}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Cn,{iconNode:t.jsx(Pi,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:z("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Cn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:_n(r.cacheRead)})}),t.jsx(Cn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:_n(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Cn,{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},rh=i.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:a}){const l=i.useRef(null),c=Lc(r??""),u=$t(P=>P.providers),d=$t(P=>P.currentProviderId),f=$t(P=>P.currentModelId),h=$t(P=>P.getCurrentModel()),x=$t(P=>P.getModelMetadata);$t(P=>P.modelsMetadata.size);const g=Oc(i.useCallback(P=>r?P.sessionModelSelections.get(r)??null:null,[r])),m=i.useMemo(()=>{for(let P=c.length-1;P>=0;P-=1){const B=c[P]?.info;if(B.role!=="user")continue;const R=B.model,F=R?.providerID??R?.providerId,Q=R?.modelID??R?.modelId,G=typeof F=="string"&&F.trim().length>0?F:void 0,M=typeof Q=="string"&&Q.trim().length>0?Q:void 0;if(G&&M)return{providerID:G,modelID:M}}return null},[c]),p=i.useMemo(()=>{for(let P=c.length-1;P>=0;P-=1){const B=c[P];if(B?.info.role==="assistant"&&To(B).total>0)return B}return null},[c]),y=m??(()=>{const P=p?.info.model,B=P?.providerID??P?.providerId,R=P?.modelID??P?.modelId;return B&&R?{providerID:B,modelID:R}:null})()??(g?{providerID:g.providerId,modelID:g.modelId}:null)??(d&&f?{providerID:d,modelID:f}:null),I=(y?u.find(P=>P.id===y.providerID):void 0)?.models.find(P=>P.id===y?.modelID),v=y?x(y.providerID,y.modelID):void 0,k=Vo(I?.limit,"context")??v?.limit?.context??Vo(h?.limit,"context")??0,S=p?To(p):null,D=p?.info?.usage,C=D?Bc(D):S?.total??0,w=!a&&C>0&&k>0?Math.min(C/k*100,999):null,j=w!==null?`${_n(C)}/${_n(k)}`:null,E=w===null?"":w>=90?"text-[var(--status-error)]":w>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",T=S?.cacheRead??null,U=S?.cacheWrite??null,_=S?_c({input:S.input,cache:{read:S.cacheRead,write:S.cacheWrite}}):{percent:0,hasInput:!1},$=_.hasInput?_.percent:null,K=w!==null&&j?{percentage:w,tokens:j,colorClass:E,cacheRead:T,cacheWrite:U,cacheHitPercent:$}:null;return t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:l,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":s,onClick:()=>n(P=>!P),style:{touchAction:"manipulation"},children:t.jsx(Pi,{percentage:K?.percentage??0,size:20,className:"size-5 -rotate-90"})}),t.jsx(nh,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:K})]})}),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",oh="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",ih=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(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":u,className:z(a??gn,u&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(A,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(Le,{children:t.jsx("p",{children:n})})]}):null}),Pa=({variant:e="desktop"})=>{const s=Ns(f=>f.entries),[n,r]=i.useState(!1),o=i.useRef(null),a=i.useMemo(()=>[...s.values()].sort((f,h)=>h.startedAt-f.startedAt),[s]),l=a.filter(f=>f.state&&f.state.phase!=="failed").length,c=i.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),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 h=f.receipt;if(!h)return;const x=Ne.getState();x.newSessionDraft.open?x.setNewSessionDraftTarget({directoryOverride:h.path,worktreeIntent:null}):x.openNewSessionDraft({directoryOverride:h.path}),Ns.getState().clearEntry(f.key),re.getState().setActiveMainTab("chat"),r(!1)};return t.jsxs(jt,{open:n,onOpenChange:r,children:[t.jsx(kt,{asChild:!0,children:t.jsxs("button",{type:"button",className:z(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(Ds,{variant:"inline",text:null,animationType:"spinner"}):t.jsx(A,{name:"task",className:"size-[18px]"}),t.jsx("span",{children:"Background tasks"})]})}),t.jsxs(Ct,{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(ah,{entry:f,onOpen:()=>d(f)},f.key))})]})]})},ah=({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(Ds,{variant:"inline",text:null,animationType:"spinner"}):n?t.jsx(A,{name:"alert",className:"size-4 text-[var(--status-error)]"}):t.jsx(A,{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(Re,{type:"button",variant:"ghost",size:"xs",onClick:()=>Ns.getState().dismissFailed(e.key),children:"Dismiss"}):null,o?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Re,{type:"button",size:"xs",onClick:s,children:"Open"}),t.jsx(Re,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Ns.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:t.jsx(A,{name:"close",className:"size-3.5"})})]}):null]})},Jo=600,lh=1,ch=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},dh=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:o})=>{const a=i.useRef(new Map),l=i.useRef([]),c=i.useRef(new Set),u=i.useRef(0),d=!1,f=i.useCallback(m=>`${m.directory}
|
|
12
|
-
${m.sessionId}`,[]),h=i.useCallback(()=>{u.current+=1,l.current=[],a.current.forEach(m=>window.clearTimeout(m)),a.current.clear()},[]),x=i.useCallback(()=>{if(!(!e||d||typeof window>"u"))for(;c.current.size<lh&&l.current.length>0;){const m=l.current.shift();if(!m)break;m.generation!==u.current||Ne.getState().currentSessionId===m.sessionId||zc(m.sessionId,m.directory).renderable}},[e,d,o,f]),g=i.useCallback(m=>{const p=m?.id,y=ch(m);if(!e||d||!p||!y||p===s||typeof window>"u")return;const b={sessionId:p,directory:y,generation:u.current};f(b)},[s,e,d,x,f]);i.useEffect(()=>{h()},[h,s,e,d]),i.useEffect(()=>{if(!e||d||!s||n.length===0)return;const m=window.setTimeout(()=>{const p=n.findIndex(y=>y.id===s);p<0||(g(n[p-1]),g(n[p+1]))},Jo);return()=>window.clearTimeout(m)},[s,e,d,g,n]),i.useEffect(()=>{if(!e||d||!s||r.length===0)return;const m=window.setTimeout(()=>{const p=r.findIndex(y=>y.id===s);p<0||(g(r[p-1]),g(r[p+1]))},Jo);return()=>window.clearTimeout(m)},[s,e,d,r,g]),i.useEffect(()=>h,[h])},uh=e=>{const s=Ne(n=>n.currentSessionId);return dh({...e,currentSessionId:s}),null},fh=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:o,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:u,createFolder:d,addSessionToFolder:f}=e;i.useEffect(()=>{!n||o||!a||l||s.forEach(h=>{if(c.has(h.normalizedPath))return;const x=Qi(h.normalizedPath),g=r.archivedSessionsByProject.get(h.id)??[],m=u[x]??[],p=new Map(m.map(y=>[y.name.toLowerCase(),y]));g.forEach(y=>{const b=du(y,h.normalizedPath),I=b.toLowerCase();let v=p.get(I);v||(v=d(x,b),p.set(I,v)),v.sessionIds.includes(y.id)||f(x,v.id,y.id)})})},[s,n,r,o,a,l,c,u,d,f])},hh=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])}),ph=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:u,hasSessionSearchQuery:d,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:h,buildGroupSearchText:x,foldersMap:g}=e,m=i.useRef(new Map),p=i.useMemo(()=>{const C=m.current,w=new Map;let j=0,E=0;const T=(_,$)=>_.length===$.length&&_.every((K,P)=>K===$[P]),U=s.map(_=>{const $=n(_.id),K=r(_.id),P=a.has(_.id)?!!a.get(_.id):c,B=l.get(_.id)??null,R=o.get(_.normalizedPath)??[],F=C.get(_.id);if(F&&F.project===_&&T(F.activeSessions,$)&&T(F.archivedSessions,K)&&F.rootBranch===B&&F.isRepo===P&&F.worktrees===R&&F.buildGroupedSessions===u)return j+=1,w.set(_.id,F),F.section;E+=1;const Q=Vi([...$,...K]),G=u(Q,_.normalizedPath,R,B,P),M={project:_,groups:G};return w.set(_.id,{project:_,activeSessions:$,archivedSessions:K,rootBranch:B,isRepo:P,worktrees:R,buildGroupedSessions:u,section:M}),M});return m.current=w,j>0&&Lt("ui.sidebar.project_section.reused",j),E>0&&Lt("ui.sidebar.project_section.rebuilt",E),U},[s,n,r,o,a,c,u,l]),y=i.useMemo(()=>p,[p]),b=i.useMemo(()=>{const C=new WeakMap;if(!d)return C;const w=j=>j.reduce((E,T)=>E+1+w(T.children),0);return y.forEach(j=>{j.groups.forEach(E=>{const T=h(E.sessions,f),U=w(T),_=x(E).includes(f),$=be(E.directory??null),P=($?g[$]??[]:[]).filter(B=>B.name.toLowerCase().includes(f)).length;C.set(E,{filteredNodes:T,matchedSessionCount:U,folderNameMatchCount:P,groupMatches:_,hasMatch:_||U>0||P>0})})}),C},[d,y,h,f,x,g]),I=i.useMemo(()=>d?y.map(C=>({...C,groups:C.groups.filter(w=>b.get(w)?.hasMatch===!0)})).filter(C=>C.groups.length>0):y,[d,y,b]),v=d?I:y,k=i.useRef(new WeakMap),S=i.useMemo(()=>{const C=k.current;return v.map(w=>{const j=C.get(w);if(j&&j.query===f)return j.section;const E=w.groups.filter(B=>!B.isArchivedBucket),T=w.groups.filter(B=>B.isArchivedBucket),U=E.flatMap(B=>d?b.get(B)?.filteredNodes??[]:B.sessions),_=E.map(B=>({scopeKey:B.folderScopeKey??be(B.directory??null),directory:B.directory??null})).filter(B=>!!B.scopeKey),$=E.find(B=>B.isMain)??null,K={id:"flat",label:$?.label??"",branch:$?.branch??null,description:$?.description??null,isMain:!0,isArchivedBucket:!1,directory:$?.directory??w.project.normalizedPath,folderScopeKey:$?.folderScopeKey??w.project.normalizedPath,folderScopes:_,sessions:U};if(d){const B=E.map(R=>b.get(R)).filter(R=>!!R);b.set(K,{filteredNodes:U,matchedSessionCount:B.reduce((R,F)=>R+F.matchedSessionCount,0),folderNameMatchCount:B.reduce((R,F)=>R+F.folderNameMatchCount,0),groupMatches:B.some(R=>R.groupMatches),hasMatch:B.some(R=>R.hasMatch)})}const P={project:w.project,groups:[K,...T]};return C.set(w,{query:f,section:P}),P})},[b,d,f,v]),D=i.useMemo(()=>d?v.reduce((C,w)=>C+w.groups.reduce((j,E)=>{const T=b.get(E);if(!T)return j;const U=T.folderNameMatchCount+(T.groupMatches?1:0);return j+T.matchedSessionCount+U},0),0):0,[d,v,b]);return{projectSections:p,visibleProjectSections:y,groupSearchDataByGroup:b,searchableProjectSections:I,sectionsForRender:v,flatSectionsForRender:S,searchMatchCount:D}},mh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:u,openNewSessionDraft:d,setActiveMainTab:f,setSessionSwitcherOpen:h}=e,x=i.useMemo(()=>{const m=new Map,p=new Map,y=(b,I,v,k)=>{m.has(b)||m.set(b,new Map);const S=m.get(b);k.forEach(D=>{const C=be(D.session.directory??v??I);S.set(D.session.id,{directory:C}),p.has(b)||p.set(b,{id:D.session.id,directory:C}),D.children.length>0&&y(b,I,C,D.children)})};return s.forEach(b=>{b.groups.forEach(I=>{y(b.project.id,b.project.normalizedPath,I.directory,I.sessions)})}),{metaByProject:m,firstSessionByProject:p}},[s]),g=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){g.current=n;return}if(g.current===n)return;const m=s.find(D=>D.project.id===n);if(!m)return;g.current=n;const p=x.metaByProject.get(n);if(a&&p&&p.has(a)){o(D=>{if(D.get(n)===a)return D;const C=new Map(D);return C.set(n,a),C});return}const y=a?Array.from(x.metaByProject.entries()).some(([D,C])=>D!==n&&C.has(a)):!1;if(a&&p&&!y)return;if(!p||p.size===0){f("chat"),u&&h(!1),d({selectedProjectId:m.project.id,directoryOverride:m.project.normalizedPath});return}const b=r.get(n),I=b&&p.has(b)?b:null,v=x.firstSessionByProject.get(n)?.id??null,k=I??v;if(!k||k===a)return;const S=p.get(k)?.directory??null;l(k,S,{keepPanelOpen:!0})},[n,r,a,l,c,u,d,s,x,f,h,o]),i.useEffect(()=>{if(!n||!a)return;const m=x.metaByProject.get(n);!m||!m.has(a)||o(p=>{if(p.get(n)===a)return p;const y=new Map(p);return y.set(n,a),y})},[n,a,x,o])},gh=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Ne(c=>c.currentSessionId),o=Ne(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return mh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},Xo=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],xh=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},bh=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,Ma=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=xh(e.trim())%Xo.length;return Xo[s]},yh=(e,s)=>{const n=Ma(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Zo=e=>!!e.time?.archived,wh=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=be(a.directory??null)??"";return`${us(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=be(l??null),h=Vi(a).sort((C,w)=>Vr(C,w,e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(h.map(C=>[C.id,C])),g=new Map,m=new Map;h.forEach(C=>{const w=C.parentID??null,j=w?x.get(w):null,E=j&&Zo(j)===Zo(C)?w:null;g.set(C.id,E),E&&m.set(E,(m.get(E)??0)+1)});const p=c.map(C=>({worktree:C,directory:be(C.path)})).filter(C=>!!C.directory&&!C.worktree.isPrimary).sort((C,w)=>w.directory.length-C.directory.length),y=(C,w)=>w===C||w.startsWith(`${C}/`),b=C=>{const w=be(C.directory??null);return w?p.find(j=>y(j.directory,w))?.worktree??null:null},I=(C,w)=>{const j=bh(C.id,g,m);return{session:C,children:[],worktree:w,forkColorId:j}},v=[],k=new Map,S=[];for(const C of p)k.set(C.directory,[]);h.forEach(C=>{const w=b(C),j=I(C,w);C.time?.archived?S.push(j):w?k.get(be(w.path)??"")?.push(j):v.push(j)});const D=[{id:"root",label:d&&u&&u!=="HEAD"?`project root: ${u}`:"project root",branch:u??null,description:f?Bo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:v}];for(const{worktree:C,directory:w}of p)D.push({id:`worktree:${w}`,label:C.branch||(C.detached?"Detached HEAD":C.name),branch:C.branch,description:Bo(w,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:C,directory:w,folderScopeKey:w,sessions:k.get(w)??[]});return S.length>0&&D.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?Qi(f):null,sessions:S}),D},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},vh=({mobileVariant:e,isTablet:s})=>!e&&!s,Sh=({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])},jh=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((v,k,S)=>{Rr("navigation.session_select"),re.getState().closeMainSurfaces();const D=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},C=S?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===Ne.getState().currentSessionId){e.allowReselect&&C&&e.onSessionSelected?.(v),D();return}Rr("navigation.session_state_set"),e.setCurrentSession(v,k??null),C&&e.onSessionSelected?.(v),D()},[e]),a=i.useCallback((v,k)=>{e.setEditingId(v),e.setEditTitle(k)},[e]),l=i.useCallback(async v=>{if(!e.editingId)return;const k=(v??e.editTitle).trim();k&&await e.updateSessionTitle(e.editingId,k),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),u=i.useCallback(async(v,k)=>{try{return(await _s(v)).ok?(n(k),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),d=i.useCallback(async v=>{const k=await e.shareSession(v.id);if(!k?.share?.url){se.error("Unable to share session");return}const S=await u(k.share.url,v.id);se[S?"success":"warning"]("Session shared",{description:S?"Share link copied to clipboard.":"Failed to copy URL"})},[e,u]),f=i.useCallback((v,k)=>{u(v,k).then(S=>{S||se.error("Failed to copy URL")})},[u]),h=i.useCallback(v=>{_s(v).then(k=>{if(k.ok){se.success("Session ID copied");return}se.error("Failed to copy session ID")}).catch(()=>se.error("Failed to copy session ID"))},[]),x=i.useCallback(async v=>{await e.unshareSession(v)?se.success("Session unshared"):se.error("Unable to unshare session")},[e]),g=i.useCallback(v=>{const k=[],S=D=>{(e.childrenMap.get(D)??[]).forEach(w=>{k.push(w),S(w.id)})};return S(v),k},[e.childrenMap]),m=i.useCallback((v,k)=>k?v:v.filter(S=>!S.time?.archived),[]),p=i.useCallback(async(v,k,S)=>{const D=k?.archivedBucket===!0||k?.hardDelete===!0,C=S?.descendantIds??m(g(v.id),D).map(T=>T.id);if(C.length===0){(D?await e.deleteSession(v.id):await e.archiveSession(v.id))?se.success(D?"Session deleted":"Session archived"):se.error(D?"Failed to delete session":"Failed to archive session");return}const w=[v.id,...C];if(D){const{deletedIds:T,failedIds:U}=await e.deleteSessions(w);if(U.length===0){const _=T.length;se.success(_===1?`Deleted ${_} session`:`Deleted ${_} sessions`)}else se.error("Failed to delete session");return}const{archivedIds:j,failedIds:E}=await e.archiveSessions(w);j.length>0&&se.success(j.length===1?`Archived ${j.length} session`:`Archived ${j.length} sessions`),E.length>0&&se.error(E.length===1?`Failed to archive ${E.length} session`:`Failed to archive ${E.length} sessions`)},[e,g,m]),y=i.useCallback((v,k)=>{const S=k?.archivedBucket===!0||k?.hardDelete===!0,D=m(g(v.id),S).map(C=>C.id);if(!e.showDeletionDialog||k?.skipConfirm===!0){p(v,k,{descendantIds:D});return}e.setDeleteSessionConfirm({session:v,descendantCount:D.length,descendantIds:D,archivedBucket:S})},[e,g,p,m]),b=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,archivedBucket:k,descendantIds:S}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await p(v,{archivedBucket:k},{descendantIds:S})},[e,p]),I=i.useCallback(async v=>{await e.unarchiveSession(v.id)?se.success("Session restored"):se.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:d,handleCopyShareUrl:f,handleCopySessionId:h,handleUnshareSession:x,handleDeleteSession:y,handleRestoreSession:I,confirmDeleteSession:b}},kh=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 h=u.current;if(u.current=null,c.current=null,!h)return;const{projects:x}=ut.getState(),g=x.map(m=>({...m,sidebarCollapsed:h.has(m.id)}));Zr({projects:g}).catch(()=>{})},[]),f=i.useCallback(h=>{typeof window>"u"||(u.current=h,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 h=s.getItem(n.sessionExpanded);if(h){const g=JSON.parse(h);Array.isArray(g)&&a(new Set(g.filter(m=>typeof m=="string")))}const x=s.getItem(n.projectCollapse);if(x){const g=JSON.parse(x);Array.isArray(g)&&l(new Set(g.filter(m=>typeof m=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const h=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(h))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:f}},Ch=3;let zn=0;const Ta=[],Nh=()=>zn<Ch?(zn+=1,Promise.resolve()):new Promise(e=>{Ta.push(e)}),Ah=()=>{const e=Ta.shift();if(e){e();return}zn=Math.max(0,zn-1)},Ih=async e=>{await Nh();try{return await e()}finally{Ah()}},Dh=5*6e4,Rh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=Ws(),c=Mi(h=>h.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(h=>{Ih(()=>c(h.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const h=new Map;s.forEach(x=>{h.set(x.id,r.get(x.normalizedPath)?.isGitRepo??null)}),o(h)},[n,s,r,o]);const u=i.useMemo(()=>s.map(h=>{const x=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${x}`}).join("|"),[s,r]),d=i.useRef(new Map),f=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let h=!1;const x=setTimeout(()=>{(async()=>{const m=new Set(s.map(v=>v.id));for(const v of d.current.keys())m.has(v)||(d.current.delete(v),f.current.delete(v));const p=Date.now();if(s.filter(v=>{const k=r.get(v.normalizedPath);if(k?.isGitRepo===!1)return d.current.delete(v.id),f.current.delete(v.id),!1;if(k?.isGitRepo!==!0||k.branch===null)return!1;const S=k.branch.trim(),D=`${v.normalizedPath}\0${S}`,C=d.current.get(v.id);if(C===D){const w=f.current.get(v.id);return w&&(w.at=p),!1}return!(C!==void 0&&p-(f.current.get(v.id)?.at??0)<Dh)}).length===0)return;const b=[];if(s.forEach(v=>{const k=r.get(v.normalizedPath)?.branch?.trim()??"",S=`${v.normalizedPath}\0${k}`;k&&b.push({id:v.id,inputKey:S,branch:k})}),h||b.length===0)return;const I=Date.now();a(v=>{const k=new Map(v);return b.forEach(({id:S,branch:D})=>{D&&k.set(S,D)}),k}),b.forEach(({id:v,inputKey:k,branch:S})=>{d.current.set(v,k),S&&f.current.set(v,{branch:S,at:I})})})()},150);return()=>{h=!0,clearTimeout(x)}},[n,s,u,r,a])},Eh=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}},Ph=e=>{if(e.runtimeKey!==Wn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=Kd(e.sessionId,e.directory,e.runtimeKey);s&&Hd.getState().clearQueue(s),at.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),Ar.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Uc(e.runtimeKey,e.directory,e.sessionId);n&&$c(n,!0),Gc.getState().clearStashedAttachmentsForSession(e)},Mh=e=>{const s=new Map;for(const n of e){const r=Os(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Th=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},Fh=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Wn(),l=Mh(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const u of Th(c,l))Ph({runtimeKey:a,...u});o.current={runtimeKey:a,identities:l}},[s,n,r])},Lh=(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,ei=(e,s,n)=>{Lh(e.get(s),n)&&e.set(s,n)},Fa=e=>{const s=e;return be(s.directory)??be(s.project?.worktree)},Oh=(e,s,n)=>{if(e.time?.archived)return!0;const r=Fa(e);if(!r)return n?.allowUnknownDirectory??!0;if(Hn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const a of s)if(be(a)?.toLowerCase()===o)return!0;return!1},Bh=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)},_h=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const g of s){const m=be(g.normalizedPath);if(!m)continue;const p=a.get(m);(!p||g.id.localeCompare(p.id)<0)&&a.set(m,g),ei(o,m,{projectId:g.id,projectRoot:m,scopeDirectory:m,kind:"project"})}if(n)for(const[g,m]of n){const p=be(g),y=p?a.get(p):void 0;if(!(!y||!p))for(const b of m||[]){const I=be(b?.path);I&&ei(o,I,{projectId:y.id,projectRoot:p,scopeDirectory:I,kind:"worktree"})}}const l=new Map,c=new Map,u=new Map,d=new Map,f=new Map,h=g=>{if(!g)return null;if(l.has(g))return l.get(g)??null;const m=[];let p=g,y=null;for(;p;){if(l.has(p)){y=l.get(p)??null;break}if(m.push(p),y=o.get(p)??null,y)break;p=Bh(p)}for(const b of m)l.set(b,y);return y},x=(g,m,p)=>{for(const y of g){const b=Fa(y);if(Hn(b))continue;const I=h(b);if(!I)continue;c.set(y.id,I);const v=m.get(I.projectId);if(v?v.push(y):m.set(I.projectId,[y]),!p)continue;const k=p.get(I.scopeDirectory);k?k.add(y.id):p.set(I.scopeDirectory,new Set([y.id]))}};return x(e,u,f),x(r,d),{bySessionId:c,sessionsByProject:u,archivedSessionsByProject:d,sessionsByScope:f,directoryResolutions:l.size}};function La({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:z("inline-flex items-center",r),"aria-label":n??s,title:n??s,children:t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):t.jsx("span",{className:z("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const zh=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:u,renderSessionNode:d,getRenderExtras:f,groupDirectory:h,projectId:x,mobileVariant:g=!1,alwaysShowActions:m=g,isRenaming:p=!1,renameDraft:y="",onRenameDraftChange:b,onRenameSave:I,onRenameCancel:v,droppableRef:k,isDropTarget:S=!1,onNewSession:D,depth:C=0,hideActions:w=!1,archivedBucket:j=!1})=>{const[E,T]=i.useState(!1),[U,_]=i.useState(""),$=i.useRef(null),K=p||E,P=p?y:U,B=i.useCallback(()=>{_(e.name),T(!0)},[e.name]),R=i.useCallback(()=>{const M=P.trim();M&&M!==e.name&&c(M),p&&I&&I(),T(!1),_("")},[P,e.name,p,c,I]),F=i.useCallback(()=>{p&&v&&v(),T(!1),_("")},[p,v]),Q=i.useCallback(M=>{p&&b?b(M):_(M)},[p,b]);i.useEffect(()=>{if(!p)return;const M=()=>{const ye=$.current;ye&&(ye.focus(),ye.select())},ee=requestAnimationFrame(M),H=window.setTimeout(M,0);return()=>{cancelAnimationFrame(ee),window.clearTimeout(H)}},[p]);const G=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:k,className:z("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",S&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:K?void 0:M=>{M.currentTarget.blur(),l()},role:K?void 0:"button",tabIndex:K?void 0:0,onKeyDown:K?void 0:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:z("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",j?m?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":m?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(A,{name:G,className:z(Rn,S?"text-primary":"text-muted-foreground")}),K?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),onSubmit:M=>{M.preventDefault(),R()},children:[t.jsx("input",{ref:$,value:P,onChange:M=>Q(M.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:M=>M.stopPropagation(),onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),onKeyDown:M=>{if(M.key==="Escape"){M.stopPropagation(),F();return}(M.key===" "||M.key==="Enter")&&M.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:M=>M.stopPropagation(),onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),children:t.jsx(A,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),F()},onPointerDown:M=>M.stopPropagation(),onMouseDown:M=>M.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(A,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("span",{className:z(Ji,S?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(Le,{side:"right",sideOffset:8,className:"max-w-xs",children:s??e.name})]}),t.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),a?t.jsx(La,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(A,{name:"arrow-right-s",className:z(Rn,"text-muted-foreground")}):t.jsx(A,{name:"arrow-down-s",className:z(Rn,"text-muted-foreground")})]})]}),!K&&(!w||j)?t.jsx("div",{className:z("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",m?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:t.jsxs("div",{className:"flex items-center gap-0.5",children:[!j&&D?t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),D()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-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(A,{name:"add",className:"size-4"})}):null,j?null:t.jsx("button",{type:"button",onClick:M=>{M.stopPropagation(),B()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:t.jsx(A,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:M=>{M.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":j?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(A,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(M=>t.jsx(i.Fragment,{children:d(M,0,h??null,x??null,j,void 0,"project",f?.(M))},M.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Uh=i.memo(zh),$h=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=Nu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),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})},Gh=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Au({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},Kh=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=so(On(oa,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,u]=i.useState("Session"),[d,f]=i.useState(null),[h,x]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const g=m=>{l(null),f(null),x(null);const{active:p,over:y}=m;if(!y)return;const b=p.data.current,I=y.data.current;b?.type==="session"&&b.sessionId&&I?.type==="folder"&&I.folderId&&n(b.sessionId,I.folderId)};return t.jsxs(no,{sensors:o,collisionDetection:ro,onDragStart:m=>{const p=m.active.data.current;if(p?.type==="session"&&p.sessionId){l(p.sessionId),u(p.sessionTitle??"Session");const y=m.active.rect.current.initial?.width,b=m.active.rect.current.initial?.height;f(typeof y=="number"?y:null),x(typeof b=="number"?b:null)}},onDragCancel:()=>{l(null),f(null),x(null)},onDragEnd:g,children:[r,t.jsx(ia,{children:a&&s?t.jsxs("div",{style:{width:d?`${d}px`:"auto",height:h?`${h}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[t.jsx(A,{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})]})},ks=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:z(o?uu:fu,r),children:[t.jsx(A,{name:e,className:z(un(o),"text-muted-foreground")}),t.jsx("span",{className:z(fn(o),"flex-1 text-muted-foreground"),children:s})]}),ti=(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},Hh=(e,s,n)=>{const r=new Map,o=a=>{const l=Os(a.session)??n;if(l){const c=r.get(l)??[];c.push(a.session.id),r.set(l,c)}if(!(a===e&&s))for(const c of a.children)o(c)};return o(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},Wh=(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})},si=new WeakMap;let ni=1;const Yh=e=>{const s=si.get(e);if(s!==void 0)return s;const n=ni;return ni+=1,si.set(e,n),n},Kr=e=>e.children.length===0?"":e.children.map(n=>{const r=Yh(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Kr(n)}`}).join("|"),Oa=(e,s,n,r,o,a)=>{const l=Wn(),c=(u,d)=>{if(u.session.id!==d.session.id||u.children.length!==d.children.length)return!0;const f=u.session.directory??o,h=d.session.directory??a,x=Fo(l,f??"",u.session.id),g=Fo(l,h??"",d.session.id);return(x?n.has(x):!1)!==(g?r.has(g):!1)?!0:u.children.some((m,p)=>c(m,d.children[p]))};return c(e,s)},Un=(e,s,n,r)=>{if(!s)return null;const o=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${o}:${c.session.id}`===s)return a=c.session.id,!0;for(const d of c.children)if(l(d))return!0;return!1};return e.forEach(c=>l(c)),a},Ba=(e,s)=>"",qh=ps(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),_a=e=>null,ao=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,za=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let o=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(o="unread");for(const l of e.children)if(o=ao(o,za(l,s,n,r)),o==="active")return o;return o},Ua=(e,s,n,r)=>{let o=null;for(const a of e)if(o=ao(o,za(a,s,n,r)),o==="active")return o;return o},Qh=50,Vh=28;function Jh({visibleSessions:e,shouldVirtualize:s,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:a,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:u}){const d=i.useRef(null),[f,h]=i.useState(null),[x,g]=i.useState(0),[,m]=i.useState(0);i.useEffect(()=>{if(!s)return;const b=d.current;if(!b||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>m(v=>v+1));return I.observe(b),()=>I.disconnect()},[s]),i.useLayoutEffect(()=>{if(!s){f!==null&&h(null),x!==0&&g(0);return}const b=d.current;if(!b)return;let I=f;const v=r?.current??null;if(v&&v.contains(b)){if(I=v,I!==f){h(I);return}}else if(!I||!I.contains(b)){let S=b.parentElement;for(;S;){const D=window.getComputedStyle(S);if(D.overflowY==="auto"||D.overflowY==="scroll"){I=S;break}S=S.parentElement}if(I!==f){h(I);return}}if(!I)return;const k=b.getBoundingClientRect().top-I.getBoundingClientRect().top+I.scrollTop;g(S=>Math.abs(S-k)<1?S:k)},[f,x,r,s]);const p=s&&f!==null,y=Ru({count:e.length,enabled:p,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>Vh,overscan:n?20:8,scrollMargin:x,getItemKey:b=>e[b]?.session.id??b});return t.jsx("div",{ref:d,children:s?t.jsx("div",{style:{height:y.getTotalSize(),position:"relative"},children:y.getVirtualItems().map(b=>{const I=e[b.index];return I?t.jsx("div",{"data-index":b.index,ref:y.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${b.start-x}px)`},children:c(I,0,o,a,l,void 0,"project",u(I))},I.session.id):null})}):e.map(b=>t.jsx(i.Fragment,{children:c(b,0,o,a,l,void 0,"project",u(b))},b.session.id))})}const Mn=(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 Xh({group:e,groupKey:s,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:a,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:u,groupPrSummary:d,groupActivityIndicator:f,showBranchSubtitle:h,statusLine:x,allGroupSessions:g,projectId:m,activeProjectId:p,setActiveProjectIdOnly:y,setActiveMainTab:b,mobileVariant:I,setSessionSwitcherOpen:v,openNewSessionDraft:k}){return t.jsxs("div",{className:z("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(s),role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),r(s))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[t.jsx("div",{ref:c?.setActivatorNodeRef,className:z("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.listeners??{},children:t.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[t.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:e.isArchivedBucket?t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(A,{name:"archive",className:z("size-4 shrink-0 text-muted-foreground",a?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:z("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(A,{name:"arrow-right-s",className:"size-4"}):t.jsx(A,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:Mn(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(A,{name:"git-branch",className:z("size-4 shrink-0",!u&&"text-muted-foreground",a?"hidden":"group-hover/gh:hidden"),style:u?{color:u}:void 0}),t.jsx("span",{className:z("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(A,{name:"arrow-right-s",className:"size-4"}):t.jsx(A,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Mn(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:Mn(e.label,o)}),f]})}),h&&x?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?t.jsx(A,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(A,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),t.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:x.label})]}):null]})}),e.isArchivedBucket&&g.length>0?t.jsx("div",{className:z("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),Cs.requestDelete({sessions:g,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${e.label}`,children:t.jsx(A,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?t.jsx("div",{className:z("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),m&&m!==p&&y(m),b("chat"),I&&v(!1),k({selectedProjectId:m,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:t.jsx(A,{name:"add",className:"h-4 w-4"})})}),t.jsx(Le,{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,Zh=(e,s,n)=>e.sessions.some(r=>Oa(r,r,s,n,e.directory,e.directory)),ep=(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)},ri=(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)},tp=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},sp=(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)},np=(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&&Zh(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&sp(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&ep(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=Un(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Un(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&ri(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&ri(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&tp(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 rp({group:e,isCollapsed:s}){const n=Ti(),r=i.useMemo(()=>{const x=e.folderScopes?.map(g=>be(g.directory))??[be(e.directory??null)];return[...new Set(x.filter(g=>!!g))]},[e.directory,e.folderScopes]);i.useSyncExternalStore(i.useCallback(x=>r.length>0?n.subscribeBootstrap(x):()=>{},[r.length,n]),i.useCallback(()=>r.map(x=>`${x}\0${n.getBootstrapState(x)??""}\0${n.getBootstrapFailure(x)??""}`).join(""),[r,n]),i.useCallback(()=>"",[]));const o=r.some(x=>{const g=n.getBootstrapState(x);return g==="queued"||g==="running"}),a=r.find(x=>n.getBootstrapState(x)==="failed")??null,l=a?n.getBootstrapFailure(a):void 0,c=l==="os-permission"&&Jr(),[u,d]=i.useState(!1),f=i.useCallback(()=>{a&&n.requestBootstrap({directory:a,priority:s?"visible":"expanded",reason:e.isMain?"project-expanded":"worktree-expanded",force:!0})},[n,a,e.isMain,s]),h=i.useCallback(async()=>{if(!(!a||!c||u)){d(!0);try{(await Xr(a)).success&&f()}finally{d(!1)}}},[c,a,u,f]);return{bootstrapLoading:o,failedBootstrapDirectory:a,bootstrapFailure:l,canGrantBootstrapAccess:c,isRequestingBootstrapAccess:u,retryFailedBootstrap:f,grantFailedBootstrapAccess:h}}function op({group:e,sourceGroupNodes:s,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:a,unreadActivitySessionIds:l,notifyOnSubtasks:c,collectGroupSessions:u}){const d=at(D=>D.foldersMap),f=e.folderScopeKey??be(e.directory??null),h=i.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=i.useMemo(()=>h.flatMap(({scopeKey:D,directory:C})=>(d[D]??[]).map(w=>({folder:w,scopeKey:D,scopeDirectory:C}))),[h,d]),g=i.useMemo(()=>{const D=new Map,C=w=>{w.forEach(j=>{D.set(j.session.id,j),j.children.length>0&&C(j.children)})};return C(s),D},[s]),m=i.useMemo(()=>x.map(({folder:D,scopeKey:C,scopeDirectory:w})=>{const j=Wh(D.sessionIds,g).sort(o);return{folder:D,scopeKey:C,scopeDirectory:w,nodes:j}}),[x,g,o]),p=i.useMemo(()=>{const D=new Map(m.map(E=>[E.folder.id,E])),C=new Map;for(const{folder:E}of m){if(!E.parentId)continue;const T=C.get(E.parentId);T?T.push(E.id):C.set(E.parentId,[E.id])}const w=new Map,j=E=>{const T=w.get(E);if(T!==void 0)return T;const U=D.get(E);if(!U)return w.set(E,!1),!1;const _=C.get(E)??[];if(e.isArchivedBucket&&U.nodes.length===0){const P=_.some(B=>j(B));return w.set(E,P),P}if(!n||U.folder.name.toLowerCase().includes(r)||U.nodes.length>0)return w.set(E,!0),!0;const K=_.some(P=>j(P));return w.set(E,K),K};return m.filter(({folder:E})=>j(E.id))},[m,e.isArchivedBucket,n,r]),y=i.useMemo(()=>new Set(p.flatMap(D=>D.folder.sessionIds)),[p]),b=i.useMemo(()=>s.filter(D=>!y.has(D.session.id)),[s,y]),I=i.useMemo(()=>p.filter(({folder:D})=>!D.parentId),[p]),v=i.useMemo(()=>{const D=new Map;return p.forEach(C=>{if(!C.folder.parentId)return;const w=D.get(C.folder.parentId)??[];w.push(C),D.set(C.folder.parentId,w)}),D},[p]),k=i.useMemo(()=>{const D=new Map(p.map(j=>[j.folder.id,j])),C=new Map,w=(j,E)=>{const T=C.get(j);if(T!==void 0)return T;if(E.has(j))return null;E.add(j);const U=D.get(j);let _=U?Ua(U.nodes,a,l,c):null;for(const $ of v.get(j)??[])if(_=ao(_,w($.folder.id,E)),_==="active")break;return C.set(j,_),_};return p.forEach(({folder:j})=>w(j.id,new Set)),C},[a,p,v,c,l]),S=i.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const D=new Map,C=new Map;for(const{folder:j}of p){if(!j.parentId)continue;const E=C.get(j.parentId)??[];E.push(j.id),C.set(j.parentId,E)}const w=(j,E)=>{if(E.has(j))return[];E.add(j);const T=p.find(({folder:$})=>$.id===j),U=T?u(T.nodes):[],_=C.get(j)??[];for(const $ of _)U.push(...w($,E));return U};for(const{folder:j}of p)D.set(j.id,w(j.id,new Set));return D},[p,u,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:h,allFoldersForGroup:p,rootFolders:I,ungroupedSessions:b,folderActivityStateById:k,folderSessionsForDeleteById:S}}function ip(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:u,collapsedGroups:d,hideDirectoryControls:f,collapsedFolderIds:h,toggleFolderCollapse:x,renameFolder:g,deleteFolder:m,showDeletionDialog:p,setDeleteFolderConfirm:y,renderSessionNode:b,showMoreGroupSessions:I,resetGroupSessionLimit:v,mobileVariant:k,alwaysShowActions:S,activeProjectId:D,setActiveProjectIdOnly:C,setActiveMainTab:w,setSessionSwitcherOpen:j,openNewSessionDraft:E,addSessionToFolder:T,createFolderAndStartRename:U,renamingFolderId:_,renameFolderDraft:$,setRenameFolderDraft:K,setRenamingFolderId:P,pinnedSessionIds:B,expandedParents:R,sessionOrderIndex:F,editingId:Q,openSidebarMenuKey:G,activeActivitySessionIds:M,unreadActivitySessionIds:ee,notifyOnSubtasks:H,onToggleCollapsedGroup:ye,dragHandleProps:ce,compactBodyPadding:ae=!1,scrollContainerRef:xe}=e,we=i.useCallback((me,ze)=>{const pe=F.get(me.session.id),Be=F.get(ze.session.id);if(pe!==void 0||Be!==void 0){if(pe===void 0)return 1;if(Be===void 0)return-1;if(pe!==Be)return pe-Be}return Vr(me.session,ze.session,B,Fi)},[B,F]),ge=a?c.get(s):null,ve=a?!1:d.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const me=be(s.directory??null),ze=s.branch?.trim();return me&&ze?Ba():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const Se=_a(),ke=void 0,{bootstrapLoading:je,failedBootstrapDirectory:Z,bootstrapFailure:ue,canGrantBootstrapAccess:L,isRequestingBootstrapAccess:Y,retryFailedBootstrap:le,grantFailedBootstrapAccess:W}=rp({group:s,isCollapsed:ve}),X=f?10:5,te=Math.max(X,u??X),ne=a?ge?.groupMatches===!0:!1,Ae=a,Ie=i.useMemo(()=>[...Ae?ge?.filteredNodes??[]:s.sessions].sort(we),[we,s.sessions,ge?.filteredNodes,Ae]),Pe=i.useCallback(me=>{const ze=[],pe=Be=>{Be.forEach(_e=>{ze.push(_e.session),_e.children.length>0&&pe(_e.children)})};return pe(me),ze},[]),{folderScopeKey:De,folderScopes:Ge,allFoldersForGroup:de,rootFolders:Ue,ungroupedSessions:Ce,folderActivityStateById:Ye,folderSessionsForDeleteById:J}=op({group:s,sourceGroupNodes:Ie,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,compareSessionNodes:we,activeActivitySessionIds:M,unreadActivitySessionIds:ee,notifyOnSubtasks:H,collectGroupSessions:Pe}),Oe="project",We=i.useMemo(()=>{const me=new Set;return ti(Ie,Q,me),de.forEach(({nodes:ze})=>{ti(ze,Q,me)}),me},[Ie,de,Q]),$e=i.useMemo(()=>{if(!G)return null;const me=Un(Ie,G,Oe,!!s.isArchivedBucket);if(me)return me;for(const{nodes:ze}of de){const pe=Un(ze,G,Oe,!!s.isArchivedBucket);if(pe)return pe}return null},[G,Ie,de,s.isArchivedBucket]),Qe=i.useCallback(me=>{const ze=new WeakMap,pe=Be=>{ze.set(Be,Kr(Be));for(const _e of Be.children)pe(_e)};return me.forEach(pe),ze},[]),xt=i.useMemo(()=>Qe(Ie),[Qe,Ie]),Ht=i.useMemo(()=>{const me=new WeakMap;return de.forEach(({nodes:ze})=>{ze.forEach(pe=>me.set(pe,Kr(pe)))}),me},[de]),ot=i.useCallback(me=>xt.get(me)??Ht.get(me)??"",[xt,Ht]),Xe=i.useCallback(me=>({subtreeContainsEditing:We,menuOpenSessionId:$e,nodeStructureKey:ot(me)}),[We,$e,ot]),bt=Ce.length,et=s.isArchivedBucket||a?Ce:Ce.slice(0,te),tt=bt-et.length,Nt=!s.isArchivedBucket&&!a&&bt>X&&tt===0,Wt=s.isArchivedBucket===!0&&!a&&et.length>=Qh,ft=s.isArchivedBucket?"archived":"active",qe=Wt&&et.some(me=>{if(me.children.length===0)return!1;const ze=`project:${ft}:${me.session.id}`;return R.has(ze)}),yt=i.useMemo(()=>Pe(Ie),[Pe,Ie]);if(a&&!ne&&Ue.length===0&&Ce.length===0)return null;const At=!s.isMain&&!!s.branch,Ot=s.branch&&hu(s.branch,s.label)?{label:s.branch,color:null}:null,ht=ve?Ua(Ie,M,ee,H):null,Yt=ht?t.jsx(La,{state:ht,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Bt=(me,ze)=>{const{folder:pe,scopeKey:Be,scopeDirectory:_e,nodes:ct}=me,pt=J.get(pe.id)??[],Dt=a?!1:h.has(pe.id);return t.jsx(Gh,{folderId:pe.id,children:(mt,Tt)=>t.jsx(Uh,{folder:pe,displayName:ze,sessions:ct,isCollapsed:Dt,collapsedActivityState:Dt?Ye.get(pe.id)??null:null,onToggle:()=>x(pe.id),onRename:st=>{g(Be,pe.id,st)},onDelete:()=>{if(s.isArchivedBucket){Cs.requestDelete({sessions:pt,mode:"session"});return}if(!p){m(Be,pe.id);return}const st=de.filter(({folder:Qt})=>Qt.parentId===pe.id).length,ms=ct.length;y({scopeKey:Be,folderId:pe.id,folderName:pe.name,subFolderCount:st,sessionCount:ms})},renderSessionNode:b,getRenderExtras:ot?st=>({subtreeContainsEditing:We,menuOpenSessionId:$e,nodeStructureKey:ot(st),childRenderExtrasFor:Xe}):void 0,groupDirectory:_e??s.directory,projectId:r,mobileVariant:k,alwaysShowActions:S,isRenaming:_===pe.id,renameDraft:_===pe.id?$:void 0,onRenameDraftChange:st=>K(st),onRenameSave:()=>{const st=$.trim();st&&g(Be,pe.id,st),P(null),K("")},onRenameCancel:()=>{P(null),K("")},droppableRef:mt,isDropTarget:Tt,depth:0,onNewSession:()=>{r&&r!==D&&C(r),w("chat"),k&&j(!1),E({selectedProjectId:r,directoryOverride:_e??s.directory,targetFolderId:pe.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},pe.id)},It=()=>{const me=new Map;for(const Be of de){const _e=Be.folder.parentId;if(!_e)continue;const ct=me.get(_e);ct?ct.push(Be):me.set(_e,[Be])}const ze=[],pe=(Be,_e)=>{const ct=_e?`${_e} / ${Be.folder.name}`:Be.folder.name;ze.push(Bt(Be,ct)),!(!a&&h.has(Be.folder.id))&&(me.get(Be.folder.id)??[]).forEach(Dt=>pe(Dt,ct))};return Ue.forEach(Be=>pe(Be,"")),ze},qt=S?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",_t=Z?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[ue==="os-permission"?"Folder access is required.":"Could not refresh sessions.",L?t.jsx(Re,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:Y,onClick:()=>{W()},children:"Grant access"}):null,t.jsx(Re,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:le,children:"Try again"})]}):null,ns=t.jsxs(Kh,{scopeKey:Ge[0]?.scopeKey??De,hasFolders:de.length>0,onSessionDroppedOnFolder:(me,ze)=>{const pe=de.find(({folder:_e})=>_e.id===ze);if(!pe)return;const Be=at.getState();for(const{scopeKey:_e}of Ge)_e!==pe.scopeKey&&Be.getSessionFolderId(_e,me)&&Be.removeSessionFromFolder(_e,me);T(pe.scopeKey,ze,me)},children:[It(),s.isArchivedBucket?t.jsx(Jh,{visibleSessions:et,shouldVirtualize:Wt,hasExpandedParent:qe,scrollContainerRef:xe,groupDirectory:s.directory,projectId:r,isArchivedBucket:s.isArchivedBucket===!0,renderSessionNode:b,getRenderExtras:me=>({subtreeContainsEditing:We,menuOpenSessionId:$e,nodeStructureKey:ot(me),childRenderExtrasFor:Xe})}):et.map(me=>t.jsx(i.Fragment,{children:b(me,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:We,menuOpenSessionId:$e,nodeStructureKey:ot(me),childRenderExtrasFor:Xe})},me.session.id)),bt===0&&de.length===0?s.isArchivedBucket?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):je?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:t.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t.jsx(A,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):_t?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:_t}):t.jsx(ks,{icon:"chat-new",onClick:()=>{E({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,bt>0&&_t?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:_t}):null,tt>0?t.jsx(ks,{icon:"arrow-down-s",onClick:()=>I(n,et.length),children:tt===1?"Show 1 more session":`Show ${tt} more sessions`}):null,Nt?t.jsx(ks,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:ns})}):t.jsxs("div",{className:"oc-group",children:[t.jsx(Xh,{group:s,groupKey:n,isCollapsed:ve,onToggleCollapsedGroup:ye,normalizedSessionSearchQuery:l,alwaysShowActions:S,groupHeaderRightPadding:qt,dragHandleProps:ce,groupPrColor:ke,groupPrSummary:Se,groupActivityIndicator:Yt,showBranchSubtitle:At,statusLine:Ot,allGroupSessions:yt,projectId:r,activeProjectId:D,setActiveProjectIdOnly:C,setActiveMainTab:w,mobileVariant:k,setSessionSwitcherOpen:j,openNewSessionDraft:E}),ve?null:t.jsx("div",{className:"oc-group-body",children:ns})]})}const ap=i.memo(ip,np);function lp(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:u,headerActionButtonClass:d,isSessionSearchOpen:f,setIsSessionSearchOpen:h,sessionSearchInputRef:x,sessionSearchQuery:g,setSessionSearchQuery:m,hasSessionSearchQuery:p,searchMatchCount:y,selectionModeEnabled:b,onToggleSelectionMode:I,mobileVariant:v=!1}=e;if(s)return null;const k=z(d,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return t.jsx("div",{className:z("select-none flex-shrink-0",v?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:z("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:z("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:z("flex min-w-0 items-center",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[o?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:k,"aria-label":"Settings",children:t.jsx(A,{name:"settings-3",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!v&&a?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:k,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(A,{name:"server",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:k,"aria-label":"Update",children:t.jsx(A,{name:"download",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,v?null:t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:k,"aria-label":"Add project",children:t.jsx(A,{name:"folder-add",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),v?null:t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:k,"aria-label":"Archive",children:t.jsx(A,{name:"archive",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:z("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>h(S=>!S),className:k,"aria-label":"Search sessions","aria-expanded":f,children:t.jsx(A,{name:"search",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:I,className:z(k,b&&"bg-interactive-hover text-primary"),"aria-label":b?"Exit selection":"Select sessions","aria-pressed":b,children:t.jsx(A,{name:"checkbox-multiple",className:u})})}),t.jsx(Le,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:b?"Exit selection":"Select sessions"})})]})]})]}),f?t.jsxs("div",{className:z(v?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:p?t.jsx("span",{children:y===1?`${y} match`:`${y} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(A,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{ref:x,value:g,onChange:S=>m(S.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:S=>{S.key==="Escape"&&(S.stopPropagation(),p?m(""):h(!1))}}),g.length>0?t.jsx("button",{type:"button",onClick:()=>m(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:t.jsx(A,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function cp(e){const s=re(o=>o.toggleSidebar),n=re(o=>o.shortcutOverrides),r=eo(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, ${zo})`}}),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, ${zo})))`}}),t.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsxs("button",{type:"button",onClick:e.onNewSession,className:z("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),children:[t.jsx(A,{name:"chat-new",className:z(Rn,"text-current")}),t.jsx("span",{className:Ji,children:"New session"})]}),e.showSidebarToggle?t.jsxs(Te,{children:[t.jsx(Fe,{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(A,{name:"layout-left",className:"size-4"})})}),t.jsx(Le,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const $a=500,dp=({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),h=i.useCallback(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]);i.useEffect(()=>()=>h(),[h]);const x=i.useCallback(()=>{h(),d.current=window.setTimeout(()=>{d.current=null,u(!0)},$a)},[h]);return t.jsxs(Ia,{open:c,onOpenChange:u,children:[t.jsxs(Da,{render:t.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:h,onTouchEnd:h,onTouchCancel:h,style:{touchAction:"manipulation"},className:z($n(l,n),"pl-6"),"aria-pressed":n,title:s.path}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx(A,{name:"git-branch",className:z(un(l),"text-muted-foreground")}),t.jsx("span",{className:fn(l),children:f})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsx(Ra,{className:"min-w-[160px]",children:t.jsxs(Gr,{disabled:!a,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>a?.(e,s),className:"text-destructive focus:text-destructive",children:[t.jsx(A,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close worktree"})]})})]})},$n=(e,s)=>z("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),up=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:a,isExpanded:l,canDrag:c,onSelect:u,onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:h=!1})=>{const{listeners:x,setNodeRef:g,transform:m,transition:p,isDragging:y}=la({id:e.id,disabled:!c}),[b,I]=i.useState(!1),v=i.useRef(null),k=i.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);i.useEffect(()=>()=>k(),[k]);const S=i.useCallback(()=>{k(),v.current=window.setTimeout(()=>{v.current=null,I(!0)},$a)},[k]);return t.jsx("div",{ref:g,style:{transform:ca.Translate.toString(m),transition:p},className:z(y&&"opacity-60"),children:t.jsxs(Ia,{open:b,onOpenChange:I,children:[t.jsxs(Da,{render:t.jsx("button",{type:"button",onClick:()=>{b||u()},onTouchStart:S,onTouchMove:k,onTouchEnd:k,onTouchCancel:k,style:{touchAction:"manipulation"},className:$n(h,n),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:z("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${s}`:void 0,...c?x:{},children:t.jsx(A,{name:"folder",className:z(un(h),"text-muted-foreground")})}),t.jsx("span",{className:fn(h),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(Ds,{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(A,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?t.jsx(A,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(Ra,{className:"min-w-[160px]",children:[t.jsxs(Gr,{onClick:()=>d(e.id),children:[t.jsx(A,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(eh,{}),t.jsxs(Gr,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(A,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},fp=({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:h,activeDirectoriesByProject:x,homeDirectory:g,className:m,mobileVariant:p=!1})=>{const y=s===null,b=ut(S=>S.reorderProjects),I=e.length>1,v=so(On(Du,{activationConstraint:{distance:8}}),On(Iu,{activationConstraint:{delay:200,tolerance:6}})),k=i.useCallback(S=>{const{active:D,over:C}=S;if(!C||D.id===C.id)return;const w=ut.getState().projects,j=w.findIndex(T=>T.id===D.id),E=w.findIndex(T=>T.id===C.id);j<0||E<0||b(j,E)},[b]);return t.jsxs("div",{className:z("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:$n(p,y),"aria-pressed":y,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(A,{name:"chat-history",className:un(p)}),t.jsx("span",{className:fn(p),children:"All sessions"})]})}),t.jsx(no,{sensors:v,collisionDetection:ro,onDragEnd:k,children:t.jsx(aa,{items:e.map(S=>S.id),strategy:Eu,children:e.map(S=>{const D=s===S.id,C=D&&!n,w=r.get(S.normalizedPath)??[],j=Yn(S.label?.trim()||Gs(S.normalizedPath,g)||S.normalizedPath),E=x?.get(S.id),T=be(S.normalizedPath)?.toLowerCase()??"",U=T?E?.has(T)??!1:!1,_=(E?.size??0)>0,$=h?.(S.id)??!1,K=x?D?U:_:$;return t.jsxs(i.Fragment,{children:[t.jsx(up,{project:S,label:j,isSelected:C,hasActive:K,hasWorktrees:w.length>0,worktreeError:o.get(S.normalizedPath),isExpanded:D,canDrag:I,onSelect:()=>a(S.id),onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:p}),D?w.map(P=>{const B=n===P.path,R=be(P.path)?.toLowerCase()??"",F=R?E?.has(R)??!1:!1,Q=x?F:!1;return t.jsx(dp,{projectId:S.id,worktree:P,isSelected:B,hasActive:Q,onSelect:()=>l?.(S.id,P.path),onClose:c,mobileVariant:p},P.path)}):null]},S.id)})})}),t.jsxs("button",{type:"button",onClick:u,className:$n(p,!1),children:[t.jsx(A,{name:"add",className:un(p)}),t.jsx("span",{className:fn(p),children:"Add folder"})]})]})},cr="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function hp({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(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:cr,"aria-label":"Settings",children:t.jsx(A,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(Le,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:cr,"aria-label":"Shortcuts",children:t.jsx(A,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(Le,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:cr,"aria-label":"About PiChamber",children:t.jsx(A,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(Le,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Re,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:r,children:"Update"}):null]})}const pp=(e,s)=>Yn(e.label?.trim()||Gs(e.normalizedPath,s)||e.normalizedPath);function mp(e){Lt("ui.sidebar_projects_list.render");const s=i.useRef(new Map),n=i.useRef(e.getOrderedGroups);n.current!==e.getOrderedGroups&&(n.current=e.getOrderedGroups,s.current.clear());const r=(h,x)=>{const g=s.current,m=g.get(h);if(m&&m.groups===x)return m.ordered;const p=e.getOrderedGroups(h,x);if(g.set(h,{groups:x,ordered:p}),g.size>256){const y=g.keys().next().value;y!==void 0&&g.delete(y)}return p},o=i.useRef(null),a=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const h=[],x=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const g of x){const m=pp(g.project,e.homeDirectory);for(const p of g.groups)if(!p.isArchivedBucket)for(const y of p.sessions){const b=!!e.pinnedSessionIds?.has(y.session.id),I=y.session.time?.updated||y.session.time?.created||0;h.push({node:y,project:g.project,projectLabel:m,isPinned:b,timestamp:I,globalSession:g===e.allFoldersOnlySection})}}return h.sort((g,m)=>g.isPinned!==m.isPinned?g.isPinned?-1:1:m.timestamp-g.timestamp),h},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=i.useState(30);i.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const u=a.slice(0,l),d=a.length-u.length;if(e.sharedSessionsOnly)return t.jsx(ws,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("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(ws,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("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(ws,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("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(ws,{ref:o,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:z("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.showOnlyMainWorkspace?t.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const h=e.sectionsForRender.find(p=>p.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!h)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const x=h.groups.find(p=>p.isMain&&p.sessions.length>0)??h.groups.find(p=>p.sessions.length>0)??h.groups.find(p=>p.isMain)??h.groups[0];if(!x)return t.jsx(ks,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath}),children:"New session"});const g=h.groups.find(p=>p.isArchivedBucket);return[x,...g&&g.id!==x.id?[g]:[]].map(p=>{const y=`${h.project.id}:${p.id}`,b=p.id===x.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(p,y,h.project.id,b,null,!0,o)},y)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[u.map(({node:h,project:x,projectLabel:g,globalSession:m})=>{const p=h.session.directory??x.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(h,0,p,x.id,!1,{projectLabel:g,showFolderLabel:!0,globalSession:m},"project")},h.session.id)}),d>0?t.jsx(ks,{icon:"arrow-down-s",onClick:()=>c(h=>h+30),children:d===1?"Show 1 more session":`Show ${d} more sessions`}):null,l>30&&a.length>30?t.jsx(ks,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(h=>{const x=h.project.id,g=r(x,h.groups),m=g.find(y=>y.isMain)??null,p=m?g.filter(y=>y.id!==m.id):g;return t.jsxs("div",{children:[m?e.renderGroupSessions(m,`${x}:${m.id}`,x,!0,null,void 0,o):null,p.map(y=>{const b=`${x}:${y.id}`,I=g.length===1;return t.jsx(i.Fragment,{children:e.renderGroupSessions(y,b,x,I,null,void 0,o)},y.id)})]},x)})})]})})})}const gp=i.memo(mp);let Hr=!1;const Wr=new Set;let oi=!1;function xp(){for(const e of Wr)e()}function lo(e){Hr!==e&&(Hr=e,xp())}function bp(e){e.key==="Shift"&&lo(!0)}function yp(e){e.key==="Shift"&&lo(!1)}function wp(){lo(!1)}function vp(){oi||typeof window>"u"||(oi=!0,window.addEventListener("keydown",bp),window.addEventListener("keyup",yp),window.addEventListener("blur",wp))}function Sp(e){return vp(),Wr.add(e),()=>{Wr.delete(e)}}function jp(){return Hr}function kp(){return!1}function Cp(){return Me.useSyncExternalStore(Sp,jp,kp)}const Np=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:u}){const d=Cp(),f=d?n:s,h=x=>{if(d||x.shiftKey){u(x);return}c(x)};return t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:a,onMouseDown:l,onClick:h,onKeyDown:x=>x.stopPropagation(),children:t.jsx(A,{name:d?"delete-bin":"archive",className:o})})}),t.jsx(Le,{side:"left",sideOffset:8,children:f})]})}),Ap=i.memo(function({open:s,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,onExport:l}){return t.jsx(Gt,{open:s,onOpenChange:n,children:t.jsxs(Kt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:"Export Markdown"}),t.jsx(hs,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} sub-agent tasks. Include them in the export?`})]}),t.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:o,onChange:c=>a(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Is,{children:[t.jsx(Re,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Re,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function Ip(e,s){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:a,archivedBucket:l,isElectron:c,pendingRenameRef:u,handleCopySessionId:d,togglePinnedSession:f,handleExportSession:h,handleOpenMiniChatWindow:x,handleDeleteSession:g,handleRestoreSession:m}=e,{Item:p,Separator:y}=s;return t.jsxs(t.Fragment,{children:[t.jsxs(p,{onClick:()=>{u.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[t.jsx(A,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(p,{onClick:()=>d(n.id),className:"[&>svg]:mr-1",children:[t.jsx(A,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(p,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[a?t.jsx(A,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(A,{name:"pushpin",className:"mr-1 h-4 w-4"}),a?"Unpin session":"Pin session"]}),t.jsxs(p,{onClick:()=>{h()},className:"[&>svg]:mr-1",children:[t.jsx(A,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?t.jsxs(p,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[t.jsx(A,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(y,{}),l?null:t.jsxs(p,{className:"[&>svg]:mr-1",onClick:()=>g(n,{archivedBucket:l}),children:[t.jsx(A,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?t.jsxs(p,{className:"[&>svg]:mr-1",onClick:()=>m(n),children:[t.jsx(A,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(p,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>g(n,{archivedBucket:l,hardDelete:!0}),children:[t.jsx(A,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Dp(e){const{renamingFolderId:s,editingIdRef:n}=e;return t.jsx(ea,{children:t.jsx(ta,{className:"app-region-no-drag z-50",children:t.jsx(sa,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(s||n.current),style:{color:"var(--surface-elevated-foreground)"},className:z(Di,"min-w-[180px]"),children:Ip(e,{Item:({className:r,...o})=>t.jsx(na,{className:z(Ri,r),...o}),Separator:({className:r,...o})=>t.jsx(ra,{className:z(Ei,r),...o})})})})})}const dr=new WeakMap,Rp=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,Lt("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 Ep(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 Pp(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 Mp(e){const s=e.info.role==="user"?"User":"Assistant",n=Ep(e.info.time?.created),r=Pp(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
|
|
13
|
-
|
|
14
|
-
*${o}*`:`**${s}**`}function Tp(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Ga(e){const s=Mp(e),n=Tp(e.parts).trim();return n?`${s}
|
|
15
|
-
|
|
16
|
-
${n}`:""}function Ka(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
`,a=e.records.map(Ga).filter(Boolean).join(`
|
|
21
|
-
|
|
22
|
-
---
|
|
23
|
-
|
|
24
|
-
`),l=[o+a];for(const c of e.children)l.push(Ka(c,s+1));return l.join(`
|
|
25
|
-
|
|
26
|
-
---
|
|
27
|
-
|
|
28
|
-
`)}function Ha(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
29
|
-
|
|
30
|
-
*Exported on ${o}*
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
`,l=e.map(Ga).filter(Boolean).join(`
|
|
35
|
-
|
|
36
|
-
---
|
|
37
|
-
|
|
38
|
-
`);let c=a+l;if(n&&n.length>0){const u=n.map(d=>Ka(d,1)).join(`
|
|
39
|
-
|
|
40
|
-
---
|
|
41
|
-
|
|
42
|
-
`);c+=`
|
|
43
|
-
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
`+u}return c}function Wa(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function Ya(e,s){const n=await Wd(s,e);return n||null}async function Fp(e){const s=Zt()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await Yd(e)?!0:Ki(e)}function Lp(){return qd()}function qa(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const Gn=e=>{const s=[],n=r=>{r.children.forEach(o=>{s.push(o.session.id),n(o)})};return n(e),s};function Op(e,s){const n=Li(),[r,o]=i.useState(!1),[a,l]=i.useState(!0),c=e.session,u=i.useMemo(()=>Gn(e).length,[e]),d=i.useCallback(async g=>{const m=[];let p=0;for(const y of g)try{if(!s)throw new Error("Session directory is required for export");const b=Ir(n.getState(),y.session.id).list,I=y.session.title||"Untitled Sub-agent",v=typeof y.session.agent=="string"?y.session.agent:void 0,k=await d(y.children);p+=k.skipped,m.push({title:I,agent:v,records:b,children:k.children})}catch{p+=Gn(y).length+1}return{children:m,skipped:p}},[n,s]),f=i.useCallback(g=>{g<=0||se.warning(g===1?`Exported session, but skipped ${g} sub-agent task that could not be loaded.`:`Exported session, but skipped ${g} sub-agent tasks that could not be loaded.`)},[]),h=i.useCallback(async g=>{if(!s){se.error("Nothing to export");return}const m=Ir(n.getState(),c.id).list;if(m.length===0){se.error("Nothing to export");return}let p,y=0;if(g&&e.children.length>0){const k=await d(e.children);p=k.children,y=k.skipped}const b=Ha(m,c.title??null,p),I=qa(c.title??null),v=await Ya(b,I);if(v){se.success("Session exported",{action:{label:Lp(),onClick:()=>{Fp(v).then(k=>{k||se.error("Failed to reveal path")})}}}),f(y);return}Wa(b,I),se.success("Session exported"),f(y)},[d,n,e.children,c.id,c.title,s,f]),x=i.useCallback(async()=>{if(e.children.length>0){l(!0),o(!0);return}await h(!1)},[h,e.children.length]);return{exportDialogOpen:r,setExportDialogOpen:o,exportIncludeSubtasks:a,setExportIncludeSubtasks:l,descendantCount:u,handleExportSession:x,doExportSession:h}}const Bp=(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},lt=ps()((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 x of f)l.delete(x);u===n&&(u=null)}else{for(const x of f)l.add(x);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[h,x]=d<=f?[d,f]:[f,d],g=o.slice(h,x+1),m=Bp(g,l),y=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const b of m)y.add(b);e({selectedIds:y,scopeKey:a??c.scopeKey,anchorId: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}))}})),ii=e=>be(e.session.directory??null),_p=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),zp=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},An=e=>e.menuOpenSessionId??zp(e),In=(e,s,n)=>s?n.has(e.node.session.id)?!0:ts(e.node,s):!1,Yr=(e,s,n,r,o)=>{if(e.session.id!==s.session.id)return!0;const a=o(e);if(n.has(a)!==r.has(a)||e.children.length!==s.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(Yr(e.children[l],s.children[l],n,r,o))return!0;return!1},Up=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Yr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Yr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},$p=(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||ii(e.node)!==ii(s.node)||!_p(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Oa(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&Up(e,s)||e.editingId!==s.editingId&&(In(e,e.editingId,e.subtreeContainsEditing)||In(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(In(e,e.editingId,e.subtreeContainsEditing)||In(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=An(e),r=An(s);if(ts(e.node,n)||ts(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=An(e),r=An(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 Gp({node:e,groupDirectory:s,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:a,expansionKey:l,hasSessionSearchQuery:c,notifyOnSubtasks:u}){const d=e.session,f=be(d.directory??null)??be(s??null),h=Ne(je=>je.currentSessionId===d.id),x=Oi(f),g=Kc(f),m=ut(i.useCallback(je=>{if(r?.projectLabel||!n)return null;const Z=je.projects.find(ue=>ue.id===n);return Z?Z.label?.trim()||Gs(be(Z.path)??Z.path,null)||Z.path:null},[n,r?.projectLabel])),p=r?.projectLabel??(m?Yn(m):null),y=e.worktree,b=r?.branchLabel??y?.branch??(x&&x!=="HEAD"?x:null),I=b,v=g===!0||!!(b||y),k=e.children.length,S=d.agent;i.useMemo(()=>{const je=y?.branch?.trim()||b?.trim(),Z=be(y?.path??f);return je&&Z?Ba():null},[b,f,y]);const D=_a(),C=void 0,w=i.useMemo(()=>null,[D]),j=n??f??null,E=lt(je=>je.enabled),T=lt(i.useCallback(je=>je.selectedIds.has(d.id),[d.id])),U=lt(je=>je.toggleSelected),_=lt(je=>je.setRange),$=Hc(i.useCallback(je=>!!je.sessionMemoryState.get(Wc(d.id))?.isZombie,[d.id])),P=Bi(d.id)?.type??"idle",B=P==="busy"||P==="retry",R=Yc(d.id,B),F=qc(d.id),Q=us(d),G=e.children.length>0,M=Qc(o,f,d.id),ee=c?!0:a.has(l);i.useMemo(()=>Hh(e,ee,f),[ee,e,f]);const H=Jc(),ye=!!d.parentID,ae=Vc(d.id)>0&&(!ye||u),xe=d.time?.updated||d.time?.created||Date.now(),we=pu(xe),ge=i.useMemo(()=>Ma(e.forkColorId),[e.forkColorId]),ve=i.useMemo(()=>yh(e.forkColorId,{active:h||T}),[e.forkColorId,h,T]),Se=r?.globalSession&&!h&&!T?"var(--surface-elevated)":null;return{session:d,sessionDirectory:f,isActive:h,tooltipProjectLabel:p,tooltipBranchLabel:I,isGitRepo:v,subtaskCount:k,agentName:S,prSummary:D,prIconColor:C,prStatusLabel:w,selectionScopeKey:j,selectionModeEnabled:E,isRowSelected:T,toggleRowSelected:U,setRowRange:_,isZombie:$,isStreaming:B,hasActivityDuration:R,sessionPermissions:F,sessionTitle:Q,hasChildren:G,isPinnedSession:M,isExpanded:ee,pendingQuestionCount:H,needsAttention:ae,sessionCompactUpdatedLabel:we,forkSolid:ge,rowBackground:ve??Se}}function Kp(e){Lt("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:h,setEditingId:x,editTitle:g,setEditTitle:m,handleSaveEdit:p,handleCancelEdit:y,toggleParent:b,handleSessionSelect:I,handleSessionDoubleClick:v,togglePinnedSession:k,handleShareSession:S,copiedSessionId:D,handleCopyShareUrl:C,handleCopySessionId:w,handleUnshareSession:j,openSidebarMenuKey:E,setOpenSidebarMenuKey:T,renamingFolderId:U,getFoldersForScope:_,getSessionFolderId:$,removeSessionFromFolder:K,addSessionToFolder:P,createFolderAndStartRename:B,handleDeleteSession:R,handleRestoreSession:F,mobileVariant:Q,alwaysShowActions:G,allowQuickArchiveAction:M,renderSessionNode:ee,secondaryMeta:H,renderContext:ye="project",subtreeContainsEditing:ce,menuOpenSessionId:ae,childRenderExtrasFor:xe}=e,we=i.useMemo(()=>Hi(),[]),ge=!a&&M,ve=i.useRef(!1),Se=i.useRef(h);Se.current=h;const ke=i.useRef(null),je=i.useRef(p);je.current=p;const[Z,ue]=i.useState(g),L=i.useRef(Z);L.current=Z;const Y=i.useRef(null),le=i.useRef(null),X=`${ye}:${a?"archived":"active"}:${s.session.id}`,{session:te,sessionDirectory:ne,isActive:Ae,tooltipProjectLabel:Ie,tooltipBranchLabel:Pe,isGitRepo:De,subtaskCount:Ge,agentName:de,prSummary:Ue,selectionScopeKey:Ce,selectionModeEnabled:Ye,isRowSelected:J,toggleRowSelected:Oe,setRowRange:We,isZombie:$e,isStreaming:Qe,hasActivityDuration:xt,sessionPermissions:Ht,sessionTitle:ot,hasChildren:Xe,isPinnedSession:bt,isExpanded:et,pendingQuestionCount:tt,needsAttention:Nt,sessionCompactUpdatedLabel:Wt,forkSolid:ft,rowBackground:qe}=Gp({node:s,groupDirectory:r,projectId:o,secondaryMeta:H,pinnedSessionIds:l,expandedParents:c,expansionKey:X,hasSessionSearchQuery:u,notifyOnSubtasks:f}),{exportDialogOpen:yt,setExportDialogOpen:At,exportIncludeSubtasks:Ot,setExportIncludeSubtasks:ht,descendantCount:Yt,handleExportSession:Bt,doExportSession:It}=Op(s,ne),[qt,_t]=i.useState(!1),ns=i.useCallback(()=>{ne&&rn("desktop_open_session_mini_chat_window",{sessionId:te.id,directory:ne,apiBaseUrl:Pr(),clientToken:Er()}).catch(ie=>{console.warn("[session-sidebar] failed to open mini chat window",ie)})},[te.id,ne]);i.useEffect(()=>{if(h!==te.id)return;const ie=Ze=>{const is=Ze.target?.closest?.(`[data-session-rename-form="${CSS.escape(te.id)}"]`);le.current&&!is&&je.current(L.current)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[h,te.id]),i.useLayoutEffect(()=>{if(h!==te.id){Y.current===te.id&&(Y.current=null);return}Y.current!==te.id&&(Y.current=te.id,ue(g))},[h,g,te.id]);const me=Ht.length,ze=!Qe&&Nt&&!Ae,pe=Qe&&xt,Be=bt,_e=t.jsx(A,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),ct=Be?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:_e}):null,pt=Xe?t.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),b(X)},onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),ie.stopPropagation(),b(X))},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-label":et?"Collapse subsessions":"Expand subsessions",children:et?t.jsx(A,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(A,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Dt=$e?t.jsx(A,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,mt=ie=>{if(!ie&&ke.current){const{id:Ze,title:dt}=ke.current;ke.current=null,x(Ze),m(dt)}},Tt=ie=>{_t(ie)},st=ie=>{ie.preventDefault(),ie.stopPropagation()},ms=ie=>{ie.preventDefault(),ie.stopPropagation()},Qt=ie=>{ie.preventDefault(),ie.stopPropagation(),T(null),R(te,{archivedBucket:a})},rs=ie=>{ie.preventDefault(),ie.stopPropagation(),T(null),R(te,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},os=ie=>{if(ve.current){ve.current=!1;return}if(Ye){if(ie?.preventDefault(),ie?.stopPropagation(),ie?.shiftKey){const dt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(as=>as.getAttribute("data-session-row")).filter(as=>typeof as=="string"&&as.length>0),is=lt.getState().anchorId,nt=new Map;nt.set(te.id,Gn(s)),We(is,te.id,dt,Ce,nt);return}Oe(te.id,Ce,Gn(s));return}ie?.currentTarget&&Rp(ie.currentTarget),I(te.id,ne)},wt=ie=>{ie.defaultPrevented||ie.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||os(ie)},gs=ie=>{(ie.button===2||ie.button===0&&ie.ctrlKey&&!Ye)&&(ve.current=!0)},vt={session:te,sessionTitle:ot,sessionDirectory:ne,isPinnedSession:bt,archivedBucket:a,isElectron:we,renamingFolderId:U,editingIdRef:Se,pendingRenameRef:ke,handleCopySessionId:w,togglePinnedSession:k,handleExportSession:Bt,handleOpenMiniChatWindow:ns,handleDeleteSession:R,handleRestoreSession:F},Rs=t.jsx(Dp,{...vt});return t.jsxs(i.Fragment,{children:[t.jsx($h,{sessionId:te.id,sessionDirectory:ne??null,sessionTitle:ot,children:t.jsxs(Xi,{open:qt,onOpenChange:Tt,onOpenChangeComplete:mt,children:[t.jsxs(Zi,{render:t.jsx("div",{"data-session-row":te.id,"data-session-scope":Ce??"","data-session-archived":a?"1":"0","data-fork-color":ft?s.forkColorId:void 0,"data-global-session":H?.globalSession?"1":void 0,onClick:wt,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...qe?{backgroundColor:qe}:void 0},className:z("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!qe&&n>0?"bg-secondary/30 hover:bg-interactive-hover":qe?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!qe&&Ae&&!J&&"bg-interactive-selection",!qe&&J&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[pt,ct,h===te.id?t.jsxs("form",{ref:le,"data-session-rename-form":te.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:ie=>ie.stopPropagation(),onMouseDown:ie=>ie.stopPropagation(),onSubmit:ie=>{ie.preventDefault(),p(Z)},children:[t.jsx("input",{value:Z,onChange:ie=>ue(ie.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:ie=>{ie.stopPropagation(),ie.key==="Escape"&&y()}}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(A,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:y,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(A,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:gs,onClick:ie=>os(ie),onDoubleClick:ie=>{ie.stopPropagation(),v(te.id,ot)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:z("block min-w-0 flex-1 truncate font-normal typography-ui-label",Nt?"text-foreground":"text-foreground/90"),children:Mn(ot,d)})}),H?.showFolderLabel&&Ie||Pe||De||Ue||Ge>0||de&&de!=="default"||pe||me>0||tt>0?t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[H?.showFolderLabel&&Ie?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Ie}):null,Pe?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(A,{name:"git-branch",className:z("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Pe})]}):De?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(A,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,Ge>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(A,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:Ge})]}):null,de&&de!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:de}):null,pe?t.jsx(mu,{sessionId:te.id,running:Qe,className:"text-muted-foreground/70"}):null,me>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[t.jsx(A,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:me})]}):null,null]}):null]})]}),bt?t.jsx(A,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,t.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[t.jsx("div",{className:z("flex items-center justify-end",ge&&(G||qt)?"opacity-0":ge?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Qe?t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):ze?t.jsx(gu,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:Wt})}),ge?t.jsx("div",{className:z("absolute inset-0 flex items-center justify-end",G||qt?"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(Np,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:st,onMouseDown:ms,onArchive:Qt,onDelete:rs})}):null]}),Dt&&!Q?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:Dt}):null]}),Rs]})}),Xe&&et?s.children.map(ie=>{const Ze=xe?xe(ie):{subtreeContainsEditing:ce,menuOpenSessionId:ae,nodeStructureKey:""};return t.jsx(i.Fragment,{children:ee(ie,n+1,ne??r,o,a,H?.globalSession?{globalSession:!0}:void 0,ye,Ze)},ie.session.id)}):null,t.jsx(Ap,{open:yt,onOpenChange:At,descendantCount:Yt,exportIncludeSubtasks:Ot,setExportIncludeSubtasks:ht,onExport:It})]},te.id)}const Hp=i.memo(Kp,$p),Wp=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(Gt,{open:e,onOpenChange:s,children:t.jsx(Kt,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(ws,{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(Zf,{project:n,onIdentitySave:r}):null})})})});function Qa(e){const{showDeletionDialog:s,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:a}=e;return t.jsxs(Is,{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(A,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(A,{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 Yp(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=c=>us(c);return t.jsx(Gt,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(Kt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(hs,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`"${l(s.session)}" and its ${s.descendantCount} sub-task will be permanently deleted.`:`"${l(s.session)}" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`"${l(s.session)}" and its ${s.descendantCount} sub-task will be archived.`:`"${l(s.session)}" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`"${s?.session?l(s.session):"Untitled Session"}" will be permanently deleted.`:`"${s?.session?l(s.session):"Untitled Session"}" will be archived.`})]}),t.jsx(Qa,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:s?.archivedBucket?"Delete":"Archive"})]})})}function qp(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(Gt,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(Kt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:u}),t.jsx(hs,{children:d})]}),t.jsx(Qa,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:l?"Delete":"Archive"})]})})}function Qp(e){const{value:s,setValue:n,onConfirm:r}=e,{git:o}=Ws(),[a,l]=i.useState(null),[c,u]=i.useState(!1),[d,f]=i.useState(!1),[h,x]=i.useState(!1),g=s?.worktree.path??null;i.useEffect(()=>{let S=!1;return l(null),u(!1),f(!1),x(!1),!s||!g?()=>{S=!0}:(o.getGitStatus(g).then(D=>{if(!S){if(typeof D?.isClean!="boolean"){u(!0);return}l(D)}}).catch(()=>{S||u(!0)}),()=>{S=!0})},[o,s,g]);const m=a?.isClean===!1,p=(a?.ahead??0)>0,y=p&&!s?.worktree.branch,b=s?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",I=!!(s&&a&&!c&&!s.hasActiveSession&&(!m&&!y||d)&&!h),v=s?.worktree.branch||s?.worktree.name||s?.worktree.path||"",k=async()=>{if(I){x(!0);try{await r({force:m})}finally{x(!1)}}};return t.jsx(Gt,{open:!!s,onOpenChange:S=>{!S&&!h&&n(null)},children:t.jsxs(Kt,{showCloseButton:!1,className:"max-w-md gap-5",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:"Close worktree?"}),t.jsx(hs,{children:`Closing "${v}" removes its worktree directory. ${b}`})]}),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(A,{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(A,{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,m?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(A,{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(kr,{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,p?t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:a?.ahead===1?`This worktree has 1 unpushed commit. ${b}`:`This worktree has ${a?.ahead} unpushed commits. ${b}`}),y?t.jsxs("div",{className:"space-y-3 rounded-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(A,{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(kr,{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(Is,{className:"sm:justify-end",children:[t.jsx(Re,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:h,children:"Cancel"}),t.jsx(Re,{variant:"destructive",size:"sm",onClick:()=>{k()},disabled:!I,children:h?"Closing…":"Close worktree"})]})]})})}function Vp(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(Gt,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(Kt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:"Delete folder?"}),t.jsx(hs,{children:s&&(s.subFolderCount>0||s.sessionCount>0)?s.subFolderCount>0?s.subFolderCount===1?`"${s.folderName}" will be deleted along with ${s.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`"${s.folderName}" will be deleted along with ${s.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`"${s.folderName}" will be deleted. Sessions inside will not be deleted.`:`"${s?.folderName??""}" will be permanently deleted.`})]}),t.jsxs(Is,{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 Jp=({updateDialogOpen:e,setUpdateDialogOpen:s,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:a,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:u,setShowDeletionDialog:d,confirmDeleteSession:f,deleteFolderConfirm:h,setDeleteFolderConfirm:x,confirmDeleteFolder:g,closeWorktreeConfirm:m,setCloseWorktreeConfirm:p,confirmCloseWorktree:y,bulkDeleteConfirm:b,setBulkDeleteConfirm:I,confirmBulkDelete:v})=>t.jsxs(t.Fragment,{children:[t.jsx(va,{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(Wp,{open:!!r,onOpenChange:k=>{k||o(null)},project:r,onSave:a}),t.jsx(Yp,{value:l,setValue:c,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:f}),t.jsx(Vp,{value:h,setValue:x,onConfirm:g}),t.jsx(Qp,{value:m,setValue:p,onConfirm:y}),t.jsx(qp,{value:b,setValue:I,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:v})]}),Xp=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=be(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=be(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(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},ai={selected:0,"active-project":1,expanded:2,visible:3,background:4};function Zp(e){const s=new Map,n=(r,o,a)=>{const l=be(r??null);if(!l)return;const c=s.get(l);c&&ai[c.priority]<=ai[o]||s.set(l,{directory:l,priority:o,reason:a})};for(const r of e.projectSections){const o=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":o&&(a="expanded"),n(r.project.normalizedPath,a,o?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=o&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let u="background";c?u="expanded":o&&(u="visible"),n(l.directory,u,c?"worktree-expanded":"known-worktree")}}return n(e.currentDirectory,"selected","current-directory"),n(e.currentSessionDirectory,"selected","selected-session"),[...s.values()]}const em=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l})=>{const c=Ne(u=>u.currentSessionDirectory);return i.useEffect(()=>{s.setBootstrapDemand(e,Zp({projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,o,l,c,e,n]),i.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},tm=e=>{let s=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(s+=r.sessions.length);return s},sm=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},nm=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),rm=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),om=(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=be(a.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},im=e=>e.map(s=>s.groups.some(n=>n.isArchivedBucket)?{...s,groups:s.groups.filter(n=>!n.isArchivedBucket)}:s),am=(e,s,n,r)=>{if(!n)return s;const o=e.find(c=>c.project.id===n);if(!o)return[];const a=be(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&be(c.directory)===a);return l?[{...o,groups:[l]}]:[]},lm=(e,s)=>{const n=new Map,r=new Map;return e.forEach(o=>{const a=Yn(o.project.label?.trim()||Gs(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(h=>{const x=o.project.normalizedPath.length,g=r.get(h.session.id)??-1;x<g||(n.set(h.session.id,{node:h,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:u}),r.set(h.session.id,x),h.children.length>0&&d(h.children))})};d(l.sessions)})}),n};function cm({projectSections:e,flatSectionsForRender:s,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:a,activeSessionIdSet:l,unreadSessionIdSet:c}){const u=i.useMemo(()=>lm(e,a),[e,a]),d=i.useMemo(()=>im(s),[s]),f=i.useMemo(()=>am(n,d,r,o),[n,d,r,o]),h=i.useMemo(()=>tm(e),[e]),x=i.useMemo(()=>sm(e),[e]),g=i.useCallback(y=>{const b=e.find(I=>I.project.id===y);return b?nm(b,l):!1},[l,e]),m=i.useMemo(()=>om(e,l),[l,e]),p=i.useCallback(y=>{const b=e.find(I=>I.project.id===y);return b?rm(b,c):!1},[e,c]);return{sessionSidebarMetaById:u,sectionsForSidebarRender:d,filteredSectionsForSidebarRender:f,totalSessionCount:h,sessionCountByProject:x,hasActiveSessionByProject:g,activeDirectoriesByProject:m,hasUnseenByProject:p}}const dm=({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(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(A,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(Le,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:z("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":a,children:t.jsx(A,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(Le,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:t.jsx(A,{name:"close",className:"h-4 w-4"})})}),t.jsx(Le,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},um=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:u,unarchiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:h}=e,x=lt(B=>B.enabled),g=lt(B=>B.selectedIds.size),m=g>0,p=lt(B=>B.selectedIds),y=lt(B=>B.scopeKey),b=i.useCallback(()=>{lt.getState().toggleMode()},[]),I=i.useCallback(()=>{lt.getState().disable()},[]),v=i.useMemo(()=>{if(!m||typeof document>"u")return!1;let B=!1,R=!1;for(const F of p){const Q=document.querySelectorAll(`[data-session-row="${CSS.escape(F)}"]`);for(const G of Q)G.getAttribute("data-session-archived")==="1"?R=!0:B=!0}return R&&!B},[m,p]),k=i.useMemo(()=>{if(y)return y;if(!m||typeof document>"u")return null;for(const B of p){const F=document.querySelector(`[data-session-row="${CSS.escape(B)}"]`)?.getAttribute("data-session-scope");if(F&&F.length>0)return F}return null},[m,p,y]),S=i.useMemo(()=>{if(!k)return[];const B=o.get(k);return B&&B.length>0?B.map(R=>R.scopeKey):[k]},[k,o]),D=i.useMemo(()=>S.flatMap(B=>r[B]??[]),[r,S]),C=i.useCallback(B=>{for(const R of S)if((r[R]??[]).some(F=>F.id===B))return R;return null},[r,S]),w=i.useMemo(()=>{if(!m)return!1;for(const B of S)for(const R of r[B]??[])for(const F of R.sessionIds)if(p.has(F))return!0;return!1},[r,S,m,p]),j=i.useCallback((B,R)=>{const F=Array.from(p);for(const Q of S)Q!==B&&l(Q,F);a(B,R,F)},[a,l,p,S]),E=i.useCallback(B=>{if(!m)return;const R=C(B);R&&j(R,B)},[m,j,C]),T=i.useCallback(()=>{const B=S[0];if(!B||!m)return;const R=c(B);R&&j(B,R.id)},[c,m,j,S]),U=i.useCallback(()=>{if(!m)return;const B=Array.from(p);for(const R of S)l(R,B)},[l,p,S,m]),_=i.useCallback(async()=>{const B=Array.from(p);if(B.length!==0){if(v){const{deletedIds:R,failedIds:F}=await f(B);R.length>0&&se.success(R.length===1?`Deleted ${R.length} session`:`Deleted ${R.length} sessions`),F.length>0&&se.error(F.length===1?`Failed to delete ${F.length} session`:`Failed to delete ${F.length} sessions`)}else{const{archivedIds:R,failedIds:F}=await u(B);R.length>0&&se.success(R.length===1?`Archived ${R.length} session`:`Archived ${R.length} sessions`),F.length>0&&se.error(F.length===1?`Failed to archive ${F.length} session`:`Failed to archive ${F.length} sessions`)}lt.getState().clear()}},[u,v,f,p]),$=i.useCallback(()=>{if(!m)return;const B=p.size;if(!n){_();return}h({sessionCount:B,archivedBucket:v})},[v,_,p,n,h,m]),K=i.useCallback(async()=>{if(!m||!v)return;const B=Array.from(p),{restoredIds:R,failedIds:F}=await d(B);R.length>0&&se.success(R.length===1?`Restored ${R.length} session`:`Restored ${R.length} sessions`),F.length>0&&se.error(F.length===1?`Failed to restore ${F.length} session`:`Failed to restore ${F.length} sessions`),lt.getState().clear()},[v,m,p,d]),P=i.useCallback(async()=>{h(null),await _()},[_]);return i.useEffect(()=>{if(!x)return;const B=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),R=F=>{if(s)return;const Q=F.target;if(Q&&(Q.tagName==="INPUT"||Q.tagName==="TEXTAREA"||Q.isContentEditable))return;const G=B?F.metaKey:F.ctrlKey;if(F.key==="Escape"){F.preventDefault(),lt.getState().disable();return}if(G&&F.key==="Backspace"){F.preventDefault(),$();return}if(G&&(F.key==="a"||F.key==="A")){const M=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(M.length===0)return;F.preventDefault();const H=lt.getState().scopeKey??M[0]?.getAttribute("data-session-scope")??null,ye=ae=>H?ae.getAttribute("data-session-scope")===H:!0,ce=M.filter(ye).map(ae=>ae.getAttribute("data-session-row")).filter(ae=>typeof ae=="string"&&ae.length>0);if(ce.length===0)return;lt.getState().replaceAll(ce,H||null)}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[$,s,x]),{selectionModeEnabled:x,hasSelection:m,selectedIdsSize:g,bulkScopeIsArchived:v,derivedSelectionScope:k,bulkScopeFolders:D,bulkCanRemoveFromFolder:w,handleToggleSelectionMode:b,handleExitSelectionMode:I,handleBulkMoveToFolder:E,handleBulkCreateFolderAndMove:T,handleBulkRemoveFromFolder:U,handleBulkDelete:$,handleBulkRestore:K,confirmBulkDelete:P}},fm=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},hm=ps()(to(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(s=>({stickyZoneHeaders:!s.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:s=>e({showRecentSection:s}),setShowArchivedSessions:s=>e({showArchivedSessions:s}),toggleRecentSection:()=>e(s=>({showRecentSection:!s.showRecentSection})),toggleArchivedSessions:()=>e(s=>({showArchivedSessions:!s.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:fm})),li="oc.sessions.projectCollapse",ci="oc.sessions.groupOrder",di="oc.sessions.groupCollapse",ui="oc.sessions.activeSessionByProject",fi="oc.sessions.expandedParents.v3",pm=new Set,ur=[],Et=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},mm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Rr("react.session_sidebar_render"),Lt("ui.session_sidebar.render"),Lt(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Lt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,u]=i.useState(!1),[d,f]=i.useState(""),h=i.useRef(null),x=i.useRef(null),[g,m]=i.useState(null),[p,y]=i.useState(""),[b,I]=i.useState(null),[v,k]=i.useState(new Set),S=i.useMemo(()=>Sn(),[]),[D,C]=i.useState(new Set),[w,j]=i.useState(null),[E,T]=i.useState(null),[U,_]=i.useState(new Map),[$,K]=i.useState(new Map),[P,B]=i.useState(!1),[R,F]=i.useState(null),[Q,G]=i.useState(null),[M,ee]=i.useState(""),[H,ye]=i.useState(null),[ce,ae]=i.useState(null),[xe,we]=i.useState(null),[ge,ve]=i.useState(null),Se=Ar(N=>N.ids),ke=Xc(i.useCallback(N=>e?N.rankById:Fi,[e])),je=nn(N=>e?Zc(N.catalog):"",void 0,"catalog"),Z=i.useMemo(()=>je?je.split("|"):ur,[je]),ue=i.useMemo(()=>new Set(Z),[Z]),L=ed(Lr(N=>e?Object.entries(N.index.session.unseenCount).filter(([,q])=>q>0).map(([q])=>q).sort():ur)),Y=i.useMemo(()=>new Set(L),[L]),le=Ar(N=>N.toggle),[W,X]=i.useState(()=>{try{const N=Sn().getItem(di);if(!N)return new Set;const q=JSON.parse(N);return new Set(Array.isArray(q)?q.filter(V=>typeof V=="string"):[])}catch{return new Set}}),[te,ne]=i.useState(()=>{try{const N=Sn().getItem(ci);if(!N)return new Map;const q=JSON.parse(N),V=new Map;return Object.entries(q).forEach(([Ee,Ke])=>{Array.isArray(Ke)&&V.set(Ee,Ke.filter(Ve=>typeof Ve=="string"))}),V}catch{return new Map}}),Ae=i.useMemo(()=>{try{const N=Sn().getItem(ui);if(!N)return new Map;const q=JSON.parse(N),V=new Map;return Object.entries(q).forEach(([Ee,Ke])=>{typeof Ke=="string"&&Ke.length>0&&V.set(Ee,Ke)}),V}catch{return new Map}},[]),Ie=i.useCallback(N=>{try{S.setItem(ui,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[S]),[Pe,De]=i.useState(new Map),Ge=i.useRef(0),de=$s(N=>N.homeDirectory),Ue=$s(N=>N.currentDirectory),Ce=ut(N=>N.projects),Ye=ut(N=>N.activeProjectId),J=ut(N=>N.removeProject),Oe=ut(N=>N.setActiveProjectIdOnly),We=ut(N=>N.updateProjectMeta),$e=ut(N=>N.reorderProjects),Qe=re(N=>N.setActiveMainTab),xt=re(N=>N.setSettingsDialogOpen),Ht=re(N=>N.setSettingsPage),ot=re(N=>N.toggleHelpDialog),Xe=re(N=>N.setSessionSwitcherOpen),bt=re(N=>N.setArchivePageOpen),et=re(N=>N.notifyOnSubtasks),tt=re(N=>N.showDeletionDialog),Nt=re(N=>N.setShowDeletionDialog),Wt=td(d,120),ft=i.useMemo(()=>Wt.trim().toLowerCase(),[Wt]),qe=ft.length>0,yt=at(N=>N.collapsedFolderIds),At=at(N=>N.foldersMap),Ot=at(N=>N.getFoldersForScope),ht=at(N=>N.createFolder),Yt=at(N=>N.renameFolder),Bt=at(N=>N.deleteFolder),It=at(N=>N.addSessionToFolder),qt=at(N=>N.addSessionsToFolder),_t=at(N=>N.removeSessionFromFolder),ns=at(N=>N.removeSessionsFromFolders),me=at(N=>N.toggleFolderCollapse),ze=at(N=>N.getSessionFolderId);Sh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:x,sessionSearchContainerRef:h});const pe=sd(e),Be=_i(),{git:_e}=Ws(),ct=Ti(),pt=nn(N=>N.connection,void 0,"chrome"),Dt=nn(N=>{for(const q of N.catalog.listStatusByDirectory.values())if(q==="ready")return!0;return!1},void 0,"catalog"),mt=Nr({archived:!1}),Tt=Nr({archived:!0}),st=`session-sidebar:${i.useId()}`,ms=Ne(N=>N.setCurrentSession),Qt=Ne(N=>N.updateSessionTitle),rs=Ne(N=>N.shareSession),os=Ne(N=>N.unshareSession),wt=Dr(N=>N.projects),gs=Dr(N=>N.refreshProject),vt=i.useMemo(()=>nd(Ce,{projects:wt}),[Ce,wt]),Rs=i.useMemo(()=>{const N=new Map;for(const q of Ce){const V=be(q.path);if(!V)continue;const Ee=wt.get(V)?.error;Ee&&N.set(V,Ee)}return N},[Ce,wt]);i.useEffect(()=>{if(!w)return;const N=Ce.find(V=>V.id===w);if(!N){j(null),T(null);return}if(!E)return;(vt.get(be(N.path)??N.path)??[]).some(V=>be(V.path)===be(E))||(T(null),se.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[vt,Ce,w,E]);const ie=Ne(N=>N.openNewSessionDraft),Ze=i.useCallback(N=>{re.getState().closeMainSurfaces(),ie(N),r?.()},[r,ie]),dt=Pn(Lr(N=>({checkForUpdates:N.checkForUpdates,available:N.available,runtimeType:N.runtimeType,info:N.info,downloading:N.downloading,downloaded:N.downloaded,progress:N.progress,error:N.error,downloadUpdate:N.downloadUpdate,restartToUpdate:N.restartToUpdate}))),is=i.useMemo(()=>rd(Ce,vt,{includeWorktrees:!0}),[vt,Ce]),nt=i.useMemo(()=>mt.filter(N=>Oh(N,is,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:de})),[mt,de,is]),as=i.useMemo(()=>[...nt,...Tt],[Tt,nt]),Vt=Wn(),qn=i.useMemo(()=>`${Vt}|${Ce.map(N=>`${N.id}:${be(N.path)??""}`).join("|")}`,[Ce,Vt]),Ys=i.useMemo(()=>{const N=new Set;let q=!0;for(const V of Ce){const Ee=be(V.path);if(!Ee)continue;const Ke=wt.get(Ee)?.status??"idle";Ke==="failed"&&N.add(Ee),(Ke==="idle"||Ke==="loading")&&(q=!1)}return{complete:q,unresolved:N}},[Ce,wt]),Qn=Ys.complete?qn:null,Vn=!Ys.complete,xn=Ys.unresolved,{isTablet:qs}=As(),Es=s||qs,O=vh({mobileVariant:s,isTablet:qs}),{buildGroupSearchText:oe,filterSessionNodesForSearch:fe,buildGroupedSessions:He}=wh({homeDirectory:de,pinnedSessionIds:Se,sessionOrderRanks:ke}),{scheduleCollapsedProjectsPersist:Jt}=kh({safeStorage:S,keys:{sessionExpanded:fi,projectCollapse:li,groupOrder:ci,groupCollapse:di},groupOrderByProject:te,collapsedGroups:W,setExpandedParents:k,setCollapsedProjects:C}),it=i.useMemo(()=>od(nt,Se,ke),[Se,ke,nt]),xs=i.useMemo(()=>it.map(N=>N.id).join("|"),[it]),zt=i.useRef(null),co=i.useMemo(()=>{const N=zt.current;if(N&&N.signature===xs)return N.map;const q=new Map(it.map((V,Ee)=>[V.id,Ee]));return zt.current={signature:xs,map:q},q},[it,xs]),Za=i.useMemo(()=>{const N=new Map;return it.forEach(q=>{const V=q.parentID;if(!V)return;const Ee=N.get(V)??[];Ee.push(q),N.set(V,Ee)}),N.forEach(q=>q.sort((V,Ee)=>Vr(V,Ee,Se,ke))),N},[it,Se,ke]),el=i.useMemo(()=>t.jsx(ks,{icon:"chat-new",mobileVariant:s,onClick:()=>Ze(),children:"New session"}),[s,Ze]),tl=i.useMemo(()=>Ce.find(N=>N.id===b)??null,[Ce,b]),sl=i.useCallback(N=>{b&&We(b,{label:N.label,defaultModel:N.defaultModel??null})},[b,We]),nl=i.useCallback(()=>{const N=Pn.getState();if(N.available&&N.info){B(!0);return}dt.checkForUpdates().then(()=>{const{available:q,error:V}=Pn.getState();if(V){se.error("Failed to check for updates",{description:V});return}if(!q){se.success("You are on the latest version");return}B(!0)})},[dt]),Ps=id(),uo=i.useCallback(()=>{if(s&&Xe(!1),r?.(),Ps?.openSettings){Ps.openSettings();return}xt(!0)},[Ps,s,r,Xe,xt]),rl=dt.available&&(dt.runtimeType==="desktop"||dt.runtimeType==="web"),ol=Ne(N=>N.deleteSession),fo=Ne(N=>N.deleteSessions),il=Ne(N=>N.archiveSession),ho=Ne(N=>N.archiveSessions),al=Ne(N=>N.unarchiveSession),ll=Ne(N=>N.unarchiveSessions),{copiedSessionId:cl,handleSessionSelect:dl,handleSessionDoubleClick:ul,handleSaveEdit:fl,handleCancelEdit:hl,handleShareSession:pl,handleCopyShareUrl:ml,handleCopySessionId:gl,handleUnshareSession:xl,handleDeleteSession:bl,handleRestoreSession:yl,confirmDeleteSession:wl}=jh({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:u,setActiveMainTab:Qe,setSessionSwitcherOpen:Xe,setCurrentSession:ms,updateSessionTitle:Qt,shareSession:rs,unshareSession:os,deleteSession:ol,deleteSessions:fo,archiveSession:il,archiveSessions:ho,unarchiveSession:al,childrenMap:Za,showDeletionDialog:tt,setDeleteSessionConfirm:ye,deleteSessionConfirm:H,setEditingId:m,setEditTitle:y,editingId:g,editTitle:p}),vl=i.useCallback(()=>{if(!ce)return;const{scopeKey:N,folderId:q}=ce;ae(null),Bt(N,q)},[ce,Bt]),po=i.useCallback(()=>{Cs.requestDirectoryDialog()},[]),Sl=i.useCallback(N=>{k(q=>{const V=xu(q,N);try{S.setItem(fi,JSON.stringify(Array.from(V)))}catch{}return V})},[S]),mo=i.useCallback((N,q)=>{if(!N)return null;q&&yt.has(q)&&me(q);const V=ht(N,"New folder",q);return G(V.id),ee(V.name),V},[yt,me,ht]),Qs=Et(dl),jl=Et(ul),kl=Et(fl),Cl=Et(hl),Nl=Et(pl),Al=Et(ml),Il=Et(gl),Dl=Et(xl),Rl=Et(bl),El=Et(yl),Jn=Et(mo),go=i.useCallback((N,q)=>{K(V=>{const Ee=new Map(V);return Ee.set(N,q+7),Ee})},[]),bn=i.useCallback(N=>{K(q=>{if(!q.has(N))return q;const V=new Map(q);return V.delete(N),V})},[]),xo=i.useCallback(N=>{K(q=>{let V=!1;const Ee=new Map(q),Ke=`${N}:`;for(const Ve of Ee.keys())Ve.startsWith(Ke)&&(Ee.delete(Ve),V=!0);return V?Ee:q})},[]),Pl=i.useCallback(N=>{Ge.current=Date.now()+150,xo(N),C(q=>{const V=new Set(q);V.has(N)?V.delete(N):V.add(N);try{S.setItem(li,JSON.stringify(Array.from(V)))}catch{}return Jt(V),V})},[xo,S,Jt]),ls=i.useMemo(()=>Ce.map(N=>({...N,normalizedPath:be(N.path)})).filter(N=>!!N.normalizedPath),[Ce]),Ml=i.useMemo(()=>ls.map(N=>N.normalizedPath),[ls]),bo=ad(e?Ml:ur);Rh({enabled:e,normalizedProjects:ls,gitRepoStatus:bo,setProjectRepoStatus:_,setProjectRootBranches:De});const Tl=Ne(N=>N.isLoading),yo=i.useMemo(()=>_h(nt,ls,vt,Tt),[Tt,vt,ls,nt]);Fh({enabled:e,hasAuthoritativeGlobalSessions:Dt,sessions:as});const{getSessionsForProject:Fl,getArchivedSessionsForProject:Ll}=Eh({ownership:yo});fh({enabled:e,normalizedProjects:ls,ownership:yo,isSessionsLoading:Tl,hasAuthoritativeGlobalSessions:Dt,isWorktreeTopologyLoading:Vn,unresolvedWorktreeProjectPaths:xn,foldersMap:At,createFolder:ht,addSessionToFolder:It});const wo=i.useRef(!1);Ye&&U.has(Ye)&&(wo.current=!!U.get(Ye));const Ol=hm(N=>N.showArchivedSessions),Xn=ut(N=>N.manualProjectOrder),vo=i.useRef(new Set),yn=bu(vo.current,v,"project");vo.current=yn;const Zn={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:qs,catalogSessions:mt,archivedSessions:Tt,projects:Ce,activeProjectId:Ye,manualProjectOrder:Xn,currentDirectory:Ue,availableWorktreesByProject:vt,pinnedSessionIds:Se,sessionOrderRanks:ke,foldersMap:At,collapsedFolderIds:yt,gitBranches:pe,gitRepoStatus:bo,updateStore:dt,showArchivedSessions:Ol,projectRepoStatus:U,projectRootBranches:Pe,resolvedWorktreeTopologyKey:Qn,unresolvedWorktreeProjectPaths:xn,isSessionSearchOpen:c,sessionSearchQuery:d,editingId:g,editTitle:p,editingProjectDialogId:b,expandedParents:v,collapsedProjects:D,visibleSessionCountByGroup:$,updateDialogOpen:P,openSidebarMenuKey:R,renamingFolderId:Q,renameFolderDraft:M,deleteSessionConfirm:H,deleteFolderConfirm:ce,bulkDeleteConfirm:ge,collapsedGroups:W},So=i.useRef(null),jo=So.current;if(jo){let N=!1;for(const q of Object.keys(Zn))Object.is(jo[q],Zn[q])||(Lt(`ui.session_sidebar.source.${q}`),N=!0);N||Lt("ui.session_sidebar.source.parent_or_context")}So.current=Zn;const Bl=i.useMemo(()=>{const N=new Map(Xn.map((q,V)=>[q,V]));return[...ls].sort((q,V)=>(N.get(q.id)??1/0)-(N.get(V.id)??1/0))},[Xn,ls]),{projectSections:Rt,groupSearchDataByGroup:ko,sectionsForRender:_l,flatSectionsForRender:er,searchMatchCount:zl}=ph({normalizedProjects:Bl,getSessionsForProject:Fl,getArchivedSessionsForProject:Ll,availableWorktreesByProject:vt,projectRepoStatus:U,projectRootBranches:Pe,lastRepoStatus:wo.current,buildGroupedSessions:He,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:ft,filterSessionNodesForSearch:fe,buildGroupSearchText:oe,foldersMap:At}),wn=i.useMemo(()=>{const N=nt.filter(V=>Hn(Os(V),de));if(N.length===0)return null;const q=He(N,"~",[],null,!1).map(V=>qe?{...V,sessions:fe(V.sessions,ft)}:V).filter(V=>V.sessions.length>0&&!V.isArchivedBucket);return q.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:q}},[He,fe,qe,de,ft,nt]),Ul=i.useMemo(()=>{if(!qe||!wn)return 0;const N=q=>q.reduce((V,Ee)=>V+1+N(Ee.children),0);return wn.groups.reduce((q,V)=>q+N(V.sessions),0)},[wn,qe]),$l=i.useMemo(()=>t.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[t.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),t.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Gl}=hh(te),Co=i.useRef(!1);i.useEffect(()=>{if(Co.current||Rt.length===0)return;const N=Rt.flatMap(q=>q.groups.filter(V=>V.isArchivedBucket).map(V=>`${q.project.id}:${V.id}`));N.length>0&&X(q=>new Set([...q,...N])),Co.current=!0},[Rt]);const{filteredSectionsForSidebarRender:Kl,totalSessionCount:Hl,sessionCountByProject:Wl,hasActiveSessionByProject:Yl,activeDirectoriesByProject:Vs,hasUnseenByProject:ql}=cm({projectSections:Rt,flatSectionsForRender:er,sectionsForRender:_l,selectedSpaceId:w,selectedWorktreePath:E,homeDirectory:de,activeSessionIdSet:ue,unreadSessionIdSet:Y}),tr=i.useCallback(N=>{if(j(N),T(null),!N)return;Oe(N);const q=Rt.find(Ke=>Ke.project.id===N),V=q?.groups.find(Ke=>Ke.isMain),Ee=V?.sessions[0]?.session;Ee?Qs(Ee.id,V?.directory??q?.project.normalizedPath??null,{keepPanelOpen:!0}):q&&Ze({selectedProjectId:N,directoryOverride:q.project.normalizedPath})},[Ze,Rt,Oe,Qs]),Ql=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",Vl=s?"size-5":"h-4.5 w-4.5",vn=Et((N,q=0,V,Ee,Ke=!1,Ve,Ut="project",Ms)=>t.jsx(Hp,{node:N,depth:q,groupDirectory:V,projectId:Ee,archivedBucket:Ke,pinnedSessionIds:Se,expandedParents:yn,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:ft,notifyOnSubtasks:et,editingId:g,setEditingId:m,editTitle:p,setEditTitle:y,handleSaveEdit:kl,handleCancelEdit:Cl,toggleParent:Sl,handleSessionSelect:Qs,handleSessionDoubleClick:jl,togglePinnedSession:le,handleShareSession:Nl,copiedSessionId:cl,handleCopyShareUrl:Al,handleCopySessionId:Il,handleUnshareSession:Dl,openSidebarMenuKey:R,setOpenSidebarMenuKey:F,renamingFolderId:Q,getFoldersForScope:Ot,getSessionFolderId:ze,removeSessionFromFolder:_t,addSessionToFolder:It,createFolderAndStartRename:Jn,handleDeleteSession:Rl,handleRestoreSession:El,mobileVariant:s,alwaysShowActions:Es,allowQuickArchiveAction:O,renderSessionNode:vn,secondaryMeta:Ve,renderContext:Ut,subtreeContainsEditing:Ms?.subtreeContainsEditing??pm,menuOpenSessionId:Ms?.menuOpenSessionId??null,nodeStructureKey:Ms?.nodeStructureKey??"",childRenderExtrasFor:Ms?.childRenderExtrasFor})),Jl=i.useMemo(()=>{const N=new Map;return er.forEach(q=>{const V=q.groups.find(Ee=>!Ee.isArchivedBucket);V?.folderScopes&&V.folderScopes.length>0&&N.set(q.project.id,V.folderScopes)}),N},[er]),Xl=i.useCallback((N,q)=>{const V=[];return q.forEach(Ee=>{Ee.isArchivedBucket||(V.push(Ee.directory),Ee.folderScopes?.forEach(Ke=>V.push(Ke.directory)))}),t.jsx(Xp,{directories:V})},[]),No=i.useCallback(N=>{bn(N),X(q=>{const V=new Set(q);return V.has(N)?V.delete(N):V.add(N),V})},[bn]),Zl=i.useCallback((N,q,V,Ee,Ke,Ve,Ut)=>t.jsx(ap,{group:N,groupKey:q,projectId:V,hideGroupLabel:Ee,dragHandleProps:Ke,compactBodyPadding:Ve,hasSessionSearchQuery:qe,normalizedSessionSearchQuery:ft,groupSearchDataByGroup:ko,visibleSessionCount:$.get(q),collapsedGroups:W,hideDirectoryControls:a,collapsedFolderIds:yt,toggleFolderCollapse:me,renameFolder:Yt,deleteFolder:Bt,showDeletionDialog:tt,setDeleteFolderConfirm:ae,renderSessionNode:vn,showMoreGroupSessions:go,resetGroupSessionLimit:bn,mobileVariant:s,alwaysShowActions:Es,activeProjectId:Ye,setActiveProjectIdOnly:Oe,setActiveMainTab:Qe,setSessionSwitcherOpen:Xe,openNewSessionDraft:Ze,addSessionToFolder:It,createFolderAndStartRename:Jn,renamingFolderId:Q,renameFolderDraft:M,setRenameFolderDraft:ee,setRenamingFolderId:G,pinnedSessionIds:Se,expandedParents:yn,sessionOrderIndex:co,editingId:g,editTitle:p,openSidebarMenuKey:R,activeActivitySessionIds:ue,unreadActivitySessionIds:Y,notifyOnSubtasks:et,onToggleCollapsedGroup:No,scrollContainerRef:Ut}),[qe,ft,ko,$,W,a,yt,me,Yt,Bt,tt,vn,go,bn,s,Es,Ye,Oe,Qe,Xe,Ze,It,Jn,Q,M,Se,yn,co,g,p,R,ue,Y,et,No]),Ao=!!(Q||g||b),{selectionModeEnabled:sr,hasSelection:Io,selectedIdsSize:ec,bulkScopeIsArchived:tc,derivedSelectionScope:sc,bulkScopeFolders:nc,bulkCanRemoveFromFolder:rc,handleToggleSelectionMode:oc,handleExitSelectionMode:ic,handleBulkMoveToFolder:ac,handleBulkCreateFolderAndMove:lc,handleBulkRemoveFromFolder:cc,handleBulkDelete:dc,handleBulkRestore:uc,confirmBulkDelete:fc}=um({isInlineEditing:Ao,showDeletionDialog:tt,foldersMap:At,folderScopesByProject:Jl,addSessionsToFolder:qt,removeSessionsFromFolders:ns,createFolderAndStartRename:mo,archiveSessions:ho,unarchiveSessions:ll,deleteSessions:fo,setBulkDeleteConfirm:ve}),Do=i.useCallback(()=>{re.getState().closeMainSurfaces(),Qe("chat"),s&&Xe(!1),ie(),r?.()},[s,r,ie,Qe,Xe]),hc=i.useCallback((N,q)=>{const V=Ce.find(Ve=>Ve.id===N);if(!V)return;const Ee=be(q.path)?.toLowerCase(),Ke=!!(Ee&&Vs.get(N)?.has(Ee));we({projectId:N,projectPath:V.path,worktree:q,hasActiveSession:Ke})},[Vs,Ce]),pc=i.useCallback(async({force:N})=>{const q=xe;if(!q)return;const V=be(q.worktree.path)?.toLowerCase();if(!!(V&&Vs.get(q.projectId)?.has(V))){we({...q,hasActiveSession:!0}),se.warning("Stop the active session before closing this worktree.");return}if(!_e.deleteGitWorktree){se.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await _e.deleteGitWorktree(q.projectPath,{directory:q.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let Ve=await gs(q.projectPath,_e);const Ut=be(q.worktree.path);Ve!==null&&Ut!==null&&Ve.some(gc=>be(gc.path)===Ut)&&(Ve=await gs(q.projectPath,_e));const Ms=Ut!==null&&be(Ue)===Ut,mc=Ut!==null&&w===q.projectId&&be(E)===Ut;(Ms||mc)&&tr(q.projectId),we(null),Ve===null?se.warning("Worktree closed, but the sidebar could not be refreshed."):se.success("Worktree closed.")}catch(Ke){const Ve=Ke instanceof Error?Ke.message:"Try again.";se.error("Failed to close worktree.",{description:Ve})}},[Vs,xe,Ue,_e,tr,gs,w,E]);return t.jsx(ld,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:h,className:z("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(em,{owner:st,childStores:ct,projectSections:Rt,activeProjectId:Ye,collapsedProjects:D,collapsedGroups:W,currentDirectory:Ue}),t.jsx(gh,{projectSections:Rt,activeProjectId:Ye,initialActiveSessionByProject:Ae,persistActiveSessionByProject:Ie,handleSessionSelect:Qs,mobileVariant:s,openNewSessionDraft:ie,setActiveMainTab:Qe,setSessionSwitcherOpen:Xe}),t.jsx(uh,{enabled:e,sortedSessions:it,prefetchSession:async N=>{await Be.syncSession(N)}}),!a&&!s?t.jsx(cp,{onNewSession:Do,showSidebarToggle:!0}):null,t.jsx(lp,{hideDirectoryControls:a,handleOpenDirectoryDialog:po,onOpenArchive:()=>{s&&Xe(!1),bt(!0)},onOpenSettings:s?uo:void 0,onOpenInstances:s?Ps?.openInstances:void 0,instanceLabel:s?Ps?.instanceLabel:void 0,onOpenUpdate:s?Ps?.openUpdate:void 0,headerActionIconClass:Vl,headerActionButtonClass:Ql,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:x,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:qe,searchMatchCount:zl+(w===null?Ul:0),selectionModeEnabled:sr,onToggleSelectionMode:oc,mobileVariant:s}),pt==="error"||pt==="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&&Rt.length>0?t.jsx(fp,{projects:Rt.map(N=>N.project),selectedProjectId:w,selectedWorktreePath:E,worktreesByProject:vt,worktreeErrorsByProject:Rs,onSelectProject:tr,onSelectWorktree:(N,q)=>{j(N),T(q),Oe(N);const Ke=Rt.find(Ve=>Ve.project.id===N)?.groups.find(Ve=>be(Ve.directory)===be(q))?.sessions[0]?.session;Ke?Qs(Ke.id,q,{keepPanelOpen:!0}):Ze({selectedProjectId:N,directoryOverride:q})},onCloseWorktree:hc,onOpenDirectoryDialog:po,onOpenProjectEditDialog:I,onRemoveProject:J,totalSessionCount:Hl,getSessionCountForProject:N=>Wl.get(N)??0,hasActiveSessionByProject:Yl,activeDirectoriesByProject:Vs,hasUnseenByProject:ql,homeDirectory:de,mobileVariant:s}):null,t.jsx(gp,{sectionsForRender:Kl,allFoldersOnlySection:w===null?wn:null,projectSections:Rt,activeProjectId:Ye,showOnlyMainWorkspace:l,hasSessionSearchQuery:qe,emptyState:el,searchEmptyState:$l,isAllFoldersView:w===null,pinnedSessionIds:Se,renderSessionNode:vn,renderGroupSessions:Zl,homeDirectory:de,collapsedProjects:D,hideDirectoryControls:a,projectRepoStatus:U,mobileVariant:s,alwaysShowActions:Es,toggleProject:Pl,setActiveProjectIdOnly:Oe,setActiveMainTab:Qe,setSessionSwitcherOpen:Xe,openNewSessionDraft:Ze,openProjectEditDialog:I,removeProject:J,reorderProjects:$e,getOrderedGroups:Gl,setGroupOrderByProject:ne,renderProjectStatusIndicator:Xl,openSidebarMenuKey:R,setOpenSidebarMenuKey:F,isInlineEditing:Ao}),s&&!(sr&&Io)?t.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex flex-col gap-2 bg-gradient-to-t from-sidebar via-sidebar/85 to-transparent px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-10",children:[t.jsx(Pa,{variant:"mobile"}),t.jsx(Re,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:Do,"aria-label":"New session",children:t.jsx(A,{name:"chat-new",className:"size-4"})})]}):null,sr&&Io?t.jsx(dm,{selectedCount:ec,scopeKey:sc,scopeFolders:nc,archivedBucket:tc,onMoveToFolder:ac,onCreateFolderAndMove:lc,onRemoveFromFolder:cc,canRemoveFromFolder:rc,onRestore:uc,onDelete:dc,onDone:ic}):null,s?null:t.jsx(hp,{onOpenSettings:uo,onOpenShortcuts:ot,onOpenAbout:()=>{Ht("about"),xt(!0)},onOpenUpdate:nl,showRuntimeButtons:!0,showUpdateButton:rl}),t.jsx(Jp,{updateDialogOpen:P,setUpdateDialogOpen:B,updateStore:dt,editingProject:tl,setEditingProjectDialogId:I,handleSaveProjectEdit:sl,deleteSessionConfirm:H,setDeleteSessionConfirm:ye,showDeletionDialog:tt,setShowDeletionDialog:Nt,confirmDeleteSession:wl,deleteFolderConfirm:ce,setDeleteFolderConfirm:ae,confirmDeleteFolder:vl,closeWorktreeConfirm:xe,setCloseWorktreeConfirm:we,confirmCloseWorktree:pc,bulkDeleteConfirm:ge,setBulkDeleteConfirm:ve,confirmBulkDelete:fc})]})})},Rx=i.memo(mm),hi=6,Pt=.18,tn=1.2,sn=.38,Tn=48,gm=(e,s)=>e==="left"?s<0:s>0,Ex=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Px=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,pi=(e,s,n,r)=>e==="left"?s?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):s?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),Mx=e=>{const{side:s,dx:n,dy:r,dt:o,progress:a,isDragging:l}=e,c=n/Math.max(1,o);if(l){const u=s==="left"?c<-Pt:c>Pt,d=s==="left"?c>Pt:c<-Pt;return u||!d&&a<sn}return Math.abs(n)>=Tn&&Math.abs(r)<=Math.abs(n)*tn&&gm(s,n)},xm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:o,progress:a}=e,l=r/Math.max(1,o);return s==="left"?n?l<-Pt?!1:l>Pt?!0:a>sn:l>Pt?!0:l<-Pt?!1:a>sn:n?l>Pt?!1:l<-Pt?!0:a>sn:l<-Pt?!0:l>Pt?!1:a>sn},bm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',ym=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(bm);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},Fn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),qr=512*1024,wm=new TextEncoder,vm=new TextDecoder,fr=e=>{const s=wm.encode(e);if(s.byteLength<=qr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-qr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:vm.decode(r),byteLength:r.byteLength}},Ts=(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},Sm="terminal-store";let mi=!1,gi=0;const Dn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(gi+=1,`tab-${Date.now().toString(36)}-${gi.toString(36)}`),pr=e=>typeof e=="object"&&e!==null,jm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function rt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const km=/^Terminal(?: (\d+))?$/,Cm=e=>{let s=0;for(const n of e){const r=km.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}),Ft=(e,s)=>e.tabs.findIndex(n=>n.id===s);let xr=null,br=null;const Nm=e=>{if(br&&xr?.sessions===e.sessions&&xr.nextTabId===e.nextTabId)return br;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return xr={sessions:e.sessions,nextTabId:e.nextTabId},br=s,s},Am=()=>{const e=lu(()=>Qd());if(!e)return;let s=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==s)return s=r.state,e.setItem(n,r)},removeItem:n=>(s=null,e.removeItem(n))}},he=ps()(qi(to((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=rt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=Dn(),c=mr(l,"Terminal");return a.set(r,gr(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=rt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=rt(n),o=s().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(l=>l.id===a)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>s().buffers.get(Ts(rt(n),r))??Fn,createTab:n=>{const r=rt(n);if(!r)return"tab-invalid";const o=Dn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),u=a.nextTabId+1,d=Cm(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=rt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Ft(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=rt(n),l=o.trim();l&&e(c=>{const u=new Map(c.sessions),d=u.get(a);if(!d)return c;const f=Ft(d,r);if(f<0||d.tabs[f]?.label===l)return c;const h=[...d.tabs];return h[f]={...h[f],label:l},u.set(a,{...d,tabs:h}),{sessions:u}})},setTabIconKey:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(u,r);if(d<0)return l;const f=o?.trim()||null;if(u.tabs[d]?.iconKey===f)return l;const h=[...u.tabs];return h[d]={...h[d],iconKey:f},c.set(a,{...u,tabs:h}),{sessions:c}})},closeTab:(n,r)=>{const o=rt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const u=Ft(c,r);if(u<0)return a;const d=c.tabs.filter(p=>p.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,p])=>!(p.directory===o&&p.tabId===r))),h=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,x=Ts(o,r),g=a.buffers.has(x)?hr(a.buffers,p=>p===x):null;if(d.length===0){const p=Dn(),y=mr(p,"Terminal");return l.set(o,gr(y)),{sessions:l,nextTabId:a.nextTabId+1,...g?{buffers:g}:{},...h?{projectActionRuns:f}:{}}}let m=c.activeTabId;return c.activeTabId===r&&(m=d[Math.min(u,d.length-1)]?.id??d[0]?.id??null),l.set(o,{...c,tabs:d,activeTabId:m}),{sessions:l,...g?{buffers:g}:{},...h?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(u,r);if(d<0)return l;const f=u.tabs[d],h=o!==null&&f.terminalSessionId!==o,x=o?"running":f.terminalSessionId?"exited":f.lifecycle,g={...f,terminalSessionId:o,lifecycle:x,isConnecting:!1},m=Ts(a,r),p=h&&l.buffers.has(m)?hr(l.buffers,b=>b===m):null,y=[...u.tabs];return y[d]=g,c.set(a,{...u,tabs:y}),{sessions:c,...p?{buffers:p}:{}}})},setTabLifecycle:(n,r,o)=>{const a=rt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(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=rt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(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=rt(n);e(c=>{const u=c.sessions.get(l);if(!u||Ft(u,r)<0)return c;const d=Ts(l,r),f=c.buffers.get(d)??Fn;if(f.lastSequence>a)return c;const h=fr(o);if(f.lastSequence===a&&f.byteLength===h.byteLength&&f.chunks.map(m=>m.data).join("")===h.text)return c;const x=c.nextChunkId,g=new Map(c.buffers);return g.set(d,{chunks:h.text?[{id:x,data:h.text,byteLength:h.byteLength}]:[],byteLength:h.byteLength,lastSequence:a}),{buffers:g,nextChunkId:h.text?x+1:x}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=rt(n);e(u=>{const d=u.sessions.get(c);if(!d||Ft(d,r)<0)return u;const f=Ts(c,r),h=u.buffers.get(f)??Fn;if(a!==void 0&&a<=h.lastSequence)return u;const x=u.nextChunkId,g=fr(o),m=l!==void 0&&l!==o?fr(l).text:void 0,p={id:x,data:g.text,...m!==void 0?{replayData:m}:{},byteLength:g.byteLength},y=[...h.chunks,p];let b=h.byteLength+p.byteLength;for(;b>qr&&y.length>1;){const v=y.shift();if(!v)break;b-=v.byteLength}const I=new Map(u.buffers);return I.set(f,{chunks:y,byteLength:b,lastSequence:a??h.lastSequence}),{buffers:I,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=rt(n);e(c=>{const u=new Map(c.sessions),d=u.get(l);if(!d)return c;const f=Ft(d,r);if(f<0)return c;const h=d.tabs[f],x=a.autoOpened??h.previewAutoOpened,g=a.locked??h.previewUrlLocked;if(h.previewUrl===o&&h.previewAutoOpened===x&&h.previewUrlLocked===g)return c;const m=[...d.tabs];return m[f]={...h,previewUrl:o,previewAutoOpened:x,previewUrlLocked:g},u.set(l,{...d,tabs:m}),{sessions:u}})},markPreviewAutoOpened:(n,r)=>{const o=rt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const u=Ft(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=rt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Ts(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:Sm,storage:Am(),partialize:Nm,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:[],h=[],x=new Map;for(const y of f){if(!pr(y))continue;const b=typeof y.id=="string"?y.id:null;if(!b)continue;const I=jm(b);I!==null&&(o=Math.max(o,I));const v=I===null?b:Dn();x.set(b,v),h.push({id:v,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(h.length===0)continue;const g=typeof d.activeTabId=="string"?d.activeTabId:null,m=g?x.get(g)??g:null,p=m?h.some(y=>y.id===m):!1;r.set(u,{tabs:h,activeTabId:p?m:h[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,o+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!mi){mi=!0;const e=he.persist,s=()=>{he.getState().hasHydrated||he.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Im(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 Dm(e,s,n,r,o=!1){const l=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",fontSize:s,fontFamily:l,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:o}}const yr=["\x1B[0m","\x1B[m"],Rm=e=>{const s=e.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(s)?.[1];if(n){const a=n.length<=4?n.slice(0,3).split("").map(l=>l+l).join(""):n.slice(0,6);return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16)]}const r=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(s);if(!r)return null;const o=r.slice(1,4).map(Number);return o.some(a=>a<0||a>255)?null:o},xi=e=>{const s=Rm(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},Em=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let o=0;const a=Math.max(...yr.map(u=>u.length))-1;for(let u=1;u<=Math.min(a,r.length);u+=1){const d=r.slice(-u);yr.some(f=>f.length>d.length&&f.startsWith(d))&&(o=u)}const l=o>0?r.slice(-o):"";let c=o>0?r.slice(0,-o):r;for(const u of yr)c=c.replaceAll(u,n);return{data:c,carry:l}},Pm=(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))}},Mm=(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 Tm=null;const Fm=()=>Tm??=Ss(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,24])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Lm=2e3,Om=()=>{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,Lm))]).then(()=>{})},Bm=(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))}},Va=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},h)=>{const x=i.useRef(null),g=i.useRef(null),m=i.useRef(null),p=i.useRef(n),y=i.useRef(r),b=i.useRef(null),I=i.useRef(null),v=i.useRef(null),k=i.useRef(""),S=i.useRef(""),D=i.useRef(xi(o.background)),C=i.useRef(!1),w=i.useRef(0),j=i.useRef(f),E=i.useRef(!1),[T,U]=i.useState(0),[_,$]=i.useState(0);p.current=n,y.current=r,j.current=f,D.current=xi(o.background),i.useLayoutEffect(()=>{const R=x.current;if(!R)return;const F=Bm(R,a,l);I.current=F,F&&y.current(F.cols,F.rows)},[a,l]);const K=i.useCallback(()=>{const R=x.current,F=g.current;if(!R||!F||!m.current||!j.current)return;const Q=R.getBoundingClientRect();if(!(Q.width<24||Q.height<24))try{m.current.fit();const G={cols:F.cols,rows:F.rows};(!b.current||b.current.cols!==G.cols||b.current.rows!==G.rows)&&(b.current=G,y.current(G.cols,G.rows)),E.current||(E.current=!0,U(M=>M+1))}catch{}},[]),P=i.useCallback(()=>{if(C.current||!k.current||!g.current)return;const R=g.current,F=k.current;k.current="";const Q=Em(F,S.current,D.current);if(S.current=Q.carry,!Q.data){k.current&&P();return}C.current=!0;const G=w.current;R.write(Q.data,()=>{g.current!==R||w.current!==G||(C.current=!1,k.current&&P())})},[]),B=i.useCallback(()=>{v.current=null,k.current="",S.current="",C.current=!1,w.current+=1;const R=g.current;if(!R){$(F=>F+1);return}try{R.reset();const F=D.current;F&&R.write(`${F}\x1B[2J\x1B[H`)}catch{$(F=>F+1)}},[]);return i.useEffect(()=>{const R=x.current;if(!R)return;let F=!1,Q=null,G=null,M=null,ee=null,H=[];const ye=()=>{Q&&j.current&&(Q.options.cursorBlink=!0)},ce=we=>{we.relatedTarget instanceof Node&&R.contains(we.relatedTarget)||Q&&(Q.options.cursorBlink=!1)},ae=()=>{Q&&j.current&&R.contains(document.activeElement)&&(Q.options.cursorBlink=!0)},xe=()=>{Q&&(Q.options.cursorBlink=!1)};return R.addEventListener("focusin",ye),R.addEventListener("focusout",ce),window.addEventListener("focus",ae),window.addEventListener("blur",xe),Promise.all([Fm(),Om()]).then(([{module:we,ghostty:ge}])=>{if(F)return;Q=new we.Terminal({...Dm(a,l,o,ge,!1),...I.current??{}});const ve=new we.FitAddon;Q.loadAddon(ve),Q.open(R),g.current=Q,m.current=ve,H=[Q.onData(ke=>p.current(ke))],G=new ResizeObserver(()=>{M&&clearTimeout(M),M=setTimeout(K,80)}),G.observe(R),K();const Se=D.current;Se&&Q.write(`${Se}\x1B[2J\x1B[H`),ee=requestAnimationFrame(K)}),()=>{F=!0;const we=document.activeElement;we instanceof HTMLElement&&R.contains(we)&&(we.blur(),window.Capacitor?.getPlatform?.()==="android"&&Ss(async()=>{const{Keyboard:ve}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ve}},__vite__mapDeps([113,114])).then(({Keyboard:ve})=>ve.hide()).catch(()=>{})),G?.disconnect(),M&&clearTimeout(M),ee!==null&&cancelAnimationFrame(ee),R.removeEventListener("focusin",ye),R.removeEventListener("focusout",ce),window.removeEventListener("focus",ae),window.removeEventListener("blur",xe),H.forEach(ge=>ge.dispose()),Q?.dispose(),g.current=null,m.current=null,b.current=null,v.current=null,k.current="",S.current="",C.current=!1,w.current+=1,E.current=!1}},[K,a,l,_,o]),i.useEffect(()=>{const R=g.current,F=x.current;!R||!F||(R.options.cursorBlink=f&&document.hasFocus()&&F.contains(document.activeElement))},[f,T]),i.useEffect(()=>{if(!g.current)return;if(s.length===0){v.current!==null&&B();return}const F=v.current;let Q=-1;if(F!==null){for(let ee=s.length-1;ee>=0;ee-=1){const H=s[ee].id;if(H===F){Q=ee;break}if(H<F)break}if(Q<0){B();return}}const G=Q<0,M=Q>=0?s.slice(Q+1):s;k.current+=M.map(ee=>G?ee.replayData??ee.data:ee.data).join(""),v.current=s.at(-1)?.id??null,P()},[s,P,T,B]),i.useEffect(()=>{if(!d||!f)return;const R=requestAnimationFrame(()=>g.current?.focus());return()=>cancelAnimationFrame(R)},[d,f,T,e]),i.useEffect(()=>{const R=x.current;if(!u||!R)return;const F=Q=>{const G=Q;if(!G.isComposing)switch(G.inputType){case"insertText":G.data&&p.current(G.data);break;case"insertLineBreak":case"insertParagraph":p.current("\r");break;case"deleteContentBackward":p.current("");break}};return R.addEventListener("beforeinput",F),()=>R.removeEventListener("beforeinput",F)},[u,T]),i.useEffect(()=>{const R=x.current,F=g.current;if(!u||!R||!F)return;let Q=null,G=null,M="idle",ee=0,H=0,ye=0,ce=0,ae=null;const xe=Math.max(12,l+2),we=()=>{window.Capacitor?.getPlatform?.()==="android"&&Ss(async()=>{const{Keyboard:le}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:le}},__vite__mapDeps([113,114])).then(({Keyboard:le})=>le.show()).catch(()=>{})},ge=()=>{G&&(clearTimeout(G),G=null)},ve=(Y,le)=>{const W=R.querySelector("canvas");return W?Pm(Y,le,W.getBoundingClientRect(),F.cols,F.rows):null},Se=(Y,le)=>{const W=R.querySelector("canvas");if(!W)return;const X=W.getBoundingClientRect(),te=X.left+(le.column+.5)/F.cols*X.width,ne=X.top+(le.row+.5)/F.rows*X.height;W.dispatchEvent(new MouseEvent(Y,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:te,clientY:ne}))},ke=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},je=Y=>{Y.pointerType!=="touch"||Q!==null||(Q=Y.pointerId,M="pending",ee=Y.clientX,H=Y.clientY,ye=Y.clientY,ce=0,ae=null,R.setPointerCapture(Y.pointerId),G=setTimeout(()=>{if(G=null,Q!==Y.pointerId||M!=="pending")return;const le=ve(ee,H);if(!le)return;const W=F.buffer.active,X=Math.max(0,W.length-F.rows-W.viewportY+le.row),te=W.getLine(X),ne=Array.from({length:F.cols},(Pe,De)=>te?.getCell(De)?.getChars()??""),Ae=Mm(ne,le.column),Ie={column:Ae.startColumn,row:le.row};ae={column:Ae.endColumn,row:le.row},M="selecting",Se("mousedown",Ie),Se("mousemove",ae)},350))},Z=Y=>{if(Q!==Y.pointerId)return;if(M==="selecting"){const X=ve(Y.clientX,Y.clientY);X&&(!ae||X.column!==ae.column||X.row!==ae.row)&&(ae=X,Se("mousemove",X)),Y.cancelable&&Y.preventDefault();return}if(M==="pending"){if(Math.hypot(Y.clientX-ee,Y.clientY-H)<8)return;ge(),M="scrolling"}if(M!=="scrolling")return;const le=ye-Y.clientY;ye=Y.clientY,ce+=le;const W=Math.trunc(ce/xe);W&&(F.scrollLines(W),ce-=W*xe),Y.cancelable&&Y.preventDefault()},ue=Y=>{if(Q!==Y.pointerId)return;const le=M==="pending",W=M==="selecting";ge(),R.hasPointerCapture(Y.pointerId)&&R.releasePointerCapture(Y.pointerId),Q=null,M="idle",W&&ke(),le&&(F.focus(),we())},L=Y=>{if(Q!==Y.pointerId)return;const le=M==="selecting";ge(),R.hasPointerCapture(Y.pointerId)&&R.releasePointerCapture(Y.pointerId),Q=null,M="idle",le&&ke()};return R.addEventListener("pointerdown",je),R.addEventListener("pointermove",Z,{passive:!1}),R.addEventListener("pointerup",ue),R.addEventListener("pointercancel",L),()=>{ge(),R.removeEventListener("pointerdown",je),R.removeEventListener("pointermove",Z),R.removeEventListener("pointerup",ue),R.removeEventListener("pointercancel",L)}},[u,l,T]),i.useImperativeHandle(h,()=>({focus:()=>g.current?.focus(),fit:K,getSelection:()=>{const R=g.current,F=R?.getSelectionPosition(),Q=R?.getSelection()??"";return!F||!Q.trim()?null:{text:Q,startLine:F.start.y+1,endLine:F.end.y+1}}}),[K]),t.jsx("div",{ref:x,"data-terminal-owner":"main",className:z("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});Va.displayName="TerminalViewport";const _m=280,bi=4,zm=({transform:e})=>({...e,y:0}),Um=({id:e,children:s,className:n})=>{const{attributes:r,listeners:o,setNodeRef:a,transform:l,transition:c,isDragging:u}=la({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:ca.Transform.toString(l),transition:c},className:z("h-full rounded-md",n,u&&"opacity-50"),...r,...o,children:s})},$m=({id:e,children:s,className:n})=>t.jsx("div",{className:z("h-full",n),"data-sortable-tab-id":e,children:s}),Gm=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:o,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:u,inactiveTabsIconOnly:d=!1,animateActivePill:f,activePillLowercase:h=!0,nonCompositedIndicator:x=!1,className:g})=>{const m=re(L=>L.isMobile),{isTablet:p}=As(),y=m||p,b=i.useRef(null),[I,v]=i.useState({left:!1,right:!1}),k=i.useMemo(()=>e.map(L=>L.id),[e]),S=a==="scrollable",D=l==="default",C=l==="active-pill",j=C||l==="animated",E=D,T=j||E,U=C&&S,_=j,$=f??j,K=typeof o=="function",P=K?Um:$m,B=i.useRef(new Map),[R,F]=i.useState(null),[Q,G]=i.useState(!1),[M,ee]=i.useState(null),H=i.useRef(!1),ye=i.useRef(0),ce=i.useRef(s),ae=i.useRef(null),xe=i.useMemo(()=>{if(!T||!M||!s||M===s)return 0;const L=e.findIndex(le=>le.id===M),Y=e.findIndex(le=>le.id===s);return L<0||Y<0?0:L>Y?bi:-bi},[s,e,M,T]),we=so(On(oa,{activationConstraint:{distance:8}})),ge=i.useCallback((L,Y)=>!L||!Y?L===Y:Math.abs(L.left-Y.left)<.5&&Math.abs(L.top-Y.top)<.5&&Math.abs(L.width-Y.width)<.5&&Math.abs(L.height-Y.height)<.5,[]),ve=i.useCallback((L,Y)=>{if(Y){B.current.set(L,Y);return}B.current.delete(L)},[]),Se=i.useCallback(()=>{if(!T||!s){F(ne=>ne===null?ne:null);return}const L=b.current,Y=B.current.get(s);if(!L||!Y){F(ne=>ne===null?ne:null);return}let le=0,W=0,X=Y;for(;X&&X!==L;)le+=X.offsetLeft,W+=X.offsetTop,X=X.offsetParent;const te={left:le,top:W,width:Y.offsetWidth,height:Y.offsetHeight};F(ne=>ge(ne,te)?ne:te)},[s,ge,T]),ke=i.useCallback(()=>{if(!S){v({left:!1,right:!1});return}const L=b.current;if(!L){v({left:!1,right:!1});return}v({left:L.scrollLeft>2,right:L.scrollLeft+L.clientWidth<L.scrollWidth-2})},[S]);i.useEffect(()=>{if(!S){v({left:!1,right:!1});return}const L=b.current;if(!L)return;ke(),L.addEventListener("scroll",ke,{passive:!0});const Y=new ResizeObserver(ke);return Y.observe(L),()=>{L.removeEventListener("scroll",ke),Y.disconnect()}},[S,e.length,ke]),i.useEffect(()=>{if(!T){F(null);return}Se();const L=b.current;if(!L)return;const Y=new ResizeObserver(()=>{performance.now()-ye.current>_m&&G(!1),Se()});if(Y.observe(L),s){const le=B.current.get(s);le&&Y.observe(le)}return()=>{Y.disconnect()}},[s,e.length,Se,T]),i.useLayoutEffect(()=>{Se()});const je=k.join("\0");i.useLayoutEffect(()=>{if(!T){H.current=!1,G(!1);return}const L=ae.current!==je;if(ae.current=je,!H.current){H.current=!0,ce.current=s;return}const Y=ce.current!==s;if(ce.current=s,!Y||L){G(!1);return}ye.current=performance.now(),G(!0)},[s,je,T]),i.useEffect(()=>{if(!S||!s)return;const L=b.current;if(!L)return;const Y=window.requestAnimationFrame(()=>{const le=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),W=L.querySelector(`[data-sortable-tab-id="${le}"]`);W&&(W.scrollIntoView({block:"nearest",inline:"nearest"}),ke())});return()=>{window.cancelAnimationFrame(Y)}},[s,S,e.length,ke]);const Z=i.useCallback(L=>{if(!o)return;const{active:Y,over:le}=L;!le||Y.id===le.id||o(String(Y.id),String(le.id))},[o]),ue=t.jsxs("div",{className:z("relative flex h-full min-w-0 flex-1",g),children:[S&&I.left?t.jsx("div",{className:z("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",j?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,S&&I.right?t.jsx("div",{className:z("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",j?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:b,className:z("relative flex h-full min-w-0 flex-1",j?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",j&&"@container/pill-tabs",j&&"pill-tabs__track",j&&(c??"gap-0.5 py-0.5"),E&&"items-center overflow-y-hidden",_&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",S?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:S?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[j&&R?t.jsx("div",{className:z("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",$&&Q&&(x?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:x?{left:`${R.left+xe}px`,top:`${R.top}px`,width:`${R.width}px`,height:`${R.height}px`}:{transform:`translate3d(${R.left+xe}px, ${R.top}px, 0)`,width:`${R.width}px`,height:`${R.height}px`}}):null,E&&R?t.jsx("div",{className:z("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",Q&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${R.left+xe}px, 0, 0)`,width:`${R.width}px`},"aria-hidden":!0}):null,e.map(L=>{const Y=L.id===s,le=d&&j&&!Y&&!!L.icon,W=!le,X=!!L.icon,te=d&&j&&Y&&!S&&!U,ne=L.closable!==!1&&!!r,Ae=ne&&!!L.icon,Ie=S||U?void 0:j?te?"flex-none basis-auto":m?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",Pe=ne?de=>{de.button===1&&(de.preventDefault(),de.stopPropagation(),r?.(L.id))}:void 0,De=ne?de=>{de.button===1&&de.preventDefault()}:void 0,Ge=de=>X?t.jsxs("span",{className:de,children:[t.jsx("span",{className:z("flex items-center justify-center transition-opacity",Ae&&(y?"opacity-0":"group-hover:opacity-0")),children:L.icon}),Ae?t.jsx("span",{role:"button",tabIndex:-1,className:z("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",y?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Ue=>Ue.stopPropagation(),onClick:Ue=>{Ue.stopPropagation(),r?.(L.id)},"aria-label":L.closeLabel??`Close ${L.label} tab`,title:L.closeLabel??`Close ${L.label} tab`,children:t.jsx(A,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return t.jsx(P,{id:L.id,className:Ie,children:t.jsxs("div",{ref:de=>ve(L.id,de),onAuxClick:Pe,onMouseDown:De,className:z("group flex h-full min-w-0 flex-nowrap items-center",S||U?"shrink-0":j?"w-full":"w-full min-w-0",j?"relative z-10 bg-transparent":Y?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":Y,"aria-label":le?L.title??L.label:void 0,onClick:()=>n(L.id),onPointerDown:T?()=>{G(!0),ee(L.id)}:void 0,onPointerUp:T?()=>ee(null):void 0,onPointerLeave:T?()=>ee(null):void 0,onPointerCancel:T?()=>ee(null):void 0,className:z(j?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",j&&h?"lowercase":null,j&&(le?"gap-0":"gap-1.5"),j?U?"shrink-0 whitespace-nowrap px-3 text-center":S?"max-w-56 shrink-0 px-3 text-center":le?"px-2 !min-w-0 text-center":te?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":S?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",j?u??(C?m?"h-[38px]":"h-[31px]":"h-7"):null,j?Y?"text-foreground":"text-muted-foreground hover:text-foreground":null,j?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:L.title??L.label,children:j?t.jsxs(t.Fragment,{children:[Ge("relative flex h-4 w-4 shrink-0 items-center justify-center"),W?t.jsx("span",{className:"animated-tabs__label truncate",children:L.label}):null]}):t.jsxs("span",{className:z("flex min-w-0 flex-nowrap items-center gap-1.5",!S&&"justify-center"),children:[Ge(z("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",Y?"text-[var(--primary-base)]":"text-muted-foreground")),t.jsx("span",{className:"truncate leading-[1.2]",children:L.label})]})}),ne&&!Ae?t.jsx("button",{type:"button",onPointerDown:de=>{de.stopPropagation()},onClick:de=>{de.stopPropagation(),r?.(L.id)},className:z("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",j?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",j?Y?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":Y?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":L.closeLabel??`Close ${L.label} tab`,title:L.closeLabel??`Close ${L.label} tab`,children:t.jsx(A,{name:"close",className:"h-3 w-3"})}):null]})},L.id)})]})]});return K?t.jsxs(no,{sensors:we,collisionDetection:ro,onDragEnd:Z,modifiers:[zm],children:[t.jsx(aa,{items:k,strategy:Pu,children:ue}),t.jsx(ia,{dropAnimation:null})]}):ue},Km=({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(Re,{type:"button",size:a,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[t.jsx(A,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Re,{type:"button",size:a,variant:"chip","aria-pressed":s==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Re,{type:"button",size:a,variant:"chip","aria-pressed":s==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[t.jsx(A,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[t.jsx(A,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[t.jsx(A,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[t.jsx(A,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Re,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[t.jsx(A,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Hm="\x1B",Wm=new RegExp(`${Hm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ym=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,qm=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Qm=/Serving HTTP on .*? port (\d{2,5})/i,Vm=new Set([".",",",";",":","!","?"]),Jm=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(Vm.has(n)){s=s.slice(0,-1);continue}break}return s},yi=e=>{let s=Jm(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},Xm=e=>{if(!e)return null;const s=e.replace(Wm,""),n=s.match(Qm);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=s.split(`
|
|
47
|
-
`);for(const o of r){if(!qm.test(o))continue;const a=Array.from(o.matchAll(Ym));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(yi(c[1])).port}catch{return!1}});return yi((l??a[0])[1])}return null},Zm=async(e,s=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,a=window.setTimeout(()=>o.abort(),s);try{const l=await Mt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},eg={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},tg=(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 eg[e]},Ja=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},sg=(e,s)=>e&&(s==="ctrl"?Ja(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Xa={cols:80,rows:24},wi={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class ng{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(s,n,r,o){if(!r)return;const a=`${this.tail}${r}`.replace(/\r\n|\r/g,`
|
|
48
|
-
`),l=a.split(`
|
|
49
|
-
`),c=a.endsWith(`
|
|
50
|
-
`)?l.join(`
|
|
51
|
-
`):l.slice(0,-1).join(`
|
|
52
|
-
`);if(this.tail=a.endsWith(`
|
|
53
|
-
`)?"":(l[l.length-1]??"").slice(-1024),!c)return;const u=Xm(c);if(!u||this.pendingUrls.has(u))return;const d=this.probeGeneration;this.pendingUrls.add(u),Zm(u).then(f=>{if(this.pendingUrls.delete(u),!f||this.probeGeneration!==d)return;const h=he.getState().getDirectoryState(s)?.tabs.find(x=>x.id===n);!h||h.previewUrlLocked||h.previewUrl===u||o(s,n,u,{locked:!1,autoOpened:!1})})}}const rg=(e,s)=>{if(s!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Ja(o):null};function og({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:d,enableTabs:f,hasActiveContext:h,focusTerminalWhenWindowActive:x}){const g=he(M=>M.ensureDirectory),m=he(M=>M.setTabSessionId),p=he(M=>M.setTabLifecycle),y=he(M=>M.setConnecting),b=he(M=>M.appendToBuffer),I=he(M=>M.replaceBuffer),v=he(M=>M.setTabPreviewUrl),[k,S]=i.useState(null),[D,C]=i.useState(!1),[w,j]=i.useState(!1),E=i.useRef(null),T=i.useRef(null),U=i.useRef(n),_=i.useRef(r),$=i.useRef(s),K=i.useRef(null),P=i.useRef(new Set),B=i.useRef(new ng),R=i.useCallback(()=>{B.current.reset()},[]);i.useEffect(()=>{_.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,d.current).catch(()=>{})},[d,e,r]),i.useEffect(()=>{U.current=n,R()},[n,R]),i.useEffect(()=>{$.current=s},[s]);const F=i.useCallback(()=>{E.current?.(),E.current=null,T.current=null,j(!1)},[]);i.useEffect(()=>()=>{F(),_.current=null},[F]);const Q=i.useCallback((M,ee,H)=>{B.current.scan(M,ee,H,v)},[v]),G=i.useCallback((M,ee,H)=>{if(T.current===H)return;F(),T.current=H;const ye=e.connect(H,{onEvent:ce=>{if(T.current===H)switch(ce.type){case"snapshot":{y(M,ee,!1),S(null),C(!1),j(!1),x(),I(M,ee,ce.data??"",ce.sequence??0),Q(M,ee,ce.data??""),ce.status==="exited"&&p(M,ee,"exited");break}case"reconnecting":{S(null),C(!1),j(!0);break}case"data":{ce.data&&(b(M,ee,ce.data,ce.sequence,ce.replayData),Q(M,ee,ce.data));break}case"exit":{const ae=typeof ce.exitCode=="number"?ce.exitCode:null,xe=typeof ce.signal=="number"?ce.signal:null,ge=!!he.getState().getDirectoryState(M)?.tabs.find(ve=>ve.id===ee)?.label?.startsWith("Action:");b(M,ee,`\\r\\n[Process exited${ae!==null?` with code ${ae}`:""}${xe!==null?` (signal ${xe})`:""}]\\r\\n`),p(M,ee,"exited"),y(M,ee,!1),S(ge?null:"Terminal session ended"),C(!1),j(!1),F();break}}},onError:(ce,ae)=>{if(T.current===H){if(!ae){S(null),C(!1);return}if(j(!1),ce.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(M)?.tabs.find(we=>we.id===ee)?.label?.startsWith("Action:")){S(null),C(!1),y(M,ee,!1),m(M,ee,null),p(M,ee,"idle"),F();return}S(`Connection failed: ${ce.message}`),C(!0),y(M,ee,!1),p(M,ee,"exited"),m(M,ee,null),F()}}});E.current=()=>{ye.close(),T.current=null}},[b,F,x,I,Q,y,p,m,e]);return i.useEffect(()=>{let M=!1;if(!l||!a)return;if(!s){S(h?"No working directory available for terminal.":"Select a session to open the terminal."),F();return}return(async()=>{const H=s;if(!$.current||$.current!==H)return;if(!he.getState().getDirectoryState(H)){g(H);return}const ce=he.getState().getDirectoryState(H);if(!ce||ce.tabs.length===0)return;const ae=ce.activeTabId??ce.tabs[0]?.id??null;if(!ae)return;const xe=ce.tabs.find(je=>je.id===ae)??ce.tabs[0],we=xe?.terminalSessionId??null,ge=xe?.lifecycle??"idle",ve=!!xe?.label?.startsWith("Action:"),Se=he.getState().getBuffer(H,ae),ke=Se.byteLength>0||Se.chunks.length>0;if(!we){if(ge==="exited"){y(H,ae,!1);return}if(ve&&ke){y(H,ae,!1);return}const je=`${H}\0${ae}`;if(P.current.has(je))return;const Z=K.current??Xa;P.current.add(je),S(null),C(!1),j(!1),y(H,ae,!0);try{const ue=await e.createSession({cwd:H,sessionId:ae,cols:Z.cols,rows:Z.rows,shell:c,loginShell:u,...d.current}),L=!M&&$.current===H&&U.current===ae;if(!he.getState().getDirectoryState(H)?.tabs.find(W=>W.id===ae)){try{await e.close(ue.sessionId)}catch{}return}if(m(H,ae,ue.sessionId),!L)return;const le=K.current;le&&(le.cols!==Z.cols||le.rows!==Z.rows)&&e.resize({sessionId:ue.sessionId,...le}).catch(()=>{});return}catch(ue){const L=he.getState().getDirectoryState(H)?.tabs.find(Y=>Y.id===ae);if(!L||L.terminalSessionId||(y(H,ae,!1),$.current!==H||U.current!==ae))return;S(ue instanceof Error?ue.message:"Failed to start terminal session"),C(!0),j(!1);return}finally{P.current.delete(je)}}!we||M||(_.current=we,G(H,ae,we))})(),()=>{M=!0,_.current=null,F()}},[h,s,r,o,n,a,f,l,g,y,p,m,G,F,e,u,c,d]),{connectionError:k,setConnectionError:S,isFatalError:D,setIsFatalError:C,isReconnectPending:w,setIsReconnectPending:j,terminalIdRef:_,lastViewportSizeRef:K,directoryRef:$,activeTabIdRef:U,disconnectStream:F,resetTerminalPreviewScan:R,startStream:G}}function ig({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:u}){const[d,f]=i.useState(null),h=i.useRef(null),x=i.useCallback(()=>{u||h.current?.focus()},[u]),g=i.useCallback(()=>{u||typeof document<"u"&&!document.hasFocus()||h.current?.focus()},[u]);i.useEffect(()=>{!o&&d!==null&&f(null)},[o,d]),i.useEffect(()=>{!c&&d!==null&&f(null)},[c,d]);const m=i.useCallback(v=>{if(!v||n)return;let k=v,S=!1;d&&v.length>0&&(k=sg(v,d),S=!0);const D=s.current;D&&(e.sendInput(D,k).catch(C=>{n||r(C instanceof Error?C.message:"Failed to send input")}),S&&(f(null),x()))},[d,x,n,r,e,s]),p=i.useCallback((v,k)=>{const S=l.current;if((!S||S.cols!==v||S.rows!==k)&&(l.current={cols:v,rows:k}),!a)return;const D=s.current;D&&e.resize({sessionId:D,cols:v,rows:k}).catch(()=>{})},[a,l,e,s]),y=i.useCallback(v=>{f(k=>k===v?null:v),x()},[x]),b=i.useCallback(v=>{const k=tg(v,d);k&&(m(k),f(null),x())},[d,x,m]),I=i.useCallback(v=>{if(v.repeat)return;const k=v.key;if(!k||k==="Control"||k==="Meta"||k==="Alt"||k==="Shift")return;const S=k.length===1?k.toLowerCase():k;if(S in wi){v.preventDefault(),v.stopPropagation(),b(wi[S]);return}const D=rg(v,d);D&&(v.preventDefault(),v.stopPropagation(),m(D),f(null),x())},[d,x,b,m]);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:h,focusTerminalController:x,focusTerminalWhenWindowActive:g,handleViewportInput:m,handleViewportResize:p,handleModifierToggle:y,handleMobileKeyPress:b}}function ag({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:u,activeTabIdRef:d,terminalIdRef:f,disconnectStream:h,resetTerminalPreviewScan:x,startStream:g,setConnectionError:m,setIsFatalError:p,setIsReconnectPending:y}){const b=he(_=>_.createTab),I=he(_=>_.setActiveTab),v=he(_=>_.closeTab),k=he(_=>_.setTabSessionId),S=he(_=>_.setTabLifecycle),[D,C]=i.useState(!1),w=i.useCallback(async()=>{if(!s||D)return;const _=he.getState().getDirectoryState(s),$=n??_?.activeTabId??_?.tabs[0]?.id??null;if(!$)return;const K=_?.tabs.find(P=>P.id===$)?.terminalSessionId??null;if(!(!K||!e.restartSession)){C(!0),m(null),p(!1),y(!1),h(),x();try{const P=c.current??Xa,B=await e.restartSession(K,{cwd:s,shell:o,loginShell:a,...P,...l.current});if(he.getState().getDirectoryState(s)?.tabs.find(F=>F.id===$)?.terminalSessionId!==K||(k(s,$,B.sessionId),S(s,$,"running"),u.current!==s||d.current!==$))return;f.current=B.sessionId,g(s,$,B.sessionId)}catch(P){if(he.getState().getDirectoryState(s)?.tabs.find(R=>R.id===$)?.terminalSessionId!==K||u.current!==s||d.current!==$)return;m(P instanceof Error?P.message:"Failed to restart terminal"),p(!1),y(!1),f.current=K,g(s,$,K)}finally{C(!1)}}},[n,d,u,h,s,r,D,c,x,m,p,y,S,k,g,e,l,f,a,o]),j=i.useCallback(async()=>{await w()},[w]),E=i.useCallback(()=>{if(!s)return;const _=b(s);I(s,_),m(null),p(!1),y(!1),h()},[b,h,s,I,m,p,y]),T=i.useCallback(_=>{s&&(I(s,_),m(null),p(!1),y(!1),h())},[h,s,I,m,p,y]),U=i.useCallback(_=>{if(!s)return;_===n&&h(),m(null),p(!1),y(!1);const $=he.getState().getDirectoryState(s)?.tabs.find(K=>K.id===_)?.terminalSessionId;(async()=>{$&&await e.close($),v(s,_)})().catch(K=>m(K instanceof Error?K.message:"Terminal session ended"))},[n,v,h,s,m,p,y,e]);return{isRestarting:D,handleRestart:w,handleHardRestart:j,handleCreateTab:E,handleSelectTab:T,handleCloseTab:U}}const Tx=({visible:e})=>{const{terminal:s,runtime:n}=Ws(),{currentTheme:r}=zi(),o=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});o.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=cd(),l=re(J=>J.terminalFontSize),c=re(J=>J.terminalShell),u=re(J=>J.terminalLoginShells.includes(J.terminalShell)),{isMobile:d,isTablet:f,hasTouchOnlyPointer:h}=As(),x=d||f,g=(x||h)&&n.platform==="web",m=!0,p=re(J=>J.showTerminalQuickKeysOnDesktop),y=x||p,b=Ne(J=>J.currentSessionId),I=Ne(J=>J.newSessionDraft),v=b!==null||I?.open===!0,k=dd()??null,S=he(J=>k?J.sessions.get(k):void 0),D=he(J=>J.hasHydrated),C=re(J=>J.openContextPreview),w=i.useMemo(()=>S?S.activeTabId??S.tabs[0]?.id??null:null,[S,m]),j=i.useMemo(()=>{if(S)return w?S.tabs.find(J=>J.id===w)??S.tabs[0]:S.tabs[0]},[S,w]),E=i.useMemo(()=>(S?.tabs??[]).map(J=>({icon:(()=>{const Oe=J.iconKey?an[J.iconKey]??"terminal":"terminal";return t.jsx(A,{name:Oe,className:"h-4 w-4"})})(),id:J.id,label:J.label,title:J.label,closeLabel:"Close tab"})),[S?.tabs]),T=j?.terminalSessionId??null,U=j?.lifecycle??"idle",_=he(J=>k&&w?J.getBuffer(k,w).chunks:Fn.chunks),$=j?.isConnecting??!1,K=j?.previewUrl??null,B=re(J=>J.activeMainTab)==="terminal",R=e??B,[F,Q]=i.useState(R);i.useEffect(()=>{R&&Q(!0)},[R]);const{connectionError:G,setConnectionError:M,isFatalError:ee,setIsFatalError:H,isReconnectPending:ye,setIsReconnectPending:ce,terminalIdRef:ae,lastViewportSizeRef:xe,directoryRef:we,activeTabIdRef:ge,disconnectStream:ve,resetTerminalPreviewScan:Se,startStream:ke}=og({terminal:s,effectiveDirectory:k,activeTabId:w,terminalSessionId:T,terminalLifecycle:U,hasOpenedTerminalViewport:F,terminalHydrated:D,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:o,enableTabs:m,hasActiveContext:v,focusTerminalWhenWindowActive:()=>{!g&&typeof document<"u"&&document.hasFocus()&&Z.current?.focus()}}),{activeModifier:je,terminalControllerRef:Z,focusTerminalWhenWindowActive:ue,handleViewportInput:L,handleViewportResize:Y,handleModifierToggle:le,handleMobileKeyPress:W}=ig({terminal:s,terminalIdRef:ae,isReconnectPending:ye,setConnectionError:M,showQuickKeys:y,isTerminalVisible:R,lastViewportSizeRef:xe,terminalSessionId:T,useTouchTerminalInput:g}),{isRestarting:X,handleRestart:te,handleHardRestart:ne,handleCreateTab:Ae,handleSelectTab:Ie,handleCloseTab:Pe}=ag({terminal:s,effectiveDirectory:k,activeTabId:w,enableTabs:m,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:o,lastViewportSizeRef:xe,directoryRef:we,activeTabIdRef:ge,terminalIdRef:ae,disconnectStream:ve,resetTerminalPreviewScan:Se,startStream:ke,setConnectionError:M,setIsFatalError:H,setIsReconnectPending:ce});i.useEffect(()=>{if(!R||g)return;if(typeof window>"u"){ue();return}const J=window.requestAnimationFrame(()=>{ue()});return()=>{window.cancelAnimationFrame(J)}},[w,ue,R,g]);const De=i.useMemo(()=>{const J=Zs[or].stack;if(typeof window>"u")return(Zs[a]??Zs[or]).stack;const We=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return We&&We.trim().length>0?We.trim():(Zs[a]??Zs[or]).stack??J},[a]),Ge=i.useMemo(()=>Im(r),[r]),de=`${k??"no-dir"}::${w??"no-tab"}`;if(i.useEffect(()=>{if(!R||g)return;const J=Z.current;if(!J)return;const Oe=()=>{J.fit()};if(typeof window<"u"){const We=window.requestAnimationFrame(()=>{Oe(),ue()}),$e=[220,400].map(Qe=>window.setTimeout(Oe,Qe));return()=>{window.cancelAnimationFrame(We),$e.forEach(Qe=>window.clearTimeout(Qe))}}Oe()},[ue,R,g,Z,de,T]),i.useEffect(()=>{if(!R||!g)return;let J=null;const Oe=()=>{J!==null&&window.cancelAnimationFrame(J),J=window.requestAnimationFrame(()=>{J=null,Z.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Oe),()=>{window.removeEventListener("oc:keyboard-settled",Oe),J!==null&&window.cancelAnimationFrame(J)}},[R,Z,de,g]),!v)return t.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!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:te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Ue=!T||$||X||ye,Ce=F,Ye=t.jsx(Km,{isTouchTerminal:x,activeModifier:je,disabled:Ue,onKeyPress:W,onModifierToggle:le});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:z("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[S?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:z("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(Gm,{items:E,activeId:w,onSelect:Ie,onClose:Pe,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Re,{type:"button",size:"xs",variant:"ghost",className:z("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ae,title:"New tab",children:t.jsx(A,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Re,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{te()},disabled:X,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(A,{name:"restart",className:"h-4 w-4"})}),K?t.jsxs(Re,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{k&&C(k,K)},title:"Open preview pane",children:[t.jsx(A,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&y&&m&&S?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Ye}):null,!x&&y&&!S?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Ye}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Ge.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Ce?t.jsx(Va,{ref:J=>{Z.current=J},sessionKey:de,chunks:_,onInput:L,onResize:Y,theme:Ge,fontFamily:De,fontSize:l,enableTouchScroll:g,autoFocus:R,isVisible:R},de):null}),!ye&&G&&t.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[t.jsx("span",{children:G}),ee&&x&&t.jsx(Re,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ne,disabled:X,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&y?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:Ye})}):null]})},lg=48,cg=96,gt=(e,...s)=>{try{e?.(...s)}catch{}},wr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Fx=(e,s)=>{const n=i.useRef(s);n.current=s;const r=s.enabled;i.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const a=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?cg:lg;let u=!1,d=!1,f=!1,h=null,x=!1,g=0,m=0,p=0,y=0;const b=()=>{u=!1,d=!1,f=!1,h=null},I=()=>{const j=n.current,E=h,T=x;d&&E&&(gt(E==="left"?j.onLeftProgress:j.onRightProgress,T?1:0),gt(j.onDragEnd,E,T)),b()},v=()=>{I(),d||b()},k=j=>{const E=n.current;if(E.enabled===!1){d&&h?I():b();return}if(j.touches.length!==1){d&&h?I():b();return}const T=j.touches[0],U=o.getBoundingClientRect(),_=o.clientWidth,$=!!E.leftOpen,K=!!E.rightOpen,P=B=>ym(B,o);if($||K){if(P(j.target)){b();return}if($&&K){const B=T.clientX<=U.left+c;T.clientX>=U.right-c?(h="right",x=!0):B?(h="left",x=!0):(h=$?"left":"right",x=!0)}else $?(h="left",x=!0):(h="right",x=!0);y=wr(h==="left"?E.leftWidth:E.rightWidth,_),y<10&&(y=_||window.innerWidth||320),y<10&&(y=320),u=!0}else{if(P(j.target)){b();return}h=null,x=!1,y=0,u=!0}g=T.clientX,m=T.clientY,p=Date.now(),d=!1,f=!1},S=j=>{if(!u)return;if(j.touches.length!==1){v();return}const E=j.touches[0],T=E.clientX-g,U=E.clientY-m;if(!f){if(Math.abs(T)<hi&&Math.abs(U)<hi)return;if(Math.abs(U)>Math.abs(T)*tn){b();return}if(!h){const K=n.current;h=T>0?"left":"right",y=wr(h==="left"?K.leftWidth:K.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(h==="left"){if(!x&&T<=0){b();return}if(x&&T>=0){b();return}}else{if(!x&&T>=0){b();return}if(x&&T<=0){b();return}}f=!0,d=!0,gt(n.current.onDragStart,h)}if(!d)return;j.cancelable&&j.preventDefault();const _=n.current,$=pi(h,x,T,y);gt(h==="left"?_.onLeftProgress:_.onRightProgress,$)},D=(j,E)=>{if(!u){b();return}const T=j-g,U=E-m;if(!h&&!x&&Math.abs(T)>=Tn&&Math.abs(U)<=Math.abs(T)*tn){const R=n.current;h=T>0?"left":"right",y=wr(h==="left"?R.leftWidth:R.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(!h){b();return}const _=Math.max(1,Date.now()-p),$=n.current;if(!d){const R=Math.abs(T),F=Math.abs(U);R>=Tn&&F<=R*tn?h==="left"&&!x&&T>0?(gt($.onLeftProgress,1),gt($.onLeftOpen)):h==="right"&&!x&&T<0?(gt($.onRightProgress,1),gt($.onRightOpen)):gt(h==="left"?$.onLeftProgress:$.onRightProgress,x?1:0):gt(h==="left"?$.onLeftProgress:$.onRightProgress,x?1:0);const Q=h;b(),gt($.onDragEnd,Q);return}const K=pi(h,x,T,y),P=xm({side:h,isOpenAtStart:x,dx:T,dt:_,progress:K}),B=h;gt(B==="left"?P?$.onLeftOpen:$.onLeftClose:P?$.onRightOpen:$.onRightClose),b(),gt($.onDragEnd,B,P)},C=j=>{const E=j.changedTouches[0];if(!E){b();return}const T=E.clientX-g,U=E.clientY-m;u&&(d||Math.abs(T)>=Tn&&Math.abs(U)<=Math.abs(T)*tn)&&j.cancelable&&j.preventDefault(),D(E.clientX,E.clientY)},w=()=>{v()};return o.addEventListener("touchstart",k,{passive:!0}),o.addEventListener("touchmove",S,{passive:!1}),o.addEventListener("touchend",C,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{d&&h&&I()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",k),o.removeEventListener("touchmove",S),o.removeEventListener("touchend",C),o.removeEventListener("touchcancel",w)}},[e,r])};function Lx({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(A,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function vi({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 dg=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,ug=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Hn(s,n)?null:e,vr=()=>vs.filter(e=>Tr.has(e.id)).map(e=>({...Wi(e)})),fg=()=>{if(typeof window>"u")return Fr;const e=window.localStorage.getItem("openInAppId");return e&&Mr(e)?e:Fr};let Sr=!1,Fs=!1,cs=!1,ds=0,ln=null;const Si=()=>{ln&&(clearTimeout(ln),ln=null)},bs=ps()((e,s)=>({selectedAppId:fg(),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(m=>m.name)),h=new Map(u.map(m=>[m.name,m.iconDataUrl??void 0])),g=vs.filter(m=>f.has(m.appName)||Tr.has(m.id)).map(m=>({...Wi(m),iconDataUrl:h.get(m.appName)}));e({availableApps:g,hasLoadedApps:!0})},r=async u=>{if(!Us()||!dn()||Fs||s().hasLoadedApps&&!u)return;const f=vs.map(h=>h.appName);Si(),Fs=!0,cs=!1,e({isScanning:!0});try{const{apps:h,success:x,hasCache:g,isCacheStale:m}=await _o(f,u),p=x&&!g&&h.length===0&&ds<3;if(e({isCacheStale:g?m:!1}),n(h,x?!p:!1),x){if(p){const b=[800,1600,3200][ds]??3200;ds+=1,cs=!0,ln=setTimeout(()=>{r()},b);return}ds=0,cs=!1;return}if(ds<3){const b=[1e3,3e3,7e3][ds]??7e3;ds+=1,cs=!0,ln=setTimeout(()=>{r()},b)}}finally{Fs=!1,cs||e({isScanning:!1})}};r();const o=u=>{const d=u.detail,f=d&&typeof d.openInAppId=="string"&&d.openInAppId.length>0&&Mr(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)&&(ds=3,cs=!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(),!Us()||!dn()||Fs||s().hasLoadedApps&&!n)return;const o=vs.map(a=>a.appName);Si(),n&&e({hasLoadedApps:!1}),Fs=!0,cs=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await _o(o,n),u=new Set(a.map(x=>x.name)),d=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),h=vs.filter(x=>u.has(x.appName)||Tr.has(x.id)).map(x=>({...x,iconDataUrl:d.get(x.appName)}));e({availableApps:h.length>0?h:vr(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{Fs=!1,cs||e({isScanning:!1})}},selectApp:async n=>{Mr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Zr({openInAppId:n}))}})),hg="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",pg="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"?hg:e.id==="terminal"?pg:void 0}),ji=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,o]=i.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):t.jsx("span",{className:z("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},mg=({directory:e,className:s})=>{const n=bs(m=>m.selectedAppId),r=bs(m=>m.availableApps),o=bs(m=>m.isCacheStale),a=bs(m=>m.isScanning),l=bs(m=>m.initialize),c=bs(m=>m.loadInstalledApps),u=bs(m=>m.selectApp);i.useEffect(()=>{l()},[l]);const d=Us()&&dn(),f=i.useMemo(()=>{const m=r.find(p=>p.id===n)??r.find(p=>p.id===Fr)??r[0]??vs[0];return jr(m||vs[0])},[r,n]);if(!d||!e||r.length===0)return null;const h=async m=>{await Vd(e,m.id,m.appName)||await Ki(e,m.appName)},x=async m=>{await u(m.id),await h(m)},g=async()=>{(await _s(e)).ok&&se.success("Path copied to clipboard")};return t.jsxs("div",{className:z("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{h(f)},className:z("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:t.jsx(ji,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(jt,{children:[t.jsx(kt,{asChild:!0,children:t.jsx("button",{type:"button",className:z("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(A,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Ct,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Je,{className:"flex items-center gap-2",onClick:()=>{g()},children:[t.jsx(A,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(zs,{}),r.map(m=>{const p=jr(m);return t.jsxs(Je,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[t.jsx(ji,{label:m.label,iconDataUrl:m.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:m.label}),f.id===m.id?t.jsx(A,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?t.jsxs(Je,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(A,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},gg="\x1B",xg=new RegExp(`${gg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),bg=/https?:\/\/[^\s<>'"`]+/gi,St="__pichamber_auto_discover_preview__",yg=15e3,wg=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},vg=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}},Sg=e=>{const n=e.replace(xg,"").match(bg);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||"/",h=f.split("/").filter(Boolean).length,x=f==="/"||f==="",g=!!(c.search||c.hash);let m=0;return d&&(m+=50),x&&(m+=30),m-=Math.min(h*5,20),g&&(m-=10),m};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},jg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],kg=["dev","start","preview","serve"];async function Cg(e,s,n){if(!e)return null;const r=Ig(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Dg(n);if(o){const a=await Rg(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 Ng(e)){const o=await Ag(),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 Ng(e){const s=`${e}/index.html`,n=await Kn(s,e);return typeof n=="string"&&n.trim().length>0}async function Ag(){try{const e=await Mt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Ig(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(kg.some(o=>n.includes(o)))return s}return null}function Dg(e){for(const{pattern:s}of jg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Rg(e){const s=await Kn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Kn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Kn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Mt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=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 Mt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Eg(e){try{const s=await Kn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Pg=(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 Mg({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=zi(),{terminal:o}=Ws(),{isMobile:a}=As(),l=re(W=>W.terminalShell),c=re(W=>W.terminalLoginShells.includes(W.terminalShell)),u=re(W=>W.setSettingsPage),d=re(W=>W.setSettingsDialogOpen),f=re(W=>W.setSettingsProjectsSelectedId),h=re(W=>W.openContextPreview),x=he(W=>W.ensureDirectory),g=he(W=>W.setTabLabel),m=he(W=>W.setTabIconKey),p=he(W=>W.setActiveTab),y=he(W=>W.setConnecting),b=he(W=>W.setTabSessionId),I=he(W=>W.setTabPreviewUrl),v=he(W=>W.projectActionRuns),k=he(W=>W.setProjectActionRun),S=he(W=>W.updateProjectActionRunStatus),D=he(W=>W.removeProjectActionRun),[C,w]=i.useState([]),[j,E]=i.useState(null),[T,U]=i.useState(!1),_=i.useRef({}),$=i.useRef({}),K=i.useRef({}),P=i.useRef({}),B=i.useRef(new Set),R=i.useRef(0),F=e?.id??null,Q=e?.path??"",G=i.useMemo(()=>F?{id:F,path:Q}:null,[F,Q]),M=i.useCallback(async W=>{await Ii(W)},[]),ee=i.useCallback(async()=>{if(!G)return;const W=R.current+1;R.current=W,U(!0);try{const X=await Cr(G);if(R.current!==W)return;const te=X.actions;w(te),E(ne=>ne===St||ne&&te.some(Ae=>Ae.id===ne)?ne:null)}catch{if(R.current!==W)return}finally{R.current===W&&U(!1)}},[G]),H=i.useMemo(()=>Na(s||G?.path||""),[s,G?.path]),ye=i.useMemo(()=>j?C.find(W=>W.id===j)??null:null,[C,j]),ce=i.useMemo(()=>({id:St,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),ae=!a,xe=i.useMemo(()=>ae?[ce,...C]:C,[C,ce,ae]);i.useEffect(()=>{ee()},[ee]),i.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const te=X.detail;F&&(te?.projectId&&te.projectId!==F||ee())};return window.addEventListener(Ur,W),()=>{window.removeEventListener(Ur,W)}},[ee,F]),i.useEffect(()=>{j&&(j===St&&ae||C.some(W=>W.id===j)||E(null))},[C,ae,j]),i.useEffect(()=>{const W=()=>{const X=he.getState(),te=X.sessions,ne=X.projectActionRuns;for(const[Ae,Ie]of Object.entries(ne)){const De=te.get(Ie.directory)?.tabs.find($e=>$e.id===Ie.tabId);if(!De||De.terminalSessionId!==Ie.sessionId){D(Ae);continue}const Ge=$.current[Ae]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};$.current[Ae]=Ge;const de=xe.find($e=>$e.id===Ie.actionId),Ue=X.getBuffer(Ie.directory,Ie.tabId).chunks;if(!de||Ue.length===0)continue;const Ce=Ue.filter($e=>Ge.lastSeenChunkId===null||$e.id>Ge.lastSeenChunkId);if(Ce.length===0)continue;const Ye=Ce.map($e=>$e.data).join(""),J=`${Ge.tail}${Ye}`,Oe=!Ge.openedUrl&&de.autoOpenUrl===!0?Sg(J):null,We=Ce[Ce.length-1]?.id??Ge.lastSeenChunkId;if(Ge.lastSeenChunkId=We,Ge.tail=J.slice(-512),Oe)if(Ge.openedUrl=!0,Ge.openInPreview){const $e=ne[Ae];$e&&(I($e.directory,$e.tabId,Oe,{locked:!1,autoOpened:!1}),$e.status==="waiting-for-preview"&&S(Ae,"running"),window.clearTimeout(P.current[Ae]),delete P.current[Ae],h($e.directory,Oe))}else M(Oe),se.success("Opened URL from action output");$.current[Ae]=Ge}for(const Ae of Object.keys($.current))ne[Ae]||(delete $.current[Ae],window.clearTimeout(P.current[Ae]),delete P.current[Ae])};return W(),he.subscribe((X,te)=>{(X.sessions!==te.sessions||X.buffers!==te.buffers)&&W()})},[xe,h,M,v,D,I,S]);const we=i.useCallback(async(W,X={})=>{if(!H)throw new Error("No active directory");const te=es(H,W.id);x(H);const ne=he.getState(),Ae=ne.getDirectoryState(H);let Ie=_.current[te]||null;const Pe=Ie?!!Ae?.tabs.some(de=>de.id===Ie):!1;(!Ie||!Pe)&&(Ie=ne.createTab(H),_.current[te]=Ie),g(H,Ie,`Action: ${W.name}`),m(H,Ie,W.icon||"play"),p(H,Ie),X.revealTerminal!==!1&&re.getState().openContextPanelTab(H,{mode:"terminal"});const Ge=he.getState().getDirectoryState(H)?.tabs.find(de=>de.id===Ie);return{key:te,tabId:Ie,sessionId:Ge?.terminalSessionId??null}},[x,H,p,m,g]),ge=i.useCallback(async W=>{if(!n&&a)return;if(!H){se.error("No active directory for action");return}const X=es(H,W.id),te=v[X];if(!(te&&te.status==="running")&&!B.current.has(X)){B.current.add(X);try{const ne=W.id===St?await(async()=>{const[J,Oe]=await Promise.all([Cr({id:G?.id??"",path:H}),Eg(H)]),We=await Cg(H,J.actions,Oe);if(!We)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:We.command,icon:"scan-2",autoOpenUrl:!0,openUrl:We.previewUrlHint||""}})():W,Ae=ne.autoOpenUrl===!0&&(ne.openUrl||"").trim().length>0,Ie=!Ae&&W.id!==St,{key:Pe,tabId:De,sessionId:Ge}=await we(ne,{revealTerminal:Ie});let de=Ge;if(!de){y(H,De,!0);try{de=(await o.createSession({cwd:H,sessionId:De,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,b(H,De,de)}finally{y(H,De,!1)}}if(!de)throw new Error("Failed to create terminal session");K.current[Pe]?.(),y(H,De,!0);const Ue=o.connect(de,{onEvent:J=>{J.type==="snapshot"&&(he.getState().replaceBuffer(H,De,J.data??"",J.sequence??0),he.getState().setConnecting(H,De,!1)),J.type==="data"&&typeof J.data=="string"&&J.data.length>0&&he.getState().appendToBuffer(H,De,J.data,J.sequence,J.replayData),J.type==="exit"&&(he.getState().setTabLifecycle(H,De,"exited"),he.getState().setConnecting(H,De,!1),he.getState().removeProjectActionRun(Pe),delete $.current[Pe],K.current[Pe]?.(),delete K.current[Pe],window.clearTimeout(P.current[Pe]),delete P.current[Pe])},onError:(J,Oe)=>{he.getState().setConnecting(H,De,!1),Oe&&(he.getState().setTabLifecycle(H,De,"exited"),he.getState().setTabSessionId(H,De,null),he.getState().removeProjectActionRun(Pe))}});K.current[Pe]=Ue.close;const Ce=ne.autoOpenUrl?vg(ne.openUrl):null;k({key:Pe,directory:H,actionId:ne.id,tabId:De,sessionId:de,status:ne.id===St&&!Ce?"waiting-for-preview":"running"}),window.clearTimeout(P.current[Pe]),delete P.current[Pe],ne.id===St&&!Ce&&(P.current[Pe]=window.setTimeout(()=>{const J=he.getState(),Oe=J.projectActionRuns[Pe];J.updateProjectActionRunStatus(Pe,"running"),Oe&&(J.setActiveTab(Oe.directory,Oe.tabId),re.getState().openContextPanelTab(Oe.directory,{mode:"terminal"})),delete P.current[Pe]},yg)),$.current[Pe]={lastSeenChunkId:null,openedUrl:!!Ce||Ae,tail:"",openInPreview:ne.id===St};const Ye=wg(ne.command.trim().replace(/\r\n|\r/g,`
|
|
54
|
-
`));await o.sendInput(de,`${Ye}\r`),Ce?(I(H,De,Ce,{locked:!0,autoOpened:!0}),h(H,Ce),se.success("Opened action URL")):Ae?(I(H,De,null,{locked:!0}),se.error("Invalid custom URL format")):I(H,De,null,{locked:!1,autoOpened:!1})}catch(ne){D(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X],se.error(ne instanceof Error?ne.message:"Failed to run action")}finally{B.current.delete(X)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,we,n,a,H,c,l,h,v,D,y,k,I,b,G?.id,o]),ve=i.useCallback(async W=>{const X=es(H,W.id),te=v[X];if(!te)return;S(X,"stopping");const ne=Pg(o,te.sessionId,1e3);try{await o.sendInput(te.sessionId,"")}catch{}const Ae=await ne;if(he.getState().getDirectoryState(te.directory)?.tabs.find(De=>De.id===te.tabId)?.terminalSessionId===te.sessionId&&!Ae){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:te.sessionId})}catch{}else try{await o.close(te.sessionId)}catch{}b(te.directory,te.tabId,null)}D(X),delete $.current[X],K.current[X]?.(),delete K.current[X],window.clearTimeout(P.current[X]),delete P.current[X]},[H,v,D,b,o,S]),Se=i.useCallback(()=>{const W=ye??xe[0];if(!W)return;const X=es(H,W.id),te=v[X];if(te?.status!=="stopping"){if(te){ve(W);return}ge(W)}},[xe,H,ge,v,ye,ve]),ke=i.useCallback((W,X=!1)=>{if(E(W.id),!X){ge(W);return}const te=es(H,W.id),ne=v[te];if(ne?.status!=="stopping"){if(ne){ve(W);return}ge(W)}},[H,ge,v,ve]),je=i.useCallback(()=>{G?.id&&(f(G.id),u("projects"),d(!0))},[d,u,f,G?.id]),Z=ye??xe[0]??null,ue=Z?v[es(H,Z.id)]:null,L=he(W=>ue?W.sessions.get(ue.directory)?.tabs.find(X=>X.id===ue.tabId)?.previewUrl??null:null),Y=!!((n||!a)&&G&&H),le=ye??xe[0]??null;return{shouldRender:Y,isLoading:T,normalizedDirectory:H,resolvedSelected:le,displayActions:xe,projectActionRuns:v,selectedRunPreviewUrl:L,handlePrimaryClick:Se,handleSelectAction:ke,openProjectActionsSettings:je,openContextPreview:h}}const ki=({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:h,handlePrimaryClick:x,handleSelectAction:g,openProjectActionsSettings:m,openContextPreview:p}=Mg({projectRef:e,directory:s,allowMobile:o});if(!a||!u)return null;const y=u.icon||"play",b=u.id===St?"scan-2":an[y]||"play",I=es(c,u.id),v=f[I],k=v?.status==="stopping",S=v?.status==="waiting-for-preview",D=!!(v&&h),C=()=>{!v||!h||p(v.directory,h)},w=u.id===St;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||k,className:z("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":v?`Stop ${u.name}`:`Run ${u.name}`,children:k||S?t.jsx(A,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?t.jsx(A,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(A,{name:b,className:"h-5 w-5"})})}),w?t.jsx(Le,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),D?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:C,children:t.jsx(A,{name:"global",className:"h-4 w-4"})})}),t.jsx(Le,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(jt,{children:[t.jsx(kt,{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(A,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Ct,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Je,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(A,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(zs,{}),d.map(j=>{const E=j.icon||"play",T=j.id===St?"scan-2":an[E]||"play",U=es(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Je,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(A,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(A,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(A,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]}):t.jsxs("div",{className:z("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:x,disabled:l||k,className:z("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":v?`Stop ${u.name}`:`Run ${u.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:k||S?t.jsx(A,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?t.jsx(A,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(A,{name:b,className:"h-4 w-4"})})})}),w?t.jsx(Le,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),D?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:C,className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(A,{name:"global",className:"h-4 w-4"})})}),t.jsx(Le,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(jt,{children:[t.jsx(kt,{asChild:!0,children:t.jsx("button",{type:"button",className:z(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(A,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Ct,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Je,{className:"flex items-center gap-2",onClick:m,children:[t.jsx(A,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(zs,{}),d.map(j=>{const E=j.icon||"play",T=j.id===St?"scan-2":an[E]||"play",U=es(c,j.id),_=f[U],$=!!_,K=_?.status==="stopping";return t.jsxs(Je,{className:"flex items-center gap-2",onClick:()=>{g(j,!0)},children:[t.jsx(A,{name:T,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:j.name}),K||_?.status==="waiting-for-preview"?t.jsx(A,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?t.jsx(A,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},j.id)})]})]})]})},Tg=i.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:o,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(jt,{children:[t.jsx(kt,{asChild:!0,children:t.jsx("button",{type:"button",className:z(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(A,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Ct,{align:"end",className:"w-64",children:[t.jsx(ud,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(zs,{}),r.map(u=>{const d=u.user,f=!!u.current,h=u.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(Je,{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(A,{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:h})]}):null]}),f?t.jsx(A,{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(A,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Fg=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:u,remoteUpdateInfo:d,remoteUpdateChecking:f,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(jt,{open:a,onOpenChange:g=>{l(g),g&&c()},children:[t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx(kt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:z(gn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(A,{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(Le,{children:t.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),t.jsx(Ct,{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...":h||"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:x,children:"Update"}):null]})}),t.jsx(fd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Lg=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Gt,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Kt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(fs,{children:[t.jsx(ss,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(hs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Is,{children:[t.jsx(Re,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Re,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Og=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},en=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Bg=i.lazy(()=>Ss(()=>import("./SessionSwitcherDropdown-Cgw2mQIO.js"),__vite__mapDeps([115,24,3,4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),Ox=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Lt("ui.header.render");const l=re(O=>O.setSessionSwitcherOpen),c=re(O=>O.toggleSidebar),u=re(O=>O.isSidebarOpen),d=re(O=>O.activeMainTab),f=re(O=>O.setActiveMainTab),h=re(O=>O.shortcutOverrides);re(O=>O.timeFormatPreference),Ws();const x=Ne(O=>!!O.newSessionDraft?.open),g=Ne(O=>O.currentSessionId),m=Bi(g??""),p=hd(g),y=i.useMemo(()=>{if(!p)return null;const O=p;return{title:p.title??null,directory:O.directory??null,created:p.time?.created??null,slug:O.slug??null,shareUrl:p.share?.url??null,parentId:p.parentID??null}},[p]),b=ut(Lr(O=>{if(!O.activeProjectId)return null;const oe=O.projects.find(fe=>fe.id===O.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),I=$s(O=>O.homeDirectory),v=i.useMemo(()=>{if(!b)return null;const O=b.label?.trim();if(O)return O;const oe=b.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[b]),{isMobile:k}=As(),{enabled:S}=Qr(),D=!!(S&&a&&o!==void 0),C=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[w,j]=i.useState(!1),E=null,T=i.useRef(null),[U,_]=i.useState(()=>typeof window>"u"?!1:Us()),$=i.useMemo(()=>Hi(),[]),K=pd(),[P,B]=i.useState(!1),R=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:F,side:Q}=Ui(),G=i.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const fe=Number.parseInt(oe[1],10),He=Number.parseInt(oe[2],10);return Number.isNaN(fe)?null:fe===10?He:fe},[]);Me.useEffect(()=>{typeof window>"u"||_(Us())},[]);const M=re(O=>O.isSessionSwitcherOpen),ee=null,H=null,ye=[],[ce,ae]=i.useState(!1),[xe,we]=i.useState(!1),[ge,ve]=i.useState("Local"),[Se,ke]=i.useState(!0),[je,Z]=i.useState(!1),[ue,L]=i.useState(null),[Y,le]=i.useState(!1),[W,X]=i.useState(null),te=i.useMemo(()=>Og(ge),[ge]),ne=i.useCallback(async()=>{if(!(typeof window>"u"||!U))try{if(dn()){ve("Local"),ke(!0);return}ke(!1);const O=await Jd(),oe=Xd(),fe=Zd([eu(oe),...O.hosts]);if(fe.id===tu){ve("Local"),ke(!0);return}ve(su(fe.label.trim()||"Instance"))}catch{ve("Local"),ke(!0)}},[U]);Me.useEffect(()=>(ne(),nu(()=>{ne()})),[ne]);const Ae=i.useCallback(async()=>{if(Se){L(null),X(null);return}le(!0),X(null);try{const O=new URLSearchParams({appType:"web",instanceMode:"remote"}),oe=await Mt(`/api/pi/update-check?${O.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!oe.ok)throw new Error(`Server responded with ${oe.status}`);const fe=await oe.json();L({available:fe.available??!1,version:fe.version,currentVersion:fe.currentVersion??"unknown",body:fe.body,nextSuggestedCheckInSec:typeof fe.nextSuggestedCheckInSec=="number"?fe.nextSuggestedCheckInSec:void 0,packageManager:fe.packageManager,updateCommand:fe.updateCommand})}catch(O){L(null),X(O instanceof Error?O.message:"Failed to check remote instance updates")}finally{le(!1)}},[Se]);i.useEffect(()=>{L(null),X(null),Z(!1)},[Se,ge]),i.useEffect(()=>{if(!U||Se)return;const O=3e3,oe=3600*1e3;let fe=!1,He=null;const Jt=it=>{He=window.setTimeout(()=>{if(fe||typeof document<"u"&&document.visibilityState!=="visible"){Jt(oe);return}Ae().finally(()=>{fe||Jt(oe)})},it)};return Jt(O),()=>{fe=!0,He!==null&&window.clearTimeout(He)}},[Ae,Se,ge,U]);const Ie=i.useCallback(()=>{if(ue?.available){Z(!0);return}Ae()},[Ae,ue?.available]),Pe=g?y??null:null,De=i.useRef(null),[Ge,de]=i.useState(0);i.useEffect(()=>{if(!g){De.current&&(De.current=null,de(He=>He+1));return}if(Pe){De.current={sessionId:g,session:Pe,expiresAt:Date.now()+2e3};return}const O=De.current;if(!O||O.sessionId!==g)return;const oe=O.expiresAt-Date.now();if(oe<=0){De.current=null,de(He=>He+1);return}const fe=window.setTimeout(()=>{De.current?.sessionId===g&&(De.current=null),de(He=>He+1)},oe);return()=>{window.clearTimeout(fe)}},[g,Pe]);const Ue=(()=>{if(Pe)return Pe;if(!g)return null;const O=De.current;return O&&O.sessionId===g&&O.expiresAt>Date.now()?O.session:null})(),Ce=i.useMemo(()=>{const O=typeof Ue?.directory=="string"?Ue.directory:"";return en(O||"")},[Ue?.directory]),Ye=Ne(O=>O.newSessionDraft?.open?en(O.newSessionDraft.directoryOverride??""):""),J=i.useMemo(()=>dg({sessionDirectory:Ce,draftDirectory:Ye,isNewSessionDraftOpen:x}),[Ye,x,Ce]),We=Oi(J||null),$e=i.useMemo(()=>ug({activeProjectLabel:v,openDirectory:J,homeDirectory:I}),[v,I,J]),Qe=!!($e||We),xt=i.useMemo(()=>g?us(Ue):$e??"PiChamber",[Ue,g,$e]),Ht=Li(),ot=_i(),Xe=Ne(O=>O.updateSessionTitle),bt=Ne(O=>O.archiveSessions),et=Ne(O=>O.deleteSessions),[tt,Nt]=i.useState(!1),[Wt,ft]=i.useState(!1),qe=i.useRef(!1),[yt,At]=i.useState(""),[Ot,ht]=i.useState(null),Yt=i.useRef(null);i.useEffect(()=>{qe.current=!1,ft(!1),Nt(!1),At(""),ht(null)},[g]);const Bt=i.useCallback(()=>{g&&(At(Ue?.title?.trim()||xt),Nt(!0))},[Ue?.title,g,xt]),It=i.useCallback(async()=>{if(!g)return;const O=yt.trim();O&&O!==Ue?.title?.trim()&&await Xe(g,O),Nt(!1)},[Ue?.title,g,yt,Xe]);i.useEffect(()=>{if(!tt)return;const O=oe=>{const fe=oe.target;(!fe||!Yt.current?.contains(fe))&&It()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[tt,It]);const qt=i.useCallback(()=>{g&&_s(g).then(O=>{se[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>se.error("Failed to copy session ID"))},[g]),_t=i.useCallback(async()=>{if(!g||!J){se.error("Nothing to export");return}try{await ot.syncSession(g)}catch{se.error("Failed to load the complete session history");return}const O=Ir(Ht.getState()).list;if(O.length===0){se.error("Nothing to export");return}const oe=Ha(O,Ue?.title??null),fe=qa(Ue?.title??null);await Ya(oe,fe)||Wa(oe,fe),se.success("Session exported")},[Ue?.title,g,Ht,J,ot]);m?.type==="busy"||m?.type;const ns=i.useCallback(async()=>{if(!g||!Ot)return;const O=md(),oe=[g];for(let it=0;it<oe.length;it+=1){const xs=oe[it];for(const zt of O)zt.parentID===xs&&!oe.includes(zt.id)&&oe.push(zt.id)}const fe=Ot;if(ht(null),(fe==="archive"?await bt(oe):await et(oe)).failedIds.length>0){se.error(fe==="archive"?"Failed to archive session":"Failed to delete session");return}se.success(fe==="archive"?"Session archived":"Session deleted")},[bt,g,et,Ot]),me=re(O=>O.isArchivePageOpen),ze=i.useMemo(()=>me?{title:"Archive",subtitle:null}:null,[me]),pe=i.useMemo(()=>en(J||b?.path||""),[b?.path,J]),Be=i.useCallback(()=>{pe&&_s(pe).then(O=>{se[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>se.error("Failed to copy working directory"))},[pe]),_e=i.useMemo(()=>b?{id:b.id,path:b.path}:null,[b]),ct=i.useRef(null);i.useEffect(()=>{!_e||!pe||(ct.current={projectRef:_e,directory:pe})},[pe,_e]);const pt=i.useMemo(()=>_e&&pe?{projectRef:_e,directory:pe}:ct.current,[pe,_e]),Dt=i.useCallback(async O=>{},[]),mt=i.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const oe=O.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||O.isContentEditable)&&O.blur()},[]),Tt=i.useCallback(()=>{if(k){mt(),l(!M);return}c()},[mt,k,M,l,c]),st=i.useCallback(()=>{rn("desktop_open_draft_mini_chat_window",{directory:en(J||b?.path||""),projectId:b?.id??null,apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[b?.id,b?.path,J]),ms=i.useCallback(()=>{if(x){st();return}g&&rn("desktop_open_session_mini_chat_window",{sessionId:g,directory:en(J||b?.path||""),apiBaseUrl:Pr(),clientToken:Er()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[b?.path,g,st,x,J]),Qt=gn,rs=oh,os=i.useMemo(()=>n?"sessions":D?r&&o?o:null:r?"git":d,[d,D,n,r,o]),wt=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&M&&l(!1)},[M,n,e,s,r,l]),gs=i.useCallback(()=>{e?.()},[e]),vt=i.useCallback(()=>{s?.()},[s]),Rs=i.useMemo(()=>U&&R&&!P?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!U||F?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[U,P,R,K,F]);Me.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Rs)},[Rs]);const ie=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ze=u?"0px":U&&F?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":S?"2.75rem":"2.5rem";Me.useEffect(()=>{if(!U||!R){B(!1);return}let O=!1;const oe=async()=>{try{const He=await rn("desktop_is_window_fullscreen");O||B(He===!0)}catch{O||B(!1)}},fe=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",fe),()=>{O=!0,window.removeEventListener("pichamber:window-resized",fe)}},[U,R]);const dt=i.useMemo(()=>!U||!R||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[U,R,G]),is=i.useMemo(()=>{if(!(U&&!F))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[U,F]),nt=i.useCallback(()=>{if(typeof document>"u")return;const O=T.current?.getBoundingClientRect().height;O&&document.documentElement.style.setProperty("--oc-header-height",`${O}px`)},[]);Me.useEffect(()=>{if(typeof window>"u")return;nt();const O=T.current;if(!O||typeof ResizeObserver>"u")return()=>{};let oe=0;const fe=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,nt()}))},He=new ResizeObserver(fe);return He.observe(O),window.addEventListener("resize",fe),window.addEventListener("orientationchange",fe),()=>{oe&&cancelAnimationFrame(oe),He.disconnect(),window.removeEventListener("resize",fe),window.removeEventListener("orientationchange",fe)}},[nt]),Me.useEffect(()=>{nt()},[nt,k,dt]);const as=i.useCallback(async O=>{const oe=O.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||O.button===0&&U&&await gd()},[U]),Vt=i.useMemo(()=>k?[{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"}]:[],[k]),qn=i.useCallback(O=>eo(Ln(O,h)),[h]);Me.useEffect(()=>{!k&&d!=="chat"&&d!=="terminal"&&d!=="diagram"&&f("chat")},[d,k,f]),Me.useEffect(()=>{const O=oe=>{if(ru(oe)&&!oe.shiftKey&&!oe.altKey){const fe=parseInt(oe.key,10);fe>=1&&fe<=Vt.length&&(oe.preventDefault(),k&&(mt(),wt()),f(Vt[fe-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[mt,wt,k,f,Vt]),Me.useEffect(()=>{const O=oe=>{const fe=Ln("toggle_services_menu",h);if(ou(oe,fe)){oe.preventDefault(),xe?we(!1):(we(!0),ne());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[h,xe,ne]);const Ys=O=>{const oe=d===O.id,fe=O.icon==="diff",He=fe?null:O.icon,Jt=O.id==="chat",it=zt=>fe?t.jsx(vi,{size:zt}):He?t.jsx(A,{name:He,className:`h-${zt/4} w-${zt/4}`}):null,xs=t.jsxs("button",{type:"button",onClick:()=>f(O.id),className:z("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",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",Jt&&!k&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":oe,role:"tab",children:[k?it(20):t.jsxs(t.Fragment,{children:[it(16),t.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return t.jsx(i.Fragment,{children:xs},O.id)},Qn=t.jsxs(t.Fragment,{children:[t.jsx(mg,{directory:pe,className:"mr-1"}),U?t.jsx(Fg,{isDesktopApp:U,currentInstanceLabel:ge,compactCurrentInstanceLabel:te,currentInstanceIsLocal:Se,isDesktopServicesOpen:xe,setIsDesktopServicesOpen:we,refreshCurrentInstanceLabel:ne,shortcutLabel:qn,remoteUpdateInfo:ue,remoteUpdateChecking:Y,remoteUpdateError:W,onOpenRemoteUpdate:Ie}):null,t.jsx(Tg,{isMobile:k,githubAuthStatus:E,githubAccounts:ye,githubAvatarUrl:ee,githubLogin:H,isSwitchingGitHubAccount:ce,handleGitHubAccountSwitch:Dt})]}),Vn=$&&(x||!!g),xn=()=>t.jsxs("div",{onMouseDown:as,className:z("app-region-drag relative flex h-12 select-none items-center pr-3",dt),style:is,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ie}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ze}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[ze?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:ze.title}),ze.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:ze.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(A,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Bg,{align:"start",children:t.jsx("button",{type:"button",className:Qt,"aria-label":"Open session switcher",children:t.jsx(A,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[tt?t.jsxs("form",{ref:Yt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),It()},children:[t.jsx("input",{value:yt,onChange:O=>At(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&Nt(!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(A,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>Nt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(A,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:x?"New session":xt}),Qe?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:[$e?t.jsx("span",{className:"truncate",children:$e}):null,We?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(A,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:We})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:g&&!x&&!tt?t.jsxs(jt,{open:Wt,onOpenChange:ft,onOpenChangeComplete:O=>{!O&&qe.current&&(qe.current=!1,Bt())},children:[t.jsx(kt,{asChild:!0,children:t.jsx(Re,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(A,{name:"more",className:"size-4"})})}),t.jsxs(Ct,{align:"end",className:"min-w-[190px]",children:[t.jsxs(Je,{onClick:()=>{qe.current=!0},children:[t.jsx(A,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(Je,{onClick:qt,children:[t.jsx(A,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(Je,{onClick:Be,disabled:!pe,children:[t.jsx(A,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(zs,{}),t.jsxs(Je,{onClick:()=>{_t()},children:[t.jsx(A,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(zs,{}),t.jsxs(Je,{onClick:()=>ht("archive"),children:[t.jsx(A,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(Je,{className:"text-destructive focus:text-destructive",onClick:()=>ht("delete"),children:[t.jsx(A,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Vt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Vt.map(O=>Ys(O))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Pa,{}),pt?t.jsx(ki,{projectRef:pt.projectRef,directory:pt.directory,className:"mr-1"}):null,t.jsx(ih,{visible:Vn,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:ms,className:z(Qt,"mr-1"),Icon:"picture-in-picture-2"}),Qn,t.jsx($i,{visible:F&&Q==="right",position:"right"})]})]})]}),qs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[S&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ie}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ze}})]}),!S&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:gs,className:z(rs,os==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(A,{name:"layout-left",className:"h-5 w-5"})}):M?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(A,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Tt,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(A,{name:"play-list-add",className:"h-5 w-5"})}),!e&&M&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!M||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!D&&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:Vt.map(O=>{const oe=d===O.id,fe=O.icon==="diff",He=fe?null:O.icon;return t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{k&&(mt(),wt()),f(O.id)},"aria-label":O.label,"aria-selected":oe,role:"tab",className:z(rs,"relative rounded-lg",os===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[fe?t.jsx(vi,{className:"h-5 w-5"}):He?t.jsx(A,{name:He,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(Le,{children:t.jsx("p",{children:O.label})})]},O.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[D&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:C.map(O=>{const oe=r&&o===O.id;return t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{k&&(mt(),wt()),j(!1),a?.(O.id)},"aria-label":O.label,"aria-selected":oe,role:"tab",className:z(rs,"relative rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(A,{name:O.icon,className:"h-5 w-5"})})}),t.jsx(Le,{children:t.jsx("p",{children:O.label})})]},O.id)})}),t.jsx(rh,{open:w,onOpenChange:j,currentSessionId:g,effectiveDirectory:J||null,isNewSessionDraftOpen:x})]}),pt&&t.jsx(ki,{projectRef:pt.projectRef,directory:pt.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!D?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:vt,className:z(rs,"relative",os==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(A,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(Le,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Es=z("header-safe-area relative z-10 bg-background",k&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:T,className:Es,style:{"--padding-scale":"1"},children:k?qs():xn()}),t.jsx(Lg,{action:Ot,onClose:()=>ht(null),sessionTitle:xt,onConfirm:()=>{ns()}}),t.jsx(va,{open:je,onOpenChange:Z,info:ue,downloading:!1,downloaded:!1,progress:null,error:W,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ci="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",_g="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Bx=()=>{const e=re(p=>p.isSidebarOpen),s=re(p=>p.toggleSidebar),n=re(p=>p.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=eo(Ln("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=Ui(),{enabled:u}=Qr(),d=!e,f=l&&c==="left",h=l,x=d||f||h,g=f||h,m=i.useCallback(()=>{rn("desktop_show_app_menu").catch(p=>{console.warn("[titlebar] failed to open app menu",p)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const p=S=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(S)}px`)},y=S=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(S)}px`)};if(!g)return;const b=o.current,I=r.current;if(!b||!I){p(0),y(0);return}const v=()=>{const S=Math.max(b.getBoundingClientRect().width,b.scrollWidth);p(S),y(I.getBoundingClientRect().width)};if(v(),typeof ResizeObserver>"u")return;const k=new ResizeObserver(v);return k.observe(b),k.observe(I),()=>{k.disconnect()}},[g]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[f?t.jsx($i,{visible:!0,position:"left"}):null,h?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:m,"aria-label":"Open PiChamber menu",className:z(Ci,"shrink-0"),children:t.jsx(A,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(Le,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,d?t.jsxs(Te,{children:[t.jsx(Fe,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:z(u?_g:Ci,"shrink-0"),children:t.jsx(A,{name:"layout-left",className:u?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(Le,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Ni=200,zg="cubic-bezier(0.22, 1, 0.36, 1)",_x=e=>{const s=i.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=i.useState(e),[o,a]=i.useState(e);return i.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),Ni);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${Ni}ms ${zg}`}},Ug=ps(()=>({statusById:new Map})),zx=()=>{Yi(),Gi()},Ux=e=>{Ne.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),re.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),Yi(),he.getState().clearAll(),$s.getState().resetForRuntimeSwitch(),xd.getState().resetForRuntimeSwitch(),bd.getState().resetForRuntimeSwitch(),yd(),wd.getState().resetForRuntimeSwitch(),$t.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ut.getState().resetForRuntimeSwitch(),vd.getState().resetForRuntimeSwitch(),Ug.setState({statusById:new Map}),Sd(),jd(),Mu.getState().reset(),iu.getState().resetForRuntimeSwitch(),Mi.getState().resetForRuntimeSwitch(e.runtimeKey),Dr.getState().resetForRuntimeSwitch(e.runtimeKey),Ns.getState().resetForRuntimeSwitch(e.runtimeKey),qh.getState().resetForRuntimeSwitch(),at.getState().resetForRuntimeSwitch(e.runtimeKey),au.getState().resetForRuntimeSwitch(e.runtimeKey),Ne.getState().restoreForRuntimeSwitch(e.runtimeKey),re.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=re.getState();Or({sessionId:Ne.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),Gi()};export{pn as $,Dx as A,Ex as B,Ia as C,Lx as D,Tn as E,dx as F,Mx as G,Ox as H,zx as I,Vu as J,ys as K,ux as L,Ea as M,rx as N,wx as O,Tf as P,io as Q,bx as R,Gm as S,Tx as T,va as U,Mf as V,ix as W,ka as X,Zf as Y,If as Z,Ff as _,Da as a,Sa as a0,mn as a1,on as a2,Rf as a3,px as a4,jx as a5,Df as a6,hx as a7,Ef as a8,Sx as a9,Nx as aa,Cx as ab,Lf as ac,vx as ad,kx as ae,Ax as af,fx as ag,mx as ah,gx as ai,xx as aj,qf as ak,yx as al,hf as am,Pf as an,pf as ao,Ra as b,Gr as c,eh as d,bs as e,_x as f,uf as g,ax as h,Fx as i,sx as j,cx as k,ox as l,Ix as m,Rx as n,Bx as o,lx as p,Pn as q,Ux as r,sh as s,rh as t,nx as u,ym as v,hi as w,tn as x,gm as y,Px as z};
|