@pi-chamber/web 1.0.6-rc.5 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView--XO16VPB.js → DiagramView-DsCdfDOP.js} +1 -1
- package/dist/assets/{DiffView-Duy2_7Gp.js → DiffView-BWo7yT-P.js} +6 -6
- package/dist/assets/{FileSaveConflictDialog-B1DvL9zy.js → FileSaveConflictDialog-IFbuQCcP.js} +1 -1
- package/dist/assets/{FilesView-CjjPpE4c.js → FilesView-DLIQkVep.js} +4 -4
- package/dist/assets/{GitHubDetailScaffold-DqxAKqCT.js → GitHubDetailScaffold-CxGg6x7R.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-ELF_chia.js → GitHubLinkPicker-BmqbTUpE.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-C2nGTntk.js → GitHubListPrimitives-a1DxU6Zp.js} +1 -1
- package/dist/assets/{GitView-5fIq2nzM.js → GitView-DbqM8Qi1.js} +5 -5
- package/dist/assets/{IssuesSurface-Dq5A_bWq.js → IssuesSurface-B2EfICtZ.js} +3 -3
- package/dist/assets/{JsonTreeView-BjFFSUwi.js → JsonTreeView-DzVqgwz-.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-B9Cu4TCh.js → MarkdownRendererImpl-7yTzCIEI.js} +3 -3
- package/dist/assets/PatchDiff-Dvfm6eOV.js +1 -0
- package/dist/assets/{PierreDiffViewer-H2f4pJ1k.js → PierreDiffViewer-ByYaUifK.js} +2 -2
- package/dist/assets/{PullRequestsSurface-DPpb2RW_.js → PullRequestsSurface-1IP_dDn8.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-B5DaBWZU.js → SessionSwitcherContent-DVxWhG4x.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-D86FaZg_.js → SessionSwitcherDropdown-DiBGmmtD.js} +2 -2
- package/dist/assets/{SessionUnreadDot-CY9-1iV2.js → SessionUnreadDot-qw67HcBO.js} +1 -1
- package/dist/assets/SettingsView-CMTIIpWD.js +6 -0
- package/dist/assets/{SettingsWindow-Bw1dUoJ1.js → SettingsWindow-DZUSs5Is.js} +1 -1
- package/dist/assets/{ToolOutputDialog-aR4kcgKL.js → ToolOutputDialog-pgTNzNPN.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-B_wWmhtE.js → ToolPartDiffPreview-Cvnr4JkU.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-BYby097w.js → VirtualizedFileDiff-D8dSHI_H.js} +3 -3
- package/dist/assets/{collapsible-Dz0bPrJ_.js → collapsible-ZT74WYMA.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-8MuwxSC6.js → computeVirtualFileMetrics-g1aOl5nF.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-fZ2NIQMQ.js → contextFileOpenGuard-IWdho_6z.js} +1 -1
- package/dist/assets/{fileTreeStatus-BzhMMLA9.js → fileTreeStatus-trDHgX4B.js} +2 -2
- package/dist/assets/{gitStatusPredicates-Cyh9UhYX.js → gitStatusPredicates-CfBh9Rne.js} +1 -1
- package/dist/assets/{githubLink-D2PznPcI.js → githubLink-CuQ2WFBa.js} +1 -1
- package/dist/assets/index-BaLCg7tL.css +1 -0
- package/dist/assets/{index-BX5pAOQX.js → index-CK9t5Znh.js} +1 -1
- package/dist/assets/{index-Cs2nBW_t.js → index-fmzQmSSv.js} +3 -3
- package/dist/assets/{main-BI6qe8pz.js → main-DOlk_lfi.js} +2 -2
- package/dist/assets/{main-7vBNPBMb.js → main-UnRe9F68.js} +4 -4
- package/dist/assets/{markdownCore-D5jiabKe.js → markdownCore-DuZmdypZ.js} +2 -2
- package/dist/assets/{miniChat-B3up4Bnz.js → miniChat-Dy9h0B6G.js} +2 -2
- package/dist/assets/{mobile-B4vLFgBc.js → mobile-CWrtn0Si.js} +2 -2
- package/dist/assets/{nativeFileSave-DpBH1Sa3.js → nativeFileSave-B4Rg6n8u.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-BrB72skF.js → pi-session-focus-preference-q-s-Bhf0.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-B6T04JGG.js → renderDiffWithHighlighter-HRnE6vfE.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CX10w321.js → renderElectronMiniChatApp-OZ2fG5eY.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-DtAcGyJr.js → renderFileWithHighlighter-tJRUQWjE.js} +1 -1
- package/dist/assets/{renderMobileApp-C9n-BhPZ.js → renderMobileApp-D1nkBJLP.js} +3 -3
- package/dist/assets/runtimeEndpointReset-Bby2E_Je.js +62 -0
- package/dist/assets/{runtimeSurface-DiP2a57a.js → runtimeSurface-X62LLBLv.js} +1 -1
- package/dist/assets/{useAppFontEffects-Oyin3dgQ.js → useAppFontEffects-BFgKpDYT.js} +86 -86
- package/dist/assets/{useGitHubRemoteSearch-CZ9Hauw0.js → useGitHubRemoteSearch-MxC4J-VO.js} +1 -1
- package/dist/assets/{useSwitcherItems-BSqDA1IF.js → useSwitcherItems-D5TsQEbM.js} +1 -1
- package/dist/assets/{web-components-CkTNGkJ2.js → web-components-B_NMC-2c.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/pi/routes.js +5 -1
- package/server/lib/pi/routes.test.js +3 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +60 -1
- package/server/lib/pi/session-daemon/session-daemon.js +34 -10
- package/server/lib/pi/session-daemon/session-engine-router.js +5 -1
- package/server/lib/pi/session-daemon/session-engine-router.test.js +21 -0
- package/dist/assets/PatchDiff-CTqTTcg7.js +0 -1
- package/dist/assets/SettingsView-CiIuOi_E.js +0 -6
- package/dist/assets/index-tmO0fZa4.css +0 -1
- package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +0 -62
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CK9t5Znh.js","assets/useAppFontEffects-BFgKpDYT.js","assets/index-fmzQmSSv.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-BaLCg7tL.css","assets/vendor-boot-3SaHYVb1.js","assets/runtimeSurface-X62LLBLv.js","assets/nativeFileSave-B4Rg6n8u.js","assets/computeVirtualFileMetrics-g1aOl5nF.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.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-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.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/renderFileWithHighlighter-tJRUQWjE.js","assets/renderDiffWithHighlighter-HRnE6vfE.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-BbiDqlyL.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/vendor-capacitor-keyboard-CgrHt8iN.js","assets/SessionSwitcherDropdown-DiBGmmtD.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as ht}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as n,aS as su,aT as ru,aU as ou,aV as iu,aW as au,aX as lu,aY as cu,aZ as Br,a_ as ds,a$ as ol,b0 as _r,b1 as mi,b2 as il,b3 as du,b4 as al,b5 as ll,b6 as cl,b7 as Eo,b8 as Do,b9 as Ro,ba as dl,bb as ul,bc as fl,bd as hl,be as pl,bf as ml,bg as gi,bh as bi,bi as uu,bj as fu,bk as hu,bl as Po,aP as pu}from"./vendor-boot-3SaHYVb1.js";import{a as Te,R as l}from"./vendor-react-Bz1tRBxM.js";import{aq as ss,ar as mu,a as ct,h as Me,t as oe,as as ms,I as R,at as Gs,au as _s,av as en,aw as tn,ax as mn,ay as Cn,B as Ae,az as qs,v as un,aA as gu,aB as zn,aC as gs,aD as Bn,aE as bu,g as ts,aF as so,aG as Gi,aH as qi,aI as zs,e as yr,aJ as xu,aK as yu,aL as wu,aM as vu,aN as Su,aO as ju,o as gl,aP as Mn,aQ as Vi,ah as fn,aR as Ke,aS as We,aT as He,aU as ku,aV as Cu,aW as Au,aX as Nu,aY as Iu,aZ as To,a_ as Eu,a$ as Gt,b0 as qt,b1 as Vt,b2 as Mo,O as Kt,b3 as Du,b4 as Ru,b5 as Pu,b6 as Tu,b7 as Mu,b8 as Fu,b9 as Fo,r as is,G as xi,ba as Lu,bb as Ou,bc as bl,bd as xl,Z as jn,be as Bu,bf as _u,bg as zu,bh as Uu,d as yl,b as Vs,bi as tr,z as Un,bj as wl,bk as Ys,bl as Yi,bm as vl,bn as gt,bo as $u,bp as Ku,bq as Sl,br as Lo,bs as jl,bt as kl,bu as yi,bv as dt,bw as Wu,bx as Hu,by as Gu,bz as Qs,bA as qu,bB as Vu,bC as Yu,bD as Qu,bE as Oo,bF as Ju,i as Cl,p as Xu,j as Zu,u as Al,k as ef,m as tf,bG as Nl,n as nf,bH as sf,q as Qi,bI as rf,bJ as Jn,c as of,bK as af,bL as lf,bM as cf,bN as Bo,bO as df,bP as uf,bQ as ff,bR as hf,bS as pf,a4 as mf,bT as us,bU as Il,M as gf,y as bf,bV as xf,w as yf,bW as wf,bX as vf,bY as El,bZ as Sf,aj as jf,b_ as kf,b$ as Cf,c0 as Af,c1 as Nf,c2 as If,c3 as Ef,c4 as Df,c5 as Rf,c6 as Pf,c7 as Tf}from"./useAppFontEffects-BFgKpDYT.js";import{A as Ji,f as _,B as Mf,h as ue,z as nt,a as fs,C as Dl,D as Rl,E as Ff,F as Lf,u as hs,G as Of,H as Bf,I as _f,J as zf,K as Ze,b as Tt,p as bs,L as Uf,M as $f,N as Kf,O as Wf,n as Re,P as Xi,Q as Wt,R as _o,T as Zi,U as zo,V as Pl,j as hn,W as wi,X as Nr,e as rs,Y as Hf,v as Tl,Z as Gf,_ as Ml,$ as qf,a0 as Fl,a1 as Us,a2 as Uo,k as $o,a3 as Vf,a4 as Yf,a5 as Qf,a6 as ea,a7 as Ds,a8 as ro,a9 as Ko,aa as Ir,ab as Fn,ac as ta,ad as Wo,ae as Ll,af as Ho,ag as Jf,ah as Xf,ai as Zf,aj as eh,ak as th,al as nh,am as sh,an as rh,ao as oh,ap as Ol,aq as ih,ar as ah,as as lh,at as ch,au as dh}from"./index-fmzQmSSv.js";import{b as uh,d as Bl,g as xs,s as wr,c as _l,e as _n,h as ps,i as fh,j as hh,k as ph,l as mh,f as gh,a as na,S as bh,t as xh,m as yh}from"./SessionUnreadDot-qw67HcBO.js";import{c as $n,d as zr,p as zl,a as wh}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{saveOrShareFile as vh}from"./nativeFileSave-B4Rg6n8u.js";import{usePermissionStore as Sh}from"./permissionStore-zIpxq9Pq.js";const jh="chat";function Ul(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(ss.SESSION,e.sessionId),e.isSettingsOpen){const s=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(ss.SETTINGS,s),t}return e.tab!==jh&&t.set(ss.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(ss.FILE,e.diffFile),t}function kh(e,t){const s=typeof window<"u"?window.location.pathname:"/",r=s.startsWith("/session")||s.startsWith("/s/")?"/":s,o=e.toString();return o?`${r}?${o}`:r}function Ch(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),s=Ul(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(ss.SESSION)&&t.set(ss.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==a[c][0]||i[c][1]!==a[c][1])return!1;return!0}catch{return!0}}function Go(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Ch(e)))try{const s=Ul(e),r=kh(s);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ah=["typescript","javascript","tsx","jsx","json","markdown"],$l={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let sa=null;const Kl=()=>(sa??=Promise.all([ht(()=>import("./index-CK9t5Znh.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])),ht(()=>import("./workerFactory-DlGfNFqf.js"),[]),ht(()=>import("./appThemeRegistry-Ca8eGRB9.js"),__vite__mapDeps([43,44,30,31,5,15,16,17,18,19,20,21,22,23,24,25,26,27,28]))]).then(([e,t,s])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:s.ensurePierreThemeRegistered})),sa),Js={},ra=new Set,qo=new Set;let vr={light:"pierre-light",dark:"pierre-dark"};const Nh=()=>{for(const e of qo)e()},Wl=(e,t)=>{t.setRenderOptions({theme:vr,lineDiffType:$l[e].lineDiffType})},Vo=e=>{typeof window>"u"||ra.has(e)||(ra.add(e),Kl().then(t=>{if(Js[e])return;const s=$l[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:s.poolSize,totalASTLRUCacheSize:s.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ah,lineDiffType:s.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Js[e]=r,Wl(e,r),Nh()}))},Ih=e=>(qo.add(e),()=>qo.delete(e)),Eh=e=>{if(!(vr.light===e.light&&vr.dark===e.dark)){vr=e;for(const t of Object.keys(Js)){const s=Js[t];s&&Wl(t,s)}}},Vy=({children:e})=>{const t=mu(),s=Ji(!1),r=Ji(!0),o=t?.lightThemeId??s.metadata.id,i=t?.darkThemeId??r.metadata.id,a=t?.availableThemes.find(d=>d.metadata.id===o)??s,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Te.useEffect(()=>{let d=!1;return Kl().then(u=>{d||(u.ensurePierreThemeRegistered(a),u.ensurePierreThemeRegistered(c),Eh({light:a.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,a]),Te.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Vo("unified"),Vo("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),n.jsx(n.Fragment,{children:e})},Yy=(e="unified")=>{const t=Te.useSyncExternalStore(Ih,()=>Js[e],()=>{});return Te.useEffect(()=>{Vo(e)},[e]),t},Dh=e=>{const t=e.trim();return t&&(t.split(/[?#]/,1)[0]||t).match(/([^/:]+?)(?:\.git)?\/?$/)?.[1]?.trim()||""},Rh=e=>{const t=e.trim();return t?/[/\\]/.test(t)?"A name can’t contain / or \\.":t==="."||t===".."?"Choose a different name.":null:"Enter a name for the folder."},oa=(e,t)=>e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t,Yo=({children:e,className:t})=>n.jsx("kbd",{className:_("inline-flex h-4 min-w-4 normal-case items-center justify-center rounded border border-border bg-[var(--surface-muted)] px-1 font-sans typography-micro text-muted-foreground",t),children:e}),Ph=({hints:e})=>n.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",children:e.map(t=>{const s=n.jsxs(n.Fragment,{children:[t.keys.map(r=>n.jsx(Yo,{children:r},r)),n.jsx("span",{children:t.label})]});return t.onSelect?n.jsx("button",{type:"button",onClick:t.onSelect,className:"-mx-1 flex items-center gap-1 rounded px-1 transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s},t.label):n.jsx("span",{className:"flex items-center gap-1",children:s},t.label)})}),Hl=l.forwardRef(({id:e,active:t,onSelect:s,onHover:r,ariaLabel:o,ariaChecked:i,className:a,quiet:c=!1,children:d},u)=>n.jsx("div",{ref:u,id:e,role:"option","aria-selected":t,"aria-checked":i,"aria-label":o,onMouseMove:t?void 0:r,onMouseDown:f=>f.preventDefault(),onClick:s,className:_("flex w-full cursor-pointer select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left typography-ui-label text-foreground",t&&(c?"group-focus-within/palette:bg-interactive-hover":"group-focus-within/palette:bg-interactive-selection group-focus-within/palette:text-interactive-selection-foreground"),!t&&"hover:bg-interactive-hover/60",a),children:d}));Hl.displayName="PaletteRow";const Th=e=>e==="/",kn=e=>e.replace(/\\/g,"/"),pn=e=>{if(!e||Th(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},as=e=>e.endsWith("/"),$s=e=>{const t=e.trim();return!t||as(t)?t:`${t}/`},vi=e=>e.lastIndexOf("/"),Mh=e=>{if(as(e))return e;const t=vi(e);return t<0?e:e.slice(0,t+1)},Fh=e=>{const t=vi(e);return e.slice(t+1)},Gl=e=>{const t=pn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const s=vi(t);return s<0?null:t.startsWith("~/")&&s<=1?"~/":s===0?"/":`${t.slice(0,s)}/`},Lh=e=>as(e)&&Gl(e)!==null,Sr=e=>{if(!e)return null;const t=pn(kn(e.trim()));return t?t.toLowerCase():null},oo=(e,t)=>{const s=e.trim();return s==="~"?t:s.startsWith("~/")?`${t}${s.slice(1)}`:s},Oh=(e,t)=>{const s=pn(kn(e.trim())),r=pn(kn(t.trim()));if(!s)return"";if(!r)return $s(s);if(s.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return s.toLowerCase().startsWith(o.toLowerCase())?`~/${s.slice(r.length+1)}/`:$s(s)},ql=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),Bh=e=>ql()?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,_h=()=>ql()?"⌘":"Ctrl",zh=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Uh=async()=>Mf({fresh:!0}),cr=async(e,t)=>{try{const s=await e.json();if(typeof s.error=="string"&&s.error.trim())return s.error.trim()}catch{}return t},io=(e,t,s)=>nt(e,{method:"POST",headers:{"Content-Type":"application/json"},query:s,body:JSON.stringify(t)});function $h({open:e,onClose:t,isMobile:s}){const r=ct(x=>x.addProject),o=ue(x=>x.setActiveMainTab),i=ue(x=>x.setSessionSwitcherOpen),a=Me(x=>x.openNewSessionDraft),[c,d]=l.useState(null),[u,f]=l.useState(null);l.useEffect(()=>{e&&(d(null),f(null))},[e]);const m=l.useCallback(x=>{const C=r(x);return C?(o("chat"),s&&i(!1),a({selectedProjectId:C.id,directoryOverride:C.path}),t(),!0):(f("PiChamber couldn’t add this folder. Check that the path is a folder."),!1)},[r,s,t,a,o,i]),g=l.useCallback(async(x,C)=>{if(!c){d(x),f(null);try{await C()}catch(S){f(S instanceof Error&&S.message?S.message:"Something went wrong. Try again.")}finally{d(null)}}},[c]),b=l.useCallback((x,C)=>g("add",async()=>{if(C.create){const S=await io("/api/fs/mkdir",{path:x},{directory:C.location});if(!S.ok)throw new Error(await cr(S,"Couldn’t create the folder."))}m(x)}),[m,g]),p=l.useCallback((x,C)=>g("clone",async()=>{const S=await io("/api/fs/clone",{remoteUrl:x.trim(),destinationPath:`${pn(C)}/`});if(!S.ok){const y=(await cr(S,"The clone failed.")).replace(/^Cloning into '[^']*'\.\.\.\s*/,"").replace(/^fatal:\s*/,"");throw new Error(y.charAt(0).toUpperCase()+y.slice(1))}const A=await S.json();if(typeof A.path!="string"||!A.path)throw new Error("The clone finished, but the server didn’t say where. Add the folder from Folder on this server.");m(A.path)}),[m,g]),h=l.useCallback((x,C,S)=>g("create",async()=>{const A=`${pn(x)}/${C.trim()}`,y=await io("/api/fs/mkdir",{path:A},{directory:x});if(!y.ok)throw new Error(await cr(y,"Couldn’t create the folder."));if(S){const j=await nt("/api/git/init",{method:"POST",query:{directory:A}});if(!j.ok){const v=await cr(j,"git init failed.");throw new Error(`The folder was created, but git init failed: ${v}`)}}m(A)}),[m,g]),w=l.useCallback(()=>f(null),[]);return{pending:c,error:u,clearError:w,addFolder:b,cloneRepository:p,createProject:h}}const Kh=()=>{const[e,t]=Te.useState(!1),[s,r]=Te.useState(!1);Te.useEffect(()=>{t(fs()),r(Dl())},[]);const o=Te.useCallback(async c=>e?await Rl(c):{success:!0,path:c},[e]),i=Te.useCallback(async c=>e?await Ff():{success:!0},[e]),a=Te.useCallback(async c=>e?await Lf():{success:!0},[e]);return{isDesktop:e,canRequestAccess:s,requestAccess:o,startAccessing:i,stopAccessing:a}},ao=async(e,t)=>{try{const r=(await Bf(t)).filter(o=>o.isDirectory).map(o=>({name:o.name,path:kn(o.path)})).sort((o,i)=>o.name.localeCompare(i.name));return{displayDir:e,absoluteDir:t,entries:r,error:null}}catch(s){return{displayDir:e,absoluteDir:t,entries:[],error:_f(s)?s.reason:"unknown"}}},Wh=250;function Hh({open:e,addedProjectPaths:t}){const s=hs(W=>W.homeDirectory),{canRequestAccess:r,startAccessing:o}=Kh(),[i,a]=l.useState(""),[c,d]=l.useState("~/"),[u,f]=l.useState(null),[m,g]=l.useState(!1),[b,p]=l.useState(!1),[h,w]=l.useState(!1),x=l.useRef(0),C=i||s;l.useEffect(()=>{if(!e)return;x.current+=1,d("~/"),f(null),p(!1),w(!1);let W=!1;return(async()=>{const ae=await Uh();W||a(ae||s||"")})(),()=>{W=!0}},[s,e]);const S=l.useMemo(()=>Mh(c),[c]),A=l.useMemo(()=>as(c)?"":Fh(c),[c]),y=l.useMemo(()=>C?oo(S,C):"",[S,C]),j=!!(u&&u.displayDir===S&&u.absoluteDir===y);l.useEffect(()=>{if(!e||!y||j)return;const W=++x.current;ao(S,y).then(L=>{W===x.current&&f(L)})},[y,S,j,e]),l.useEffect(()=>{if(j||!y){g(!1);return}const W=window.setTimeout(()=>g(!0),Wh);return()=>window.clearTimeout(W)},[y,j]);const v=l.useCallback(async W=>{const L=$s(W);if(!C)return d(L),!0;const ae=++x.current,J=await ao(L,oo(L,C));return ae!==x.current?!1:(f(J),d(L),!0)},[C]),k=l.useCallback(()=>{if(!y)return;const W=++x.current;ao(S,y).then(L=>{W===x.current&&f(L)})},[y,S]),E=l.useMemo(()=>j?A:!u||!c.startsWith(u.displayDir)?"":c.slice(u.displayDir.length).split("/")[0]??"",[A,j,u,c]),P=l.useMemo(()=>{if(!u)return[];const W=E.toLowerCase(),L=h||E.startsWith(".");return u.entries.filter(ae=>ae.name.toLowerCase().startsWith(W)&&(L||!ae.name.startsWith(".")))},[E,u,h]),z=l.useMemo(()=>{if(!u||u.error)return[];const W=[],L=Lh(u.displayDir)?Gl(u.displayDir):null;if(L){const ae=Sr(u.absoluteDir);W.push({type:"parent",value:"browse:up",name:"..",path:u.absoluteDir,target:L,alreadyAdded:!!(ae&&t.has(ae))})}for(const ae of P){const J=Sr(ae.path);W.push({type:"directory",value:`browse:${ae.path}`,name:ae.name,path:ae.path,target:`${$s(u.displayDir)}${ae.name}/`,alreadyAdded:!!(J&&t.has(J))})}return W},[t,P,u]),K=j?u?.error??null:null,q=l.useMemo(()=>j&&u?u.entries:[],[j,u]),G=l.useMemo(()=>C?pn(oo(c,C)):"",[C,c]),F=Sr(G),D=!!(F&&t.has(F)),T=l.useMemo(()=>A?q.find(W=>W.name===A)??null:null,[A,q]),I=!!(j&&G&&!D&&(K===null||K==="not-found")&&(as(c)&&K==="not-found"||!as(c)&&A.trim().length>0&&T===null)),M=l.useCallback(async W=>{const L=await o(W);if(!L.success)return oe.error("Failed to open directory",{description:L.error||"Desktop could not grant file access."}),!1;const ae=C?Oh(W,C):$s(kn(W));return await v(ae),!0},[C,v,o]),H=l.useCallback(async()=>{if(!b){p(!0);try{if(Dl()){const L=await Rl(G);if(!L.success||!L.path){L.error&&L.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:L.error});return}await M(L.path);return}const W=await Of(G);if(W.status==="cancelled")return;if(W.status!=="picked"){oe.error("Couldn't open a folder picker",{description:W.error});return}await M(W.path)}catch(W){oe.error("Failed to select directory",{description:W instanceof Error?W.message:"Unknown error occurred."})}finally{p(!1)}}},[M,b,G]);return{query:c,setQuery:d,isSettled:j,showLoading:m,browseErrorReason:K,reload:k,isPickingLocation:b,showHidden:h,setShowHidden:w,explorerRootDirectory:C,browseDirectoryDisplayPath:S,browseDirectoryAbsolutePath:y,browseFilterQuery:A,entries:q,rows:z,targetPath:G,isAlreadyAdded:D,shouldCreateTarget:I,canRequestAccess:r,navigate:v,handleBrowseLocation:H}}const Gh={folder:"source","clone-url":"source","clone-location":"clone-url","new-name":"source","new-location":"new-name"},zt=e=>e==="folder"||e==="clone-location"||e==="new-location",qh=[{step:"folder",icon:"folder-6",title:"Folder on this server",description:"Pick a folder that’s already here."},{step:"clone-url",icon:"download-cloud",title:"Clone a repository",description:"Copy a Git repository from a URL."},{step:"new-name",icon:"folder-add",title:"New project",description:"Start an empty folder, with Git if you want it."}],Vh={folder:"Open folder","clone-url":"Clone","clone-location":"Clone","new-name":"New project","new-location":"New project"},Yh={source:"Choose where the project comes from, type a folder path, or paste a Git URL.",folder:"Pick a folder on this server or type its path.","clone-url":"Paste the URL of the repository to clone.","clone-location":"Pick the folder the repository is cloned into.","new-name":"Name the new project.","new-location":"Pick the folder the new project goes in."},Qh={source:"Filter sources, type a folder path, or paste a Git URL",folder:"Folder path","clone-url":"Repository URL","clone-location":"Location","new-name":"Project name","new-location":"Location"},Jh={source:"Choose a source, type a path, or paste a Git URL",folder:"~/","clone-url":"https://github.com/owner/repo.git","clone-location":"~/","new-name":"Project name","new-location":"~/"},Xh=e=>/^(~|\/|[a-zA-Z]:[\\/])/.test(e),Zh=e=>/^(https?:\/\/|ssh:\/\/|git:\/\/|git@)/i.test(e)||/^[\w.-]+@[\w.-]+:/.test(e),ep=e=>pn(kn(e)).split("/").pop()??"",tp=({open:e,onOpenChange:t})=>{const s=ct(U=>U.projects),{isMobile:r,isTablet:o}=ms(),i=r||o,[a,c]=l.useState("source"),[d,u]=l.useState(""),[f,m]=l.useState(""),[g,b]=l.useState(""),[p,h]=l.useState(!0),[w,x]=l.useState(null),C=l.useRef(null),S=l.useRef(new Map),A=l.useId(),y=l.useMemo(()=>new Set(s.map(U=>Sr(U.path)).filter(U=>!!U)),[s]),j=l.useCallback(()=>t(!1),[t]),v=Hh({open:e,addedProjectPaths:y}),{pending:k,error:E,clearError:P,addFolder:z,cloneRepository:K,createProject:q}=$h({open:e,onClose:j,isMobile:r});l.useEffect(()=>{e&&(c("source"),u(""),m(""),b(""),h(!0),x(null))},[e]),l.useEffect(()=>{P()},[v.query,P,g,f,a]),l.useLayoutEffect(()=>{e&&(i&&a!=="clone-url"&&a!=="new-name"||zh(C.current))},[i,e,a]);const G=l.useCallback(U=>{c(U),x(null)},[]),F=l.useCallback(()=>{k||a==="source"||G(Gh[a])},[G,k,a]),{navigate:D}=v,T=l.useCallback(U=>{const ge=U.type==="parent"?`dir:${ep(U.path)}`:null;D(U.target).then(se=>{se&&x(ge)})},[D]),I=l.useMemo(()=>new Set(v.entries.map(U=>U.name)),[v.entries]),M=v.browseDirectoryDisplayPath,H=v.browseErrorReason==="not-found"?"This folder doesn’t exist. Pick a location that does.":v.browseErrorReason?"PiChamber can’t read this location.":null,W=!v.isSettled||v.isPickingLocation,L=Dh(f),ae=g.trim(),J=Rh(ae);let le=!1,Ie="",Y="",B=null;if(a==="folder"){Y="Adding…";const U=pn(v.query.trim())||v.query.trim();if(v.isAlreadyAdded)Ie="Added",U&&(B={tone:"outcome",text:"Already added:",path:U});else{Ie=v.shouldCreateTarget?"Create and add":"Add";const ge=v.browseErrorReason&&v.browseErrorReason!=="not-found";le=!!v.targetPath&&!ge&&!W,U&&!ge&&(B={tone:"outcome",text:v.shouldCreateTarget?"Creates and adds":"Adds",path:U})}}else if(a==="clone-location"){Ie="Clone",Y="Cloning…";const U=oa(M,L);H?B={tone:"problem",text:H}:I.has(L)?B={tone:"problem",text:"Already exists:",path:U}:(B={tone:"outcome",text:"Clones into",path:U},le=!!L&&!W)}else if(a==="new-location"){Ie="Create",Y="Creating…";const U=oa(M,ae);H?B={tone:"problem",text:H}:J?B={tone:"problem",text:J,path:U}:I.has(ae)?B={tone:"problem",text:"Already exists:",path:U}:(B={tone:"outcome",text:"Creates",path:U},le=!W)}le=le&&k===null;const $=()=>{le&&(a==="folder"?z(v.targetPath,{create:v.shouldCreateTarget,location:v.browseDirectoryAbsolutePath}):a==="clone-location"?K(f,v.browseDirectoryAbsolutePath):a==="new-location"&&q(v.browseDirectoryAbsolutePath,ae,p))},X=a==="clone-url"?!!L:a==="new-name"?!!ae&&!J:!1,ee=()=>{X&&G(a==="clone-url"?"clone-location":"new-location")},ie=[];if(a==="source"){const U=d.trim().toLowerCase();for(const ge of qh)U&&!`${ge.title} ${ge.description}`.toLowerCase().includes(U)||ie.push({key:`source:${ge.step}`,kind:"source",select:()=>G(ge.step),content:n.jsxs(n.Fragment,{children:[n.jsx(R,{name:ge.icon,className:"size-4 shrink-0 text-muted-foreground"}),n.jsxs("span",{className:"flex min-w-0 flex-1 flex-col py-0.5",children:[n.jsx("span",{className:"truncate",children:ge.title}),n.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:ge.description})]})]})})}else if(zt(a)){a==="new-location"&&ie.push({key:"toggle:git",kind:"toggle",select:()=>h(U=>!U),ariaChecked:p,ariaLabel:"Initialize a Git repository",content:n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"pointer-events-none flex size-4 shrink-0 items-center justify-center",children:n.jsx(Gs,{checked:p,onChange:h})}),n.jsx("span",{className:"flex-1 truncate",children:"Initialize a Git repository"})]})});for(const U of v.rows){const ge=U.type==="parent";ie.push({key:ge?"browse:up":`dir:${U.name}`,kind:ge?"parent":"directory",select:()=>T(U),ariaLabel:ge?`Up to ${U.target}`:`${U.name}${U.alreadyAdded?", already added":""}`,content:n.jsxs(n.Fragment,{children:[n.jsx(R,{name:ge?"arrow-up-s":"folder-6",className:"size-4 shrink-0 text-muted-foreground"}),ge?n.jsxs("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[n.jsx("span",{className:"shrink-0",children:"Up to"}),n.jsx(_s,{value:U.target,className:"min-w-0 font-mono typography-meta text-muted-foreground"})]}):n.jsx("span",{className:"min-w-0 flex-1 truncate",children:U.name}),!ge&&U.alreadyAdded?n.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:"Added"}):null]})})}}const Ce=zt(a)?ie.findIndex(U=>U.kind==="directory"):ie.length>0?0:-1,pe=w?ie.findIndex(U=>U.key===w):-1,je=pe>=0?pe:Ce,be=je>=0?ie[je]:void 0,ze=be?.key,me=U=>`${A}-option-${U}`;l.useLayoutEffect(()=>{ze&&S.current.get(ze)?.scrollIntoView({block:"nearest"})},[ze]);const Pe=U=>{if(ie.length===0)return;const ge=je>=0?je:U>0?-1:ie.length,se=Math.min(ie.length-1,Math.max(0,ge+U));x(ie[se]?.key??null)},V=a==="source"?d:a==="clone-url"?f:a==="new-name"?g:v.query,fe=U=>{if(x(null),a==="source"){const ge=U.trimStart();if(Zh(ge)){u(""),m(ge),G("clone-url");return}if(Xh(ge)){u(""),v.setQuery(ge==="~"?"~/":kn(ge)),G("folder");return}u(U);return}if(a==="clone-url"){m(U);return}if(a==="new-name"){b(U);return}v.setQuery(kn(U).replace(/\/{2,}/g,"/"))},xe=U=>{if(!U.nativeEvent.isComposing){if(U.key==="ArrowDown"||U.key==="ArrowUp"){if(ie.length===0)return;U.preventDefault(),Pe(U.key==="ArrowDown"?1:-1);return}if(U.key==="Enter"){if(U.preventDefault(),k)return;if(zt(a)&&Bh(U)){$();return}if(a==="clone-url"||a==="new-name"){ee();return}be?be.select():zt(a)&&$();return}if(U.key==="Tab"&&!U.shiftKey&&be?.kind==="directory"){U.preventDefault(),be.select();return}U.key==="Backspace"&&V===""&&a!=="source"&&(U.preventDefault(),F())}},te=_h(),re=[];ie.length>1&&re.push({keys:["↑","↓"],label:"Navigate"}),a==="source"?be&&re.push({keys:["↵"],label:"Select"}):a==="clone-url"||a==="new-name"?re.push({keys:["↵"],label:"Continue"}):be?re.push({keys:["↵"],label:be.kind==="toggle"?"Toggle":"Open"}):re.push({keys:["↵"],label:Ie}),a!=="source"&&V===""&&re.push({keys:["⌫"],label:"Back"}),re.push({keys:["Esc"],label:"Close",onSelect:()=>t(!1)});const Be=zt(a)&&be?[te,"↵"]:["↵"];let ke=null;zt(a)?ke=n.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!le,onMouseDown:U=>U.preventDefault(),onClick:$,children:[k?Y:Ie,!r&&!k&&le?n.jsx("span",{className:"flex items-center gap-0.5",children:Be.map(U=>n.jsx(Yo,{className:"border-current/30 bg-transparent text-current",children:U},U))}):null]}):(a==="clone-url"||a==="new-name")&&(ke=n.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!X,onMouseDown:U=>U.preventDefault(),onClick:ee,children:["Continue",!r&&X?n.jsx(Yo,{className:"border-current/30 bg-transparent text-current",children:"↵"}):null]}));let Q=null;const ve=ie.filter(U=>U.kind==="directory").length;a==="source"&&ie.length===0?Q={tone:"quiet",text:"Nothing matches. Type a folder path, or paste a Git URL."}:a==="clone-url"?f.trim()?L?Q={tone:"quiet",text:n.jsxs(n.Fragment,{children:["Clones as ",n.jsx("span",{className:"font-mono text-foreground",children:L}),". Press Enter to choose where it goes."]})}:Q={tone:"problem",text:"This URL doesn’t name a repository."}:Q={tone:"quiet",text:"Paste the repository’s HTTPS or SSH URL, then press Enter to choose where it goes."}:a==="new-name"?ae?J?Q={tone:"problem",text:J}:Q={tone:"quiet",text:n.jsxs(n.Fragment,{children:["Press Enter to choose where ",n.jsx("span",{className:"font-mono text-foreground",children:ae})," goes."]})}:Q={tone:"quiet",text:"Name the project, then press Enter to choose where it goes."}:zt(a)&&(v.browseErrorReason==="not-found"?Q=a==="folder"?{tone:"quiet",text:"This folder doesn’t exist yet. Adding it creates it."}:{tone:"problem",text:"This folder doesn’t exist. Pick a location that does."}:v.browseErrorReason?Q={tone:"problem",text:v.browseErrorReason==="os-permission"?"PiChamber needs access to this folder.":"Couldn’t read this folder.",actions:n.jsxs(n.Fragment,{children:[v.browseErrorReason==="os-permission"&&v.canRequestAccess?n.jsx(Ae,{size:"xs",onClick:()=>{v.handleBrowseLocation()},disabled:v.isPickingLocation,children:"Grant access"}):null,n.jsx(Ae,{variant:"outline",size:"xs",onClick:v.reload,children:"Try again"})]})}:v.showLoading&&ve===0?Q={tone:"quiet",text:"Loading folders…"}:v.isSettled&&ve===0&&(Q={tone:"quiet",text:v.browseFilterQuery?a==="folder"?n.jsxs(n.Fragment,{children:["No folder named ",n.jsx("span",{className:"font-mono text-foreground",children:v.browseFilterQuery})," here. Adding it creates it."]}):"No folders match.":"No folders in here."}));const he=E?n.jsx("p",{role:"alert",className:"border-b border-border/60 px-4 py-2 typography-meta text-[var(--status-error)] text-pretty",children:E}):null,Se=(U,ge)=>n.jsx("button",{type:"button",onClick:F,disabled:k!==null,"aria-label":ge,className:"ml-auto shrink-0 rounded px-1 typography-ui-label text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:pointer-events-none disabled:opacity-50",children:U}),qe=B?n.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/60 px-4 py-2",children:[a==="new-location"?n.jsxs("div",{className:"flex min-w-0 items-center gap-2 typography-ui-label",children:[n.jsx("label",{htmlFor:"new-project-name",className:"shrink-0 text-muted-foreground",children:"Name"}),n.jsx("input",{value:g,onChange:U=>b(U.target.value),onKeyDown:U=>{U.nativeEvent.isComposing||U.key==="Enter"&&(U.preventDefault(),$())},id:"new-project-name",spellCheck:!1,autoComplete:"off",disabled:k!==null,className:"h-7 min-w-0 flex-1 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-1.5 font-mono text-foreground outline-none focus-visible:border-[var(--interactive-focus)] focus-visible:ring-2 focus-visible:ring-primary/30"})]}):null,n.jsxs("p",{className:_("flex min-w-0 items-baseline gap-1.5 typography-ui-label",B.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:[n.jsx("span",{className:"shrink-0",children:B.text}),B.path?n.jsx(_s,{value:B.path,className:"min-w-0 font-mono text-foreground"}):null]}),a==="clone-location"?n.jsxs("p",{className:"flex min-w-0 items-baseline gap-1.5 typography-ui-label text-muted-foreground",children:[n.jsx("span",{className:"shrink-0",children:"From"}),n.jsx(_s,{value:f.trim(),className:"min-w-0 font-mono text-foreground"}),Se("Change","Change the repository URL")]}):null]}):null,Ue=a!=="source"&&a!=="new-name";return n.jsx(en,{open:e,onOpenChange:t,children:n.jsxs(tn,{showCloseButton:!1,initialFocus:i?!1:C,className:_("group/palette w-full max-w-xl gap-0 self-start overflow-hidden rounded-2xl p-0","mt-[max(env(safe-area-inset-top),0.25rem)] max-h-[calc(100%-0.5rem)] sm:mt-[10vh] sm:max-h-[80vh]"),children:[n.jsx(mn,{className:"sr-only",children:"Add folder"}),n.jsx(Cn,{className:"sr-only",children:Yh[a]}),n.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-border/60 pl-2.5 pr-2",children:[a==="source"?n.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center text-muted-foreground",children:n.jsx(R,{name:"folder-add",className:"size-4"})}):n.jsx(Ae,{variant:"ghost",size:"icon",className:"size-7 shrink-0",onMouseDown:U=>U.preventDefault(),onClick:F,disabled:k!==null,"aria-label":"Back",title:"Back",children:n.jsx(R,{name:"arrow-left-s",className:"size-4"})}),a!=="source"?n.jsxs("span",{className:"flex shrink-0 items-center gap-2 typography-ui-label font-medium text-foreground","aria-hidden":"true",children:[Vh[a],n.jsx("span",{className:"h-4 w-px bg-border"})]}):null,n.jsx("input",{ref:C,value:V,onChange:U=>fe(U.target.value),onKeyDown:xe,readOnly:k!==null,"aria-busy":k!==null||void 0,"aria-label":Qh[a],placeholder:Jh[a],role:"combobox","aria-expanded":ie.length>0,"aria-controls":A,"aria-autocomplete":"list","aria-activedescendant":je>=0?me(je):void 0,"aria-invalid":Q?.tone==="problem"&&!zt(a)?!0:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("min-w-0 flex-1 text-foreground outline-none placeholder:text-muted-foreground",a==="source"?"h-full bg-transparent":"h-8 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2","typography-markdown md:typography-ui-label",Ue&&"font-mono")}),ke]}),qe,he,n.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain sm:max-h-[min(24rem,52vh)]",children:[ie.length>0?n.jsx("div",{id:A,role:"listbox","aria-label":a==="source"?"Sources":"Folders",className:"flex flex-col gap-px p-1.5",children:ie.map((U,ge)=>n.jsxs(l.Fragment,{children:[ge>0&&ie[ge-1]?.kind==="toggle"?n.jsx("div",{role:"presentation",className:"mx-2.5 my-1 h-px bg-border/60"}):null,n.jsx(Hl,{ref:se=>{se?S.current.set(U.key,se):S.current.delete(U.key)},id:me(ge),active:ge===je,onSelect:U.select,onHover:()=>x(U.key),ariaLabel:U.ariaLabel,ariaChecked:U.ariaChecked,className:U.kind==="source"?"py-2":void 0,quiet:zt(a),children:U.content})]},U.key))}):null,Q?n.jsxs("div",{className:_("flex flex-col items-center gap-3 px-6 text-center",ie.length>0?"pb-6 pt-3":"py-8"),children:[n.jsx("p",{className:_("typography-meta text-balance",Q.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:Q.text}),Q.actions?n.jsx("div",{className:"flex items-center gap-2",children:Q.actions}):null]}):null]}),!r||zt(a)?n.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-3 border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:[r?n.jsx("span",{}):n.jsx(Ph,{hints:re}),zt(a)?n.jsxs("span",{className:"flex shrink-0 items-center gap-3",children:[n.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5",children:[n.jsx(Gs,{checked:v.showHidden,onChange:v.setShowHidden,ariaLabel:"Show hidden folders"}),"Hidden"]}),n.jsx(Ae,{variant:"ghost",size:"xs",disabled:k!==null||v.isPickingLocation,onMouseDown:U=>U.preventDefault(),onClick:()=>{v.handleBrowseLocation()},title:"Pick a folder with the system dialog",children:v.isPickingLocation?"Opening…":"Browse…"})]}):null]}):null]})})},dr=e=>e?n.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Qy=()=>{const[e,t]=l.useState(!1),[s,r]=l.useState(null),[o,i]=l.useState(!1),a=Me(j=>j.deleteSession),c=Me(j=>j.deleteSessions),d=ue(j=>j.showDeletionDialog),u=ue(j=>j.setShowDeletionDialog),{isMobile:f,isTablet:m,hasTouchInput:g}=ms(),b=f||m||g;l.useEffect(()=>zf(()=>{t(!1)}),[]);const p=l.useCallback(j=>{r({sessions:j.sessions,dateLabel:j.dateLabel})},[]),h=l.useCallback(()=>{r(null),i(!1)},[]),w=l.useCallback(async j=>{if(j.sessions.length===0)return;if(j.sessions.length===1){const P=j.sessions[0];await a(P.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const v=j.sessions.map(P=>P.id),{deletedIds:k,failedIds:E}=await c(v);if(k.length>0){const P=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:j.dateLabel?`Removed all sessions from ${j.dateLabel}.`:void 0;oe.success(k.length===1?"Deleted {count} session":`Deleted ${k.length} sessions`,{description:dr(P)})}E.length>0&&oe.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:dr("Please try again in a moment.")})},[a,c]);l.useEffect(()=>qs.onDeleteRequest(j=>{if(!d){w(j);return}p(j)}),[p,d,w]),l.useEffect(()=>qs.onDirectoryRequest(()=>{t(!0)}),[]);const x=l.useCallback(async()=>{if(s){i(!0);try{if(s.sessions.length===1){const j=s.sessions[0];if(!await a(j.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const j=s.sessions.map(P=>P.id),v=await c(j),k=v.deletedIds,E=v.failedIds;if(k.length>0){const P=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:s.dateLabel?`Removed all sessions from ${s.dateLabel}.`:void 0;oe.success(k.length===1?"Deleted {count} session":`Deleted ${k.length} sessions`,{description:dr(P),action:{label:"OK",onClick:()=>{}}})}if(E.length>0&&(oe.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:dr("Please try again in a moment.")}),k.length===0)){i(!1);return}}h()}finally{i(!1)}}},[s,a,c,h]),C=s?s.sessions.length===1?s.dateLabel?`This action permanently removes 1 session from ${s.dateLabel}.`:"This action permanently removes 1 session.":s.dateLabel?`This action permanently removes ${s.sessions.length} sessions from ${s.dateLabel}.`:`This action permanently removes ${s.sessions.length} sessions.`:"",S=s?n.jsxs("div",{className:"space-y-2",children:[s.sessions.length>0&&n.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:n.jsxs("ul",{className:"space-y-0.5",children:[s.sessions.slice(0,5).map(j=>n.jsx("li",{className:"typography-micro text-subtle-foreground",children:n.jsx("span",{className:"truncate",children:un(j)})},j.id)),s.sessions.length>5&&n.jsx("li",{className:"typography-micro text-subtle-foreground",children:`+${s.sessions.length-5} more`})]})}),n.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:n.jsx("p",{className:"typography-meta text-subtle-foreground",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=n.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[n.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?n.jsx(R,{name:"checkbox-blank",className:"size-4"}):n.jsx(R,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ae,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":s?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),y=s?.sessions.length===1?"Delete session":"Delete sessions";return n.jsxs(n.Fragment,{children:[b?n.jsx(gu,{open:!!s,onClose:()=>{o||h()},title:y,footer:n.jsx("div",{className:"flex justify-end gap-2",children:A}),children:n.jsxs("div",{className:"space-y-2 pb-2",children:[C&&n.jsx("p",{className:"typography-meta text-subtle-foreground",children:C}),S]})}):n.jsx(en,{open:!!s,onOpenChange:j=>{if(!j){if(o)return;h()}},children:n.jsxs(tn,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:y}),C&&n.jsx(Cn,{children:C})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:S}),n.jsx(gs,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),n.jsx(tp,{open:e,onOpenChange:t})]})},Jy=()=>{const e=Bn(t=>t.entries);return l.useEffect(()=>{for(const t of e.values())!bu(t)||!t.receipt||(Bn.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},np=[{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-access",title:"Remote access",group:"projects",kind:"single",description:"How other devices reach this computer.",keywords:["remote","access","mobile","phone","pair","qr","device","devices","tailscale","funnel","lan","network","wifi","password","passkey"],isAvailable:e=>!e.isMobile&&(e.isDesktop||e.isWeb)},{slug:"servers",title:"Servers",group:"projects",kind:"single",description:"Which PiChamber server this app uses.",keywords:["server","servers","instance","switch","connect","import link","host"],isAvailable:e=>!e.isMobile&&e.isDesktop||e.isMobile&&e.isCapacitor===!0},{slug:"remote-instances",title:"Remote instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"],isAvailable:()=>!1},{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","ssh","commit","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],sp={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function rp(e){const t=e.trim().toLowerCase();return np.find(s=>s.slug===t)??null}function op(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const s=sp[t];if(s)return s;const r=rp(t);return r?r.slug:"home"}function Xy(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-access":return"server";case"servers":return"server";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function Zy(){const e=l.useRef(!1),t=l.useRef(!1),s=Me(f=>f.setCurrentSession),r=ue(f=>f.setActiveMainTab),o=ue(f=>f.setSettingsDialogOpen),i=ue(f=>f.setSettingsPage),a=ue(f=>f.navigateToDiff),c=l.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const m=Me.getState().currentSessionId,g=ts().getState().selectedSessionId;if(f.sessionId!==m||f.sessionId!==g){const b=Me.getState().getDirectoryForSession(f.sessionId);s(f.sessionId,b)}}if(f.settingsPath){i(op(f.settingsPath)),o(!0);return}ue.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&a(f.diffFile)}finally{t.current=!1}}},[s,r,o,i,a]),d=l.useCallback(()=>{const f=Me.getState(),m=ts().getState(),g=ue.getState();return{sessionId:so({currentSessionId:f.currentSessionId,piSelectedSessionId:m.selectedSessionId,draft:f.newSessionDraft}),tab:g.activeMainTab,isSettingsOpen:g.isSettingsDialogOpen,settingsPath:g.settingsPage,diffFile:g.pendingDiffFile}},[]),u=l.useCallback((f={})=>{if(t.current)return;const m=d();Go(m,f)},[d]);l.useEffect(()=>{if(e.current||(e.current=!0,!Gi()))return;const f=qi();(async()=>(await c(f),Go({...d(),sessionId:f.sessionId??so({currentSessionId:Me.getState().currentSessionId,piSelectedSessionId:ts().getState().selectedSessionId,draft:Me.getState().newSessionDraft}),tab:f.tab??ue.getState().activeMainTab,settingsPath:f.settingsPath??ue.getState().settingsPage,diffFile:f.diffFile??ue.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),l.useEffect(()=>{const f=()=>{const w=Me.getState(),x=ts().getState();return so({currentSessionId:w.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:w.newSessionDraft})};let m=f(),g=Me.getState().newSessionDraft?.open===!0;const b=()=>{const w=Me.getState(),x=f(),C=w.newSessionDraft?.open===!0;x===m&&C===g||t.current||(m=x,g=C,u({replace:!0}))},p=Me.subscribe(()=>{b()}),h=ts().subscribe(()=>{b()});return()=>{p(),h()}},[u]),l.useEffect(()=>{let f=ue.getState().activeMainTab,m=ue.getState().isSettingsDialogOpen,g=ue.getState().settingsPage,b=ue.getState().pendingDiffFile;return ue.subscribe(h=>{if(t.current)return;const w=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==m,C=h.settingsPage!==g,S=h.pendingDiffFile!==b&&h.activeMainTab==="diff";f=h.activeMainTab,m=h.isSettingsDialogOpen,g=h.settingsPage,b=h.pendingDiffFile,(w||x||C||S)&&u()})},[u]),l.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const m=qi();if(Gi())c(m);else{const g=ue.getState();g.isSettingsDialogOpen&&o(!1),g.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function ip(e=!0){const t=yr(r=>r.checkForUpdates),s=l.useRef(t);l.useEffect(()=>{s.current=t},[t]),l.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,a=1440*60*1e3;let c=!1,d=null;const u=m=>{const g=Math.round(m*1e3);return Math.max(i,Math.min(a,g))},f=m=>{c||(d=window.setTimeout(async()=>{const g=await s.current(),b=typeof g=="number"&&Number.isFinite(g)?u(g):o;f(b)},m))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function ew(){const e=zs(t=>t.connection==="ready",void 0,"chrome");return ip(e),null}const ap=200,lp=15e3,cp=e=>{const{id:t,url:s}=e.payload,r=yu(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=wu(vu(s),r.target,{isMobile:ue.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:lp});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Su(r.target,s,ju()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},tw=()=>(l.useEffect(()=>{const e=new Set;return xu(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>ap){const s=e.values().next().value;s!==void 0&&e.delete(s)}cp(t)}})},[]),null),ia=12,dp=[{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"}],up=({isActive:e,burstKey:t=0,className:s,durationMs:r=900,bursts:o=dp,onComplete:i})=>{const a=Te.useRef(!1);Te.useEffect(()=>{!e&&a.current&&i?.(),e&&(a.current=!0)},[e,i]);const c=Te.useMemo(()=>Array.from({length:ia},(d,u)=>{const f=Math.PI*2*u/ia;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?n.jsx("div",{className:_("fireworks-overlay pointer-events-none",s),"aria-hidden":"true","data-burst-key":t,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return n.jsx("div",{className:"firework-burst",style:u,children:c.map((f,m)=>{const g=f.x*d.radius,b=f.y*d.radius,p={"--translate-x":`${g}px`,"--translate-y":`${b}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return n.jsx("span",{className:"firework-particle",style:p},`${d.id}-${m}-${t}`)})},`${d.id}-${t}`)})}):null},fp=({durationMs:e=3400}={})=>{const[t,s]=Te.useState({isActive:!1,cycle:0}),r=Te.useRef(null),o=Te.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Te.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),a=Te.useCallback(()=>{o(),s(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{s(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Te.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:a,dismissFireworks:i}},Vl=l.createContext(void 0),nw=({children:e})=>{const{isActive:t,burstKey:s,triggerFireworks:r,dismissFireworks:o}=fp(),i=l.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return n.jsxs(Vl.Provider,{value:i,children:[e,n.jsx(up,{isActive:t,burstKey:s})]})},hp={triggerFireworks:()=>{},dismissFireworks:()=>{}},sw=()=>l.useContext(Vl)??hp,Er=2e3,Yl=600*1e3;async function pp(){try{const e=await nt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const s=await e.json().catch(()=>({}));return{success:!1,error:s.error||`Server error: ${e.status}`,commands:Array.isArray(s.commands)?s.commands.filter(r=>typeof r=="string"):void 0}}const t=await e.json().catch(()=>({}));return{success:!0,autoRestart:t.autoRestart!==!1,jobId:typeof t.jobId=="string"?t.jobId:void 0,channel:t.channel==="rc"?"rc":t.channel==="stable"?"stable":void 0,targetVersion:typeof t.targetVersion=="string"?t.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function mp(e,t=Math.ceil(Yl/Er),s=Er,r=Ze()){for(let o=0;o<t;o++){if(Ze()!==r)return{applied:!1,stale:!0};try{const i=await nt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Ze()!==r)return{applied:!1,stale:!0};if(i.ok){const a=await i.json().catch(()=>null);if(Ze()!==r)return{applied:!1,stale:!0};if(typeof a?.error=="string"&&a.error.length>0)return{applied:!1,error:a.error};if(a&&a.available===!1)return{applied:!0};if(a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Ze()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,s))}return{applied:!1}}async function gp(e,t,s=Math.ceil(Yl/Er),r=Er,o=Ze()){for(let i=0;i<s;i++){if(Ze()!==o)return{applied:!1,stale:!0};try{const a=await nt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Ze()!==o)return{applied:!1,stale:!0};if(a.ok){const c=await a.json().catch(()=>null);if(Ze()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?t("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&t("updating")}else{if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(a.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(a.status===503){const c=await a.json().catch(()=>null);if(Ze()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};t("reconnecting")}else t("reconnecting")}}catch{if(Ze()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(a=>setTimeout(a,r))}return{applied:!1}}const aa="https://github.com/RyderAsKing/PiChamber/releases";function bp(e){const t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(t)}function xp(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function la(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function yp(e,t){const s=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=s(e),[i,a]=s(t),c=r.split(".").map(u=>Number.parseInt(u,10)),d=i.split(".").map(u=>Number.parseInt(u,10));for(let u=0;u<3;u+=1){const f=Number.isFinite(c[u])?c[u]:0,m=Number.isFinite(d[u])?d[u]:0;if(f!==m)return m-f}return!o||!a?(o?1:0)-(a?1:0):a.localeCompare(o,void 0,{numeric:!0})}function wp(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,s=[];let r;for(;(r=t.exec(e))!==null;)s.push({version:r[1]??"",date:r[2]??"",start:r.index});return s.length===0?[]:s.map((o,i)=>{const a=s[i+1]?.start??e.length,c=e.slice(o.start,a).trim();return{version:o.version,date:o.date,start:o.start,end:a,raw:c}})}const Ql=({open:e,onOpenChange:t,info:s,downloading:r,downloaded:o,progress:i,error:a,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,m]=Te.useState(null),[g,b]=Te.useState("idle"),[p,h]=Te.useState(null),[w,x]=Te.useState(null),[C,S]=Te.useState({}),A=s?.version?s.releaseUrl||`${aa}/tag/v${s.version}`:aa,y=s?.downloadUrl||A,j=i?.total?Math.round(i.downloaded/i.total*100):0,v=u==="web",k=u==="mobile",E=s?.updateCommand||"pichamber update",P=C.version||s?.version,z=C.channel||s?.channel;Te.useEffect(()=>{e||(b("idle"),h(null),x(null),S({}))},[e]);const K=async(I=E)=>{(await fn(I)).ok&&(m(I),setTimeout(()=>m(null),2e3))},q=Te.useCallback(async I=>{await gl(I)},[]),G=Te.useCallback(async()=>{const I=Ze();b("updating"),h(null),x(null),S({});const M=await pp();if(Ze()!==I)return;if(!M.success){b("error"),h(M.error||"Update failed"),x(M.commands??null);return}if(S({version:M.targetVersion,channel:M.channel}),M.jobId){const W=await gp(M.jobId,L=>{Ze()===I&&b(L)},void 0,void 0,I);if(W.stale||Ze()!==I)return;if(W.applied){window.location.reload();return}b("error"),h(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}b(M.autoRestart?"restarting":"reconnecting");const H=await mp(s?.currentVersion,void 0,void 0,I);if(!(H.stale||Ze()!==I)){if(H.applied){window.location.reload();return}b("error"),h(H.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[s?.currentVersion]),F=Te.useCallback(()=>{q(y)},[q,y]),D=g!=="idle"&&g!=="error",T=Te.useMemo(()=>{if(!s?.body)return null;const I=s.body.trim();if(!I)return null;const M=wp(I);return M.length===0?{kind:"raw",title:"What's new",content:la(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((W,L)=>yp(W.version,L.version)).map(W=>({version:W.version,dateLabel:bp(W.date),content:la(xp(W.raw)||I)}))}},[s?.body]);return n.jsx(en,{open:e,onOpenChange:D?void 0:t,children:n.jsxs(tn,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[n.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[n.jsxs(mn,{className:"flex items-center gap-2.5",children:[n.jsx(R,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),n.jsx("span",{className:"text-lg font-semibold text-foreground",children:g==="restarting"||g==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(s?.currentVersion||P||v&&z)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(s?.currentVersion||P)&&n.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[s?.currentVersion&&n.jsx("span",{className:"text-muted-foreground",children:s.currentVersion}),s?.currentVersion&&P&&n.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"→"}),P&&n.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:P})]}),v&&z&&n.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:z==="rc"?"RC channel":"Stable channel"})]})]}),n.jsxs("div",{className:"space-y-2",children:[v&&D&&n.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),n.jsxs("div",{className:"typography-ui-label text-foreground",children:[g==="updating"&&"Installing update...",g==="restarting"&&"Server restarting...",g==="reconnecting"&&"Waiting for server..."]})]}),n.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!D&&n.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:n.jsx(Mn,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:T.kind==="raw"?n.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:I=>{const H=I.target.closest("a");H&&H.href&&(I.preventDefault(),I.stopPropagation(),q(H.href))},children:n.jsx(Vi,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):n.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(I=>n.jsxs("div",{className:"p-4",children:[n.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[n.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",I.version]}),n.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),n.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:M=>{const W=M.target.closest("a");W&&W.href&&(M.preventDefault(),M.stopPropagation(),q(W.href))},children:n.jsx(Vi,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(a||p)&&n.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:n.jsx("p",{className:"text-sm text-[var(--status-error)]",children:a||p})}),v&&g==="error"&&(w??[E]).length>0&&n.jsxs("div",{className:"space-y-2 mt-4",children:[n.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[n.jsx(R,{name:"terminal",className:"h-4 w-4"}),n.jsx("span",{children:w?"Run these commands:":"Or update via terminal:"})]}),(w??[E]).map(I=>n.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:[n.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),n.jsx(Ae,{variant:"ghost",size:"icon",onClick:()=>{K(I)},className:f===I?"text-[var(--status-success)]":void 0,title:f===I?"Copied!":"Copy command","aria-label":f===I?"Copied!":"Copy command",children:f===I?n.jsx(R,{name:"check",className:"h-4 w-4"}):n.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!v&&!k&&r&&n.jsxs("div",{className:"space-y-2 mt-4",children:[n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),n.jsxs("span",{className:"font-mono text-foreground",children:[j,"%"]})]}),n.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:n.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${j}%`}})})]})]}),n.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[n.jsxs("a",{href:A,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[n.jsx(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),n.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!k&&!o&&!r&&n.jsxs(Ae,{onClick:c,children:[n.jsx(R,{name:"download",className:"h-4 w-4"}),"Download update"]}),!v&&!k&&r&&n.jsxs(Ae,{disabled:!0,children:[n.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!k&&o&&n.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[n.jsx(R,{name:"restart",className:"h-4 w-4"}),"Restart to update"]}),k&&n.jsxs(Ae,{onClick:F,size:"default",children:[n.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!D&&n.jsxs(Ae,{onClick:G,children:[n.jsx(R,{name:"download",className:"h-4 w-4"}),"Update now"]}),v&&D&&n.jsxs(Ae,{disabled:!0,children:[n.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Jl=l.memo(function({checked:t,onChange:s,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:a,iconClassName:c}){const d=l.useCallback(g=>{g.preventDefault(),g.stopPropagation(),!r&&!t&&s()},[t,r,s]),u=l.useCallback(g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),!r&&!t&&s())},[t,r,s]),f=n.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),m=_("relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full","transition-[background-color,box-shadow] duration-200 ease-out",t?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none":"bg-background shadow-[inset_0_0_0_1px_var(--interactive-border-hover)]");return i?n.jsx("span",{"aria-hidden":!0,className:_(m,r&&"opacity-50",a),children:f}):n.jsx("button",{type:"button",role:"radio",onClick:d,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",m,t?"hover:bg-[var(--primary-base)]":"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:f})}),nr=({children:e,className:t,contentClassName:s})=>{const[r,o]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>{if(!r)return;const a=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[r]),n.jsxs(Ke,{open:r,onOpenChange:o,children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:a=>{a.preventDefault(),a.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-subtle-foreground hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:n.jsx(R,{name:"information",className:"h-3.5 w-3.5"})})}),n.jsx(He,{sideOffset:8,className:_("max-w-sm",s),children:e})]})},rw="w-full min-w-40 max-w-48",ow="settings",vp="w-full min-w-40 max-w-48",iw="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Sp="w-full max-w-[24rem]",aw="min-w-0 flex-1",lw="flex w-full min-w-0 items-center gap-2",cw="typography-meta shrink-0 text-muted-foreground tabular-nums",Xl="space-y-3.5",jp="space-y-1.5",dw="typography-settings-page-title text-foreground",kp="typography-settings-section-title text-foreground",Zl="typography-settings-group-title text-foreground",Si="typography-settings-field-label text-foreground",Cp="typography-settings-description text-muted-foreground",sr="typography-meta text-muted-foreground",uw="typography-meta font-medium text-foreground",Ap=({title:e,description:t,titleAccessory:s,info:r,headerAction:o,children:i,divider:a=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return n.jsxs("section",{"data-settings-item":u,className:_("space-y-4",a?"border-t border-border/60 py-6":"pb-6",c),children:[f?n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?n.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?n.jsx("h2",{className:kp,children:e}):e,s,r!=null?n.jsx(nr,{children:r}):null]}):null,t!=null?n.jsx("div",{className:Cp,children:t}):null]}),o?n.jsx("div",{className:"shrink-0",children:o}):null]}):null,n.jsx("div",{className:_(d),children:i})]})},fw=({children:e,className:t})=>n.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),Np=({children:e,className:t,as:s="h3"})=>n.jsx(s,{className:_(Zl,t),children:e}),hw=({title:e,description:t,info:s,children:r,className:o,contentClassName:i,settingsItem:a})=>n.jsxs("div",{"data-settings-item":a,className:_("space-y-2",o),children:[e!=null||t!=null||s!=null?n.jsxs("div",{className:"space-y-0.5",children:[e!=null?n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(Np,{children:e}),s!=null?n.jsx(nr,{children:s}):null]}):null,t!=null?n.jsx("p",{className:sr,children:t}):null]}):null,n.jsx("div",{className:_(i),children:r})]}),Ks=({label:e,description:t,info:s,descriptionPlacement:r="before",children:o,settingsItem:i,className:a,controlClassName:c})=>{const d=t!=null?n.jsx("p",{className:sr,children:t}):null;return n.jsxs("div",{"data-settings-item":i,className:_("space-y-2",a),children:[n.jsxs("div",{className:"space-y-0.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:Si,children:e}),s!=null?n.jsx(nr,{children:s}):null]}),r==="before"?d:null]}),n.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},pw=({label:e,description:t,info:s,children:r,settingsItem:o,className:i,labelClassName:a,controlClassName:c,alignEnd:d=!0})=>n.jsxs("div",{"data-settings-item":o,className:_("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",i),children:[n.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",a),children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:Si,children:e}),s!=null?n.jsx(nr,{children:s}):null]}),t!=null?n.jsx("p",{className:_(sr,"mt-0.5"),children:t}):null]}),n.jsx("div",{className:_("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",d&&"@xl:justify-end",c),children:r})]}),mw=({children:e,className:t,settingsItem:s})=>n.jsx("div",{"data-settings-item":s,className:_("pt-4",t),children:e}),gw=({label:e,children:t,divider:s=!0,className:r,contentClassName:o,defaultOpen:i=!1})=>{const[a]=l.useState(i);return n.jsxs("details",{open:a||void 0,className:_("group/disclosure",s?"border-t border-border/60 py-6":"pb-6",r),children:[n.jsxs("summary",{className:"flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md typography-ui-label text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] [&::-webkit-details-marker]:hidden",children:[n.jsx(R,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),n.jsx("div",{className:_("pt-4",o),children:t})]})},Ip=({checked:e,onChange:t,label:s,description:r,disabled:o=!1,ariaLabel:i,settingsItem:a,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},m=r!=null;return n.jsxs("div",{"data-settings-item":a,className:_("group flex cursor-pointer gap-2 py-0.5",m?"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:g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),f())},children:[n.jsx(Gs,{checked:e,onChange:t,disabled:o,ariaLabel:i}),n.jsxs("div",{className:"flex min-w-0 flex-col",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:Si,children:s}),d,u!=null?n.jsx(nr,{children:u}):null]}),m?n.jsx("span",{className:sr,children:r}):null]})]})},bw=({selected:e,onSelect:t,label:s,description:r,ariaLabel:o,disabled:i=!1,className:a})=>n.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",a),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[n.jsx(Jl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),n.jsxs("div",{className:"flex min-w-0 flex-col",children:[n.jsx("span",{className:_("typography-settings-field-label font-normal","text-foreground"),children:s}),r!=null?n.jsx("span",{className:sr,children:r}):null]})]}),xw=({selected:e,onSelect:t,label:s,preview:r,description:o,ariaLabel:i,disabled:a=!1,className:c})=>{const d=l.useId();return n.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",a&&"cursor-not-allowed opacity-60",c),role:"radio",tabIndex:a?-1:0,"aria-checked":e,"aria-label":i,"aria-describedby":o?d:void 0,"aria-disabled":a||void 0,onClick:()=>{a||t()},onKeyDown:u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),a||t())},children:[n.jsx("div",{"aria-hidden":!0,className:_("aspect-[4/3] overflow-hidden rounded-lg border transition-colors",e?"border-[var(--primary-base)] ring-1 ring-[var(--primary-base)]":"border-[var(--interactive-border)] group-hover/preview:border-foreground/30"),children:r}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx(Jl,{checked:e,onChange:t,disabled:a,decorative:!0}),n.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal","text-foreground"),children:s})]}),o?n.jsx("p",{id:d,className:"-mt-1 pl-[20px] typography-meta text-muted-foreground text-pretty",children:o}):null]})},yw=({"aria-label":e,children:t,className:s})=>n.jsx("div",{role:"radiogroup","aria-label":e,className:_(jp,s),children:t});function ww({value:e,options:t,onChange:s,className:r,"aria-label":o}){return n.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>n.jsx(Ae,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>s(i.value),children:i.label},i.value))})}const Qo="pichamber:server-update-channel-changed",vw=()=>{typeof window<"u"&&window.dispatchEvent(new Event(Qo))},Ep=e=>typeof window>"u"?()=>{}:(window.addEventListener(Qo,e),()=>window.removeEventListener(Qo,e));class Dp extends l.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?n.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:n.jsxs(ku,{className:"w-full max-w-md",children:[n.jsx(Cu,{className:"text-center",children:n.jsxs(Au,{className:"flex items-center justify-center gap-2 text-destructive",children:[n.jsx(R,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),n.jsxs(Nu,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&n.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&n.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[n.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),n.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),n.jsx("div",{className:"flex gap-2",children:n.jsxs(Ae,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[n.jsx(R,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),n.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Rp(e){return n.jsx(Dp,{...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 Sw=({active:e=!0})=>{const t=Me(s=>s.currentSessionId);return n.jsx(Rp,{sessionId:t||void 0,children:n.jsx(Iu,{active:e},t??"no-session")})};function Pp({onResizeStart:e,ariaLabel:t}){return n.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":t,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:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:n.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ec=Te.forwardRef(({className:e,outerClassName:t,scrollbarClassName:s,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:a,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:m,...g},b)=>{const p=Te.useRef(null),h=Te.useRef(null),[w,x]=Te.useState(null),C=c??w,S=Te.useCallback(y=>{const j=p.current;if(!j)return;h.current={startY:y.clientY,startHeight:j.getBoundingClientRect().height};const v=y.currentTarget;v.setPointerCapture(y.pointerId);const k=P=>{const z=h.current;if(!z)return;const K=z.startHeight+(P.clientY-z.startY),q=Math.max(82,K);d?d(q):x(q)},E=()=>{h.current=null,v.removeEventListener("pointermove",k),v.removeEventListener("pointerup",E),v.removeEventListener("pointercancel",E)};v.addEventListener("pointermove",k),v.addEventListener("pointerup",E),v.addEventListener("pointercancel",E),y.preventDefault()},[d]),A=Te.useCallback(y=>{if(y.target.closest('textarea, button, [role="separator"]'))return;const v=p.current?.querySelector("textarea");v&&document.activeElement!==v&&(y.preventDefault(),v.focus())},[]);return f?n.jsx(Mn,{as:"textarea",ref:b,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:s,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...g}):n.jsx("div",{ref:p,onPointerDown:A,style:C!==null?{height:`${C}px`}:void 0,className:_("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!a&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],a&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[n.jsx("textarea",{ref:b,className:_("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-subtle-foreground placeholder:text-subtle-foreground",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...g}),n.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,n.jsx(Pp,{onResizeStart:S,ariaLabel:"Resize textarea"})]})]})})});ec.displayName="Textarea";const tc=[{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"}],Ws=Object.fromEntries(tc.map(e=>[e.key,e.Icon])),Jo="pichamber:project-actions-updated",nc=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},cn=(e,t)=>`${nc(e)}::${t}`,sc=({title:e,description:t,info:s,settingsItem:r,titleAccessory:o,headerAction:i,children:a,className:c,contentClassName:d,divider:u=!0})=>n.jsx(Ap,{title:e,description:t,info:s,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:a}),Xo=e=>e.name.trim().length>0&&e.command.trim().length>0,Tp=e=>e.name.trim().length===0&&e.command.trim().length===0,Mp=e=>!Xo(e)&&!Tp(e),Fp=(e,t)=>e.some(r=>t.has(r.id)&&!Xo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Xo)},Lp=450,Op=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Bp=()=>({id:Op(),name:"",command:"",icon:"play"}),_p=({projectRef:e})=>{const[t,s]=l.useState([]),[r,o]=l.useState(!1),[i,a]=l.useState(null),[c,d]=l.useState(new Set),u=l.useRef(!1);l.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const C=await To(e);if(x)return;s(C.actions),a(JSON.stringify({actions:C.actions})),d(new Set(C.actions.map(S=>S.id)))}catch{if(x)return;s([]),a(JSON.stringify({actions:[]})),d(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=l.useMemo(()=>Fp(t,c),[t,c]),m=l.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),g=i!==null&&f.canPersist&&m!==i,b=l.useCallback(async x=>await Eu(e,{actions:x,primaryActionId:null})?(a(JSON.stringify({actions:x})),d(new Set(x.map(S=>S.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Jo,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);l.useEffect(()=>{if(!g||r||u.current)return;const x=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await b(f.actions)}finally{u.current=!1}})())},Lp);return()=>{window.clearTimeout(x)}},[g,r,b,f.actions]);const p=l.useCallback(()=>{const x=Bp();s(C=>[...C,x])},[]),h=l.useCallback(x=>{s(C=>C.filter(S=>S.id!==x))},[]),w=l.useCallback((x,C)=>{s(S=>S.map(A=>A.id===x?C(A):A))},[]);return n.jsx(sc,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:n.jsxs(Ae,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:p,children:[n.jsx(R,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):n.jsx("div",{className:_("space-y-6",Sp),children:t.map((x,C)=>{const S=x.icon||"play",A=Ws[S]||"play",y=x.name.trim()||`Action ${C+1}`,j=Mp(x);return n.jsxs("div",{className:Xl,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("h3",{className:Zl,children:y}),n.jsx(Ae,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${y}`,children:n.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),n.jsxs(Ks,{label:"Name",controlClassName:"w-full max-w-none",children:[n.jsxs(Gt,{children:[n.jsx(qt,{asChild:!0,children:n.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:n.jsx(R,{name:A,className:"h-4 w-4"})})}),n.jsx(Vt,{align:"start",className:"w-56 p-2",children:n.jsx("div",{className:"grid grid-cols-6 gap-1",children:tc.map(v=>{const k=v.Icon,E=(x.icon||"play")===v.key;return n.jsx("button",{type:"button",onClick:()=>w(x.id,P=>({...P,icon:v.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",E&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${v.label}`,children:n.jsx(R,{name:k,className:"h-4 w-4"})},v.key)})})})]}),n.jsx(Mo,{value:x.name,onChange:v=>w(x.id,k=>({...k,name:v.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),n.jsx(Ks,{label:"Command",controlClassName:"w-full max-w-none",children:n.jsx(ec,{value:x.command,onChange:v=>w(x.id,k=>({...k,command:v.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),j?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,n.jsx(Ip,{checked:x.autoOpenUrl===!0,onChange:v=>w(x.id,k=>({...k,...v?{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 ${y}`}),x.autoOpenUrl===!0?n.jsx(n.Fragment,{children:n.jsx(Ks,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:n.jsx(Mo,{value:x.openUrl||"",onChange:v=>w(x.id,k=>({...k,openUrl:v.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},zp={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)"},Up=({value:e,noneLabel:t,ariaLabel:s,disabled:r=!1,className:o,isModelAllowed:i,onChange:a})=>{const c=Kt(k=>k.providers),d=Kt(k=>k.modelsMetadata),u=ue(k=>k.hiddenModels),f=ue(k=>k.isFavoriteModel),m=ue(k=>k.toggleFavoriteModel),g=ue(k=>k.reorderFavoriteModel),{favoriteModelsList:b,recentModelsList:p}=Du(),[h,w]=l.useState(!1),[x,C]=l.useState("");l.useEffect(()=>{h?Kt.getState().ensureModelMetadata():C("")},[h]);const S=e?c.find(k=>k.id===e.providerId):void 0,A=e&&S?(Array.isArray(S.models)?S.models:[]).find(k=>k.id===e.modelId):void 0,y=e?Ru(A,e.modelId):t,j=l.useMemo(()=>e?u.filter(k=>!(k.providerID===e.providerId&&k.modelID===e.modelId)):u,[u,e]),v=l.useCallback(k=>{a({providerId:k.providerID,modelId:k.modelID}),w(!1)},[a]);return n.jsxs(Gt,{modal:!1,open:h,onOpenChange:k=>{r||w(k)},children:[n.jsx(qt,{asChild:!0,disabled:r,children:n.jsxs("button",{type:"button","aria-label":s,disabled:r,className:_(Tu({size:"default"}),vp,"min-w-0",o),children:[n.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?n.jsx(Pu,{providerId:e.providerId,className:"size-4 shrink-0"}):null,n.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:y})]}),n.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),n.jsx(Vt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:n.jsx(Mu,{providers:c,favoriteModels:b,recentModels:p,modelsMetadata:d,searchQuery:x,onSearchQueryChange:C,onSelect:v,labels:{...zp,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:j,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{a(null),w(!1)},disabled:r,autoFocus:!0,onEscape:()=>w(!1),isFavorite:k=>f(k.providerID,k.modelID),onToggleFavorite:k=>m(k.providerID,k.modelID),onReorderFavorite:(k,E)=>g(k.providerID,k.modelID,E.providerID,E.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},lo="w-full max-w-none",$p=({form:e})=>{const{name:t,setName:s,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,a=Kt(c=>c.loadProviders);return l.useEffect(()=>{a({source:"projectSettings"})},[a]),i?n.jsx(sc,{title:"Project",divider:!1,children:n.jsxs("div",{className:Xl,children:[n.jsx(Ks,{label:"Name",settingsItem:"projects.name",controlClassName:lo,children:n.jsx(Mo,{value:t,onChange:c=>s(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),n.jsx(Ks,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:lo,children:n.jsx(Up,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:lo,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Kp=e=>{const[t,s]=l.useState(""),[r,o]=l.useState(void 0);l.useEffect(()=>{if(!e){s(""),o(void 0);return}s(e.label??""),o(e.defaultModel)},[e]);const i=l.useMemo(()=>Fu(r),[r]),a=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=l.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=l.useCallback(async()=>{if(!e)return null;const u=t.trim();return u?{label:u,defaultModel:r??null}:null},[r,t,e]);return{name:t,setName:s,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:a,prepareSaveData:d,project:e}},Wp=450,Hp=(e,t)=>{const{hasChanges:s,name:r,defaultModel:o,prepareSaveData:i}=e,a=l.useRef(!1);l.useEffect(()=>{if(!s||!r.trim()||a.current)return;const c=window.setTimeout(()=>{a.current||(a.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{oe.error("Failed to save project settings")}}finally{a.current=!1}})())},Wp);return()=>{window.clearTimeout(c)}},[o,s,r,t,i])},Gp=({project:e,onIdentitySave:t})=>{const s=Kp(e),r=l.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=l.useCallback(async i=>{await t(i)},[t]);return Hp(s,o),!e||!r?null:n.jsxs("div",{className:"space-y-0",children:[n.jsx($p,{form:s}),n.jsx(_p,{projectRef:r})]})},qp=6e4,Vp=3e4,Rs=new Map;let ca=0,da=!1;const Yp=()=>{if(da||typeof window>"u")return;da=!0;const e=()=>{const t=Date.now();t-ca<Vp||typeof document<"u"&&document.hidden||(ca=t,ht(async()=>{const{getRegisteredRuntimeAPIs:s}=await import("./index-fmzQmSSv.js").then(r=>r.cJ);return{getRegisteredRuntimeAPIs:s}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:s})=>{const r=s()?.github;r&&Ur.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},Ur=$n()(zr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Tt(),resetForRuntimeSwitch:s=>{const r=s??Tt();Rs.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(s,r)=>{Yp();const o=Tt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),a=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&a-i.fetchedAt<qp)return i.status;const c=Rs.get(o);if(c)return c;const d=s??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return Tt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Tt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();Rs.set(o,u);try{return await u}finally{Rs.get(o)===u&&Rs.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&bs(e=>{Ur.getState().resetForRuntimeSwitch(e.runtimeKey)});const Qp=()=>Ur(e=>(e.status?.hosts??[]).find(s=>s.authenticated)?.login??null),jw=e=>{if(e.byteLength<4)return null;const t=new DataView(e).getUint32(0);if(t<=0||4+t>e.byteLength)return null;try{const s=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(s?.width)||!Number.isFinite(s?.height)?null:{header:s,jpeg:new Uint8Array(e,4+t)}}catch{return null}},kw=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},Cw=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",Aw=50*1024*1024-1,Nw=[250,1e3,2e3,4e3,8e3],Jp=(e,t)=>{const s=r=>{let o=r>>>0;for(const i of`${e}\0${t}`)o^=i.codePointAt(0)??0,o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0")};return`tab-${s(2166136261)}${s(16777619)}`},Iw=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),Ew=(e,t,s,r)=>{if(s.width<=0||s.height<=0)return null;const o=(e-s.left)/s.width*r.width,i=(t-s.top)/s.height*r.height;return{x:Math.round(Math.max(0,Math.min(r.width-1,o))*100)/100,y:Math.round(Math.max(0,Math.min(r.height-1,i))*100)/100}},Dw=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,Rw=(e,t)=>{const s=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(s)&&s>0?s:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},ys=async(e,t)=>{const s=await e.json().catch(()=>null);return new Error(typeof s?.error=="string"?s.error:t)},Pw=async()=>{const e=await nt("/api/server-browser/status");if(!e.ok)throw await ys(e,"Could not check the server browser");return await e.json()},Tw=async e=>{const t=await nt("/api/server-browser/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await ys(t,"Could not save the server browser settings");return await t.json()},Mw=async(e,t)=>{const s=await nt("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!s.ok)throw await ys(s,"Could not find dev servers");const r=await s.json();return Array.isArray(r.servers)?r.servers:[]},Fw=async(e,t,s)=>{const r=await nt("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:s});if(!r.ok)return{framing:"unknown"};const o=await r.json().catch(()=>null);return o?.framing==="refused"||o?.framing==="allowed"?{framing:o.framing,reason:o.reason==="frame-ancestors"?"frame-ancestors":"x-frame-options"}:{framing:"unknown"}},Lw=async()=>{const e=await nt("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await ys(e,"Could not clear browsing data")},Ow=(e,t)=>{const s=Jp(e,t);nt(`/api/server-browser/tabs/${encodeURIComponent(s)}`,{method:"DELETE"}).catch(()=>{})},Bw=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),s=await nt(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!s.ok)throw await ys(s,`Could not upload ${e.name}`);const r=await s.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},_w=async(e,t)=>{const s=await nt(`/api/server-browser/downloads/${encodeURIComponent(e)}`);if(!s.ok)throw await ys(s,`Could not download ${t}`);const r=await s.blob(),o=URL.createObjectURL(r);try{const i=document.createElement("a");i.href=o,i.download=t,i.rel="noopener",document.body.appendChild(i),i.click(),i.remove()}finally{setTimeout(()=>URL.revokeObjectURL(o),6e4)}},zw=async(e,t,s)=>{const r=await $f();return{socket:Kf(Wf().websocket("/api/server-browser/ws",{tab:e,url:t,popup:s},r)),urlAuthToken:r}},Uw=e=>{Uf(e)},ur=100;function $w(){const e=ue(k=>k.isArchivePageOpen),t=ue(k=>k.setArchivePageOpen),s=ue(k=>k.setActiveMainTab),r=Me(k=>k.setCurrentSession),o=Me(k=>k.unarchiveSession),i=hs(k=>k.homeDirectory),a=Fo({archived:!0}),[c,d]=l.useState(""),[u,f]=l.useState(null),[m,g]=l.useState(ur),b=c.trim().toLowerCase(),p=l.useMemo(()=>e?[...a].sort((k,E)=>(E.time?.archived??0)-(k.time?.archived??0)):[],[a,e]),h=l.useMemo(()=>{const k=new Map;for(const E of p){const P=Re(is(E))??"",z=k.get(P);if(z){z.sessions.push(E);continue}k.set(P,{directory:P,label:P?Xi(P,i)||P:"other projects",sessions:[E]})}return[...k.values()].sort((E,P)=>P.sessions.length-E.sessions.length)},[i,p]),w=l.useMemo(()=>b?p.filter(k=>(k.title??"").toLowerCase().includes(b)):u===null?p:h.find(k=>k.directory===u)?.sessions??[],[h,b,u,p]),x=w.slice(0,m),C=w.length-x.length,S=a.length,A=l.useCallback(k=>{f(k),g(ur)},[]),y=l.useCallback(k=>{const E=Re(is(k));r(k.id,E??void 0),s("chat"),t(!1)},[s,r,t]),j=l.useCallback(k=>{o(k.id).then(E=>{E?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const v=(k,E,P,z,K,q,G)=>n.jsxs("div",{className:"group/dir relative",children:[n.jsxs("button",{type:"button",onClick:K,title:q,className:_("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",G?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",z?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[n.jsx("span",{className:"min-w-0 flex-1 truncate",children:E}),n.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:P})]}),G?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>qs.requestDelete({sessions:G,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 ${E}`,children:n.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},k);return n.jsx(su,{open:e,onOpenChange:t,children:n.jsxs(ru,{children:[n.jsx(ou,{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"}),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:n.jsxs(iu,{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:[n.jsx(au,{className:"sr-only",children:"Archived sessions"}),n.jsx(lu,{className:"sr-only",children:"Browse and restore archived sessions."}),n.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:n.jsx(R,{name:"close",className:"size-4"})}),n.jsxs("div",{className:"flex min-h-0 flex-1",children:[n.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:n.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[v("__all__","All directories",S,u===null,()=>A(null)),h.map(k=>v(k.directory||"__none__",k.label,k.sessions.length,u===k.directory,()=>A(k.directory),k.directory||void 0,k.sessions))]})}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[n.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[n.jsxs("div",{className:"relative min-w-0 flex-1",children:[n.jsx(R,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),n.jsx("input",{value:c,onChange:k=>{d(k.target.value),g(ur)},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"})]}),n.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:w.length===1?`${w.length} archived session`:`${w.length} archived sessions`})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:n.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[x.length===0?n.jsx("div",{className:"py-10 text-center text-muted-foreground",children:n.jsx("p",{className:"typography-ui-label font-semibold",children:b?"No matching archived sessions":"No archived sessions"})}):x.map(k=>{const E=Re(is(k))??"",P=E?Xi(E,i)||E:null;return n.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:()=>y(k),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),y(k))},children:[n.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:un(k)}),b&&P?n.jsx("span",{className:"max-w-40 flex-shrink-0 truncate typography-micro text-subtle-foreground",title:E,children:P}):null,n.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:uh(k.time?.archived??k.time?.updated??k.time?.created??Date.now())}),n.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),j(k)},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 ${un(k)}`,children:n.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),n.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),qs.requestDelete({sessions:[k],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity 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 ${un(k)}`,children:n.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},k.id)}),C>0?n.jsx("button",{type:"button",onClick:()=>g(k=>k+ur),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-subtle-foreground leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const Xp=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,s=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+s+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,s);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},Zp=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,s=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+s+r},Xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,em=e=>{if(!e||typeof e!="object")return null;const t=Xt(e.input),s=Xt(e.output),r=Xt(e.cacheRead),o=Xt(e.cacheWrite);return{input:t,output:s,reasoning:null,cacheRead:r,cacheWrite:o,total:t+s+r+o}},ua=e=>{const t=em(e.info.usage);if(t)return t;const s=e.info.tokens,r=s!==void 0?s:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Xt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=Xt(o.input),a=Xt(o.output),c=Xt(o.reasoning),d=Xt(o.cache?.read),u=Xt(o.cache?.write);return{input:i,output:a,reasoning:c,cacheRead:d,cacheWrite:u,total:i+a+c+d+u}},rc=380,co=8,tm=140;function nm({open:e,onClose:t,anchorRef:s,closeOnWheel:r=!1}){const o=l.useRef(null),i=l.useRef(null),[a,c]=l.useState(e),[d,u]=l.useState(!1),[f,m]=l.useState(null),{enabled:g}=xi();return l.useLayoutEffect(()=>{if(!e||!g||!a)return;const b=()=>{const w=s.current?.getBoundingClientRect(),x=i.current?.getBoundingClientRect();if(!w||!x){m(null);return}const C=w.left-x.left;m(Math.min(Math.max(C,co),Math.max(co,x.width-rc-co)))};b();const p=i.current;if(typeof ResizeObserver>"u"||!p)return;const h=new ResizeObserver(b);return h.observe(p),()=>h.disconnect()},[s,g,e,a]),l.useEffect(()=>{if(e){c(!0),u(!1);return}if(!a)return;u(!0);const b=window.setTimeout(()=>{c(!1),u(!1)},tm);return()=>window.clearTimeout(b)},[e,a]),l.useEffect(()=>{if(!e)return;const b=p=>{p.key==="Escape"&&t()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t,e]),l.useEffect(()=>{if(!e)return;const b=p=>{const h=p.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||s.current?.contains(h)||t()};return document.addEventListener("pointerdown",b,!0),r&&document.addEventListener("wheel",b,!0),()=>{document.removeEventListener("pointerdown",b,!0),r&&document.removeEventListener("wheel",b,!0)}},[s,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:d,anchorLeft:f,isPopover:g&&f!==null}}const fa=(e,t)=>{if(!e||typeof e!="object")return;const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0},Dr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),fr=({icon:e,iconNode:t,label:s,children:r})=>n.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[n.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?n.jsx(R,{name:e,className:"size-[18px]"}):null)}),n.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:s}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),sm=({open:e,onClose:t,anchorRef:s,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:c,anchorLeft:d,isPopover:u}=nm({open:e,onClose:t,anchorRef:s,closeOnWheel:!0});return a?n.jsxs("div",{ref:i,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:[n.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:_("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...u?{top:8,left:d??8,width:`min(${rc}px, calc(100% - 16px))`}:null},children:n.jsx("div",{className:"space-y-1",children:r?n.jsxs(n.Fragment,{children:[n.jsx(fr,{iconNode:n.jsx(bl,{percentage:r.percentage}),label:"Context",children:n.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[n.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),n.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?n.jsxs(n.Fragment,{children:[n.jsx(fr,{icon:"stack",label:"Cache read",children:n.jsx("span",{className:"tabular-nums",children:Dr(r.cacheRead)})}),n.jsx(fr,{icon:"edit",label:"Cache write",children:n.jsx("span",{className:"tabular-nums",children:Dr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?n.jsx(fr,{icon:"check",label:"Cache hit",children:n.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):n.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),n.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},rm=l.memo(function({open:t,onOpenChange:s,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const a=l.useRef(null),c=Lu(r??""),d=Kt(D=>D.providers),u=Kt(D=>D.currentProviderId),f=Kt(D=>D.currentModelId),m=Kt(D=>D.getCurrentModel()),g=Kt(D=>D.getModelMetadata);Kt(D=>D.modelsMetadata.size);const b=Ou(l.useCallback(D=>r?D.sessionModelSelections.get(r)??null:null,[r])),p=l.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const T=c[D]?.info;if(T.role!=="user")continue;const I=T.model,M=I?.providerID??I?.providerId,H=I?.modelID??I?.modelId,W=typeof M=="string"&&M.trim().length>0?M:void 0,L=typeof H=="string"&&H.trim().length>0?H:void 0;if(W&&L)return{providerID:W,modelID:L}}return null},[c]),h=l.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const T=c[D];if(T?.info.role==="assistant"&&ua(T).total>0)return T}return null},[c]),w=p??(()=>{const D=h?.info.model,T=D?.providerID??D?.providerId,I=D?.modelID??D?.modelId;return T&&I?{providerID:T,modelID:I}:null})()??(b?{providerID:b.providerId,modelID:b.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),C=(w?d.find(D=>D.id===w.providerID):void 0)?.models.find(D=>D.id===w?.modelID),S=w?g(w.providerID,w.modelID):void 0,A=fa(C?.limit,"context")??S?.limit?.context??fa(m?.limit,"context")??0,y=h?ua(h):null,j=h?.info?.usage,v=j?Zp(j):y?.total??0,k=!i&&v>0&&A>0?Math.min(v/A*100,999):null,E=k!==null?`${Dr(v)}/${Dr(A)}`:null,P=k===null?"":k>=90?"text-[var(--status-error)]":k>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",z=y?.cacheRead??null,K=y?.cacheWrite??null,q=y?Xp({input:y.input,cache:{read:y.cacheRead,write:y.cacheWrite}}):{percent:0,hasInput:!1},G=q.hasInput?q.percent:null,F=k!==null&&E?{percentage:k,tokens:E,colorClass:P,cacheRead:z,cacheWrite:K,cacheHitPercent:G}:null;return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:a,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":t,onClick:()=>s(D=>!D),style:{touchAction:"manipulation"},children:F?n.jsx(bl,{percentage:F.percentage,size:20,className:"size-5 -rotate-90"}):n.jsx(R,{name:"pie-chart",className:"size-5"})}),n.jsx(sm,{open:t,onClose:()=>s(!1),anchorRef:a,contextDisplay:F})]})}),ws="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",om="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",im=l.memo(function({visible:t=!0,title:s,ariaLabel:r,onClick:o,className:i,Icon:a,iconClassName:c,pressed:d=!1}){return t?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:_(i??ws,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(R,{name:a,className:c??"h-[18px] w-[18px]"})})}),n.jsx(He,{children:n.jsx("p",{children:s})})]}):null}),am=e=>{let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return(t>>>0).toString(36).padStart(7,"0").slice(-6)},oc=({variant:e="desktop"})=>{const t=Bn(f=>f.entries),[s,r]=l.useState(!1),o=l.useRef(null),i=l.useMemo(()=>[...t.values()].sort((f,m)=>m.startedAt-f.startedAt),[t]),a=i.filter(f=>f.state&&f.state.phase!=="failed"||xl(f)).length,c=l.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=l.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(l.useEffect(()=>()=>c(),[c]),i.length===0)return null;const u=f=>{if(!Uu(f))return;const m=f.receipt;if(!m)return;const g=Me.getState();g.newSessionDraft.open?g.setNewSessionDraftTarget({directoryOverride:m.path,worktreeIntent:null}):g.openNewSessionDraft({directoryOverride:m.path}),Bn.getState().clearEntry(f.key),ue.getState().setActiveMainTab("chat"),r(!1)};return n.jsxs(Gt,{open:s,onOpenChange:r,children:[n.jsx(qt,{asChild:!0,children:n.jsxs("button",{type:"button",className:_(e==="desktop"?ws:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&d()},children:[a>0?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner"}):n.jsx(R,{name:"task",className:"size-[18px]"}),n.jsx("span",{children:"Background tasks"})]})}),n.jsxs(Vt,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:d,children:[n.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[n.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),n.jsx("p",{className:"typography-micro text-muted-foreground",children:a===1?"1 worktree is being created":`${a} worktrees are being created`})]}),n.jsx("div",{className:"divide-y divide-border",children:i.map(f=>n.jsx(lm,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},lm=({entry:e,onOpen:t})=>{const s=e.state?.phase==="failed",r=!!(e.state&&!s),o=xl(e),i=Bu(e),a=s?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":o?"Sending prompt...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return n.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[n.jsx("div",{className:"mt-0.5 shrink-0",children:r||o?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner"}):s?n.jsx(R,{name:"alert",className:"size-4 text-[var(--status-error)]"}):n.jsx(R,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),n.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:s?e.state?.error:e.path??e.intent.sourceDirectory})]}),s?n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.failedSend?n.jsx(Ae,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${am(e.key)})`,onClick:()=>{const c=_u(e.key),d=zu(c,"background-task");d&&oe.error(d.title,{description:d.description})},children:"Restore draft"}):null,n.jsx(Ae,{type:"button",variant:"ghost",size:"xs",onClick:()=>Bn.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(Ae,{type:"button",size:"xs",onClick:t,children:"Open"}),n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Bn.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:n.jsx(R,{name:"close",className:"size-3.5"})})]}):null]})},cm=["pinned","today","yesterday","thisWeek","lastWeek","older"],dm={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},um=(e,t)=>{if(e==="sunday")return 0;if(e==="monday")return 1;try{const s=t||(typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().locale:"en-US");if(typeof Intl<"u"&&typeof Intl.Locale=="function"){const r=new Intl.Locale(s),i=(typeof r.getWeekInfo=="function"?r.getWeekInfo():r.weekInfo)?.firstDay;if(i===7||i===0)return 0;if(i!==void 0)return 1}}catch{}return 1},Zo=(e,t)=>{const s=new Date(e);s.setHours(0,0,0,0);const r=s.getTime(),o=new Date(r);o.setDate(o.getDate()-1),o.setHours(0,0,0,0);const i=o.getTime(),c=(s.getDay()-t+7)%7,d=new Date(r);d.setDate(d.getDate()-c),d.setHours(0,0,0,0);const u=d.getTime(),f=new Date(u);f.setDate(f.getDate()-7),f.setHours(0,0,0,0);const m=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:u,startOfLastWeek:m}},fm=(e,t)=>!Number.isFinite(e)||e<=0?"older":e>=t.startOfToday?"today":e>=t.startOfYesterday?"yesterday":e>=t.startOfThisWeek?"thisWeek":e>=t.startOfLastWeek?"lastWeek":"older",hm=(e,t)=>{const s={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,a=e.length;for(let d=0;d<a;d++){const u=e[d];if(o(u))s.pinned.push(u);else{const f=r(u),m=fm(f,i);s[m].push(u)}}const c=[];for(const d of cm){const u=s[d];u.length>0&&c.push({id:d,items:u})}return c},pm=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},mm=(e,t)=>{const[s,r]=l.useState(0),o=l.useMemo(()=>e?Zo(Date.now(),t):null,[e,t,s]),i=o?.startOfToday??null;return l.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const a=Date.now(),c=window.setTimeout(()=>{r(u=>u+1)},Math.max(50,pm(a)-a+50)),d=()=>{document.visibilityState==="visible"&&Zo(Date.now(),t).startOfToday!==i&&r(u=>u+1)};return document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(c),document.removeEventListener("visibilitychange",d)}},[i,t,s]),o},gm=e=>({getOrderedGroups:l.useCallback((s,r)=>{const o=e.get(s);if(!o||o.length===0)return r;const i=new Map(r.map(d=>[d.id,d])),a=[];o.forEach(d=>{const u=i.get(d);u&&(a.push(u),i.delete(d))});const c=[];return r.forEach(d=>{i.has(d.id)&&c.push(d)}),[...c,...a]},[e])}),bm=[],xm=e=>{const{normalizedProjects:t,getSessionsForProject:s,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:m,buildGroupSearchText:g,foldersMap:b,alwaysIncludeArchived:p=!1}=e,h=l.useRef(new Map),w=u||p,x=l.useMemo(()=>{const E=h.current,P=new Map;let z=0,K=0;const q=(F,D)=>F.length===D.length&&F.every((T,I)=>T===D[I]),G=t.map(F=>{const D=s(F.id),T=w?r(F.id):bm,I=i.has(F.id)?!!i.get(F.id):c,M=a.get(F.id)??null,H=o.get(F.normalizedPath)??[],W=E.get(F.id);if(W&&W.project===F&&q(W.activeSessions,D)&&q(W.archivedSessions,T)&&W.rootBranch===M&&W.isRepo===I&&W.worktrees===H&&W.buildGroupedSessions===d)return z+=1,P.set(F.id,W),W.section;K+=1;const L=Bl([...D,...T]),ae=d(L,F.normalizedPath,H,M,I),J={project:F,groups:ae};return P.set(F.id,{project:F,activeSessions:D,archivedSessions:T,rootBranch:M,isRepo:I,worktrees:H,buildGroupedSessions:d,section:J}),J});return h.current=P,z>0&&Wt("ui.sidebar.project_section.reused",z),K>0&&Wt("ui.sidebar.project_section.rebuilt",K),G},[t,s,r,w,o,i,c,d,a]),C=l.useMemo(()=>x,[x]),S=l.useMemo(()=>{const E=new WeakMap;if(!u)return E;const P=z=>z.reduce((K,q)=>K+1+P(q.children),0);return C.forEach(z=>{z.groups.forEach(K=>{const q=m(K.sessions,f),G=P(q),F=g(K).includes(f),D=Re(K.directory??null),I=(D?b[D]??[]:[]).filter(M=>M.name.toLowerCase().includes(f)).length;E.set(K,{filteredNodes:q,matchedSessionCount:G,folderNameMatchCount:I,groupMatches:F,hasMatch:F||G>0||I>0})})}),E},[u,C,m,f,g,b]),A=l.useMemo(()=>u?C.map(E=>({...E,groups:E.groups.filter(P=>S.get(P)?.hasMatch===!0)})).filter(E=>E.groups.length>0):C,[u,C,S]),y=u?A:C,j=l.useRef(new WeakMap),v=l.useMemo(()=>{const E=j.current;return y.map(P=>{const z=E.get(P);if(z&&z.query===f)return z.section;const K=P.groups,q=K.flatMap(I=>u?S.get(I)?.filteredNodes??[]:I.sessions),G=K.map(I=>({scopeKey:I.folderScopeKey??Re(I.directory??null),directory:I.directory??null})).filter(I=>!!I.scopeKey),F=K.find(I=>I.isMain)??null,D={id:"flat",label:F?.label??"",branch:F?.branch??null,description:F?.description??null,isMain:!0,directory:F?.directory??P.project.normalizedPath,folderScopeKey:F?.folderScopeKey??P.project.normalizedPath,folderScopes:G,sessions:q};if(u){const I=K.map(M=>S.get(M)).filter(M=>!!M);S.set(D,{filteredNodes:q,matchedSessionCount:I.reduce((M,H)=>M+H.matchedSessionCount,0),folderNameMatchCount:I.reduce((M,H)=>M+H.folderNameMatchCount,0),groupMatches:I.some(M=>M.groupMatches),hasMatch:I.some(M=>M.hasMatch)})}const T={project:P.project,groups:[D]};return E.set(P,{query:f,section:T}),T})},[S,u,f,y]),k=l.useMemo(()=>u?y.reduce((E,P)=>E+P.groups.reduce((z,K)=>{const q=S.get(K);if(!q)return z;const G=q.folderNameMatchCount+(q.groupMatches?1:0);return z+q.matchedSessionCount+G},0),0):0,[u,y,S]);return{projectSections:x,visibleProjectSections:C,groupSearchDataByGroup:S,searchableProjectSections:A,sectionsForRender:y,flatSectionsForRender:v,searchMatchCount:k}},$r=e=>!!e.session.time?.archived,ic=e=>{let t=0;for(const s of e)$r(s)||(t+=1);return t},ym=e=>{let t=0;for(const s of e)for(const r of s.groups)t+=ic(r.sessions);return t},wm=e=>{const t=new Map;for(const s of e){let r=0;for(const o of s.groups)r+=ic(o.sessions);t.set(s.project.id,r)}return t},vm=(e,t)=>e.groups.some(s=>s.sessions.some(r=>!$r(r)&&t.has(r.session.id))),Sm=(e,t)=>e.groups.some(s=>s.sessions.some(r=>!$r(r)&&t.has(r.session.id))),jm=(e,t)=>{const s=new Map;for(const r of e){const o=new Set;for(const i of r.groups)if(i.sessions.some(c=>!$r(c)&&t.has(c.session.id))&&i.directory){const c=Re(i.directory)?.toLowerCase();c&&o.add(c)}o.size>0&&s.set(r.project.id,o)}return s},ac=(e,t,s,r)=>{if(!s)return t;const o=e.find(c=>c.project.id===s);if(!o)return[];const i=Re(r??o.project.normalizedPath),a=o.groups.find(c=>Re(c.directory)===i);return a?[{...o,groups:[a]}]:[]},km=(e,t)=>{const s=new Map,r=new Map;return e.forEach(o=>{const i=xs(o.project,t);o.groups.forEach(a=>{const c=a.branch&&a.branch!=="HEAD"&&a.branch!==i?a.branch:null,d={projectLabel:i,branchLabel:c},u=f=>{f.forEach(m=>{const g=o.project.normalizedPath.length,b=r.get(m.session.id)??-1;g<b||(s.set(m.session.id,{node:m,projectId:o.project.id,groupDirectory:a.directory,secondaryMeta:d}),r.set(m.session.id,g),m.children.length>0&&u(m.children))})};u(a.sessions)})}),s};function Cm({projectSections:e,flatSectionsForRender:t,sectionsForRender:s,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:a,unreadSessionIdSet:c}){const d=l.useMemo(()=>km(e,i),[e,i]),u=t,f=l.useMemo(()=>ac(s,u,r,o),[s,u,r,o]),m=l.useMemo(()=>ym(e),[e]),g=l.useMemo(()=>wm(e),[e]),b=l.useCallback(w=>{const x=e.find(C=>C.project.id===w);return x?vm(x,a):!1},[a,e]),p=l.useMemo(()=>jm(e,a),[a,e]),h=l.useCallback(w=>{const x=e.find(C=>C.project.id===w);return x?Sm(x,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:m,sessionCountByProject:g,hasActiveSessionByProject:b,activeDirectoriesByProject:p,hasUnseenByProject:h}}const ha=[],Am={id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},Nm=(e,t,s)=>{const r=[],o=new Set,i=(a,c)=>{const d=xs(a.project,s);for(const u of a.groups)for(const f of u.sessions){if(o.has(f.session.id))continue;o.add(f.session.id);const m=f.session.time;r.push({node:f,project:a.project,projectLabel:d,isPinned:!1,timestamp:m?.archived||m?.updated||m?.created||0,globalSession:c})}};t&&i(t,!0);for(const a of e)i(a,!1);return r.sort((a,c)=>c.timestamp-a.timestamp)},Im=({viewMode:e,enabled:t,projects:s,archivedSessions:r,getArchivedSessionsForProject:o,isGlobalSession:i,buildGroupedSessions:a,availableWorktreesByProject:c,projectRepoStatus:d,projectRootBranches:u,lastRepoStatus:f,selectedSpaceId:m,selectedWorktreePath:g,homeDirectory:b})=>{const h=t&&(e==="threads"||e==="folder"||e==="workspace"),w=e==="workspace"?m:null,x=l.useMemo(()=>{if(!h)return[];const S=[];for(const A of s){if(w!==null&&A.id!==w)continue;const y=o(A.id);if(y.length===0)continue;const j=d.has(A.id)?!!d.get(A.id):f;S.push({project:A,groups:a(y,A.normalizedPath,c.get(A.normalizedPath)??[],u.get(A.id)??null,j)})}return S},[h,c,a,o,f,d,u,s,w]),C=l.useMemo(()=>{if(!h||w!==null)return null;const S=r.filter(i);return S.length===0?null:{project:Am,groups:a(S,"~",[],null,!1)}},[h,r,a,i,w]);return l.useMemo(()=>{if(!h)return ha;const S=w!==null?ac(x,x,w,g):x,A=Nm(S,C,b);return A.length>0?A:ha},[h,b,C,x,w,g])},Em=e=>{const{projectSections:t,activeProjectId:s,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:a,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:m}=e,g=l.useMemo(()=>{const p=new Map,h=new Map,w=(x,C,S,A)=>{p.has(x)||p.set(x,new Map);const y=p.get(x);A.forEach(j=>{const v=Re(j.session.directory??S??C);y.set(j.session.id,{directory:v}),h.has(x)||h.set(x,{id:j.session.id,directory:v}),j.children.length>0&&w(x,C,v,j.children)})};return t.forEach(x=>{x.groups.forEach(C=>{w(x.project.id,x.project.normalizedPath,C.directory,C.sessions)})}),{metaByProject:p,firstSessionByProject:h}},[t]),b=l.useRef(null);l.useLayoutEffect(()=>{if(!s)return;if(c){b.current=s;return}if(b.current===s)return;const p=t.find(j=>j.project.id===s);if(!p)return;b.current=s;const h=g.metaByProject.get(s);if(i&&h&&h.has(i)){o(j=>{if(j.get(s)===i)return j;const v=new Map(j);return v.set(s,i),v});return}const w=i?Array.from(g.metaByProject.entries()).some(([j,v])=>j!==s&&v.has(i)):!1;if(i&&h&&!w)return;if(!h||h.size===0){f("chat"),d&&m(!1),u({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath});return}const x=r.get(s),C=x&&h.has(x)?x:null,S=g.firstSessionByProject.get(s)?.id??null,A=C??S;if(!A||A===i)return;const y=h.get(A)?.directory??null;a(A,y,{keepPanelOpen:!0})},[s,r,i,a,c,d,u,t,g,f,m,o]),l.useEffect(()=>{if(!s||!i)return;const p=g.metaByProject.get(s);!p||!p.has(i)||o(h=>{if(h.get(s)===i)return h;const w=new Map(h);return w.set(s,i),w})},[s,i,g,o])},Dm=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...s})=>{const r=Me(c=>c.currentSessionId),o=Me(c=>!!c.newSessionDraft?.open),[i,a]=l.useState(()=>new Map(e));return Em({...s,activeSessionByProject:i,setActiveSessionByProject:a,currentSessionId:r,newSessionDraftOpen:o}),l.useEffect(()=>{t(i)},[i,t]),null},pa=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Rm=e=>{let t=5381;for(let s=0;s<e.length;s+=1)t=t*33^e.charCodeAt(s);return t>>>0},Pm=(e,t,s)=>(s.get(e)??0)>0?e:t.get(e)??null,lc=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=Rm(e.trim())%pa.length;return pa[t]},Tm=(e,t)=>{const s=lc(e);return s?t?.active?`color-mix(in srgb, ${s} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${s} 18%, transparent)`:null},ma=e=>!!e.time?.archived,Mm=e=>{const t=l.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),s=l.useCallback(i=>{const a=Re(i.directory??null)??"";return`${un(i)} ${a}`.toLowerCase()},[]),r=l.useCallback((i,a)=>a?i.flatMap(c=>{if(s(c.session).includes(a))return[c];const u=r(c.children,a);return u.length===0?[]:[{...c,children:u}]}):i,[s]),o=l.useCallback((i,a,c=[],d,u)=>{const f=Re(a??null),m=Bl(i).sort(yl(e.pinnedSessionIds,e.sessionOrderRanks)),g=new Map(m.map(j=>[j.id,j])),b=new Map,p=new Map;m.forEach(j=>{const v=j.parentID??null,k=v?g.get(v):null,E=k&&ma(k)===ma(j)?v:null;b.set(j.id,E),E&&p.set(E,(p.get(E)??0)+1)});const h=c.map(j=>({worktree:j,directory:Re(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,v)=>v.directory.length-j.directory.length),w=(j,v)=>v===j||v.startsWith(`${j}/`),x=j=>{const v=Re(j.directory??null);return v?h.find(k=>w(k.directory,v))?.worktree??null:null},C=(j,v)=>{const k=Pm(j.id,b,p);return{session:j,children:[],worktree:v,forkColorId:k}},S=[],A=new Map;for(const j of h)A.set(j.directory,[]);m.forEach(j=>{const v=x(j),k=C(j,v);v?A.get(Re(v.path)??"")?.push(k):S.push(k)});const y=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?_o(f,e.homeDirectory):null,isMain:!0,worktree:null,directory:f,folderScopeKey:f,sessions:S}];for(const{worktree:j,directory:v}of h)y.push({id:`worktree:${v}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:_o(v,e.homeDirectory),isMain:!1,worktree:j,directory:v,folderScopeKey:v,sessions:A.get(v)??[]});return y},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:s,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Fm=({mobileVariant:e,isTablet:t})=>!e&&!t,Lm=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:s,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{l.useEffect(()=>{if(!e||!t||typeof window>"u")return;const i=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(i)},[e,t,r]),l.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=a=>{o.current&&(o.current.contains(a.target)||s(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,s,o])},uo=(e,t)=>t===1?`Could not ${e} the session`:`Could not ${e} the sessions`,ga=(e,t)=>{if(!e.directory)return;const s=Vs.getState();tr(s.ids,e.directory,e.sessionId)!==t&&s.toggle({directory:e.directory,sessionId:e.sessionId})},cc=async(e,t={})=>{if(e.length===0)return;const s=Vs.getState(),r=new Set(e.filter(b=>tr(s.ids,b.directory,b.sessionId)).map(b=>b.sessionId));for(const b of e)r.has(b.sessionId)&&ga(b,!1);const o=b=>{for(const p of b)r.has(p.sessionId)&&ga(p,!0)},i=[...new Set(e.flatMap(b=>[b.sessionId,...b.forkIds]))];let a;try{a=await Me.getState().archiveSessions(i)}catch(b){console.warn("[session-archive] archive failed",b),a={archivedIds:[],failedIds:i}}const c=new Set(a.archivedIds),d=e.filter(b=>c.has(b.sessionId));if(o(e.filter(b=>!c.has(b.sessionId))),d.length===0){c.size>0&&Me.getState().unarchiveSessions([...c]),oe.error(uo("archive",e.length));return}const f=e.length===1&&t.title?`Archived “${t.title}”`:`Archived ${Zi(d.length)}`,m=a.archivedIds;oe.success(f,{action:{label:"Undo",onClick:()=>{o(d),Me.getState().unarchiveSessions(m).then(({failedIds:b})=>{b.length>0&&oe.error(uo("unarchive",m.length))}).catch(b=>{console.warn("[session-archive] undo failed",b),oe.error(uo("unarchive",m.length))})}}});const g=i.length-c.size;g>0&&oe.error(`Could not archive ${Zi(g)}`)},Om=e=>{const[t,s]=l.useState(null),r=l.useRef(null);l.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=l.useCallback((S,A,y)=>{zo("navigation.session_select"),ue.getState().closeMainSurfaces();const j=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},v=y?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),S===Me.getState().currentSessionId){e.allowReselect&&v&&e.onSessionSelected?.(S),j();return}zo("navigation.session_state_set"),e.setCurrentSession(S,A??null),v&&e.onSessionSelected?.(S),j()},[e]),i=l.useCallback((S,A)=>{e.setEditingId(S),e.setEditTitle(A)},[e]),a=l.useCallback(async S=>{if(!e.editingId)return;const A=(S??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=l.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=l.useCallback(async(S,A)=>{try{return(await fn(S)).ok?(s(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{s(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=l.useCallback(async S=>{const A=await e.shareSession(S.id);if(!A?.share?.url){oe.error("Unable to share session");return}const y=await d(A.share.url,S.id);oe[y?"success":"warning"]("Session shared",{description:y?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=l.useCallback((S,A)=>{d(S,A).then(y=>{y||oe.error("Failed to copy URL")})},[d]),m=l.useCallback(S=>{fn(S).then(A=>{if(A.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),g=l.useCallback(async S=>{await e.unshareSession(S)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),b=l.useCallback(S=>{const A=[],y=j=>{(e.childrenMap.get(j)??[]).forEach(k=>{A.push(k),y(k.id)})};return y(S),A},[e.childrenMap]),p=l.useCallback((S,A)=>A?S:S.filter(y=>!y.time?.archived),[]),h=l.useCallback(async(S,A)=>{const y=A?.descendantIds??p(b(S.id),!0).map(k=>k.id);if(y.length===0){await e.deleteSession(S.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const{deletedIds:j,failedIds:v}=await e.deleteSessions([S.id,...y]);if(v.length===0){const k=j.length;oe.success(k===1?`Deleted ${k} session`:`Deleted ${k} sessions`)}else oe.error("Failed to delete session")},[e,b,p]),w=l.useCallback((S,A)=>{const y=A?.archivedBucket===!0||A?.hardDelete===!0,j=p(b(S.id),y).map(v=>v.id);if(!y){cc([{sessionId:S.id,directory:S.directory??null,forkIds:j}],{title:un(S,"Untitled session")});return}if(!e.showDeletionDialog||A?.skipConfirm===!0){h(S,{descendantIds:j});return}e.setDeleteSessionConfirm({session:S,descendantCount:j.length,descendantIds:j})},[e,b,h,p]),x=l.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:S,descendantIds:A}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(S,{descendantIds:A})},[e,h]),C=l.useCallback(async S=>{await e.unarchiveSession(S.id)?oe.success("Session unarchived"):oe.error("Could not unarchive the session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:a,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:m,handleUnshareSession:g,handleDeleteSession:w,handleRestoreSession:C,confirmDeleteSession:x}},Bm=e=>{const{safeStorage:t,keys:s,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:a}=e,c=l.useRef(null),d=l.useRef(null),u=l.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:g}=ct.getState(),b=g.map(p=>({...p,sidebarCollapsed:m.has(p.id)}));Pl({projects:b}).catch(()=>{})},[]),f=l.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return l.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),l.useEffect(()=>{try{const m=t.getItem(s.sessionExpanded);if(m){const b=JSON.parse(m);Array.isArray(b)&&i(new Set(b.filter(p=>typeof p=="string")))}const g=t.getItem(s.projectCollapse);if(g){const b=JSON.parse(g);Array.isArray(b)&&a(new Set(b.filter(p=>typeof p=="string")))}}catch{}},[s.projectCollapse,s.sessionExpanded,t,a,i]),l.useEffect(()=>{try{const m=Object.fromEntries(r.entries());t.setItem(s.groupOrder,JSON.stringify(m))}catch{}},[r,s.groupOrder,t]),l.useEffect(()=>{try{t.setItem(s.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,s.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},_m=3;let Rr=0;const dc=[],zm=()=>Rr<_m?(Rr+=1,Promise.resolve()):new Promise(e=>{dc.push(e)}),Um=()=>{const e=dc.shift();if(e){e();return}Rr=Math.max(0,Rr-1)},$m=async e=>{await zm();try{return await e()}finally{Um()}},Km=5*6e4,Wm=e=>{const{normalizedProjects:t,enabled:s=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:a}=Un(),c=wl(p=>p.ensureStatus),d=l.useMemo(()=>t.map(p=>p.normalizedPath).slice().sort().join("\0"),[t]),u=l.useRef(null);l.useEffect(()=>{if(!s||!a||t.length===0){u.current=null,o(new Map);return}const p=`${Tt()}\0${d}`;u.current!==p&&(u.current=p,t.forEach(h=>{$m(()=>c(h.normalizedPath,a))}))},[s,t,d,a,c,o]);const f=l.useRef(null);l.useEffect(()=>{if(!s){f.current=null;return}const p=new Map;t.forEach(w=>{p.set(w.id,r.get(w.normalizedPath)?.isGitRepo??null)});const h=t.map(w=>`${w.id}:${String(p.get(w.id))}`).join("|");f.current!==h&&(f.current=h,o(p))},[s,t,d,r,o]);const m=l.useMemo(()=>t.map(p=>{const h=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${h}`}).join("|"),[t,r]),g=l.useRef(new Map),b=l.useRef(new Map);l.useEffect(()=>{if(!s)return;let p=!1;const h=setTimeout(()=>{(async()=>{const x=new Set(t.map(j=>j.id));for(const j of g.current.keys())x.has(j)||(g.current.delete(j),b.current.delete(j));const C=Date.now();if(t.filter(j=>{const v=r.get(j.normalizedPath);if(v?.isGitRepo===!1)return g.current.delete(j.id),b.current.delete(j.id),!1;if(v?.isGitRepo!==!0||v.branch===null)return!1;const k=v.branch.trim(),E=`${j.normalizedPath}\0${k}`,P=g.current.get(j.id);if(P===E){const z=b.current.get(j.id);return z&&(z.at=C),!1}return!(P!==void 0&&C-(b.current.get(j.id)?.at??0)<Km)}).length===0)return;const A=[];if(t.forEach(j=>{const v=r.get(j.normalizedPath)?.branch?.trim()??"",k=`${j.normalizedPath}\0${v}`;v&&A.push({id:j.id,inputKey:k,branch:v})}),p||A.length===0)return;const y=Date.now();i(j=>{const v=new Map(j);return A.forEach(({id:k,branch:E})=>{E&&v.set(k,E)}),v}),A.forEach(({id:j,inputKey:v,branch:k})=>{g.current.set(j,v),k&&b.current.set(j,{branch:k,at:y})})})()},150);return()=>{p=!0,clearTimeout(h)}},[s,t,m,r,i])},Hm=e=>{const{ownership:t}=e,s=l.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=l.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:s,getArchivedSessionsForProject:r}},Gm=e=>{const t=new Map;for(const s of e){const r=is(s);r&&t.set(s.id,{directory:r,sessionId:s.id})}return t},qm=(e,t)=>{if(!e)return[];const s=[];return e.forEach((r,o)=>{t.has(o)||s.push(r)}),s},Vm=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:s,sessions:r}=e,o=l.useRef(null);l.useEffect(()=>{if(!t||!s)return;const i=Tt(),a=Gm(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const d of qm(c,a))ts().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:i,identities:a}},[t,s,r])},Ym=(e,t)=>e?t.kind!==e.kind?t.kind==="project":t.projectRoot.length!==e.projectRoot.length?t.projectRoot.length>e.projectRoot.length:t.projectId.localeCompare(e.projectId)<0:!0,ba=(e,t,s)=>{Ym(e.get(t),s)&&e.set(t,s)},uc=e=>{const t=e;return Re(t.directory)??Re(t.project?.worktree)},Qm=(e,t,s)=>{if(e.time?.archived)return!0;const r=uc(e);if(!r)return s?.allowUnknownDirectory??!0;if(Ys(r,s?.homeDirectory))return!0;if(t.size===0)return s?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Re(i)?.toLowerCase()===o)return!0;return!1},Jm=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const t=e.lastIndexOf("/");return t<0?null:t===0?"/":t===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,t)},Xm=(e,t,s,r=[])=>{const o=new Map,i=new Map;for(const b of t){const p=Re(b.normalizedPath);if(!p)continue;const h=i.get(p);(!h||b.id.localeCompare(h.id)<0)&&i.set(p,b),ba(o,p,{projectId:b.id,projectRoot:p,scopeDirectory:p,kind:"project"})}if(s)for(const[b,p]of s){const h=Re(b),w=h?i.get(h):void 0;if(!(!w||!h))for(const x of p||[]){const C=Re(x?.path);C&&ba(o,C,{projectId:w.id,projectRoot:h,scopeDirectory:C,kind:"worktree"})}}const a=new Map,c=new Map,d=new Map,u=new Map,f=new Map,m=b=>{if(!b)return null;if(a.has(b))return a.get(b)??null;const p=[];let h=b,w=null;for(;h;){if(a.has(h)){w=a.get(h)??null;break}if(p.push(h),w=o.get(h)??null,w)break;h=Jm(h)}for(const x of p)a.set(x,w);return w},g=(b,p,h)=>{for(const w of b){const x=uc(w);if(Ys(x))continue;const C=m(x);if(!C)continue;c.set(w.id,C);const S=p.get(C.projectId);if(S?S.push(w):p.set(C.projectId,[w]),!h)continue;const A=h.get(C.scopeDirectory);A?A.add(w.id):h.set(C.scopeDirectory,new Set([w.id]))}};return g(e,d,f),g(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:a.size}};function fc({state:e,activeLabel:t,unreadLabel:s,inputLabel:r,className:o}){if(e==="input"){const i=r??"Needs input";return n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":i,title:i,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return e==="unread"?n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":s??t,title:s??t,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":t,title:t,children:n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Zm=({folder:e,displayName:t,sessions:s,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:a,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:m,projectId:g,mobileVariant:b=!1,alwaysShowActions:p=b,isRenaming:h=!1,renameDraft:w="",onRenameDraftChange:x,onRenameSave:C,onRenameCancel:S,droppableRef:A,isDropTarget:y=!1,onNewSession:j,depth:v=0,hideActions:k=!1,archivedBucket:E=!1})=>{const[P,z]=l.useState(!1),[K,q]=l.useState(""),G=l.useRef(null),F=h||P,D=h?w:K,T=l.useCallback(()=>{q(e.name),z(!0)},[e.name]),I=l.useCallback(()=>{const L=D.trim();L&&L!==e.name&&c(L),h&&C&&C(),z(!1),q("")},[D,e.name,h,c,C]),M=l.useCallback(()=>{h&&S&&S(),z(!1),q("")},[h,S]),H=l.useCallback(L=>{h&&x?x(L):q(L)},[h,x]);l.useEffect(()=>{if(!h)return;const L=()=>{const le=G.current;le&&(le.focus(),le.select())},ae=requestAnimationFrame(L),J=window.setTimeout(L,0);return()=>{cancelAnimationFrame(ae),window.clearTimeout(J)}},[h]);const W=o?"folder":"folder-open";return n.jsxs("div",{className:"oc-folder",children:[n.jsxs("div",{ref:A,className:_("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",y&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:F?void 0:L=>{L.currentTarget.blur(),a()},role:F?void 0:"button",tabIndex:F?void 0:0,onKeyDown:F?void 0:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),a())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[n.jsxs("div",{className:_("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",E?p?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":p?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[n.jsx(R,{name:W,className:_(wr,y?"text-primary":"text-muted-foreground")}),F?n.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onSubmit:L=>{L.preventDefault(),I()},children:[n.jsx("input",{ref:G,value:D,onChange:L=>H(L.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:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onKeyDown:L=>{if(L.key==="Escape"){L.stopPropagation(),M();return}(L.key===" "||L.key==="Enter")&&L.stopPropagation()}}),n.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),children:n.jsx(R,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),M()},onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(R,{name:"close",className:"size-4"})})]}):n.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("span",{className:_(_l,y?"text-primary":"text-muted-foreground"),children:t??e.name})}),n.jsx(He,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),n.jsxs("span",{className:"typography-micro text-subtle-foreground flex-shrink-0",children:["• ",s.length]}),i?n.jsx(fc,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?n.jsx(R,{name:"arrow-right-s",className:_(wr,"text-muted-foreground")}):n.jsx(R,{name:"arrow-down-s",className:_(wr,"text-muted-foreground")})]})]}),!F&&(!k||E)?n.jsx("div",{className:_("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",p?"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:n.jsxs("div",{className:"flex items-center gap-0.5",children:[!E&&j?n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),j()},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:n.jsx(R,{name:"add",className:"size-4"})}):null,E?null:n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),T()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:n.jsx(R,{name:"pencil-ai",className:"size-4"})}),n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":E?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:n.jsx(R,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:n.jsxs("div",{className:"pb-1",children:[r,s.length>0?s.map(L=>n.jsx(l.Fragment,{children:u(L,0,m??null,g??null,E,void 0,"project",f?.(L))},L.session.id)):r?null:n.jsx("div",{className:"py-1 px-3 text-left typography-micro text-subtle-foreground",children:"Empty folder"})]})]})},eg=l.memo(Zm),Kr=l.createContext(null),tg=({sessionId:e,sessionDirectory:t,sessionTitle:s,children:r})=>{const{attributes:o,listeners:i,setNodeRef:a,isDragging:c}=du({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:s}}),d=l.useCallback(u=>{u.stopPropagation(),i?.onPointerDown&&i.onPointerDown(u)},[i]);return n.jsx("div",{ref:a,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},ng=({folderId:e,children:t})=>{const{setNodeRef:s,isOver:r}=al({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return n.jsx(n.Fragment,{children:t(s,r)})},sg=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:s,children:r})=>{const o=Br(ds(ol,{activationConstraint:{distance:8}})),[i,a]=l.useState(null),[c,d]=l.useState("Session"),[u,f]=l.useState(null),[m,g]=l.useState(null);if(!e)return n.jsx(n.Fragment,{children:r});const b=p=>{a(null),f(null),g(null);const{active:h,over:w}=p;if(!w)return;const x=h.data.current,C=w.data.current;x?.type==="session"&&x.sessionId&&C?.type==="folder"&&C.folderId&&s(x.sessionId,C.folderId)};return n.jsxs(_r,{sensors:o,collisionDetection:mi,onDragStart:p=>{const h=p.active.data.current;if(h?.type==="session"&&h.sessionId){a(h.sessionId),d(h.sessionTitle??"Session");const w=p.active.rect.current.initial?.width,x=p.active.rect.current.initial?.height;f(typeof w=="number"?w:null),g(typeof x=="number"?x:null)}},onDragCancel:()=>{a(null),f(null),g(null)},onDragEnd:b,children:[r,n.jsx(il,{children:i&&t?n.jsxs("div",{style:{width:u?`${u}px`:"auto",height:m?`${m}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:[n.jsx(R,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),n.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Wr="gap-2",hc="my-0.5 rounded-lg py-1.5",Xs=l.createContext("card"),Ht=({icon:e,children:t,onClick:s,className:r,mobileVariant:o=!1})=>{const i=l.useContext(Xs)==="tree";return n.jsxs("button",{type:"button",onClick:s,"data-sidebar-tree-row":i?"":void 0,className:_(o?fh:hh,i&&Wr,i&&hc,r),children:[n.jsx(R,{name:e,className:_(_n(o),"text-muted-foreground")}),n.jsx("span",{className:_(ps(o),"flex-1 text-muted-foreground"),children:t})]})},rg="select-none px-3 pb-1 typography-ui-label font-medium text-muted-foreground",ls=({label:e,first:t=!1,count:s,expanded:r,onToggle:o})=>{const i=t?"pt-1":"pt-3",a=typeof s=="number"?n.jsx("span",{className:"font-normal tabular-nums text-subtle-foreground",children:s}):null;return o?n.jsx("div",{role:"heading","aria-level":3,className:i,children:n.jsxs("button",{type:"button","aria-expanded":r,onClick:o,className:"group/heading flex h-7 w-full select-none items-center gap-1.5 rounded-md px-3 text-left typography-ui-label font-medium text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e,a,n.jsx(R,{name:r?"arrow-down-s":"arrow-right-s",className:"ml-auto size-4 shrink-0 text-muted-foreground group-hover/heading:text-foreground"})]})}):n.jsxs("div",{role:"heading","aria-level":3,className:_(rg,i,"flex items-center gap-1.5"),children:[e,a]})},xa=(e,t,s)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const a of o.children)i=r(a)||i;return i&&s.add(o.session.id),i};for(const o of e)r(o)},dn=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const s of e.children)if(dn(s,t))return!0;return!1},og=(e,t)=>{const s=new Set(e);return e.map(r=>t.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let i=r.session.parentID??null;for(;i&&!o.has(i);){if(s.has(i)&&t.has(i))return!1;o.add(i),i=t.get(i)?.session?.parentID??null}return!0})},ya=new WeakMap;let wa=1;const ig=e=>{const t=ya.get(e);if(t!==void 0)return t;const s=wa;return wa+=1,ya.set(e,s),s},ei=e=>e.children.length===0?"":e.children.map(s=>{const r=ig(s.session);return s.children.length===0?`${s.session.id}@${r}`:`${s.session.id}@${r}:${ei(s)}`}).join("|"),pc=(e,t,s,r,o,i)=>{const a=Tt(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,m=u.session.directory??i,g=Yi(a,f??"",d.session.id),b=Yi(a,m??"",u.session.id);return(g?s.has(g):!1)!==(b?r.has(b):!1)?!0:d.children.some((p,h)=>c(p,u.children[h]))};return c(e,t)},Zs=(e,t)=>`${e}:${t.time?.archived?"archived":"active"}:${t.id}`,Pr=(e,t,s)=>{if(!t)return null;let r=null;const o=i=>{if(Zs(s,i.session)===t)return r=i.session.id,!0;for(const c of i.children)if(o(c))return!0;return!1};return e.forEach(i=>o(i)),r},ag=5*6e4,lg=6e4,va=5*6e4,Sa=100,Ps=new Map,ns=new Map,Ln=new Map,cs=new Map,er=(e,t)=>{const s=hn((e??"").trim()),r=(t??"").trim();return!s||!r?"":`${Tt()}
|
|
12
|
+
${s}
|
|
13
|
+
${r}`},ja=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),cg=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},dg=e=>{const t=Object.keys(e);if(t.length<=Sa)return e;const s=t.sort((o,i)=>(cs.get(o)??0)-(cs.get(i)??0)),r={...e};for(let o=0;o<s.length-Sa;o+=1){const i=s[o];delete r[i],cs.delete(i),ns.delete(i);const a=Ln.get(i);a!==void 0&&(clearTimeout(a),Ln.delete(i))}return r},mc=e=>e.pr?e.pr.state!=="open"?va:e.checks?.state==="pending"?lg:va:ag,ti=(e,t,s,r)=>{if(typeof window>"u"||Ln.has(e))return;const o=Zt.getState().results[e];if(!o)return;const i=mc(o),a=setTimeout(()=>{if(Ln.delete(e),!!Zt.getState().results[e]){if(typeof document<"u"&&document.hidden){ti(e,t,s,r);return}Zt.getState().refresh(t,s,r)}},i);typeof a=="object"&&a!==null&&typeof a.unref=="function"&&a.unref(),Ln.set(e,a)},Zt=$n()(zr((e,t)=>({results:{},refresh:async(s,r,o,i)=>{const a=hn((s||"").trim()),c=(r||"").trim();if(!a||!c)return null;const d=er(a,c);if(!d)return null;const u=Ps.get(d);if(u&&!i?.force)return u;const f=o??null;if(!f)return t().results[d]??null;const m=(ns.get(d)??0)+1;ns.set(d,m);const g=t().results[d]??ja();e(p=>({results:{...p.results,[d]:{...g,isLoading:!0}}}));const b=(async()=>{try{const p=await f.prStatus(a,c);if(ns.get(d)!==m||Tt()!==d.split(`
|
|
14
|
+
`)[0])return t().results[d]??null;const h={pr:p.pr??null,checks:p.checks??null,checksStale:p.checksStale,defaultBranch:p.defaultBranch??null,skippedDefaultBranch:p.skippedDefaultBranch,fetchedAt:p.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return cs.set(d,Date.now()),e(w=>({results:dg({...w.results,[d]:h})})),ti(d,a,c,f),h}catch(p){if(ns.get(d)!==m)return t().results[d]??null;const h=cg(p),w=g.pr||g.fetchedAt?{...g,isLoading:!1,stale:!0,error:h}:{...ja(),error:h};return e(x=>({results:{...x.results,[d]:w}})),ti(d,a,c,f),w}})();Ps.set(d,b);try{return await b}finally{Ps.get(d)===b&&Ps.delete(d)}},load:async(s,r,o)=>{const i=hn((s||"").trim()),a=(r||"").trim();if(!i||!a)return null;const c=er(i,a);cs.set(c,Date.now());const d=t().results[c];return d&&(d.pr||d.fetchedAt)?(t().refresh(i,a,o),d):t().refresh(i,a,o)},resetForRuntimeSwitch:()=>{Ps.clear(),ns.clear(),cs.clear(),Fs=null;for(const s of Ln.values())clearTimeout(s);Ln.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(bs(()=>{Zt.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await ht(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-fmzQmSSv.js").then(o=>o.cJ);return{getRegisteredRuntimeAPIs:r}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:r})=>r()?.github??null).catch(()=>null);if(!e)return;const t=Date.now(),s=Object.entries(Zt.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=mc(r)).map(([r])=>r);for(const r of s){const[,o,i]=r.split(`
|
|
15
|
+
`);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await Zt.getState().refresh(o,i,e).catch(()=>null)}}})()}));let Fs=null;const Kw=e=>{if(Fs&&Fs.results===e)return Fs.index;const t=new Map;for(const s of Object.values(e)){const r=s.pr?.url;!r||t.has(r)||t.set(r,s.checks?.state??null)}return Fs={results:e,index:t},t},ug=e=>{const t=e?.pr;if(!t)return null;if(t.state==="merged")return{visualState:"merged",number:t.number,draft:t.draft,title:t.title};if(t.state==="closed")return{visualState:"closed",number:t.number,draft:t.draft,title:t.title};if(t.draft)return{visualState:"draft",number:t.number,draft:!0,title:t.title,mergeableState:t.mergeableState??void 0,checks:e?.checks?{state:e.checks.state}:void 0};const s=e?.checks?.state,r=t.mergeableState??void 0;return r==="dirty"||r==="blocked"||s==="failure"?{visualState:"blocked",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}:{visualState:"open",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}},gc=e=>{const t=Zt(s=>e?s.results[e]??null:null);return l.useMemo(()=>ug(t),[t])},bc=(e,t,s)=>{const r=l.useMemo(()=>er(e,t),[e,t]),o=s??null;l.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return ht(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-fmzQmSSv.js").then(c=>c.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{if(i)return;const c=o??a()?.github??null;c&&Zt.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},xc=new Set,ji=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,ni=(e,t,s,r=xc)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(ni(i,t,s,r)==="input")return"input";return"active"}let o=s.has(e.session.id)?"unread":null;for(const i of e.children)if(o=ji(o,ni(i,t,s,r)),o==="input")return o;return o},yc=(e,t,s,r=xc)=>{let o=null;for(const i of e)if(o=ji(o,ni(i,t,s,r)),o==="input")return o;return o},si=(e,t)=>{if(!t)return e;const s=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let a=0,c=s.indexOf(r,a);for(;c!==-1;){c>a&&i.push(e.slice(a,c));const d=e.slice(c,c+o);i.push(n.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),a=c+o,c=s.indexOf(r,a)}return a<e.length&&i.push(e.slice(a)),i.length>0?i:e},vs=e=>[Tt(),...e.map(t=>(t??"").toString())].join(`
|
|
16
|
+
`),hr=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},fg=200,os=(e={})=>{const t=e.maxEntries??fg,s=new Map,r=new Map,o=new Map;let i=0;const a=new Map,c=new Map,d=h=>{const w=s.get(h)??null;return w&&a.set(h,i+=1),w},u=h=>{const w=c.get(h);if(w)for(const x of[...w])try{x()}catch{}},f=()=>{if(s.size<=t)return;const h=[...s.keys()].filter(x=>!r.has(x)&&(c.get(x)?.size??0)===0).sort((x,C)=>(a.get(x)??0)-(a.get(C)??0)),w=s.size-t;for(let x=0;x<w&&x<h.length;x+=1){const C=h[x];s.delete(C),a.delete(C),o.set(C,(o.get(C)??0)+1)}};let m=!1;const g=()=>{if(m||s.size<=t)return;m=!0;const h=()=>{m=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(h):setTimeout(h,0)},b=(h,w)=>{const C={...s.get(h)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(h)??0},...w};return s.set(h,C),a.set(h,i+=1),g(),u(h),C},p=async(h,w)=>{const x=r.get(h);if(x)return x;const C=(o.get(h)??0)+1;o.set(h,C);const S=s.get(h);b(h,{isLoading:!0,generation:C});const A=(async()=>{try{const y=await w();return o.get(h)!==C?s.get(h)??{data:y,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:C}:b(h,{data:y,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:C})}catch(y){return o.get(h)!==C?s.get(h)??{data:S?.data??null,fetchedAt:S?.fetchedAt??null,isLoading:!1,stale:!0,error:hr(y),generation:C}:S?.data!=null?b(h,{isLoading:!1,stale:!0,error:hr(y),generation:C}):b(h,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:hr(y),generation:C})}})();r.set(h,A);try{return await A}finally{r.get(h)===A&&r.delete(h),e.onSettle?.(h)}};return{getEntry:d,snapshot:()=>Object.fromEntries(s),subscribe:(h,w)=>{let x=c.get(h);return x||(x=new Set,c.set(h,x)),x.add(w),()=>{const C=c.get(h);C&&(C.delete(w),C.size===0&&c.delete(h))}},ensure:(h,w,x)=>!x?.force&&r.has(h)?r.get(h):!x?.force&&s.get(h)?.data!=null&&s.get(h)?.isLoading?r.get(h)??Promise.resolve(s.get(h)):!x?.force&&s.get(h)?.data!=null?(p(h,w),Promise.resolve(s.get(h))):p(h,w),refresh:(h,w)=>p(h,w),invalidate:async(h,w,x)=>{if(x?.exact??!0)return o.set(h,(o.get(h)??0)+1),s.delete(h),a.delete(h),r.has(h)&&r.delete(h),u(h),w?p(h,w):null;for(const S of[...s.keys()])(S===h||S.startsWith(h))&&(o.set(S,(o.get(S)??0)+1),s.delete(S),a.delete(S),r.delete(S),u(S));return null},markStale:h=>{const w=s.get(h);w?.data&&(w.stale||b(h,{stale:!0}))},setError:(h,w)=>{const x=s.get(h);return x?.data?b(h,{isLoading:!1,stale:!0,error:hr(w)}):x??null},remove:h=>{o.set(h,(o.get(h)??0)+1),s.delete(h),a.delete(h),r.delete(h),u(h)},reset:()=>{const h=[...s.keys()];s.clear(),r.clear(),o.clear(),a.clear();for(const w of h)u(w)}}},Ss=(e,t)=>Te.useSyncExternalStore(s=>t?e.subscribe(t,s):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),Ww=e=>{const t=e.trim().match(/^#?(\d{1,7})$/);if(!t)return null;const s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:null},wc=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),ri=e=>{if(!e)return[];const t=[];for(const s of e)s?.login&&t.push(s.login.toLowerCase());return t},vc=e=>{const t=[],s=[];for(const r of e.trim().toLowerCase().split(/\s+/))r&&(r.startsWith("label:")&&r.length>6?s.push(r.slice(6)):t.push(r));return{tokens:t,labelTokens:s}},ki=e=>{if(!e)return[];const t=[];for(const s of e)s?.name&&t.push(s.name.toLowerCase());return t},Sc=(e,t,s)=>{const r=ki(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...s])if(!r.some(a=>a===i||a.includes(i)))return!1;return!0},hg=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const s of ki(e.labels))t.push(s);return t},pg=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const s of ki(e.labels))t.push(s);return t},jc=(e,t)=>{for(const s of t){let r=!1;for(const o of e)if(o.includes(s)){r=!0;break}if(!r)return!1}return!0},ka=e=>e.state==="merged"||!!e.mergedAt,mg=(e,t)=>t==="all"?e:t==="open"?e.filter(s=>s.state==="open"):t==="merged"?e.filter(s=>ka(s)):e.filter(s=>s.state==="closed"&&!ka(s)),gg=(e,t)=>t==="all"?e:e.filter(s=>s.state===t),bg=(e,t,s)=>t==="all"||!s?!0:t==="mine"?wc(e.author?.login,s):t==="review"?ri(e.requestedReviewers).includes(s.toLowerCase()):ri(e.assignees).includes(s.toLowerCase()),xg=(e,t,s)=>t==="all"||!s||t==="mentioned"?!0:t==="mine"?wc(e.author?.login,s):ri(e.assignees).includes(s.toLowerCase()),Xn=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},kc=(e,t)=>{const s=[...e];return t==="newest"?(s.sort((r,o)=>Xn(o.createdAt)-Xn(r.createdAt)||o.number-r.number),s):t==="oldest"?(s.sort((r,o)=>Xn(r.createdAt)-Xn(o.createdAt)||r.number-o.number),s):(s.sort((r,o)=>Xn(o.updatedAt)-Xn(r.updatedAt)||o.number-r.number),s)},Hw=(e,t)=>{const{tokens:s,labelTokens:r}=vc(t.search),o=[];for(const i of mg(e,t.state))bg(i,t.involvement,t.viewerLogin)&&Sc(i.labels,"",r)&&jc(hg(i),s)&&o.push(i);return kc(o,t.sort)},Gw=(e,t)=>{const{tokens:s,labelTokens:r}=vc(t.search),o=[];for(const i of gg(e,t.state))xg(i,t.involvement,t.viewerLogin)&&Sc(i.labels,t.labels,r)&&jc(pg(i),s)&&o.push(i);return kc(o,t.sort)},pr=(e,t)=>{if(t.length===0)return e;const s=new Map;for(const i of t)s.set(i.number,i);const r=e.map(i=>s.get(i.number)??i),o=new Set(e.map(i=>i.number));for(const i of t)o.has(i.number)||r.push(i);return r},qw=(e,t)=>e.filter(s=>!t.has(s.number)),yg=(e,t)=>{if(t.length===0)return e;const s=new Set(e.map(o=>o.id)),r=[...e];for(const o of t)s.has(o.id)||(s.add(o.id),r.push(o));return r},Ca=Object.freeze({repo:null,number:null}),fo=e=>e.split(`
|
|
17
|
+
`)[1]??"",oi=(e,t)=>`${hn(e)}
|
|
18
|
+
${t}`,Ts=(e,t)=>`${e}#${t}`,wg=(e,t)=>{const s=e?.body;return s&&typeof s.kind=="string"?s:{kind:"failed",message:e instanceof Error?e.message:t}},Tn=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Aa=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,Na=10,vg=(e,t)=>{const s=os(),r=os({maxEntries:60}),o=os(),i=os(),a=new Map,c=new Map,d=async(F,D)=>{const T=c.get(F);if(T)return await T.catch(()=>null),{ran:!1,result:null};const I=D();c.set(F,I);try{return{ran:!0,result:await I}}finally{c.get(F)===I&&c.delete(F)}},u=(F,D)=>{if(D.length===0)return;const T=e.collectionKeyFor(F,e.openCollection);let I=a.get(T);I||(I=new Map,a.set(T,I));for(const M of D)I.set(M.number,M)},f=F=>{const D=Object.keys(r.snapshot()).filter(I=>fo(I)===F&&!r.getEntry(I)?.isLoading);if(D.length<=Na)return;const T=D.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,M)=>I.fetchedAt-M.fetchedAt);for(let I=0;I<T.length-Na;I+=1)r.remove(T[I].key)},m=F=>{const D=s.getEntry(e.collectionKeyFor(F,e.openCollection))?.data?.items??[],T=s.getEntry(e.collectionKeyFor(F,e.closedCollection))?.data?.items??[],I=pr(D,T),M=a.get(e.collectionKeyFor(F,e.openCollection));return!M||M.size===0?I:pr(I,[...M.values()])},g=(F,D,T)=>{const I=oi(F,D),M=t.get().filtersByScope[I]??e.defaultFilters;t.set(H=>({filtersByScope:{...H.filtersByScope,[I]:{...M,...T}}}))},b=(F,D)=>{const T=oi(F,D);t.set(I=>({filtersByScope:{...I.filtersByScope,[T]:{...e.defaultFilters}}}))},p=(F,D,T)=>{const I=hn(F);I&&t.set(M=>({selectionByDirectory:{...M.selectionByDirectory,[I]:{repo:D,number:T}}}))},h=(F,D,T,I)=>{const M=e.collectionKeyFor(D,T);return s.ensure(M,async()=>{const H=await e.fetchList(I,F,D,e.buildCollectionQuery(T));return{items:H.items,nextCursor:H.nextCursor,fetchedAt:H.fetchedAt}})},w=(F,D,T)=>{const I=e.collectionKeyFor(D,e.closedCollection);s.getEntry(I)?.data||s.getEntry(I)?.isLoading||h(F,D,e.closedCollection,T).catch(()=>null)},x=async(F,D,T,I)=>{const M=T==="open"||T==="both",H=T==="closed"||T==="both",W=[],L=s.getEntry(e.collectionKeyFor(D,e.openCollection)),ae=s.getEntry(e.collectionKeyFor(D,e.closedCollection));M&&(!Aa(L,e.freshWindowMs)||L?.stale)&&W.push(h(F,D,e.openCollection,I)),H&&(!Aa(ae,e.freshWindowMs)||ae?.stale)&&W.push(h(F,D,e.closedCollection,I)),await Promise.all(W.map(J=>J.catch(()=>null))),M&&!s.getEntry(e.collectionKeyFor(D,e.closedCollection))?.data&&w(F,D,I)},C=async(F,D,T,I)=>{const M=e.collectionKeyFor(D,T),H=s.getEntry(M),W=H?.data?.nextCursor??null;if(!W||H?.isLoading)return H;try{const L=await d(`${M}:more`,async()=>{const ae=await e.fetchList(I,F,D,{...e.buildCollectionQuery(T),cursor:W}),J=s.getEntry(M)?.data,le={items:pr(J?.items??[],ae.items),nextCursor:ae.nextCursor,fetchedAt:ae.fetchedAt};return s.refresh(M,async()=>le)});return L.ran?L.result??s.getEntry(M):s.getEntry(M)}catch(L){return s.setError(M,L)??s.getEntry(M)}},S=async(F,D,T,I)=>{const M=T==="both"?[e.openCollection,e.closedCollection]:[T];await Promise.all(M.map(H=>{const W=e.collectionKeyFor(D,H);return s.refresh(W,async()=>{const L=await e.fetchList(I,F,D,e.buildCollectionQuery(H));return{items:L.items,nextCursor:L.nextCursor,fetchedAt:L.fetchedAt}}).catch(()=>null)}))},A=async(F,D,T,I)=>{const M=e.remoteKeyFor(D,T),H=await r.refresh(M,async()=>{const W=await e.fetchList(I,F,D,e.buildRemoteQuery(T));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}});return H.data&&(u(D,H.data.items),f(D)),H},y=async(F,D,T,I)=>{const M=e.remoteKeyFor(D,T),H=r.getEntry(M),W=H?.data?.nextCursor??null;if(!W||H?.isLoading)return H;try{const L=await e.fetchList(I,F,D,e.buildRemoteQuery(T,W)),ae=r.getEntry(M)?.data,J={items:pr(ae?.items??[],L.items),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt},le=await r.refresh(M,async()=>J);return le.data&&(u(D,le.data.items),f(D)),le}catch(L){return r.setError(M,L)??r.getEntry(M)}},j=F=>{for(const D of Object.keys(r.snapshot()))fo(D)===F&&r.remove(D);for(const D of[...a.keys()])fo(D)===F&&a.delete(D)},v=(F,D,T,I)=>{const M=e.detailKeyFor(D,T);return o.refresh(M,async()=>({detail:await e.fetchDetail(I,F,D,T)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:s,remote:r,details:o,comments:i},setFilters:g,resetFilters:b,select:p,ensureCollection:h,ensureCollectionsFresh:x,prefetchClosedCollection:w,loadMoreCollection:C,refreshCollections:S,searchRemote:A,loadMoreRemote:y,dropRemoteForRepo:j,refreshAllForScope:async(F,D,T)=>{await Tn(T,{directory:F,repo:D,kind:e.serverKind}),j(D),await S(F,D,"both",T).catch(()=>null);const I=t.get().selectionByDirectory[hn(F)];I?.repo===D&&typeof I.number=="number"&&await v(F,D,I.number,T).catch(()=>null)},ensureDetail:(F,D,T,I)=>{const M=e.detailKeyFor(D,T);return o.ensure(M,async()=>({detail:await e.fetchDetail(I,F,D,T)}))},refreshDetail:v,ensureComments:(F,D,T,I)=>{const M=e.commentsKeyFor(D,T);return i.ensure(M,async()=>{const H=await e.fetchComments(I,F,D,T);return{comments:H.comments,nextCursor:H.nextCursor,fetchedAt:H.fetchedAt}})},loadMoreComments:async(F,D,T,I)=>{const M=e.commentsKeyFor(D,T),H=i.getEntry(M),W=H?.data?.nextCursor??null;if(!W||H?.isLoading)return H;try{const L=await e.fetchComments(I,F,D,T,W),ae=i.getEntry(M)?.data,J={comments:yg(ae?.comments??[],L.comments),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt};return await i.refresh(M,async()=>J)}catch(L){return i.setError(M,L)??i.getEntry(M)}},refreshComments:(F,D,T,I)=>{const M=e.commentsKeyFor(D,T);return i.refresh(M,async()=>{const H=await e.fetchComments(I,F,D,T);return{comments:H.comments,nextCursor:H.nextCursor,fetchedAt:H.fetchedAt}})},markCollectionsStale:F=>{s.markStale(e.collectionKeyFor(F,e.openCollection)),s.markStale(e.collectionKeyFor(F,e.closedCollection))},getLocalIndex:m,withSingleFlight:d,resetCore:()=>{s.reset(),r.reset(),a.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:F=>wg(F,e.errorFallback)}},ii={state:"open",involvement:"all",search:"",sort:"updated"},Sg=3e4,jg=100,kg=50,Cc=(e,t)=>vs([e,"pulls-collection",t]),Ac=(e,t)=>vs([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),Tr=(e,t)=>vs([e,"pull-detail",t]),Ci=(e,t)=>vs([e,"pull-comments",t]),ai=(e,t)=>vs([e,"pull-files",t]),li=(e,t)=>vs([e,"pull-checks",t]),Cg=e=>({state:e,perPage:jg}),Ag=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:kg,...t?{cursor:t}:{}}),Mr=e=>`pichamber:pr-merge-method:${e}`,Nc=new Map,Ng=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},Ig=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},Vw=e=>{if(!e)return null;const t=Ng(Mr(e));return t==="merge"||t==="squash"||t==="rebase"?t:Nc.get(Mr(e))??null},Eg=(e,t)=>{if(e){Nc.set(Mr(e),t);try{Ig(Mr(e),t)}catch{}}},Dg={set:e=>{typeof e=="function"?Sn.setState(t=>{const s={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(s)}):Sn.setState(e)},get:()=>{const e=Sn.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Fe=vg({openCollection:"open",closedCollection:"closed",defaultFilters:ii,freshWindowMs:Sg,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Cc,remoteKeyFor:Ac,detailKeyFor:Tr,commentsKeyFor:Ci,buildCollectionQuery:e=>({...Cg(e)}),buildRemoteQuery:(e,t)=>({...Ag(e,t)}),fetchList:async(e,t,s,r)=>{const o=await e.pullsList(t,s,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,s,r)=>e.pullGet(t,s,r),fetchComments:async(e,t,s,r,o)=>{const i=await e.pullComments(t,s,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},Dg),Jt=os(),jr=os(),Sn=$n()(zr((e,t)=>({...Fe.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Fe.setFilters,resetFilters:Fe.resetFilters,selectPullRequest:Fe.select,ensureCollection:Fe.ensureCollection,ensureCollectionsFresh:Fe.ensureCollectionsFresh,prefetchClosedCollection:Fe.prefetchClosedCollection,loadMoreCollection:Fe.loadMoreCollection,refreshCollections:Fe.refreshCollections,searchRemote:Fe.searchRemote,loadMoreRemote:Fe.loadMoreRemote,dropRemoteForRepo:Fe.dropRemoteForRepo,refreshAllForScope:Fe.refreshAllForScope,ensureDetail:Fe.ensureDetail,refreshDetail:Fe.refreshDetail,ensureComments:Fe.ensureComments,loadMoreComments:Fe.loadMoreComments,refreshComments:Fe.refreshComments,ensureFiles:(s,r,o,i)=>{const a=ai(r,o);return Jt.ensure(a,async()=>i.pullFiles(s,r,o))},loadMoreFiles:async(s,r,o,i)=>{const a=ai(r,o),c=Jt.getEntry(a),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Fe.withSingleFlight(`${a}:more`,async()=>{const f=await i.pullFiles(s,r,o,d),m=Jt.getEntry(a)?.data,g=new Set((m?.files??[]).map(p=>p.filename)),b={repo:f.repo,number:f.number,files:[...m?.files??[],...f.files.filter(p=>!g.has(p.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Jt.refresh(a,async()=>b)});return u.ran?u.result??Jt.getEntry(a):Jt.getEntry(a)}catch(u){return Jt.setError(a,u)??Jt.getEntry(a)}},ensureChecks:(s,r,o,i)=>{const a=li(r,o);return jr.ensure(a,async()=>i.pullChecks(s,r,o,!0))},refreshChecks:(s,r,o,i)=>{const a=li(r,o);return jr.refresh(a,async()=>i.pullChecks(s,r,o,!0))},performAction:async(s,r,o,i,a)=>{const c=Ts(r,o),d=Tr(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(g=>({actingActions:{...g.actingActions,[c]:!0},actionErrorByDetail:{...g.actionErrorByDetail,[c]:null}}));const u=Fe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=f?{...f,state:i==="close"?"closed":i==="reopen"?"open":i==="merge"||i==="squash"||i==="rebase"?"merged":f.state,draft:i==="ready"?!1:i==="draft"?!0:f.draft}:null;m&&u&&await Fe.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullAction(s,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(s,r,"both",a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),await t().refreshChecks(s,r,o,a).catch(()=>null),e(g=>({actingActions:{...g.actingActions,[c]:!1}})),{ok:!0}}catch(g){const b=Fe.toStoreError(g);return u&&await Fe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(p=>({actingActions:{...p.actingActions,[c]:!1},actionErrorByDetail:{...p.actionErrorByDetail,[c]:b}})),{ok:!1,error:b}}},updateTitleBody:async(s,r,o,i,a)=>{const c=Ts(r,o),d=Tr(r,o),u=Fe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;m&&u&&await Fe.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullUpdate(s,r,o,i),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(s,r,"both",a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(g){const b=Fe.toStoreError(g);return u&&await Fe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[c]:b}})),{ok:!1,error:b}}},addComment:async(s,r,o,i,a)=>{const c=Ts(r,o),d=Ci(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},m=Fe.resources.comments.getEntry(d)?.data??null;if(m){const g={comments:[...m.comments,f],nextCursor:m.nextCursor,fetchedAt:m.fetchedAt};await Fe.resources.comments.refresh(d,async()=>g).catch(()=>null)}try{return await a.pullComment(s,r,o,u),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshComments(s,r,o,a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(g){const b=Fe.toStoreError(g);return m?await Fe.resources.comments.refresh(d,async()=>m).catch(()=>null):Fe.resources.comments.remove(d),e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[c]:b}})),{ok:!1,error:b}}},submitReview:async(s,r,o,i,a)=>{const c=Ts(r,o);try{return await a.pullReview(s,r,o,{event:i.event,body:i.body,comments:i.comments}),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(d){const u=Fe.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(s,r,o,i,a,c)=>{const d=Ts(r,o);try{return await c.pullThread(s,r,o,i,a),await Tn(c,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshDetail(s,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Fe.toStoreError(u);return e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[d]:f}})),{ok:!1,error:f}}},checkout:async(s,r,o,i,a)=>{try{const c=await a.pullCheckout(s,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Fe.toStoreError(c)}}},createPullRequest:async(s,r)=>{try{const o=await r.pullCreate(s);return await Tn(r,{directory:s.directory,repo:s.repo,kind:"pulls"}),t().dropRemoteForRepo(s.repo),await t().refreshCollections(s.directory,s.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Fe.toStoreError(o)}}},rerunFailedChecks:async(s,r,o,i)=>{try{return await i.checksRerun(s,r,o),{ok:!0}}catch(a){return{ok:!1,error:Fe.toStoreError(a)}}},setMergeMethod:(s,r)=>{Eg(s,r)},notifyAgentTurnComplete:s=>{const r=hn((s||"").trim());if(!r)return;const o=Zt.getState();for(const a of Object.keys(o.results)){const[,c]=a.split(`
|
|
19
|
+
`);if(c!==r)continue;const[,,d]=a.split(`
|
|
20
|
+
`);d&&ht(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-fmzQmSSv.js").then(f=>f.cJ);return{getRegisteredRuntimeAPIs:u}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:u})=>{const f=u()?.github??null;if(f)return o.refresh(r,d,f,{force:!0})}).catch(()=>{})}const i=t().selectionByDirectory[r];i?.repo&&typeof i.number=="number"&&(Fe.markCollectionsStale(i.repo),ht(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-fmzQmSSv.js").then(c=>c.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{const c=a()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Fe.resetCore(),Jt.reset(),jr.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(bs(()=>{Sn.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Yw=e=>{if(typeof window>"u")return()=>{};let t=new Set,s=!1,r=!1,o=null;return ht(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-BFgKpDYT.js").then(a=>a.ey);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const a=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!s){t=d,s=!0;return}for(const u of c){const f=`${u.type}:${u.session??""}:${u.time}`;t.has(f)||(t.add(f),u.type==="turn-complete"&&u.directory&&(Sn.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};a(),o=i.subscribe(a)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},Qw=e=>Fe.getLocalIndex(e),Jw=(e,t)=>Fe.getLocalIndex(e).find(s=>s.number===t)??null,Xw=(e,t)=>Ss(Fe.resources.collections,e?Cc(e,t):null),Zw=(e,t)=>Ss(Fe.resources.remote,e?Ac(e,t):null),ev=(e,t)=>Ss(Fe.resources.details,e!=null&&t!=null?Tr(e,t):null),tv=(e,t)=>Ss(Fe.resources.comments,e!=null&&t!=null?Ci(e,t):null),nv=(e,t)=>Ss(Jt,e!=null&&t!=null?ai(e,t):null),sv=(e,t)=>Ss(jr,e!=null&&t!=null?li(e,t):null),rv=(e,t)=>Sn(s=>!e||!t?ii:s.filtersByScope[oi(e,t)]??ii),ov=e=>Sn(t=>e?t.selectionByDirectory[hn(e)]??Ca:Ca),Ic=(e,t,s)=>{Sn.getState().selectPullRequest(e,t,s);const r=hn(e);ht(async()=>{const{useUIStore:o}=await import("./index-fmzQmSSv.js").then(i=>i.cM);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),ht(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-BFgKpDYT.js").then(i=>i.eA);return{useGitHubScopeStore:o}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useGitHubScopeStore:o})=>{o.getState().setSelectedRepo(e,t)}).catch(()=>{})},Rg=({directory:e,number:t,color:s})=>{const r=vl(e);return!e||!r?n.jsxs("span",{className:"ml-auto flex-shrink-0 typography-micro font-medium leading-none",style:s?{color:s}:void 0,children:["#",t]}):n.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Ic(e,r,t)},className:"ml-auto flex-shrink-0 rounded typography-micro font-medium leading-none hover:bg-interactive-hover",style:s?{color:s}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function Pg({group:e,groupKey:t,isCollapsed:s,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:a,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:m,statusLine:g,projectId:b,activeProjectId:p,setActiveProjectIdOnly:h,setActiveMainTab:w,mobileVariant:x,setSessionSwitcherOpen:C,openNewSessionDraft:S}){return n.jsxs("div",{className:_("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(t),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),r(t))},"aria-label":s?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!s,children:[n.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",a),...c?.listeners??{},children:n.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[n.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground",children:!e.isMain||e.worktree?n.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[n.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[n.jsx(R,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),n.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:s?n.jsx(R,{name:"arrow-right-s",className:"size-4"}):n.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),n.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:si(e.label,o)}),f,u?n.jsx(Rg,{directory:e.directory??null,number:u.number,color:d}):null]}):n.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[n.jsx("span",{className:"min-w-0 truncate",children:si(e.label,o)}),f]})}),m&&g?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.jsx(R,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),n.jsx("span",{className:"min-w-0 truncate typography-micro font-medium text-subtle-foreground",children:g.label})]}):null]})}),e.directory?n.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),b&&b!==p&&h(b),w("chat"),x&&C(!1),S({selectedProjectId:b,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:n.jsx(R,{name:"add",className:"h-4 w-4"})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"New draft session"})})]})}):null]})}const mr=(e,t)=>t?e.sessions.some(s=>dn(s,t)):!1,Tg=(e,t,s)=>e.sessions.some(r=>pc(r,r,t,s,e.directory,e.directory)),Mg=(e,t,s)=>{const r=o=>{const i=o.session.id;return t.get(i)!==s.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},Ia=(e,t,s)=>{const r=o=>t.has(o.session.id)!==s.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Fg=(e,t,s)=>{const r=o=>{const i=Zs("project",o.session);return t.has(i)!==s.has(i)?!0:o.children.some(r)};return e.sessions.some(r)},Lg=(e,t)=>{if(e.group!==t.group||e.groupKey!==t.groupKey||e.projectId!==t.projectId||e.hideGroupLabel!==t.hideGroupLabel||e.compactBodyPadding!==t.compactBodyPadding||e.groupSearchDataByGroup!==t.groupSearchDataByGroup||e.visibleSessionCount!==t.visibleSessionCount||e.collapsedGroups!==t.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==t.collapsedGroups.has(t.groupKey)||e.pinnedSessionIds!==t.pinnedSessionIds&&Tg(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Fg(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Mg(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(mr(e.group,e.editingId)||mr(t.group,t.editingId))||e.editTitle!==t.editTitle&&(mr(e.group,e.editingId)||mr(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const s=Pr(e.group.sessions,e.openSidebarMenuKey,"project"),r=Pr(t.group.sessions,t.openSidebarMenuKey,"project");if(s||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&Ia(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&Ia(t.group,e.unreadActivitySessionIds,t.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===t.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===t.normalizedSessionSearchQuery&&e.hideDirectoryControls===t.hideDirectoryControls&&e.collapsedFolderIds===t.collapsedFolderIds&&e.toggleFolderCollapse===t.toggleFolderCollapse&&e.renameFolder===t.renameFolder&&e.deleteFolder===t.deleteFolder&&e.showDeletionDialog===t.showDeletionDialog&&e.setDeleteFolderConfirm===t.setDeleteFolderConfirm&&e.renderSessionNode===t.renderSessionNode&&e.showMoreGroupSessions===t.showMoreGroupSessions&&e.resetGroupSessionLimit===t.resetGroupSessionLimit&&e.mobileVariant===t.mobileVariant&&e.alwaysShowActions===t.alwaysShowActions&&e.activeProjectId===t.activeProjectId&&e.setActiveProjectIdOnly===t.setActiveProjectIdOnly&&e.setActiveMainTab===t.setActiveMainTab&&e.setSessionSwitcherOpen===t.setSessionSwitcherOpen&&e.openNewSessionDraft===t.openNewSessionDraft&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.renamingFolderId===t.renamingFolderId&&e.renameFolderDraft===t.renameFolderDraft&&e.setRenameFolderDraft===t.setRenameFolderDraft&&e.setRenamingFolderId===t.setRenamingFolderId&&e.onToggleCollapsedGroup===t.onToggleCollapsedGroup&&e.dragHandleProps===t.dragHandleProps};function Og({group:e,sourceGroupNodes:t,hasSessionSearchQuery:s,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:a,inputActivitySessionIds:c}){const d=gt(A=>A.foldersMap),u=e.folderScopeKey??Re(e.directory??null),f=l.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),m=l.useMemo(()=>f.flatMap(({scopeKey:A,directory:y})=>(d[A]??[]).map(j=>({folder:j,scopeKey:A,scopeDirectory:y}))),[f,d]),g=l.useMemo(()=>{const A=new Map,y=j=>{j.forEach(v=>{A.set(v.session.id,v),v.children.length>0&&y(v.children)})};return y(t),A},[t]),b=l.useMemo(()=>m.map(({folder:A,scopeKey:y,scopeDirectory:j})=>{const v=og(A.sessionIds,g).sort(o);return{folder:A,scopeKey:y,scopeDirectory:j,nodes:v}}),[m,g,o]),p=l.useMemo(()=>{const A=new Map(b.map(k=>[k.folder.id,k])),y=new Map;for(const{folder:k}of b){if(!k.parentId)continue;const E=y.get(k.parentId);E?E.push(k.id):y.set(k.parentId,[k.id])}const j=new Map,v=k=>{const E=j.get(k);if(E!==void 0)return E;const P=A.get(k);if(!P)return j.set(k,!1),!1;const z=y.get(k)??[];if(!s||P.folder.name.toLowerCase().includes(r)||P.nodes.length>0)return j.set(k,!0),!0;const q=z.some(G=>v(G));return j.set(k,q),q};return b.filter(({folder:k})=>v(k.id))},[b,s,r]),h=l.useMemo(()=>new Set(p.flatMap(A=>A.folder.sessionIds)),[p]),w=l.useMemo(()=>t.filter(A=>!h.has(A.session.id)),[t,h]),x=l.useMemo(()=>p.filter(({folder:A})=>!A.parentId),[p]),C=l.useMemo(()=>{const A=new Map;return p.forEach(y=>{if(!y.folder.parentId)return;const j=A.get(y.folder.parentId)??[];j.push(y),A.set(y.folder.parentId,j)}),A},[p]),S=l.useMemo(()=>{const A=new Map(p.map(v=>[v.folder.id,v])),y=new Map,j=(v,k)=>{const E=y.get(v);if(E!==void 0)return E;if(k.has(v))return null;k.add(v);const P=A.get(v);let z=P?yc(P.nodes,i,a,c):null;for(const K of C.get(v)??[])if(z=ji(z,j(K.folder.id,k)),z==="input")break;return y.set(v,z),z};return p.forEach(({folder:v})=>j(v.id,new Set)),y},[i,p,C,c,a]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:p,rootFolders:x,ungroupedSessions:w,folderActivityStateById:S}}function Bg(e){const{group:t,groupKey:s,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:m,toggleFolderCollapse:g,renameFolder:b,deleteFolder:p,showDeletionDialog:h,setDeleteFolderConfirm:w,renderSessionNode:x,showMoreGroupSessions:C,resetGroupSessionLimit:S,mobileVariant:A,alwaysShowActions:y,activeProjectId:j,setActiveProjectIdOnly:v,setActiveMainTab:k,setSessionSwitcherOpen:E,openNewSessionDraft:P,addSessionToFolder:z,createFolderAndStartRename:K,renamingFolderId:q,renameFolderDraft:G,setRenameFolderDraft:F,setRenamingFolderId:D,pinnedSessionIds:T,sessionOrderIndex:I,editingId:M,openSidebarMenuKey:H,activeActivitySessionIds:W,unreadActivitySessionIds:L,onToggleCollapsedGroup:ae,dragHandleProps:J,compactBodyPadding:le=!1}=e,Ie=l.useCallback((Ee,Ye)=>{const Ne=I.get(Ee.session.id),De=I.get(Ye.session.id);if(Ne!==void 0||De!==void 0){if(Ne===void 0)return 1;if(De===void 0)return-1;if(Ne!==De)return Ne-De}return $u(Ee.session,Ye.session,T,Sl)},[T,I]),Y=i?c.get(t):null,B=i?!1:u.has(s),$=!t.isMain&&!o?Re(t.directory??null):null,X=!t.isMain&&!o&&t.branch?.trim()||null,ee=l.useMemo(()=>$&&X?er($,X):null,[$,X]),ie=gc(ee);bc($,X);const Ce=ie?`var(--pr-${ie.visualState})`:void 0,pe=l.useContext(Kr)!==null,je=f?10:5,be=Math.max(je,d??je),ze=i?Y?.groupMatches===!0:!1,me=i,Pe=l.useMemo(()=>[...me?Y?.filteredNodes??[]:t.sessions].sort(Ie),[Ie,t.sessions,Y?.filteredNodes,me]),V=Ku(),fe=l.useMemo(()=>new Set(V.map(Ee=>Ee.sessionId)),[V]),{folderScopeKey:xe,folderScopes:te,allFoldersForGroup:re,rootFolders:Be,ungroupedSessions:ke,folderActivityStateById:Q}=Og({group:t,sourceGroupNodes:Pe,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,compareSessionNodes:Ie,activeActivitySessionIds:W,unreadActivitySessionIds:L,inputActivitySessionIds:fe}),ve="project",he=l.useMemo(()=>{const Ee=new Set;return xa(Pe,M,Ee),re.forEach(({nodes:Ye})=>{xa(Ye,M,Ee)}),Ee},[Pe,re,M]),Se=l.useMemo(()=>{if(!H)return null;const Ee=Pr(Pe,H,ve);if(Ee)return Ee;for(const{nodes:Ye}of re){const Ne=Pr(Ye,H,ve);if(Ne)return Ne}return null},[H,Pe,re]),qe=l.useCallback(Ee=>{const Ye=new WeakMap,Ne=De=>{Ye.set(De,ei(De));for(const Ge of De.children)Ne(Ge)};return Ee.forEach(Ne),Ye},[]),Ue=l.useMemo(()=>qe(Pe),[qe,Pe]),U=l.useMemo(()=>{const Ee=new WeakMap;return re.forEach(({nodes:Ye})=>{Ye.forEach(Ne=>Ee.set(Ne,ei(Ne)))}),Ee},[re]),ge=l.useCallback(Ee=>Ue.get(Ee)??U.get(Ee)??"",[Ue,U]),se=l.useCallback(Ee=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ee)}),[he,Se,ge]),_e=ke.length,st=pe||i?ke:ke.slice(0,be),pt=_e-st.length,Xe=!pe&&!i&&_e>je&&pt===0;if(i&&!ze&&Be.length===0&&ke.length===0)return null;const Yt=!t.isMain&&!!t.branch,mt=t.branch&&ph(t.branch,t.label)?{label:t.branch,color:null}:null,Nt=B?yc(Pe,W,L,fe):null,nn=Nt?n.jsx(fc,{state:Nt,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,Qe=(Ee,Ye)=>{const{folder:Ne,scopeKey:De,scopeDirectory:Ge,nodes:ut}=Ee,sn=i?!1:m.has(Ne.id);return n.jsx(ng,{folderId:Ne.id,children:(Lt,Ot)=>n.jsx(eg,{folder:Ne,displayName:Ye,sessions:ut,isCollapsed:sn,collapsedActivityState:sn?Q.get(Ne.id)??null:null,onToggle:()=>g(Ne.id),onRename:Ve=>{b(De,Ne.id,Ve)},onDelete:()=>{if(!h){p(De,Ne.id);return}const Ve=re.filter(({folder:An})=>An.parentId===Ne.id).length,rn=ut.length;w({scopeKey:De,folderId:Ne.id,folderName:Ne.name,subFolderCount:Ve,sessionCount:rn})},renderSessionNode:x,getRenderExtras:ge?Ve=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ve),childRenderExtrasFor:se}):void 0,groupDirectory:Ge??t.directory,projectId:r,mobileVariant:A,alwaysShowActions:y,isRenaming:q===Ne.id,renameDraft:q===Ne.id?G:void 0,onRenameDraftChange:Ve=>F(Ve),onRenameSave:()=>{const Ve=G.trim();Ve&&b(De,Ne.id,Ve),D(null),F("")},onRenameCancel:()=>{D(null),F("")},droppableRef:Lt,isDropTarget:Ot,depth:0,onNewSession:()=>{r&&r!==j&&v(r),k("chat"),A&&E(!1),P({selectedProjectId:r,directoryOverride:Ge??t.directory,targetFolderId:Ne.id})},hideActions:!1})},Ne.id)},Mt=()=>{const Ee=new Map;for(const De of re){const Ge=De.folder.parentId;if(!Ge)continue;const ut=Ee.get(Ge);ut?ut.push(De):Ee.set(Ge,[De])}const Ye=[],Ne=(De,Ge)=>{const ut=Ge?`${Ge} / ${De.folder.name}`:De.folder.name;Ye.push(Qe(De,ut)),!(!i&&m.has(De.folder.id))&&(Ee.get(De.folder.id)??[]).forEach(Lt=>Ne(Lt,ut))};return Be.forEach(De=>Ne(De,"")),Ye},Ft=y?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",jt=n.jsxs(sg,{scopeKey:te[0]?.scopeKey??xe,hasFolders:re.length>0,onSessionDroppedOnFolder:(Ee,Ye)=>{const Ne=re.find(({folder:Ge})=>Ge.id===Ye);if(!Ne)return;const De=gt.getState();for(const{scopeKey:Ge}of te)Ge!==Ne.scopeKey&&De.getSessionFolderId(Ge,Ee)&&De.removeSessionFromFolder(Ge,Ee);z(Ne.scopeKey,Ye,Ee)},children:[Mt(),st.map(Ee=>n.jsx(l.Fragment,{children:x(Ee,0,t.directory,r,!1,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ee),childRenderExtrasFor:se})},Ee.session.id)),_e===0&&re.length===0&&!pe?n.jsx(Ht,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,pt>0?n.jsx(Ht,{icon:"arrow-down-s",onClick:()=>C(s,st.length),children:pt===1?"Show 1 more session":`Show ${pt} more sessions`}):null,Xe?n.jsx(Ht,{icon:"arrow-up-s",onClick:()=>S(s),children:"Show fewer sessions"}):null]});return o?n.jsx("div",{className:"oc-group",children:n.jsx("div",{className:"oc-group-body",children:jt})}):n.jsxs("div",{className:"oc-group",children:[n.jsx(Pg,{group:t,groupKey:s,isCollapsed:B,onToggleCollapsedGroup:ae,normalizedSessionSearchQuery:a,alwaysShowActions:y,groupHeaderRightPadding:Ft,dragHandleProps:J,groupPrColor:Ce,groupPrSummary:ie,groupActivityIndicator:nn,showBranchSubtitle:Yt,statusLine:mt,projectId:r,activeProjectId:j,setActiveProjectIdOnly:v,setActiveMainTab:k,mobileVariant:A,setSessionSwitcherOpen:E,openNewSessionDraft:P}),B?null:n.jsx("div",{className:"oc-group-body",children:jt})]})}const _g=l.memo(Bg,Lg);function zg(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:s,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:a,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:m,sessionSearchInputRef:g,sessionSearchQuery:b,setSessionSearchQuery:p,hasSessionSearchQuery:h,searchMatchCount:w,selectionModeEnabled:x,onToggleSelectionMode:C,mobileVariant:S=!1,onClose:A}=e;if(t)return null;const y=_(u,"text-muted-foreground hover:text-foreground",!S&&"hover:bg-transparent"),j=o?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,className:y,"aria-label":"Settings",children:n.jsx(R,{name:"settings-3",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Settings"})})]}):null,v=c?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:c,className:y,"aria-label":"Update",children:n.jsx(R,{name:"download",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Update"})})]}):null;return n.jsx("div",{className:_("select-none flex-shrink-0",S?"px-2":"px-2 py-1"),children:n.jsxs("div",{className:_("flex flex-col",S?"gap-0":"h-auto min-h-8 gap-1"),children:[n.jsxs("div",{className:_("flex items-center justify-between",S?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[n.jsxs("div",{className:_("flex min-w-0 items-center",S?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":S?"true":void 0,children:[S?n.jsx("h2",{className:"truncate pl-2 typography-ui-header font-semibold text-foreground",children:"Sessions"}):n.jsxs(n.Fragment,{children:[j,v]}),!S&&i?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:i,className:y,"aria-label":a?`Servers: ${a}`:"Servers",children:n.jsx(R,{name:"server",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:a||"Servers"})})]}):null,S?null:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:y,"aria-label":"Add folder",children:n.jsx(R,{name:"folder-add",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Add folder"})})]}),S?null:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:r,className:y,"aria-label":"Archive",children:n.jsx(R,{name:"archive",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Archive"})})]})]}),n.jsxs("div",{className:_("flex shrink-0 items-center",S?"gap-1":"gap-1.5"),children:[S?n.jsxs(n.Fragment,{children:[j,v]}):null,n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>m(k=>!k),className:y,"aria-label":"Search sessions","aria-expanded":f,children:n.jsx(R,{name:"search",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Search sessions"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:C,className:_(y,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:n.jsx(R,{name:"checkbox-multiple",className:d})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:x?"Exit selection":"Select sessions"})})]}),S&&A?n.jsx("button",{type:"button",onClick:A,className:y,"aria-label":"Close sessions",children:n.jsx(R,{name:"close",className:d})}):null]})]}),f?n.jsxs("div",{className:_(S?"pb-2":"pb-1"),children:[n.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-subtle-foreground",children:h?n.jsx("span",{children:w===1?`${w} match`:`${w} matches`}):n.jsx("span",{})}),n.jsxs("div",{className:"relative",children:[n.jsx(R,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),n.jsx("input",{ref:g,value:b,onChange:k=>p(k.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:k=>{k.key==="Escape"&&(k.stopPropagation(),h?p(""):m(!1))}}),b.length>0?n.jsx("button",{type:"button",onClick:()=>p(""),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:n.jsx(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const ho="0.75rem";function Ug(e){const t=ue(o=>o.toggleSidebar),s=ue(o=>o.shortcutOverrides),r=wi(Nr("toggle_sidebar",s));return n.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${ho})`}}),n.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, ${ho})))`}}),n.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsxs("button",{type:"button",onClick:e.onNewSession,className:_("group flex min-w-0 flex-1 items-center gap-1.5 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"),style:{paddingLeft:`max(3px, calc(${mh} - max(var(--oc-titlebar-left-inset, ${ho}), var(--oc-titlebar-overlay-width, 0px))))`},children:[n.jsx(R,{name:"chat-new",className:_(wr,"text-current")}),n.jsx("span",{className:_l,children:"New session"})]}),e.showSidebarToggle?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,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:n.jsx(R,{name:"layout-left",className:"size-4"})})}),n.jsx(He,{children:n.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Hr({...e}){return n.jsx(ll,{...e})}function Gr({...e}){return n.jsx(cl,{...e})}function qr({className:e,positionerClassName:t,children:s,style:r,...o}){return n.jsx(Eo,{children:n.jsx(Do,{className:_("app-region-no-drag z-50",t),children:n.jsx(Ro,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Lo,e),...o,children:s})})})}function On({className:e,...t}){return n.jsx(dl,{className:_(jl,e),...t})}function Ec({className:e,...t}){return n.jsx(ul,{className:_(kl,e),...t})}const Dc=500,$g=({projectId:e,worktree:t,isSelected:s,hasActive:r,onSelect:o,onClose:i,mobileVariant:a=!1})=>{const[c,d]=l.useState(!1),u=l.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),m=l.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);l.useEffect(()=>()=>m(),[m]);const g=l.useCallback(()=>{m(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},Dc)},[m]);return n.jsxs(Hr,{open:c,onOpenChange:d,children:[n.jsxs(Gr,{render:n.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:g,onTouchMove:m,onTouchEnd:m,onTouchCancel:m,style:{touchAction:"manipulation"},className:_(Fr(a,s),"pl-6"),"aria-pressed":s,title:t.path}),children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsx(R,{name:"git-branch",className:_(_n(a),"text-muted-foreground")}),t.branch?n.jsx(_s,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):n.jsx("span",{className:ps(a),children:f})]}),n.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),n.jsx(qr,{className:"min-w-[160px]",children:n.jsxs(On,{disabled:!i,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>i?.(e,t),className:"text-destructive focus:text-destructive",children:[n.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Close worktree"})]})})]})},Fr=(e,t)=>_("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",t?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),Kg=({project:e,label:t,isSelected:s,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:a,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:m=!1})=>{const{listeners:g,setNodeRef:b,transform:p,transition:h,isDragging:w}=gi({id:e.id,disabled:!c}),[x,C]=l.useState(!1),S=l.useRef(null),A=l.useCallback(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]);l.useEffect(()=>()=>A(),[A]);const y=l.useCallback(()=>{A(),S.current=window.setTimeout(()=>{S.current=null,C(!0)},Dc)},[A]);return n.jsx("div",{ref:b,style:{transform:bi.Translate.toString(p),transition:h},className:_(w&&"opacity-60"),children:n.jsxs(Hr,{open:x,onOpenChange:C,children:[n.jsxs(Gr,{render:n.jsx("button",{type:"button",onClick:()=>{x||d()},onTouchStart:y,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Fr(m,s),"aria-pressed":s}),children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsx("span",{className:_("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${t}`:void 0,...c?g:{},children:n.jsx(yi,{directory:e.normalizedPath,label:t,className:_n(m)})}),n.jsx("span",{className:ps(m),children:t})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?n.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:n.jsx(R,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?n.jsx(R,{name:a?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),n.jsxs(qr,{className:"min-w-[160px]",children:[n.jsxs(On,{onClick:()=>u(e.id),children:[n.jsx(R,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Edit folder"})]}),n.jsx(Ec,{}),n.jsxs(On,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[n.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Close folder"})]})]})]})})},Wg=({projects:e,selectedProjectId:t,selectedWorktreePath:s=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:a,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:m,activeDirectoriesByProject:g,homeDirectory:b,className:p,mobileVariant:h=!1})=>{const w=t===null,x=ct(y=>y.reorderProjects),C=e.length>1,S=Br(ds(ml,{activationConstraint:{distance:8}}),ds(pl,{activationConstraint:{delay:200,tolerance:6}})),A=l.useCallback(y=>{const{active:j,over:v}=y;if(!v||j.id===v.id)return;const k=ct.getState().projects,E=k.findIndex(z=>z.id===j.id),P=k.findIndex(z=>z.id===v.id);E<0||P<0||x(E,P)},[x]);return n.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",p),children:[n.jsx("button",{type:"button",onClick:()=>i(null),className:Fr(h,w),"aria-pressed":w,children:n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx(R,{name:"chat-history",className:_n(h)}),n.jsx("span",{className:ps(h),children:"All sessions"})]})}),n.jsx(_r,{sensors:S,collisionDetection:mi,onDragEnd:A,children:n.jsx(fl,{items:e.map(y=>y.id),strategy:hl,children:e.map(y=>{const j=t===y.id,v=j&&!s,k=r.get(y.normalizedPath)??[],E=xs(y,b),P=g?.get(y.id),z=Re(y.normalizedPath)?.toLowerCase()??"",K=z?P?.has(z)??!1:!1,q=(P?.size??0)>0,G=m?.(y.id)??!1,F=g?j?K:q:G;return n.jsxs(l.Fragment,{children:[n.jsx(Kg,{project:y,label:E,isSelected:v,hasActive:F,hasWorktrees:k.length>0,worktreeError:o.get(y.normalizedPath),isExpanded:j,canDrag:C,onSelect:()=>i(y.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),j?k.map(D=>{const T=s===D.path,I=Re(D.path)?.toLowerCase()??"",M=I?P?.has(I)??!1:!1,H=g?M:!1;return n.jsx($g,{projectId:y.id,worktree:D,isSelected:T,hasActive:H,onSelect:()=>a?.(y.id,D.path),onClose:c,mobileVariant:h},D.path)}):null]},y.id)})})}),n.jsxs("button",{type:"button",onClick:d,className:Fr(h,!1),children:[n.jsx(R,{name:"add",className:_n(h)}),n.jsx("span",{className:ps(h),children:"Add folder"})]})]})},po="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 Hg({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:s,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:n.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?n.jsxs(n.Fragment,{children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:e,className:po,"aria-label":"Settings",children:n.jsx(R,{name:"settings-3",className:"size-4"})})}),n.jsx(He,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Settings"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,className:po,"aria-label":"Shortcuts",children:n.jsx(R,{name:"command",className:"size-4"})})}),n.jsx(He,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Shortcuts"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:po,"aria-label":"About PiChamber",children:n.jsx(R,{name:"information",className:"size-4"})})}),n.jsx(He,{side:"top",sideOffset:4,children:n.jsx("p",{children:"About PiChamber"})})]})]}):null,i?n.jsx(Ae,{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 Ea="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-[opacity,background-color,color] hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Da="opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto",Rc=({projectLabel:e,projectPath:t=null,mobileVariant:s=!1})=>{const r=_n(s),o=ps(s);return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?n.jsx(yi,{directory:t,label:e,className:r}):n.jsx(R,{name:"folder",className:_(r,"text-subtle-foreground")})}),n.jsx("span",{className:_(o,"font-medium text-foreground"),children:e})]})},Pc=({isCollapsed:e,mobileVariant:t=!1,className:s})=>n.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",s),children:n.jsx(R,{name:e?"arrow-right-s":"arrow-down-s",className:_n(t)})}),Gg=({id:e,disabled:t=!1,projectLabel:s,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:a,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:m,onRenameStart:g,onClose:b,children:p,showCreateButtons:h=!0,hideHeader:w=!1,openSidebarMenuKey:x,setOpenSidebarMenuKey:C,statusIndicator:S=null,sessionCount:A=null,isEmpty:y=!1})=>{const{listeners:j,setNodeRef:v,transform:k,transition:E,isDragging:P}=gi({id:e,disabled:t}),z=l.useRef(!1),K=`project:${e}`,q=x===K,[G,F]=l.useState(!1),D=u&&!i,T=!a&&!d,I=l.useCallback(le=>{le&&F(!1),C(le?K:null)},[K,C]),M=le=>n.jsxs(n.Fragment,{children:[h&&!a&&m&&n.jsxs(le,{onClick:m,children:[n.jsx(R,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),n.jsxs(le,{onClick:g,children:[n.jsx(R,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),n.jsxs(le,{onClick:b,className:"text-destructive focus:text-destructive",children:[n.jsx(R,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),H=l.useCallback(le=>{le.stopPropagation()},[]),W=l.useCallback(le=>{le.stopPropagation()},[]),L=l.useCallback(le=>{le.stopPropagation()},[]),ae=l.useCallback(le=>{(le.button===2||le.button===0&&le.ctrlKey)&&(z.current=!0)},[]),J=l.useCallback(le=>{if(le.currentTarget.blur(),z.current){z.current=!1;return}f()},[f]);return n.jsxs("div",{ref:v,style:{transform:bi.Translate.toString(k),transition:E},className:_("relative",P&&"opacity-60"),children:[w?null:n.jsxs(Hr,{open:G,onOpenChange:F,children:[n.jsxs(Gr,{render:n.jsx("div",{className:_("text-left group/project select-none",D&&"oc-sidebar-sticky-header sticky top-0 z-20 bg-sidebar before:pointer-events-none before:absolute before:inset-x-0 before:bottom-full before:h-2 before:bg-sidebar"),"data-sidebar-sticky-header":D?"true":void 0,onContextMenu:le=>{a||P||(le.preventDefault(),F(!0))}}),children:[n.jsxs("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:ae,onClick:J,...j,className:_(Wr,"flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing"),children:[n.jsx(Rc,{id:e,projectLabel:s,projectPath:r,mobileVariant:c}),A?n.jsx("span",{className:"shrink-0 typography-micro text-subtle-foreground tabular-nums","aria-label":A===1?"1 session":`${A} sessions`,children:A}):null,S?n.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:S}):null,n.jsx(Pc,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",y&&"invisible",T&&"group-hover/project:pl-14 group-focus-within/project:pl-14","pl-2")})]})}),d?null:n.jsx(He,{side:"right",sideOffset:8,children:o})]}),T?n.jsxs("div",{className:_("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5",y?"right-2":"right-7"),children:[h&&m?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),m()},className:_(Ea,Da),"aria-label":"New session",children:n.jsx(R,{name:"add",className:"size-4"})})}),n.jsx(He,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"New session"})})]}):null,n.jsxs(Gt,{open:q,onOpenChange:I,children:[n.jsx(qt,{asChild:!0,children:n.jsx("button",{type:"button",className:_(Ea,q?"opacity-100 pointer-events-auto bg-interactive-active text-foreground":Da),"aria-label":"Folder menu",onPointerDown:W,onMouseDown:L,onClick:H,children:n.jsx(R,{name:"more-fill",className:"size-4"})})}),n.jsx(Vt,{align:"end",className:"min-w-[180px]",children:M(dt)})]})]}):null]}),D?n.jsx("span",{"aria-hidden":!0,className:"oc-sidebar-sticky-header-fade pointer-events-none absolute inset-x-0 top-full h-4 bg-gradient-to-b from-sidebar to-transparent"}):null]}),n.jsx(qr,{className:"min-w-[180px]",children:M(On)})]}),p]})},qg=({id:e,disabled:t=!1,children:s})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:d}=gi({id:e,disabled:t}),u=l.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return n.jsx("div",{ref:o,style:{transform:bi.Transform.toString(a),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof s=="function"?s(u):s})};l.memo(qg);const Vg=e=>e.session.time?.updated||e.session.time?.created||0,Yg=(e,t)=>{const s={pinned:[],active:[],working:[],snoozed:[]},r=new Map,o=new Set;for(const a of e){const c=a.node.session.id,d=t.entries[c],u={entry:d,pinned:a.isPinned,working:t.working.has(c),needsInput:t.needsInput.has(c),updatedAt:Vg(a.node),now:t.now,workingShelf:t.workingShelf},f=Wu(u);r.set(c,f),f!=="snoozed"&&Hu(d,t.now)&&o.add(c);const m=f==="snoozed"?-(d?.snoozedUntil??0):Gu(u);s[f].push({item:a,key:m})}const i=a=>s[a].sort((c,d)=>d.key-c.key).map(({item:c})=>c);return{pinned:i("pinned"),active:i("active"),working:i("working"),snoozed:i("snoozed"),sectionById:r,wokeIds:o}},Qg=(e,t)=>{const s=(r,o)=>r.length===o.length&&r.every((i,a)=>i===o[a]);if(e.wokeIds.size!==t.wokeIds.size)return!1;for(const r of e.wokeIds)if(!t.wokeIds.has(r))return!1;return s(e.pinned,t.pinned)&&s(e.active,t.active)&&s(e.working,t.working)&&s(e.snoozed,t.snoozed)},Jg=6e4,Xg=1500,Zg=(e,t)=>{const[s,r]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!e||typeof document>"u")return;let o=null;const i=()=>{r(Date.now()),o===null&&(o=window.setInterval(()=>r(Date.now()),Jg))},a=()=>{o!==null&&window.clearInterval(o),o=null},c=()=>document.visibilityState==="visible"?i():a();return c(),document.addEventListener("visibilitychange",c),()=>{a(),document.removeEventListener("visibilitychange",c)}},[e]),l.useEffect(()=>{if(!e||t===null)return;const o=Math.min(Math.max(0,t-Date.now())+50,2**31-1),i=window.setTimeout(()=>r(Date.now()),o);return()=>window.clearTimeout(i)},[e,t]),s},eb=(e,t)=>{const s=Qs(o=>o.load);l.useEffect(()=>{if(!e)return;s();const o=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",o);const i=bs(()=>{s()});return()=>{document.removeEventListener("visibilitychange",o),i()}},[e,s]);const r=l.useRef(t);l.useEffect(()=>{const o=r.current;if(r.current=t,!e)return;let i=!1;for(const c of t)if(!o.has(c)){i=!0;break}if(!i)return;const a=window.setTimeout(()=>{s()},Xg);return()=>window.clearTimeout(a)},[e,t,s])},tb=(e,{enabled:t,workingShelf:s})=>{const r=Qs(g=>t?g.entries:nb),{working:o,needsInput:i}=qu(t),a=l.useMemo(()=>Vu(r,Date.now()),[r]),c=Zg(t,a);eb(t,o);const d=l.useRef(null),u=l.useMemo(()=>{if(!t)return null;const g=Yg(e,{entries:r,working:o,needsInput:i,now:c,workingShelf:s});return d.current&&Qg(d.current,g)&&d.current.sectionById.size===g.sectionById.size&&[...g.sectionById].every(([p,h])=>d.current.sectionById.get(p)===h)?d.current:g},[t,e,r,o,i,c,s]);d.current=u;const f=Me(g=>g.currentSessionId),m=!!(t&&f&&u?.wokeIds.has(f));return l.useEffect(()=>{!m||!f||Qs.getState().update(f,{snoozedUntil:null}).catch(g=>console.warn("[session-shelf] could not clear a finished snooze",g))},[m,f]),u},nb=Object.freeze({}),ci=(e,t,s,r)=>{Qs.getState().update(e,t,s??void 0).catch(o=>{console.warn("[session-shelf] update failed",o),oe.error(r)})},Ra={snoozed:"Snoozed",archived:"Archived"},sb=e=>e==="snoozed"||e==="archived",Pa=10,Ta=20,Tc="oc.sidebar.shelves.expanded",rb=()=>{try{const e=rs().getItem(Tc),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(sb)):new Set}catch{return new Set}},ob=()=>{const[e,t]=l.useState(rb),s=l.useCallback(r=>{t(o=>{const i=new Set(o);i.has(r)?i.delete(r):i.add(r);try{rs().setItem(Tc,JSON.stringify([...i]))}catch{}return i})},[]);return{expanded:e,toggle:s}},Ma=({target:e,dragging:t,className:s,children:r})=>{const{setNodeRef:o,isOver:i}=al({id:`shelf-drop:${e}`,data:{type:"shelf",target:e}});return n.jsx("div",{ref:o,"data-shelf-drop":e,className:_("rounded-xl transition-colors",t&&"outline outline-1 -outline-offset-1 outline-transparent",t&&i&&"bg-interactive-hover outline-[var(--interactive-border)]",s),children:r})},ib=["snoozed","archived"],Ai=({shelfIds:e,shelves:t,renderItem:s,hasSessionSearchQuery:r,mobileVariant:o=!1,className:i})=>{const{expanded:a,toggle:c}=ob(),d=Me(p=>p.currentSessionId),[u,f]=l.useState(Pa),m=p=>r||a.has(p),g=e.filter(p=>(t[p]?.length??0)>0);if(g.length===0)return null;const b=(p,h)=>{if(p!=="archived"||r||h.length<=u)return h;const w=h.slice(0,u),x=h.find(C=>C.node.session.id===d);return x&&!w.includes(x)?[...w,x]:w};return n.jsx("div",{className:i,children:g.map(p=>{const h=t[p]??[],w=m(p),x=w?b(p,h):[],C=p==="archived"&&w&&!r?h.length-Math.min(u,h.length):0;return n.jsxs("section",{"aria-label":Ra[p],"data-session-shelf":p,children:[n.jsx(ls,{label:Ra[p],count:h.length,expanded:w,onToggle:()=>{p==="archived"&&f(Pa),c(p)}}),x.map(s),C>0?n.jsx(Ht,{icon:"arrow-down-s",mobileVariant:o,onClick:()=>f(S=>S+Ta),children:`Show ${Math.min(Ta,C)} more`}):null]},p)})})},ab=({items:e,shelves:t,archived:s,renderSessionNode:r,hasSessionSearchQuery:o,mobileVariant:i,emptyState:a,searchEmptyState:c})=>{const[d,u]=l.useState(null),f=Br(ds(ol,{activationConstraint:{distance:8}})),m=l.useMemo(()=>({sectionById:t.sectionById,wokeIds:t.wokeIds}),[t.sectionById,t.wokeIds]),g=A=>n.jsx(l.Fragment,{children:r(A.node,0,A.node.session.directory??A.project.normalizedPath,A.project.id,!1,{projectLabel:A.projectLabel,showFolderLabel:!0,globalSession:A.globalSession},"project")},A.node.session.id),b=A=>{const y=A.active.data.current;if(y?.type!=="session"||!y.sessionId)return;const j=A.active.rect.current.initial?.width;u({sessionId:y.sessionId,title:y.sessionTitle??"Session",width:typeof j=="number"?j:null})},p=A=>{u(null);const y=A.active.data.current,j=A.over?.data.current;if(y?.type!=="session"||!y.sessionId||j?.type!=="shelf"||!j.target)return;const v=y.sessionId,k=y.sessionDirectory??null,E=t.sectionById.get(v);E&&lb(v,k,E,j.target)};if(e.length===0&&s.length===0)return n.jsx(n.Fragment,{children:o?c:a});const h=!!d,w=t.pinned.length>0||h,x=t.working.length>0,C=w||x||t.snoozed.length>0||s.length>0,S=n.jsxs("div",{className:"flex min-h-full flex-1 flex-col","data-sidebar-threads":"",children:[w?n.jsxs(Ma,{target:"pinned",dragging:h,children:[n.jsx(ls,{label:"Pinned",first:!0}),t.pinned.map(g),h&&t.pinned.length===0?n.jsx("div",{className:"px-3 py-2 typography-micro text-subtle-foreground",children:"Drop here to pin"}):null]}):null,x?n.jsxs("section",{"aria-label":"Working","data-session-shelf":"working",children:[n.jsx(ls,{label:"Working",first:!w}),t.working.map(g)]}):null,n.jsxs(Ma,{target:"active",dragging:h,children:[C?n.jsx(ls,{label:"Recent",first:!w&&!x}):null,t.active.map(g),t.active.length===0&&!o?n.jsx("div",{className:"px-3 py-1.5 typography-micro text-subtle-foreground",children:h?"Drop here to keep it in the list":t.snoozed.length>0?"Nothing recent. Snoozed sessions are below.":s.length>0?"Nothing recent. Archived sessions are below.":"Nothing recent."}):null]}),n.jsx(Ai,{shelfIds:ib,shelves:{snoozed:t.snoozed,archived:s},renderItem:g,hasSessionSearchQuery:o,mobileVariant:i,className:"mt-auto border-t border-border pt-1"})]});return n.jsx(Kr.Provider,{value:m,children:i?S:n.jsxs(_r,{sensors:f,collisionDetection:uu,onDragStart:b,onDragCancel:()=>u(null),onDragEnd:p,children:[S,n.jsx(il,{children:d?n.jsx("div",{style:{width:d.width?`${d.width}px`:"auto"},className:"pointer-events-none flex items-center rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2",children:n.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:d.title})}):null})]})})},lb=(e,t,s,r)=>{const o=Vs.getState(),i=tr(o.ids,t,e),a=c=>{!t||i===c||o.toggle({directory:t,sessionId:e})};s==="snoozed"&&ci(e,{snoozedUntil:null},t,"Could not wake the session"),a(r==="pinned")},cb=l.memo(ab),db=[],ub=["snoozed","archived"],Fa=(e,t)=>{let s=!1;const r=e.groups.map(o=>{const i=o.sessions.filter(a=>!t.has(a.session.id));return i.length===o.sessions.length?o:(s=!0,{...o,sessions:i})});return s?{...e,groups:r}:e},La=e=>e.groups.reduce((t,s)=>t+s.sessions.length,0),Oa="pt-0.5 pb-1",fb=({shelves:e=null,archived:t=db,sections:s,homeSection:r,homeDirectory:o,collapsedProjects:i,toggleProject:a,hasSessionSearchQuery:c,activeProjectId:d,hideDirectoryControls:u,mobileVariant:f,alwaysShowActions:m,isInlineEditing:g,stickyFolderHeaders:b,renderGroupSessions:p,renderSessionNode:h,getOrderedGroups:w,renderProjectStatusIndicator:x,setActiveProjectIdOnly:C,setActiveMainTab:S,setSessionSwitcherOpen:A,openNewSessionDraft:y,openProjectEditDialog:j,removeProject:v,reorderProjects:k,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,onOpenDirectoryDialog:z,emptyState:K,searchEmptyState:q})=>{const G=c?null:e,F=l.useMemo(()=>{if(!G)return null;const $=new Set;for(const X of[...G.pinned,...G.snoozed])$.add(X.node.session.id);return $},[G]),D=l.useMemo(()=>F?s.map($=>Fa($,F)):s,[s,F]),T=l.useMemo(()=>F&&r?Fa(r,F):r,[r,F]),I=l.useMemo(()=>e?{sectionById:e.sectionById,wokeIds:e.wokeIds}:null,[e]),M=$=>n.jsx(l.Fragment,{children:h?.($.node,0,$.node.session.directory??$.project.normalizedPath,$.project.id,!1,{projectLabel:$.projectLabel,showFolderLabel:!0,globalSession:$.globalSession},"project")},$.node.session.id),H=Br(ds(ml,{activationConstraint:{distance:8}}),ds(pl,{activationConstraint:{delay:200,tolerance:6}})),W=D.length>1&&!c&&!g,L=l.useCallback($=>{if(g||c)return;const{active:X,over:ee}=$;if(!ee||X.id===ee.id)return;const ie=ct.getState().projects,Ce=ie.findIndex(je=>je.id===X.id),pe=ie.findIndex(je=>je.id===ee.id);Ce<0||pe<0||Ce===pe||k(Ce,pe)},[g,c,k]),[ae,J]=l.useState(5);l.useEffect(()=>{J(5)},[c]);const le=l.useMemo(()=>T?T.groups.flatMap($=>$.sessions):[],[T]),Ie=c||G?le:le.slice(0,ae),Y=le.length-Ie.length,B=c?!1:i.has("__home__");return D.length===0&&!T&&!(G&&t.length>0)?c?q:K:n.jsx(Kr.Provider,{value:I,children:n.jsxs("div",{className:G?"flex min-h-full flex-1 flex-col gap-1":"space-y-1",children:[G&&G.pinned.length>0?n.jsx(Xs.Provider,{value:"card",children:n.jsxs("section",{"aria-label":"Pinned","data-session-shelf":"pinned",children:[n.jsx(ls,{label:"Pinned",first:!0}),G.pinned.map(M)]})}):null,n.jsx(_r,{sensors:H,collisionDetection:mi,onDragEnd:L,children:n.jsx(fl,{items:D.map($=>$.project.id),strategy:hl,children:D.map($=>{const X=$.project,ee=X.id,ie=xs(X,o),Ce=_o(X.normalizedPath,o),pe=c?!1:i.has(ee),je=pe?[]:w(ee,$.groups),be=pe?null:je.find(me=>me.isMain)??null,ze=pe?[]:be?je.filter(me=>me.id!==be.id):je;return n.jsx(Gg,{id:ee,disabled:!W,projectLabel:ie,projectPath:X.normalizedPath,projectDescription:Ce,isCollapsed:pe,hideDirectoryControls:u,mobileVariant:f,alwaysShowActions:m,stickyHeader:b,statusIndicator:pe?x?.(ee,$.groups):null,sessionCount:pe?La($):null,isEmpty:!!G&&La($)===0,onToggle:()=>a(ee),onNewSession:()=>{ee!==d&&C(ee),S("chat"),f&&A(!1),y({selectedProjectId:ee,directoryOverride:X.normalizedPath})},onRenameStart:()=>j(ee),onClose:()=>v(ee),openSidebarMenuKey:E,setOpenSidebarMenuKey:P,children:pe?null:n.jsxs("div",{className:Oa,children:[be?p(be,`${ee}:${be.id}`,ee,!0,null):null,ze.map(me=>{const Pe=`${ee}:${me.id}`,V=je.length===1;return n.jsx(l.Fragment,{children:p(me,Pe,ee,V,null)},me.id)})]})},ee)})})}),T?n.jsxs("div",{children:[n.jsx("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:n.jsxs("button",{type:"button","aria-expanded":!B,style:{touchAction:"manipulation"},onClick:()=>a("__home__"),className:`${Wr} flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md`,children:[n.jsx(Rc,{id:"__home__",projectLabel:"No folder",mobileVariant:f}),n.jsx(Pc,{isCollapsed:B,mobileVariant:f})]})}),B?null:n.jsxs("div",{className:Oa,children:[Ie.map($=>n.jsx(l.Fragment,{children:h?.($,0,$.session.directory??"~","__home__",!1,{globalSession:!0},"project")},$.session.id)),!c&&Y>0?n.jsx(Ht,{icon:"arrow-down-s",mobileVariant:f,onClick:()=>J($=>$+7),children:Y===1?"Show 1 more session":`Show ${Y} more sessions`}):null,!c&&ae>5&&le.length>5?n.jsx(Ht,{icon:"arrow-up-s",mobileVariant:f,onClick:()=>J(5),children:"Show fewer sessions"}):null]})]}):null,!u&&z?n.jsx(Ht,{icon:"add",mobileVariant:f,onClick:z,children:"Add folder"}):null,G?n.jsx(Xs.Provider,{value:"card",children:n.jsx(Ai,{shelfIds:ub,shelves:{snoozed:G.snoozed,archived:t},renderItem:M,hasSessionSearchQuery:c,mobileVariant:f,className:"mt-auto border-t border-border pt-1"})}):null]})})},hb=l.memo(fb),pb=[],mb=["archived"];function gb(e){Wt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",s=t==="timeline",r=l.useRef(new Map),o=l.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(y,j)=>{const v=r.current,k=v.get(y);if(k&&k.groups===j)return k.ordered;const E=e.getOrderedGroups(y,j);if(v.set(y,{groups:j,ordered:E}),v.size>256){const P=v.keys().next().value;P!==void 0&&v.delete(P)}return E},a=t==="threads",c=t==="folder",d=e.archivedShelfItems??pb,u=t==="workspace"&&d.length>0&&!e.hasSessionSearchQuery&&!e.showOnlyMainWorkspace,f=!!(e.isAllFoldersView||s||a||c),m=l.useMemo(()=>{if(!f)return[];const y=[],j=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const v of j){const k=xs(v.project,e.homeDirectory);for(const E of v.groups)for(const P of E.sessions){const z=e.pinnedSessionIds?tr(e.pinnedSessionIds,P.session.directory??v.project.normalizedPath,P.session.id):!1,K=P.session.time?.updated||P.session.time?.created||0;y.push({node:P,project:v.project,projectLabel:k,isPinned:z,timestamp:K,globalSession:v===e.allFoldersOnlySection})}}return y.sort((v,k)=>v.isPinned!==k.isPinned?v.isPinned?-1:1:k.timestamp-v.timestamp),y},[e.allFoldersOnlySection,f,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),g=tb(m,{enabled:a||c,workingShelf:a}),[b,p]=l.useState(30);l.useEffect(()=>{p(30)},[e.hasSessionSearchQuery]);const h=l.useMemo(()=>m.slice(0,b),[m,b]),w=l.useMemo(()=>e.timelineBoundaries??Zo(Date.now(),1),[e.timelineBoundaries]),x=l.useMemo(()=>s?hm(h,{getTimestamp:y=>y.timestamp,isPinned:y=>y.isPinned,boundaries:w}):[],[s,h,w]);if(e.sharedSessionsOnly)return n.jsx(Mn,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const C=(e.isAllFoldersView||s||a||c)&&!!e.allFoldersOnlySection,S=d.length>0&&!e.hasSessionSearchQuery&&!e.showOnlyMainWorkspace;if(e.projectSections.length===0&&!C&&!S)return n.jsx(Mn,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!C&&!S)return n.jsx(Mn,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const A=()=>{const y=m.length-h.length;return n.jsxs(n.Fragment,{children:[y>0?n.jsx(Ht,{icon:"arrow-down-s",onClick:()=>p(j=>j+30),children:y===1?"Show 1 more session":`Show ${y} more sessions`}):null,b>30&&m.length>30?n.jsx(Ht,{icon:"arrow-up-s",onClick:()=>p(30),children:"Show fewer sessions"}):null]})};return n.jsx("div",{className:"relative flex min-h-0 flex-1",children:n.jsx(Mn,{useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",children:n.jsxs("div",{className:_((a||c&&g&&!e.hasSessionSearchQuery||u)&&!e.showOnlyMainWorkspace?"flex min-h-full flex-col gap-1 px-2":"space-y-1 px-2"),children:[e.topContent,e.showOnlyMainWorkspace?n.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const y=e.sectionsForRender.find(k=>k.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!y)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const j=y.groups.find(k=>k.isMain&&k.sessions.length>0)??y.groups.find(k=>k.sessions.length>0)??y.groups.find(k=>k.isMain)??y.groups[0];if(!j)return n.jsx(Ht,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:y.project.id,directoryOverride:y.project.normalizedPath}),children:"New session"});const v=`${y.project.id}:${j.id}`;return n.jsx(l.Fragment,{children:e.renderGroupSessions(j,v,y.project.id,!0,null,!0)},v)})()}):a&&g&&e.renderSessionNode?n.jsx(cb,{items:m,shelves:g,archived:d,renderSessionNode:e.renderSessionNode,hasSessionSearchQuery:e.hasSessionSearchQuery,mobileVariant:e.mobileVariant,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState}):t==="folder"?n.jsx(Xs.Provider,{value:"tree",children:n.jsx(hb,{shelves:g,archived:d,sections:e.sectionsForRender,homeSection:e.allFoldersOnlySection,homeDirectory:e.homeDirectory,collapsedProjects:e.collapsedProjects,toggleProject:e.toggleProject,hasSessionSearchQuery:e.hasSessionSearchQuery,activeProjectId:e.activeProjectId,hideDirectoryControls:e.hideDirectoryControls,mobileVariant:e.mobileVariant,alwaysShowActions:e.alwaysShowActions,isInlineEditing:e.isInlineEditing,stickyFolderHeaders:e.stickyFolderHeaders,renderGroupSessions:e.renderGroupSessions,renderSessionNode:e.renderSessionNode,getOrderedGroups:i,renderProjectStatusIndicator:e.renderProjectStatusIndicator,setActiveProjectIdOnly:e.setActiveProjectIdOnly,setActiveMainTab:e.setActiveMainTab,setSessionSwitcherOpen:e.setSessionSwitcherOpen,openNewSessionDraft:e.openNewSessionDraft,openProjectEditDialog:e.openProjectEditDialog,removeProject:e.removeProject,reorderProjects:e.reorderProjects,openSidebarMenuKey:e.openSidebarMenuKey,setOpenSidebarMenuKey:e.setOpenSidebarMenuKey,onOpenDirectoryDialog:e.onOpenDirectoryDialog,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState})}):t==="timeline"&&e.renderSessionNode?n.jsx("div",{children:m.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:n.jsxs(n.Fragment,{children:[x.map((y,j)=>{const v=dm[y.id];return n.jsxs("section",{"aria-label":v,"data-timeline-bucket":y.id,children:[n.jsx(ls,{label:v,first:j===0}),y.items.map(({node:k,project:E,projectLabel:P,globalSession:z})=>{const K=k.session.directory??E.normalizedPath;return n.jsx(l.Fragment,{children:e.renderSessionNode(k,0,K,E.id,!1,{projectLabel:P,showFolderLabel:!0,globalSession:z},"project")},k.session.id)})]},y.id)}),A()]})}):e.isAllFoldersView&&e.renderSessionNode?n.jsx("div",{children:m.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:n.jsxs(n.Fragment,{children:[h.map(({node:y,project:j,projectLabel:v,globalSession:k})=>{const E=y.session.directory??j.normalizedPath;return n.jsx(l.Fragment,{children:e.renderSessionNode(y,0,E,j.id,!1,{projectLabel:v,showFolderLabel:!0,globalSession:k},"project")},y.session.id)}),A()]})}):n.jsx("div",{children:e.sectionsForRender.map(y=>{const j=y.project.id,v=i(j,y.groups),k=v.find(P=>P.isMain)??null,E=k?v.filter(P=>P.id!==k.id):v;return n.jsxs("div",{children:[k?e.renderGroupSessions(k,`${j}:${k.id}`,j,!0,null):null,E.map(P=>{const z=`${j}:${P.id}`,K=v.length===1;return n.jsx(l.Fragment,{children:e.renderGroupSessions(P,z,j,K,null)},P.id)})]},j)})}),u&&e.renderSessionNode?n.jsx(Ai,{shelfIds:mb,shelves:{archived:d},renderItem:y=>n.jsx(l.Fragment,{children:e.renderSessionNode(y.node,0,y.node.session.directory??y.project.normalizedPath,y.project.id,!0,{projectLabel:y.projectLabel,showFolderLabel:!!e.isAllFoldersView,globalSession:y.globalSession},"project")},y.node.session.id),hasSessionSearchQuery:!1,mobileVariant:e.mobileVariant,className:"mt-auto border-t border-border pt-1"}):null]})})})}const bb=l.memo(gb);let di=!1;const ui=new Set;let Ba=!1;function xb(){for(const e of ui)e()}function Ni(e){di!==e&&(di=e,xb())}function yb(e){e.key==="Shift"&&Ni(!0)}function wb(e){e.key==="Shift"&&Ni(!1)}function vb(){Ni(!1)}function Sb(){Ba||typeof window>"u"||(Ba=!0,window.addEventListener("keydown",yb),window.addEventListener("keyup",wb),window.addEventListener("blur",vb))}function jb(e){return Sb(),ui.add(e),()=>{ui.delete(e)}}function kb(){return di}function Cb(){return!1}function Ab(){return Te.useSyncExternalStore(jb,kb,Cb)}const Nb=l.memo(function({archiveLabel:t,deleteLabel:s,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:a,onArchive:c,onDelete:d}){const u=Ab(),f=u?s:t,m=g=>{if(u||g.shiftKey){d(g);return}c(g)};return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",className:_("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:i,onMouseDown:a,onClick:m,onKeyDown:g=>g.stopPropagation(),children:n.jsx(R,{name:u?"delete-bin":"archive",className:o})})}),n.jsx(He,{side:"left",sideOffset:8,children:f})]})}),Ib=l.memo(function({open:t,onOpenChange:s,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:a}){return n.jsx(en,{open:t,onOpenChange:s,children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Export Markdown"}),n.jsx(Cn,{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?`})]}),n.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:o,onChange:c=>i(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),n.jsxs(gs,{children:[n.jsx(Ae,{type:"button",onClick:()=>s(!1),variant:"outline",size:"sm",children:"Cancel"}),n.jsx(Ae,{type:"button",onClick:()=>{s(!1),a(o)},size:"sm",children:"Export"})]})]})})});function Eb(e,t){const{session:s,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:a,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:m,handleOpenMiniChatWindow:g,handleDeleteSession:b,handleRestoreSession:p,shelfActions:h}=e,{Item:w,Separator:x,Sub:C,SubTrigger:S,SubContent:A}=t;return n.jsxs(n.Fragment,{children:[n.jsxs(w,{onClick:()=>{d.current={id:s.id,title:r}},className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),n.jsxs(w,{onClick:()=>u(s.id),className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),n.jsxs(w,{onClick:()=>o&&f({directory:o,sessionId:s.id}),className:"[&>svg]:mr-1",children:[i?n.jsx(R,{name:"unpin",className:"mr-1 h-4 w-4"}):n.jsx(R,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),h&&!a?n.jsx(n.Fragment,{children:h.section==="snoozed"?n.jsxs(w,{onClick:h.onWake,className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"alarm",className:"mr-1 h-4 w-4"}),"Wake session"]}):n.jsxs(C,{children:[n.jsxs(S,{className:"[&>svg:first-child]:mr-1",children:[n.jsx(R,{name:"alarm",className:"mr-1 h-4 w-4"}),"Snooze"]}),n.jsx(A,{className:"min-w-[200px]",children:Yu(new Date).map(y=>n.jsxs(w,{onClick:()=>h.onSnooze(y.snoozedUntil),children:[n.jsx("span",{className:"flex-1",children:y.label}),n.jsx("span",{className:"ml-4 typography-micro text-muted-foreground tabular-nums",children:y.whenLabel})]},y.id))})]})}):null,n.jsxs(w,{onClick:()=>{m()},className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?n.jsxs(w,{disabled:!o,onClick:g,className:"[&>svg]:mr-1",children:[n.jsx(R,{name:"window",className:"mr-1 h-4 w-4"}),n.jsx("span",{className:"truncate",children:"Open in Mini Chat window"})]}):null,n.jsx(x,{}),a?null:n.jsxs(w,{className:"[&>svg]:mr-1",onClick:()=>b(s,{archivedBucket:a}),children:[n.jsx(R,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?n.jsxs(w,{className:"[&>svg]:mr-1",onClick:()=>p(s),children:[n.jsx(R,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Unarchive"]}):null,n.jsxs(w,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>b(s,{archivedBucket:a,hardDelete:!0}),children:[n.jsx(R,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Db(e){const{renamingFolderId:t,editingIdRef:s}=e;return n.jsx(Eo,{children:n.jsx(Do,{className:"app-region-no-drag z-50",children:n.jsx(Ro,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||s.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Lo,"min-w-[180px]"),children:Eb(e,{Item:({className:r,...o})=>n.jsx(dl,{className:_(jl,r),...o}),Separator:({className:r,...o})=>n.jsx(ul,{className:_(kl,r),...o}),Sub:fu,SubTrigger:({className:r,children:o,...i})=>n.jsxs(hu,{className:_(Qu,r),...i,children:[o,n.jsx(R,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:r,children:o,...i})=>n.jsx(Eo,{children:n.jsx(Do,{className:"app-region-no-drag z-50",children:n.jsx(Ro,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:_(Lo,r),...i,children:o})})})})})})})}const mo=new WeakMap,Rb=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),s=t?.closest(".overlay-scrollbar-container");if(!t||!s)return;mo.get(s)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,a=null;const c=()=>{i=!0,a!==null&&window.cancelAnimationFrame(a),a=null,mo.delete(s),s.removeEventListener("wheel",c),s.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!s.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(s.scrollTop+=u,Wt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}a=window.requestAnimationFrame(d)};s.addEventListener("wheel",c,{passive:!0}),s.addEventListener("touchstart",c,{passive:!0}),mo.set(s,c),a=window.requestAnimationFrame(d)};function Pb(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const s=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${s} ${r}, ${o}, ${i}:${a}`}function Tb(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",s=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&s?`${t}/${s}`:s||t}function Mb(e){const t=e.info.role==="user"?"User":"Assistant",s=Pb(e.info.time?.created),r=Tb(e),o=s&&r?`${s} (${r})`:s||r;return o?`**${t}**
|
|
21
|
+
|
|
22
|
+
*${o}*`:`**${t}**`}function Fb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function Mc(e){const t=Mb(e),s=Fb(e.parts).trim();return s?`${t}
|
|
23
|
+
|
|
24
|
+
${s}`:""}function Fc(e,t){const s="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${s} Sub-agent: ${e.title}${r}
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
`,i=e.records.map(Mc).filter(Boolean).join(`
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`),a=[o+i];for(const c of e.children)a.push(Fc(c,t+1));return a.join(`
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`)}function Lc(e,t,s){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
|
|
37
|
+
|
|
38
|
+
*Exported on ${o}*
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
`,a=e.map(Mc).filter(Boolean).join(`
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
`);let c=i+a;if(s&&s.length>0){const d=s.map(u=>Fc(u,1)).join(`
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
`);c+=`
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
`+d}return c}function Oc(e,t){vh({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(s=>console.warn("[export] Markdown save failed",s))}async function Bc(e,t){const s=await Hf(t,e);return s||null}async function Lb(e){const t=Tl()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await Gf(e)?!0:Ml(e)}function Ob(){return qf()}function _c(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 Lr=e=>{const t=[],s=r=>{r.children.forEach(o=>{t.push(o.session.id),s(o)})};return s(e),t};function Bb(e,t){const[s,r]=l.useState(!1),[o,i]=l.useState(!0),a=e.session,c=l.useMemo(()=>Lr(e).length,[e]),d=l.useCallback(async g=>{const b=[];let p=0;for(const h of g)try{if(!t)throw new Error("Session directory is required for export");const w=[],x=h.session.title||"Untitled Sub-agent",C=typeof h.session.agent=="string"?h.session.agent:void 0,S=await d(h.children);p+=S.skipped,b.push({title:x,agent:C,records:w,children:S.children})}catch{p+=Lr(h).length+1}return{children:b,skipped:p}},[t]),u=l.useCallback(g=>{g<=0||oe.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.`)},[]),f=l.useCallback(async g=>{if(!t){oe.error("Nothing to export");return}const b=[];if(b.length===0){oe.error("Nothing to export");return}let p,h=0;if(g&&e.children.length>0){const S=await d(e.children);p=S.children,h=S.skipped}const w=Lc(b,a.title??null,p),x=_c(a.title??null),C=await Bc(w,x);if(C){oe.success("Session exported",{action:{label:Ob(),onClick:()=>{Lb(C).then(S=>{S||oe.error("Failed to reveal path")})}}}),u(h);return}Oc(w,x),oe.success("Session exported"),u(h)},[d,e.children,a.title,t,u]),m=l.useCallback(async()=>{if(e.children.length>0){i(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:s,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,descendantCount:c,handleExportSession:m,doExportSession:f}}const _b=(e,t)=>{if(!t)return Array.from(e);const s=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),s.push(o));const i=t.get(o);if(i)for(const a of i)r.has(a)||(r.add(a),s.push(a))}return s},lt=$n()((e,t)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{t().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{t().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(s,r,o)=>{const i=t(),a=new Set(i.selectedIds);let c=i.scopeKey,d=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(a.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[s,...o]:[s];if(a.has(s)){for(const g of f)a.delete(g);d===s&&(d=null)}else{for(const g of f)a.add(g);d=s}a.size===0?e({selectedIds:a,scopeKey:null,anchorId:null}):e({selectedIds:a,scopeKey:c,anchorId:d})},setRange:(s,r,o,i,a)=>{const c=t();if(o.length===0)return;const d=s&&o.includes(s)?s:o[0],u=o.indexOf(d),f=o.indexOf(r);if(u<0||f<0)return;const[m,g]=u<=f?[u,f]:[f,u],b=o.slice(m,g+1),p=_b(b,a),w=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of p)w.add(x);e({selectedIds:w,scopeKey:i??c.scopeKey,anchorId:d})},replaceAll:(s,r)=>{if(s.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(s),scopeKey:r,anchorId:s[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:s=>{const r=t();if(r.selectedIds.size===0||s.length===0)return;const o=new Set(r.selectedIds);for(const i of s)o.delete(i);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),_a=e=>Re(e.session.directory??null),zb=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),Ub=e=>{if(!e.openSidebarMenuKey)return null;const t=e.renderContext??"project",[s,,...r]=e.openSidebarMenuKey.split(":");return s===t&&r.length>0?r.join(":"):null},gr=e=>e.menuOpenSessionId??Ub(e),br=(e,t,s)=>t?s.has(e.node.session.id)?!0:dn(e.node,t):!1,fi=(e,t,s,r,o)=>{if(e.session.id!==t.session.id)return!0;const i=o(e);if(s.has(i)!==r.has(i)||e.children.length!==t.children.length)return!0;for(let a=0;a<e.children.length;a+=1)if(fi(e.children[a],t.children[a],s,r,o))return!0;return!1},$b=(e,t)=>e.hasSessionSearchQuery||t.hasSessionSearchQuery?!1:fi(e.node,t.node,e.expandedParents,t.expandedParents,s=>Zs(e.renderContext??"project",s.session))||fi(e.node,t.node,e.expandedParents,t.expandedParents,s=>Zs(t.renderContext??"project",s.session)),Kb=(e,t)=>{if(e.node.session.id!==t.node.session.id||e.node.session!==t.node.session||e.depth!==t.depth||e.groupDirectory!==t.groupDirectory||e.projectId!==t.projectId||e.archivedBucket!==t.archivedBucket||(e.renderContext??"project")!==(t.renderContext??"project")||e.mobileVariant!==t.mobileVariant||e.alwaysShowActions!==t.alwaysShowActions||e.allowQuickArchiveAction!==t.allowQuickArchiveAction||e.hasSessionSearchQuery!==t.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==t.normalizedSessionSearchQuery||e.nodeStructureKey!==t.nodeStructureKey||_a(e.node)!==_a(t.node)||!zb(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&pc(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&$b(e,t)||e.editingId!==t.editingId&&(br(e,e.editingId,e.subtreeContainsEditing)||br(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(br(e,e.editingId,e.subtreeContainsEditing)||br(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(dn(e.node,e.copiedSessionId)||dn(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const s=gr(e),r=gr(t);if(dn(e.node,s)||dn(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const s=gr(e),r=gr(t);if(dn(e.node,s)||dn(t.node,r))return!1}return e.setEditingId===t.setEditingId&&e.setEditTitle===t.setEditTitle&&e.handleSaveEdit===t.handleSaveEdit&&e.handleCancelEdit===t.handleCancelEdit&&e.toggleParent===t.toggleParent&&e.handleSessionSelect===t.handleSessionSelect&&e.handleSessionDoubleClick===t.handleSessionDoubleClick&&e.togglePinnedSession===t.togglePinnedSession&&e.handleShareSession===t.handleShareSession&&e.handleCopyShareUrl===t.handleCopyShareUrl&&e.handleCopySessionId===t.handleCopySessionId&&e.handleUnshareSession===t.handleUnshareSession&&e.setOpenSidebarMenuKey===t.setOpenSidebarMenuKey&&e.getFoldersForScope===t.getFoldersForScope&&e.getSessionFolderId===t.getSessionFolderId&&e.removeSessionFromFolder===t.removeSessionFromFolder&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.handleDeleteSession===t.handleDeleteSession&&e.handleRestoreSession===t.handleRestoreSession&&e.renderSessionNode===t.renderSessionNode};function Wb({node:e,groupDirectory:t,projectId:s,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:a,hasSessionSearchQuery:c}){const d=e.session,u=Re(d.directory??null)??Re(t??null),f=Me(me=>me.currentSessionId===d.id),m=Oo(u),g=Ju(u),b=ct(l.useCallback(me=>{if(r?.projectLabel||!s)return null;const Pe=me.projects.find(V=>V.id===s);return Pe?xs({label:Pe.label,normalizedPath:Re(Pe.path)??Pe.path},null):null},[s,r?.projectLabel])),p=r?.projectLabel??b,h=ct(l.useCallback(me=>s?me.projects.find(Pe=>Pe.id===s)?.path??null:null,[s])),w=e.worktree,x=r?.branchLabel??w?.branch??(m&&m!=="HEAD"?m:null),C=Re(h),S=Oo(C),y=!!C&&u===C||!!x&&x===S,j=y?null:x,v=!y&&(g===!0||!!(x||w)),k=e.children.length,E=d.agent,P=w?.branch?.trim()||x?.trim()||null,z=Re(w?.path??u),K=l.useMemo(()=>P&&z?er(z,P):null,[P,z]),q=gc(K);bc(z,P);const G=q?`var(--pr-${q.visualState})`:void 0,F=l.useMemo(()=>{if(!q)return null;switch(q.visualState){case"merged":return"Merged";case"open":return q.canMerge===!0||q.mergeableState==="clean"||q.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return q.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[q]),D=s??u??null,T=lt(me=>me.enabled),I=lt(l.useCallback(me=>me.selectedIds.has(d.id),[d.id])),M=lt(me=>me.toggleSelected),H=lt(me=>me.setRange),L=Cl(d.id)?.type??"idle",ae=L==="busy"||L==="retry",J=Xu(d.id,ae),le=un(d,"Untitled session"),Ie=e.children.length>0,Y=tr(o,u,d.id),B=c?!0:i.has(a),$=Zu(d.id);Al(l.useCallback(me=>me.index.session.unseenHasError[d.id]??!1,[d.id]));const X=ef(d.id),ee=tf({pendingInput:X,isStreaming:ae,unseenCount:$,isActive:f}),ie=$>0||Nl(X),Ce=d.time?.updated||d.time?.created||Date.now(),pe=gh(Ce),je=l.useMemo(()=>lc(e.forkColorId),[e.forkColorId]),ze=l.useMemo(()=>Tm(e.forkColorId,{active:f||I}),[e.forkColorId,f,I]);return{session:d,sessionDirectory:u,prDirectory:z,prBranch:P,prNumber:q?.number??null,isActive:f,tooltipProjectLabel:p,projectPath:h,tooltipBranchLabel:j,isGitRepo:v,subtaskCount:k,agentName:E,prSummary:q,prIconColor:G,prStatusLabel:F,selectionScopeKey:D,selectionModeEnabled:T,isRowSelected:I,toggleRowSelected:M,setRowRange:H,isStreaming:ae,hasActivityDuration:J,sessionTitle:le,hasChildren:Ie,isPinnedSession:Y,isExpanded:B,needsAttention:ie,pendingInput:X,attention:ee,sessionCompactUpdatedLabel:pe,forkSolid:je,rowBackground:ze}}const Hb=({prDirectory:e,prNumber:t,prStatusLabel:s,prIconColor:r})=>{const o=vl(e);if(!e||!o)return n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",style:r?{color:r}:void 0,title:s?`PR #${t} — ${s}`:`PR #${t}`,children:[n.jsx(R,{name:"git-pull-request",className:"size-3.5 shrink-0"}),n.jsxs("span",{children:["#",t]})]});const i=a=>{a.stopPropagation(),a.preventDefault(),Ic(e,o,t)};return n.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:a=>{a.stopPropagation(),a.preventDefault()},onKeyDown:a=>{if(!(a.key!=="Enter"&&a.key!==" ")){if(a.repeat){a.stopPropagation(),a.preventDefault();return}i(a)}},className:"inline-flex shrink-0 cursor-pointer items-center gap-1 rounded hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",style:r?{color:r}:void 0,title:s?`PR #${t} — ${s}. Open in Pull requests`:`Open PR #${t} in Pull requests`,"aria-label":s?`Open pull request #${t}, ${s}, in Pull requests`:`Open pull request #${t} in Pull requests`,children:[n.jsx(R,{name:"git-pull-request",className:"size-3.5 shrink-0"}),n.jsxs("span",{children:["#",t]})]})};function Gb(e){Wt("ui.sidebar_session_node.render");const{node:t,depth:s=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:a,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,editingId:f,setEditingId:m,editTitle:g,setEditTitle:b,handleSaveEdit:p,handleCancelEdit:h,toggleParent:w,handleSessionSelect:x,handleSessionDoubleClick:C,togglePinnedSession:S,handleShareSession:A,copiedSessionId:y,handleCopyShareUrl:j,handleCopySessionId:v,handleUnshareSession:k,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,renamingFolderId:z,getFoldersForScope:K,getSessionFolderId:q,removeSessionFromFolder:G,addSessionToFolder:F,createFolderAndStartRename:D,handleDeleteSession:T,handleRestoreSession:I,alwaysShowActions:M,allowQuickArchiveAction:H,renderSessionNode:W,secondaryMeta:L,renderContext:ae="project",subtreeContainsEditing:J,menuOpenSessionId:le,childRenderExtrasFor:Ie}=e,Y=i||!!t.session.time?.archived,B=l.useContext(Xs)==="tree",$="size-3 shrink-0",X=l.useMemo(()=>Fl(),[]),ee=!Y&&H,ie=l.useRef(!1),Ce=l.useRef(f);Ce.current=f;const pe=l.useRef(null),je=l.useRef(p);je.current=p;const[be,ze]=l.useState(g),me=l.useRef(be);me.current=be;const Pe=l.useRef(null),V=l.useRef(null),xe=Zs(ae,t.session),{session:te,sessionDirectory:re,prDirectory:Be,prNumber:ke,isActive:Q,tooltipProjectLabel:ve,projectPath:he,tooltipBranchLabel:Se,isGitRepo:qe,subtaskCount:Ue,agentName:U,prSummary:ge,prIconColor:se,prStatusLabel:_e,selectionScopeKey:st,selectionModeEnabled:pt,isRowSelected:Xe,toggleRowSelected:Yt,setRowRange:mt,isStreaming:Nt,hasActivityDuration:nn,sessionTitle:Qe,hasChildren:Mt,isPinnedSession:Ft,isExpanded:jt,pendingInput:Ee,attention:Ye,sessionCompactUpdatedLabel:Ne,forkSolid:De,rowBackground:Ge}=Wb({node:t,groupDirectory:r,projectId:o,secondaryMeta:L,pinnedSessionIds:a,expandedParents:c,expansionKey:xe,hasSessionSearchQuery:d}),{exportDialogOpen:ut,setExportDialogOpen:sn,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:Ot,descendantCount:Ve,handleExportSession:rn,doExportSession:An}=Bb(t,re),[It,Kn]=l.useState(!1),bt=l.useContext(Kr),rt=s===0&&!Y?bt?.sectionById.get(te.id)??null:null,Qt=Qs(l.useCallback(de=>rt==="snoozed"?de.entries[te.id]?.snoozedUntil??null:null,[rt,te.id])),Bt=rt==="snoozed"||Y,gn=rt!==null&&rt!=="snoozed"&&!!bt?.wokeIds.has(te.id),on=l.useMemo(()=>{if(!rt)return null;const de=re??null;return{section:rt,onSnooze:_t=>ci(te.id,{snoozedUntil:_t},de,"Could not snooze the session"),onWake:()=>ci(te.id,{snoozedUntil:null},de,"Could not wake the session")}},[rt,te.id,re]),xt=on?.section==="snoozed"?{label:"Wake",hint:"Wake now: back to the list",icon:"alarm",run:on.onWake}:null,yt=l.useCallback(()=>{re&&Us("desktop_open_session_mini_chat_window",{sessionId:te.id,directory:re,apiBaseUrl:$o(),clientToken:Uo()}).catch(de=>{console.warn("[session-sidebar] failed to open mini chat window",de)})},[te.id,re]);l.useEffect(()=>{if(f!==te.id)return;const de=_t=>{const As=_t.target?.closest?.(`[data-session-rename-form="${CSS.escape(te.id)}"]`);V.current&&!As&&je.current(me.current)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[f,te.id]),l.useLayoutEffect(()=>{if(f!==te.id){Pe.current===te.id&&(Pe.current=null);return}Pe.current!==te.id&&(Pe.current=te.id,ze(g))},[f,g,te.id]);const Et=Ye==="needs-input",Wn=Et&&Ee?nf(Ee.kind,Ee.count):null,Nn=Ye==="unread",In=Qt!==null?sf(Qt,Date.now()):gn?"Woke":Ne,kt=Nt&&nn,an=ee&&(M||It),tt=Nt&&!B&&!an&&f!==te.id,ln=!!(L?.showFolderLabel&&ve),wt=!!Se||qe,Ct=!!(U&&U!=="default"),ot=!!ge&&ke!=null,En=kt&&!tt,it=ln&&wt||ot||Ue>0||Ct||En,Hn=de=>Se?n.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",de?"shrink":"flex-1"),children:[n.jsx(R,{name:"git-branch",className:$,style:se?{color:se}:void 0}),n.jsx(_s,{value:Se})]}):qe?n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[n.jsx(R,{name:"git-repository",className:$}),n.jsx("span",{children:"git"})]}):null,Gn=Ft,js=n.jsx(R,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),Dn=Gn?n.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:js}):null,ks=Mt?n.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),w(xe)},onKeyDown:de=>{(de.key==="Enter"||de.key===" ")&&(de.preventDefault(),de.stopPropagation(),w(xe))},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":jt?"Collapse subsessions":"Expand subsessions",children:jt?n.jsx(R,{name:"arrow-down-s",className:"h-3 w-3"}):n.jsx(R,{name:"arrow-right-s",className:"h-3 w-3"})}):null,O=de=>{if(!de&&pe.current){const{id:_t,title:qn}=pe.current;pe.current=null,m(_t),b(qn)}},ce=de=>{Kn(de)},ye=de=>{de.preventDefault(),de.stopPropagation()},$e=de=>{de.preventDefault(),de.stopPropagation()},ft=de=>{de.preventDefault(),de.stopPropagation(),P(null),T(te,{archivedBucket:Y})},Je=de=>{de.preventDefault(),de.stopPropagation(),P(null),T(te,{archivedBucket:Y,hardDelete:!0,skipConfirm:!0})},vt=de=>{if(ie.current){ie.current=!1;return}if(pt){if(de?.preventDefault(),de?.stopPropagation(),de?.shiftKey){const qn=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Vn=>Vn.getAttribute("data-session-row")).filter(Vn=>typeof Vn=="string"&&Vn.length>0),As=lt.getState().anchorId,or=new Map;or.set(te.id,Lr(t)),mt(As,te.id,qn,st,or);return}Yt(te.id,st,Lr(t));return}de?.currentTarget&&Rb(de.currentTarget),x(te.id,re)},Dt=de=>{de.defaultPrevented||de.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||vt(de)},bn=de=>{(de.button===2||de.button===0&&de.ctrlKey&&!pt)&&(ie.current=!0)},Cs={session:te,sessionTitle:Qe,sessionDirectory:re,isPinnedSession:Ft,archivedBucket:Y,isElectron:X,renamingFolderId:z,editingIdRef:Ce,pendingRenameRef:pe,handleCopySessionId:v,togglePinnedSession:S,handleExportSession:rn,handleOpenMiniChatWindow:yt,handleDeleteSession:T,handleRestoreSession:I,shelfActions:on},rr=n.jsx(Db,{...Cs});return n.jsxs(l.Fragment,{children:[n.jsx(tg,{sessionId:te.id,sessionDirectory:re??null,sessionTitle:Qe,children:n.jsxs(ll,{open:It,onOpenChange:ce,onOpenChangeComplete:O,children:[n.jsxs(cl,{render:n.jsx("div",{"data-session-row":te.id,"data-session-scope":st??"","data-session-archived":Y?"1":"0","data-fork-color":De?t.forkColorId:void 0,"data-global-session":L?.globalSession?"1":void 0,"data-sidebar-tree-row":B?"":void 0,onClick:Dt,style:{...s>0?{marginLeft:`${s*14}px`}:void 0,...Ge?{backgroundColor:Ge}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",B?hc:"my-0.5 rounded-xl py-2",!Ge&&s>0?"bg-secondary/30 hover:bg-interactive-hover":Ge?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!Ge&&Q&&!Xe&&"bg-interactive-selection",!Ge&&Xe&&"bg-interactive-selection")}),children:[n.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",tt&&"oc-session-row-working-fade"),"data-clear-on-hover":tt&&ee?"true":void 0,"data-working-duration":tt&&kt?"true":void 0,children:[n.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",B?Wr:"gap-1.5"),children:[B?n.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:Nt&&!Et?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,ks,Dn,f===te.id?n.jsxs("form",{ref:V,"data-session-rename-form":te.id,className:_("flex min-w-0 flex-1 items-center gap-2",B?"min-h-5":"min-h-8"),onPointerDown:de=>de.stopPropagation(),onMouseDown:de=>de.stopPropagation(),onSubmit:de=>{de.preventDefault(),p(be)},children:[n.jsx("input",{value:be,onChange:de=>ze(de.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:de=>{de.stopPropagation(),de.key==="Escape"&&h()}}),n.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:n.jsx(R,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:h,"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:n.jsx(R,{name:"close",className:"size-4"})})]}):n.jsxs("button",{type:"button",onMouseDown:bn,onClick:de=>vt(de),onDoubleClick:de=>{de.stopPropagation(),C(te.id,Qe)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[n.jsxs("div",{className:_("flex w-full min-w-0 flex-1 gap-1.5 overflow-hidden",B?"items-center":"items-start"),children:[n.jsx("div",{className:_("block min-w-0 flex-1 truncate typography-ui-label",Q?"font-medium text-foreground":"font-normal",!Q&&(Bt?"text-muted-foreground group-hover:text-foreground":"text-foreground")),children:si(Qe,u)}),Ft?n.jsx(R,{name:"star-fill",className:_("h-3 w-3 text-primary shrink-0",!B&&"mt-1")}):null,n.jsx("span",{"aria-hidden":"true",className:_("invisible ml-1 min-w-6 shrink-0 whitespace-nowrap typography-micro",(Qt!==null||gn)&&!Nn&&"pl-4"),children:Nn?null:In})]}),!B&&(ln||wt||it)?n.jsxs("div",{className:_("flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden typography-micro leading-4 font-normal",Bt?"text-subtle-foreground":"text-muted-foreground"),children:[ln?n.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",it?"max-w-[60%] shrink-0":"flex-1"),children:[he?n.jsx(yi,{directory:he,label:ve??"",className:$}):n.jsx(R,{name:"folder",className:$}),n.jsx("span",{className:"truncate",children:ve})]}):Hn(!1),it?n.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",ln?"flex-1":"shrink-0"),children:[ln?Hn(!0):null,ot?n.jsx(Hb,{prDirectory:Be,prNumber:ke,prStatusLabel:_e,prIconColor:se}):null,Ue>0?n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[n.jsx(R,{name:"node-tree",className:$}),n.jsx("span",{children:Ue})]}):null,Ct?n.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:U}):null,En?n.jsx(na,{sessionId:te.id,running:Nt,className:"shrink-0 text-subtle-foreground"}):null]}):null]}):null]})]}),n.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",B?"top-1/2 -translate-y-1/2":"top-2",f===te.id&&"hidden"),children:[n.jsx("div",{className:_("flex items-center justify-end",an?"opacity-0":ee?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Et&&!tt?n.jsx(Qi,{label:Wn??"Needs input"}):Nn?n.jsx(bh,{label:"Session complete"}):Qt!==null||gn?n.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro text-muted-foreground whitespace-nowrap",title:Qt!==null?`Snoozed until ${new Date(Qt).toLocaleString()}`:"Back from snooze",children:[n.jsx(R,{name:"alarm",className:"size-3 shrink-0"}),In]}):n.jsx("span",{className:"typography-micro text-subtle-foreground whitespace-nowrap",children:Ne})}),ee?n.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",M||It?"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:xt?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":xt.label,className:"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:ye,onMouseDown:$e,onKeyDown:de=>de.stopPropagation(),onClick:de=>{de.preventDefault(),de.stopPropagation(),P(null),xt.run()},children:n.jsx(R,{name:xt.icon,className:"size-4"})})}),n.jsx(He,{side:"top",sideOffset:6,children:xt.hint})]}):n.jsx(Nb,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:ye,onMouseDown:$e,onArchive:ft,onDelete:Je})}):null]})]}),tt?n.jsxs("span",{"data-session-working":!0,className:_("pointer-events-none absolute inset-y-0 right-0 flex items-center rounded-r-[inherit] pr-3 transition-opacity",ee&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[Et?null:n.jsx("span",{"aria-hidden":"true",className:"oc-session-row-working-aura absolute inset-y-0 right-0 w-24 rounded-r-[inherit] bg-gradient-to-l from-primary/15 to-transparent"}),n.jsxs("span",{className:"relative flex flex-col items-end gap-1",children:[n.jsx("span",{className:"flex h-5 items-center",children:Et?n.jsx("span",{className:"inline-flex size-3 shrink-0 items-center justify-center",children:n.jsx(Qi,{label:Wn??"Needs input"})}):n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}),kt?n.jsx(na,{sessionId:te.id,running:Nt,className:"typography-micro leading-4"}):null]})]}):null]}),rr]})}),Mt&&jt?t.children.map(de=>{const _t=Ie?Ie(de):{subtreeContainsEditing:J,menuOpenSessionId:le,nodeStructureKey:""};return n.jsx(l.Fragment,{children:W(de,s+1,re??r,o,Y,L?.globalSession?{globalSession:!0}:void 0,ae,_t)},de.session.id)}):null,n.jsx(Ib,{open:ut,onOpenChange:sn,descendantCount:Ve,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:Ot,onExport:An})]},te.id)}const qb=l.memo(Gb,Kb),Vb=({open:e,onOpenChange:t,project:s,onSave:r})=>n.jsx(en,{open:e,onOpenChange:t,children:n.jsx(tn,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:n.jsx(Mn,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:n.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&s?n.jsx(Gp,{project:s,onIdentitySave:r}):null})})})});function zc(e){const{showDeletionDialog:t,setShowDeletionDialog:s,onCancel:r,onConfirm:o,confirmLabel:i}=e;return n.jsxs(gs,{className:"w-full sm:items-center sm:justify-between",children:[n.jsxs("button",{type:"button",onClick:()=>s(!t),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":!t,children:[t?n.jsx(R,{name:"checkbox-blank",className:"h-4 w-4"}):n.jsx(R,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.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"}),n.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:i})]})]})}function Yb(e){const{value:t,setValue:s,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=c=>un(c);return n.jsx(en,{open:!!t,onOpenChange:c=>{c||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Delete session?"}),n.jsx(Cn,{children:t&&t.descendantCount>0?t.descendantCount===1?`"${a(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${a(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:`"${t?.session?a(t.session):"Untitled Session"}" will be permanently deleted.`})]}),n.jsx(zc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>s(null),onConfirm:i,confirmLabel:"Delete"})]})})}function Qb(e){const{value:t,setValue:s,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=t?.sessionCount??0,c=a===1?"Delete session?":"Delete sessions?",d=a===1?`${a} session will be permanently deleted.`:`${a} sessions will be permanently deleted.`;return n.jsx(en,{open:!!t,onOpenChange:u=>{u||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:c}),n.jsx(Cn,{children:d})]}),n.jsx(zc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>s(null),onConfirm:i,confirmLabel:"Delete"})]})})}function Jb(e){const{value:t,setValue:s,onConfirm:r}=e,{git:o}=Un(),[i,a]=l.useState(null),[c,d]=l.useState(!1),[u,f]=l.useState(!1),[m,g]=l.useState(!1),b=t?.worktree.path??null;l.useEffect(()=>{let y=!1;return a(null),d(!1),f(!1),g(!1),!t||!b?()=>{y=!0}:(o.getGitStatus(b).then(j=>{if(!y){if(typeof j?.isClean!="boolean"){d(!0);return}a(j)}}).catch(()=>{y||d(!0)}),()=>{y=!0})},[o,t,b]);const p=i?.isClean===!1,h=(i?.ahead??0)>0,w=h&&!t?.worktree.branch,x=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",C=!!(t&&i&&!c&&!t.hasActiveSession&&(!p&&!w||u)&&!m),S=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",A=async()=>{if(C){g(!0);try{await r({force:p})}finally{g(!1)}}};return n.jsx(en,{open:!!t,onOpenChange:y=>{!y&&!m&&s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-md gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Close worktree?"}),n.jsx(Cn,{children:`Closing "${S}" removes its worktree directory. ${x}`})]}),c?n.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:[n.jsx(R,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):i===null?n.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,t?.hasActiveSession?n.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:[n.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,p?n.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),n.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[n.jsx(Gs,{checked:u,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),n.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,h?n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"typography-ui-label text-muted-foreground",children:i?.ahead===1?`This worktree has 1 unpushed commit. ${x}`:`This worktree has ${i?.ahead} unpushed commits. ${x}`}),w?n.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(R,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),n.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[n.jsx(Gs,{checked:u,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),n.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,n.jsxs(gs,{className:"sm:justify-end",children:[n.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>s(null),disabled:m,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!C,children:m?"Closing…":"Close worktree"})]})]})})}function Xb(e){const{value:t,setValue:s,onConfirm:r}=e;return n.jsx(en,{open:!!t,onOpenChange:o=>{o||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Delete folder?"}),n.jsx(Cn,{children:t&&(t.subFolderCount>0||t.sessionCount>0)?t.subFolderCount>0?t.subFolderCount===1?`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted. Sessions inside will not be deleted.`:`"${t?.folderName??""}" will be permanently deleted.`})]}),n.jsxs(gs,{children:[n.jsx("button",{type:"button",onClick:()=>s(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"}),n.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 Zb=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:s,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:a,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:m,setDeleteFolderConfirm:g,confirmDeleteFolder:b,closeWorktreeConfirm:p,setCloseWorktreeConfirm:h,confirmCloseWorktree:w,bulkDeleteConfirm:x,setBulkDeleteConfirm:C,confirmBulkDelete:S})=>n.jsxs(n.Fragment,{children:[n.jsx(Ql,{open:e,onOpenChange:t,info:s.info,downloading:s.downloading,downloaded:s.downloaded,progress:s.progress,error:s.error,onDownload:s.downloadUpdate,onRestart:s.restartToUpdate,runtimeType:s.runtimeType}),n.jsx(Vb,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:i}),n.jsx(Yb,{value:a,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),n.jsx(Xb,{value:m,setValue:g,onConfirm:b}),n.jsx(Jb,{value:p,setValue:h,onConfirm:w}),n.jsx(Qb,{value:x,setValue:C,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:S})]}),ex=({directories:e})=>{const t=l.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Re(o)?.toLowerCase();i&&r.add(i)}),r},[e]),s=zs(r=>{let o=0,i=!1;for(const a of r.catalog.byId.values()){const c=Re(a.directory)?.toLowerCase();!c||!t.has(c)||(Nl(a.pendingInput)?o+=1:(a.lifecycle==="busy"||a.lifecycle==="retry")&&(i=!0))}return{inputCount:o,hasBusySession:i}},(r,o)=>r.inputCount===o.inputCount&&r.hasBusySession===o.hasBusySession,"catalog");if(s.inputCount>0){const r=rf(s.inputCount);return n.jsx("span",{className:"inline-flex items-center","aria-label":r,title:r,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return s.hasBusySession?n.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},tx=({selectedCount:e,archivedBucket:t,onRestore:s,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",a="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 n.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border pl-5 pr-3.5 py-1.5",children:[n.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),n.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[t?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:a,"aria-label":"Unarchive",children:n.jsx(R,{name:"inbox-unarchive",className:"h-4 w-4"})})}),n.jsx(He,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Unarchive"})})]}):null,n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:r,className:_(t?"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":a),"aria-label":i,children:n.jsx(R,{name:t?"delete-bin":"inbox-archive",className:"h-4 w-4"})})}),n.jsx(He,{side:"top",sideOffset:4,children:n.jsx("p",{children:i})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,className:a,"aria-label":"Exit selection",children:n.jsx(R,{name:"close",className:"h-4 w-4"})})}),n.jsx(He,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Exit selection"})})]})]})]})},nx=e=>{if(typeof document>"u")return!1;const t=document.querySelectorAll(`[data-session-row="${CSS.escape(e)}"]`);if(t.length===0)return!1;for(const s of t)if(s.getAttribute("data-session-archived")!=="1")return!1;return!0},sx=e=>{const{isInlineEditing:t,showDeletionDialog:s,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:a,createFolderAndStartRename:c,resolveSessionDirectory:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:m}=e,g=lt(T=>T.enabled),b=lt(T=>T.selectedIds.size),p=b>0,h=lt(T=>T.selectedIds),w=lt(T=>T.scopeKey),x=l.useCallback(()=>{lt.getState().toggleMode()},[]),C=l.useCallback(()=>{lt.getState().disable()},[]),S=l.useMemo(()=>{if(!p||typeof document>"u")return!1;let T=!1,I=!1;for(const M of h){const H=document.querySelectorAll(`[data-session-row="${CSS.escape(M)}"]`);for(const W of H)W.getAttribute("data-session-archived")==="1"?I=!0:T=!0}return I&&!T},[p,h]),A=l.useMemo(()=>{if(w)return w;if(!p||typeof document>"u")return null;for(const T of h){const M=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(M&&M.length>0)return M}return null},[p,h,w]),y=l.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(I=>I.scopeKey):[A]},[A,o]),j=l.useMemo(()=>y.flatMap(T=>r[T]??[]),[r,y]),v=l.useCallback(T=>{for(const I of y)if((r[I]??[]).some(M=>M.id===T))return I;return null},[r,y]),k=l.useMemo(()=>{if(!p)return!1;for(const T of y)for(const I of r[T]??[])for(const M of I.sessionIds)if(h.has(M))return!0;return!1},[r,y,p,h]),E=l.useCallback((T,I)=>{const M=Array.from(h);for(const H of y)H!==T&&a(H,M);i(T,I,M)},[i,a,h,y]),P=l.useCallback(T=>{if(!p)return;const I=v(T);I&&E(I,T)},[p,E,v]),z=l.useCallback(()=>{const T=y[0];if(!T||!p)return;const I=c(T);I&&E(T,I.id)},[c,p,E,y]),K=l.useCallback(()=>{if(!p)return;const T=Array.from(h);for(const I of y)a(I,T)},[a,h,y,p]),q=l.useCallback(async()=>{const T=Array.from(h);if(T.length===0)return;const{deletedIds:I,failedIds:M}=await f(T);I.length>0&&oe.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Failed to delete ${M.length} session`:`Failed to delete ${M.length} sessions`),lt.getState().clear()},[f,h]),G=l.useCallback(()=>{if(p){if(!S){const T=Array.from(h).filter(I=>!nx(I)).map(I=>({sessionId:I,directory:d(I),forkIds:[]}));lt.getState().clear(),cc(T);return}if(!s){q();return}m({sessionCount:h.size})}},[S,q,d,h,s,m,p]),F=l.useCallback(async()=>{if(!p||!S)return;const T=Array.from(h),{restoredIds:I,failedIds:M}=await u(T);I.length>0&&oe.success(I.length===1?`Unarchived ${I.length} session`:`Unarchived ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Could not unarchive ${M.length} session`:`Could not unarchive ${M.length} sessions`),lt.getState().clear()},[S,p,h,u]),D=l.useCallback(async()=>{m(null),await q()},[q]);return l.useEffect(()=>{if(!g)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=M=>{if(t)return;const H=M.target;if(H&&(H.tagName==="INPUT"||H.tagName==="TEXTAREA"||H.isContentEditable))return;const W=T?M.metaKey:M.ctrlKey;if(M.key==="Escape"){M.preventDefault(),lt.getState().disable();return}if(W&&M.key==="Backspace"){M.preventDefault(),G();return}if(W&&(M.key==="a"||M.key==="A")){const L=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(L.length===0)return;M.preventDefault();const J=lt.getState().scopeKey??L[0]?.getAttribute("data-session-scope")??null,le=Y=>J?Y.getAttribute("data-session-scope")===J:!0,Ie=L.filter(le).map(Y=>Y.getAttribute("data-session-row")).filter(Y=>typeof Y=="string"&&Y.length>0);if(Ie.length===0)return;lt.getState().replaceAll(Ie,J||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[G,t,g]),{selectionModeEnabled:g,hasSelection:p,selectedIdsSize:b,bulkScopeIsArchived:S,derivedSelectionScope:A,bulkScopeFolders:j,bulkCanRemoveFromFolder:k,handleToggleSelectionMode:x,handleExitSelectionMode:C,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:z,handleBulkRemoveFromFolder:K,handleBulkDelete:G,handleBulkRestore:F,confirmBulkDelete:D}},rx=(e,t)=>{const s=e??{};return delete s.projectSortOrder,delete s.showArchivedSessions,t<4&&delete s.displayMode,t<5&&delete s.sessionGroupingMode,s},ox=$n()(zl(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,setShowRecentSection:t=>e({showRecentSection:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection}))}),{name:"pichamber:session-display-settings",version:7,migrate:rx})),za="oc.sessions.projectCollapse",Ua="oc.sessions.groupOrder",$a="oc.sessions.groupCollapse",Ka="oc.sessions.activeSessionByProject",Wa="oc.sessions.expandedParents.v3",ix=new Set,go=[],Rt=e=>{const t=l.useRef(e);return t.current=e,l.useCallback((...s)=>t.current(...s),[])},ax=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:s,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:a=!1})=>{zo("react.session_sidebar_render"),Wt("ui.session_sidebar.render"),Wt(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),Wt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=l.useState(!1),[u,f]=l.useState(""),m=l.useRef(null),g=l.useRef(null),[b,p]=l.useState(null),[h,w]=l.useState(""),[x,C]=l.useState(null),[S,A]=l.useState(new Set),y=l.useMemo(()=>rs(),[]),[j,v]=l.useState(new Set),k=Jn(N=>N.selectedSpaceId),E=Jn(N=>N.selectedWorktreePath),[P,z]=l.useState(new Map),[K,q]=l.useState(new Map),[G,F]=l.useState(!1),[D,T]=l.useState(null),[I,M]=l.useState(null),[H,W]=l.useState(""),[L,ae]=l.useState(null),[J,le]=l.useState(null),[Ie,Y]=l.useState(null),[B,$]=l.useState(null),X=Vs(N=>N.ids),ee=of(l.useCallback(N=>e?N.rankById:Sl,[e])),ie=zs(N=>e?af(N.catalog):"",void 0,"catalog"),Ce=l.useMemo(()=>ie?ie.split("|"):go,[ie]),pe=l.useMemo(()=>new Set(Ce),[Ce]),je=Al(Po(N=>e?Object.entries(N.index.session.unseenCount).filter(([,Z])=>Z>0).map(([Z])=>Z).sort():go)),be=l.useMemo(()=>new Set(je),[je]),ze=Vs(N=>N.toggle),[me,Pe]=l.useState(()=>{try{const N=rs().getItem($a);if(!N)return new Set;const Z=JSON.parse(N);return new Set(Array.isArray(Z)?Z.filter(ne=>typeof ne=="string"):[])}catch{return new Set}}),[V,fe]=l.useState(()=>{try{const N=rs().getItem(Ua);if(!N)return new Map;const Z=JSON.parse(N),ne=new Map;return Object.entries(Z).forEach(([Le,Oe])=>{Array.isArray(Oe)&&ne.set(Le,Oe.filter(et=>typeof et=="string"))}),ne}catch{return new Map}}),xe=l.useMemo(()=>{try{const N=rs().getItem(Ka);if(!N)return new Map;const Z=JSON.parse(N),ne=new Map;return Object.entries(Z).forEach(([Le,Oe])=>{typeof Oe=="string"&&Oe.length>0&&ne.set(Le,Oe)}),ne}catch{return new Map}},[]),te=l.useCallback(N=>{try{y.setItem(Ka,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[y]),[re,Be]=l.useState(new Map),ke=l.useRef(0),Q=hs(N=>N.homeDirectory),ve=hs(N=>N.currentDirectory),he=ct(N=>N.projects),Se=ct(N=>N.activeProjectId),qe=ct(N=>N.removeProject),Ue=ct(N=>N.setActiveProjectIdOnly),U=ct(N=>N.updateProjectMeta),ge=ct(N=>N.reorderProjects),se=ue(N=>N.setActiveMainTab),_e=ue(N=>N.setSettingsDialogOpen),st=ue(N=>N.setSettingsPage),pt=ue(N=>N.toggleHelpDialog),Xe=ue(N=>N.setSessionSwitcherOpen),Yt=ue(N=>N.setArchivePageOpen),mt=ue(N=>N.showDeletionDialog),Nt=ue(N=>N.setShowDeletionDialog),nn=ue(N=>N.sidebarViewMode),Qe=i||a||!Vf(nn)?"workspace":nn,Mt=ue(N=>N.weekStartPreference),Ft=l.useMemo(()=>um(Mt),[Mt]),jt=mm(e&&Qe==="timeline",Ft),Ee=ox(N=>N.stickyZoneHeaders),Ye=lf(u,120),Ne=l.useMemo(()=>Ye.trim().toLowerCase(),[Ye]),De=Ne.length>0,Ge=gt(N=>N.collapsedFolderIds),ut=gt(N=>N.foldersMap),sn=gt(N=>N.getFoldersForScope),Lt=gt(N=>N.createFolder),Ot=gt(N=>N.renameFolder),Ve=gt(N=>N.deleteFolder),rn=gt(N=>N.addSessionToFolder),An=gt(N=>N.addSessionsToFolder),It=gt(N=>N.removeSessionFromFolder),Kn=gt(N=>N.removeSessionsFromFolders),bt=gt(N=>N.toggleFolderCollapse),rt=gt(N=>N.getSessionFolderId);Lm({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:g,sessionSearchContainerRef:m});const Qt=cf(e),{git:Bt}=Un(),gn=zs(N=>N.connection,void 0,"chrome"),on=zs(N=>{for(const Z of N.catalog.listStatusByDirectory.values())if(Z==="ready")return!0;return!1},void 0,"catalog"),xt=Fo({archived:!1}),yt=Fo({archived:!0}),Et=Me(N=>N.setCurrentSession),Wn=Me(N=>N.updateSessionTitle),Nn=Me(N=>N.shareSession),In=Me(N=>N.unshareSession),kt=Bo(N=>N.projects),an=Bo(N=>N.refreshProject),tt=l.useMemo(()=>df(he,{projects:kt}),[he,kt]),ln=l.useMemo(()=>{const N=new Map;for(const Z of he){const ne=Re(Z.path);if(!ne)continue;const Le=kt.get(ne)?.error;Le&&N.set(ne,Le)}return N},[he,kt]);l.useEffect(()=>{if(!k)return;const N=he.find(ne=>ne.id===k);if(!N){Jn.getState().clearSpaceSelection();return}if(!E)return;(tt.get(Re(N.path)??N.path)??[]).some(ne=>Re(ne.path)===Re(E))||(Jn.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[tt,he,k,E]);const wt=Me(N=>N.openNewSessionDraft),Ct=l.useCallback(N=>{ue.getState().closeMainSurfaces(),wt(N),r?.()},[r,wt]),ot=yr(Po(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}))),En=l.useMemo(()=>uf(he,tt,{includeWorktrees:!0}),[tt,he]),it=l.useMemo(()=>xt.filter(N=>Qm(N,En,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:Q})),[xt,Q,En]),Hn=l.useMemo(()=>[...it,...yt],[yt,it]),Gn=Tt(),js=l.useMemo(()=>`${Gn}|${he.map(N=>`${N.id}:${Re(N.path)??""}`).join("|")}`,[he,Gn]),Dn=l.useMemo(()=>{const N=new Set;let Z=!0;for(const ne of he){const Le=Re(ne.path);if(!Le)continue;const Oe=kt.get(Le)?.status??"idle";Oe==="failed"&&N.add(Le),(Oe==="idle"||Oe==="loading")&&(Z=!1)}return{complete:Z,unresolved:N}},[he,kt]),ks=Dn.complete?js:null;Dn.complete;const O=Dn.unresolved,{isTablet:ce}=ms(),ye=t||ce,$e=Fm({mobileVariant:t,isTablet:ce}),{buildGroupSearchText:ft,filterSessionNodesForSearch:Je,buildGroupedSessions:vt}=Mm({homeDirectory:Q,pinnedSessionIds:X,sessionOrderRanks:ee}),{scheduleCollapsedProjectsPersist:Dt}=Bm({safeStorage:y,keys:{sessionExpanded:Wa,projectCollapse:za,groupOrder:Ua,groupCollapse:$a},groupOrderByProject:V,collapsedGroups:me,setExpandedParents:A,setCollapsedProjects:v}),bn=l.useMemo(()=>ff(it,X,ee),[X,ee,it]),Cs=l.useMemo(()=>bn.map(N=>N.id).join("|"),[bn]),rr=l.useRef(null),de=l.useMemo(()=>{const N=rr.current;if(N&&N.signature===Cs)return N.map;const Z=new Map(bn.map((ne,Le)=>[ne.id,Le]));return rr.current={signature:Cs,map:Z},Z},[bn,Cs]),_t=l.useMemo(()=>{const N=new Map;bn.forEach(ne=>{const Le=ne.parentID;if(!Le)return;const Oe=N.get(Le)??[];Oe.push(ne),N.set(Le,Oe)});const Z=yl(X,ee);return N.forEach(ne=>ne.sort(Z)),N},[bn,X,ee]),qn=l.useMemo(()=>n.jsx(Ht,{icon:"chat-new",mobileVariant:t,onClick:()=>Ct(),children:"New session"}),[t,Ct]),As=l.useMemo(()=>he.find(N=>N.id===x)??null,[he,x]),or=l.useCallback(N=>{x&&U(x,{label:N.label,defaultModel:N.defaultModel??null})},[x,U]),Vn=l.useCallback(()=>{const N=yr.getState();if(N.available&&N.info){F(!0);return}ot.checkForUpdates().then(()=>{const{available:Z,error:ne}=yr.getState();if(ne){oe.error("Failed to check for updates",{description:ne});return}if(!Z){oe.success("You are on the latest version");return}F(!0)})},[ot]),Yn=hf(),Ii=l.useCallback(()=>{if(t&&Xe(!1),r?.(),Yn?.openSettings){Yn.openSettings();return}_e(!0)},[Yn,t,r,Xe,_e]),Hc=ot.available&&(ot.runtimeType==="desktop"||ot.runtimeType==="web"),Gc=Me(N=>N.deleteSession),Ei=Me(N=>N.deleteSessions),qc=Me(N=>N.unarchiveSession),Vc=Me(N=>N.unarchiveSessions),{copiedSessionId:Yc,handleSessionSelect:Qc,handleSessionDoubleClick:Jc,handleSaveEdit:Xc,handleCancelEdit:Zc,handleShareSession:ed,handleCopyShareUrl:td,handleCopySessionId:nd,handleUnshareSession:sd,handleDeleteSession:rd,handleRestoreSession:od,confirmDeleteSession:id}=Om({mobileVariant:t,allowReselect:o,onSessionSelected:s,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:se,setSessionSwitcherOpen:Xe,setCurrentSession:Et,updateSessionTitle:Wn,shareSession:Nn,unshareSession:In,deleteSession:Gc,deleteSessions:Ei,unarchiveSession:qc,childrenMap:_t,showDeletionDialog:mt,setDeleteSessionConfirm:ae,deleteSessionConfirm:L,setEditingId:p,setEditTitle:w,editingId:b,editTitle:h}),ad=l.useCallback(()=>{if(!J)return;const{scopeKey:N,folderId:Z}=J;le(null),Ve(N,Z)},[J,Ve]),Vr=l.useCallback(()=>{qs.requestDirectoryDialog()},[]),ld=l.useCallback(N=>{A(Z=>{const ne=xh(Z,N);try{y.setItem(Wa,JSON.stringify(Array.from(ne)))}catch{}return ne})},[y]),Di=l.useCallback((N,Z)=>{if(!N)return null;Z&&Ge.has(Z)&&bt(Z);const ne=Lt(N,"New folder",Z);return M(ne.id),W(ne.name),ne},[Ge,bt,Lt]),Ns=Rt(Qc),cd=Rt(Jc),dd=Rt(Xc),ud=Rt(Zc),fd=Rt(ed),hd=Rt(td),pd=Rt(nd),md=Rt(sd),gd=Rt(rd),bd=Rt(od),Yr=Rt(Di),Ri=l.useCallback((N,Z)=>{q(ne=>{const Le=new Map(ne);return Le.set(N,Z+7),Le})},[]),ir=l.useCallback(N=>{q(Z=>{if(!Z.has(N))return Z;const ne=new Map(Z);return ne.delete(N),ne})},[]),Pi=l.useCallback(N=>{q(Z=>{let ne=!1;const Le=new Map(Z),Oe=`${N}:`;for(const et of Le.keys())et.startsWith(Oe)&&(Le.delete(et),ne=!0);return ne?Le:Z})},[]),Qr=l.useCallback(N=>{ke.current=Date.now()+150,Pi(N),v(Z=>{const ne=new Set(Z);ne.has(N)?ne.delete(N):ne.add(N);try{y.setItem(za,JSON.stringify(Array.from(ne)))}catch{}return Dt(ne),ne})},[Pi,y,Dt]),Ti=l.useRef(null);l.useEffect(()=>{const N=Ti.current;Ti.current=Se,Qe==="folder"&&(!N||!Se||N===Se||j.has(Se)&&Qr(Se))},[Se,j,Qe,Qr]);const Rn=l.useMemo(()=>he.map(N=>({...N,normalizedPath:Re(N.path)})).filter(N=>!!N.normalizedPath),[he]),xd=l.useMemo(()=>Rn.map(N=>N.normalizedPath),[Rn]),Mi=pf(e?xd:go);Wm({enabled:e,normalizedProjects:Rn,gitRepoStatus:Mi,setProjectRepoStatus:z,setProjectRootBranches:Be});const yd=l.useMemo(()=>Xm(it,Rn,tt,yt),[yt,tt,Rn,it]);Vm({enabled:e,hasAuthoritativeGlobalSessions:on,sessions:Hn});const{getSessionsForProject:wd,getArchivedSessionsForProject:Fi}=Hm({ownership:yd}),Jr=l.useRef(!1);Se&&P.has(Se)&&(Jr.current=!!P.get(Se));const Xr=ct(N=>N.manualProjectOrder),Li=l.useRef(new Set),ar=yh(Li.current,S,"project");Li.current=ar;const Zr={isVisible:e,mobileVariant:t,onSessionSelected:s,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:a,isTablet:ce,catalogSessions:xt,archivedSessions:yt,projects:he,activeProjectId:Se,manualProjectOrder:Xr,currentDirectory:ve,availableWorktreesByProject:tt,pinnedSessionIds:X,sessionOrderRanks:ee,foldersMap:ut,collapsedFolderIds:Ge,gitBranches:Qt,gitRepoStatus:Mi,updateStore:ot,projectRepoStatus:P,projectRootBranches:re,resolvedWorktreeTopologyKey:ks,unresolvedWorktreeProjectPaths:O,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:b,editTitle:h,editingProjectDialogId:x,expandedParents:S,collapsedProjects:j,visibleSessionCountByGroup:K,updateDialogOpen:G,openSidebarMenuKey:D,renamingFolderId:I,renameFolderDraft:H,deleteSessionConfirm:L,deleteFolderConfirm:J,bulkDeleteConfirm:B,collapsedGroups:me},Oi=l.useRef(null),Bi=Oi.current;if(Bi){let N=!1;for(const Z of Object.keys(Zr))Object.is(Bi[Z],Zr[Z])||(Wt(`ui.session_sidebar.source.${Z}`),N=!0);N||Wt("ui.session_sidebar.source.parent_or_context")}Oi.current=Zr;const _i=l.useMemo(()=>{const N=new Map(Xr.map((Z,ne)=>[Z,ne]));return[...Rn].sort((Z,ne)=>(N.get(Z.id)??1/0)-(N.get(ne.id)??1/0))},[Xr,Rn]),{projectSections:xn,groupSearchDataByGroup:zi,sectionsForRender:vd,flatSectionsForRender:eo,searchMatchCount:Sd}=xm({normalizedProjects:_i,getSessionsForProject:wd,getArchivedSessionsForProject:Fi,availableWorktreesByProject:tt,projectRepoStatus:P,projectRootBranches:re,lastRepoStatus:Jr.current,buildGroupedSessions:vt,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,filterSessionNodesForSearch:Je,buildGroupSearchText:ft,foldersMap:ut,alwaysIncludeArchived:Qe==="timeline"}),Is=l.useMemo(()=>{const ne=(De||Qe==="timeline"?[...it,...yt]:it).filter(Oe=>Ys(is(Oe),Q));if(ne.length===0)return null;const Le=vt(ne,"~",[],null,!1).map(Oe=>De?{...Oe,sessions:Je(Oe.sessions,Ne)}:Oe).filter(Oe=>Oe.sessions.length>0);return Le.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Le}},[yt,vt,Je,De,Q,Ne,it,Qe]),jd=l.useCallback(N=>Ys(is(N),Q),[Q]),kd=Im({viewMode:Qe,enabled:!De&&!a,projects:_i,archivedSessions:yt,getArchivedSessionsForProject:Fi,isGlobalSession:jd,buildGroupedSessions:vt,availableWorktreesByProject:tt,projectRepoStatus:P,projectRootBranches:re,lastRepoStatus:Jr.current,selectedSpaceId:k,selectedWorktreePath:E,homeDirectory:Q}),Cd=l.useMemo(()=>{if(!De||!Is)return 0;const N=Z=>Z.reduce((ne,Le)=>ne+1+N(Le.children),0);return Is.groups.reduce((Z,ne)=>Z+N(ne.sessions),0)},[Is,De]),Ad=l.useMemo(()=>n.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[n.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),n.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Nd}=gm(V),{sectionsForSidebarRender:Id,filteredSectionsForSidebarRender:Ed,totalSessionCount:Dd,sessionCountByProject:Rd,hasActiveSessionByProject:Pd,activeDirectoriesByProject:Es,hasUnseenByProject:Td}=Cm({projectSections:xn,flatSectionsForRender:eo,sectionsForRender:vd,selectedSpaceId:k,selectedWorktreePath:E,homeDirectory:Q,activeSessionIdSet:pe,unreadSessionIdSet:be}),to=l.useCallback(N=>{if(Jn.getState().selectSpace(N),!N)return;Ue(N);const Z=xn.find(Oe=>Oe.project.id===N),ne=Z?.groups.find(Oe=>Oe.isMain),Le=ne?.sessions[0]?.session;Le?Ns(Le.id,ne?.directory??Z?.project.normalizedPath??null,{keepPanelOpen:!0}):Z&&Ct({selectedProjectId:N,directoryOverride:Z.project.normalizedPath})},[Ct,xn,Ue,Ns]),Md=t?"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",Fd=t?"size-5":"size-4",lr=Rt((N,Z=0,ne,Le,Oe=!1,et,yn="project",Qn)=>n.jsx(qb,{node:N,depth:Z,groupDirectory:ne,projectId:Le,archivedBucket:Oe,pinnedSessionIds:X,expandedParents:ar,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,editingId:b,setEditingId:p,editTitle:h,setEditTitle:w,handleSaveEdit:dd,handleCancelEdit:ud,toggleParent:ld,handleSessionSelect:Ns,handleSessionDoubleClick:cd,togglePinnedSession:ze,handleShareSession:fd,copiedSessionId:Yc,handleCopyShareUrl:hd,handleCopySessionId:pd,handleUnshareSession:md,openSidebarMenuKey:D,setOpenSidebarMenuKey:T,renamingFolderId:I,getFoldersForScope:sn,getSessionFolderId:rt,removeSessionFromFolder:It,addSessionToFolder:rn,createFolderAndStartRename:Yr,handleDeleteSession:gd,handleRestoreSession:bd,mobileVariant:t,alwaysShowActions:ye,allowQuickArchiveAction:$e,renderSessionNode:lr,secondaryMeta:et,renderContext:yn,subtreeContainsEditing:Qn?.subtreeContainsEditing??ix,menuOpenSessionId:Qn?.menuOpenSessionId??null,nodeStructureKey:Qn?.nodeStructureKey??"",childRenderExtrasFor:Qn?.childRenderExtrasFor})),Ld=l.useMemo(()=>{const N=new Map;return eo.forEach(Z=>{const ne=Z.groups[0];ne?.folderScopes&&ne.folderScopes.length>0&&N.set(Z.project.id,ne.folderScopes)}),N},[eo]),Od=l.useCallback((N,Z)=>{const ne=[];return Z.forEach(Le=>{ne.push(Le.directory),Le.folderScopes?.forEach(Oe=>ne.push(Oe.directory))}),n.jsx(ex,{directories:ne})},[]),Ui=l.useCallback(N=>{ir(N),Pe(Z=>{const ne=new Set(Z);return ne.has(N)?ne.delete(N):ne.add(N),ne})},[ir]),Bd=l.useCallback((N,Z,ne,Le,Oe,et)=>n.jsx(_g,{group:N,groupKey:Z,projectId:ne,hideGroupLabel:Le,dragHandleProps:Oe,compactBodyPadding:et,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,groupSearchDataByGroup:zi,visibleSessionCount:K.get(Z),collapsedGroups:me,hideDirectoryControls:i,collapsedFolderIds:Ge,toggleFolderCollapse:bt,renameFolder:Ot,deleteFolder:Ve,showDeletionDialog:mt,setDeleteFolderConfirm:le,renderSessionNode:lr,showMoreGroupSessions:Ri,resetGroupSessionLimit:ir,mobileVariant:t,alwaysShowActions:ye,activeProjectId:Se,setActiveProjectIdOnly:Ue,setActiveMainTab:se,setSessionSwitcherOpen:Xe,openNewSessionDraft:Ct,addSessionToFolder:rn,createFolderAndStartRename:Yr,renamingFolderId:I,renameFolderDraft:H,setRenameFolderDraft:W,setRenamingFolderId:M,pinnedSessionIds:X,expandedParents:ar,sessionOrderIndex:de,editingId:b,editTitle:h,openSidebarMenuKey:D,activeActivitySessionIds:pe,unreadActivitySessionIds:be,onToggleCollapsedGroup:Ui}),[De,Ne,zi,K,me,i,Ge,bt,Ot,Ve,mt,lr,Ri,ir,t,ye,Se,Ue,se,Xe,Ct,rn,Yr,I,H,X,ar,de,b,h,D,pe,be,Ui]),$i=!!(I||b||x),Ki=l.useRef(it);Ki.current=it;const _d=l.useCallback(N=>Ki.current.find(Z=>Z.id===N)?.directory??null,[]),{selectionModeEnabled:no,hasSelection:Wi,selectedIdsSize:zd,bulkScopeIsArchived:Ud,derivedSelectionScope:$d,bulkScopeFolders:Kd,bulkCanRemoveFromFolder:Wd,handleToggleSelectionMode:Hd,handleExitSelectionMode:Gd,handleBulkMoveToFolder:qd,handleBulkCreateFolderAndMove:Vd,handleBulkRemoveFromFolder:Yd,handleBulkDelete:Qd,handleBulkRestore:Jd,confirmBulkDelete:Xd}=sx({isInlineEditing:$i,showDeletionDialog:mt,foldersMap:ut,folderScopesByProject:Ld,addSessionsToFolder:An,removeSessionsFromFolders:Kn,createFolderAndStartRename:Di,resolveSessionDirectory:_d,unarchiveSessions:Vc,deleteSessions:Ei,setBulkDeleteConfirm:$}),Hi=l.useCallback(()=>{ue.getState().closeMainSurfaces(),se("chat"),t&&Xe(!1),wt(),r?.()},[t,r,wt,se,Xe]),Zd=l.useCallback((N,Z)=>{const ne=he.find(et=>et.id===N);if(!ne)return;const Le=Re(Z.path)?.toLowerCase(),Oe=!!(Le&&Es.get(N)?.has(Le));Y({projectId:N,projectPath:ne.path,worktree:Z,hasActiveSession:Oe})},[Es,he]),eu=l.useCallback(async({force:N})=>{const Z=Ie;if(!Z)return;const ne=Re(Z.worktree.path)?.toLowerCase();if(!!(ne&&Es.get(Z.projectId)?.has(ne))){Y({...Z,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!Bt.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Bt.deleteGitWorktree(Z.projectPath,{directory:Z.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let et=await an(Z.projectPath,Bt,{force:!0});const yn=Re(Z.worktree.path);et!==null&&yn!==null&&et.some(nu=>Re(nu.path)===yn)&&(et=await an(Z.projectPath,Bt,{force:!0}));const Qn=yn!==null&&Re(ve)===yn,tu=yn!==null&&k===Z.projectId&&Re(E)===yn;(Qn||tu)&&to(Z.projectId),Y(null),et===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(Oe){const et=Oe instanceof Error?Oe.message:"Try again.";oe.error("Failed to close worktree.",{description:et})}},[Es,Ie,ve,Bt,to,an,k,E]);return n.jsx(mf,{delay:400,closeDelay:150,timeout:600,children:n.jsxs("div",{ref:m,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[n.jsx(Dm,{projectSections:xn,activeProjectId:Se,initialActiveSessionByProject:xe,persistActiveSessionByProject:te,handleSessionSelect:Ns,mobileVariant:t,openNewSessionDraft:wt,setActiveMainTab:se,setSessionSwitcherOpen:Xe}),!i&&!t?n.jsx(Ug,{onNewSession:Hi,showSidebarToggle:!0}):null,n.jsx(zg,{hideDirectoryControls:i,handleOpenDirectoryDialog:Vr,onOpenArchive:()=>{t&&Xe(!1),Yt(!0)},onOpenSettings:t?Ii:void 0,onOpenInstances:t?Yn?.openInstances:void 0,instanceLabel:t?Yn?.instanceLabel:void 0,onOpenUpdate:t?Yn?.openUpdate:void 0,headerActionIconClass:Fd,headerActionButtonClass:Md,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:g,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:De,searchMatchCount:Sd+(Qe!=="workspace"||k===null?Cd:0),selectionModeEnabled:no,onToggleSelectionMode:Hd,mobileVariant:t,onClose:t?()=>Xe(!1):void 0}),gn==="error"||gn==="unavailable"?n.jsx("div",{role:"alert",className:"mx-2 mb-2 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-2 text-xs text-foreground",children:"Unable to reach server"}):null,!i&&xn.length>0&&Qe==="workspace"?n.jsx(Wg,{projects:xn.map(N=>N.project),selectedProjectId:k,selectedWorktreePath:E,worktreesByProject:tt,worktreeErrorsByProject:ln,onSelectProject:to,onSelectWorktree:(N,Z)=>{Jn.getState().selectWorktree(N,Z),Ue(N);const Oe=xn.find(et=>et.project.id===N)?.groups.find(et=>Re(et.directory)===Re(Z))?.sessions[0]?.session;Oe?Ns(Oe.id,Z,{keepPanelOpen:!0}):Ct({selectedProjectId:N,directoryOverride:Z})},onCloseWorktree:Zd,onOpenDirectoryDialog:Vr,onOpenProjectEditDialog:C,onRemoveProject:qe,totalSessionCount:Dd,getSessionCountForProject:N=>Rd.get(N)??0,hasActiveSessionByProject:Pd,activeDirectoriesByProject:Es,hasUnseenByProject:Td,homeDirectory:Q,mobileVariant:t}):null,n.jsx(bb,{viewMode:Qe,timelineBoundaries:jt,onOpenDirectoryDialog:Vr,stickyFolderHeaders:Ee,sectionsForRender:Qe==="workspace"?Ed:Id,allFoldersOnlySection:Qe==="workspace"?k===null?Is:null:Is,isAllFoldersView:Qe==="workspace"?k===null:Qe==="timeline",projectSections:xn,activeProjectId:Se,showOnlyMainWorkspace:a,hasSessionSearchQuery:De,emptyState:qn,searchEmptyState:Ad,pinnedSessionIds:X,archivedShelfItems:kd,renderSessionNode:lr,renderGroupSessions:Bd,homeDirectory:Q,collapsedProjects:j,hideDirectoryControls:i,projectRepoStatus:P,mobileVariant:t,alwaysShowActions:ye,toggleProject:Qr,setActiveProjectIdOnly:Ue,setActiveMainTab:se,setSessionSwitcherOpen:Xe,openNewSessionDraft:Ct,openProjectEditDialog:C,removeProject:qe,reorderProjects:ge,getOrderedGroups:Nd,setGroupOrderByProject:fe,renderProjectStatusIndicator:Od,openSidebarMenuKey:D,setOpenSidebarMenuKey:T,isInlineEditing:$i}),t&&!(no&&Wi)?n.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-2",children:[n.jsx(oc,{variant:"mobile"}),n.jsxs(Ae,{type:"button",variant:"default",size:"lg",className:"w-full",onClick:Hi,children:[n.jsx(R,{name:"chat-new",className:"size-4"}),"New session"]})]}):null,no&&Wi?n.jsx(tx,{selectedCount:zd,scopeKey:$d,scopeFolders:Kd,archivedBucket:Ud,onMoveToFolder:qd,onCreateFolderAndMove:Vd,onRemoveFromFolder:Yd,canRemoveFromFolder:Wd,onRestore:Jd,onDelete:Qd,onDone:Gd}):null,t?null:n.jsx(Hg,{onOpenSettings:Ii,onOpenShortcuts:pt,onOpenAbout:()=>{st("about"),_e(!0)},onOpenUpdate:Vn,showRuntimeButtons:!0,showUpdateButton:Hc}),n.jsx(Zb,{updateDialogOpen:G,setUpdateDialogOpen:F,updateStore:ot,editingProject:As,setEditingProjectDialogId:C,handleSaveProjectEdit:or,deleteSessionConfirm:L,setDeleteSessionConfirm:ae,showDeletionDialog:mt,setShowDeletionDialog:Nt,confirmDeleteSession:id,deleteFolderConfirm:J,setDeleteFolderConfirm:le,confirmDeleteFolder:ad,closeWorktreeConfirm:Ie,setCloseWorktreeConfirm:Y,confirmCloseWorktree:eu,bulkDeleteConfirm:B,setBulkDeleteConfirm:$,confirmBulkDelete:Xd})]})})},iv=l.memo(ax),Ha=6,Pt=.18,Ls=1.2,Os=.38,kr=48,lx=(e,t)=>e==="left"?t<0:t>0,av=(e,t,s)=>Math.min(1,Math.max(0,e==="left"?1+t/s:1-t/s)),lv=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,Ga=(e,t,s,r)=>e==="left"?t?Math.min(1,Math.max(0,1+s/r)):Math.min(1,Math.max(0,s/r)):t?Math.min(1,Math.max(0,1-s/r)):Math.min(1,Math.max(0,-s/r)),cv=e=>{const{side:t,dx:s,dy:r,dt:o,progress:i,isDragging:a}=e,c=s/Math.max(1,o);if(a){const d=t==="left"?c<-Pt:c>Pt,u=t==="left"?c>Pt:c<-Pt;return d||!u&&i<Os}return Math.abs(s)>=kr&&Math.abs(r)<=Math.abs(s)*Ls&&lx(t,s)},cx=e=>{const{side:t,isOpenAtStart:s,dx:r,dt:o,progress:i}=e,a=r/Math.max(1,o);return t==="left"?s?a<-Pt?!1:a>Pt?!0:i>Os:a>Pt?!0:a<-Pt?!1:i>Os:s?a>Pt?!1:a<-Pt?!0:i>Os:a<-Pt?!0:a>Pt?!1:i>Os},dx='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',ux=(e,t,s)=>{if(!(e instanceof Element))return!1;if(s?.excludeInteractive??!0){const i=e.closest(dx);if(i&&t.contains(i))return!0}else{const i=e.closest("[data-no-drawer-swipe]");if(i&&t.contains(i))return!0}let o=e;for(;o&&o!==t;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const i=getComputedStyle(o).overflowX;if(i==="auto"||i==="scroll")return!0}o=o.parentElement}return!1},Cr=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),hi=512*1024,fx=new TextEncoder,hx=new TextDecoder,bo=e=>{const t=fx.encode(e);if(t.byteLength<=hi)return{text:e,byteLength:t.byteLength};let s=t.byteLength-hi;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;const r=t.subarray(s);return{text:hx.decode(r),byteLength:r.byteLength}},Zn=(e,t)=>`${e}\0${t}`,xo=(e,t)=>{let s=null;for(const r of e.keys())t(r)&&(s??=new Map(e),s.delete(r));return s},px="terminal-store";let qa=!1,Va=0;const xr=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Va+=1,`tab-${Date.now().toString(36)}-${Va.toString(36)}`),yo=e=>typeof e=="object"&&e!==null,mx=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const s=Number(t[1]);return Number.isFinite(s)?s:null};function at(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const gx=/^Terminal(?: (\d+))?$/,bx=e=>{let t=0;for(const s of e){const r=gx.exec(s.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},wo=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),vo=e=>({tabs:[e],activeTabId:e.id}),Ut=(e,t)=>e.tabs.findIndex(s=>s.id===t);let So=null,jo=null;const xx=e=>{if(jo&&So?.sessions===e.sessions&&So.nextTabId===e.nextTabId)return jo;const t={sessions:Array.from(e.sessions.entries()).map(([s,r])=>[s,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return So={sessions:e.sessions,nextTabId:e.nextTabId},jo=t,t},yx=()=>{const e=wh(()=>Yf());if(!e)return;let t=null;return{getItem:s=>e.getItem(s),setItem:(s,r)=>{if(r.state!==t)return t=r.state,e.setItem(s,r)},removeItem:s=>(t=null,e.removeItem(s))}},we=$n()(zr(zl((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:s=>{const r=at(s);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),a=xr(),c=wo(a,"Terminal");return i.set(r,vo(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:s=>{const r=at(s);return t().sessions.get(r)},getActiveTab:s=>{const r=at(s),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(a=>a.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(s,r)=>t().buffers.get(Zn(at(s),r))??Cr,createTab:s=>{const r=at(s);if(!r)return"tab-invalid";const o=xr();return e(i=>{const a=new Map(i.sessions),c=a.get(r),d=i.nextTabId+1,u=bx(c?.tabs??[]),f=wo(o,u);return c?a.set(r,{...c,tabs:[...c.tabs,f]}):a.set(r,vo(f)),{sessions:a,nextTabId:d}}),o},setActiveTab:(s,r)=>{const o=at(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);return!c||c.activeTabId===r||Ut(c,r)<0?i:(a.set(o,{...c,activeTabId:r}),{sessions:a})})},setTabLabel:(s,r,o)=>{const i=at(s),a=o.trim();a&&e(c=>{const d=new Map(c.sessions),u=d.get(i);if(!u)return c;const f=Ut(u,r);if(f<0||u.tabs[f]?.label===a)return c;const m=[...u.tabs];return m[f]={...m[f],label:a},d.set(i,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return a;const m=[...d.tabs];return m[u]={...m[u],iconKey:f},c.set(i,{...d,tabs:m}),{sessions:c}})},closeTab:(s,r)=>{const o=at(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=Ut(c,r);if(d<0)return i;const u=c.tabs.filter(h=>h.id!==r),f=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,h])=>!(h.directory===o&&h.tabId===r))),m=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,g=Zn(o,r),b=i.buffers.has(g)?xo(i.buffers,h=>h===g):null;if(u.length===0){const h=xr(),w=wo(h,"Terminal");return a.set(o,vo(w)),{sessions:a,nextTabId:i.nextTabId+1,...b?{buffers:b}:{},...m?{projectActionRuns:f}:{}}}let p=c.activeTabId;return c.activeTabId===r&&(p=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),a.set(o,{...c,tabs:u,activeTabId:p}),{sessions:a,...b?{buffers:b}:{},...m?{projectActionRuns:f}:{}}})},setTabSessionId:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=d.tabs[u],m=o!==null&&f.terminalSessionId!==o,g=o?"running":f.terminalSessionId?"exited":f.lifecycle,b={...f,terminalSessionId:o,lifecycle:g,isConnecting:!1},p=Zn(i,r),h=m&&a.buffers.has(p)?xo(a.buffers,x=>x===p):null,w=[...d.tabs];return w[u]=b,c.set(i,{...d,tabs:w}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(i,{...d,tabs:f}),{sessions:c}})},setConnecting:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Ut(d,r);if(u<0)return a;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(i,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(s,r,o,i)=>{const a=at(s);e(c=>{const d=c.sessions.get(a);if(!d||Ut(d,r)<0)return c;const u=Zn(a,r),f=c.buffers.get(u)??Cr;if(f.lastSequence>i)return c;const m=bo(o);if(f.lastSequence===i&&f.byteLength===m.byteLength&&f.chunks.map(p=>p.data).join("")===m.text)return c;const g=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:m.text?[{id:g,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:i}),{buffers:b,nextChunkId:m.text?g+1:g}})},appendToBuffer:(s,r,o,i,a)=>{if(!o)return;const c=at(s);e(d=>{const u=d.sessions.get(c);if(!u||Ut(u,r)<0)return d;const f=Zn(c,r),m=d.buffers.get(f)??Cr;if(i!==void 0&&i<=m.lastSequence)return d;const g=d.nextChunkId,b=bo(o),p=a!==void 0&&a!==o?bo(a).text:void 0,h={id:g,data:b.text,...p!==void 0?{replayData:p}:{},byteLength:b.byteLength},w=[...m.chunks,h];let x=m.byteLength+h.byteLength;for(;x>hi&&w.length>1;){const S=w.shift();if(!S)break;x-=S.byteLength}const C=new Map(d.buffers);return C.set(f,{chunks:w,byteLength:x,lastSequence:i??m.lastSequence}),{buffers:C,nextChunkId:g+1}})},setTabPreviewUrl:(s,r,o,i={})=>{const a=at(s);e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=Ut(u,r);if(f<0)return c;const m=u.tabs[f],g=i.autoOpened??m.previewAutoOpened,b=i.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===g&&m.previewUrlLocked===b)return c;const p=[...u.tabs];return p[f]={...m,previewUrl:o,previewAutoOpened:g,previewUrlLocked:b},d.set(a,{...u,tabs:p}),{sessions:d}})},markPreviewAutoOpened:(s,r)=>{const o=at(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=Ut(c,r);if(d<0)return i;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return i;const f=[...c.tabs];return f[d]={...u,previewAutoOpened:!0},a.set(o,{...c,tabs:f}),{sessions:a}})},setProjectActionRun:s=>{e(r=>{const o=r.projectActionRuns[s.key];return o&&o.directory===s.directory&&o.actionId===s.actionId&&o.tabId===s.tabId&&o.sessionId===s.sessionId&&o.status===s.status?r:{projectActionRuns:{...r.projectActionRuns,[s.key]:s}}})},updateProjectActionRunStatus:(s,r)=>{e(o=>{const i=o.projectActionRuns[s];return!i||i.status===r?o:{projectActionRuns:{...o.projectActionRuns,[s]:{...i,status:r}}}})},removeProjectActionRun:s=>{e(r=>{if(!r.projectActionRuns[s])return r;const o={...r.projectActionRuns};return delete o[s],{projectActionRuns:o}})},removeDirectory:s=>{const r=at(s);e(o=>{const i=new Map(o.sessions);i.delete(r);const a=Zn(r,""),c=xo(o.buffers,u=>u.startsWith(a)),d=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:i,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:px,storage:yx(),partialize:xx,merge:(e,t)=>{if(!yo(e))return t;const s=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of s){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!yo(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],m=[],g=new Map;for(const w of f){if(!yo(w))continue;const x=typeof w.id=="string"?w.id:null;if(!x)continue;const C=mx(x);C!==null&&(o=Math.max(o,C));const S=C===null?x:xr();g.set(x,S),m.push({id:S,label:typeof w.label=="string"?w.label:"Terminal",iconKey:typeof w.iconKey=="string"?w.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof w.createdAt=="number"?w.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const b=typeof u.activeTabId=="string"?u.activeTabId:null,p=b?g.get(b)??b:null,h=p?m.some(w=>w.id===p):!1;r.set(d,{tabs:m,activeTabId:h?p:m[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,a=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:a,hasHydrated:!0}}})));if(typeof window<"u"&&!qa){qa=!0;const e=we.persist,t=()=>{we.getState().hasHydrated||we.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}function wx(e){const{colors:t}=e,s=t.syntax.base;return{background:t.surface.background,foreground:s.foreground,cursor:t.interactive.cursor,cursorAccent:t.surface.background,selectionBackground:t.interactive.selection,selectionForeground:t.interactive.selectionForeground,selectionInactiveBackground:t.interactive.selection+"50",black:t.surface.muted,red:t.status.error,green:t.status.success,yellow:t.status.warning,blue:s.function,magenta:s.keyword,cyan:s.type,white:s.foreground,brightBlack:s.comment,brightRed:t.status.error,brightGreen:t.status.success,brightYellow:t.status.warning,brightBlue:s.function,brightMagenta:s.keyword,brightCyan:s.type,brightWhite:t.surface.elevatedForeground}}function ko(e,t,s){const o=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",cursorInactiveStyle:"none",fontSize:t,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:s.background,foreground:s.foreground,cursor:s.cursor,cursorAccent:s.cursorAccent,selectionBackground:s.selectionBackground,selectionForeground:s.selectionForeground,selectionInactiveBackground:s.selectionInactiveBackground,black:s.black,red:s.red,green:s.green,yellow:s.yellow,blue:s.blue,magenta:s.magenta,cyan:s.cyan,white:s.white,brightBlack:s.brightBlack,brightRed:s.brightRed,brightGreen:s.brightGreen,brightYellow:s.brightYellow,brightBlue:s.brightBlue,brightMagenta:s.brightMagenta,brightCyan:s.brightCyan,brightWhite:s.brightWhite}}}const vx=(e,t)=>{const s=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(s)?"mac":"other"},Sx=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),jx=(e,t,s)=>{if(e.altKey)return null;const r=Sx(e);return t==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?s?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?s?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?s?"copy":"ignore":null},Bs=e=>typeof e=="string"&&e.trim().length>0;async function Ya(e){return Bs(e)?(await fn(e)).ok:!1}async function kx(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const Cx=(e,t,s,r,o)=>{if(s.width<=0||s.height<=0||r<=0||o<=0)return null;const i=Math.floor((e-s.left)/s.width*r),a=Math.floor((t-s.top)/s.height*o);return{column:Math.max(0,Math.min(r-1,i)),row:Math.max(0,Math.min(o-1,a))}},Ax=(e,t)=>{const s=Math.max(0,Math.min(e.length-1,t)),r=a=>!!(a&&!/^\s+$/u.test(a));if(!r(e[s]))return{startColumn:s,endColumn:s};let o=s,i=s;for(;o>0&&r(e[o-1]);)o-=1;for(;i<e.length-1&&r(e[i+1]);)i+=1;return{startColumn:o,endColumn:i}};let Nx=null;const Ix=()=>Nx??=Promise.all([ht(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),ht(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),Ex=2e3,Dx=()=>{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(t=>setTimeout(t,Ex))]).then(()=>{})},Rx=(e,t,s)=>{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=`${s}px ${t}`;const o=r.measureText("M"),i=Math.ceil(o.width),a=Math.ceil((o.actualBoundingBoxAscent||s*.8)+(o.actualBoundingBoxDescent||s*.2))+2;if(i<1||a<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/i)),rows:Math.max(1,Math.floor((e.clientHeight-u)/a))}},Uc=l.forwardRef(({sessionKey:e,chunks:t,onInput:s,onResize:r,theme:o,fontFamily:i,fontSize:a,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},m)=>{const g=l.useRef(null),b=l.useRef(null),p=l.useRef(null),h=l.useRef(s),w=l.useRef(r),x=l.useRef(o),C=l.useRef(i),S=l.useRef(a),A=l.useRef(null),y=l.useRef(null),j=l.useRef(null),v=l.useRef(""),k=l.useRef(!1),E=l.useRef(0),P=l.useRef(f),z=l.useRef(!1),[K,q]=l.useState(0),[G,F]=l.useState(0),[D,T]=l.useState(!1),[I,M]=l.useState(!1);h.current=s,w.current=r,P.current=f,x.current=o,C.current=i,S.current=a,l.useLayoutEffect(()=>{const Y=g.current;if(!Y)return;const B=Rx(Y,i,a);y.current=B,B&&w.current(B.cols,B.rows)},[i,a]);const H=l.useCallback(()=>{const Y=g.current,B=b.current;if(!Y||!B||!p.current||!P.current)return;const $=Y.getBoundingClientRect();if(!($.width<24||$.height<24))try{p.current.fit();const X={cols:B.cols,rows:B.rows};(!A.current||A.current.cols!==X.cols||A.current.rows!==X.rows)&&(A.current=X,w.current(X.cols,X.rows)),z.current||(z.current=!0,q(ee=>ee+1))}catch{}},[]),W=l.useCallback(()=>{if(k.current||!v.current||!b.current)return;const Y=b.current,B=v.current;if(v.current="",!B)return;k.current=!0;const $=E.current;Y.write(B,()=>{b.current!==Y||E.current!==$||(k.current=!1,v.current&&W())})},[]),L=l.useCallback(()=>{j.current=null,v.current="",k.current=!1,E.current+=1;const Y=b.current;if(!Y){F(B=>B+1);return}try{Y.reset()}catch{F(B=>B+1)}},[]),ae=l.useCallback(Y=>{Y?.preventDefault(),M(Bs(b.current?.getSelection())),T(!0)},[]),J=l.useCallback(Y=>{Y.stopPropagation();const B=b.current,$=B?.getSelection()??"";B?.focus(),Bs($)&&Ya($)},[]),le=l.useCallback(Y=>{Y.stopPropagation();const B=b.current;B?.focus(),kx().then($=>{$&&b.current===B&&B&&B.paste($)})},[]),Ie=l.useCallback(Y=>{Y.stopPropagation();const B=b.current;B?.focus();try{B?.selectAll()}catch{}M(Bs(B?.getSelection()))},[]);return l.useEffect(()=>{const Y=g.current;if(!Y)return;let B=!1,$=null,X=null,ee=null,ie=null,Ce=[];const pe=()=>{$&&P.current&&($.options.cursorBlink=!0)},je=me=>{me.relatedTarget instanceof Node&&Y.contains(me.relatedTarget)||$&&($.options.cursorBlink=!1)},be=()=>{$&&P.current&&Y.contains(document.activeElement)&&($.options.cursorBlink=!0)},ze=()=>{$&&($.options.cursorBlink=!1)};return Y.addEventListener("focusin",pe),Y.addEventListener("focusout",je),window.addEventListener("focus",be),window.addEventListener("blur",ze),Promise.all([Ix(),Dx()]).then(([{Xterm:me,Fit:Pe}])=>{if(B)return;const V=x.current,fe=C.current,xe=S.current;$=new me.Terminal({...ko(fe,xe,V),...y.current??{}});const te=new Pe.FitAddon;$.loadAddon(te),$.open(Y),b.current=$,p.current=te;const re=typeof navigator>"u"?"other":vx(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Be=$;$.attachCustomKeyEventHandler(ke=>{if(ke.type!=="keydown")return!0;const Q=Be.getSelection(),ve=jx({key:ke.key,code:ke.code,ctrlKey:ke.ctrlKey,shiftKey:ke.shiftKey,metaKey:ke.metaKey,altKey:ke.altKey},re,Bs(Q));return ve==="copy"?(Ya(Q),!1):ve!=="ignore"}),Ce=[$.onData(ke=>h.current(ke))],X=new ResizeObserver(()=>{ee&&clearTimeout(ee),ee=setTimeout(H,80)}),X.observe(Y),H(),ie=requestAnimationFrame(H)}),()=>{B=!0;const me=document.activeElement;me instanceof HTMLElement&&Y.contains(me)&&(me.blur(),window.Capacitor?.getPlatform?.()==="android"&&ht(async()=>{const{Keyboard:V}=await import("./vendor-capacitor-keyboard-CgrHt8iN.js");return{Keyboard:V}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:V})=>V.hide()).catch(()=>{})),X?.disconnect(),ee&&clearTimeout(ee),ie!==null&&cancelAnimationFrame(ie),Y.removeEventListener("focusin",pe),Y.removeEventListener("focusout",je),window.removeEventListener("focus",be),window.removeEventListener("blur",ze),Ce.forEach(Pe=>Pe.dispose()),$?.dispose(),b.current=null,p.current=null,A.current=null,j.current=null,v.current="",k.current=!1,E.current+=1,z.current=!1}},[H,G]),l.useEffect(()=>{const Y=b.current;Y&&(Y.options.theme=ko(i,a,o).theme,Y.options.fontFamily=ko(i,a,o).fontFamily,Y.options.fontSize=a)},[i,a,o]),l.useEffect(()=>{const Y=b.current,B=g.current;!Y||!B||(Y.options.cursorBlink=f&&document.hasFocus()&&B.contains(document.activeElement))},[f,K]),l.useEffect(()=>{if(!b.current)return;if(t.length===0){j.current!==null&&L();return}const B=j.current;let $=-1;if(B!==null){for(let ie=t.length-1;ie>=0;ie-=1){const Ce=t[ie].id;if(Ce===B){$=ie;break}if(Ce<B)break}if($<0){L();return}}const X=$<0,ee=$>=0?t.slice($+1):t;v.current+=ee.map(ie=>X?ie.replayData??ie.data:ie.data).join(""),j.current=t.at(-1)?.id??null,W()},[t,W,K,L]),l.useEffect(()=>{if(!u||!f)return;const Y=requestAnimationFrame(()=>b.current?.focus());return()=>cancelAnimationFrame(Y)},[u,f,K,e]),l.useEffect(()=>{const Y=g.current,B=b.current;if(!d||!Y||!B)return;let $=null,X=null,ee="idle",ie=0,Ce=0,pe=0,je=0,be=null;const ze=Math.max(12,a+2),me=()=>{window.Capacitor?.getPlatform?.()==="android"&&ht(async()=>{const{Keyboard:ve}=await import("./vendor-capacitor-keyboard-CgrHt8iN.js");return{Keyboard:ve}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:ve})=>ve.show()).catch(()=>{})},Pe=()=>{X&&(clearTimeout(X),X=null)},V=(Q,ve)=>{const he=Y.querySelector("canvas");return he?Cx(Q,ve,he.getBoundingClientRect(),B.cols,B.rows):null},fe=(Q,ve)=>{const he=Y.querySelector("canvas");if(!he)return;const Se=he.getBoundingClientRect(),qe=Se.left+(ve.column+.5)/B.cols*Se.width,Ue=Se.top+(ve.row+.5)/B.rows*Se.height;he.dispatchEvent(new MouseEvent(Q,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:qe,clientY:Ue}))},xe=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},te=Q=>{Q.pointerType!=="touch"||$!==null||($=Q.pointerId,ee="pending",ie=Q.clientX,Ce=Q.clientY,pe=Q.clientY,je=0,be=null,Y.setPointerCapture(Q.pointerId),X=setTimeout(()=>{if(X=null,$!==Q.pointerId||ee!=="pending")return;const ve=V(ie,Ce);if(!ve)return;const he=B.buffer.active,Se=Math.max(0,he.length-B.rows-he.viewportY+ve.row),qe=he.getLine(Se),Ue=Array.from({length:B.cols},(se,_e)=>qe?.getCell(_e)?.getChars()??""),U=Ax(Ue,ve.column),ge={column:U.startColumn,row:ve.row};be={column:U.endColumn,row:ve.row},ee="selecting",fe("mousedown",ge),fe("mousemove",be)},350))},re=Q=>{if($!==Q.pointerId)return;if(ee==="selecting"){const Se=V(Q.clientX,Q.clientY);Se&&(!be||Se.column!==be.column||Se.row!==be.row)&&(be=Se,fe("mousemove",Se)),Q.cancelable&&Q.preventDefault();return}if(ee==="pending"){if(Math.hypot(Q.clientX-ie,Q.clientY-Ce)<8)return;Pe(),ee="scrolling"}if(ee!=="scrolling")return;const ve=pe-Q.clientY;pe=Q.clientY,je+=ve;const he=Math.trunc(je/ze);he&&(B.scrollLines(he),je-=he*ze),Q.cancelable&&Q.preventDefault()},Be=Q=>{if($!==Q.pointerId)return;const ve=ee==="pending",he=ee==="selecting";Pe(),Y.hasPointerCapture(Q.pointerId)&&Y.releasePointerCapture(Q.pointerId),$=null,ee="idle",he&&xe(),ve&&(B.focus(),me())},ke=Q=>{if($!==Q.pointerId)return;const ve=ee==="selecting";Pe(),Y.hasPointerCapture(Q.pointerId)&&Y.releasePointerCapture(Q.pointerId),$=null,ee="idle",ve&&xe()};return Y.addEventListener("pointerdown",te),Y.addEventListener("pointermove",re,{passive:!1}),Y.addEventListener("pointerup",Be),Y.addEventListener("pointercancel",ke),()=>{Pe(),Y.removeEventListener("pointerdown",te),Y.removeEventListener("pointermove",re),Y.removeEventListener("pointerup",Be),Y.removeEventListener("pointercancel",ke)}},[d,a,K]),l.useImperativeHandle(m,()=>({focus:()=>b.current?.focus(),fit:H,getSelection:()=>{const Y=b.current,B=Y?.getSelectionPosition(),$=Y?.getSelection()??"";return!B||!$.trim()?null:{text:$,startLine:B.start.y+1,endLine:B.end.y+1}}}),[H]),n.jsxs(Hr,{open:D,onOpenChange:T,children:[n.jsx(Gr,{render:n.jsx("div",{ref:g,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:ae})}),n.jsxs(qr,{className:"min-w-[180px]",children:[n.jsxs(On,{disabled:!I,onClick:J,children:[n.jsx(R,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),n.jsxs(On,{onClick:le,children:[n.jsx(R,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),n.jsx(Ec,{}),n.jsx(On,{onClick:Ie,children:"Select all"})]})]})});Uc.displayName="TerminalViewport";const Px=({directory:e,tabId:t,sessionId:s,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:a,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:m,onInput:g,controllerRef:b})=>{const p=we(S=>e&&t?S.getBuffer(e,t).chunks:Cr.chunks),h=l.useRef(null),w=o&&i,x=l.useCallback(S=>{h.current=S,b&&(b.current=o?S:b.current),!o&&b&&b.current===S&&(b.current=null)},[b,o]);l.useEffect(()=>{if(!o||!i)return;const S=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(S)},[o,i,r,s]);const C=l.useCallback((S,A)=>{if(!o)return;const y=m.current;(!y||y.cols!==S||y.rows!==A)&&(m.current={cols:S,rows:A}),s&&a.resize({sessionId:s,cols:S,rows:A}).catch(()=>{})},[o,m,s,a]);return n.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:n.jsx(Uc,{ref:x,sessionKey:r,chunks:p,onInput:g,onResize:C,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:w,isVisible:w},r)})},Qa=({items:e,activeId:t,onSelect:s,onClose:r,onCreate:o,disabled:i=!1})=>{const a=e.find(c=>c.id===t)??e[0]??null;return n.jsxs(Gt,{modal:!1,children:[n.jsx(qt,{asChild:!0,children:n.jsxs(Ae,{type:"button",variant:"ghost",size:"sm",disabled:i,title:a?`Switch terminal, current: ${a.label}`:"Switch terminal","aria-label":a?`Switch terminal, current: ${a.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[a?.icon??n.jsx(R,{name:"terminal",className:"size-4 shrink-0"}),n.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:a?.label??"Terminal"}),n.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),n.jsxs(Vt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(a?.id??t);return n.jsxs(dt,{title:c.title??c.label,onClick:()=>s(c.id),className:"group/tab min-w-0",children:[n.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,n.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),d?n.jsx(R,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,n.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:u=>{u.preventDefault(),u.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:n.jsx(R,{name:"close",className:"size-3"})})]},c.id)}),n.jsx(us,{}),n.jsxs(dt,{onClick:o,children:[n.jsx(R,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},Tx=({leading:e,icon:t,title:s,actions:r,className:o})=>n.jsxs("header",{className:_("flex h-11 shrink-0 items-center gap-1 border-b border-border bg-background pl-3 pr-2",o),children:[e,s!=null?typeof s=="string"?n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[typeof t=="string"?n.jsx(R,{name:t,className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):t??null,n.jsx("h2",{className:"truncate typography-ui-label font-medium text-foreground",children:s})]}):n.jsx("div",{className:"min-w-0 flex-1",children:s}):null,r?n.jsx("div",{className:"flex shrink-0 items-center gap-1",children:r}):null]}),Mx=({isTouchTerminal:e,activeModifier:t,disabled:s,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",a=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return n.jsxs(n.Fragment,{children:[n.jsx(Ae,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:s,children:"Esc"}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("tab"),disabled:s,children:[n.jsx(R,{name:"arrow-right",className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Tab"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"chip","aria-pressed":t==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:s,children:[n.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),n.jsx("span",{className:"sr-only",children:"Control modifier"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"chip","aria-pressed":t==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:s,children:[n.jsx("span",{className:"text-xs font-medium",children:"Alt"}),n.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:s,children:[n.jsx(R,{name:"arrow-up"}),n.jsx("span",{className:"sr-only",children:"Arrow up"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:s,children:[n.jsx(R,{name:"arrow-left"}),n.jsx("span",{className:"sr-only",children:"Arrow left"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:s,children:[n.jsx(R,{name:"arrow-down"}),n.jsx("span",{className:"sr-only",children:"Arrow down"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:s,children:[n.jsx(R,{name:"arrow-right"}),n.jsx("span",{className:"sr-only",children:"Arrow right"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("enter"),disabled:s,children:[n.jsx(R,{name:"arrow-go-back"}),n.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Fx="\x1B",Lx=new RegExp(`${Fx}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ox=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Bx=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,_x=/Serving HTTP on .*? port (\d{2,5})/i,zx=new Set([".",",",";",":","!","?"]),Ux=e=>{let t=e;for(;t.length>0;){const s=t[t.length-1];if(s===")"||s==="]"||s==="}"||s===">"){const r=s===")"?"(":s==="]"?"[":s==="}"?"{":"<",o=t.slice(0,-1),i=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,a=(o.match(new RegExp(`\\${s}`,"g"))||[]).length;if(i>a)break;t=o;continue}if(zx.has(s)){t=t.slice(0,-1);continue}break}return t},Ja=e=>{let t=Ux(e);return t=t.replace("0.0.0.0","127.0.0.1"),t=t.replace("[::1]","127.0.0.1"),t=t.replace("[::]","127.0.0.1"),t},$x=e=>{if(!e)return null;const t=e.replace(Lx,""),s=t.match(_x);if(s?.[1]){const o=Number.parseInt(s[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=t.split(`
|
|
55
|
+
`);for(const o of r){if(!Bx.test(o))continue;const i=Array.from(o.matchAll(Ox));if(i.length===0)continue;const a=i.find(c=>{try{return!!new URL(Ja(c[1])).port}catch{return!1}});return Ja((a??i[0])[1])}return null},Kx=async(e,t=1500)=>{if(!e||typeof window>"u")return!1;let s;try{s=new URL(e)}catch{return!1}if(s.protocol!=="http:"&&s.protocol!=="https:")return!1;const r=s.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,i=window.setTimeout(()=>o.abort(),t);try{const a=await nt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:s.toString()}),cache:"no-store",signal:o.signal});return a.ok?(await a.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},Wx={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Hx=(e,t)=>{if(t&&e.startsWith("arrow-")){const s=t==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${s}${r}`}return Wx[e]},$c=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},Gx=(e,t)=>e&&(t==="ctrl"?$c(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Kc={cols:80,rows:24},Xa={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class qx{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(t,s,r,o){if(!r)return;const i=`${this.tail}${r}`.replace(/\r\n|\r/g,`
|
|
56
|
+
`),a=i.split(`
|
|
57
|
+
`),c=i.endsWith(`
|
|
58
|
+
`)?a.join(`
|
|
59
|
+
`):a.slice(0,-1).join(`
|
|
60
|
+
`);if(this.tail=i.endsWith(`
|
|
61
|
+
`)?"":(a[a.length-1]??"").slice(-1024),!c)return;const d=$x(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Kx(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const m=we.getState().getDirectoryState(t)?.tabs.find(g=>g.id===s);!m||m.previewUrlLocked||m.previewUrl===d||o(t,s,d,{locked:!1,autoOpened:!1})})}}const Vx=(e,t)=>{if(t!=="ctrl")return null;const s=e.key,r=e.code??"",o=s.length===1&&/[a-zA-Z]/.test(s)?s.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?$c(o):null};function Yx({terminal:e,effectiveDirectory:t,activeTabId:s,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:a,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:m,focusTerminalWhenWindowActive:g,tabs:b}){const p=we(B=>B.ensureDirectory),h=we(B=>B.setTabSessionId),w=we(B=>B.setTabLifecycle),x=we(B=>B.setConnecting),C=we(B=>B.appendToBuffer),S=we(B=>B.replaceBuffer),A=we(B=>B.setTabPreviewUrl),[y,j]=l.useState(null),[v,k]=l.useState(!1),[E,P]=l.useState(!1),z=l.useRef(new Map),K=l.useRef(null),q=l.useRef(s),G=l.useRef(r),F=l.useRef(t),D=l.useRef(null),T=l.useRef(new Set),I=l.useRef(new Map),M=l.useRef(b),H=l.useRef(a),W=l.useRef(i),L=l.useRef(e);M.current=b,H.current=a,W.current=i,L.current=e;const ae=l.useCallback(()=>{const B=q.current;B&&I.current.get(B)?.reset()},[]);l.useEffect(()=>{G.current=r},[r]),l.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),l.useEffect(()=>{q.current=s},[s]),l.useEffect(()=>{F.current=t},[t]);const J=l.useCallback(()=>{for(const B of z.current.values())try{B()}catch{}z.current.clear(),K.current=null,P(!1)},[]);l.useEffect(()=>()=>{J(),G.current=null},[J]);const le=l.useCallback((B,$,X)=>{let ee=I.current.get($);ee||(ee=new qx,I.current.set($,ee)),ee.scan(B,$,X,A)},[A]),Ie=l.useCallback((B,$,X)=>{if(z.current.has(X)){K.current=X;return}const ee=ea(),ie=()=>ea()===ee&&F.current===B&&we.getState().getDirectoryState(B)?.tabs.find(pe=>pe.id===$)?.terminalSessionId===X,Ce=e.connect(X,{onEvent:pe=>{if(ie())switch(pe.type){case"snapshot":{q.current===$&&G.current===X?(x(B,$,!1),j(null),k(!1),P(!1),g()):x(B,$,!1),S(B,$,pe.data??"",pe.sequence??0),le(B,$,pe.data??""),pe.status==="exited"&&w(B,$,"exited");break}case"reconnecting":{q.current===$&&(j(null),k(!1),P(!0));break}case"data":{pe.data&&(C(B,$,pe.data,pe.sequence,pe.replayData),le(B,$,pe.data));break}case"exit":{const je=typeof pe.exitCode=="number"?pe.exitCode:null,be=typeof pe.signal=="number"?pe.signal:null,me=!!we.getState().getDirectoryState(B)?.tabs.find(Pe=>Pe.id===$)?.label?.startsWith("Action:");C(B,$,`\\r\\n[Process exited${je!==null?` with code ${je}`:""}${be!==null?` (signal ${be})`:""}]\\r\\n`),w(B,$,"exited"),q.current===$&&(x(B,$,!1),j(me?null:"Terminal session ended"),k(!1),P(!1));break}}},onError:(pe,je)=>{if(!ie())return;const be=q.current===$;if(!je){be&&(j(null),k(!1));return}if(pe.code==="SESSION_NOT_FOUND"&&!we.getState().getDirectoryState(B)?.tabs.find(me=>me.id===$)?.label?.startsWith("Action:")){be&&(j(null),k(!1),x(B,$,!1),P(!1)),h(B,$,null),w(B,$,"idle");return}be&&(P(!1),j(`Connection failed: ${pe.message}`),k(!0),x(B,$,!1),w(B,$,"exited"),h(B,$,null))}});z.current.set(X,()=>Ce.close()),K.current=X},[C,g,S,le,x,w,h,e]),Y=l.useMemo(()=>b.map(B=>`${B.id}:${B.terminalSessionId??""}`).join(","),[b]);return l.useEffect(()=>{if(!a||!i||!t)return;const B=t,$=new Set;for(const X of b)X.terminalSessionId&&($.add(X.terminalSessionId),Ie(B,X.id,X.terminalSessionId));for(const[X,ee]of z.current)if(!$.has(X)){try{ee()}catch{}z.current.delete(X)}},[Y,b,t,a,i,Ie]),l.useEffect(()=>Qf(()=>{if(!H.current||!W.current)return;const B=F.current;if(!B)return;const $=[];for(const ee of M.current){if(!ee.terminalSessionId)continue;we.getState().getDirectoryState(B)?.tabs.find(Ce=>Ce.id===ee.id)?.terminalSessionId===ee.terminalSessionId&&$.push({id:ee.id,terminalSessionId:ee.terminalSessionId})}if(z.current.clear(),K.current=null,$.length===0)return;P(!0),j(null),k(!1);for(const ee of $)Ie(B,ee.id,ee.terminalSessionId);const X=D.current;if(X)for(const ee of $)L.current.resize({sessionId:ee.terminalSessionId,...X}).catch(()=>{})}),[Ie]),l.useEffect(()=>{let B=!1;if(!a||!i)return;if(!t){j(m?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const X=t;if(!F.current||F.current!==X)return;if(!we.getState().getDirectoryState(X)){p(X);return}const ie=we.getState().getDirectoryState(X);if(!ie||ie.tabs.length===0)return;const Ce=ie.activeTabId??ie.tabs[0]?.id??null;if(!Ce)return;const pe=ie.tabs.find(V=>V.id===Ce)??ie.tabs[0],je=pe?.terminalSessionId??null,be=pe?.lifecycle??"idle",ze=!!pe?.label?.startsWith("Action:"),me=we.getState().getBuffer(X,Ce),Pe=me.byteLength>0||me.chunks.length>0;if(!je){if(be==="exited"){x(X,Ce,!1);return}if(ze&&Pe){x(X,Ce,!1);return}const V=`${X}\0${Ce}`;if(T.current.has(V))return;const fe=D.current??Kc;T.current.add(V),j(null),k(!1),P(!1),x(X,Ce,!0);try{const xe=await e.createSession({cwd:X,sessionId:Ce,cols:fe.cols,rows:fe.rows,shell:c,loginShell:d,...u.current});if(!we.getState().getDirectoryState(X)?.tabs.find(Be=>Be.id===Ce)){try{await e.close(xe.sessionId)}catch{}return}h(X,Ce,xe.sessionId);const re=D.current;re&&(re.cols!==fe.cols||re.rows!==fe.rows)&&e.resize({sessionId:xe.sessionId,...re}).catch(()=>{});return}catch(xe){const te=we.getState().getDirectoryState(X)?.tabs.find(re=>re.id===Ce);if(!te||te.terminalSessionId||(x(X,Ce,!1),F.current!==X||q.current!==Ce))return;j(xe instanceof Error?xe.message:"Failed to start terminal session"),k(!0),P(!1);return}finally{T.current.delete(V)}}!je||B||(G.current=je)})(),()=>{B=!0}},[m,t,r,o,s,i,f,a,p,x,w,h,e,d,c,u]),{connectionError:y,setConnectionError:j,isFatalError:v,setIsFatalError:k,isReconnectPending:E,setIsReconnectPending:P,terminalIdRef:G,lastViewportSizeRef:D,directoryRef:F,activeTabIdRef:q,disconnectStream:J,resetTerminalPreviewScan:ae,startStream:Ie}}function Qx({terminal:e,terminalIdRef:t,isReconnectPending:s,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:a,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=l.useState(null),m=l.useRef(null),g=l.useCallback(()=>{d||m.current?.focus()},[d]),b=l.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||m.current?.focus()},[d]);l.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),l.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const p=l.useCallback(S=>{if(!S||s)return;let A=S,y=!1;u&&S.length>0&&(A=Gx(S,u),y=!0);const j=t.current;j&&(e.sendInput(j,A).catch(v=>{s||r(v instanceof Error?v.message:"Failed to send input")}),y&&(f(null),g()))},[u,g,s,r,e,t]),h=l.useCallback((S,A)=>{const y=a.current;if((!y||y.cols!==S||y.rows!==A)&&(a.current={cols:S,rows:A}),!i)return;const j=t.current;j&&e.resize({sessionId:j,cols:S,rows:A}).catch(()=>{})},[i,a,e,t]),w=l.useCallback(S=>{f(A=>A===S?null:S),g()},[g]),x=l.useCallback(S=>{const A=Hx(S,u);A&&(p(A),f(null),g())},[u,g,p]),C=l.useCallback(S=>{if(S.repeat)return;const A=S.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const y=A.length===1?A.toLowerCase():A;if(y in Xa){S.preventDefault(),S.stopPropagation(),x(Xa[y]);return}const j=Vx(S,u);j&&(S.preventDefault(),S.stopPropagation(),p(j),f(null),g())},[u,g,x,p]);return l.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[u,C,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:m,focusTerminalController:g,focusTerminalWhenWindowActive:b,handleViewportInput:p,handleViewportResize:h,handleModifierToggle:w,handleMobileKeyPress:x}}function Jx({terminal:e,effectiveDirectory:t,activeTabId:s,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:a,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:m,startStream:g,setConnectionError:b,setIsFatalError:p,setIsReconnectPending:h}){const w=we(K=>K.createTab),x=we(K=>K.setActiveTab),C=we(K=>K.closeTab),S=we(K=>K.setTabSessionId),A=we(K=>K.setTabLifecycle),[y,j]=l.useState(!1),v=l.useCallback(async()=>{if(!t||y)return;const K=we.getState().getDirectoryState(t),q=s??K?.activeTabId??K?.tabs[0]?.id??null;if(!q)return;const G=K?.tabs.find(F=>F.id===q)?.terminalSessionId??null;if(!(!G||!e.restartSession)){j(!0),b(null),p(!1),h(!1),m();try{const F=c.current??Kc,D=await e.restartSession(G,{cwd:t,shell:o,loginShell:i,...F,...a.current});if(we.getState().getDirectoryState(t)?.tabs.find(I=>I.id===q)?.terminalSessionId!==G||(S(t,q,D.sessionId),A(t,q,"running"),d.current!==t||u.current!==q))return;f.current=D.sessionId,g(t,q,D.sessionId)}catch(F){if(we.getState().getDirectoryState(t)?.tabs.find(T=>T.id===q)?.terminalSessionId!==G||d.current!==t||u.current!==q)return;b(F instanceof Error?F.message:"Failed to restart terminal"),p(!1),h(!1),f.current=G,g(t,q,G)}finally{j(!1)}}},[s,u,d,t,r,y,c,m,b,p,h,A,S,g,e,a,f,i,o]),k=l.useCallback(async()=>{await v()},[v]),E=l.useCallback(()=>{if(!t)return;const K=w(t);x(t,K),b(null),p(!1),h(!1)},[w,t,x,b,p,h]),P=l.useCallback(K=>{t&&(x(t,K),b(null),p(!1),h(!1))},[t,x,b,p,h]),z=l.useCallback(K=>{if(!t)return;b(null),p(!1),h(!1);const q=we.getState().getDirectoryState(t)?.tabs.find(G=>G.id===K)?.terminalSessionId;(async()=>{q&&await e.close(q),C(t,K)})().catch(G=>b(G instanceof Error?G.message:"Terminal session ended"))},[C,t,b,p,h,e]);return{isRestarting:y,handleRestart:v,handleHardRestart:k,handleCreateTab:E,handleSelectTab:P,handleCloseTab:z}}const dv=({visible:e,onCloseView:t,terminalHeaderSlot:s})=>{const{terminal:r,runtime:o}=Un(),{currentTheme:i}=Il(),a=l.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});a.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=gf(),d=ue(se=>se.terminalFontSize),u=ue(se=>se.terminalShell),f=ue(se=>se.terminalLoginShells.includes(se.terminalShell)),{isMobile:m,isTablet:g,hasTouchOnlyPointer:b}=ms(),p=m||g,h=(p||b)&&o.platform==="web",w=!0,x=ue(se=>se.showTerminalQuickKeysOnDesktop),C=p||x,S=Me(se=>se.currentSessionId),A=Me(se=>se.newSessionDraft),y=S!==null||A?.open===!0,j=bf()??null,v=we(se=>j?se.sessions.get(j):void 0),k=we(se=>se.hasHydrated),E=ue(se=>se.openContextPreview),P=l.useMemo(()=>v?v.activeTabId??v.tabs[0]?.id??null:null,[v,w]),z=l.useMemo(()=>{if(v)return P?v.tabs.find(se=>se.id===P)??v.tabs[0]:v.tabs[0]},[v,P]),K=l.useMemo(()=>(v?.tabs??[]).map(se=>({icon:(()=>{const _e=se.iconKey?Ws[se.iconKey]??"terminal":"terminal";return n.jsx(R,{name:_e,className:"h-4 w-4"})})(),id:se.id,label:se.label,title:se.label,closeLabel:"Close tab"})),[v?.tabs]),q=z?.terminalSessionId??null,G=z?.lifecycle??"idle",F=l.useMemo(()=>(v?.tabs??[]).map(se=>({id:se.id,terminalSessionId:se.terminalSessionId,label:se.label})),[v?.tabs]),D=z?.isConnecting??!1,T=z?.previewUrl??null,M=ue(se=>se.activeMainTab)==="terminal",H=e??M,[W,L]=l.useState(H);l.useEffect(()=>{H&&L(!0)},[H]);const{connectionError:ae,setConnectionError:J,isFatalError:le,setIsFatalError:Ie,isReconnectPending:Y,setIsReconnectPending:B,terminalIdRef:$,lastViewportSizeRef:X,directoryRef:ee,activeTabIdRef:ie,resetTerminalPreviewScan:Ce,startStream:pe}=Yx({terminal:r,effectiveDirectory:j,activeTabId:P,terminalSessionId:q,terminalLifecycle:G,hasOpenedTerminalViewport:W,terminalHydrated:k,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,enableTabs:w,hasActiveContext:y,tabs:F,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&be.current?.focus()}}),{activeModifier:je,terminalControllerRef:be,focusTerminalWhenWindowActive:ze,handleViewportInput:me,handleModifierToggle:Pe,handleMobileKeyPress:V}=Qx({terminal:r,terminalIdRef:$,isReconnectPending:Y,setConnectionError:J,showQuickKeys:C,isTerminalVisible:H,lastViewportSizeRef:X,terminalSessionId:q,useTouchTerminalInput:h}),{isRestarting:fe,handleRestart:xe,handleHardRestart:te,handleCreateTab:re,handleSelectTab:Be,handleCloseTab:ke}=Jx({terminal:r,effectiveDirectory:j,activeTabId:P,enableTabs:w,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,lastViewportSizeRef:X,directoryRef:ee,activeTabIdRef:ie,terminalIdRef:$,resetTerminalPreviewScan:Ce,startStream:pe,setConnectionError:J,setIsFatalError:Ie,setIsReconnectPending:B});l.useEffect(()=>{if(!H||h)return;if(typeof window>"u"){ze();return}const se=window.requestAnimationFrame(()=>{ze()});return()=>{window.cancelAnimationFrame(se)}},[P,ze,H,h]);const Q=l.useMemo(()=>{const se=Ds[ro].stack;if(typeof window>"u")return(Ds[c]??Ds[ro]).stack;const st=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return st&&st.trim().length>0?st.trim():(Ds[c]??Ds[ro]).stack??se},[c]),ve=l.useMemo(()=>wx(i),[i]),he=`${j??"no-dir"}::${P??"no-tab"}`;if(l.useEffect(()=>{if(!H||h)return;const se=be.current;if(!se)return;const _e=()=>{se.fit()};if(typeof window<"u"){const st=window.requestAnimationFrame(()=>{_e(),ze()}),pt=[220,400].map(Xe=>window.setTimeout(_e,Xe));return()=>{window.cancelAnimationFrame(st),pt.forEach(Xe=>window.clearTimeout(Xe))}}_e()},[ze,H,h,be,he,q]),l.useEffect(()=>{if(!H||!h)return;let se=null;const _e=()=>{se!==null&&window.cancelAnimationFrame(se),se=window.requestAnimationFrame(()=>{se=null,be.current?.fit()})};return window.addEventListener("oc:keyboard-settled",_e),()=>{window.removeEventListener("oc:keyboard-settled",_e),se!==null&&window.cancelAnimationFrame(se)}},[H,be,he,h]),!y)return n.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(!j)return n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{children:"No working directory available for this session."}),n.jsx("button",{onClick:xe,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Se=!q||D||fe||Y,qe=W,Ue=v?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx(Qa,{items:K,activeId:P,onSelect:Be,onClose:ke,onCreate:re})}),n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:re,title:"New tab","aria-label":"New tab",children:n.jsx(R,{name:"add",className:"h-4 w-4"})}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{xe()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:n.jsx(R,{name:"restart",className:"h-4 w-4"})}),T?n.jsxs(Ae,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{j&&E(j,T)},title:"Open preview pane",children:[n.jsx(R,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,U=n.jsx(Mx,{isTouchTerminal:p,activeModifier:je,disabled:Se,onKeyPress:V,onModifierToggle:Pe}),ge=!s||p||C;return n.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[Ue&&s?pu.createPortal(n.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ue}),s):null,p&&Ue&&!s&&v?n.jsx(Tx,{leading:n.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:n.jsx(Qa,{items:K,activeId:P,onSelect:Be,onClose:ke,onCreate:re})}),actions:n.jsxs(n.Fragment,{children:[n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:re,title:"New tab","aria-label":"New tab",children:n.jsx(R,{name:"add",className:"size-4"})}),n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:()=>{xe()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:n.jsx(R,{name:"restart",className:"size-4"})}),T?n.jsxs(Ae,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{j&&E(j,T)},title:"Open preview pane",children:[n.jsx(R,{name:"global",className:"size-3.5 shrink-0"}),n.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:n.jsx(R,{name:"close",className:"size-4"})}):null]})}):null,!p&&ge?n.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[Ue&&!s?n.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ue,t?n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:n.jsx(R,{name:"close",className:"h-4 w-4"})}):null]}):null,!p&&C&&w&&v?n.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:U}):null,!p&&C&&!v?n.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:U}):null]}):null,n.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:ve.background},children:[n.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:qe&&j&&v?v.tabs.map(se=>{const _e=se.id===P;return n.jsx(Px,{directory:j,tabId:se.id,sessionId:se.terminalSessionId,sessionKey:`${j}::${se.id}`,isActive:_e,isTerminalVisible:H,terminal:r,theme:ve,fontFamily:Q,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:X,onInput:me,controllerRef:be},se.id)}):null}),!Y&&ae&&n.jsxs("div",{className:"absolute inset-x-0 bottom-0 border-t border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 text-xs text-foreground flex items-center justify-between gap-2",children:[n.jsx("span",{children:ae}),le&&p&&n.jsx(Ae,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:te,disabled:fe,title:"Force kill and create fresh session",type:"button",children:"Hard restart"})]})]}),p&&C?n.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:n.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:U})}):null]})},pi=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"pull-requests",label:"PRs",icon:"git-pull-request"},{id:"issues",label:"Issues",icon:"task"}],Xx=new Set(pi.map(e=>e.id)),Zx=e=>typeof e=="string"&&Xx.has(e),uv=e=>Zx(e)?e:"changes",Wc=e=>e==="pull-requests"||e==="issues",ey=e=>e?pi:pi.filter(t=>!Wc(t.id)),fv=(e,t)=>Wc(e)?"changes":e,ty=48,ny=96,St=(e,...t)=>{try{e?.(...t)}catch{}},Co=(e,t)=>{if(typeof e=="function"){const s=e();return s>0?s:t}return typeof e=="number"&&e>0?e:t},hv=(e,t)=>{const s=l.useRef(t);s.current=t;const r=t.enabled;l.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const i=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?ny:ty;let d=!1,u=!1,f=!1,m=null,g=!1,b=0,p=0,h=0,w=0;const x=()=>{d=!1,u=!1,f=!1,m=null},C=()=>{const E=s.current,P=m,z=g;u&&P&&(St(P==="left"?E.onLeftProgress:E.onRightProgress,z?1:0),St(E.onDragEnd,P,z)),x()},S=()=>{C(),u||x()},A=E=>{const P=s.current;if(P.enabled===!1){u&&m?C():x();return}if(E.touches.length!==1){u&&m?C():x();return}const z=E.touches[0],K=o.getBoundingClientRect(),q=o.clientWidth,G=!!P.leftOpen,F=!!P.rightOpen,D=T=>ux(T,o);if(G||F){if(D(E.target)){x();return}if(G&&F){const T=z.clientX<=K.left+c;z.clientX>=K.right-c?(m="right",g=!0):T?(m="left",g=!0):(m=G?"left":"right",g=!0)}else G?(m="left",g=!0):(m="right",g=!0);w=Co(m==="left"?P.leftWidth:P.rightWidth,q),w<10&&(w=q||window.innerWidth||320),w<10&&(w=320),d=!0}else{if(D(E.target)){x();return}m=null,g=!1,w=0,d=!0}b=z.clientX,p=z.clientY,h=Date.now(),u=!1,f=!1},y=E=>{if(!d)return;if(E.touches.length!==1){S();return}const P=E.touches[0],z=P.clientX-b,K=P.clientY-p;if(!f){if(Math.abs(z)<Ha&&Math.abs(K)<Ha)return;if(Math.abs(K)>Math.abs(z)*Ls){x();return}if(!m){const F=s.current;m=z>0?"left":"right",w=Co(m==="left"?F.leftWidth:F.rightWidth,o.clientWidth),w<10&&(w=window.innerWidth||320)}if(m==="left"){if(!g&&z<=0){x();return}if(g&&z>=0){x();return}}else{if(!g&&z>=0){x();return}if(g&&z<=0){x();return}}f=!0,u=!0,St(s.current.onDragStart,m)}if(!u)return;E.cancelable&&E.preventDefault();const q=s.current,G=Ga(m,g,z,w);St(m==="left"?q.onLeftProgress:q.onRightProgress,G)},j=(E,P)=>{if(!d){x();return}const z=E-b,K=P-p;if(!m&&!g&&Math.abs(z)>=kr&&Math.abs(K)<=Math.abs(z)*Ls){const I=s.current;m=z>0?"left":"right",w=Co(m==="left"?I.leftWidth:I.rightWidth,o.clientWidth),w<10&&(w=window.innerWidth||320)}if(!m){x();return}const q=Math.max(1,Date.now()-h),G=s.current;if(!u){const I=Math.abs(z),M=Math.abs(K);I>=kr&&M<=I*Ls?m==="left"&&!g&&z>0?(St(G.onLeftProgress,1),St(G.onLeftOpen)):m==="right"&&!g&&z<0?(St(G.onRightProgress,1),St(G.onRightOpen)):St(m==="left"?G.onLeftProgress:G.onRightProgress,g?1:0):St(m==="left"?G.onLeftProgress:G.onRightProgress,g?1:0);const H=m;x(),St(G.onDragEnd,H);return}const F=Ga(m,g,z,w),D=cx({side:m,isOpenAtStart:g,dx:z,dt:q,progress:F}),T=m;St(T==="left"?D?G.onLeftOpen:G.onLeftClose:D?G.onRightOpen:G.onRightClose),x(),St(G.onDragEnd,T,D)},v=E=>{const P=E.changedTouches[0];if(!P){x();return}const z=P.clientX-b,K=P.clientY-p;d&&(u||Math.abs(z)>=kr&&Math.abs(K)<=Math.abs(z)*Ls)&&E.cancelable&&E.preventDefault(),j(P.clientX,P.clientY)},k=()=>{S()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",y,{passive:!1}),o.addEventListener("touchend",v,{passive:!1}),o.addEventListener("touchcancel",k,{passive:!0}),()=>{try{u&&m&&C()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",y),o.removeEventListener("touchend",v),o.removeEventListener("touchcancel",k)}},[e,r])};function pv({className:e="h-5 w-5"}){return n.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[n.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),n.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),n.jsx(R,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Za({size:e,className:t,style:s,...r}){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:t,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...s},...r,children:n.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 sy=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:s})=>s?t:e,ry=({activeProjectLabel:e,openDirectory:t,homeDirectory:s})=>Ys(t,s)?null:e,Ao=()=>Fn.filter(e=>Wo.has(e.id)).map(e=>({...Ll(e)})),oy=()=>{if(typeof window>"u")return Ho;const e=window.localStorage.getItem("openInAppId");return e&&Ko(e)?e:Ho};let No=!1,es=!1,wn=!1,vn=0,Hs=null;const el=()=>{Hs&&(clearTimeout(Hs),Hs=null)},Pn=$n()((e,t)=>({selectedAppId:oy(),availableApps:Ao(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(No||typeof window>"u")return;No=!0;const s=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Ao(),hasLoadedApps:u});return}const f=new Set(d.map(p=>p.name)),m=new Map(d.map(p=>[p.name,p.iconDataUrl??void 0])),b=Fn.filter(p=>f.has(p.appName)||Wo.has(p.id)).map(p=>({...Ll(p),iconDataUrl:m.get(p.appName)}));e({availableApps:b,hasLoadedApps:!0})},r=async d=>{if(!fs()||!Ir()||es||t().hasLoadedApps&&!d)return;const f=Fn.map(m=>m.appName);el(),es=!0,wn=!1,e({isScanning:!0});try{const{apps:m,success:g,hasCache:b,isCacheStale:p}=await ta(f,d),h=g&&!b&&m.length===0&&vn<3;if(e({isCacheStale:b?p:!1}),s(m,g?!h:!1),g){if(h){const x=[800,1600,3200][vn]??3200;vn+=1,wn=!0,Hs=setTimeout(()=>{r()},x);return}vn=0,wn=!1;return}if(vn<3){const x=[1e3,3e3,7e3][vn]??7e3;vn+=1,wn=!0,Hs=setTimeout(()=>{r()},x)}}finally{es=!1,wn||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Ko(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},a=d=>{const u=d.detail;Array.isArray(u)&&(vn=3,wn=!1,e({isScanning:!1,isCacheStale:!1}),s(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",a),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async s=>{if(No||t().initialize(),!fs()||!Ir()||es||t().hasLoadedApps&&!s)return;const o=Fn.map(i=>i.appName);el(),s&&e({hasLoadedApps:!1}),es=!0,wn=!1,e({isScanning:!0});try{const{apps:i,hasCache:a,isCacheStale:c}=await ta(o,s),d=new Set(i.map(g=>g.name)),u=new Map(i.map(g=>[g.name,g.iconDataUrl??void 0])),m=Fn.filter(g=>d.has(g.appName)||Wo.has(g.id)).map(g=>({...g,iconDataUrl:u.get(g.appName)}));e({availableApps:m.length>0?m:Ao(),hasLoadedApps:m.length>0,isCacheStale:a?c:!1})}finally{es=!1,wn||e({isScanning:!1})}},selectApp:async s=>{Ko(s)&&(e({selectedAppId:s}),typeof window<"u"&&window.localStorage.setItem("openInAppId",s),await Pl({openInAppId:s}))}})),iy="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",ay="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",Io=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?iy:e.id==="terminal"?ay:void 0}),tl=({label:e,iconDataUrl:t,fallbackIconDataUrl:s})=>{const[r,o]=l.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",a=t||s;return a&&!r?n.jsx("img",{src:a,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):n.jsx("span",{className:_("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},ly=({directory:e,className:t})=>{const s=Pn(p=>p.selectedAppId),r=Pn(p=>p.availableApps),o=Pn(p=>p.isCacheStale),i=Pn(p=>p.isScanning),a=Pn(p=>p.initialize),c=Pn(p=>p.loadInstalledApps),d=Pn(p=>p.selectApp);l.useEffect(()=>{a()},[a]);const u=fs()&&Ir(),f=l.useMemo(()=>{const p=r.find(h=>h.id===s)??r.find(h=>h.id===Ho)??r[0]??Fn[0];return Io(p||Fn[0])},[r,s]);if(!u||!e||r.length===0)return null;const m=async p=>{await Jf(e,p.id,p.appName)||await Ml(e,p.appName)},g=async p=>{await d(p.id),await m(p)},b=async()=>{(await fn(e)).ok&&oe.success("Path copied to clipboard")};return n.jsxs("div",{className:_("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",t),children:[n.jsx("button",{type:"button",onClick:()=>{m(f)},className:_("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",i&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:n.jsx(tl,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),n.jsxs(Gt,{children:[n.jsx(qt,{asChild:!0,children:n.jsx("button",{type:"button",className:_("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:n.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),n.jsxs(Vt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[n.jsxs(dt,{className:"flex items-center gap-2",onClick:()=>{b()},children:[n.jsx(R,{name:"file-copy",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy path"})]}),n.jsx(us,{}),r.map(p=>{const h=Io(p);return n.jsxs(dt,{className:"flex items-center gap-2",onClick:()=>{g(p)},children:[n.jsx(tl,{label:p.label,iconDataUrl:p.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),n.jsx("span",{className:"typography-ui-label text-foreground",children:p.label}),f.id===p.id?n.jsx(R,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},p.id)}),o?n.jsxs(dt,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[n.jsx(R,{name:"refresh",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh apps"})]}):null]})]})]})},cy="\x1B",dy=new RegExp(`${cy}\\[[0-9;?]*[ -/]*[@-~]`,"g"),uy=/https?:\/\/[^\s<>'"`]+/gi,At="__pichamber_auto_discover_preview__",fy=15e3,hy=e=>{let t="";for(let s=0;s<e.length;s+=1){const r=e.charCodeAt(s);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(t+=e[s])}return t},py=e=>{const t=(e||"").trim();if(!t)return null;const s=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(s);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},my=e=>{const s=e.replace(dy,"").match(uy);if(!s||s.length===0)return null;const r=s.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const a=new URL(i);a.port&&a.port.length>0&&o.push({raw:i,parsed:a})}catch{}if(o.length>0){const i=a=>{const{parsed:c}=a,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",m=f.split("/").filter(Boolean).length,g=f==="/"||f==="",b=!!(c.search||c.hash);let p=0;return u&&(p+=50),g&&(p+=30),p-=Math.min(m*5,20),b&&(p-=10),p};return o.sort((a,c)=>i(c)-i(a)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},gy=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],by=["dev","start","preview","serve"];async function xy(e,t,s){if(!e)return null;const r=vy(t);if(r)return{command:r.command,label:r.name||"Start preview",actionId:r.id,previewUrlHint:r.openUrl};if(s){const o=Sy(s);if(o){const i=await jy(e);return{command:`${i==="npm"?"npm run":i==="yarn"?"yarn":i==="pnpm"?"pnpm":i==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await yy(e)){const o=await wy(),i=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${i}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${i}/`}}return null}async function yy(e){const t=`${e}/index.html`,s=await Or(t,e);return typeof s=="string"&&s.trim().length>0}async function wy(){try{const e=await nt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),s=typeof t?.port=="number"?t.port:null;return s&&Number.isFinite(s)?s:null}catch{return null}}function vy(e){for(const t of e){const s=`${t.name} ${t.command}`.toLowerCase();if(by.some(o=>s.includes(o)))return t}return null}function Sy(e){for(const{pattern:t}of gy)for(const s of Object.keys(e))if(t.test(s))return s;return null}async function jy(e){const t=await Or(`${e}/package.json`,e);if(t)try{const r=JSON.parse(t),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 s=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of s){const i=await Or(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function Or(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await nt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const s=Tl()?.files;if(s?.readFile)try{const r=await s.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await nt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function ky(e){try{const t=await Or(`${e}/package.json`,e);if(t==null)return null;const r=JSON.parse(t).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Cy=(e,t,s)=>new Promise(r=>{let o=!1,i=null,a=null;const c=d=>{o||(o=!0,a&&clearTimeout(a),i?.close(),r(d))};i=e.connect(t,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?i.close():a=setTimeout(()=>c(!1),s)});function Ay({projectRef:e,directory:t,allowMobile:s=!1}){const{currentTheme:r}=Il(),{terminal:o}=Un(),{isMobile:i}=ms(),a=ue(V=>V.terminalShell),c=ue(V=>V.terminalLoginShells.includes(V.terminalShell)),d=ue(V=>V.setSettingsPage),u=ue(V=>V.setSettingsDialogOpen),f=ue(V=>V.setSettingsProjectsSelectedId),m=ue(V=>V.openContextPreview),g=we(V=>V.ensureDirectory),b=we(V=>V.setTabLabel),p=we(V=>V.setTabIconKey),h=we(V=>V.setActiveTab),w=we(V=>V.setConnecting),x=we(V=>V.setTabSessionId),C=we(V=>V.setTabPreviewUrl),S=we(V=>V.projectActionRuns),A=we(V=>V.setProjectActionRun),y=we(V=>V.updateProjectActionRunStatus),j=we(V=>V.removeProjectActionRun),[v,k]=l.useState([]),[E,P]=l.useState(null),[z,K]=l.useState(!1),q=l.useRef({}),G=l.useRef({}),F=l.useRef({}),D=l.useRef({}),T=l.useRef(new Set),I=l.useRef(0),M=e?.id??null,H=e?.path??"",W=l.useMemo(()=>M?{id:M,path:H}:null,[M,H]),L=l.useCallback(async V=>{await gl(V)},[]),ae=l.useCallback(async()=>{if(!W)return;const V=I.current+1;I.current=V,K(!0);try{const fe=await To(W);if(I.current!==V)return;const xe=fe.actions;k(xe),P(te=>te===At||te&&xe.some(re=>re.id===te)?te:null)}catch{if(I.current!==V)return}finally{I.current===V&&K(!1)}},[W]),J=l.useMemo(()=>nc(t||W?.path||""),[t,W?.path]),le=l.useMemo(()=>E?v.find(V=>V.id===E)??null:null,[v,E]),Ie=l.useMemo(()=>({id:At,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Y=!i,B=l.useMemo(()=>Y?[Ie,...v]:v,[v,Ie,Y]);l.useEffect(()=>{ae()},[ae]),l.useEffect(()=>{if(typeof window>"u")return;const V=fe=>{const xe=fe.detail;M&&(xe?.projectId&&xe.projectId!==M||ae())};return window.addEventListener(Jo,V),()=>{window.removeEventListener(Jo,V)}},[ae,M]),l.useEffect(()=>{E&&(E===At&&Y||v.some(V=>V.id===E)||P(null))},[v,Y,E]),l.useEffect(()=>{const V=()=>{const fe=we.getState(),xe=fe.sessions,te=fe.projectActionRuns;for(const[re,Be]of Object.entries(te)){const Q=xe.get(Be.directory)?.tabs.find(_e=>_e.id===Be.tabId);if(!Q||Q.terminalSessionId!==Be.sessionId){j(re);continue}const ve=G.current[re]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};G.current[re]=ve;const he=B.find(_e=>_e.id===Be.actionId),Se=fe.getBuffer(Be.directory,Be.tabId).chunks;if(!he||Se.length===0)continue;const qe=Se.filter(_e=>ve.lastSeenChunkId===null||_e.id>ve.lastSeenChunkId);if(qe.length===0)continue;const Ue=qe.map(_e=>_e.data).join(""),U=`${ve.tail}${Ue}`,ge=!ve.openedUrl&&he.autoOpenUrl===!0?my(U):null,se=qe[qe.length-1]?.id??ve.lastSeenChunkId;if(ve.lastSeenChunkId=se,ve.tail=U.slice(-512),ge)if(ve.openedUrl=!0,ve.openInPreview){const _e=te[re];_e&&(C(_e.directory,_e.tabId,ge,{locked:!1,autoOpened:!1}),_e.status==="waiting-for-preview"&&y(re,"running"),window.clearTimeout(D.current[re]),delete D.current[re],m(_e.directory,ge))}else L(ge),oe.success("Opened URL from action output");G.current[re]=ve}for(const re of Object.keys(G.current))te[re]||(delete G.current[re],window.clearTimeout(D.current[re]),delete D.current[re])};return V(),we.subscribe((fe,xe)=>{(fe.sessions!==xe.sessions||fe.buffers!==xe.buffers)&&V()})},[B,m,L,S,j,C,y]);const $=l.useCallback(async(V,fe={})=>{if(!J)throw new Error("No active directory");const xe=cn(J,V.id);g(J);const te=we.getState(),re=te.getDirectoryState(J);let Be=q.current[xe]||null;const ke=Be?!!re?.tabs.some(he=>he.id===Be):!1;(!Be||!ke)&&(Be=te.createTab(J),q.current[xe]=Be),b(J,Be,`Action: ${V.name}`),p(J,Be,V.icon||"play"),h(J,Be),fe.revealTerminal!==!1&&ue.getState().openContextPanelTab(J,{mode:"terminal"});const ve=we.getState().getDirectoryState(J)?.tabs.find(he=>he.id===Be);return{key:xe,tabId:Be,sessionId:ve?.terminalSessionId??null}},[g,J,h,p,b]),X=l.useCallback(async V=>{if(!s&&i)return;if(!J){oe.error("No active directory for action");return}const fe=cn(J,V.id),xe=S[fe];if(!(xe&&xe.status==="running")&&!T.current.has(fe)){T.current.add(fe);try{const te=V.id===At?await(async()=>{const[U,ge]=await Promise.all([To({id:W?.id??"",path:J}),ky(J)]),se=await xy(J,U.actions,ge);if(!se)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:At,name:"Auto-discover",command:se.command,icon:"scan-2",autoOpenUrl:!0,openUrl:se.previewUrlHint||""}})():V,re=te.autoOpenUrl===!0&&(te.openUrl||"").trim().length>0,Be=!re&&V.id!==At,{key:ke,tabId:Q,sessionId:ve}=await $(te,{revealTerminal:Be});let he=ve;if(!he){w(J,Q,!0);try{he=(await o.createSession({cwd:J,sessionId:Q,shell:a,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(J,Q,he)}finally{w(J,Q,!1)}}if(!he)throw new Error("Failed to create terminal session");F.current[ke]?.(),w(J,Q,!0);const Se=o.connect(he,{onEvent:U=>{U.type==="snapshot"&&(we.getState().replaceBuffer(J,Q,U.data??"",U.sequence??0),we.getState().setConnecting(J,Q,!1)),U.type==="data"&&typeof U.data=="string"&&U.data.length>0&&we.getState().appendToBuffer(J,Q,U.data,U.sequence,U.replayData),U.type==="exit"&&(we.getState().setTabLifecycle(J,Q,"exited"),we.getState().setConnecting(J,Q,!1),we.getState().removeProjectActionRun(ke),delete G.current[ke],F.current[ke]?.(),delete F.current[ke],window.clearTimeout(D.current[ke]),delete D.current[ke])},onError:(U,ge)=>{we.getState().setConnecting(J,Q,!1),ge&&(we.getState().setTabLifecycle(J,Q,"exited"),we.getState().setTabSessionId(J,Q,null),we.getState().removeProjectActionRun(ke))}});F.current[ke]=Se.close;const qe=te.autoOpenUrl?py(te.openUrl):null;A({key:ke,directory:J,actionId:te.id,tabId:Q,sessionId:he,status:te.id===At&&!qe?"waiting-for-preview":"running"}),window.clearTimeout(D.current[ke]),delete D.current[ke],te.id===At&&!qe&&(D.current[ke]=window.setTimeout(()=>{const U=we.getState(),ge=U.projectActionRuns[ke];U.updateProjectActionRunStatus(ke,"running"),ge&&(U.setActiveTab(ge.directory,ge.tabId),ue.getState().openContextPanelTab(ge.directory,{mode:"terminal"})),delete D.current[ke]},fy)),G.current[ke]={lastSeenChunkId:null,openedUrl:!!qe||re,tail:"",openInPreview:te.id===At};const Ue=hy(te.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
+
`));await o.sendInput(he,`${Ue}\r`),qe?(C(J,Q,qe,{locked:!0,autoOpened:!0}),m(J,qe),oe.success("Opened action URL")):re?(C(J,Q,null,{locked:!0}),oe.error("Invalid custom URL format")):C(J,Q,null,{locked:!1,autoOpened:!1})}catch(te){j(fe),delete G.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe],oe.error(te instanceof Error?te.message:"Failed to run action")}finally{T.current.delete(fe)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,$,s,i,J,c,a,m,S,j,w,A,C,x,W?.id,o]),ee=l.useCallback(async V=>{const fe=cn(J,V.id),xe=S[fe];if(!xe)return;y(fe,"stopping");const te=Cy(o,xe.sessionId,1e3);try{await o.sendInput(xe.sessionId,"")}catch{}const re=await te;if(we.getState().getDirectoryState(xe.directory)?.tabs.find(Q=>Q.id===xe.tabId)?.terminalSessionId===xe.sessionId&&!re){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:xe.sessionId})}catch{}else try{await o.close(xe.sessionId)}catch{}x(xe.directory,xe.tabId,null)}j(fe),delete G.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe]},[J,S,j,x,o,y]),ie=l.useCallback(()=>{const V=le??B[0];if(!V)return;const fe=cn(J,V.id),xe=S[fe];if(xe?.status!=="stopping"){if(xe){ee(V);return}X(V)}},[B,J,X,S,le,ee]),Ce=l.useCallback((V,fe=!1)=>{if(P(V.id),!fe){X(V);return}const xe=cn(J,V.id),te=S[xe];if(te?.status!=="stopping"){if(te){ee(V);return}X(V)}},[J,X,S,ee]),pe=l.useCallback(()=>{W?.id&&(f(W.id),d("projects"),u(!0))},[u,d,f,W?.id]),je=le??B[0]??null,be=je?S[cn(J,je.id)]:null,ze=we(V=>be?V.sessions.get(be.directory)?.tabs.find(fe=>fe.id===be.tabId)?.previewUrl??null:null),me=!!((s||!i)&&W&&J),Pe=le??B[0]??null;return{shouldRender:me,isLoading:z,normalizedDirectory:J,resolvedSelected:Pe,displayActions:B,projectActionRuns:S,selectedRunPreviewUrl:ze,handlePrimaryClick:ie,handleSelectAction:Ce,openProjectActionsSettings:pe,openContextPreview:m}}const nl=({projectRef:e,directory:t,className:s,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:a,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:m,handlePrimaryClick:g,handleSelectAction:b,openProjectActionsSettings:p,openContextPreview:h}=Ay({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const w=d.icon||"play",x=d.id===At?"scan-2":Ws[w]||"play",C=cn(c,d.id),S=f[C],A=S?.status==="stopping",y=S?.status==="waiting-for-preview",j=!!(S&&m),v=()=>{!S||!m||h(S.directory,m)},k=d.id===At;return r?n.jsxs("div",{className:"inline-flex items-center",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",disabled:a||A,className:_("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",s),onClick:g,"aria-label":S?`Stop ${d.name}`:`Run ${d.name}`,children:A||y?n.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):S?n.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):n.jsx(R,{name:x,className:"h-5 w-5"})})}),k?n.jsx(He,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),j?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.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:v,children:n.jsx(R,{name:"global",className:"h-4 w-4"})})}),n.jsx(He,{sideOffset:6,children:"Open preview"})]}):null,n.jsxs(Gt,{children:[n.jsx(qt,{asChild:!0,children:n.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:n.jsx(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),n.jsxs(Vt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[n.jsxs(dt,{className:"flex items-center gap-2",onClick:p,children:[n.jsx(R,{name:"add",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),n.jsx(us,{}),u.map(E=>{const P=E.icon||"play",z=E.id===At?"scan-2":Ws[P]||"play",K=cn(c,E.id),q=f[K],G=!!q,F=q?.status==="stopping";return n.jsxs(dt,{className:"flex items-center gap-2",onClick:()=>{b(E,!0)},children:[n.jsx(R,{name:z,className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E.name}),F||q?.status==="waiting-for-preview"?n.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):G?n.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},E.id)})]})]})]}):n.jsxs("div",{className:_("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",s),children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:g,disabled:a||A,className:_("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":S?`Stop ${d.name}`:`Run ${d.name}`,children:n.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||y?n.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):S?n.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):n.jsx(R,{name:x,className:"h-4 w-4"})})})}),k?n.jsx(He,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),j?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:v,className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open preview",children:n.jsx(R,{name:"global",className:"h-4 w-4"})})}),n.jsx(He,{sideOffset:6,children:"Open preview"})]}):null,n.jsxs(Gt,{children:[n.jsx(qt,{asChild:!0,children:n.jsx("button",{type:"button",className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:n.jsx(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),n.jsxs(Vt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[n.jsxs(dt,{className:"flex items-center gap-2",onClick:p,children:[n.jsx(R,{name:"add",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),n.jsx(us,{}),u.map(E=>{const P=E.icon||"play",z=E.id===At?"scan-2":Ws[P]||"play",K=cn(c,E.id),q=f[K],G=!!q,F=q?.status==="stopping";return n.jsxs(dt,{className:"flex items-center gap-2",onClick:()=>{b(E,!0)},children:[n.jsx(R,{name:z,className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E.name}),F||q?.status==="waiting-for-preview"?n.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):G?n.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},E.id)})]})]})]})},$t={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function Ar(e){return e?.deploymentKind==="docker"?{name:$t.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:$t.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:$t.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:$t.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:$t.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:$t.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:$t.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:$t.centos,color:"#932279"}:{name:$t.linux}:e?.serverPlatform==="darwin"?{name:$t.darwin}:{name:$t.unknown}}const Ny=e=>e?.deploymentKind==="docker"?"Docker":e?.serverPlatform==="win32"?"Windows":e?.serverPlatform==="darwin"?"macOS":e?.serverPlatform==="linux"?typeof e.serverDistribution=="string"&&e.serverDistribution.trim()?{ubuntu:"Ubuntu",arch:"Arch Linux",nixos:"NixOS",fedora:"Fedora",debian:"Debian",centos:"CentOS"}[e.serverDistribution]??"Linux":"Linux":"Server";function Iy({open:e,onOpenChange:t}){const[s,r]=l.useState(null),o=l.useCallback(async()=>{const u=Ze();try{const f=await nt("/api/version");if(!f.ok)throw new Error("Version request failed");const m=await f.json().catch(()=>null);u===Ze()&&r(m)}catch{u===Ze()&&r(null)}},[]);l.useEffect(()=>(o(),bs(()=>{o()})),[o]);const i=Ar(s),a=Ny(s),c=typeof s?.pichamberVersion=="string"?s.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return n.jsxs(Gt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx(qt,{asChild:!0,children:n.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(ws,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[n.jsx(R,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),n.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),n.jsx(He,{children:n.jsx("p",{children:"Connected server information"})})]}),n.jsxs(Vt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(R,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),n.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:a})]}),c?n.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),n.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),n.jsxs("button",{type:"button",className:"ml-auto flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:`Copy ${d}`,"aria-label":"Copy server address",onClick:()=>{fn(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[n.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),n.jsx(R,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const Ey=({isMobile:e})=>{const s=Un().github??null,r=Ur(i=>i.refresh),o=Qp();return l.useEffect(()=>{!s||e||r(s)},[s,e,r]),e||!s||!o?null:n.jsxs("span",{className:_(ws,"app-region-no-drag inline-flex w-auto cursor-default gap-1.5 px-2"),title:`${o} via GitHub CLI`,"aria-label":`Signed in to GitHub as ${o} via GitHub CLI`,children:[n.jsx(R,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),n.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},Dy=l.memo(function({isDesktopApp:t,currentInstanceLabel:s,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:m,remoteUpdateError:g,onOpenRemoteUpdate:b}){return n.jsxs(Gt,{open:a,onOpenChange:p=>{c(p),p&&d()},children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx(qt,{asChild:!0,children:n.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${s})`:"Open services, usage and MCP",className:_(ws,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[n.jsx(R,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?n.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),n.jsx(He,{children:n.jsx("p",{children:`Current instance: ${s} (${u("toggle_services_menu")})`})})]}),n.jsx(Vt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?n.jsxs("div",{children:[o?null:n.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),n.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:m?"Looking for updates...":g||"This instance is up to date."})]}),f?.available?n.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:b,children:"Update"}):null]})}),n.jsx(xf,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),Ry=({action:e,onClose:t,sessionTitle:s,onConfirm:r})=>n.jsx(en,{open:e!==null,onOpenChange:o=>{o||t()},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:e==="delete"?"Delete session?":"Archive session?"}),n.jsx(Cn,{children:e==="delete"?`"${s}" will be permanently deleted.`:`"${s}" will be archived.`})]}),n.jsxs(gs,{children:[n.jsx(Ae,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Py=e=>{const t=e.trim();if(!t)return"";const s=t.split(/\s+/).filter(Boolean);if(s.length>=2){const r=s[0],o=s[1].slice(0,3),i=`${r} ${o}`.trim();return s.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},Ms=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},Ty=l.lazy(()=>ht(()=>import("./SessionSwitcherDropdown-DiBGmmtD.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),mv=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:s,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:a=!1})=>{Wt("ui.header.render");const c=ue(O=>O.setSessionSwitcherOpen),d=ue(O=>O.toggleSidebar),u=ue(O=>O.isSidebarOpen),f=ue(O=>O.activeMainTab),m=ue(O=>O.setActiveMainTab),g=ue(O=>O.shortcutOverrides);ue(O=>O.timeFormatPreference),Un();const b=Me(O=>!!O.newSessionDraft?.open),p=Me(O=>O.currentSessionId),h=Cl(p??""),w=yf(p),x=l.useMemo(()=>{if(!w)return null;const O=w;return{title:w.title??null,directory:O.directory??null,created:w.time?.created??null,slug:O.slug??null,shareUrl:w.share?.url??null,parentId:w.parentID??null,messageCount:typeof w.messageCount=="number"?w.messageCount:null}},[w]),C=ct(Po(O=>{if(!O.activeProjectId)return null;const ce=O.projects.find(ye=>ye.id===O.activeProjectId);return ce?{id:ce.id,path:ce.path,label:ce.label}:null})),S=hs(O=>O.homeDirectory),A=l.useMemo(()=>C?wf(C):null,[C]),{isMobile:y}=ms(),{enabled:j}=xi(),v=!!(j&&i&&o!==void 0),k=l.useMemo(()=>[...ey(a)],[a]),[E,P]=l.useState(!1),z=l.useRef(null),[K,q]=l.useState(()=>typeof window>"u"?!1:fs()),G=l.useMemo(()=>Fl(),[]),F=vf(),[D,T]=l.useState(!1),I=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=El(),H=l.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 ce=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ce)return null;const ye=Number.parseInt(ce[1],10),$e=Number.parseInt(ce[2],10);return Number.isNaN(ye)?null:ye===10?$e:ye},[]);Te.useEffect(()=>{typeof window>"u"||q(fs())},[]);const W=ue(O=>O.isSessionSwitcherOpen),[L,ae]=l.useState(!1),[J,le]=l.useState("Local"),[Ie,Y]=l.useState(!0),[B,$]=l.useState(()=>Ar(null)),[X,ee]=l.useState(!1),[ie,Ce]=l.useState(null),[pe,je]=l.useState(!1),[be,ze]=l.useState(null),me=l.useRef(0),Pe=l.useMemo(()=>Py(J),[J]),V=l.useCallback(async()=>{if(typeof window>"u"||!K)return;const O=Ze(),ce=()=>Ze()===O;try{const ye=await nt("/api/version");if(!ce())return;const $e=ye.ok?await ye.json().catch(()=>null):null;if(!ce())return;if($(Ar($e)),Ir()){le("Local"),Y(!0);return}Y(!1);const ft=await Xf();if(!ce())return;const Je=Zf(),vt=eh([th(Je),...ft.hosts]);if(vt.id===nh){le("Local"),Y(!0);return}le(sh(vt.label.trim()||"Instance"))}catch{ce()&&(le("Local"),Y(!0),$(Ar(null)))}},[K]);Te.useEffect(()=>(V(),bs(()=>{me.current+=1,Ce(null),ze(null),je(!1),ee(!1),V()})),[V]);const fe=l.useCallback(async()=>{const O=me.current+1;me.current=O;const ce=Ze(),ye=()=>me.current===O&&Ze()===ce;if(Ie){Ce(null),ze(null);return}je(!0),ze(null);try{const $e=new URLSearchParams({appType:"web",instanceMode:"remote"}),ft=await nt(`/api/pi/update-check?${$e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ft.ok)throw new Error(`Server responded with ${ft.status}`);const Je=await ft.json();if(!ye())return;Ce({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch($e){if(!ye())return;Ce(null),ze($e instanceof Error?$e.message:"Failed to check remote instance updates")}finally{ye()&&je(!1)}},[Ie]);l.useEffect(()=>Ep(()=>{Ie||fe()}),[fe,Ie]),l.useEffect(()=>{me.current+=1,Ce(null),ze(null),je(!1),ee(!1)},[Ie,J]),l.useEffect(()=>{if(!K||Ie)return;const O=3e3,ce=3600*1e3;let ye=!1,$e=null;const ft=Je=>{$e=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){ft(ce);return}fe().finally(()=>{ye||ft(ce)})},Je)};return ft(O),()=>{ye=!0,$e!==null&&window.clearTimeout($e)}},[fe,Ie,J,K]);const xe=l.useCallback(()=>{if(ie?.available){ee(!0);return}fe()},[fe,ie?.available]),te=p?x??null:null,re=l.useRef(null),[Be,ke]=l.useState(0);l.useEffect(()=>{if(!p){re.current&&(re.current=null,ke($e=>$e+1));return}if(te){re.current={sessionId:p,session:te,expiresAt:Date.now()+2e3};return}const O=re.current;if(!O||O.sessionId!==p)return;const ce=O.expiresAt-Date.now();if(ce<=0){re.current=null,ke($e=>$e+1);return}const ye=window.setTimeout(()=>{re.current?.sessionId===p&&(re.current=null),ke($e=>$e+1)},ce);return()=>{window.clearTimeout(ye)}},[p,te]);const Q=(()=>{if(te)return te;if(!p)return null;const O=re.current;return O&&O.sessionId===p&&O.expiresAt>Date.now()?O.session:null})(),ve=l.useMemo(()=>{const O=typeof Q?.directory=="string"?Q.directory:"";return Ms(O||"")},[Q?.directory]),he=Me(O=>O.newSessionDraft?.open?Ms(O.newSessionDraft.directoryOverride??""):""),Se=l.useMemo(()=>sy({sessionDirectory:ve,draftDirectory:he,isNewSessionDraftOpen:b}),[he,b,ve]),Ue=Oo(Se||null),U=l.useMemo(()=>ry({activeProjectLabel:A,openDirectory:Se,homeDirectory:S}),[A,S,Se]),ge=!!(U||Ue),se=l.useMemo(()=>p?un(Q,"Untitled session"):U??"PiChamber",[Q,p,U]),_e=Sf(),st=Me(O=>O.updateSessionTitle),pt=Me(O=>O.archiveSessions),Xe=Me(O=>O.deleteSessions),[Yt,mt]=l.useState(!1),[Nt,nn]=l.useState(!1),Qe=l.useRef(!1),[Mt,Ft]=l.useState(""),[jt,Ee]=l.useState(null),Ye=l.useRef(null);l.useEffect(()=>{Qe.current=!1,nn(!1),mt(!1),Ft(""),Ee(null)},[p]);const Ne=l.useCallback(()=>{p&&(Ft(Q?.title?.trim()||se),mt(!0))},[Q?.title,p,se]),De=l.useCallback(async()=>{if(!p)return;const O=Mt.trim();O&&O!==Q?.title?.trim()&&await st(p,O),mt(!1)},[Q?.title,p,Mt,st]);l.useEffect(()=>{if(!Yt)return;const O=ce=>{const ye=ce.target;(!ye||!Ye.current?.contains(ye))&&De()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[Yt,De]);const Ge=l.useCallback(()=>{p&&fn(p).then(O=>{oe[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[p]),ut=l.useCallback(async()=>{if(!p||!Se){oe.error("Nothing to export");return}try{await _e.syncSession(p)}catch{oe.error("Failed to load the complete session history");return}const O=[];if(O.length===0){oe.error("Nothing to export");return}const ce=Lc(O,Q?.title??null),ye=_c(Q?.title??null);await Bc(ce,ye)||Oc(ce,ye),oe.success("Session exported")},[Q?.title,p,Se,_e]);h?.type==="busy"||h?.type;const sn=l.useCallback(async()=>{if(!p||!jt)return;const O=jf(),ce=[p];for(let Je=0;Je<ce.length;Je+=1){const vt=ce[Je];for(const Dt of O)Dt.parentID===vt&&!ce.includes(Dt.id)&&ce.push(Dt.id)}const ye=jt;if(Ee(null),(ye==="archive"?await pt(ce):await Xe(ce)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[pt,p,Xe,jt]),Lt=ue(O=>O.isArchivePageOpen),Ot=l.useMemo(()=>Lt?{title:"Archive",subtitle:null}:null,[Lt]),Ve=l.useMemo(()=>Ms(Se||C?.path||""),[C?.path,Se]),rn=l.useCallback(()=>{Ve&&fn(Ve).then(O=>{oe[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[Ve]),An=l.useCallback(()=>{Ue&&fn(Ue).then(O=>{oe[O.ok?"success":"error"](O.ok?"Branch name copied":"Failed to copy branch name")}).catch(()=>oe.error("Failed to copy branch name"))},[Ue]),It=l.useMemo(()=>C?{id:C.id,path:C.path}:null,[C]),Kn=l.useRef(null);l.useEffect(()=>{!It||!Ve||(Kn.current={projectRef:It,directory:Ve})},[Ve,It]);const bt=l.useMemo(()=>It&&Ve?{projectRef:It,directory:Ve}:Kn.current,[Ve,It]),rt=l.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const ce=O.tagName;(ce==="INPUT"||ce==="TEXTAREA"||ce==="SELECT"||O.isContentEditable)&&O.blur()},[]),Qt=l.useCallback(()=>{if(y){rt(),c(!W);return}d()},[rt,y,W,c,d]),Bt=l.useCallback(()=>{Us("desktop_open_draft_mini_chat_window",{directory:Ms(Se||C?.path||""),projectId:C?.id??null,apiBaseUrl:$o(),clientToken:Uo()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[C?.id,C?.path,Se]),gn=l.useCallback(()=>{if(b){Bt();return}p&&Us("desktop_open_session_mini_chat_window",{sessionId:p,directory:Ms(Se||C?.path||""),apiBaseUrl:$o(),clientToken:Uo()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[C?.path,p,Bt,b,Se]),on=ws,xt=om,yt=l.useMemo(()=>s?"sessions":v?r&&o?o:null:r?"git":f,[f,v,s,r,o]),Et=l.useCallback(()=>{s&&e&&e(),r&&t&&t(),!e&&W&&c(!1)},[W,s,e,t,r,c]),Wn=l.useCallback(()=>{e?.()},[e]),Nn=l.useCallback(()=>{t?.()},[t]),In=l.useMemo(()=>K&&I&&!D?"5.5rem":F?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!K||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,D,I,F,M]);Te.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",In)},[In]);const kt=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",an=u?"0px":K&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":j?"2.75rem":"2.5rem";Te.useEffect(()=>{if(!K||!I){T(!1);return}let O=!1;const ce=async()=>{try{const $e=await Us("desktop_is_window_fullscreen");O||T($e===!0)}catch{O||T(!1)}},ye=()=>{ce()};return ce(),window.addEventListener("pichamber:window-resized",ye),()=>{O=!0,window.removeEventListener("pichamber:window-resized",ye)}},[K,I]);const tt=l.useMemo(()=>!K||!I||H===null?"":H>=26?"h-12":H<=15?"h-14":"",[K,I,H]),ln=l.useMemo(()=>{if(!(K&&!M))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))"}},[K,M]),wt=l.useCallback(()=>{if(typeof document>"u")return;const O=z.current?.getBoundingClientRect().height;if(O){const ce=`${O}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==ce&&ye.setProperty("--oc-header-height",ce)}},[]);Te.useEffect(()=>{if(typeof window>"u")return;wt();const O=z.current;if(!O||typeof ResizeObserver>"u")return()=>{};let ce=0;const ye=()=>{ce||(ce=requestAnimationFrame(()=>{ce=0,wt()}))},$e=new ResizeObserver(ye);return $e.observe(O),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{ce&&cancelAnimationFrame(ce),$e.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[wt]),Te.useEffect(()=>{wt()},[wt,y,tt]);const Ct=l.useCallback(async O=>{const ce=O.target;ce.closest(".app-region-no-drag")||ce.closest("button, a, input, select, textarea")||O.button===0&&K&&await kf()},[K]),ot=l.useMemo(()=>y?[{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"}]:[],[y]),En=l.useCallback(O=>wi(Nr(O,g)),[g]);Te.useEffect(()=>{!y&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&m("chat")},[f,y,m]),Te.useEffect(()=>{const O=ce=>{if(rh(ce)&&!ce.shiftKey&&!ce.altKey){const ye=parseInt(ce.key,10);ye>=1&&ye<=ot.length&&(ce.preventDefault(),y&&(rt(),Et()),m(ot[ye-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[rt,Et,y,m,ot]),Te.useEffect(()=>{const O=ce=>{const ye=Nr("toggle_services_menu",g);if(oh(ce,ye)){ce.preventDefault(),L?ae(!1):(ae(!0),V());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[g,L,V]);const it=O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon,ft=O.id==="chat",Je=Dt=>ye?n.jsx(Za,{size:Dt}):$e?n.jsx(R,{name:$e,className:`h-${Dt/4} w-${Dt/4}`}):null,vt=n.jsxs("button",{type:"button",onClick:()=>m(O.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ce?"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",ft&&!y&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":ce,role:"tab",children:[y?Je(20):n.jsxs(n.Fragment,{children:[Je(16),n.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&n.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return n.jsx(l.Fragment,{children:vt},O.id)},Hn=n.jsxs(n.Fragment,{children:[n.jsx(ly,{directory:Ve,className:"mr-1"}),K?n.jsx(Dy,{isDesktopApp:K,currentInstanceLabel:J,compactCurrentInstanceLabel:Pe,currentInstanceIsLocal:Ie,currentInstanceIcon:B,isDesktopServicesOpen:L,setIsDesktopServicesOpen:ae,refreshCurrentInstanceLabel:V,shortcutLabel:En,remoteUpdateInfo:ie,remoteUpdateChecking:pe,remoteUpdateError:be,onOpenRemoteUpdate:xe}):n.jsx(Iy,{open:L,onOpenChange:ae}),n.jsx(Ey,{isMobile:y})]}),Gn=G&&(b||!!p),js=()=>n.jsxs("div",{onMouseDown:Ct,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",tt),style:ln,role:"tablist","aria-label":"Main navigation",children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:kt}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:an}}),n.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ot?n.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:[n.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:Ot.title}),Ot.subtitle?n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),n.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-subtle-foreground max-w-full",children:Ot.subtitle})]}):null]}):n.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:n.jsx(l.Suspense,{fallback:n.jsx("button",{type:"button",className:on,"aria-label":"Open session switcher",children:n.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:n.jsx(Ty,{align:"start",children:n.jsx("button",{type:"button",className:on,"aria-label":"Open session switcher",children:n.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Yt?n.jsxs("form",{ref:Ye,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),De()},children:[n.jsx("input",{value:Mt,onChange:O=>Ft(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&mt(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),n.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(R,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:()=>mt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(R,{name:"close",className:"size-4"})})]}):n.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":se}),ge?n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-subtle-foreground",children:[U?n.jsx("span",{className:"truncate",children:U}):null,Ue?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[n.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-subtle-foreground"}),n.jsx("span",{className:"truncate",children:Ue})]}):null]})]}):null]}),n.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:p&&!b&&!Yt?n.jsxs(Gt,{open:Nt,onOpenChange:nn,onOpenChangeComplete:O=>{!O&&Qe.current&&(Qe.current=!1,Ne())},children:[n.jsx(qt,{asChild:!0,children:n.jsx(Ae,{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:n.jsx(R,{name:"more",className:"size-4"})})}),n.jsxs(Vt,{align:"end",className:"min-w-[190px]",children:[n.jsxs(dt,{onClick:()=>{Qe.current=!0},children:[n.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),n.jsxs(dt,{onClick:Ge,children:[n.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),n.jsxs(dt,{onClick:rn,disabled:!Ve,children:[n.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),Ue?n.jsxs(dt,{onClick:An,children:[n.jsx(R,{name:"git-branch",className:"mr-2 size-4"}),"Copy branch name"]}):null,n.jsx(us,{}),n.jsxs(dt,{onClick:()=>{ut()},children:[n.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),n.jsx(us,{}),n.jsxs(dt,{onClick:()=>Ee("archive"),children:[n.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),n.jsxs(dt,{className:"text-destructive focus:text-destructive",onClick:()=>Ee("delete"),children:[n.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),ot.length>0&&n.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:ot.map(O=>it(O))}),n.jsx("div",{className:"flex-1"}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(oc,{}),bt?n.jsx(nl,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,n.jsx(im,{visible:Gn,title:b?"New Mini Chat window":"Open session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:gn,className:_(on,"mr-1"),Icon:"picture-in-picture-2"}),Hn,n.jsx(Cf,{visible:M})]})]})]}),Dn=()=>n.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[j&&n.jsxs(n.Fragment,{children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:kt}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:an}})]}),!j&&n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?n.jsx("button",{type:"button",onClick:Wn,className:_(xt,yt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":s?"Close sessions":"Open sessions",children:n.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):W?n.jsx("button",{type:"button",onClick:()=>c(!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:n.jsx(R,{name:"arrow-left-s",className:"h-5 w-5"})}):n.jsx("button",{type:"button",onClick:Qt,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:n.jsx(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&W&&n.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!W||!!e)&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!v&&n.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:n.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:n.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:ot.map(O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon;return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsxs("button",{type:"button",onClick:()=>{y&&(rt(),Et()),m(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(xt,"relative rounded-lg",yt===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?n.jsx(Za,{className:"h-5 w-5"}):$e?n.jsx(R,{name:$e,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&n.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&n.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),n.jsx(He,{children:n.jsx("p",{children:O.label})})]},O.id)})})})})}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:k.map(O=>{const ce=r&&o===O.id;return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>{y&&(rt(),Et()),P(!1),i?.(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(xt,"relative h-11 w-11 rounded-lg",ce&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(R,{name:O.icon,className:"h-5 w-5"})})}),n.jsx(He,{children:n.jsx("p",{children:O.label})})]},O.id)})}),n.jsx(rm,{open:E,onOpenChange:P,currentSessionId:p,effectiveDirectory:Se||null,isNewSessionDraftOpen:b})]}),bt&&n.jsx(nl,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!v?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:Nn,className:_(xt,"relative",yt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:n.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),n.jsx(He,{children:n.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),ks=_("header-safe-area relative z-10 bg-background",y&&"border-b border-border/50");return n.jsxs(n.Fragment,{children:[n.jsx("header",{ref:z,className:ks,style:{"--padding-scale":"1"},children:y?Dn():js()}),n.jsx(Ry,{action:jt,onClose:()=>Ee(null),sessionTitle:se,onConfirm:()=>{sn()}}),n.jsx(Ql,{open:X,onOpenChange:ee,info:ie,downloading:!1,downloaded:!1,progress:null,error:be,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},sl="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",My="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",gv=()=>{const e=ue(b=>b.isSidebarOpen),t=ue(b=>b.toggleSidebar),s=ue(b=>b.shortcutOverrides),r=l.useRef(null),o=l.useRef(null),i=wi(Nr("toggle_sidebar",s)),a=El(),{enabled:c}=xi(),d=!e,u=a,f=d||u,m=u,g=l.useCallback(()=>{Us("desktop_show_app_menu").catch(b=>{console.warn("[titlebar] failed to open app menu",b)})},[]);return l.useEffect(()=>{if(typeof document>"u")return;const b=S=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(S)}px`)},p=S=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(S)}px`)};if(!m)return;const h=o.current,w=r.current;if(!h||!w){b(0),p(0);return}const x=()=>{const S=Math.max(h.getBoundingClientRect().width,h.scrollWidth);b(S),p(w.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const C=new ResizeObserver(x);return C.observe(h),C.observe(w),()=>{C.disconnect()}},[m]),f?n.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:n.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:g,"aria-label":"Open PiChamber menu",className:_(sl,"shrink-0"),children:n.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),n.jsx(He,{children:n.jsx("p",{children:"PiChamber menu"})})]}):null,d?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?My:sl,"shrink-0"),children:n.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),n.jsx(He,{children:n.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},rl=200,Fy="cubic-bezier(0.22, 1, 0.36, 1)",bv=e=>{const t=l.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[s,r]=l.useState(e),[o,i]=l.useState(e);return l.useLayoutEffect(()=>{if(t){i(e),r(e);return}if(e){i(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const a=window.setTimeout(()=>i(!1),rl);return()=>window.clearTimeout(a)},[e,t]),{slidIn:s,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${rl}ms ${Fy}`}},xv=()=>{Ol()},yv=e=>{Me.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ue.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),we.getState().clearAll(),Ol(),hs.getState().resetForRuntimeSwitch(),Af.getState().resetForRuntimeSwitch(),Nf.getState().resetForRuntimeSwitch(),If(),ih(),ah(),Tf(),Ef.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ct.getState().resetForRuntimeSwitch(),Df(),Rf(),Sh.getState().reset(),lh.getState().resetForRuntimeSwitch(),wl.getState().resetForRuntimeSwitch(e.runtimeKey),Bo.getState().resetForRuntimeSwitch(e.runtimeKey),ch(),Bn.getState().resetForRuntimeSwitch(e.runtimeKey),Pf.getState().resetForRuntimeSwitch(),Zt.getState().resetForRuntimeSwitch(),gt.getState().resetForRuntimeSwitch(e.runtimeKey),dh.getState().resetForRuntimeSwitch(e.runtimeKey),Me.getState().restoreForRuntimeSwitch(e.runtimeKey),ue.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=ue.getState();Go({sessionId:Me.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{nr as $,$w as A,Ap as B,Sw as C,Ha as D,pw as E,nw as F,Si as G,mv as H,dw as I,Cp as J,ec as K,Ks as L,rc as M,iw as N,tw as O,Gp as P,jp as Q,Ip as R,iv as S,dv as T,Ql as U,hw as V,Jy as W,Zl as X,sr as Y,gw as Z,Np as _,rm as a,rv as a$,Xl as a0,fw as a1,rw as a2,Sp as a3,yw as a4,bw as a5,Ur as a6,xw as a7,ww as a8,mw as a9,zw as aA,Aw as aB,Bw as aC,Ow as aD,Fw as aE,Hr as aF,Gr as aG,qr as aH,On as aI,Ec as aJ,Xp as aK,Zp as aL,ua as aM,pv as aN,Ph as aO,Pn as aP,Sn as aQ,Zt as aR,Ic as aS,bc as aT,er as aU,gc as aV,sw as aW,Yy as aX,Vw as aY,Kw as aZ,Yw as a_,aw as aa,lw as ab,cw as ac,Lw as ad,Up as ae,uw as af,Jl as ag,rp as ah,kp as ai,Xy as aj,op as ak,np as al,Nw as am,kw as an,jw as ao,Cw as ap,Mw as aq,Tw as ar,Ew as as,Iw as at,Dw as au,Jp as av,Pw as aw,Rw as ax,_w as ay,Uw as az,Ls as b,ov as b0,Qp as b1,Xw as b2,Qw as b3,Hw as b4,Jw as b5,ev as b6,tv as b7,nv as b8,sv as b9,Zw as ba,qw as bb,Ww as bc,oi as bd,Ca as be,Tn as bf,Ts as bg,Ss as bh,vg as bi,vs as bj,Gw as bk,lx as c,av as d,kr as e,ey as f,lv as g,Tx as h,ux as i,uv as j,Wc as k,bv as l,hv as m,gv as n,xv as o,yv as p,Zy as q,fv as r,cv as s,ew as t,nm as u,Qy as v,Vy as w,ow as x,vp as y,vw as z};
|