@pi-chamber/web 1.0.7-rc.1 → 1.0.7
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-DyF8zzYx.js → DiagramView-BB-aZobi.js} +1 -1
- package/dist/assets/{DiffView-C3rA5DfE.js → DiffView-BxW6BuOC.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-CC4F--8H.js → FileSaveConflictDialog-Bzz8FNMq.js} +1 -1
- package/dist/assets/{FilesView-Dsg-QTJu.js → FilesView-DECxN8Z0.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-C9WuBMGr.js → GitHubDetailScaffold-CWsWycRd.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-BkVdYxZT.js → GitHubLinkPicker-BVYdg_e8.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-CcVlv_rJ.js → GitHubListPrimitives-Dlv3tC4d.js} +1 -1
- package/dist/assets/{GitView-OpFCss_4.js → GitView-DD33ngnM.js} +3 -3
- package/dist/assets/{IssuesSurface-DD6Gz5Ox.js → IssuesSurface-BAY_eyX5.js} +1 -1
- package/dist/assets/{JsonTreeView-Dj75jgH6.js → JsonTreeView-DpXbUrAl.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CnIzmT1p.js → MarkdownRendererImpl-Cn63lAmn.js} +1 -1
- package/dist/assets/{PatchDiff-DND5RBnF.js → PatchDiff-BklyOEHs.js} +1 -1
- package/dist/assets/{PierreDiffViewer-Cq5CIrmH.js → PierreDiffViewer-wc6cB6qw.js} +1 -1
- package/dist/assets/{PullRequestsSurface-g8HAvbFg.js → PullRequestsSurface-BZvJkT1I.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-CUz6Cc1-.js → SessionSwitcherContent-CscYekC1.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-COZ50Y5a.js → SessionSwitcherDropdown-DShvvGwC.js} +2 -2
- package/dist/assets/{SessionUnreadDot-DOUcgBw6.js → SessionUnreadDot-CbqRq6h_.js} +1 -1
- package/dist/assets/{SettingsView-AFymxZYC.js → SettingsView-DcF-At5E.js} +3 -3
- package/dist/assets/{SettingsWindow-J6YOvGcV.js → SettingsWindow-gxjULdm1.js} +1 -1
- package/dist/assets/{ToolOutputDialog-5Tc7HM4z.js → ToolOutputDialog-DdMIfrnK.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-7GiFbVl7.js → ToolPartDiffPreview-C6Sm4eVf.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-Dq8pyTGy.js → VirtualizedFileDiff-BrbPymTL.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-uXZ9uhI_.js → computeVirtualFileMetrics-G4csGiKs.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-CckKFYjI.js → contextFileOpenGuard-UU86YHgI.js} +1 -1
- package/dist/assets/{fileTreeStatus-C_7jbeGv.js → fileTreeStatus-Bskhj4qT.js} +1 -1
- package/dist/assets/{gitStatusPredicates-CNLvdt2V.js → gitStatusPredicates-DQEO4Psc.js} +1 -1
- package/dist/assets/{githubLink-0EoMGZKd.js → githubLink-ByPAyFjh.js} +1 -1
- package/dist/assets/{index-DD0xW5WE.js → index-ComwtfT4.js} +1 -1
- package/dist/assets/{main-BnWf2tm9.js → main-DoiadX0a.js} +2 -2
- package/dist/assets/{main-yQe-k30g.js → main-DyFfbllq.js} +4 -4
- package/dist/assets/{markdownCore-C-Ulh4n9.js → markdownCore-DczkEluO.js} +1 -1
- package/dist/assets/{miniChat-DKK1hotU.js → miniChat-Ck6MEZ9Q.js} +2 -2
- package/dist/assets/{mobile-BuAWpKj9.js → mobile-BucKVm1P.js} +2 -2
- package/dist/assets/{pi-session-focus-preference-DaWQ2rEE.js → pi-session-focus-preference-Dx0UXPoO.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-DD-iWWus.js → renderDiffWithHighlighter-PL82AR81.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CKuFQBRo.js → renderElectronMiniChatApp-Cb7s7dWl.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-B0pofdV1.js → renderFileWithHighlighter-CYgfbA4F.js} +1 -1
- package/dist/assets/{renderMobileApp-B3P_bita.js → renderMobileApp-Bp74b_Lo.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-DutinXZK.js → runtimeEndpointReset-7nWYnKd4.js} +4 -4
- package/dist/assets/{useAppFontEffects-DQlUEhzN.js → useAppFontEffects-ZTyNwFk6.js} +6 -6
- package/dist/assets/{useGitHubRemoteSearch-BoZvJAk3.js → useGitHubRemoteSearch-BF3ohpsh.js} +1 -1
- package/dist/assets/{useSwitcherItems-Dy2yumiU.js → useSwitcherItems-BJzwyDGX.js} +1 -1
- package/dist/assets/{web-components-DB-GDG7P.js → web-components-CGDpzixf.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/mini-chat.html +1 -1
- package/dist/mobile.html +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
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-DQlUEhzN.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-I2QYqABE.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-DOUcgBw6.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-Cp9i5QGd.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-DD0xW5WE.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-I2QYqABE.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:`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-ComwtfT4.js","assets/useAppFontEffects-ZTyNwFk6.js","assets/index-I2QYqABE.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-CFwnvks_.js","assets/nativeFileSave-Cp9i5QGd.js","assets/computeVirtualFileMetrics-G4csGiKs.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-CYgfbA4F.js","assets/renderDiffWithHighlighter-PL82AR81.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-DShvvGwC.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-ZTyNwFk6.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-I2QYqABE.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-CbqRq6h_.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-Cp9i5QGd.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-ComwtfT4.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-I2QYqABE.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
3
|
@keyframes session-metadata-in {
|
|
4
4
|
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
5
|
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
@@ -17,7 +17,7 @@ ${r}`},ja=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:n
|
|
|
17
17
|
`)[1]??"",oi=(e,t)=>`${hn(e)}
|
|
18
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
19
|
`);if(c!==r)continue;const[,,d]=a.split(`
|
|
20
|
-
`);d&&ht(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-I2QYqABE.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-I2QYqABE.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-DQlUEhzN.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-I2QYqABE.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-DQlUEhzN.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}**
|
|
20
|
+
`);d&&ht(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-I2QYqABE.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-I2QYqABE.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-ZTyNwFk6.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-I2QYqABE.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-ZTyNwFk6.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
21
|
|
|
22
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
23
|
|
|
@@ -59,4 +59,4 @@ ${s}`:""}function Fc(e,t){const s="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${
|
|
|
59
59
|
`):a.slice(0,-1).join(`
|
|
60
60
|
`);if(this.tail=i.endsWith(`
|
|
61
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-COZ50Y5a.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};
|
|
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-DShvvGwC.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};
|