@pi-chamber/web 1.0.6-rc.1 → 1.0.6-rc.2
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-DUxXEKjQ.js → DiagramView-BdDt1SI7.js} +1 -1
- package/dist/assets/{DiffView-DEd3rdnu.js → DiffView-Dk3VIX9E.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-C6o4fYIn.js → FileSaveConflictDialog-DpyPjMH1.js} +1 -1
- package/dist/assets/{FilesView-Ccl4CxjR.js → FilesView-CumrwioK.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-DlgVm5uD.js → GitHubDetailScaffold-CW2ZqU0Y.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-BgDZR-3K.js → GitHubLinkPicker-BjJNQ7Ap.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-BTeI3B3C.js → GitHubListPrimitives-BcB-cCTs.js} +1 -1
- package/dist/assets/{GitView-BkrH0HFQ.js → GitView-BoCaX5AO.js} +3 -3
- package/dist/assets/{IssuesSurface-CD1m8BHP.js → IssuesSurface-CDZENHrE.js} +1 -1
- package/dist/assets/{JsonTreeView-RLgBKik9.js → JsonTreeView-DpCgOUXg.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-BkfhE9NN.js → MarkdownRendererImpl-BkT5TUWF.js} +1 -1
- package/dist/assets/{PatchDiff-BLNLrGYa.js → PatchDiff-Dcr3EQgA.js} +1 -1
- package/dist/assets/{PierreDiffViewer-iLnLAFeL.js → PierreDiffViewer-o_Edh6ny.js} +1 -1
- package/dist/assets/{PullRequestsSurface-_kgJMFTh.js → PullRequestsSurface-eSXl6sef.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-BCOUKRch.js → SessionSwitcherContent-Dm30bfpn.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CA64t2xd.js → SessionSwitcherDropdown-CFj9VWSa.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BZy2DM6H.js → SessionUnreadDot-CHlK2awX.js} +1 -1
- package/dist/assets/{SettingsView-TwUy1kXV.js → SettingsView-CcHRUyev.js} +3 -3
- package/dist/assets/{SettingsWindow-BXE4JP-T.js → SettingsWindow-BMzUErrM.js} +1 -1
- package/dist/assets/{ToolOutputDialog-tiXT-Xts.js → ToolOutputDialog-QC8IoeBH.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CylbiIKd.js → ToolPartDiffPreview-BigGwtul.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-Cccy1L8L.js → VirtualizedFileDiff-DvLCd7Qq.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-ydVGT2RY.js → computeVirtualFileMetrics-aX6tjjqv.js} +1 -1
- package/dist/assets/{contextFileOpenGuard--7BLkncT.js → contextFileOpenGuard-CZKJuHxf.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BzR54iPh.js → gitStatusPredicates-3i8CcYWJ.js} +1 -1
- package/dist/assets/{githubLink-WO5BkC0U.js → githubLink-BvevcNay.js} +1 -1
- package/dist/assets/{index-nOAE6UDy.js → index-BMdbHCFt.js} +1 -1
- package/dist/assets/{main-B4UP1bOp.js → main-BM-b2y8p.js} +2 -2
- package/dist/assets/{main-DxYfmK5D.js → main-BXZ561E3.js} +4 -4
- package/dist/assets/{markdownCore-DIn2dwA6.js → markdownCore-DbS8DkKw.js} +1 -1
- package/dist/assets/{miniChat-CMGH4R_p.js → miniChat-DO3DW6kJ.js} +2 -2
- package/dist/assets/{mobile-BJz0lBjK.js → mobile-BgWLkut6.js} +2 -2
- package/dist/assets/{pi-session-focus-preference-D6vrJGbH.js → pi-session-focus-preference-ChYVctYk.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-JwKOWdBN.js → renderDiffWithHighlighter-xlvSvnTf.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-DYdkuv5N.js → renderElectronMiniChatApp-CgVqxKDm.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-RJTrDxFH.js → renderFileWithHighlighter-CCoYfC-t.js} +1 -1
- package/dist/assets/{renderMobileApp-x1P9U65-.js → renderMobileApp-CoY1tsk5.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-OqTh3bbO.js → runtimeEndpointReset-fozcAShH.js} +4 -4
- package/dist/assets/{useAppFontEffects-CHnpTOtc.js → useAppFontEffects-D_gtiA95.js} +6 -6
- package/dist/assets/{useFilesViewSearch-DeVixiGZ.js → useFilesViewSearch-BUxcZj60.js} +1 -1
- package/dist/assets/{useGitHubRemoteSearch-GjQca1iD.js → useGitHubRemoteSearch-CevR5iLf.js} +1 -1
- package/dist/assets/{useSwitcherItems-DYtnl0T2.js → useSwitcherItems-kaRkXggX.js} +1 -1
- package/dist/assets/{web-components-CIPJC1JE.js → web-components-6ORYp3Iv.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 mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as s,aS as Dd,aT as Pd,aU as Md,aV as Td,aW as Fd,aX as Ld,aY as Od,aZ as _o,a_ as Fn,a$ as Bd,b0 as Uo,b1 as zo,b2 as _d,b3 as Ud,b4 as zd,b5 as $d,b6 as Ca,b7 as Aa,b8 as Na,b9 as Ia,ba as Ea,bb as Ra,bc as Da,bd as Pa,be as Ma,bf as Ta,bg as Fa,bh as $o,bi as Ko,bj as oo,aP as Kd}from"./vendor-boot-CoTxysn6.js";import{a as Re,R as a}from"./vendor-react-Bz1tRBxM.js";import{aq as Zs,ar as Wd,t as oe,a as ct,h as Te,as as dn,B as Ne,I as P,at as Ln,au as La,av as ts,aw as ss,ax as ws,ay as ds,az as vs,aA as Ls,aB as Ms,v as gs,aC as Ts,aD as Gd,g as Js,aE as Br,aF as Si,aG as ji,aH as En,e as sr,aI as Hd,aJ as qd,aK as Yd,aL as Vd,aM as Qd,aN as Jd,o as Oa,aO as Is,aP as ki,ah as xs,aQ as $e,aR as Ke,aS as We,aT as io,aU as Xd,aV as Zd,aW as eu,aX as tu,aY as su,aZ as ao,a_ as nu,a$ as Gt,b0 as Ht,b1 as qt,O as Kt,b2 as ru,b3 as ou,b4 as iu,b5 as au,b6 as lu,b7 as cu,b8 as lo,r as Rn,G as Wo,b9 as du,ba as uu,bb as Ba,bc as _a,Z as ys,bd as fu,be as hu,bf as mu,bg as pu,d as Ua,z as Os,bh as za,bi as Sr,bj as Ci,bk as $a,bl as bt,bm as gu,bn as bu,bo as Ka,bp as Wa,bq as Ga,br as Ha,bs as Go,bt as qa,bu as ht,bv as Ya,bw as xu,i as Va,p as yu,bx as wu,j as vu,u as Qa,k as Su,m as ju,by as Ja,n as ku,q as Ai,bz as Cu,bA as qs,b as Ni,c as Au,bB as Nu,bC as Iu,bD as Eu,bE as co,bF as Ru,bG as Du,bH as Pu,bI as Mu,bJ as Tu,a4 as Fu,bK as nn,bL as Xa,M as Lu,y as Ou,bM as Bu,w as _u,bN as Uu,bO as Za,bP as zu,aj as $u,bQ as Ku,bR as Wu,bS as Gu,bT as Hu,bU as qu,bV as Yu,bW as Vu,bX as Qu,bY as Ju,bZ as Xu}from"./useAppFontEffects-CHnpTOtc.js";import{A as Ii,B as Zu,a as rn,C as el,D as tl,E as ef,F as tf,u as on,G as sf,H as nf,I as rf,h as ce,z as nt,f as _,J as of,K as Je,b as Ft,o as Un,L as af,M as lf,N as cf,O as df,q as Ee,P as On,Q as Wt,R as uo,T as fo,U as sl,n as cs,V as Ho,W as dr,X as uf,v as nl,Y as ff,Z as rl,_ as hf,$ as ol,a0 as Dn,a1 as ho,j as mo,e as Hn,a2 as mf,a3 as pf,a4 as gf,a5 as Ei,a6 as wn,a7 as _r,a8 as po,a9 as ur,aa as Es,ab as Ri,ac as go,ad as il,ae as bo,af as bf,ag as xf,ah as yf,ai as wf,aj as vf,ak as Sf,al as jf,am as kf,an as Cf,ao as al,ap as Af,aq as Nf,ar as If,as as Ef,at as Rf}from"./index-C2ISrmRR.js";import{b as Df,g as ll,r as Pf,d as cl,s as nr,c as dl,e as Fs,h as an,i as Mf,j as Tf,k as Ff,l as Lf,m as qo,n as ul,f as Of,a as Di,S as Bf,t as _f,o as Uf}from"./SessionUnreadDot-BZy2DM6H.js";import{c as Bs,d as jr,p as fl,a as zf}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{saveOrShareFile as $f}from"./nativeFileSave-Bhafll_7.js";import{usePermissionStore as Kf}from"./permissionStore-zIpxq9Pq.js";const Wf="chat";function hl(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Zs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Zs.SETTINGS,n),t}return e.tab!==Wf&&t.set(Zs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Zs.FILE,e.diffFile),t}function Gf(e,t){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Hf(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=hl(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Zs.SESSION)&&t.set(Zs.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==l.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==l[c][0]||i[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function xo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Hf(e)))try{const n=hl(e),r=Gf(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const qf=["typescript","javascript","tsx","jsx","json","markdown"],ml={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Pi=null;const pl=()=>(Pi??=Promise.all([mt(()=>import("./index-nOAE6UDy.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])),mt(()=>import("./workerFactory-DlGfNFqf.js"),[]),mt(()=>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,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),Pi),Bn={},Mi=new Set,yo=new Set;let rr={light:"pierre-light",dark:"pierre-dark"};const Yf=()=>{for(const e of yo)e()},gl=(e,t)=>{t.setRenderOptions({theme:rr,lineDiffType:ml[e].lineDiffType})},wo=e=>{typeof window>"u"||Mi.has(e)||(Mi.add(e),pl().then(t=>{if(Bn[e])return;const n=ml[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:qf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Bn[e]=r,gl(e,r),Yf()}))},Vf=e=>(yo.add(e),()=>yo.delete(e)),Qf=e=>{if(!(rr.light===e.light&&rr.dark===e.dark)){rr=e;for(const t of Object.keys(Bn)){const n=Bn[t];n&&gl(t,n)}}},Px=({children:e})=>{const t=Wd(),n=Ii(!1),r=Ii(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,l=t?.availableThemes.find(d=>d.metadata.id===o)??n,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Re.useEffect(()=>{let d=!1;return pl().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Qf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Re.useEffect(()=>{if(typeof window>"u")return;const d=()=>{wo("unified"),wo("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)},[]),s.jsx(s.Fragment,{children:e})},Mx=(e="unified")=>{const t=Re.useSyncExternalStore(Vf,()=>Bn[e],()=>{});return Re.useEffect(()=>{wo(e)},[e]),t},Jf=e=>e==="/",ln=e=>e.replace(/\\/g,"/"),cn=e=>{if(!e||Jf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},tn=e=>e.endsWith("/"),fr=e=>{const t=e.trim();return!t||tn(t)?t:`${t}/`},Yo=e=>e.lastIndexOf("/"),bl=e=>{if(tn(e))return e;const t=Yo(e);return t<0?e:e.slice(0,t+1)},xl=e=>{const t=Yo(e);return e.slice(t+1)},yl=e=>{const t=cn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Yo(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},wl=e=>tn(e)&&yl(e)!==null,Xf=e=>{if(!wl(e))return null;const t=cn(e.trim());return xl(t)||t},Zf=(e,t)=>`${bl(e)}${t}/`,Rs=e=>{if(!e)return null;const t=cn(ln(e.trim()));return t?t.toLowerCase():null},Ti=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},eh=(e,t)=>{const n=cn(ln(e.trim())),r=cn(ln(t.trim()));if(!n)return"";if(!r)return fr(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:fr(n)},th=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,vo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},sh=async()=>Zu({fresh:!0}),nh=()=>{const[e,t]=Re.useState(!1),[n,r]=Re.useState(!1);Re.useEffect(()=>{t(rn()),r(el())},[]);const o=Re.useCallback(async c=>e?await tl(c):{success:!0,path:c},[e]),i=Re.useCallback(async c=>e?await ef():{success:!0},[e]),l=Re.useCallback(async c=>e?await tf():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function rh({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=on(Q=>Q.homeDirectory),{canRequestAccess:o,startAccessing:i}=nh(),l=a.useRef(null),c=a.useRef(new Map),[d,u]=a.useState(""),[f,p]=a.useState("~/"),[x,y]=a.useState([]),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,w]=a.useState(null),[E,A]=a.useState(0),[k,j]=a.useState(0),[v,N]=a.useState(!1),[M,L]=a.useState(!1),[K,z]=a.useState("right"),$=a.useRef("~/"),O=d||r;a.useEffect(()=>{if(!e)return;p("~/"),y([]),j(0),N(!1),L(!1),$.current="~/",z("right"),n||requestAnimationFrame(()=>vo(l.current));let Q=!1;return(async()=>{const ke=await sh();Q||(u(ke||r||""),n||requestAnimationFrame(()=>vo(l.current)))})(),()=>{Q=!0}},[r,e,n]);const R=a.useMemo(()=>bl(f),[f]),D=a.useMemo(()=>tn(f)?"":xl(f),[f]),I=a.useMemo(()=>O?Ti(R,O):"",[R,O]);a.useEffect(()=>{const Q=$.current;Q!==R&&(z(R.length>=Q.length?"right":"left"),$.current=R)},[R]),a.useEffect(()=>{if(!e||!I){y([]),w(null);return}let Q=!1;return h(!0),g(!1),w(null),sf(I).then(ie=>{if(Q)return;g(!1),w(null);const ke=ie.filter(Se=>Se.isDirectory).map(Se=>({name:Se.name,path:ln(Se.path)})).sort((Se,He)=>Se.name.localeCompare(He.name));y(ke)}).catch(ie=>{if(!Q){y([]);const ke=nf(ie)?ie.reason:"unknown";w(ke),g(ke==="not-found")}}).finally(()=>{Q||h(!1)}),()=>{Q=!0}},[I,E,e]);const T=a.useMemo(()=>{const Q=D.toLowerCase(),ie=M||D.startsWith(".");return x.filter(ke=>ke.name.toLowerCase().startsWith(Q)&&(ie||!ke.name.startsWith(".")))},[D,x,M]),W=a.useMemo(()=>Xf(f),[f]),Z=a.useMemo(()=>yl(f),[f]),F=a.useMemo(()=>{const Q=[],ie=Rs(I);wl(f)&&W&&Z&&Q.push({type:"parent",value:"browse:up",name:W,path:Z,alreadyAdded:!!(ie&&t.has(ie))});for(const ke of T){const Se=Rs(ke.path);Q.push({type:"directory",value:`browse:${ke.path}`,name:ke.name,path:ke.path,alreadyAdded:!!(Se&&t.has(Se))})}return Q},[t,I,W,T,Z,f]);a.useEffect(()=>{j(0)},[f,F.length]);const me=a.useMemo(()=>O?cn(Ti(f,O)):"",[O,f]),q=Rs(me),Ae=!!(q&&t.has(q)),Ie=a.useMemo(()=>D?T.find(Q=>Q.name===D)??null:null,[D,T]),G=!!(me&&!Ae&&(S===null||S==="not-found")&&(tn(f)&&b||!tn(f)&&D.trim().length>0&&Ie===null)),U=F[k]??null,Y=!!U,X=a.useCallback(Q=>{p(fr(Q))},[]),se=a.useCallback(Q=>{p(Zf(f,Q.name))},[f]),we=a.useCallback(Q=>{if(Q){if(Q.type==="parent"){X(Q.path);return}se(Q)}},[X,se]),pe=a.useCallback(async Q=>{const ie=await i(Q);if(!ie.success)return oe.error("Failed to open directory",{description:ie.error||"Desktop could not grant file access."}),!1;const ke=O?eh(Q,O):fr(ln(Q));return X(ke),!0},[X,O,i]),V=a.useCallback(async()=>{if(!v){N(!0);try{if(el()){const ie=await tl(me);if(!ie.success||!ie.path){ie.error&&ie.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:ie.error});return}await pe(ie.path);return}const Q=await rf(me);if(Q.status==="cancelled")return;if(Q.status!=="picked"){oe.error("Couldn't open a folder picker",{description:Q.error});return}await pe(Q.path)}catch(Q){oe.error("Failed to select directory",{description:Q instanceof Error?Q.message:"Unknown error occurred."})}finally{N(!1)}}},[pe,v,me]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:b,browseErrorReason:S,browseReloadKey:E,setBrowseReloadKey:A,highlightedIndex:k,setHighlightedIndex:j,isPickingLocation:v,showHidden:M,setShowHidden:L,folderEnterFrom:K,explorerRootDirectory:O,browseDirectoryDisplayPath:R,browseDirectoryAbsolutePath:I,browseFilterQuery:D,filteredEntries:T,rows:F,targetPath:me,isAlreadyAdded:Ae,shouldCreateTarget:G,highlightedRow:U,hasHighlightedBrowseItem:Y,canRequestAccess:o,browseToDisplayPath:X,browseToEntry:se,executeRow:we,applyPickedLocation:pe,handleBrowseLocation:V}}function oh({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=ct(L=>L.addProject),p=ce(L=>L.setActiveMainTab),x=ce(L=>L.setSessionSwitcherOpen),y=Te(L=>L.openNewSessionDraft),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,w]=a.useState("");a.useEffect(()=>{e&&(h(!1),g(!1),w(""))},[e]);const E=a.useCallback((L,K)=>{p("chat"),n&&x(!1),y({selectedProjectId:L,directoryOverride:K}),t()},[n,t,y,p,x]),A=a.useCallback(async L=>{if(!L||m)return;const K=Rs(L);if(K&&r.has(K))return;let z=L;h(!0);try{const $=!b&&i&&Rs(L)===Rs(o);if(b){const R=S.trim();if(!R){oe.error("Enter a repository URL before cloning.");return}const D=await nt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:R,destinationPath:L})});if(!D.ok)throw new Error("Failed to clone git repository");z=(await D.json()).path||L}else if($&&!(await nt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:L})})).ok)throw new Error("Failed to select directory");const O=f(z);if(!O){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}E(O.id,O.path)}catch($){oe.error("Failed to select directory",{description:$ instanceof Error?$.message:"Unknown error occurred."})}finally{h(!1)}},[f,r,c,S,b,m,E,i,o]),k=!m&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,j=k&&S.trim().length>0,v=b?j:k,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:b,setIsCloneMode:g,cloneRemoteUrl:S,setCloneRemoteUrl:w,canSubmit:v,submitActionLabel:d?"Already added":b?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:A}}const ih=({open:e,onOpenChange:t})=>{const n=ct(V=>V.projects),{isMobile:r,isTablet:o}=dn(),i=r||o,l=a.useMemo(()=>new Set(n.map(V=>Rs(V.path)).filter(V=>!!V)),[n]),c=a.useCallback(()=>{t(!1)},[t]),{inputRef:d,rowRefs:u,query:f,setQuery:p,isLoading:x,browseErrorReason:y,setBrowseReloadKey:m,highlightedIndex:h,setHighlightedIndex:b,isPickingLocation:g,showHidden:S,setShowHidden:w,folderEnterFrom:E,browseDirectoryDisplayPath:A,browseDirectoryAbsolutePath:k,rows:j,targetPath:v,isAlreadyAdded:N,shouldCreateTarget:M,highlightedRow:L,hasHighlightedBrowseItem:K,canRequestAccess:z,executeRow:$,handleBrowseLocation:O}=rh({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:R,isCloneMode:D,setIsCloneMode:I,cloneRemoteUrl:T,setCloneRemoteUrl:W,canSubmit:Z,submitActionLabel:F,submitModifierLabel:me,finalizeSelection:q}=oh({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:v,shouldCreateTarget:M,browseErrorReason:y,browseDirectoryAbsolutePath:k,isAlreadyAdded:N,isPickingLocation:g});a.useLayoutEffect(()=>{const V=d.current;V&&(V.scrollLeft=V.scrollWidth)},[d,f]),a.useLayoutEffect(()=>{!e||i||vo(d.current)},[d,e,i]),a.useLayoutEffect(()=>{const V=j[h];V&&u.current.get(V.value)?.scrollIntoView({block:"nearest"})},[h,u,j]);const Ae=a.useCallback(V=>{if(V.key==="ArrowDown"){V.preventDefault(),b(Q=>Math.min(j.length-1,Q+1));return}if(V.key==="ArrowUp"){V.preventDefault(),b(Q=>Math.max(0,Q-1));return}if(V.key==="Enter"){if(V.preventDefault(),th(V)){q(v);return}K&&$(L);return}V.key==="Backspace"&&f===""&&(V.preventDefault(),c())},[$,q,c,K,L,f,j.length,b,v]),Ie=s.jsxs("button",{type:"button",onClick:()=>w(V=>!V),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[S?s.jsx(P,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(P,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),G=s.jsx("div",{className:"py-1.5",children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),s.jsx(Ln,{ref:d,value:f,onChange:V=>p(ln(V.target.value)),onKeyDown:Ae,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),s.jsxs(Ne,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:R||g,onMouseDown:V=>V.preventDefault(),onClick:()=>{O()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(P,{name:"folder-open",className:"h-3.5 w-3.5"}),g?"Opening...":"Browse"]})]})}),U=j.some(V=>V.type==="parent"),Y=s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:s.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[s.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),s.jsxs(Ne,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":D,disabled:R||g,onClick:()=>I(V=>!V),children:[s.jsx(P,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),D?s.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsx(Ln,{value:T,onChange:V=>W(V.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})})]}):null,N?s.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,s.jsx("div",{className:_("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",E==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):y&&y!=="not-found"?s.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[s.jsx("div",{className:"typography-ui-label text-status-error",children:y==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),s.jsxs("div",{className:"flex items-center gap-2",children:[y==="os-permission"&&z?s.jsx(Ne,{size:"xs",onClick:()=>{O()},disabled:g,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:()=>m(V=>V+1),children:"Try again"})]})]}):j.length===0?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):s.jsx("div",{className:"space-y-0.5",children:j.map((V,Q)=>{const ie=Q===h,ke=V.type==="directory"&&U;return s.jsxs("button",{ref:Se=>{Se?u.current.set(V.value,Se):u.current.delete(V.value)},type:"button","aria-label":V.type==="parent"?V.alreadyAdded?`Go back from ${V.name}, already added`:`Go back from ${V.name}`:V.alreadyAdded?`Open ${V.name}, already added`:`Open ${V.name}`,onMouseEnter:()=>b(Q),onMouseDown:Se=>Se.preventDefault(),onClick:()=>$(V),className:_("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",ie&&"bg-interactive-selection text-interactive-selection-foreground",!ie&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",ke&&"pl-4"),children:[V.type==="parent"?s.jsx(P,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(P,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:V.name})]}),V.alreadyAdded?s.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",ie?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,V.type==="parent"?s.jsx(P,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):s.jsx(P,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},V.value)})})},A)]})}),X=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[G,Y]}),se=s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(P,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(P,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{children:me}),s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),we=s.jsx(Ne,{size:r?"xs":"default",onClick:()=>{q(v)},disabled:!Z,className:_(r&&"w-full flex-1"),children:F}),pe=()=>s.jsxs(s.Fragment,{children:[r?null:se,s.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:we})]});return r?s.jsx(La,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:pe()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Ie}),X]})}):s.jsx(ts,{open:e,onOpenChange:t,children:s.jsxs(ss,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(ws,{className:"px-5 pb-2 pt-5",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx(ds,{children:"Add folder"}),s.jsx(vs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Ie]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:X}),s.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:pe()})]})})},qn=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Tx=()=>{const[e,t]=a.useState(!1),[n,r]=a.useState(null),[o,i]=a.useState(!1),l=Te(k=>k.deleteSession),c=Te(k=>k.deleteSessions),d=ce(k=>k.showDeletionDialog),u=ce(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:x}=dn(),y=f||p||x;a.useEffect(()=>of(()=>{t(!1)}),[]);const m=a.useCallback(k=>{r({sessions:k.sessions,dateLabel:k.dateLabel})},[]),h=a.useCallback(()=>{r(null),i(!1)},[]),b=a.useCallback(async k=>{if(k.sessions.length===0)return;if(k.sessions.length===1){const M=k.sessions[0];await l(M.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const j=k.sessions.map(M=>M.id),{deletedIds:v,failedIds:N}=await c(j);if(v.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:k.dateLabel?`Removed all sessions from ${k.dateLabel}.`:void 0;oe.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:qn(M)})}N.length>0&&oe.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:qn("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Ms.onDeleteRequest(k=>{if(!d){b(k);return}m(k)}),[m,d,b]),a.useEffect(()=>Ms.onDirectoryRequest(()=>{t(!0)}),[]);const g=a.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const k=n.sessions[0];if(!await l(k.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=n.sessions.map(M=>M.id),j=await c(k),v=j.deletedIds,N=j.failedIds;if(v.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;oe.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:qn(M),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(oe.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:qn("Please try again in a moment.")}),v.length===0)){i(!1);return}}h()}finally{i(!1)}}},[n,l,c,h]),S=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",w=n?s.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&s.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(k=>s.jsx("li",{className:"typography-micro text-muted-foreground/80",children:s.jsx("span",{className:"truncate",children:gs(k)})},k.id)),n.sessions.length>5&&s.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,E=s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.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?s.jsx(P,{name:"checkbox-blank",className:"size-4"}):s.jsx(P,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ne,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",onClick:g,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),A=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(La,{open:!!n,onClose:()=>{o||h()},title:A,footer:s.jsx("div",{className:"flex justify-end gap-2",children:E}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[S&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:S}),w]})}):s.jsx(ts,{open:!!n,onOpenChange:k=>{if(!k){if(o)return;h()}},children:s.jsxs(ss,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:A}),S&&s.jsx(vs,{children:S})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),s.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:E})]})}),s.jsx(ih,{open:e,onOpenChange:t})]})},Fx=()=>{const e=Ts(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!Gd(t)||!t.receipt||(Ts.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},ah=[{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"]}],lh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ch(e){const t=e.trim().toLowerCase();return ah.find(n=>n.slug===t)??null}function dh(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const n=lh[t];if(n)return n;const r=ch(t);return r?r.slug:"home"}function Lx(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 Ox(){const e=a.useRef(!1),t=a.useRef(!1),n=Te(f=>f.setCurrentSession),r=ce(f=>f.setActiveMainTab),o=ce(f=>f.setSettingsDialogOpen),i=ce(f=>f.setSettingsPage),l=ce(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Te.getState().currentSessionId,x=Js().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==x){const y=Te.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(dh(f.settingsPath)),o(!0);return}ce.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,l]),d=a.useCallback(()=>{const f=Te.getState(),p=Js().getState(),x=ce.getState();return{sessionId:Br({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=a.useCallback((f={})=>{if(t.current)return;const p=d();xo(p,f)},[d]);a.useEffect(()=>{if(e.current||(e.current=!0,!Si()))return;const f=ji();(async()=>(await c(f),xo({...d(),sessionId:f.sessionId??Br({currentSessionId:Te.getState().currentSessionId,piSelectedSessionId:Js().getState().selectedSessionId,draft:Te.getState().newSessionDraft}),tab:f.tab??ce.getState().activeMainTab,settingsPath:f.settingsPath??ce.getState().settingsPage,diffFile:f.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),a.useEffect(()=>{const f=()=>{const b=Te.getState(),g=Js().getState();return Br({currentSessionId:b.currentSessionId,piSelectedSessionId:g.selectedSessionId,draft:b.newSessionDraft})};let p=f(),x=Te.getState().newSessionDraft?.open===!0;const y=()=>{const b=Te.getState(),g=f(),S=b.newSessionDraft?.open===!0;g===p&&S===x||t.current||(p=g,x=S,u({replace:!0}))},m=Te.subscribe(()=>{y()}),h=Js().subscribe(()=>{y()});return()=>{m(),h()}},[u]),a.useEffect(()=>{let f=ce.getState().activeMainTab,p=ce.getState().isSettingsDialogOpen,x=ce.getState().settingsPage,y=ce.getState().pendingDiffFile;return ce.subscribe(h=>{if(t.current)return;const b=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==p,S=h.settingsPage!==x,w=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(b||g||S||w)&&u()})},[u]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=ji();if(Si())c(p);else{const x=ce.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function uh(e=!0){const t=sr(r=>r.checkForUpdates),n=a.useRef(t);a.useEffect(()=>{n.current=t},[t]),a.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=p=>{const x=Math.round(p*1e3);return Math.max(i,Math.min(l,x))},f=p=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),y=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(y)},p))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Bx(){const e=En(t=>t.connection==="ready",void 0,"chrome");return uh(e),null}const fh=200,hh=15e3,mh=e=>{const{id:t,url:n}=e.payload,r=qd(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=Yd(Vd(n),r.target,{isMobile:ce.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:hh});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Qd(r.target,n,Jd()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},_x=()=>(a.useEffect(()=>{const e=new Set;return Hd(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>fh){const n=e.values().next().value;n!==void 0&&e.delete(n)}mh(t)}})},[]),null),Fi=12,ph=[{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"}],gh=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=ph,onComplete:i})=>{const l=Re.useRef(!1);Re.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Re.useMemo(()=>Array.from({length:Fi},(d,u)=>{const f=Math.PI*2*u/Fi;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?s.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"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 s.jsx("div",{className:"firework-burst",style:u,children:c.map((f,p)=>{const x=f.x*d.radius,y=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${y}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return s.jsx("span",{className:"firework-particle",style:m},`${d.id}-${p}-${t}`)})},`${d.id}-${t}`)})}):null},bh=({durationMs:e=3400}={})=>{const[t,n]=Re.useState({isActive:!1,cycle:0}),r=Re.useRef(null),o=Re.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Re.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Re.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Re.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},vl=a.createContext(void 0),Ux=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=bh(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(vl.Provider,{value:i,children:[e,s.jsx(gh,{isActive:t,burstKey:n})]})},xh={triggerFireworks:()=>{},dismissFireworks:()=>{}},zx=()=>a.useContext(vl)??xh,hr=2e3,Sl=600*1e3;async function yh(){try{const e=await nt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const 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 wh(e,t=Math.ceil(Sl/hr),n=hr,r=Je()){for(let o=0;o<t;o++){if(Je()!==r)return{applied:!1,stale:!0};try{const i=await nt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Je()!==r)return{applied:!1,stale:!0};if(i.ok){const l=await i.json().catch(()=>null);if(Je()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Je()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function vh(e,t,n=Math.ceil(Sl/hr),r=hr,o=Je()){for(let i=0;i<n;i++){if(Je()!==o)return{applied:!1,stale:!0};try{const l=await nt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Je()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Je()!==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(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Je()!==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(Je()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Li="https://github.com/RyderAsKing/PiChamber/releases";function Sh(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 jh(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Oi(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function kh(e,t){const n=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=n(e),[i,l]=n(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,p=Number.isFinite(d[u])?d[u]:0;if(f!==p)return p-f}return!o||!l?(o?1:0)-(l?1:0):l.localeCompare(o,void 0,{numeric:!0})}function Ch(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=t.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,i)=>{const l=n[i+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const jl=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Re.useState(null),[x,y]=Re.useState("idle"),[m,h]=Re.useState(null),[b,g]=Re.useState(null),[S,w]=Re.useState({}),E=n?.version?n.releaseUrl||`${Li}/tag/v${n.version}`:Li,A=n?.downloadUrl||E,k=i?.total?Math.round(i.downloaded/i.total*100):0,j=u==="web",v=u==="mobile",N=n?.updateCommand||"pichamber update",M=S.version||n?.version,L=S.channel||n?.channel;Re.useEffect(()=>{e||(y("idle"),h(null),g(null),w({}))},[e]);const K=async(I=N)=>{(await xs(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},z=Re.useCallback(async I=>{await Oa(I)},[]),$=Re.useCallback(async()=>{const I=Je();y("updating"),h(null),g(null),w({});const T=await yh();if(Je()!==I)return;if(!T.success){y("error"),h(T.error||"Update failed"),g(T.commands??null);return}if(w({version:T.targetVersion,channel:T.channel}),T.jobId){const Z=await vh(T.jobId,F=>{Je()===I&&y(F)},void 0,void 0,I);if(Z.stale||Je()!==I)return;if(Z.applied){window.location.reload();return}y("error"),h(Z.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(T.autoRestart?"restarting":"reconnecting");const W=await wh(n?.currentVersion,void 0,void 0,I);if(!(W.stale||Je()!==I)){if(W.applied){window.location.reload();return}y("error"),h(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),O=Re.useCallback(()=>{z(A)},[z,A]),R=x!=="idle"&&x!=="error",D=Re.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const T=Ch(I);return T.length===0?{kind:"raw",title:"What's new",content:Oi(I)}:{kind:"sections",title:"What's new",sections:[...T].sort((Z,F)=>kh(Z.version,F.version)).map(Z=>({version:Z.version,dateLabel:Sh(Z.date),content:Oi(jh(Z.raw)||I)}))}},[n?.body]);return s.jsx(ts,{open:e,onOpenChange:R?void 0:t,children:s.jsxs(ss,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[s.jsxs(ds,{className:"flex items-center gap-2.5",children:[s.jsx(P,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(n?.currentVersion||M||j&&L)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||M)&&s.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&M&&s.jsx("span",{className:"text-muted-foreground/50","aria-hidden":"true",children:"→"}),M&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:M})]}),j&&L&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:L==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[j&&R&&s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(P,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),D&&!R&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Is,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:D.kind==="raw"?s.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 W=I.target.closest("a");W&&W.href&&(I.preventDefault(),I.stopPropagation(),z(W.href))},children:s.jsx(ki,{content:D.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:D.sections.map(I=>s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.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]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),s.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:T=>{const Z=T.target.closest("a");Z&&Z.href&&(T.preventDefault(),T.stopPropagation(),z(Z.href))},children:s.jsx(ki,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(l||m)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||m})}),j&&x==="error"&&(b??[N]).length>0&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(P,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:b?"Run these commands:":"Or update via terminal:"})]}),(b??[N]).map(I=>s.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:[s.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),s.jsx(Ne,{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?s.jsx(P,{name:"check",className:"h-4 w-4"}):s.jsx(P,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!j&&!v&&r&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),s.jsxs("span",{className:"font-mono text-foreground",children:[k,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${k}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[s.jsxs("a",{href:E,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:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!v&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!j&&!v&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!v&&o&&s.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:[s.jsx(P,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),v&&s.jsxs(Ne,{onClick:O,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!R&&s.jsxs(Ne,{onClick:$,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),j&&R&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},kl=a.memo(function({checked:t,onChange:n,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:l,iconClassName:c}){const d=a.useCallback(x=>{x.preventDefault(),x.stopPropagation(),!r&&!t&&n()},[t,r,n]),u=a.useCallback(x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),!r&&!t&&n())},[t,r,n]),f=s.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),p=_("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-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)]");return i?s.jsx("span",{"aria-hidden":!0,className:_(p,r&&"opacity-50",l),children:f}):s.jsx("button",{type:"button",role:"radio",onClick:d,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",p,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",l),children:f})}),zn=({children:e,className:t,contentClassName:n})=>{const[r,o]=a.useState(!1),i=a.useRef(null);return a.useEffect(()=>{if(!r)return;const l=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),s.jsxs($e,{open:r,onOpenChange:o,children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:s.jsx(P,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(We,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},$x="w-full min-w-40 max-w-48",Kx="settings",Ah="w-full min-w-40 max-w-48",Wx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Nh="w-full max-w-[24rem]",Gx="min-w-0 flex-1",Hx="flex w-full min-w-0 items-center gap-2",qx="typography-meta shrink-0 text-muted-foreground tabular-nums",Cl="space-y-3.5",Ih="space-y-1.5",Yx="typography-settings-page-title text-muted-foreground",Eh="typography-settings-section-title text-foreground",Al="typography-settings-group-title text-foreground",Vo="typography-settings-field-label text-foreground",Rh="typography-settings-description text-muted-foreground",$n="typography-meta text-muted-foreground",Vx="typography-meta font-medium text-foreground",Qx="typography-settings-section-title text-foreground",Dh=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return s.jsxs("section",{"data-settings-item":u,className:_("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?s.jsx("h2",{className:Eh,children:e}):e,n,r!=null?s.jsx(zn,{children:r}):null]}):null,t!=null?s.jsx("div",{className:Rh,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},Jx=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),Ph=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(Al,t),children:e}),Xx=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:l})=>s.jsxs("div",{"data-settings-item":l,className:_("space-y-2",o),children:[e!=null||t!=null||n!=null?s.jsxs("div",{className:"space-y-0.5",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Ph,{children:e}),n!=null?s.jsx(zn,{children:n}):null]}):null,t!=null?s.jsx("p",{className:$n,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),Pn=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:l,controlClassName:c})=>{const d=t!=null?s.jsx("p",{className:$n,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:_("space-y-2",l),children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Vo,children:e}),n!=null?s.jsx(zn,{children:n}):null]}),r==="before"?d:null]}),s.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},Zx=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:l,controlClassName:c,alignEnd:d=!0})=>s.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:[s.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",l),children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Vo,children:e}),n!=null?s.jsx(zn,{children:n}):null]}),t!=null?s.jsx("p",{className:_($n,"mt-0.5"),children:t}):null]}),s.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})]}),ey=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),ty=({label:e,children:t,divider:n=!0,className:r,contentClassName:o})=>s.jsxs("details",{className:_("group/disclosure",n?"border-t border-border/60 py-6":"pb-6",r),children:[s.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:[s.jsx(P,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),s.jsx("div",{className:_("pt-4",o),children:t})]}),Mh=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},p=r!=null;return s.jsxs("div",{"data-settings-item":l,className:_("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[s.jsx(io,{checked:e,onChange:t,disabled:o,ariaLabel:i}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:Vo,children:n}),d,u!=null?s.jsx(zn,{children:u}):null]}),p?s.jsx("span",{className:$n,children:r}):null]})]})},sy=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",l),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:[s.jsx(kl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:_("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?s.jsx("span",{className:$n,children:r}):null]})]}),ny=({selected:e,onSelect:t,label:n,preview:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",i&&"cursor-not-allowed opacity-60",l),role:"radio",tabIndex:i?-1:0,"aria-checked":e,"aria-label":o,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.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-border group-hover/preview:border-foreground/30"),children:r}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(kl,{checked:e,onChange:t,disabled:i,decorative:!0}),s.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n})]})]}),ry=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(Ih,n),children:t});function oy({value:e,options:t,onChange:n,className:r,"aria-label":o}){return s.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>s.jsx(Ne,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>n(i.value),children:i.label},i.value))})}const So="pichamber:server-update-channel-changed",iy=()=>{typeof window<"u"&&window.dispatchEvent(new Event(So))},Th=e=>typeof window>"u"?()=>{}:(window.addEventListener(So,e),()=>window.removeEventListener(So,e));class Fh extends a.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?s.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:s.jsxs(Xd,{className:"w-full max-w-md",children:[s.jsx(Zd,{className:"text-center",children:s.jsxs(eu,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(P,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(tu,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&s.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&s.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[s.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),s.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(P,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),s.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Lh(e){return s.jsx(Fh,{...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 ay=({active:e=!0})=>{const t=Te(n=>n.currentSessionId);return s.jsx(Lh,{sessionId:t||void 0,children:s.jsx(su,{active:e},t??"no-session")})};function Oh({onResizeStart:e,ariaLabel:t}){return s.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:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:s.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const Nl=Re.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:p,...x},y)=>{const m=Re.useRef(null),h=Re.useRef(null),[b,g]=Re.useState(null),S=c??b,w=Re.useCallback(A=>{const k=m.current;if(!k)return;h.current={startY:A.clientY,startHeight:k.getBoundingClientRect().height};const j=A.currentTarget;j.setPointerCapture(A.pointerId);const v=M=>{const L=h.current;if(!L)return;const K=L.startHeight+(M.clientY-L.startY),z=Math.max(82,K);d?d(z):g(z)},N=()=>{h.current=null,j.removeEventListener("pointermove",v),j.removeEventListener("pointerup",N),j.removeEventListener("pointercancel",N)};j.addEventListener("pointermove",v),j.addEventListener("pointerup",N),j.addEventListener("pointercancel",N),A.preventDefault()},[d]),E=Re.useCallback(A=>{if(A.target.closest('textarea, button, [role="separator"]'))return;const j=m.current?.querySelector("textarea");j&&document.activeElement!==j&&(A.preventDefault(),j.focus())},[]);return f?s.jsx(Is,{as:"textarea",ref:y,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:n,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):s.jsx("div",{ref:m,onPointerDown:E,style:S!==null?{height:`${S}px`}:void 0,className:_("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[s.jsx("textarea",{ref:y,className:_("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,s.jsx(Oh,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});Nl.displayName="Textarea";const Il=[{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"}],Mn=Object.fromEntries(Il.map(e=>[e.key,e.Icon])),jo="pichamber:project-actions-updated",El=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},as=(e,t)=>`${El(e)}::${t}`,Rl=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:d,divider:u=!0})=>s.jsx(Dh,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:l}),ko=e=>e.name.trim().length>0&&e.command.trim().length>0,Bh=e=>e.name.trim().length===0&&e.command.trim().length===0,_h=e=>!ko(e)&&!Bh(e),Uh=(e,t)=>e.some(r=>t.has(r.id)&&!ko(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(ko)},zh=450,$h=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Kh=()=>({id:$h(),name:"",command:"",icon:"play"}),Wh=({projectRef:e})=>{const[t,n]=a.useState([]),[r,o]=a.useState(!1),[i,l]=a.useState(null),[c,d]=a.useState(new Set),u=a.useRef(!1);a.useEffect(()=>{let g=!1;return o(!0),(async()=>{try{const S=await ao(e);if(g)return;n(S.actions),l(JSON.stringify({actions:S.actions})),d(new Set(S.actions.map(w=>w.id)))}catch{if(g)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=a.useMemo(()=>Uh(t,c),[t,c]),p=a.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=i!==null&&f.canPersist&&p!==i,y=a.useCallback(async g=>await nu(e,{actions:g,primaryActionId:null})?(l(JSON.stringify({actions:g})),d(new Set(g.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(jo,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);a.useEffect(()=>{if(!x||r||u.current)return;const g=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await y(f.actions)}finally{u.current=!1}})())},zh);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const m=a.useCallback(()=>{const g=Kh();n(S=>[...S,g])},[]),h=a.useCallback(g=>{n(S=>S.filter(w=>w.id!==g))},[]),b=a.useCallback((g,S)=>{n(w=>w.map(E=>E.id===g?S(E):E))},[]);return s.jsx(Rl,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ne,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[s.jsx(P,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):s.jsx("div",{className:_("space-y-6",Nh),children:t.map((g,S)=>{const w=g.icon||"play",E=Mn[w]||"play",A=g.name.trim()||`Action ${S+1}`,k=_h(g);return s.jsxs("div",{className:Cl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Al,children:A}),s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(g.id),"aria-label":`Delete ${A}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(Pn,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:E,className:"h-4 w-4"})})}),s.jsx(qt,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Il.map(j=>{const v=j.Icon,N=(g.icon||"play")===j.key;return s.jsx("button",{type:"button",onClick:()=>b(g.id,M=>({...M,icon:j.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",N&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:s.jsx(P,{name:v,className:"h-4 w-4"})},j.key)})})})]}),s.jsx(Ln,{value:g.name,onChange:j=>b(g.id,v=>({...v,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(Pn,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(Nl,{value:g.command,onChange:j=>b(g.id,v=>({...v,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),k?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(Mh,{checked:g.autoOpenUrl===!0,onChange:j=>b(g.id,v=>({...v,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${A}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(Pn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Ln,{value:g.openUrl||"",onChange:j=>b(g.id,v=>({...v,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},Gh={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)"},Hh=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=Kt(v=>v.providers),d=Kt(v=>v.modelsMetadata),u=ce(v=>v.hiddenModels),f=ce(v=>v.isFavoriteModel),p=ce(v=>v.toggleFavoriteModel),x=ce(v=>v.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:m}=ru(),[h,b]=a.useState(!1),[g,S]=a.useState("");a.useEffect(()=>{h?Kt.getState().ensureModelMetadata():S("")},[h]);const w=e?c.find(v=>v.id===e.providerId):void 0,E=e&&w?(Array.isArray(w.models)?w.models:[]).find(v=>v.id===e.modelId):void 0,A=e?ou(E,e.modelId):t,k=a.useMemo(()=>e?u.filter(v=>!(v.providerID===e.providerId&&v.modelID===e.modelId)):u,[u,e]),j=a.useCallback(v=>{l({providerId:v.providerID,modelId:v.modelID}),b(!1)},[l]);return s.jsxs(Gt,{modal:!1,open:h,onOpenChange:v=>{r||b(v)},children:[s.jsx(Ht,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(au({size:"default"}),Ah,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(iu,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:A})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(lu,{providers:c,favoriteModels:y,recentModels:m,modelsMetadata:d,searchQuery:g,onSearchQueryChange:S,onSelect:j,labels:{...Gh,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:k,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{l(null),b(!1)},disabled:r,autoFocus:!0,onEscape:()=>b(!1),isFavorite:v=>f(v.providerID,v.modelID),onToggleFavorite:v=>p(v.providerID,v.modelID),onReorderFavorite:(v,N)=>x(v.providerID,v.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},Ur="w-full max-w-none",qh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=Kt(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(Rl,{title:"Project",divider:!1,children:s.jsxs("div",{className:Cl,children:[s.jsx(Pn,{label:"Name",settingsItem:"projects.name",controlClassName:Ur,children:s.jsx(Ln,{value:t,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),s.jsx(Pn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:Ur,children:s.jsx(Hh,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:Ur,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Yh=e=>{const[t,n]=a.useState(""),[r,o]=a.useState(void 0);a.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const i=a.useMemo(()=>cu(r),[r]),l=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=a.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=a.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:n,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Vh=450,Qh=(e,t)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:i}=e,l=a.useRef(!1);a.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},Vh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Jh=({project:e,onIdentitySave:t})=>{const n=Yh(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return Qh(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(qh,{form:n}),s.jsx(Wh,{projectRef:r})]})},Xh=6e4,Zh=3e4,vn=new Map;let Bi=0,_i=!1;const em=()=>{if(_i||typeof window>"u")return;_i=!0;const e=()=>{const t=Date.now();t-Bi<Zh||typeof document<"u"&&document.hidden||(Bi=t,mt(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-C2ISrmRR.js").then(r=>r.cI);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&kr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},kr=Bs()(jr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Ft(),resetForRuntimeSwitch:n=>{const r=n??Ft();vn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{em();const o=Ft();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<Xh)return i.status;const c=vn.get(o);if(c)return c;const d=n??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return Ft()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Ft()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();vn.set(o,u);try{return await u}finally{vn.get(o)===u&&vn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&Un(e=>{kr.getState().resetForRuntimeSwitch(e.runtimeKey)});const tm=()=>kr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),ly=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 n=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(n?.width)||!Number.isFinite(n?.height)?null:{header:n,jpeg:new Uint8Array(e,4+t)}}catch{return null}},cy=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},dy=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",uy=50*1024*1024-1,fy=[250,1e3,2e3,4e3,8e3],sm=(e,t)=>{const n=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-${n(2166136261)}${n(16777619)}`},hy=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),my=(e,t,n,r)=>{if(n.width<=0||n.height<=0)return null;const o=(e-n.left)/n.width*r.width,i=(t-n.top)/n.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}},py=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,gy=(e,t)=>{const n=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(n)&&n>0?n:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},un=async(e,t)=>{const n=await e.json().catch(()=>null);return new Error(typeof n?.error=="string"?n.error:t)},by=async()=>{const e=await nt("/api/server-browser/status");if(!e.ok)throw await un(e,"Could not check the server browser");return await e.json()},xy=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 un(t,"Could not save the server browser settings");return await t.json()},yy=async(e,t)=>{const n=await nt("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!n.ok)throw await un(n,"Could not find dev servers");const r=await n.json();return Array.isArray(r.servers)?r.servers:[]},wy=async(e,t,n)=>{const r=await nt("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:n});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"}},vy=async()=>{const e=await nt("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await un(e,"Could not clear browsing data")},Sy=(e,t)=>{const n=sm(e,t);nt(`/api/server-browser/tabs/${encodeURIComponent(n)}`,{method:"DELETE"}).catch(()=>{})},jy=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),n=await nt(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!n.ok)throw await un(n,`Could not upload ${e.name}`);const r=await n.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},ky=async(e,t)=>{const n=await nt(`/api/server-browser/downloads/${encodeURIComponent(e)}`);if(!n.ok)throw await un(n,`Could not download ${t}`);const r=await n.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)}},Cy=async(e,t,n)=>{const r=await lf();return{socket:cf(df().websocket("/api/server-browser/ws",{tab:e,url:t,popup:n},r)),urlAuthToken:r}},Ay=e=>{af(e)},Yn=100;function Ny(){const e=ce(v=>v.isArchivePageOpen),t=ce(v=>v.setArchivePageOpen),n=ce(v=>v.setActiveMainTab),r=Te(v=>v.setCurrentSession),o=Te(v=>v.unarchiveSession),i=on(v=>v.homeDirectory),l=lo({archived:!0}),[c,d]=a.useState(""),[u,f]=a.useState(null),[p,x]=a.useState(Yn),y=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((v,N)=>(N.time?.archived??0)-(v.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const v=new Map;for(const N of m){const M=Ee(Rn(N))??"",L=v.get(M);if(L){L.sessions.push(N);continue}v.set(M,{directory:M,label:M?On(M,i)||M:"other projects",sessions:[N]})}return[...v.values()].sort((N,M)=>M.sessions.length-N.sessions.length)},[i,m]),b=a.useMemo(()=>y?m.filter(v=>(v.title??"").toLowerCase().includes(y)):u===null?m:h.find(v=>v.directory===u)?.sessions??[],[h,y,u,m]),g=b.slice(0,p),S=b.length-g.length,w=l.length,E=a.useCallback(v=>{f(v),x(Yn)},[]),A=a.useCallback(v=>{const N=Ee(Rn(v));r(v.id,N??void 0),n("chat"),t(!1)},[n,r,t]),k=a.useCallback(v=>{o(v.id).then(N=>{N?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const j=(v,N,M,L,K,z,$)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:K,title:z,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",$?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",L?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:N}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:M})]}),$?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Ms.requestDelete({sessions:$,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${N}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},v);return s.jsx(Dd,{open:e,onOpenChange:t,children:s.jsxs(Pd,{children:[s.jsx(Md,{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"}),s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:s.jsxs(Td,{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:[s.jsx(Fd,{className:"sr-only",children:"Archived sessions"}),s.jsx(Ld,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Od,{"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:s.jsx(P,{name:"close",className:"size-4"})}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:s.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[j("__all__","All directories",w,u===null,()=>E(null)),h.map(v=>j(v.directory||"__none__",v.label,v.sessions.length,u===v.directory,()=>E(v.directory),v.directory||void 0,v.sessions))]})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{value:c,onChange:v=>{d(v.target.value),x(Yn)},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"})]}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:b.length===1?`${b.length} archived session`:`${b.length} archived sessions`})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[g.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:y?"No matching archived sessions":"No archived sessions"})}):g.map(v=>{const N=Ee(Rn(v))??"",M=N?On(N,i)||N:null;return s.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:()=>A(v),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),A(v))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:gs(v)}),y&&M?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:M}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Df(v.time?.archived??v.time?.updated??v.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),k(v)},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 ${gs(v)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),Ms.requestDelete({sessions:[v],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 ${gs(v)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},v.id)}),S>0?s.jsx("button",{type:"button",onClick:()=>x(v=>v+Yn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const nm=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+n+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,n);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},rm=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+n+r},Xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,om=e=>{if(!e||typeof e!="object")return null;const t=Xt(e.input),n=Xt(e.output),r=Xt(e.cacheRead),o=Xt(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},Ui=e=>{const t=om(e.info.usage);if(t)return t;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total: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),l=Xt(o.output),c=Xt(o.reasoning),d=Xt(o.cache?.read),u=Xt(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:i+l+c+d+u}},Dl=380,zr=8,im=140;function am({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=a.useRef(null),i=a.useRef(null),[l,c]=a.useState(e),[d,u]=a.useState(!1),[f,p]=a.useState(null),{enabled:x}=Wo();return a.useLayoutEffect(()=>{if(!e||!x||!l)return;const y=()=>{const b=n.current?.getBoundingClientRect(),g=i.current?.getBoundingClientRect();if(!b||!g){p(null);return}const S=b.left-g.left;p(Math.min(Math.max(S,zr),Math.max(zr,g.width-Dl-zr)))};y();const m=i.current;if(typeof ResizeObserver>"u"||!m)return;const h=new ResizeObserver(y);return h.observe(m),()=>h.disconnect()},[n,x,e,l]),a.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const y=window.setTimeout(()=>{c(!1),u(!1)},im);return()=>window.clearTimeout(y)},[e,l]),a.useEffect(()=>{if(!e)return;const y=m=>{m.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,e]),a.useEffect(()=>{if(!e)return;const y=m=>{const h=m.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||n.current?.contains(h)||t()};return document.addEventListener("pointerdown",y,!0),r&&document.addEventListener("wheel",y,!0),()=>{document.removeEventListener("pointerdown",y,!0),r&&document.removeEventListener("wheel",y,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const zi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},mr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Vn=({icon:e,iconNode:t,label:n,children:r})=>s.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[s.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?s.jsx(P,{name:e,className:"size-[18px]"}):null)}),s.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),lm=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=am({open:e,onClose:t,anchorRef:n,closeOnWheel:!0});return l?s.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:[s.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(${Dl}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(Vn,{iconNode:s.jsx(Ba,{percentage:r.percentage}),label:"Context",children:s.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[s.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),s.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?s.jsxs(s.Fragment,{children:[s.jsx(Vn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:mr(r.cacheRead)})}),s.jsx(Vn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:mr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(Vn,{icon:"check",label:"Cache hit",children:s.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):s.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),s.jsx("style",{children:`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BMdbHCFt.js","assets/useAppFontEffects-D_gtiA95.js","assets/index-C2ISrmRR.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-DgwThEwf.css","assets/vendor-boot-CoTxysn6.js","assets/runtimeSurface-CJN1oo_1.js","assets/nativeFileSave-Bhafll_7.js","assets/computeVirtualFileMetrics-aX6tjjqv.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-CCoYfC-t.js","assets/renderDiffWithHighlighter-xlvSvnTf.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-DJD81I9f.js","assets/SessionSwitcherDropdown-CFj9VWSa.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as mt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as s,aS as Dd,aT as Pd,aU as Md,aV as Td,aW as Fd,aX as Ld,aY as Od,aZ as _o,a_ as Fn,a$ as Bd,b0 as Uo,b1 as zo,b2 as _d,b3 as Ud,b4 as zd,b5 as $d,b6 as Ca,b7 as Aa,b8 as Na,b9 as Ia,ba as Ea,bb as Ra,bc as Da,bd as Pa,be as Ma,bf as Ta,bg as Fa,bh as $o,bi as Ko,bj as oo,aP as Kd}from"./vendor-boot-CoTxysn6.js";import{a as Re,R as a}from"./vendor-react-Bz1tRBxM.js";import{aq as Zs,ar as Wd,t as oe,a as ct,h as Te,as as dn,B as Ne,I as P,at as Ln,au as La,av as ts,aw as ss,ax as ws,ay as ds,az as vs,aA as Ls,aB as Ms,v as gs,aC as Ts,aD as Gd,g as Js,aE as Br,aF as Si,aG as ji,aH as En,e as sr,aI as Hd,aJ as qd,aK as Yd,aL as Vd,aM as Qd,aN as Jd,o as Oa,aO as Is,aP as ki,ah as xs,aQ as $e,aR as Ke,aS as We,aT as io,aU as Xd,aV as Zd,aW as eu,aX as tu,aY as su,aZ as ao,a_ as nu,a$ as Gt,b0 as Ht,b1 as qt,O as Kt,b2 as ru,b3 as ou,b4 as iu,b5 as au,b6 as lu,b7 as cu,b8 as lo,r as Rn,G as Wo,b9 as du,ba as uu,bb as Ba,bc as _a,Z as ys,bd as fu,be as hu,bf as mu,bg as pu,d as Ua,z as Os,bh as za,bi as Sr,bj as Ci,bk as $a,bl as bt,bm as gu,bn as bu,bo as Ka,bp as Wa,bq as Ga,br as Ha,bs as Go,bt as qa,bu as ht,bv as Ya,bw as xu,i as Va,p as yu,bx as wu,j as vu,u as Qa,k as Su,m as ju,by as Ja,n as ku,q as Ai,bz as Cu,bA as qs,b as Ni,c as Au,bB as Nu,bC as Iu,bD as Eu,bE as co,bF as Ru,bG as Du,bH as Pu,bI as Mu,bJ as Tu,a4 as Fu,bK as nn,bL as Xa,M as Lu,y as Ou,bM as Bu,w as _u,bN as Uu,bO as Za,bP as zu,aj as $u,bQ as Ku,bR as Wu,bS as Gu,bT as Hu,bU as qu,bV as Yu,bW as Vu,bX as Qu,bY as Ju,bZ as Xu}from"./useAppFontEffects-D_gtiA95.js";import{A as Ii,B as Zu,a as rn,C as el,D as tl,E as ef,F as tf,u as on,G as sf,H as nf,I as rf,h as ce,z as nt,f as _,J as of,K as Je,b as Ft,o as Un,L as af,M as lf,N as cf,O as df,q as Ee,P as On,Q as Wt,R as uo,T as fo,U as sl,n as cs,V as Ho,W as dr,X as uf,v as nl,Y as ff,Z as rl,_ as hf,$ as ol,a0 as Dn,a1 as ho,j as mo,e as Hn,a2 as mf,a3 as pf,a4 as gf,a5 as Ei,a6 as wn,a7 as _r,a8 as po,a9 as ur,aa as Es,ab as Ri,ac as go,ad as il,ae as bo,af as bf,ag as xf,ah as yf,ai as wf,aj as vf,ak as Sf,al as jf,am as kf,an as Cf,ao as al,ap as Af,aq as Nf,ar as If,as as Ef,at as Rf}from"./index-C2ISrmRR.js";import{b as Df,g as ll,r as Pf,d as cl,s as nr,c as dl,e as Fs,h as an,i as Mf,j as Tf,k as Ff,l as Lf,m as qo,n as ul,f as Of,a as Di,S as Bf,t as _f,o as Uf}from"./SessionUnreadDot-CHlK2awX.js";import{c as Bs,d as jr,p as fl,a as zf}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{saveOrShareFile as $f}from"./nativeFileSave-Bhafll_7.js";import{usePermissionStore as Kf}from"./permissionStore-zIpxq9Pq.js";const Wf="chat";function hl(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Zs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Zs.SETTINGS,n),t}return e.tab!==Wf&&t.set(Zs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Zs.FILE,e.diffFile),t}function Gf(e,t){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Hf(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=hl(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Zs.SESSION)&&t.set(Zs.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==l.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==l[c][0]||i[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function xo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Hf(e)))try{const n=hl(e),r=Gf(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const qf=["typescript","javascript","tsx","jsx","json","markdown"],ml={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Pi=null;const pl=()=>(Pi??=Promise.all([mt(()=>import("./index-BMdbHCFt.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])),mt(()=>import("./workerFactory-DlGfNFqf.js"),[]),mt(()=>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,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),Pi),Bn={},Mi=new Set,yo=new Set;let rr={light:"pierre-light",dark:"pierre-dark"};const Yf=()=>{for(const e of yo)e()},gl=(e,t)=>{t.setRenderOptions({theme:rr,lineDiffType:ml[e].lineDiffType})},wo=e=>{typeof window>"u"||Mi.has(e)||(Mi.add(e),pl().then(t=>{if(Bn[e])return;const n=ml[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:qf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Bn[e]=r,gl(e,r),Yf()}))},Vf=e=>(yo.add(e),()=>yo.delete(e)),Qf=e=>{if(!(rr.light===e.light&&rr.dark===e.dark)){rr=e;for(const t of Object.keys(Bn)){const n=Bn[t];n&&gl(t,n)}}},Px=({children:e})=>{const t=Wd(),n=Ii(!1),r=Ii(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,l=t?.availableThemes.find(d=>d.metadata.id===o)??n,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Re.useEffect(()=>{let d=!1;return pl().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Qf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Re.useEffect(()=>{if(typeof window>"u")return;const d=()=>{wo("unified"),wo("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)},[]),s.jsx(s.Fragment,{children:e})},Mx=(e="unified")=>{const t=Re.useSyncExternalStore(Vf,()=>Bn[e],()=>{});return Re.useEffect(()=>{wo(e)},[e]),t},Jf=e=>e==="/",ln=e=>e.replace(/\\/g,"/"),cn=e=>{if(!e||Jf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},tn=e=>e.endsWith("/"),fr=e=>{const t=e.trim();return!t||tn(t)?t:`${t}/`},Yo=e=>e.lastIndexOf("/"),bl=e=>{if(tn(e))return e;const t=Yo(e);return t<0?e:e.slice(0,t+1)},xl=e=>{const t=Yo(e);return e.slice(t+1)},yl=e=>{const t=cn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Yo(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},wl=e=>tn(e)&&yl(e)!==null,Xf=e=>{if(!wl(e))return null;const t=cn(e.trim());return xl(t)||t},Zf=(e,t)=>`${bl(e)}${t}/`,Rs=e=>{if(!e)return null;const t=cn(ln(e.trim()));return t?t.toLowerCase():null},Ti=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},eh=(e,t)=>{const n=cn(ln(e.trim())),r=cn(ln(t.trim()));if(!n)return"";if(!r)return fr(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:fr(n)},th=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,vo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},sh=async()=>Zu({fresh:!0}),nh=()=>{const[e,t]=Re.useState(!1),[n,r]=Re.useState(!1);Re.useEffect(()=>{t(rn()),r(el())},[]);const o=Re.useCallback(async c=>e?await tl(c):{success:!0,path:c},[e]),i=Re.useCallback(async c=>e?await ef():{success:!0},[e]),l=Re.useCallback(async c=>e?await tf():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function rh({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=on(Q=>Q.homeDirectory),{canRequestAccess:o,startAccessing:i}=nh(),l=a.useRef(null),c=a.useRef(new Map),[d,u]=a.useState(""),[f,p]=a.useState("~/"),[x,y]=a.useState([]),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,w]=a.useState(null),[E,A]=a.useState(0),[k,j]=a.useState(0),[v,N]=a.useState(!1),[M,L]=a.useState(!1),[K,z]=a.useState("right"),$=a.useRef("~/"),O=d||r;a.useEffect(()=>{if(!e)return;p("~/"),y([]),j(0),N(!1),L(!1),$.current="~/",z("right"),n||requestAnimationFrame(()=>vo(l.current));let Q=!1;return(async()=>{const ke=await sh();Q||(u(ke||r||""),n||requestAnimationFrame(()=>vo(l.current)))})(),()=>{Q=!0}},[r,e,n]);const R=a.useMemo(()=>bl(f),[f]),D=a.useMemo(()=>tn(f)?"":xl(f),[f]),I=a.useMemo(()=>O?Ti(R,O):"",[R,O]);a.useEffect(()=>{const Q=$.current;Q!==R&&(z(R.length>=Q.length?"right":"left"),$.current=R)},[R]),a.useEffect(()=>{if(!e||!I){y([]),w(null);return}let Q=!1;return h(!0),g(!1),w(null),sf(I).then(ie=>{if(Q)return;g(!1),w(null);const ke=ie.filter(Se=>Se.isDirectory).map(Se=>({name:Se.name,path:ln(Se.path)})).sort((Se,He)=>Se.name.localeCompare(He.name));y(ke)}).catch(ie=>{if(!Q){y([]);const ke=nf(ie)?ie.reason:"unknown";w(ke),g(ke==="not-found")}}).finally(()=>{Q||h(!1)}),()=>{Q=!0}},[I,E,e]);const T=a.useMemo(()=>{const Q=D.toLowerCase(),ie=M||D.startsWith(".");return x.filter(ke=>ke.name.toLowerCase().startsWith(Q)&&(ie||!ke.name.startsWith(".")))},[D,x,M]),W=a.useMemo(()=>Xf(f),[f]),Z=a.useMemo(()=>yl(f),[f]),F=a.useMemo(()=>{const Q=[],ie=Rs(I);wl(f)&&W&&Z&&Q.push({type:"parent",value:"browse:up",name:W,path:Z,alreadyAdded:!!(ie&&t.has(ie))});for(const ke of T){const Se=Rs(ke.path);Q.push({type:"directory",value:`browse:${ke.path}`,name:ke.name,path:ke.path,alreadyAdded:!!(Se&&t.has(Se))})}return Q},[t,I,W,T,Z,f]);a.useEffect(()=>{j(0)},[f,F.length]);const me=a.useMemo(()=>O?cn(Ti(f,O)):"",[O,f]),q=Rs(me),Ae=!!(q&&t.has(q)),Ie=a.useMemo(()=>D?T.find(Q=>Q.name===D)??null:null,[D,T]),G=!!(me&&!Ae&&(S===null||S==="not-found")&&(tn(f)&&b||!tn(f)&&D.trim().length>0&&Ie===null)),U=F[k]??null,Y=!!U,X=a.useCallback(Q=>{p(fr(Q))},[]),se=a.useCallback(Q=>{p(Zf(f,Q.name))},[f]),we=a.useCallback(Q=>{if(Q){if(Q.type==="parent"){X(Q.path);return}se(Q)}},[X,se]),pe=a.useCallback(async Q=>{const ie=await i(Q);if(!ie.success)return oe.error("Failed to open directory",{description:ie.error||"Desktop could not grant file access."}),!1;const ke=O?eh(Q,O):fr(ln(Q));return X(ke),!0},[X,O,i]),V=a.useCallback(async()=>{if(!v){N(!0);try{if(el()){const ie=await tl(me);if(!ie.success||!ie.path){ie.error&&ie.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:ie.error});return}await pe(ie.path);return}const Q=await rf(me);if(Q.status==="cancelled")return;if(Q.status!=="picked"){oe.error("Couldn't open a folder picker",{description:Q.error});return}await pe(Q.path)}catch(Q){oe.error("Failed to select directory",{description:Q instanceof Error?Q.message:"Unknown error occurred."})}finally{N(!1)}}},[pe,v,me]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:b,browseErrorReason:S,browseReloadKey:E,setBrowseReloadKey:A,highlightedIndex:k,setHighlightedIndex:j,isPickingLocation:v,showHidden:M,setShowHidden:L,folderEnterFrom:K,explorerRootDirectory:O,browseDirectoryDisplayPath:R,browseDirectoryAbsolutePath:I,browseFilterQuery:D,filteredEntries:T,rows:F,targetPath:me,isAlreadyAdded:Ae,shouldCreateTarget:G,highlightedRow:U,hasHighlightedBrowseItem:Y,canRequestAccess:o,browseToDisplayPath:X,browseToEntry:se,executeRow:we,applyPickedLocation:pe,handleBrowseLocation:V}}function oh({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=ct(L=>L.addProject),p=ce(L=>L.setActiveMainTab),x=ce(L=>L.setSessionSwitcherOpen),y=Te(L=>L.openNewSessionDraft),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,w]=a.useState("");a.useEffect(()=>{e&&(h(!1),g(!1),w(""))},[e]);const E=a.useCallback((L,K)=>{p("chat"),n&&x(!1),y({selectedProjectId:L,directoryOverride:K}),t()},[n,t,y,p,x]),A=a.useCallback(async L=>{if(!L||m)return;const K=Rs(L);if(K&&r.has(K))return;let z=L;h(!0);try{const $=!b&&i&&Rs(L)===Rs(o);if(b){const R=S.trim();if(!R){oe.error("Enter a repository URL before cloning.");return}const D=await nt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:R,destinationPath:L})});if(!D.ok)throw new Error("Failed to clone git repository");z=(await D.json()).path||L}else if($&&!(await nt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:L})})).ok)throw new Error("Failed to select directory");const O=f(z);if(!O){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}E(O.id,O.path)}catch($){oe.error("Failed to select directory",{description:$ instanceof Error?$.message:"Unknown error occurred."})}finally{h(!1)}},[f,r,c,S,b,m,E,i,o]),k=!m&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,j=k&&S.trim().length>0,v=b?j:k,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:b,setIsCloneMode:g,cloneRemoteUrl:S,setCloneRemoteUrl:w,canSubmit:v,submitActionLabel:d?"Already added":b?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:A}}const ih=({open:e,onOpenChange:t})=>{const n=ct(V=>V.projects),{isMobile:r,isTablet:o}=dn(),i=r||o,l=a.useMemo(()=>new Set(n.map(V=>Rs(V.path)).filter(V=>!!V)),[n]),c=a.useCallback(()=>{t(!1)},[t]),{inputRef:d,rowRefs:u,query:f,setQuery:p,isLoading:x,browseErrorReason:y,setBrowseReloadKey:m,highlightedIndex:h,setHighlightedIndex:b,isPickingLocation:g,showHidden:S,setShowHidden:w,folderEnterFrom:E,browseDirectoryDisplayPath:A,browseDirectoryAbsolutePath:k,rows:j,targetPath:v,isAlreadyAdded:N,shouldCreateTarget:M,highlightedRow:L,hasHighlightedBrowseItem:K,canRequestAccess:z,executeRow:$,handleBrowseLocation:O}=rh({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:R,isCloneMode:D,setIsCloneMode:I,cloneRemoteUrl:T,setCloneRemoteUrl:W,canSubmit:Z,submitActionLabel:F,submitModifierLabel:me,finalizeSelection:q}=oh({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:v,shouldCreateTarget:M,browseErrorReason:y,browseDirectoryAbsolutePath:k,isAlreadyAdded:N,isPickingLocation:g});a.useLayoutEffect(()=>{const V=d.current;V&&(V.scrollLeft=V.scrollWidth)},[d,f]),a.useLayoutEffect(()=>{!e||i||vo(d.current)},[d,e,i]),a.useLayoutEffect(()=>{const V=j[h];V&&u.current.get(V.value)?.scrollIntoView({block:"nearest"})},[h,u,j]);const Ae=a.useCallback(V=>{if(V.key==="ArrowDown"){V.preventDefault(),b(Q=>Math.min(j.length-1,Q+1));return}if(V.key==="ArrowUp"){V.preventDefault(),b(Q=>Math.max(0,Q-1));return}if(V.key==="Enter"){if(V.preventDefault(),th(V)){q(v);return}K&&$(L);return}V.key==="Backspace"&&f===""&&(V.preventDefault(),c())},[$,q,c,K,L,f,j.length,b,v]),Ie=s.jsxs("button",{type:"button",onClick:()=>w(V=>!V),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[S?s.jsx(P,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(P,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),G=s.jsx("div",{className:"py-1.5",children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),s.jsx(Ln,{ref:d,value:f,onChange:V=>p(ln(V.target.value)),onKeyDown:Ae,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),s.jsxs(Ne,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:R||g,onMouseDown:V=>V.preventDefault(),onClick:()=>{O()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(P,{name:"folder-open",className:"h-3.5 w-3.5"}),g?"Opening...":"Browse"]})]})}),U=j.some(V=>V.type==="parent"),Y=s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:s.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[s.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),s.jsxs(Ne,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":D,disabled:R||g,onClick:()=>I(V=>!V),children:[s.jsx(P,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),D?s.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsx(Ln,{value:T,onChange:V=>W(V.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})})]}):null,N?s.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,s.jsx("div",{className:_("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",E==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):y&&y!=="not-found"?s.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[s.jsx("div",{className:"typography-ui-label text-status-error",children:y==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),s.jsxs("div",{className:"flex items-center gap-2",children:[y==="os-permission"&&z?s.jsx(Ne,{size:"xs",onClick:()=>{O()},disabled:g,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:()=>m(V=>V+1),children:"Try again"})]})]}):j.length===0?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):s.jsx("div",{className:"space-y-0.5",children:j.map((V,Q)=>{const ie=Q===h,ke=V.type==="directory"&&U;return s.jsxs("button",{ref:Se=>{Se?u.current.set(V.value,Se):u.current.delete(V.value)},type:"button","aria-label":V.type==="parent"?V.alreadyAdded?`Go back from ${V.name}, already added`:`Go back from ${V.name}`:V.alreadyAdded?`Open ${V.name}, already added`:`Open ${V.name}`,onMouseEnter:()=>b(Q),onMouseDown:Se=>Se.preventDefault(),onClick:()=>$(V),className:_("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",ie&&"bg-interactive-selection text-interactive-selection-foreground",!ie&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",ke&&"pl-4"),children:[V.type==="parent"?s.jsx(P,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(P,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:V.name})]}),V.alreadyAdded?s.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",ie?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,V.type==="parent"?s.jsx(P,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):s.jsx(P,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},V.value)})})},A)]})}),X=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[G,Y]}),se=s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(P,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(P,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{children:me}),s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),we=s.jsx(Ne,{size:r?"xs":"default",onClick:()=>{q(v)},disabled:!Z,className:_(r&&"w-full flex-1"),children:F}),pe=()=>s.jsxs(s.Fragment,{children:[r?null:se,s.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:we})]});return r?s.jsx(La,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:pe()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Ie}),X]})}):s.jsx(ts,{open:e,onOpenChange:t,children:s.jsxs(ss,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(ws,{className:"px-5 pb-2 pt-5",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx(ds,{children:"Add folder"}),s.jsx(vs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Ie]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:X}),s.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:pe()})]})})},qn=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Tx=()=>{const[e,t]=a.useState(!1),[n,r]=a.useState(null),[o,i]=a.useState(!1),l=Te(k=>k.deleteSession),c=Te(k=>k.deleteSessions),d=ce(k=>k.showDeletionDialog),u=ce(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:x}=dn(),y=f||p||x;a.useEffect(()=>of(()=>{t(!1)}),[]);const m=a.useCallback(k=>{r({sessions:k.sessions,dateLabel:k.dateLabel})},[]),h=a.useCallback(()=>{r(null),i(!1)},[]),b=a.useCallback(async k=>{if(k.sessions.length===0)return;if(k.sessions.length===1){const M=k.sessions[0];await l(M.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const j=k.sessions.map(M=>M.id),{deletedIds:v,failedIds:N}=await c(j);if(v.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:k.dateLabel?`Removed all sessions from ${k.dateLabel}.`:void 0;oe.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:qn(M)})}N.length>0&&oe.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:qn("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Ms.onDeleteRequest(k=>{if(!d){b(k);return}m(k)}),[m,d,b]),a.useEffect(()=>Ms.onDirectoryRequest(()=>{t(!0)}),[]);const g=a.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const k=n.sessions[0];if(!await l(k.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=n.sessions.map(M=>M.id),j=await c(k),v=j.deletedIds,N=j.failedIds;if(v.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;oe.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:qn(M),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(oe.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:qn("Please try again in a moment.")}),v.length===0)){i(!1);return}}h()}finally{i(!1)}}},[n,l,c,h]),S=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",w=n?s.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&s.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(k=>s.jsx("li",{className:"typography-micro text-muted-foreground/80",children:s.jsx("span",{className:"truncate",children:gs(k)})},k.id)),n.sessions.length>5&&s.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,E=s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.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?s.jsx(P,{name:"checkbox-blank",className:"size-4"}):s.jsx(P,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ne,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",onClick:g,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),A=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(La,{open:!!n,onClose:()=>{o||h()},title:A,footer:s.jsx("div",{className:"flex justify-end gap-2",children:E}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[S&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:S}),w]})}):s.jsx(ts,{open:!!n,onOpenChange:k=>{if(!k){if(o)return;h()}},children:s.jsxs(ss,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:A}),S&&s.jsx(vs,{children:S})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:w}),s.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:E})]})}),s.jsx(ih,{open:e,onOpenChange:t})]})},Fx=()=>{const e=Ts(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!Gd(t)||!t.receipt||(Ts.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},ah=[{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"]}],lh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ch(e){const t=e.trim().toLowerCase();return ah.find(n=>n.slug===t)??null}function dh(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const n=lh[t];if(n)return n;const r=ch(t);return r?r.slug:"home"}function Lx(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 Ox(){const e=a.useRef(!1),t=a.useRef(!1),n=Te(f=>f.setCurrentSession),r=ce(f=>f.setActiveMainTab),o=ce(f=>f.setSettingsDialogOpen),i=ce(f=>f.setSettingsPage),l=ce(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Te.getState().currentSessionId,x=Js().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==x){const y=Te.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(dh(f.settingsPath)),o(!0);return}ce.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,l]),d=a.useCallback(()=>{const f=Te.getState(),p=Js().getState(),x=ce.getState();return{sessionId:Br({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=a.useCallback((f={})=>{if(t.current)return;const p=d();xo(p,f)},[d]);a.useEffect(()=>{if(e.current||(e.current=!0,!Si()))return;const f=ji();(async()=>(await c(f),xo({...d(),sessionId:f.sessionId??Br({currentSessionId:Te.getState().currentSessionId,piSelectedSessionId:Js().getState().selectedSessionId,draft:Te.getState().newSessionDraft}),tab:f.tab??ce.getState().activeMainTab,settingsPath:f.settingsPath??ce.getState().settingsPage,diffFile:f.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),a.useEffect(()=>{const f=()=>{const b=Te.getState(),g=Js().getState();return Br({currentSessionId:b.currentSessionId,piSelectedSessionId:g.selectedSessionId,draft:b.newSessionDraft})};let p=f(),x=Te.getState().newSessionDraft?.open===!0;const y=()=>{const b=Te.getState(),g=f(),S=b.newSessionDraft?.open===!0;g===p&&S===x||t.current||(p=g,x=S,u({replace:!0}))},m=Te.subscribe(()=>{y()}),h=Js().subscribe(()=>{y()});return()=>{m(),h()}},[u]),a.useEffect(()=>{let f=ce.getState().activeMainTab,p=ce.getState().isSettingsDialogOpen,x=ce.getState().settingsPage,y=ce.getState().pendingDiffFile;return ce.subscribe(h=>{if(t.current)return;const b=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==p,S=h.settingsPage!==x,w=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(b||g||S||w)&&u()})},[u]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=ji();if(Si())c(p);else{const x=ce.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function uh(e=!0){const t=sr(r=>r.checkForUpdates),n=a.useRef(t);a.useEffect(()=>{n.current=t},[t]),a.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=p=>{const x=Math.round(p*1e3);return Math.max(i,Math.min(l,x))},f=p=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),y=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(y)},p))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Bx(){const e=En(t=>t.connection==="ready",void 0,"chrome");return uh(e),null}const fh=200,hh=15e3,mh=e=>{const{id:t,url:n}=e.payload,r=qd(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=Yd(Vd(n),r.target,{isMobile:ce.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:hh});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Qd(r.target,n,Jd()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},_x=()=>(a.useEffect(()=>{const e=new Set;return Hd(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>fh){const n=e.values().next().value;n!==void 0&&e.delete(n)}mh(t)}})},[]),null),Fi=12,ph=[{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"}],gh=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=ph,onComplete:i})=>{const l=Re.useRef(!1);Re.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Re.useMemo(()=>Array.from({length:Fi},(d,u)=>{const f=Math.PI*2*u/Fi;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?s.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"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 s.jsx("div",{className:"firework-burst",style:u,children:c.map((f,p)=>{const x=f.x*d.radius,y=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${y}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return s.jsx("span",{className:"firework-particle",style:m},`${d.id}-${p}-${t}`)})},`${d.id}-${t}`)})}):null},bh=({durationMs:e=3400}={})=>{const[t,n]=Re.useState({isActive:!1,cycle:0}),r=Re.useRef(null),o=Re.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Re.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Re.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Re.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},vl=a.createContext(void 0),Ux=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=bh(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(vl.Provider,{value:i,children:[e,s.jsx(gh,{isActive:t,burstKey:n})]})},xh={triggerFireworks:()=>{},dismissFireworks:()=>{}},zx=()=>a.useContext(vl)??xh,hr=2e3,Sl=600*1e3;async function yh(){try{const e=await nt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const 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 wh(e,t=Math.ceil(Sl/hr),n=hr,r=Je()){for(let o=0;o<t;o++){if(Je()!==r)return{applied:!1,stale:!0};try{const i=await nt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Je()!==r)return{applied:!1,stale:!0};if(i.ok){const l=await i.json().catch(()=>null);if(Je()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Je()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function vh(e,t,n=Math.ceil(Sl/hr),r=hr,o=Je()){for(let i=0;i<n;i++){if(Je()!==o)return{applied:!1,stale:!0};try{const l=await nt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Je()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Je()!==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(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Je()!==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(Je()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Li="https://github.com/RyderAsKing/PiChamber/releases";function Sh(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 jh(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Oi(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function kh(e,t){const n=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=n(e),[i,l]=n(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,p=Number.isFinite(d[u])?d[u]:0;if(f!==p)return p-f}return!o||!l?(o?1:0)-(l?1:0):l.localeCompare(o,void 0,{numeric:!0})}function Ch(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=t.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,i)=>{const l=n[i+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const jl=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Re.useState(null),[x,y]=Re.useState("idle"),[m,h]=Re.useState(null),[b,g]=Re.useState(null),[S,w]=Re.useState({}),E=n?.version?n.releaseUrl||`${Li}/tag/v${n.version}`:Li,A=n?.downloadUrl||E,k=i?.total?Math.round(i.downloaded/i.total*100):0,j=u==="web",v=u==="mobile",N=n?.updateCommand||"pichamber update",M=S.version||n?.version,L=S.channel||n?.channel;Re.useEffect(()=>{e||(y("idle"),h(null),g(null),w({}))},[e]);const K=async(I=N)=>{(await xs(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},z=Re.useCallback(async I=>{await Oa(I)},[]),$=Re.useCallback(async()=>{const I=Je();y("updating"),h(null),g(null),w({});const T=await yh();if(Je()!==I)return;if(!T.success){y("error"),h(T.error||"Update failed"),g(T.commands??null);return}if(w({version:T.targetVersion,channel:T.channel}),T.jobId){const Z=await vh(T.jobId,F=>{Je()===I&&y(F)},void 0,void 0,I);if(Z.stale||Je()!==I)return;if(Z.applied){window.location.reload();return}y("error"),h(Z.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(T.autoRestart?"restarting":"reconnecting");const W=await wh(n?.currentVersion,void 0,void 0,I);if(!(W.stale||Je()!==I)){if(W.applied){window.location.reload();return}y("error"),h(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),O=Re.useCallback(()=>{z(A)},[z,A]),R=x!=="idle"&&x!=="error",D=Re.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const T=Ch(I);return T.length===0?{kind:"raw",title:"What's new",content:Oi(I)}:{kind:"sections",title:"What's new",sections:[...T].sort((Z,F)=>kh(Z.version,F.version)).map(Z=>({version:Z.version,dateLabel:Sh(Z.date),content:Oi(jh(Z.raw)||I)}))}},[n?.body]);return s.jsx(ts,{open:e,onOpenChange:R?void 0:t,children:s.jsxs(ss,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[s.jsxs(ds,{className:"flex items-center gap-2.5",children:[s.jsx(P,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(n?.currentVersion||M||j&&L)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||M)&&s.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&M&&s.jsx("span",{className:"text-muted-foreground/50","aria-hidden":"true",children:"→"}),M&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:M})]}),j&&L&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:L==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[j&&R&&s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(P,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),D&&!R&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Is,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:D.kind==="raw"?s.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 W=I.target.closest("a");W&&W.href&&(I.preventDefault(),I.stopPropagation(),z(W.href))},children:s.jsx(ki,{content:D.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:D.sections.map(I=>s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.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]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),s.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:T=>{const Z=T.target.closest("a");Z&&Z.href&&(T.preventDefault(),T.stopPropagation(),z(Z.href))},children:s.jsx(ki,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(l||m)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||m})}),j&&x==="error"&&(b??[N]).length>0&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(P,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:b?"Run these commands:":"Or update via terminal:"})]}),(b??[N]).map(I=>s.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:[s.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),s.jsx(Ne,{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?s.jsx(P,{name:"check",className:"h-4 w-4"}):s.jsx(P,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!j&&!v&&r&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),s.jsxs("span",{className:"font-mono text-foreground",children:[k,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${k}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[s.jsxs("a",{href:E,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:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!v&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!j&&!v&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!v&&o&&s.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:[s.jsx(P,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),v&&s.jsxs(Ne,{onClick:O,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!R&&s.jsxs(Ne,{onClick:$,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),j&&R&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},kl=a.memo(function({checked:t,onChange:n,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:l,iconClassName:c}){const d=a.useCallback(x=>{x.preventDefault(),x.stopPropagation(),!r&&!t&&n()},[t,r,n]),u=a.useCallback(x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),!r&&!t&&n())},[t,r,n]),f=s.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),p=_("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-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)]");return i?s.jsx("span",{"aria-hidden":!0,className:_(p,r&&"opacity-50",l),children:f}):s.jsx("button",{type:"button",role:"radio",onClick:d,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",p,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",l),children:f})}),zn=({children:e,className:t,contentClassName:n})=>{const[r,o]=a.useState(!1),i=a.useRef(null);return a.useEffect(()=>{if(!r)return;const l=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),s.jsxs($e,{open:r,onOpenChange:o,children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:s.jsx(P,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(We,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},$x="w-full min-w-40 max-w-48",Kx="settings",Ah="w-full min-w-40 max-w-48",Wx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Nh="w-full max-w-[24rem]",Gx="min-w-0 flex-1",Hx="flex w-full min-w-0 items-center gap-2",qx="typography-meta shrink-0 text-muted-foreground tabular-nums",Cl="space-y-3.5",Ih="space-y-1.5",Yx="typography-settings-page-title text-muted-foreground",Eh="typography-settings-section-title text-foreground",Al="typography-settings-group-title text-foreground",Vo="typography-settings-field-label text-foreground",Rh="typography-settings-description text-muted-foreground",$n="typography-meta text-muted-foreground",Vx="typography-meta font-medium text-foreground",Qx="typography-settings-section-title text-foreground",Dh=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return s.jsxs("section",{"data-settings-item":u,className:_("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?s.jsx("h2",{className:Eh,children:e}):e,n,r!=null?s.jsx(zn,{children:r}):null]}):null,t!=null?s.jsx("div",{className:Rh,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},Jx=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),Ph=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(Al,t),children:e}),Xx=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:l})=>s.jsxs("div",{"data-settings-item":l,className:_("space-y-2",o),children:[e!=null||t!=null||n!=null?s.jsxs("div",{className:"space-y-0.5",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Ph,{children:e}),n!=null?s.jsx(zn,{children:n}):null]}):null,t!=null?s.jsx("p",{className:$n,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),Pn=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:l,controlClassName:c})=>{const d=t!=null?s.jsx("p",{className:$n,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:_("space-y-2",l),children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Vo,children:e}),n!=null?s.jsx(zn,{children:n}):null]}),r==="before"?d:null]}),s.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},Zx=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:l,controlClassName:c,alignEnd:d=!0})=>s.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:[s.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",l),children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Vo,children:e}),n!=null?s.jsx(zn,{children:n}):null]}),t!=null?s.jsx("p",{className:_($n,"mt-0.5"),children:t}):null]}),s.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})]}),ey=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),ty=({label:e,children:t,divider:n=!0,className:r,contentClassName:o})=>s.jsxs("details",{className:_("group/disclosure",n?"border-t border-border/60 py-6":"pb-6",r),children:[s.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:[s.jsx(P,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),s.jsx("div",{className:_("pt-4",o),children:t})]}),Mh=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},p=r!=null;return s.jsxs("div",{"data-settings-item":l,className:_("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[s.jsx(io,{checked:e,onChange:t,disabled:o,ariaLabel:i}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:Vo,children:n}),d,u!=null?s.jsx(zn,{children:u}):null]}),p?s.jsx("span",{className:$n,children:r}):null]})]})},sy=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",l),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:[s.jsx(kl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:_("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?s.jsx("span",{className:$n,children:r}):null]})]}),ny=({selected:e,onSelect:t,label:n,preview:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",i&&"cursor-not-allowed opacity-60",l),role:"radio",tabIndex:i?-1:0,"aria-checked":e,"aria-label":o,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.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-border group-hover/preview:border-foreground/30"),children:r}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(kl,{checked:e,onChange:t,disabled:i,decorative:!0}),s.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n})]})]}),ry=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(Ih,n),children:t});function oy({value:e,options:t,onChange:n,className:r,"aria-label":o}){return s.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>s.jsx(Ne,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>n(i.value),children:i.label},i.value))})}const So="pichamber:server-update-channel-changed",iy=()=>{typeof window<"u"&&window.dispatchEvent(new Event(So))},Th=e=>typeof window>"u"?()=>{}:(window.addEventListener(So,e),()=>window.removeEventListener(So,e));class Fh extends a.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?s.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:s.jsxs(Xd,{className:"w-full max-w-md",children:[s.jsx(Zd,{className:"text-center",children:s.jsxs(eu,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(P,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(tu,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&s.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&s.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[s.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),s.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(P,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),s.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Lh(e){return s.jsx(Fh,{...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 ay=({active:e=!0})=>{const t=Te(n=>n.currentSessionId);return s.jsx(Lh,{sessionId:t||void 0,children:s.jsx(su,{active:e},t??"no-session")})};function Oh({onResizeStart:e,ariaLabel:t}){return s.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:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:s.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const Nl=Re.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:p,...x},y)=>{const m=Re.useRef(null),h=Re.useRef(null),[b,g]=Re.useState(null),S=c??b,w=Re.useCallback(A=>{const k=m.current;if(!k)return;h.current={startY:A.clientY,startHeight:k.getBoundingClientRect().height};const j=A.currentTarget;j.setPointerCapture(A.pointerId);const v=M=>{const L=h.current;if(!L)return;const K=L.startHeight+(M.clientY-L.startY),z=Math.max(82,K);d?d(z):g(z)},N=()=>{h.current=null,j.removeEventListener("pointermove",v),j.removeEventListener("pointerup",N),j.removeEventListener("pointercancel",N)};j.addEventListener("pointermove",v),j.addEventListener("pointerup",N),j.addEventListener("pointercancel",N),A.preventDefault()},[d]),E=Re.useCallback(A=>{if(A.target.closest('textarea, button, [role="separator"]'))return;const j=m.current?.querySelector("textarea");j&&document.activeElement!==j&&(A.preventDefault(),j.focus())},[]);return f?s.jsx(Is,{as:"textarea",ref:y,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:n,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):s.jsx("div",{ref:m,onPointerDown:E,style:S!==null?{height:`${S}px`}:void 0,className:_("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[s.jsx("textarea",{ref:y,className:_("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,s.jsx(Oh,{onResizeStart:w,ariaLabel:"Resize textarea"})]})]})})});Nl.displayName="Textarea";const Il=[{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"}],Mn=Object.fromEntries(Il.map(e=>[e.key,e.Icon])),jo="pichamber:project-actions-updated",El=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},as=(e,t)=>`${El(e)}::${t}`,Rl=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:d,divider:u=!0})=>s.jsx(Dh,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:l}),ko=e=>e.name.trim().length>0&&e.command.trim().length>0,Bh=e=>e.name.trim().length===0&&e.command.trim().length===0,_h=e=>!ko(e)&&!Bh(e),Uh=(e,t)=>e.some(r=>t.has(r.id)&&!ko(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(ko)},zh=450,$h=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Kh=()=>({id:$h(),name:"",command:"",icon:"play"}),Wh=({projectRef:e})=>{const[t,n]=a.useState([]),[r,o]=a.useState(!1),[i,l]=a.useState(null),[c,d]=a.useState(new Set),u=a.useRef(!1);a.useEffect(()=>{let g=!1;return o(!0),(async()=>{try{const S=await ao(e);if(g)return;n(S.actions),l(JSON.stringify({actions:S.actions})),d(new Set(S.actions.map(w=>w.id)))}catch{if(g)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=a.useMemo(()=>Uh(t,c),[t,c]),p=a.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=i!==null&&f.canPersist&&p!==i,y=a.useCallback(async g=>await nu(e,{actions:g,primaryActionId:null})?(l(JSON.stringify({actions:g})),d(new Set(g.map(w=>w.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(jo,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);a.useEffect(()=>{if(!x||r||u.current)return;const g=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await y(f.actions)}finally{u.current=!1}})())},zh);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const m=a.useCallback(()=>{const g=Kh();n(S=>[...S,g])},[]),h=a.useCallback(g=>{n(S=>S.filter(w=>w.id!==g))},[]),b=a.useCallback((g,S)=>{n(w=>w.map(E=>E.id===g?S(E):E))},[]);return s.jsx(Rl,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ne,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[s.jsx(P,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):s.jsx("div",{className:_("space-y-6",Nh),children:t.map((g,S)=>{const w=g.icon||"play",E=Mn[w]||"play",A=g.name.trim()||`Action ${S+1}`,k=_h(g);return s.jsxs("div",{className:Cl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Al,children:A}),s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(g.id),"aria-label":`Delete ${A}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(Pn,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:E,className:"h-4 w-4"})})}),s.jsx(qt,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Il.map(j=>{const v=j.Icon,N=(g.icon||"play")===j.key;return s.jsx("button",{type:"button",onClick:()=>b(g.id,M=>({...M,icon:j.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",N&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:s.jsx(P,{name:v,className:"h-4 w-4"})},j.key)})})})]}),s.jsx(Ln,{value:g.name,onChange:j=>b(g.id,v=>({...v,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(Pn,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(Nl,{value:g.command,onChange:j=>b(g.id,v=>({...v,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),k?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(Mh,{checked:g.autoOpenUrl===!0,onChange:j=>b(g.id,v=>({...v,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${A}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(Pn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Ln,{value:g.openUrl||"",onChange:j=>b(g.id,v=>({...v,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},Gh={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)"},Hh=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=Kt(v=>v.providers),d=Kt(v=>v.modelsMetadata),u=ce(v=>v.hiddenModels),f=ce(v=>v.isFavoriteModel),p=ce(v=>v.toggleFavoriteModel),x=ce(v=>v.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:m}=ru(),[h,b]=a.useState(!1),[g,S]=a.useState("");a.useEffect(()=>{h?Kt.getState().ensureModelMetadata():S("")},[h]);const w=e?c.find(v=>v.id===e.providerId):void 0,E=e&&w?(Array.isArray(w.models)?w.models:[]).find(v=>v.id===e.modelId):void 0,A=e?ou(E,e.modelId):t,k=a.useMemo(()=>e?u.filter(v=>!(v.providerID===e.providerId&&v.modelID===e.modelId)):u,[u,e]),j=a.useCallback(v=>{l({providerId:v.providerID,modelId:v.modelID}),b(!1)},[l]);return s.jsxs(Gt,{modal:!1,open:h,onOpenChange:v=>{r||b(v)},children:[s.jsx(Ht,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(au({size:"default"}),Ah,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(iu,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:A})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(lu,{providers:c,favoriteModels:y,recentModels:m,modelsMetadata:d,searchQuery:g,onSearchQueryChange:S,onSelect:j,labels:{...Gh,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:k,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{l(null),b(!1)},disabled:r,autoFocus:!0,onEscape:()=>b(!1),isFavorite:v=>f(v.providerID,v.modelID),onToggleFavorite:v=>p(v.providerID,v.modelID),onReorderFavorite:(v,N)=>x(v.providerID,v.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},Ur="w-full max-w-none",qh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=Kt(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(Rl,{title:"Project",divider:!1,children:s.jsxs("div",{className:Cl,children:[s.jsx(Pn,{label:"Name",settingsItem:"projects.name",controlClassName:Ur,children:s.jsx(Ln,{value:t,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),s.jsx(Pn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:Ur,children:s.jsx(Hh,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:Ur,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Yh=e=>{const[t,n]=a.useState(""),[r,o]=a.useState(void 0);a.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const i=a.useMemo(()=>cu(r),[r]),l=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=a.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=a.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:n,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Vh=450,Qh=(e,t)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:i}=e,l=a.useRef(!1);a.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},Vh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Jh=({project:e,onIdentitySave:t})=>{const n=Yh(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return Qh(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(qh,{form:n}),s.jsx(Wh,{projectRef:r})]})},Xh=6e4,Zh=3e4,vn=new Map;let Bi=0,_i=!1;const em=()=>{if(_i||typeof window>"u")return;_i=!0;const e=()=>{const t=Date.now();t-Bi<Zh||typeof document<"u"&&document.hidden||(Bi=t,mt(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-C2ISrmRR.js").then(r=>r.cI);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&kr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},kr=Bs()(jr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Ft(),resetForRuntimeSwitch:n=>{const r=n??Ft();vn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{em();const o=Ft();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<Xh)return i.status;const c=vn.get(o);if(c)return c;const d=n??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return Ft()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Ft()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();vn.set(o,u);try{return await u}finally{vn.get(o)===u&&vn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&Un(e=>{kr.getState().resetForRuntimeSwitch(e.runtimeKey)});const tm=()=>kr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),ly=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 n=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(n?.width)||!Number.isFinite(n?.height)?null:{header:n,jpeg:new Uint8Array(e,4+t)}}catch{return null}},cy=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},dy=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",uy=50*1024*1024-1,fy=[250,1e3,2e3,4e3,8e3],sm=(e,t)=>{const n=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-${n(2166136261)}${n(16777619)}`},hy=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),my=(e,t,n,r)=>{if(n.width<=0||n.height<=0)return null;const o=(e-n.left)/n.width*r.width,i=(t-n.top)/n.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}},py=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,gy=(e,t)=>{const n=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(n)&&n>0?n:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},un=async(e,t)=>{const n=await e.json().catch(()=>null);return new Error(typeof n?.error=="string"?n.error:t)},by=async()=>{const e=await nt("/api/server-browser/status");if(!e.ok)throw await un(e,"Could not check the server browser");return await e.json()},xy=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 un(t,"Could not save the server browser settings");return await t.json()},yy=async(e,t)=>{const n=await nt("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!n.ok)throw await un(n,"Could not find dev servers");const r=await n.json();return Array.isArray(r.servers)?r.servers:[]},wy=async(e,t,n)=>{const r=await nt("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:n});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"}},vy=async()=>{const e=await nt("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await un(e,"Could not clear browsing data")},Sy=(e,t)=>{const n=sm(e,t);nt(`/api/server-browser/tabs/${encodeURIComponent(n)}`,{method:"DELETE"}).catch(()=>{})},jy=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),n=await nt(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!n.ok)throw await un(n,`Could not upload ${e.name}`);const r=await n.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},ky=async(e,t)=>{const n=await nt(`/api/server-browser/downloads/${encodeURIComponent(e)}`);if(!n.ok)throw await un(n,`Could not download ${t}`);const r=await n.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)}},Cy=async(e,t,n)=>{const r=await lf();return{socket:cf(df().websocket("/api/server-browser/ws",{tab:e,url:t,popup:n},r)),urlAuthToken:r}},Ay=e=>{af(e)},Yn=100;function Ny(){const e=ce(v=>v.isArchivePageOpen),t=ce(v=>v.setArchivePageOpen),n=ce(v=>v.setActiveMainTab),r=Te(v=>v.setCurrentSession),o=Te(v=>v.unarchiveSession),i=on(v=>v.homeDirectory),l=lo({archived:!0}),[c,d]=a.useState(""),[u,f]=a.useState(null),[p,x]=a.useState(Yn),y=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((v,N)=>(N.time?.archived??0)-(v.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const v=new Map;for(const N of m){const M=Ee(Rn(N))??"",L=v.get(M);if(L){L.sessions.push(N);continue}v.set(M,{directory:M,label:M?On(M,i)||M:"other projects",sessions:[N]})}return[...v.values()].sort((N,M)=>M.sessions.length-N.sessions.length)},[i,m]),b=a.useMemo(()=>y?m.filter(v=>(v.title??"").toLowerCase().includes(y)):u===null?m:h.find(v=>v.directory===u)?.sessions??[],[h,y,u,m]),g=b.slice(0,p),S=b.length-g.length,w=l.length,E=a.useCallback(v=>{f(v),x(Yn)},[]),A=a.useCallback(v=>{const N=Ee(Rn(v));r(v.id,N??void 0),n("chat"),t(!1)},[n,r,t]),k=a.useCallback(v=>{o(v.id).then(N=>{N?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const j=(v,N,M,L,K,z,$)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:K,title:z,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",$?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",L?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:N}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:M})]}),$?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Ms.requestDelete({sessions:$,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${N}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},v);return s.jsx(Dd,{open:e,onOpenChange:t,children:s.jsxs(Pd,{children:[s.jsx(Md,{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"}),s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:s.jsxs(Td,{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:[s.jsx(Fd,{className:"sr-only",children:"Archived sessions"}),s.jsx(Ld,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Od,{"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:s.jsx(P,{name:"close",className:"size-4"})}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:s.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[j("__all__","All directories",w,u===null,()=>E(null)),h.map(v=>j(v.directory||"__none__",v.label,v.sessions.length,u===v.directory,()=>E(v.directory),v.directory||void 0,v.sessions))]})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{value:c,onChange:v=>{d(v.target.value),x(Yn)},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"})]}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:b.length===1?`${b.length} archived session`:`${b.length} archived sessions`})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[g.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:y?"No matching archived sessions":"No archived sessions"})}):g.map(v=>{const N=Ee(Rn(v))??"",M=N?On(N,i)||N:null;return s.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:()=>A(v),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),A(v))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:gs(v)}),y&&M?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:M}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Df(v.time?.archived??v.time?.updated??v.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),k(v)},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 ${gs(v)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),Ms.requestDelete({sessions:[v],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 ${gs(v)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},v.id)}),S>0?s.jsx("button",{type:"button",onClick:()=>x(v=>v+Yn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const nm=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+n+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,n);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},rm=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+n+r},Xt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,om=e=>{if(!e||typeof e!="object")return null;const t=Xt(e.input),n=Xt(e.output),r=Xt(e.cacheRead),o=Xt(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},Ui=e=>{const t=om(e.info.usage);if(t)return t;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total: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),l=Xt(o.output),c=Xt(o.reasoning),d=Xt(o.cache?.read),u=Xt(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:i+l+c+d+u}},Dl=380,zr=8,im=140;function am({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=a.useRef(null),i=a.useRef(null),[l,c]=a.useState(e),[d,u]=a.useState(!1),[f,p]=a.useState(null),{enabled:x}=Wo();return a.useLayoutEffect(()=>{if(!e||!x||!l)return;const y=()=>{const b=n.current?.getBoundingClientRect(),g=i.current?.getBoundingClientRect();if(!b||!g){p(null);return}const S=b.left-g.left;p(Math.min(Math.max(S,zr),Math.max(zr,g.width-Dl-zr)))};y();const m=i.current;if(typeof ResizeObserver>"u"||!m)return;const h=new ResizeObserver(y);return h.observe(m),()=>h.disconnect()},[n,x,e,l]),a.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const y=window.setTimeout(()=>{c(!1),u(!1)},im);return()=>window.clearTimeout(y)},[e,l]),a.useEffect(()=>{if(!e)return;const y=m=>{m.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,e]),a.useEffect(()=>{if(!e)return;const y=m=>{const h=m.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||n.current?.contains(h)||t()};return document.addEventListener("pointerdown",y,!0),r&&document.addEventListener("wheel",y,!0),()=>{document.removeEventListener("pointerdown",y,!0),r&&document.removeEventListener("wheel",y,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const zi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},mr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Vn=({icon:e,iconNode:t,label:n,children:r})=>s.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[s.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?s.jsx(P,{name:e,className:"size-[18px]"}):null)}),s.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),lm=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=am({open:e,onClose:t,anchorRef:n,closeOnWheel:!0});return l?s.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:[s.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(${Dl}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(Vn,{iconNode:s.jsx(Ba,{percentage:r.percentage}),label:"Context",children:s.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[s.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),s.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?s.jsxs(s.Fragment,{children:[s.jsx(Vn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:mr(r.cacheRead)})}),s.jsx(Vn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:mr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(Vn,{icon:"check",label:"Cache hit",children:s.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):s.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),s.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}`},Qi=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:n
|
|
|
17
17
|
`)[1]??"",Ro=(e,t)=>`${cs(e)}
|
|
18
18
|
${t}`,jn=(e,t)=>`${e}#${t}`,bp=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},Ns=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Zi=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,ea=10,xp=(e,t)=>{const n=en(),r=en({maxEntries:60}),o=en(),i=en(),l=new Map,c=new Map,d=async(O,R)=>{const D=c.get(O);if(D)return await D.catch(()=>null),{ran:!1,result:null};const I=R();c.set(O,I);try{return{ran:!0,result:await I}}finally{c.get(O)===I&&c.delete(O)}},u=(O,R)=>{if(R.length===0)return;const D=e.collectionKeyFor(O,e.openCollection);let I=l.get(D);I||(I=new Map,l.set(D,I));for(const T of R)I.set(T.number,T)},f=O=>{const R=Object.keys(r.snapshot()).filter(I=>$r(I)===O&&!r.getEntry(I)?.isLoading);if(R.length<=ea)return;const D=R.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,T)=>I.fetchedAt-T.fetchedAt);for(let I=0;I<D.length-ea;I+=1)r.remove(D[I].key)},p=O=>{const R=n.getEntry(e.collectionKeyFor(O,e.openCollection))?.data?.items??[],D=n.getEntry(e.collectionKeyFor(O,e.closedCollection))?.data?.items??[],I=Jn(R,D),T=l.get(e.collectionKeyFor(O,e.openCollection));return!T||T.size===0?I:Jn(I,[...T.values()])},x=(O,R,D)=>{const I=Ro(O,R),T=t.get().filtersByScope[I]??e.defaultFilters;t.set(W=>({filtersByScope:{...W.filtersByScope,[I]:{...T,...D}}}))},y=(O,R)=>{const D=Ro(O,R);t.set(I=>({filtersByScope:{...I.filtersByScope,[D]:{...e.defaultFilters}}}))},m=(O,R,D)=>{const I=cs(O);I&&t.set(T=>({selectionByDirectory:{...T.selectionByDirectory,[I]:{repo:R,number:D}}}))},h=(O,R,D,I)=>{const T=e.collectionKeyFor(R,D);return n.ensure(T,async()=>{const W=await e.fetchList(I,O,R,e.buildCollectionQuery(D));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},b=(O,R,D)=>{const I=e.collectionKeyFor(R,e.closedCollection);n.getEntry(I)?.data||n.getEntry(I)?.isLoading||h(O,R,e.closedCollection,D).catch(()=>null)},g=async(O,R,D,I)=>{const T=D==="open"||D==="both",W=D==="closed"||D==="both",Z=[],F=n.getEntry(e.collectionKeyFor(R,e.openCollection)),me=n.getEntry(e.collectionKeyFor(R,e.closedCollection));T&&(!Zi(F,e.freshWindowMs)||F?.stale)&&Z.push(h(O,R,e.openCollection,I)),W&&(!Zi(me,e.freshWindowMs)||me?.stale)&&Z.push(h(O,R,e.closedCollection,I)),await Promise.all(Z.map(q=>q.catch(()=>null))),T&&!n.getEntry(e.collectionKeyFor(R,e.closedCollection))?.data&&b(O,R,I)},S=async(O,R,D,I)=>{const T=e.collectionKeyFor(R,D),W=n.getEntry(T),Z=W?.data?.nextCursor??null;if(!Z||W?.isLoading)return W;try{const F=await d(`${T}:more`,async()=>{const me=await e.fetchList(I,O,R,{...e.buildCollectionQuery(D),cursor:Z}),q=n.getEntry(T)?.data,Ae={items:Jn(q?.items??[],me.items),nextCursor:me.nextCursor,fetchedAt:me.fetchedAt};return n.refresh(T,async()=>Ae)});return F.ran?F.result??n.getEntry(T):n.getEntry(T)}catch(F){return n.setError(T,F)??n.getEntry(T)}},w=async(O,R,D,I)=>{const T=D==="both"?[e.openCollection,e.closedCollection]:[D];await Promise.all(T.map(W=>{const Z=e.collectionKeyFor(R,W);return n.refresh(Z,async()=>{const F=await e.fetchList(I,O,R,e.buildCollectionQuery(W));return{items:F.items,nextCursor:F.nextCursor,fetchedAt:F.fetchedAt}}).catch(()=>null)}))},E=async(O,R,D,I)=>{const T=e.remoteKeyFor(R,D),W=await r.refresh(T,async()=>{const Z=await e.fetchList(I,O,R,e.buildRemoteQuery(D));return{items:Z.items,nextCursor:Z.nextCursor,fetchedAt:Z.fetchedAt}});return W.data&&(u(R,W.data.items),f(R)),W},A=async(O,R,D,I)=>{const T=e.remoteKeyFor(R,D),W=r.getEntry(T),Z=W?.data?.nextCursor??null;if(!Z||W?.isLoading)return W;try{const F=await e.fetchList(I,O,R,e.buildRemoteQuery(D,Z)),me=r.getEntry(T)?.data,q={items:Jn(me?.items??[],F.items),nextCursor:F.nextCursor,fetchedAt:F.fetchedAt},Ae=await r.refresh(T,async()=>q);return Ae.data&&(u(R,Ae.data.items),f(R)),Ae}catch(F){return r.setError(T,F)??r.getEntry(T)}},k=O=>{for(const R of Object.keys(r.snapshot()))$r(R)===O&&r.remove(R);for(const R of[...l.keys()])$r(R)===O&&l.delete(R)},j=(O,R,D,I)=>{const T=e.detailKeyFor(R,D);return o.refresh(T,async()=>({detail:await e.fetchDetail(I,O,R,D)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:n,remote:r,details:o,comments:i},setFilters:x,resetFilters:y,select:m,ensureCollection:h,ensureCollectionsFresh:g,prefetchClosedCollection:b,loadMoreCollection:S,refreshCollections:w,searchRemote:E,loadMoreRemote:A,dropRemoteForRepo:k,refreshAllForScope:async(O,R,D)=>{await Ns(D,{directory:O,repo:R,kind:e.serverKind}),k(R),await w(O,R,"both",D).catch(()=>null);const I=t.get().selectionByDirectory[cs(O)];I?.repo===R&&typeof I.number=="number"&&await j(O,R,I.number,D).catch(()=>null)},ensureDetail:(O,R,D,I)=>{const T=e.detailKeyFor(R,D);return o.ensure(T,async()=>({detail:await e.fetchDetail(I,O,R,D)}))},refreshDetail:j,ensureComments:(O,R,D,I)=>{const T=e.commentsKeyFor(R,D);return i.ensure(T,async()=>{const W=await e.fetchComments(I,O,R,D);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},loadMoreComments:async(O,R,D,I)=>{const T=e.commentsKeyFor(R,D),W=i.getEntry(T),Z=W?.data?.nextCursor??null;if(!Z||W?.isLoading)return W;try{const F=await e.fetchComments(I,O,R,D,Z),me=i.getEntry(T)?.data,q={comments:gp(me?.comments??[],F.comments),nextCursor:F.nextCursor,fetchedAt:F.fetchedAt};return await i.refresh(T,async()=>q)}catch(F){return i.setError(T,F)??i.getEntry(T)}},refreshComments:(O,R,D,I)=>{const T=e.commentsKeyFor(R,D);return i.refresh(T,async()=>{const W=await e.fetchComments(I,O,R,D);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},markCollectionsStale:O=>{n.markStale(e.collectionKeyFor(O,e.openCollection)),n.markStale(e.collectionKeyFor(O,e.closedCollection))},getLocalIndex:p,withSingleFlight:d,resetCore:()=>{n.reset(),r.reset(),l.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:O=>bp(O,e.errorFallback)}},Do={state:"open",involvement:"all",search:"",sort:"updated"},yp=3e4,wp=100,vp=50,Vl=(e,t)=>hn([e,"pulls-collection",t]),Ql=(e,t)=>hn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),br=(e,t)=>hn([e,"pull-detail",t]),Zo=(e,t)=>hn([e,"pull-comments",t]),Po=(e,t)=>hn([e,"pull-files",t]),Mo=(e,t)=>hn([e,"pull-checks",t]),Sp=e=>({state:e,perPage:wp}),jp=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:vp,...t?{cursor:t}:{}}),xr=e=>`pichamber:pr-merge-method:${e}`,Jl=new Map,kp=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},Cp=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},My=e=>{if(!e)return null;const t=kp(xr(e));return t==="merge"||t==="squash"||t==="rebase"?t:Jl.get(xr(e))??null},Ap=(e,t)=>{if(e){Jl.set(xr(e),t);try{Cp(xr(e),t)}catch{}}},Np={set:e=>{typeof e=="function"?bs.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):bs.setState(e)},get:()=>{const e=bs.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Pe=xp({openCollection:"open",closedCollection:"closed",defaultFilters:Do,freshWindowMs:yp,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Vl,remoteKeyFor:Ql,detailKeyFor:br,commentsKeyFor:Zo,buildCollectionQuery:e=>({...Sp(e)}),buildRemoteQuery:(e,t)=>({...jp(e,t)}),fetchList:async(e,t,n,r)=>{const o=await e.pullsList(t,n,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,n,r)=>e.pullGet(t,n,r),fetchComments:async(e,t,n,r,o)=>{const i=await e.pullComments(t,n,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},Np),Jt=en(),ir=en(),bs=Bs()(jr((e,t)=>({...Pe.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Pe.setFilters,resetFilters:Pe.resetFilters,selectPullRequest:Pe.select,ensureCollection:Pe.ensureCollection,ensureCollectionsFresh:Pe.ensureCollectionsFresh,prefetchClosedCollection:Pe.prefetchClosedCollection,loadMoreCollection:Pe.loadMoreCollection,refreshCollections:Pe.refreshCollections,searchRemote:Pe.searchRemote,loadMoreRemote:Pe.loadMoreRemote,dropRemoteForRepo:Pe.dropRemoteForRepo,refreshAllForScope:Pe.refreshAllForScope,ensureDetail:Pe.ensureDetail,refreshDetail:Pe.refreshDetail,ensureComments:Pe.ensureComments,loadMoreComments:Pe.loadMoreComments,refreshComments:Pe.refreshComments,ensureFiles:(n,r,o,i)=>{const l=Po(r,o);return Jt.ensure(l,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const l=Po(r,o),c=Jt.getEntry(l),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Pe.withSingleFlight(`${l}:more`,async()=>{const f=await i.pullFiles(n,r,o,d),p=Jt.getEntry(l)?.data,x=new Set((p?.files??[]).map(m=>m.filename)),y={repo:f.repo,number:f.number,files:[...p?.files??[],...f.files.filter(m=>!x.has(m.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Jt.refresh(l,async()=>y)});return u.ran?u.result??Jt.getEntry(l):Jt.getEntry(l)}catch(u){return Jt.setError(l,u)??Jt.getEntry(l)}},ensureChecks:(n,r,o,i)=>{const l=Mo(r,o);return ir.ensure(l,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const l=Mo(r,o);return ir.refresh(l,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,l)=>{const c=jn(r,o),d=br(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(x=>({actingActions:{...x.actingActions,[c]:!0},actionErrorByDetail:{...x.actionErrorByDetail,[c]:null}}));const u=Pe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,p=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;p&&u&&await Pe.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullAction(n,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),await t().refreshChecks(n,r,o,l).catch(()=>null),e(x=>({actingActions:{...x.actingActions,[c]:!1}})),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return u&&await Pe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(m=>({actingActions:{...m.actingActions,[c]:!1},actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},updateTitleBody:async(n,r,o,i,l)=>{const c=jn(r,o),d=br(r,o),u=Pe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,p=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;p&&u&&await Pe.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullUpdate(n,r,o,i),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return u&&await Pe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},addComment:async(n,r,o,i,l)=>{const c=jn(r,o),d=Zo(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},p=Pe.resources.comments.getEntry(d)?.data??null;if(p){const x={comments:[...p.comments,f],nextCursor:p.nextCursor,fetchedAt:p.fetchedAt};await Pe.resources.comments.refresh(d,async()=>x).catch(()=>null)}try{return await l.pullComment(n,r,o,u),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshComments(n,r,o,l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return p?await Pe.resources.comments.refresh(d,async()=>p).catch(()=>null):Pe.resources.comments.remove(d),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},submitReview:async(n,r,o,i,l)=>{const c=jn(r,o);try{return await l.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(d){const u=Pe.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(n,r,o,i,l,c)=>{const d=jn(r,o);try{return await c.pullThread(n,r,o,i,l),await Ns(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Pe.toStoreError(u);return e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[d]:f}})),{ok:!1,error:f}}},checkout:async(n,r,o,i,l)=>{try{const c=await l.pullCheckout(n,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Pe.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await Ns(r,{directory:n.directory,repo:n.repo,kind:"pulls"}),t().dropRemoteForRepo(n.repo),await t().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Pe.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(l){return{ok:!1,error:Pe.toStoreError(l)}}},setMergeMethod:(n,r)=>{Ap(n,r)},notifyAgentTurnComplete:n=>{const r=cs((n||"").trim());if(!r)return;const o=es.getState();for(const l of Object.keys(o.results)){const[,c]=l.split(`
|
|
19
19
|
`);if(c!==r)continue;const[,,d]=l.split(`
|
|
20
|
-
`);d&&mt(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-C2ISrmRR.js").then(f=>f.cI);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"&&(Pe.markCollectionsStale(i.repo),mt(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-C2ISrmRR.js").then(c=>c.cI);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:l})=>{const c=l()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Pe.resetCore(),Jt.reset(),ir.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(Un(()=>{bs.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Ty=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return mt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-CHnpTOtc.js").then(l=>l.el);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const l=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!n){t=d,n=!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&&(bs.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},Fy=e=>Pe.getLocalIndex(e),Ly=(e,t)=>Pe.getLocalIndex(e).find(n=>n.number===t)??null,Oy=(e,t)=>mn(Pe.resources.collections,e?Vl(e,t):null),By=(e,t)=>mn(Pe.resources.remote,e?Ql(e,t):null),_y=(e,t)=>mn(Pe.resources.details,e!=null&&t!=null?br(e,t):null),Uy=(e,t)=>mn(Pe.resources.comments,e!=null&&t!=null?Zo(e,t):null),zy=(e,t)=>mn(Jt,e!=null&&t!=null?Po(e,t):null),$y=(e,t)=>mn(ir,e!=null&&t!=null?Mo(e,t):null),Ky=(e,t)=>bs(n=>!e||!t?Do:n.filtersByScope[Ro(e,t)]??Do),Wy=e=>bs(t=>e?t.selectionByDirectory[cs(e)]??Xi:Xi),Xl=(e,t,n)=>{bs.getState().selectPullRequest(e,t,n);const r=cs(e);mt(async()=>{const{useUIStore:o}=await import("./index-C2ISrmRR.js").then(i=>i.cL);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),mt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-CHnpTOtc.js").then(i=>i.en);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(()=>{})},Ip=({directory:e,number:t,color:n})=>{const r=$a(e);return!e||!r?s.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:n?{color:n}:void 0,children:["#",t]}):s.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Xl(e,r,t)},className:"ml-auto flex-shrink-0 rounded text-[0.72rem] font-medium leading-none hover:bg-interactive-hover",style:n?{color:n}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function Ep({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:x,allGroupSessions:y,projectId:m,activeProjectId:h,setActiveProjectIdOnly:b,setActiveMainTab:g,mobileVariant:S,setSessionSwitcherOpen:w,openNewSessionDraft:E}){return s.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":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[s.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:e.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",i?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:or(e.label,o)}),f]}):!e.isMain||e.worktree?s.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:or(e.label,o)}),f,u?s.jsx(Ip,{directory:e.directory??null,number:u.number,color:d}):null]}):s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsx("span",{className:"min-w-0 truncate",children:or(e.label,o)}),f]})}),p&&x?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?s.jsx(P,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):s.jsx(P,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:x.label})]}):null]})}),e.isArchivedBucket&&y.length>0?s.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:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),Ms.requestDelete({sessions:y,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${e.label}`,children:s.jsx(P,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?s.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:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),m&&m!==h&&b(m),g("chat"),S&&w(!1),E({selectedProjectId:m,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Xn=(e,t)=>t?e.sessions.some(n=>ls(n,t)):!1,Rp=(e,t,n)=>e.sessions.some(r=>Bl(r,r,t,n,e.directory,e.directory)),Dp=(e,t,n)=>{const r=o=>{const i=o.session.id;return t.get(i)!==n.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},ta=(e,t,n)=>{const r=o=>t.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Pp=(e,t,n)=>{const r=e.isArchivedBucket?"archived":"active",o=i=>{const l=`project:${r}:${i.session.id}`;return t.has(l)!==n.has(l)?!0:i.children.some(o)};return e.sessions.some(o)},Mp=(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&&Rp(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Pp(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Dp(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Xn(e.group,e.editingId)||Xn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Xn(e.group,e.editingId)||Xn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=gr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=gr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&ta(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&ta(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&&e.scrollContainerRef===t.scrollContainerRef};function Tp({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,inputActivitySessionIds:c,collectGroupSessions:d}){const u=bt(k=>k.foldersMap),f=e.folderScopeKey??Ee(e.directory??null),p=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=a.useMemo(()=>p.flatMap(({scopeKey:k,directory:j})=>(u[k]??[]).map(v=>({folder:v,scopeKey:k,scopeDirectory:j}))),[p,u]),y=a.useMemo(()=>{const k=new Map,j=v=>{v.forEach(N=>{k.set(N.session.id,N),N.children.length>0&&j(N.children)})};return j(t),k},[t]),m=a.useMemo(()=>x.map(({folder:k,scopeKey:j,scopeDirectory:v})=>{const N=Zm(k.sessionIds,y).sort(o);return{folder:k,scopeKey:j,scopeDirectory:v,nodes:N}}),[x,y,o]),h=a.useMemo(()=>{const k=new Map(m.map(M=>[M.folder.id,M])),j=new Map;for(const{folder:M}of m){if(!M.parentId)continue;const L=j.get(M.parentId);L?L.push(M.id):j.set(M.parentId,[M.id])}const v=new Map,N=M=>{const L=v.get(M);if(L!==void 0)return L;const K=k.get(M);if(!K)return v.set(M,!1),!1;const z=j.get(M)??[];if(e.isArchivedBucket&&K.nodes.length===0){const R=z.some(D=>N(D));return v.set(M,R),R}if(!n||K.folder.name.toLowerCase().includes(r)||K.nodes.length>0)return v.set(M,!0),!0;const O=z.some(R=>N(R));return v.set(M,O),O};return m.filter(({folder:M})=>N(M.id))},[m,e.isArchivedBucket,n,r]),b=a.useMemo(()=>new Set(h.flatMap(k=>k.folder.sessionIds)),[h]),g=a.useMemo(()=>t.filter(k=>!b.has(k.session.id)),[t,b]),S=a.useMemo(()=>h.filter(({folder:k})=>!k.parentId),[h]),w=a.useMemo(()=>{const k=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const v=k.get(j.folder.parentId)??[];v.push(j),k.set(j.folder.parentId,v)}),k},[h]),E=a.useMemo(()=>{const k=new Map(h.map(N=>[N.folder.id,N])),j=new Map,v=(N,M)=>{const L=j.get(N);if(L!==void 0)return L;if(M.has(N))return null;M.add(N);const K=k.get(N);let z=K?Kl(K.nodes,i,l,c):null;for(const $ of w.get(N)??[])if(z=Jo(z,v($.folder.id,M)),z==="input")break;return j.set(N,z),z};return h.forEach(({folder:N})=>v(N.id,new Set)),j},[i,h,w,c,l]),A=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const k=new Map,j=new Map;for(const{folder:N}of h){if(!N.parentId)continue;const M=j.get(N.parentId)??[];M.push(N.id),j.set(N.parentId,M)}const v=(N,M)=>{if(M.has(N))return[];M.add(N);const L=h.find(({folder:$})=>$.id===N),K=L?d(L.nodes):[],z=j.get(N)??[];for(const $ of z)K.push(...v($,M));return K};for(const{folder:N}of h)k.set(N.id,v(N.id,new Set));return k},[h,d,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:p,allFoldersForGroup:h,rootFolders:S,ungroupedSessions:g,folderActivityStateById:E,folderSessionsForDeleteById:A}}function Fp(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:x,renameFolder:y,deleteFolder:m,showDeletionDialog:h,setDeleteFolderConfirm:b,renderSessionNode:g,showMoreGroupSessions:S,resetGroupSessionLimit:w,mobileVariant:E,alwaysShowActions:A,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:v,setSessionSwitcherOpen:N,openNewSessionDraft:M,addSessionToFolder:L,createFolderAndStartRename:K,renamingFolderId:z,renameFolderDraft:$,setRenameFolderDraft:O,setRenamingFolderId:R,pinnedSessionIds:D,expandedParents:I,sessionOrderIndex:T,editingId:W,openSidebarMenuKey:Z,activeActivitySessionIds:F,unreadActivitySessionIds:me,onToggleCollapsedGroup:q,dragHandleProps:Ae,compactBodyPadding:Ie=!1,scrollContainerRef:G}=e,U=a.useCallback((Ce,Ue)=>{const ge=T.get(Ce.session.id),Oe=T.get(Ue.session.id);if(ge!==void 0||Oe!==void 0){if(ge===void 0)return 1;if(Oe===void 0)return-1;if(ge!==Oe)return ge-Oe}return gu(Ce.session,Ue.session,D,Ka)},[D,T]),Y=i?c.get(t):null,X=i?!1:u.has(n),se=!t.isMain&&!t.isArchivedBucket&&!o?Ee(t.directory??null):null,we=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,pe=a.useMemo(()=>se&&we?_n(se,we):null,[se,we]),V=Ul(pe);zl(se,we);const Q=V?`var(--pr-${V.visualState})`:void 0,ie=f?10:5,ke=Math.max(ie,d??ie),Se=i?Y?.groupMatches===!0:!1,He=i,H=a.useMemo(()=>[...He?Y?.filteredNodes??[]:t.sessions].sort(U),[U,t.sessions,Y?.filteredNodes,He]),de=a.useCallback(Ce=>{const Ue=[],ge=Oe=>{Oe.forEach(Ge=>{Ue.push(Ge.session),Ge.children.length>0&&ge(Ge.children)})};return ge(Ce),Ue},[]),ne=bu(),ue=a.useMemo(()=>new Set(ne.map(Ce=>Ce.sessionId)),[ne]),{folderScopeKey:ve,folderScopes:Le,allFoldersForGroup:be,rootFolders:te,ungroupedSessions:xe,folderActivityStateById:fe,folderSessionsForDeleteById:je}=Tp({group:t,sourceGroupNodes:H,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:U,activeActivitySessionIds:F,unreadActivitySessionIds:me,inputActivitySessionIds:ue,collectGroupSessions:de}),Ye="project",_e=a.useMemo(()=>{const Ce=new Set;return Gi(H,W,Ce),be.forEach(({nodes:Ue})=>{Gi(Ue,W,Ce)}),Ce},[H,be,W]),De=a.useMemo(()=>{if(!Z)return null;const Ce=gr(H,Z,Ye,!!t.isArchivedBucket);if(Ce)return Ce;for(const{nodes:Ue}of be){const ge=gr(Ue,Z,Ye,!!t.isArchivedBucket);if(ge)return ge}return null},[Z,H,be,t.isArchivedBucket]),Ve=a.useCallback(Ce=>{const Ue=new WeakMap,ge=Oe=>{Ue.set(Oe,Ao(Oe));for(const Ge of Oe.children)ge(Ge)};return Ce.forEach(ge),Ue},[]),ae=a.useMemo(()=>Ve(H),[Ve,H]),Fe=a.useMemo(()=>{const Ce=new WeakMap;return be.forEach(({nodes:Ue})=>{Ue.forEach(ge=>Ce.set(ge,Ao(ge)))}),Ce},[be]),tt=a.useCallback(Ce=>ae.get(Ce)??Fe.get(Ce)??"",[ae,Fe]),xt=a.useCallback(Ce=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce)}),[_e,De,tt]),Qe=xe.length,pt=t.isArchivedBucket||i?xe:xe.slice(0,ke),Xe=Qe-pt.length,Ss=!t.isArchivedBucket&&!i&&Qe>ie&&Xe===0,St=t.isArchivedBucket===!0&&!i&&pt.length>=ip,st=t.isArchivedBucket?"archived":"active",Et=St&&pt.some(Ce=>{if(Ce.children.length===0)return!1;const Ue=`project:${st}:${Ce.session.id}`;return I.has(Ue)}),Lt=a.useMemo(()=>de(H),[de,H]);if(i&&!Se&&te.length===0&&xe.length===0)return null;const Yt=!t.isMain&&!!t.branch,jt=t.branch&&Ff(t.branch,t.label)?{label:t.branch,color:null}:null,Ot=X?Kl(H,F,me,ue):null,yt=Ot?s.jsx(Ll,{state:Ot,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,rt=(Ce,Ue)=>{const{folder:ge,scopeKey:Oe,scopeDirectory:Ge,nodes:it}=Ce,kt=je.get(ge.id)??[],ot=i?!1:p.has(ge.id);return s.jsx(Jm,{folderId:ge.id,children:(Bt,ns)=>s.jsx(Vm,{folder:ge,displayName:Ue,sessions:it,isCollapsed:ot,collapsedActivityState:ot?fe.get(ge.id)??null:null,onToggle:()=>x(ge.id),onRename:Ze=>{y(Oe,ge.id,Ze)},onDelete:()=>{if(t.isArchivedBucket){Ms.requestDelete({sessions:kt,mode:"session"});return}if(!h){m(Oe,ge.id);return}const Ze=be.filter(({folder:Dt})=>Dt.parentId===ge.id).length,Rt=it.length;b({scopeKey:Oe,folderId:ge.id,folderName:ge.name,subFolderCount:Ze,sessionCount:Rt})},renderSessionNode:g,getRenderExtras:tt?Ze=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ze),childRenderExtrasFor:xt}):void 0,groupDirectory:Ge??t.directory,projectId:r,mobileVariant:E,alwaysShowActions:A,isRenaming:z===ge.id,renameDraft:z===ge.id?$:void 0,onRenameDraftChange:Ze=>O(Ze),onRenameSave:()=>{const Ze=$.trim();Ze&&y(Oe,ge.id,Ze),R(null),O("")},onRenameCancel:()=>{R(null),O("")},droppableRef:Bt,isDropTarget:ns,depth:0,onNewSession:()=>{r&&r!==k&&j(r),v("chat"),E&&N(!1),M({selectedProjectId:r,directoryOverride:Ge??t.directory,targetFolderId:ge.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},ge.id)},dt=()=>{const Ce=new Map;for(const Oe of be){const Ge=Oe.folder.parentId;if(!Ge)continue;const it=Ce.get(Ge);it?it.push(Oe):Ce.set(Ge,[Oe])}const Ue=[],ge=(Oe,Ge)=>{const it=Ge?`${Ge} / ${Oe.folder.name}`:Oe.folder.name;Ue.push(rt(Oe,it)),!(!i&&p.has(Oe.folder.id))&&(Ce.get(Oe.folder.id)??[]).forEach(ot=>ge(ot,it))};return te.forEach(Oe=>ge(Oe,"")),Ue},Vt=A?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",us=s.jsxs(Xm,{scopeKey:Le[0]?.scopeKey??ve,hasFolders:be.length>0,onSessionDroppedOnFolder:(Ce,Ue)=>{const ge=be.find(({folder:Ge})=>Ge.id===Ue);if(!ge)return;const Oe=bt.getState();for(const{scopeKey:Ge}of Le)Ge!==ge.scopeKey&&Oe.getSessionFolderId(Ge,Ce)&&Oe.removeSessionFromFolder(Ge,Ce);L(ge.scopeKey,Ue,Ce)},children:[dt(),t.isArchivedBucket?s.jsx(lp,{visibleSessions:pt,shouldVirtualize:St,hasExpandedParent:Et,scrollContainerRef:G,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:Ce=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce),childRenderExtrasFor:xt})}):pt.map(Ce=>s.jsx(a.Fragment,{children:g(Ce,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce),childRenderExtrasFor:xt})},Ce.session.id)),Qe===0&&be.length===0?t.isArchivedBucket?s.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):s.jsx(Zt,{icon:"chat-new",onClick:()=>{M({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Xe>0?s.jsx(Zt,{icon:"arrow-down-s",onClick:()=>S(n,pt.length),children:Xe===1?"Show 1 more session":`Show ${Xe} more sessions`}):null,Ss?s.jsx(Zt,{icon:"arrow-up-s",onClick:()=>w(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:us})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(Ep,{group:t,groupKey:n,isCollapsed:X,onToggleCollapsedGroup:q,normalizedSessionSearchQuery:l,alwaysShowActions:A,groupHeaderRightPadding:Vt,dragHandleProps:Ae,groupPrColor:Q,groupPrSummary:V,groupActivityIndicator:yt,showBranchSubtitle:Yt,statusLine:jt,allGroupSessions:Lt,projectId:r,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:v,mobileVariant:E,setSessionSwitcherOpen:N,openNewSessionDraft:M}),X?null:s.jsx("div",{className:"oc-group-body",children:us})]})}const Lp=a.memo(Fp,Mp);function Op(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:m,hasSessionSearchQuery:h,searchMatchCount:b,selectionModeEnabled:g,onToggleSelectionMode:S,mobileVariant:w=!1}=e;if(t)return null;const E=_(u,"text-muted-foreground hover:text-foreground",!w&&"hover:bg-transparent");return s.jsx("div",{className:_("select-none flex-shrink-0",w?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",w?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",w?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[s.jsxs("div",{className:_("flex min-w-0 items-center",w?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":w?"true":void 0,children:[o?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:E,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!w&&i?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:E,"aria-label":l?`Servers: ${l}`:"Servers",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Servers"})})]}):null,c?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:E,"aria-label":"Update",children:s.jsx(P,{name:"download",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,w?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:E,"aria-label":"Add project",children:s.jsx(P,{name:"folder-add",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),w?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:E,"aria-label":"Archive",children:s.jsx(P,{name:"archive",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",w?"gap-1":"gap-1.5"),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(A=>!A),className:E,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:_(E,g&&"bg-interactive-hover text-primary"),"aria-label":g?"Exit selection":"Select sessions","aria-pressed":g,children:s.jsx(P,{name:"checkbox-multiple",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:_(w?"pb-2":"pb-1"),children:[s.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:h?s.jsx("span",{children:b===1?`${b} match`:`${b} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:x,value:y,onChange:A=>m(A.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:A=>{A.key==="Escape"&&(A.stopPropagation(),h?m(""):p(!1))}}),y.length>0?s.jsx("button",{type:"button",onClick:()=>m(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:s.jsx(P,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const Kr="0.75rem";function Bp(e){const t=ce(o=>o.toggleSidebar),n=ce(o=>o.shortcutOverrides),r=Ho(dr("toggle_sidebar",n));return s.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${Kr})`}}),s.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, ${Kr})))`}}),s.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[s.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(${Lf} - max(var(--oc-titlebar-left-inset, ${Kr}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(nr,"text-current")}),s.jsx("span",{className:dl,children:"New session"})]}),e.showSidebarToggle?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.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:s.jsx(P,{name:"layout-left",className:"size-4"})})}),s.jsx(We,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Ar({...e}){return s.jsx(Ca,{...e})}function Nr({...e}){return s.jsx(Aa,{...e})}function Ir({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Na,{children:s.jsx(Ia,{className:_("app-region-no-drag z-50",t),children:s.jsx(Ea,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Wa,e),...o,children:n})})})}function Ps({className:e,...t}){return s.jsx(Ra,{className:_(Ga,e),...t})}function Zl({className:e,...t}){return s.jsx(Da,{className:_(Ha,e),...t})}const ec=500,_p=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:l=!1})=>{const[c,d]=a.useState(!1),u=a.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),p=a.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);a.useEffect(()=>()=>p(),[p]);const x=a.useCallback(()=>{p(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},ec)},[p]);return s.jsxs(Ar,{open:c,onOpenChange:d,children:[s.jsxs(Nr,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_(yr(l,n),"pl-6"),"aria-pressed":n,title:t.path}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx(P,{name:"git-branch",className:_(Fs(l),"text-muted-foreground")}),t.branch?s.jsx(qa,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):s.jsx("span",{className:an(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Ir,{className:"min-w-[160px]",children:s.jsxs(Ps,{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:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},yr=(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"),Up=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:x,setNodeRef:y,transform:m,transition:h,isDragging:b}=$o({id:e.id,disabled:!c}),[g,S]=a.useState(!1),w=a.useRef(null),E=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]);a.useEffect(()=>()=>E(),[E]);const A=a.useCallback(()=>{E(),w.current=window.setTimeout(()=>{w.current=null,S(!0)},ec)},[E]);return s.jsx("div",{ref:y,style:{transform:Ko.Translate.toString(m),transition:h},className:_(b&&"opacity-60"),children:s.jsxs(Ar,{open:g,onOpenChange:S,children:[s.jsxs(Nr,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:A,onTouchMove:E,onTouchEnd:E,onTouchCancel:E,style:{touchAction:"manipulation"},className:yr(p,n),"aria-pressed":n}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.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?x:{},children:s.jsx(Go,{directory:e.normalizedPath,label:t,className:Fs(p)})}),s.jsx("span",{className:an(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?s.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:s.jsx(P,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(P,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(Ir,{className:"min-w-[160px]",children:[s.jsxs(Ps,{onClick:()=>u(e.id),children:[s.jsx(P,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(Zl,{}),s.jsxs(Ps,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},zp=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:x,homeDirectory:y,className:m,mobileVariant:h=!1})=>{const b=t===null,g=ct(A=>A.reorderProjects),S=e.length>1,w=_o(Fn(Fa,{activationConstraint:{distance:8}}),Fn(Ta,{activationConstraint:{delay:200,tolerance:6}})),E=a.useCallback(A=>{const{active:k,over:j}=A;if(!j||k.id===j.id)return;const v=ct.getState().projects,N=v.findIndex(L=>L.id===k.id),M=v.findIndex(L=>L.id===j.id);N<0||M<0||g(N,M)},[g]);return s.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:yr(h,b),"aria-pressed":b,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(P,{name:"chat-history",className:Fs(h)}),s.jsx("span",{className:an(h),children:"All sessions"})]})}),s.jsx(Uo,{sensors:w,collisionDetection:zo,onDragEnd:E,children:s.jsx(Pa,{items:e.map(A=>A.id),strategy:Ma,children:e.map(A=>{const k=t===A.id,j=k&&!n,v=r.get(A.normalizedPath)??[],N=qo(A.label?.trim()||On(A.normalizedPath,y)||A.normalizedPath),M=x?.get(A.id),L=Ee(A.normalizedPath)?.toLowerCase()??"",K=L?M?.has(L)??!1:!1,z=(M?.size??0)>0,$=p?.(A.id)??!1,O=x?k?K:z:$;return s.jsxs(a.Fragment,{children:[s.jsx(Up,{project:A,label:N,isSelected:j,hasActive:O,hasWorktrees:v.length>0,worktreeError:o.get(A.normalizedPath),isExpanded:k,canDrag:S,onSelect:()=>i(A.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),k?v.map(R=>{const D=n===R.path,I=Ee(R.path)?.toLowerCase()??"",T=I?M?.has(I)??!1:!1,W=x?T:!1;return s.jsx(_p,{projectId:A.id,worktree:R,isSelected:D,hasActive:W,onSelect:()=>l?.(A.id,R.path),onClose:c,mobileVariant:h},R.path)}):null]},A.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:yr(h,!1),children:[s.jsx(P,{name:"add",className:Fs(h)}),s.jsx("span",{className:an(h),children:"Add folder"})]})]})},Wr="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 $p({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?s.jsxs(s.Fragment,{children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:Wr,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:Wr,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Wr,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ne,{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 tc=({projectLabel:e,projectPath:t=null,mobileVariant:n=!1})=>{const r=Fs(n),o=an(n);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?s.jsx(Go,{directory:t,label:e,className:r}):s.jsx(P,{name:"folder",className:_(r,"text-muted-foreground/80")})}),s.jsx("span",{className:_(o,"text-foreground"),children:e})]})},sc=({isCollapsed:e,mobileVariant:t=!1,className:n})=>s.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",n),children:s.jsx(P,{name:e?"arrow-right-s":"arrow-down-s",className:Fs(t)})}),Kp=({id:e,disabled:t=!1,projectLabel:n,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:l,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:p,onRenameStart:x,onClose:y,children:m,showCreateButtons:h=!0,hideHeader:b=!1,openSidebarMenuKey:g,setOpenSidebarMenuKey:S,statusIndicator:w=null})=>{const{listeners:E,setNodeRef:A,transform:k,transition:j,isDragging:v}=$o({id:e,disabled:t}),N=a.useRef(!1),M=`project:${e}`,L=g===M,[K,z]=a.useState(!1),$=u&&!i,O=a.useCallback(F=>{F&&z(!1),S(F?M:null)},[M,S]),R=F=>s.jsxs(s.Fragment,{children:[h&&!l&&p&&s.jsxs(F,{onClick:p,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(F,{onClick:x,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(F,{onClick:y,className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),D=a.useCallback(F=>{F.stopPropagation()},[]),I=a.useCallback(F=>{F.stopPropagation()},[]),T=a.useCallback(F=>{F.stopPropagation()},[]),W=a.useCallback(F=>{(F.button===2||F.button===0&&F.ctrlKey)&&(N.current=!0)},[]),Z=a.useCallback(F=>{if(F.currentTarget.blur(),N.current){N.current=!1;return}f()},[f]);return s.jsxs("div",{ref:A,style:{transform:Ko.Translate.toString(k),transition:j},className:_("relative",v&&"opacity-60"),children:[b?null:s.jsxs(Ar,{open:K,onOpenChange:z,children:[s.jsxs(Nr,{render:s.jsx("div",{className:_("text-left group/project select-none",$&&"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":$?"true":void 0,onContextMenu:F=>{l||v||(F.preventDefault(),z(!0))}}),children:[s.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:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:W,onClick:Z,...E,className:_(Cr,"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:[s.jsx(tc,{id:e,projectLabel:n,projectPath:r,mobileVariant:c}),w?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:w}):null,s.jsx(sc,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",d?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(We,{side:"right",sideOffset:8,children:o})]}),s.jsx("div",{className:"absolute right-[calc(3.25rem*var(--padding-scale,1))] top-1/2 z-10 -translate-y-1/2",children:l?null:s.jsxs(Gt,{open:L,onOpenChange:O,children:[s.jsx(Ht,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",L?"opacity-100 pointer-events-auto":d?"opacity-100":"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"),"aria-label":"Folder menu",onPointerDown:I,onMouseDown:T,onClick:D,children:s.jsx(P,{name:"more-2",className:"size-4"})})}),s.jsx(qt,{align:"end",className:"min-w-[180px]",children:R(ht)})]})}),h&&!l&&p?s.jsx("div",{className:"absolute right-7 top-1/2 z-10 -translate-y-1/2",children:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),p()},className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"opacity-100":"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"),"aria-label":"New session",children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null]}),$?s.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]}),s.jsx(Ir,{className:"min-w-[180px]",children:R(Ps)})]}),m]})},Wp=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:l,transition:c,isDragging:d}=$o({id:e,disabled:t}),u=a.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:Ko.Transform.toString(l),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};a.memo(Wp);const sa="pt-0.5 pb-1",Gp=({sections:e,homeSection:t,homeDirectory:n,collapsedProjects:r,toggleProject:o,hasSessionSearchQuery:i,activeProjectId:l,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,isInlineEditing:f,stickyFolderHeaders:p,renderGroupSessions:x,renderSessionNode:y,getOrderedGroups:m,renderProjectStatusIndicator:h,scrollContainerRef:b,setActiveProjectIdOnly:g,setActiveMainTab:S,setSessionSwitcherOpen:w,openNewSessionDraft:E,openProjectEditDialog:A,removeProject:k,reorderProjects:j,openSidebarMenuKey:v,setOpenSidebarMenuKey:N,onOpenDirectoryDialog:M,emptyState:L,searchEmptyState:K})=>{const z=_o(Fn(Fa,{activationConstraint:{distance:8}}),Fn(Ta,{activationConstraint:{delay:200,tolerance:6}})),$=e.length>1&&!i&&!f,O=a.useCallback(F=>{if(f||i)return;const{active:me,over:q}=F;if(!q||me.id===q.id)return;const Ae=ct.getState().projects,Ie=Ae.findIndex(U=>U.id===me.id),G=Ae.findIndex(U=>U.id===q.id);Ie<0||G<0||Ie===G||j(Ie,G)},[f,i,j]),[R,D]=a.useState(5);a.useEffect(()=>{D(5)},[i]);const I=a.useMemo(()=>t?t.groups.filter(F=>!F.isArchivedBucket).flatMap(F=>F.sessions):[],[t]),T=i?I:I.slice(0,R),W=I.length-T.length,Z=i?!1:r.has("__home__");return e.length===0&&!t?i?K:L:s.jsxs("div",{className:"space-y-2",children:[s.jsx(Uo,{sensors:z,collisionDetection:zo,onDragEnd:O,children:s.jsx(Pa,{items:e.map(F=>F.project.id),strategy:Ma,children:e.map(F=>{const me=F.project,q=me.id,Ae=ul(me,n),Ie=uo(me.normalizedPath,n),G=i?!1:r.has(q),U=G?[]:m(q,F.groups),Y=G?null:U.find(se=>se.isMain)??null,X=G?[]:Y?U.filter(se=>se.id!==Y.id):U;return s.jsx(Kp,{id:q,disabled:!$,projectLabel:Ae,projectPath:me.normalizedPath,projectDescription:Ie,isCollapsed:G,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,stickyHeader:p,statusIndicator:G?h?.(q,F.groups):null,onToggle:()=>o(q),onNewSession:()=>{q!==l&&g(q),S("chat"),d&&w(!1),E({selectedProjectId:q,directoryOverride:me.normalizedPath})},onRenameStart:()=>A(q),onClose:()=>k(q),openSidebarMenuKey:v,setOpenSidebarMenuKey:N,children:G?null:s.jsxs("div",{className:sa,children:[Y?x(Y,`${q}:${Y.id}`,q,!0,null,void 0,b):null,X.map(se=>{const we=`${q}:${se.id}`,pe=U.length===1;return s.jsx(a.Fragment,{children:x(se,we,q,pe,null,void 0,b)},se.id)})]})},q)})})}),t?s.jsxs("div",{children:[s.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:s.jsxs("button",{type:"button","aria-expanded":!Z,style:{touchAction:"manipulation"},onClick:()=>o("__home__"),className:`${Cr} 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:[s.jsx(tc,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),s.jsx(sc,{isCollapsed:Z,mobileVariant:d})]})}),Z?null:s.jsxs("div",{className:sa,children:[T.map(F=>s.jsx(a.Fragment,{children:y?.(F,0,F.session.directory??"~","__home__",!1,{globalSession:!0},"project")},F.session.id)),!i&&W>0?s.jsx(Zt,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>D(F=>F+7),children:W===1?"Show 1 more session":`Show ${W} more sessions`}):null,!i&&R>5&&I.length>5?s.jsx(Zt,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>D(5),children:"Show fewer sessions"}):null]})]}):null,!c&&M?s.jsx(Zt,{icon:"add",mobileVariant:d,onClick:M,children:"Add folder"}):null]})},Hp=a.memo(Gp);function qp(e){Wt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",n=t==="timeline",r=a.useRef(new Map),o=a.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(b,g)=>{const S=r.current,w=S.get(b);if(w&&w.groups===g)return w.ordered;const E=e.getOrderedGroups(b,g);if(S.set(b,{groups:g,ordered:E}),S.size>256){const A=S.keys().next().value;A!==void 0&&S.delete(A)}return E},l=a.useRef(null),c=!!(e.isAllFoldersView||n),d=a.useMemo(()=>{if(!c)return[];const b=[],g=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const S of g){const w=ul(S.project,e.homeDirectory);for(const E of S.groups)if(!E.isArchivedBucket)for(const A of E.sessions){const k=!!e.pinnedSessionIds?.has(A.session.id),j=A.session.time?.updated||A.session.time?.created||0;b.push({node:A,project:S.project,projectLabel:w,isPinned:k,timestamp:j,globalSession:S===e.allFoldersOnlySection})}}return b.sort((S,w)=>S.isPinned!==w.isPinned?S.isPinned?-1:1:w.timestamp-S.timestamp),b},[e.allFoldersOnlySection,c,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[u,f]=a.useState(30);a.useEffect(()=>{f(30)},[e.hasSessionSearchQuery]);const p=a.useMemo(()=>d.slice(0,u),[d,u]),x=a.useMemo(()=>e.timelineBoundaries??Co(Date.now(),1),[e.timelineBoundaries]),y=a.useMemo(()=>n?xm(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:x}):[],[n,p,x]);if(e.sharedSessionsOnly)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const m=(e.isAllFoldersView||t==="timeline"||t==="folder")&&!!e.allFoldersOnlySection;if(e.projectSections.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const h=()=>{const b=d.length-p.length;return s.jsxs(s.Fragment,{children:[b>0?s.jsx(Zt,{icon:"arrow-down-s",onClick:()=>f(g=>g+30),children:b===1?"Show 1 more session":`Show ${b} more sessions`}):null,u>30&&d.length>30?s.jsx(Zt,{icon:"arrow-up-s",onClick:()=>f(30),children:"Show fewer sessions"}):null]})};return s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(Is,{ref:l,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const b=e.sectionsForRender.find(E=>E.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!b)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const g=b.groups.find(E=>E.isMain&&E.sessions.length>0)??b.groups.find(E=>E.sessions.length>0)??b.groups.find(E=>E.isMain)??b.groups[0];if(!g)return s.jsx(Zt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:b.project.id,directoryOverride:b.project.normalizedPath}),children:"New session"});const S=b.groups.find(E=>E.isArchivedBucket);return[g,...S&&S.id!==g.id?[S]:[]].map(E=>{const A=`${b.project.id}:${E.id}`,k=E.id===g.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(E,A,b.project.id,k,null,!0,l)},A)})})()}):t==="folder"?s.jsx(Qo.Provider,{value:"tree",children:s.jsx(Hp,{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,scrollContainerRef:l,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?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[y.map((b,g)=>{const S=pm[b.id];return s.jsxs("section",{"aria-label":S,"data-timeline-bucket":b.id,children:[s.jsx("div",{role:"heading","aria-level":3,className:_("select-none px-3 pb-1 text-xs leading-4 font-medium text-muted-foreground",g===0?"pt-1":"pt-3"),children:S}),b.items.map(({node:w,project:E,projectLabel:A,globalSession:k})=>{const j=w.session.directory??E.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(w,0,j,E.id,!1,{projectLabel:A,showFolderLabel:!0,globalSession:k},"project")},w.session.id)})]},b.id)}),h()]})}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[p.map(({node:b,project:g,projectLabel:S,globalSession:w})=>{const E=b.session.directory??g.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(b,0,E,g.id,!1,{projectLabel:S,showFolderLabel:!0,globalSession:w},"project")},b.session.id)}),h()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const g=b.project.id,S=i(g,b.groups),w=S.find(A=>A.isMain)??null,E=w?S.filter(A=>A.id!==w.id):S;return s.jsxs("div",{children:[w?e.renderGroupSessions(w,`${g}:${w.id}`,g,!0,null,void 0,l):null,E.map(A=>{const k=`${g}:${A.id}`,j=S.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(A,k,g,j,null,void 0,l)},A.id)})]},g)})})]})})})}const Yp=a.memo(qp);let To=!1;const Fo=new Set;let na=!1;function Vp(){for(const e of Fo)e()}function ei(e){To!==e&&(To=e,Vp())}function Qp(e){e.key==="Shift"&&ei(!0)}function Jp(e){e.key==="Shift"&&ei(!1)}function Xp(){ei(!1)}function Zp(){na||typeof window>"u"||(na=!0,window.addEventListener("keydown",Qp),window.addEventListener("keyup",Jp),window.addEventListener("blur",Xp))}function eg(e){return Zp(),Fo.add(e),()=>{Fo.delete(e)}}function tg(){return To}function sg(){return!1}function ng(){return Re.useSyncExternalStore(eg,tg,sg)}const rg=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:d}){const u=ng(),f=u?n:t,p=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.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:l,onClick:p,onKeyDown:x=>x.stopPropagation(),children:s.jsx(P,{name:u?"delete-bin":"archive",className:o})})}),s.jsx(We,{side:"left",sideOffset:8,children:f})]})}),og=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(ts,{open:t,onOpenChange:n,children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:"Export Markdown"}),s.jsx(vs,{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?`})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.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"]}),s.jsxs(Ls,{children:[s.jsx(Ne,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ne,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function ig(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:x,handleDeleteSession:y,handleRestoreSession:m}=e,{Item:h,Separator:b}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(h,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(h,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),s.jsxs(h,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[i?s.jsx(P,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(P,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),s.jsxs(h,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(h,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,s.jsx(b,{}),l?null:s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l}),children:[s.jsx(P,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>m(n),children:[s.jsx(P,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,s.jsxs(h,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l,hardDelete:!0}),children:[s.jsx(P,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function ag(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Na,{children:s.jsx(Ia,{className:"app-region-no-drag z-50",children:s.jsx(Ea,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Wa,"min-w-[180px]"),children:ig(e,{Item:({className:r,...o})=>s.jsx(Ra,{className:_(Ga,r),...o}),Separator:({className:r,...o})=>s.jsx(Da,{className:_(Ha,r),...o})})})})})}const Gr=new WeakMap,lg=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Gr.get(n)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,l=null;const c=()=>{i=!0,l!==null&&window.cancelAnimationFrame(l),l=null,Gr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!n.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Wt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Gr.set(n,c),l=window.requestAnimationFrame(d)};function cg(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),l=String(t.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${i}:${l}`}function dg(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&n?`${t}/${n}`:n||t}function ug(e){const t=e.info.role==="user"?"User":"Assistant",n=cg(e.info.time?.created),r=dg(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
20
|
+
`);d&&mt(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-C2ISrmRR.js").then(f=>f.cI);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"&&(Pe.markCollectionsStale(i.repo),mt(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-C2ISrmRR.js").then(c=>c.cI);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:l})=>{const c=l()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Pe.resetCore(),Jt.reset(),ir.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(Un(()=>{bs.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Ty=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return mt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-D_gtiA95.js").then(l=>l.el);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const l=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!n){t=d,n=!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&&(bs.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},Fy=e=>Pe.getLocalIndex(e),Ly=(e,t)=>Pe.getLocalIndex(e).find(n=>n.number===t)??null,Oy=(e,t)=>mn(Pe.resources.collections,e?Vl(e,t):null),By=(e,t)=>mn(Pe.resources.remote,e?Ql(e,t):null),_y=(e,t)=>mn(Pe.resources.details,e!=null&&t!=null?br(e,t):null),Uy=(e,t)=>mn(Pe.resources.comments,e!=null&&t!=null?Zo(e,t):null),zy=(e,t)=>mn(Jt,e!=null&&t!=null?Po(e,t):null),$y=(e,t)=>mn(ir,e!=null&&t!=null?Mo(e,t):null),Ky=(e,t)=>bs(n=>!e||!t?Do:n.filtersByScope[Ro(e,t)]??Do),Wy=e=>bs(t=>e?t.selectionByDirectory[cs(e)]??Xi:Xi),Xl=(e,t,n)=>{bs.getState().selectPullRequest(e,t,n);const r=cs(e);mt(async()=>{const{useUIStore:o}=await import("./index-C2ISrmRR.js").then(i=>i.cL);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),mt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-D_gtiA95.js").then(i=>i.en);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(()=>{})},Ip=({directory:e,number:t,color:n})=>{const r=$a(e);return!e||!r?s.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:n?{color:n}:void 0,children:["#",t]}):s.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Xl(e,r,t)},className:"ml-auto flex-shrink-0 rounded text-[0.72rem] font-medium leading-none hover:bg-interactive-hover",style:n?{color:n}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function Ep({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:x,allGroupSessions:y,projectId:m,activeProjectId:h,setActiveProjectIdOnly:b,setActiveMainTab:g,mobileVariant:S,setSessionSwitcherOpen:w,openNewSessionDraft:E}){return s.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":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[s.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:e.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",i?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:or(e.label,o)}),f]}):!e.isMain||e.worktree?s.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:or(e.label,o)}),f,u?s.jsx(Ip,{directory:e.directory??null,number:u.number,color:d}):null]}):s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsx("span",{className:"min-w-0 truncate",children:or(e.label,o)}),f]})}),p&&x?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?s.jsx(P,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):s.jsx(P,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:x.label})]}):null]})}),e.isArchivedBucket&&y.length>0?s.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:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),Ms.requestDelete({sessions:y,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${e.label}`,children:s.jsx(P,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?s.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:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),m&&m!==h&&b(m),g("chat"),S&&w(!1),E({selectedProjectId:m,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Xn=(e,t)=>t?e.sessions.some(n=>ls(n,t)):!1,Rp=(e,t,n)=>e.sessions.some(r=>Bl(r,r,t,n,e.directory,e.directory)),Dp=(e,t,n)=>{const r=o=>{const i=o.session.id;return t.get(i)!==n.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},ta=(e,t,n)=>{const r=o=>t.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Pp=(e,t,n)=>{const r=e.isArchivedBucket?"archived":"active",o=i=>{const l=`project:${r}:${i.session.id}`;return t.has(l)!==n.has(l)?!0:i.children.some(o)};return e.sessions.some(o)},Mp=(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&&Rp(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Pp(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Dp(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Xn(e.group,e.editingId)||Xn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Xn(e.group,e.editingId)||Xn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=gr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=gr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&ta(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&ta(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&&e.scrollContainerRef===t.scrollContainerRef};function Tp({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,inputActivitySessionIds:c,collectGroupSessions:d}){const u=bt(k=>k.foldersMap),f=e.folderScopeKey??Ee(e.directory??null),p=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=a.useMemo(()=>p.flatMap(({scopeKey:k,directory:j})=>(u[k]??[]).map(v=>({folder:v,scopeKey:k,scopeDirectory:j}))),[p,u]),y=a.useMemo(()=>{const k=new Map,j=v=>{v.forEach(N=>{k.set(N.session.id,N),N.children.length>0&&j(N.children)})};return j(t),k},[t]),m=a.useMemo(()=>x.map(({folder:k,scopeKey:j,scopeDirectory:v})=>{const N=Zm(k.sessionIds,y).sort(o);return{folder:k,scopeKey:j,scopeDirectory:v,nodes:N}}),[x,y,o]),h=a.useMemo(()=>{const k=new Map(m.map(M=>[M.folder.id,M])),j=new Map;for(const{folder:M}of m){if(!M.parentId)continue;const L=j.get(M.parentId);L?L.push(M.id):j.set(M.parentId,[M.id])}const v=new Map,N=M=>{const L=v.get(M);if(L!==void 0)return L;const K=k.get(M);if(!K)return v.set(M,!1),!1;const z=j.get(M)??[];if(e.isArchivedBucket&&K.nodes.length===0){const R=z.some(D=>N(D));return v.set(M,R),R}if(!n||K.folder.name.toLowerCase().includes(r)||K.nodes.length>0)return v.set(M,!0),!0;const O=z.some(R=>N(R));return v.set(M,O),O};return m.filter(({folder:M})=>N(M.id))},[m,e.isArchivedBucket,n,r]),b=a.useMemo(()=>new Set(h.flatMap(k=>k.folder.sessionIds)),[h]),g=a.useMemo(()=>t.filter(k=>!b.has(k.session.id)),[t,b]),S=a.useMemo(()=>h.filter(({folder:k})=>!k.parentId),[h]),w=a.useMemo(()=>{const k=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const v=k.get(j.folder.parentId)??[];v.push(j),k.set(j.folder.parentId,v)}),k},[h]),E=a.useMemo(()=>{const k=new Map(h.map(N=>[N.folder.id,N])),j=new Map,v=(N,M)=>{const L=j.get(N);if(L!==void 0)return L;if(M.has(N))return null;M.add(N);const K=k.get(N);let z=K?Kl(K.nodes,i,l,c):null;for(const $ of w.get(N)??[])if(z=Jo(z,v($.folder.id,M)),z==="input")break;return j.set(N,z),z};return h.forEach(({folder:N})=>v(N.id,new Set)),j},[i,h,w,c,l]),A=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const k=new Map,j=new Map;for(const{folder:N}of h){if(!N.parentId)continue;const M=j.get(N.parentId)??[];M.push(N.id),j.set(N.parentId,M)}const v=(N,M)=>{if(M.has(N))return[];M.add(N);const L=h.find(({folder:$})=>$.id===N),K=L?d(L.nodes):[],z=j.get(N)??[];for(const $ of z)K.push(...v($,M));return K};for(const{folder:N}of h)k.set(N.id,v(N.id,new Set));return k},[h,d,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:p,allFoldersForGroup:h,rootFolders:S,ungroupedSessions:g,folderActivityStateById:E,folderSessionsForDeleteById:A}}function Fp(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:x,renameFolder:y,deleteFolder:m,showDeletionDialog:h,setDeleteFolderConfirm:b,renderSessionNode:g,showMoreGroupSessions:S,resetGroupSessionLimit:w,mobileVariant:E,alwaysShowActions:A,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:v,setSessionSwitcherOpen:N,openNewSessionDraft:M,addSessionToFolder:L,createFolderAndStartRename:K,renamingFolderId:z,renameFolderDraft:$,setRenameFolderDraft:O,setRenamingFolderId:R,pinnedSessionIds:D,expandedParents:I,sessionOrderIndex:T,editingId:W,openSidebarMenuKey:Z,activeActivitySessionIds:F,unreadActivitySessionIds:me,onToggleCollapsedGroup:q,dragHandleProps:Ae,compactBodyPadding:Ie=!1,scrollContainerRef:G}=e,U=a.useCallback((Ce,Ue)=>{const ge=T.get(Ce.session.id),Oe=T.get(Ue.session.id);if(ge!==void 0||Oe!==void 0){if(ge===void 0)return 1;if(Oe===void 0)return-1;if(ge!==Oe)return ge-Oe}return gu(Ce.session,Ue.session,D,Ka)},[D,T]),Y=i?c.get(t):null,X=i?!1:u.has(n),se=!t.isMain&&!t.isArchivedBucket&&!o?Ee(t.directory??null):null,we=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,pe=a.useMemo(()=>se&&we?_n(se,we):null,[se,we]),V=Ul(pe);zl(se,we);const Q=V?`var(--pr-${V.visualState})`:void 0,ie=f?10:5,ke=Math.max(ie,d??ie),Se=i?Y?.groupMatches===!0:!1,He=i,H=a.useMemo(()=>[...He?Y?.filteredNodes??[]:t.sessions].sort(U),[U,t.sessions,Y?.filteredNodes,He]),de=a.useCallback(Ce=>{const Ue=[],ge=Oe=>{Oe.forEach(Ge=>{Ue.push(Ge.session),Ge.children.length>0&&ge(Ge.children)})};return ge(Ce),Ue},[]),ne=bu(),ue=a.useMemo(()=>new Set(ne.map(Ce=>Ce.sessionId)),[ne]),{folderScopeKey:ve,folderScopes:Le,allFoldersForGroup:be,rootFolders:te,ungroupedSessions:xe,folderActivityStateById:fe,folderSessionsForDeleteById:je}=Tp({group:t,sourceGroupNodes:H,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:U,activeActivitySessionIds:F,unreadActivitySessionIds:me,inputActivitySessionIds:ue,collectGroupSessions:de}),Ye="project",_e=a.useMemo(()=>{const Ce=new Set;return Gi(H,W,Ce),be.forEach(({nodes:Ue})=>{Gi(Ue,W,Ce)}),Ce},[H,be,W]),De=a.useMemo(()=>{if(!Z)return null;const Ce=gr(H,Z,Ye,!!t.isArchivedBucket);if(Ce)return Ce;for(const{nodes:Ue}of be){const ge=gr(Ue,Z,Ye,!!t.isArchivedBucket);if(ge)return ge}return null},[Z,H,be,t.isArchivedBucket]),Ve=a.useCallback(Ce=>{const Ue=new WeakMap,ge=Oe=>{Ue.set(Oe,Ao(Oe));for(const Ge of Oe.children)ge(Ge)};return Ce.forEach(ge),Ue},[]),ae=a.useMemo(()=>Ve(H),[Ve,H]),Fe=a.useMemo(()=>{const Ce=new WeakMap;return be.forEach(({nodes:Ue})=>{Ue.forEach(ge=>Ce.set(ge,Ao(ge)))}),Ce},[be]),tt=a.useCallback(Ce=>ae.get(Ce)??Fe.get(Ce)??"",[ae,Fe]),xt=a.useCallback(Ce=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce)}),[_e,De,tt]),Qe=xe.length,pt=t.isArchivedBucket||i?xe:xe.slice(0,ke),Xe=Qe-pt.length,Ss=!t.isArchivedBucket&&!i&&Qe>ie&&Xe===0,St=t.isArchivedBucket===!0&&!i&&pt.length>=ip,st=t.isArchivedBucket?"archived":"active",Et=St&&pt.some(Ce=>{if(Ce.children.length===0)return!1;const Ue=`project:${st}:${Ce.session.id}`;return I.has(Ue)}),Lt=a.useMemo(()=>de(H),[de,H]);if(i&&!Se&&te.length===0&&xe.length===0)return null;const Yt=!t.isMain&&!!t.branch,jt=t.branch&&Ff(t.branch,t.label)?{label:t.branch,color:null}:null,Ot=X?Kl(H,F,me,ue):null,yt=Ot?s.jsx(Ll,{state:Ot,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,rt=(Ce,Ue)=>{const{folder:ge,scopeKey:Oe,scopeDirectory:Ge,nodes:it}=Ce,kt=je.get(ge.id)??[],ot=i?!1:p.has(ge.id);return s.jsx(Jm,{folderId:ge.id,children:(Bt,ns)=>s.jsx(Vm,{folder:ge,displayName:Ue,sessions:it,isCollapsed:ot,collapsedActivityState:ot?fe.get(ge.id)??null:null,onToggle:()=>x(ge.id),onRename:Ze=>{y(Oe,ge.id,Ze)},onDelete:()=>{if(t.isArchivedBucket){Ms.requestDelete({sessions:kt,mode:"session"});return}if(!h){m(Oe,ge.id);return}const Ze=be.filter(({folder:Dt})=>Dt.parentId===ge.id).length,Rt=it.length;b({scopeKey:Oe,folderId:ge.id,folderName:ge.name,subFolderCount:Ze,sessionCount:Rt})},renderSessionNode:g,getRenderExtras:tt?Ze=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ze),childRenderExtrasFor:xt}):void 0,groupDirectory:Ge??t.directory,projectId:r,mobileVariant:E,alwaysShowActions:A,isRenaming:z===ge.id,renameDraft:z===ge.id?$:void 0,onRenameDraftChange:Ze=>O(Ze),onRenameSave:()=>{const Ze=$.trim();Ze&&y(Oe,ge.id,Ze),R(null),O("")},onRenameCancel:()=>{R(null),O("")},droppableRef:Bt,isDropTarget:ns,depth:0,onNewSession:()=>{r&&r!==k&&j(r),v("chat"),E&&N(!1),M({selectedProjectId:r,directoryOverride:Ge??t.directory,targetFolderId:ge.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},ge.id)},dt=()=>{const Ce=new Map;for(const Oe of be){const Ge=Oe.folder.parentId;if(!Ge)continue;const it=Ce.get(Ge);it?it.push(Oe):Ce.set(Ge,[Oe])}const Ue=[],ge=(Oe,Ge)=>{const it=Ge?`${Ge} / ${Oe.folder.name}`:Oe.folder.name;Ue.push(rt(Oe,it)),!(!i&&p.has(Oe.folder.id))&&(Ce.get(Oe.folder.id)??[]).forEach(ot=>ge(ot,it))};return te.forEach(Oe=>ge(Oe,"")),Ue},Vt=A?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",us=s.jsxs(Xm,{scopeKey:Le[0]?.scopeKey??ve,hasFolders:be.length>0,onSessionDroppedOnFolder:(Ce,Ue)=>{const ge=be.find(({folder:Ge})=>Ge.id===Ue);if(!ge)return;const Oe=bt.getState();for(const{scopeKey:Ge}of Le)Ge!==ge.scopeKey&&Oe.getSessionFolderId(Ge,Ce)&&Oe.removeSessionFromFolder(Ge,Ce);L(ge.scopeKey,Ue,Ce)},children:[dt(),t.isArchivedBucket?s.jsx(lp,{visibleSessions:pt,shouldVirtualize:St,hasExpandedParent:Et,scrollContainerRef:G,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:Ce=>({subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce),childRenderExtrasFor:xt})}):pt.map(Ce=>s.jsx(a.Fragment,{children:g(Ce,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:_e,menuOpenSessionId:De,nodeStructureKey:tt(Ce),childRenderExtrasFor:xt})},Ce.session.id)),Qe===0&&be.length===0?t.isArchivedBucket?s.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):s.jsx(Zt,{icon:"chat-new",onClick:()=>{M({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Xe>0?s.jsx(Zt,{icon:"arrow-down-s",onClick:()=>S(n,pt.length),children:Xe===1?"Show 1 more session":`Show ${Xe} more sessions`}):null,Ss?s.jsx(Zt,{icon:"arrow-up-s",onClick:()=>w(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:us})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(Ep,{group:t,groupKey:n,isCollapsed:X,onToggleCollapsedGroup:q,normalizedSessionSearchQuery:l,alwaysShowActions:A,groupHeaderRightPadding:Vt,dragHandleProps:Ae,groupPrColor:Q,groupPrSummary:V,groupActivityIndicator:yt,showBranchSubtitle:Yt,statusLine:jt,allGroupSessions:Lt,projectId:r,activeProjectId:k,setActiveProjectIdOnly:j,setActiveMainTab:v,mobileVariant:E,setSessionSwitcherOpen:N,openNewSessionDraft:M}),X?null:s.jsx("div",{className:"oc-group-body",children:us})]})}const Lp=a.memo(Fp,Mp);function Op(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:m,hasSessionSearchQuery:h,searchMatchCount:b,selectionModeEnabled:g,onToggleSelectionMode:S,mobileVariant:w=!1}=e;if(t)return null;const E=_(u,"text-muted-foreground hover:text-foreground",!w&&"hover:bg-transparent");return s.jsx("div",{className:_("select-none flex-shrink-0",w?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",w?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",w?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[s.jsxs("div",{className:_("flex min-w-0 items-center",w?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":w?"true":void 0,children:[o?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:E,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!w&&i?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:E,"aria-label":l?`Servers: ${l}`:"Servers",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Servers"})})]}):null,c?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:E,"aria-label":"Update",children:s.jsx(P,{name:"download",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,w?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:E,"aria-label":"Add project",children:s.jsx(P,{name:"folder-add",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),w?null:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:E,"aria-label":"Archive",children:s.jsx(P,{name:"archive",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",w?"gap-1":"gap-1.5"),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(A=>!A),className:E,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:_(E,g&&"bg-interactive-hover text-primary"),"aria-label":g?"Exit selection":"Select sessions","aria-pressed":g,children:s.jsx(P,{name:"checkbox-multiple",className:d})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:_(w?"pb-2":"pb-1"),children:[s.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:h?s.jsx("span",{children:b===1?`${b} match`:`${b} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:x,value:y,onChange:A=>m(A.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:A=>{A.key==="Escape"&&(A.stopPropagation(),h?m(""):p(!1))}}),y.length>0?s.jsx("button",{type:"button",onClick:()=>m(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:s.jsx(P,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const Kr="0.75rem";function Bp(e){const t=ce(o=>o.toggleSidebar),n=ce(o=>o.shortcutOverrides),r=Ho(dr("toggle_sidebar",n));return s.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${Kr})`}}),s.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, ${Kr})))`}}),s.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[s.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(${Lf} - max(var(--oc-titlebar-left-inset, ${Kr}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(nr,"text-current")}),s.jsx("span",{className:dl,children:"New session"})]}),e.showSidebarToggle?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.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:s.jsx(P,{name:"layout-left",className:"size-4"})})}),s.jsx(We,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Ar({...e}){return s.jsx(Ca,{...e})}function Nr({...e}){return s.jsx(Aa,{...e})}function Ir({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Na,{children:s.jsx(Ia,{className:_("app-region-no-drag z-50",t),children:s.jsx(Ea,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Wa,e),...o,children:n})})})}function Ps({className:e,...t}){return s.jsx(Ra,{className:_(Ga,e),...t})}function Zl({className:e,...t}){return s.jsx(Da,{className:_(Ha,e),...t})}const ec=500,_p=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:l=!1})=>{const[c,d]=a.useState(!1),u=a.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),p=a.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);a.useEffect(()=>()=>p(),[p]);const x=a.useCallback(()=>{p(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},ec)},[p]);return s.jsxs(Ar,{open:c,onOpenChange:d,children:[s.jsxs(Nr,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_(yr(l,n),"pl-6"),"aria-pressed":n,title:t.path}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx(P,{name:"git-branch",className:_(Fs(l),"text-muted-foreground")}),t.branch?s.jsx(qa,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):s.jsx("span",{className:an(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Ir,{className:"min-w-[160px]",children:s.jsxs(Ps,{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:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},yr=(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"),Up=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:x,setNodeRef:y,transform:m,transition:h,isDragging:b}=$o({id:e.id,disabled:!c}),[g,S]=a.useState(!1),w=a.useRef(null),E=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null)},[]);a.useEffect(()=>()=>E(),[E]);const A=a.useCallback(()=>{E(),w.current=window.setTimeout(()=>{w.current=null,S(!0)},ec)},[E]);return s.jsx("div",{ref:y,style:{transform:Ko.Translate.toString(m),transition:h},className:_(b&&"opacity-60"),children:s.jsxs(Ar,{open:g,onOpenChange:S,children:[s.jsxs(Nr,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:A,onTouchMove:E,onTouchEnd:E,onTouchCancel:E,style:{touchAction:"manipulation"},className:yr(p,n),"aria-pressed":n}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.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?x:{},children:s.jsx(Go,{directory:e.normalizedPath,label:t,className:Fs(p)})}),s.jsx("span",{className:an(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(ys,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?s.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:s.jsx(P,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(P,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(Ir,{className:"min-w-[160px]",children:[s.jsxs(Ps,{onClick:()=>u(e.id),children:[s.jsx(P,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(Zl,{}),s.jsxs(Ps,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},zp=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:x,homeDirectory:y,className:m,mobileVariant:h=!1})=>{const b=t===null,g=ct(A=>A.reorderProjects),S=e.length>1,w=_o(Fn(Fa,{activationConstraint:{distance:8}}),Fn(Ta,{activationConstraint:{delay:200,tolerance:6}})),E=a.useCallback(A=>{const{active:k,over:j}=A;if(!j||k.id===j.id)return;const v=ct.getState().projects,N=v.findIndex(L=>L.id===k.id),M=v.findIndex(L=>L.id===j.id);N<0||M<0||g(N,M)},[g]);return s.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:yr(h,b),"aria-pressed":b,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(P,{name:"chat-history",className:Fs(h)}),s.jsx("span",{className:an(h),children:"All sessions"})]})}),s.jsx(Uo,{sensors:w,collisionDetection:zo,onDragEnd:E,children:s.jsx(Pa,{items:e.map(A=>A.id),strategy:Ma,children:e.map(A=>{const k=t===A.id,j=k&&!n,v=r.get(A.normalizedPath)??[],N=qo(A.label?.trim()||On(A.normalizedPath,y)||A.normalizedPath),M=x?.get(A.id),L=Ee(A.normalizedPath)?.toLowerCase()??"",K=L?M?.has(L)??!1:!1,z=(M?.size??0)>0,$=p?.(A.id)??!1,O=x?k?K:z:$;return s.jsxs(a.Fragment,{children:[s.jsx(Up,{project:A,label:N,isSelected:j,hasActive:O,hasWorktrees:v.length>0,worktreeError:o.get(A.normalizedPath),isExpanded:k,canDrag:S,onSelect:()=>i(A.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),k?v.map(R=>{const D=n===R.path,I=Ee(R.path)?.toLowerCase()??"",T=I?M?.has(I)??!1:!1,W=x?T:!1;return s.jsx(_p,{projectId:A.id,worktree:R,isSelected:D,hasActive:W,onSelect:()=>l?.(A.id,R.path),onClose:c,mobileVariant:h},R.path)}):null]},A.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:yr(h,!1),children:[s.jsx(P,{name:"add",className:Fs(h)}),s.jsx("span",{className:an(h),children:"Add folder"})]})]})},Wr="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 $p({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?s.jsxs(s.Fragment,{children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:Wr,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:Wr,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Wr,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(We,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ne,{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 tc=({projectLabel:e,projectPath:t=null,mobileVariant:n=!1})=>{const r=Fs(n),o=an(n);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?s.jsx(Go,{directory:t,label:e,className:r}):s.jsx(P,{name:"folder",className:_(r,"text-muted-foreground/80")})}),s.jsx("span",{className:_(o,"text-foreground"),children:e})]})},sc=({isCollapsed:e,mobileVariant:t=!1,className:n})=>s.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",n),children:s.jsx(P,{name:e?"arrow-right-s":"arrow-down-s",className:Fs(t)})}),Kp=({id:e,disabled:t=!1,projectLabel:n,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:l,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:p,onRenameStart:x,onClose:y,children:m,showCreateButtons:h=!0,hideHeader:b=!1,openSidebarMenuKey:g,setOpenSidebarMenuKey:S,statusIndicator:w=null})=>{const{listeners:E,setNodeRef:A,transform:k,transition:j,isDragging:v}=$o({id:e,disabled:t}),N=a.useRef(!1),M=`project:${e}`,L=g===M,[K,z]=a.useState(!1),$=u&&!i,O=a.useCallback(F=>{F&&z(!1),S(F?M:null)},[M,S]),R=F=>s.jsxs(s.Fragment,{children:[h&&!l&&p&&s.jsxs(F,{onClick:p,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(F,{onClick:x,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(F,{onClick:y,className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),D=a.useCallback(F=>{F.stopPropagation()},[]),I=a.useCallback(F=>{F.stopPropagation()},[]),T=a.useCallback(F=>{F.stopPropagation()},[]),W=a.useCallback(F=>{(F.button===2||F.button===0&&F.ctrlKey)&&(N.current=!0)},[]),Z=a.useCallback(F=>{if(F.currentTarget.blur(),N.current){N.current=!1;return}f()},[f]);return s.jsxs("div",{ref:A,style:{transform:Ko.Translate.toString(k),transition:j},className:_("relative",v&&"opacity-60"),children:[b?null:s.jsxs(Ar,{open:K,onOpenChange:z,children:[s.jsxs(Nr,{render:s.jsx("div",{className:_("text-left group/project select-none",$&&"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":$?"true":void 0,onContextMenu:F=>{l||v||(F.preventDefault(),z(!0))}}),children:[s.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:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:W,onClick:Z,...E,className:_(Cr,"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:[s.jsx(tc,{id:e,projectLabel:n,projectPath:r,mobileVariant:c}),w?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:w}):null,s.jsx(sc,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",d?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(We,{side:"right",sideOffset:8,children:o})]}),s.jsx("div",{className:"absolute right-[calc(3.25rem*var(--padding-scale,1))] top-1/2 z-10 -translate-y-1/2",children:l?null:s.jsxs(Gt,{open:L,onOpenChange:O,children:[s.jsx(Ht,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",L?"opacity-100 pointer-events-auto":d?"opacity-100":"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"),"aria-label":"Folder menu",onPointerDown:I,onMouseDown:T,onClick:D,children:s.jsx(P,{name:"more-2",className:"size-4"})})}),s.jsx(qt,{align:"end",className:"min-w-[180px]",children:R(ht)})]})}),h&&!l&&p?s.jsx("div",{className:"absolute right-7 top-1/2 z-10 -translate-y-1/2",children:s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),p()},className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"opacity-100":"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"),"aria-label":"New session",children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(We,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null]}),$?s.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]}),s.jsx(Ir,{className:"min-w-[180px]",children:R(Ps)})]}),m]})},Wp=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:l,transition:c,isDragging:d}=$o({id:e,disabled:t}),u=a.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:Ko.Transform.toString(l),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};a.memo(Wp);const sa="pt-0.5 pb-1",Gp=({sections:e,homeSection:t,homeDirectory:n,collapsedProjects:r,toggleProject:o,hasSessionSearchQuery:i,activeProjectId:l,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,isInlineEditing:f,stickyFolderHeaders:p,renderGroupSessions:x,renderSessionNode:y,getOrderedGroups:m,renderProjectStatusIndicator:h,scrollContainerRef:b,setActiveProjectIdOnly:g,setActiveMainTab:S,setSessionSwitcherOpen:w,openNewSessionDraft:E,openProjectEditDialog:A,removeProject:k,reorderProjects:j,openSidebarMenuKey:v,setOpenSidebarMenuKey:N,onOpenDirectoryDialog:M,emptyState:L,searchEmptyState:K})=>{const z=_o(Fn(Fa,{activationConstraint:{distance:8}}),Fn(Ta,{activationConstraint:{delay:200,tolerance:6}})),$=e.length>1&&!i&&!f,O=a.useCallback(F=>{if(f||i)return;const{active:me,over:q}=F;if(!q||me.id===q.id)return;const Ae=ct.getState().projects,Ie=Ae.findIndex(U=>U.id===me.id),G=Ae.findIndex(U=>U.id===q.id);Ie<0||G<0||Ie===G||j(Ie,G)},[f,i,j]),[R,D]=a.useState(5);a.useEffect(()=>{D(5)},[i]);const I=a.useMemo(()=>t?t.groups.filter(F=>!F.isArchivedBucket).flatMap(F=>F.sessions):[],[t]),T=i?I:I.slice(0,R),W=I.length-T.length,Z=i?!1:r.has("__home__");return e.length===0&&!t?i?K:L:s.jsxs("div",{className:"space-y-2",children:[s.jsx(Uo,{sensors:z,collisionDetection:zo,onDragEnd:O,children:s.jsx(Pa,{items:e.map(F=>F.project.id),strategy:Ma,children:e.map(F=>{const me=F.project,q=me.id,Ae=ul(me,n),Ie=uo(me.normalizedPath,n),G=i?!1:r.has(q),U=G?[]:m(q,F.groups),Y=G?null:U.find(se=>se.isMain)??null,X=G?[]:Y?U.filter(se=>se.id!==Y.id):U;return s.jsx(Kp,{id:q,disabled:!$,projectLabel:Ae,projectPath:me.normalizedPath,projectDescription:Ie,isCollapsed:G,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,stickyHeader:p,statusIndicator:G?h?.(q,F.groups):null,onToggle:()=>o(q),onNewSession:()=>{q!==l&&g(q),S("chat"),d&&w(!1),E({selectedProjectId:q,directoryOverride:me.normalizedPath})},onRenameStart:()=>A(q),onClose:()=>k(q),openSidebarMenuKey:v,setOpenSidebarMenuKey:N,children:G?null:s.jsxs("div",{className:sa,children:[Y?x(Y,`${q}:${Y.id}`,q,!0,null,void 0,b):null,X.map(se=>{const we=`${q}:${se.id}`,pe=U.length===1;return s.jsx(a.Fragment,{children:x(se,we,q,pe,null,void 0,b)},se.id)})]})},q)})})}),t?s.jsxs("div",{children:[s.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:s.jsxs("button",{type:"button","aria-expanded":!Z,style:{touchAction:"manipulation"},onClick:()=>o("__home__"),className:`${Cr} 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:[s.jsx(tc,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),s.jsx(sc,{isCollapsed:Z,mobileVariant:d})]})}),Z?null:s.jsxs("div",{className:sa,children:[T.map(F=>s.jsx(a.Fragment,{children:y?.(F,0,F.session.directory??"~","__home__",!1,{globalSession:!0},"project")},F.session.id)),!i&&W>0?s.jsx(Zt,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>D(F=>F+7),children:W===1?"Show 1 more session":`Show ${W} more sessions`}):null,!i&&R>5&&I.length>5?s.jsx(Zt,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>D(5),children:"Show fewer sessions"}):null]})]}):null,!c&&M?s.jsx(Zt,{icon:"add",mobileVariant:d,onClick:M,children:"Add folder"}):null]})},Hp=a.memo(Gp);function qp(e){Wt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",n=t==="timeline",r=a.useRef(new Map),o=a.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(b,g)=>{const S=r.current,w=S.get(b);if(w&&w.groups===g)return w.ordered;const E=e.getOrderedGroups(b,g);if(S.set(b,{groups:g,ordered:E}),S.size>256){const A=S.keys().next().value;A!==void 0&&S.delete(A)}return E},l=a.useRef(null),c=!!(e.isAllFoldersView||n),d=a.useMemo(()=>{if(!c)return[];const b=[],g=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const S of g){const w=ul(S.project,e.homeDirectory);for(const E of S.groups)if(!E.isArchivedBucket)for(const A of E.sessions){const k=!!e.pinnedSessionIds?.has(A.session.id),j=A.session.time?.updated||A.session.time?.created||0;b.push({node:A,project:S.project,projectLabel:w,isPinned:k,timestamp:j,globalSession:S===e.allFoldersOnlySection})}}return b.sort((S,w)=>S.isPinned!==w.isPinned?S.isPinned?-1:1:w.timestamp-S.timestamp),b},[e.allFoldersOnlySection,c,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[u,f]=a.useState(30);a.useEffect(()=>{f(30)},[e.hasSessionSearchQuery]);const p=a.useMemo(()=>d.slice(0,u),[d,u]),x=a.useMemo(()=>e.timelineBoundaries??Co(Date.now(),1),[e.timelineBoundaries]),y=a.useMemo(()=>n?xm(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:x}):[],[n,p,x]);if(e.sharedSessionsOnly)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const m=(e.isAllFoldersView||t==="timeline"||t==="folder")&&!!e.allFoldersOnlySection;if(e.projectSections.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const h=()=>{const b=d.length-p.length;return s.jsxs(s.Fragment,{children:[b>0?s.jsx(Zt,{icon:"arrow-down-s",onClick:()=>f(g=>g+30),children:b===1?"Show 1 more session":`Show ${b} more sessions`}):null,u>30&&d.length>30?s.jsx(Zt,{icon:"arrow-up-s",onClick:()=>f(30),children:"Show fewer sessions"}):null]})};return s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(Is,{ref:l,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const b=e.sectionsForRender.find(E=>E.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!b)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const g=b.groups.find(E=>E.isMain&&E.sessions.length>0)??b.groups.find(E=>E.sessions.length>0)??b.groups.find(E=>E.isMain)??b.groups[0];if(!g)return s.jsx(Zt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:b.project.id,directoryOverride:b.project.normalizedPath}),children:"New session"});const S=b.groups.find(E=>E.isArchivedBucket);return[g,...S&&S.id!==g.id?[S]:[]].map(E=>{const A=`${b.project.id}:${E.id}`,k=E.id===g.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(E,A,b.project.id,k,null,!0,l)},A)})})()}):t==="folder"?s.jsx(Qo.Provider,{value:"tree",children:s.jsx(Hp,{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,scrollContainerRef:l,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?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[y.map((b,g)=>{const S=pm[b.id];return s.jsxs("section",{"aria-label":S,"data-timeline-bucket":b.id,children:[s.jsx("div",{role:"heading","aria-level":3,className:_("select-none px-3 pb-1 text-xs leading-4 font-medium text-muted-foreground",g===0?"pt-1":"pt-3"),children:S}),b.items.map(({node:w,project:E,projectLabel:A,globalSession:k})=>{const j=w.session.directory??E.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(w,0,j,E.id,!1,{projectLabel:A,showFolderLabel:!0,globalSession:k},"project")},w.session.id)})]},b.id)}),h()]})}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[p.map(({node:b,project:g,projectLabel:S,globalSession:w})=>{const E=b.session.directory??g.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(b,0,E,g.id,!1,{projectLabel:S,showFolderLabel:!0,globalSession:w},"project")},b.session.id)}),h()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const g=b.project.id,S=i(g,b.groups),w=S.find(A=>A.isMain)??null,E=w?S.filter(A=>A.id!==w.id):S;return s.jsxs("div",{children:[w?e.renderGroupSessions(w,`${g}:${w.id}`,g,!0,null,void 0,l):null,E.map(A=>{const k=`${g}:${A.id}`,j=S.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(A,k,g,j,null,void 0,l)},A.id)})]},g)})})]})})})}const Yp=a.memo(qp);let To=!1;const Fo=new Set;let na=!1;function Vp(){for(const e of Fo)e()}function ei(e){To!==e&&(To=e,Vp())}function Qp(e){e.key==="Shift"&&ei(!0)}function Jp(e){e.key==="Shift"&&ei(!1)}function Xp(){ei(!1)}function Zp(){na||typeof window>"u"||(na=!0,window.addEventListener("keydown",Qp),window.addEventListener("keyup",Jp),window.addEventListener("blur",Xp))}function eg(e){return Zp(),Fo.add(e),()=>{Fo.delete(e)}}function tg(){return To}function sg(){return!1}function ng(){return Re.useSyncExternalStore(eg,tg,sg)}const rg=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:d}){const u=ng(),f=u?n:t,p=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.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:l,onClick:p,onKeyDown:x=>x.stopPropagation(),children:s.jsx(P,{name:u?"delete-bin":"archive",className:o})})}),s.jsx(We,{side:"left",sideOffset:8,children:f})]})}),og=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(ts,{open:t,onOpenChange:n,children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:"Export Markdown"}),s.jsx(vs,{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?`})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.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"]}),s.jsxs(Ls,{children:[s.jsx(Ne,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ne,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function ig(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:x,handleDeleteSession:y,handleRestoreSession:m}=e,{Item:h,Separator:b}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(h,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(h,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),s.jsxs(h,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[i?s.jsx(P,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(P,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),s.jsxs(h,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(h,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,s.jsx(b,{}),l?null:s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l}),children:[s.jsx(P,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>m(n),children:[s.jsx(P,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,s.jsxs(h,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l,hardDelete:!0}),children:[s.jsx(P,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function ag(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Na,{children:s.jsx(Ia,{className:"app-region-no-drag z-50",children:s.jsx(Ea,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Wa,"min-w-[180px]"),children:ig(e,{Item:({className:r,...o})=>s.jsx(Ra,{className:_(Ga,r),...o}),Separator:({className:r,...o})=>s.jsx(Da,{className:_(Ha,r),...o})})})})})}const Gr=new WeakMap,lg=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Gr.get(n)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,l=null;const c=()=>{i=!0,l!==null&&window.cancelAnimationFrame(l),l=null,Gr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!n.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Wt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Gr.set(n,c),l=window.requestAnimationFrame(d)};function cg(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),l=String(t.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${i}:${l}`}function dg(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&n?`${t}/${n}`:n||t}function ug(e){const t=e.info.role==="user"?"User":"Assistant",n=cg(e.info.time?.created),r=dg(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
21
21
|
|
|
22
22
|
*${o}*`:`**${t}**`}function fg(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function nc(e){const t=ug(e),n=fg(e.parts).trim();return n?`${t}
|
|
23
23
|
|
|
@@ -59,4 +59,4 @@ ${n}`:""}function rc(e,t){const n="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${
|
|
|
59
59
|
`):l.slice(0,-1).join(`
|
|
60
60
|
`);if(this.tail=i.endsWith(`
|
|
61
61
|
`)?"":(l[l.length-1]??"").slice(-1024),!c)return;const d=Ab(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Nb(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const p=he.getState().getDirectoryState(t)?.tabs.find(x=>x.id===n);!p||p.previewUrlLocked||p.previewUrl===d||o(t,n,d,{locked:!1,autoOpened:!1})})}}const Pb=(e,t)=>{if(t!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?uc(o):null};function Mb({terminal:e,effectiveDirectory:t,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:l,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:x,tabs:y}){const m=he(U=>U.ensureDirectory),h=he(U=>U.setTabSessionId),b=he(U=>U.setTabLifecycle),g=he(U=>U.setConnecting),S=he(U=>U.appendToBuffer),w=he(U=>U.replaceBuffer),E=he(U=>U.setTabPreviewUrl),[A,k]=a.useState(null),[j,v]=a.useState(!1),[N,M]=a.useState(!1),L=a.useRef(new Map),K=a.useRef(null),z=a.useRef(n),$=a.useRef(r),O=a.useRef(t),R=a.useRef(null),D=a.useRef(new Set),I=a.useRef(new Map),T=a.useRef(y),W=a.useRef(l),Z=a.useRef(i),F=a.useRef(e);T.current=y,W.current=l,Z.current=i,F.current=e;const me=a.useCallback(()=>{const U=z.current;U&&I.current.get(U)?.reset()},[]);a.useEffect(()=>{$.current=r},[r]),a.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),a.useEffect(()=>{z.current=n},[n]),a.useEffect(()=>{O.current=t},[t]);const q=a.useCallback(()=>{for(const U of L.current.values())try{U()}catch{}L.current.clear(),K.current=null,M(!1)},[]);a.useEffect(()=>()=>{q(),$.current=null},[q]);const Ae=a.useCallback((U,Y,X)=>{let se=I.current.get(Y);se||(se=new Db,I.current.set(Y,se)),se.scan(U,Y,X,E)},[E]),Ie=a.useCallback((U,Y,X)=>{if(L.current.has(X)){K.current=X;return}const se=Ei(),we=()=>Ei()===se&&O.current===U&&he.getState().getDirectoryState(U)?.tabs.find(V=>V.id===Y)?.terminalSessionId===X,pe=e.connect(X,{onEvent:V=>{if(we())switch(V.type){case"snapshot":{z.current===Y&&$.current===X?(g(U,Y,!1),k(null),v(!1),M(!1),x()):g(U,Y,!1),w(U,Y,V.data??"",V.sequence??0),Ae(U,Y,V.data??""),V.status==="exited"&&b(U,Y,"exited");break}case"reconnecting":{z.current===Y&&(k(null),v(!1),M(!0));break}case"data":{V.data&&(S(U,Y,V.data,V.sequence,V.replayData),Ae(U,Y,V.data));break}case"exit":{const Q=typeof V.exitCode=="number"?V.exitCode:null,ie=typeof V.signal=="number"?V.signal:null,Se=!!he.getState().getDirectoryState(U)?.tabs.find(He=>He.id===Y)?.label?.startsWith("Action:");S(U,Y,`\\r\\n[Process exited${Q!==null?` with code ${Q}`:""}${ie!==null?` (signal ${ie})`:""}]\\r\\n`),b(U,Y,"exited"),z.current===Y&&(g(U,Y,!1),k(Se?null:"Terminal session ended"),v(!1),M(!1));break}}},onError:(V,Q)=>{if(!we())return;const ie=z.current===Y;if(!Q){ie&&(k(null),v(!1));return}if(V.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(U)?.tabs.find(Se=>Se.id===Y)?.label?.startsWith("Action:")){ie&&(k(null),v(!1),g(U,Y,!1),M(!1)),h(U,Y,null),b(U,Y,"idle");return}ie&&(M(!1),k(`Connection failed: ${V.message}`),v(!0),g(U,Y,!1),b(U,Y,"exited"),h(U,Y,null))}});L.current.set(X,()=>pe.close()),K.current=X},[S,x,w,Ae,g,b,h,e]),G=a.useMemo(()=>y.map(U=>`${U.id}:${U.terminalSessionId??""}`).join(","),[y]);return a.useEffect(()=>{if(!l||!i||!t)return;const U=t,Y=new Set;for(const X of y)X.terminalSessionId&&(Y.add(X.terminalSessionId),Ie(U,X.id,X.terminalSessionId));for(const[X,se]of L.current)if(!Y.has(X)){try{se()}catch{}L.current.delete(X)}},[G,y,t,l,i,Ie]),a.useEffect(()=>gf(()=>{if(!W.current||!Z.current)return;const U=O.current;if(!U)return;const Y=[];for(const se of T.current){if(!se.terminalSessionId)continue;he.getState().getDirectoryState(U)?.tabs.find(pe=>pe.id===se.id)?.terminalSessionId===se.terminalSessionId&&Y.push({id:se.id,terminalSessionId:se.terminalSessionId})}if(L.current.clear(),K.current=null,Y.length===0)return;M(!0),k(null),v(!1);for(const se of Y)Ie(U,se.id,se.terminalSessionId);const X=R.current;if(X)for(const se of Y)F.current.resize({sessionId:se.terminalSessionId,...X}).catch(()=>{})}),[Ie]),a.useEffect(()=>{let U=!1;if(!l||!i)return;if(!t){k(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const X=t;if(!O.current||O.current!==X)return;if(!he.getState().getDirectoryState(X)){m(X);return}const we=he.getState().getDirectoryState(X);if(!we||we.tabs.length===0)return;const pe=we.activeTabId??we.tabs[0]?.id??null;if(!pe)return;const V=we.tabs.find(H=>H.id===pe)??we.tabs[0],Q=V?.terminalSessionId??null,ie=V?.lifecycle??"idle",ke=!!V?.label?.startsWith("Action:"),Se=he.getState().getBuffer(X,pe),He=Se.byteLength>0||Se.chunks.length>0;if(!Q){if(ie==="exited"){g(X,pe,!1);return}if(ke&&He){g(X,pe,!1);return}const H=`${X}\0${pe}`;if(D.current.has(H))return;const de=R.current??fc;D.current.add(H),k(null),v(!1),M(!1),g(X,pe,!0);try{const ne=await e.createSession({cwd:X,sessionId:pe,cols:de.cols,rows:de.rows,shell:c,loginShell:d,...u.current});if(!he.getState().getDirectoryState(X)?.tabs.find(Le=>Le.id===pe)){try{await e.close(ne.sessionId)}catch{}return}h(X,pe,ne.sessionId);const ve=R.current;ve&&(ve.cols!==de.cols||ve.rows!==de.rows)&&e.resize({sessionId:ne.sessionId,...ve}).catch(()=>{});return}catch(ne){const ue=he.getState().getDirectoryState(X)?.tabs.find(ve=>ve.id===pe);if(!ue||ue.terminalSessionId||(g(X,pe,!1),O.current!==X||z.current!==pe))return;k(ne instanceof Error?ne.message:"Failed to start terminal session"),v(!0),M(!1);return}finally{D.current.delete(H)}}!Q||U||($.current=Q)})(),()=>{U=!0}},[p,t,r,o,n,i,f,l,m,g,b,h,e,d,c,u]),{connectionError:A,setConnectionError:k,isFatalError:j,setIsFatalError:v,isReconnectPending:N,setIsReconnectPending:M,terminalIdRef:$,lastViewportSizeRef:R,directoryRef:O,activeTabIdRef:z,disconnectStream:q,resetTerminalPreviewScan:me,startStream:Ie}}function Tb({terminal:e,terminalIdRef:t,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=a.useState(null),p=a.useRef(null),x=a.useCallback(()=>{d||p.current?.focus()},[d]),y=a.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[d]);a.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),a.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const m=a.useCallback(w=>{if(!w||n)return;let E=w,A=!1;u&&w.length>0&&(E=Rb(w,u),A=!0);const k=t.current;k&&(e.sendInput(k,E).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),A&&(f(null),x()))},[u,x,n,r,e,t]),h=a.useCallback((w,E)=>{const A=l.current;if((!A||A.cols!==w||A.rows!==E)&&(l.current={cols:w,rows:E}),!i)return;const k=t.current;k&&e.resize({sessionId:k,cols:w,rows:E}).catch(()=>{})},[i,l,e,t]),b=a.useCallback(w=>{f(E=>E===w?null:w),x()},[x]),g=a.useCallback(w=>{const E=Eb(w,u);E&&(m(E),f(null),x())},[u,x,m]),S=a.useCallback(w=>{if(w.repeat)return;const E=w.key;if(!E||E==="Control"||E==="Meta"||E==="Alt"||E==="Shift")return;const A=E.length===1?E.toLowerCase():E;if(A in xa){w.preventDefault(),w.stopPropagation(),g(xa[A]);return}const k=Pb(w,u);k&&(w.preventDefault(),w.stopPropagation(),m(k),f(null),x())},[u,x,g,m]);return a.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[u,S,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:x,focusTerminalWhenWindowActive:y,handleViewportInput:m,handleViewportResize:h,handleModifierToggle:b,handleMobileKeyPress:g}}function Fb({terminal:e,effectiveDirectory:t,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:x,setConnectionError:y,setIsFatalError:m,setIsReconnectPending:h}){const b=he(K=>K.createTab),g=he(K=>K.setActiveTab),S=he(K=>K.closeTab),w=he(K=>K.setTabSessionId),E=he(K=>K.setTabLifecycle),[A,k]=a.useState(!1),j=a.useCallback(async()=>{if(!t||A)return;const K=he.getState().getDirectoryState(t),z=n??K?.activeTabId??K?.tabs[0]?.id??null;if(!z)return;const $=K?.tabs.find(O=>O.id===z)?.terminalSessionId??null;if(!(!$||!e.restartSession)){k(!0),y(null),m(!1),h(!1),p();try{const O=c.current??fc,R=await e.restartSession($,{cwd:t,shell:o,loginShell:i,...O,...l.current});if(he.getState().getDirectoryState(t)?.tabs.find(I=>I.id===z)?.terminalSessionId!==$||(w(t,z,R.sessionId),E(t,z,"running"),d.current!==t||u.current!==z))return;f.current=R.sessionId,x(t,z,R.sessionId)}catch(O){if(he.getState().getDirectoryState(t)?.tabs.find(D=>D.id===z)?.terminalSessionId!==$||d.current!==t||u.current!==z)return;y(O instanceof Error?O.message:"Failed to restart terminal"),m(!1),h(!1),f.current=$,x(t,z,$)}finally{k(!1)}}},[n,u,d,t,r,A,c,p,y,m,h,E,w,x,e,l,f,i,o]),v=a.useCallback(async()=>{await j()},[j]),N=a.useCallback(()=>{if(!t)return;const K=b(t);g(t,K),y(null),m(!1),h(!1)},[b,t,g,y,m,h]),M=a.useCallback(K=>{t&&(g(t,K),y(null),m(!1),h(!1))},[t,g,y,m,h]),L=a.useCallback(K=>{if(!t)return;y(null),m(!1),h(!1);const z=he.getState().getDirectoryState(t)?.tabs.find($=>$.id===K)?.terminalSessionId;(async()=>{z&&await e.close(z),S(t,K)})().catch($=>y($ instanceof Error?$.message:"Terminal session ended"))},[S,t,y,m,h,e]);return{isRestarting:A,handleRestart:j,handleHardRestart:v,handleCreateTab:N,handleSelectTab:M,handleCloseTab:L}}const Vy=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Os(),{currentTheme:i}=Xa(),l=a.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=Lu(),d=ce(ae=>ae.terminalFontSize),u=ce(ae=>ae.terminalShell),f=ce(ae=>ae.terminalLoginShells.includes(ae.terminalShell)),{isMobile:p,isTablet:x,hasTouchOnlyPointer:y}=dn(),m=p||x,h=(m||y)&&o.platform==="web",b=!0,g=ce(ae=>ae.showTerminalQuickKeysOnDesktop),S=m||g,w=Te(ae=>ae.currentSessionId),E=Te(ae=>ae.newSessionDraft),A=w!==null||E?.open===!0,k=Ou()??null,j=he(ae=>k?ae.sessions.get(k):void 0),v=he(ae=>ae.hasHydrated),N=ce(ae=>ae.openContextPreview),M=a.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,b]),L=a.useMemo(()=>{if(j)return M?j.tabs.find(ae=>ae.id===M)??j.tabs[0]:j.tabs[0]},[j,M]),K=a.useMemo(()=>(j?.tabs??[]).map(ae=>({icon:(()=>{const Fe=ae.iconKey?Mn[ae.iconKey]??"terminal":"terminal";return s.jsx(P,{name:Fe,className:"h-4 w-4"})})(),id:ae.id,label:ae.label,title:ae.label,closeLabel:"Close tab"})),[j?.tabs]),z=L?.terminalSessionId??null,$=L?.lifecycle??"idle",O=a.useMemo(()=>(j?.tabs??[]).map(ae=>({id:ae.id,terminalSessionId:ae.terminalSessionId,label:ae.label})),[j?.tabs]),R=L?.isConnecting??!1,D=L?.previewUrl??null,T=ce(ae=>ae.activeMainTab)==="terminal",W=e??T,[Z,F]=a.useState(W);a.useEffect(()=>{W&&F(!0)},[W]);const{connectionError:me,setConnectionError:q,isFatalError:Ae,setIsFatalError:Ie,isReconnectPending:G,setIsReconnectPending:U,terminalIdRef:Y,lastViewportSizeRef:X,directoryRef:se,activeTabIdRef:we,resetTerminalPreviewScan:pe,startStream:V}=Mb({terminal:r,effectiveDirectory:k,activeTabId:M,terminalSessionId:z,terminalLifecycle:$,hasOpenedTerminalViewport:Z,terminalHydrated:v,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:b,hasActiveContext:A,tabs:O,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ie.current?.focus()}}),{activeModifier:Q,terminalControllerRef:ie,focusTerminalWhenWindowActive:ke,handleViewportInput:Se,handleModifierToggle:He,handleMobileKeyPress:H}=Tb({terminal:r,terminalIdRef:Y,isReconnectPending:G,setConnectionError:q,showQuickKeys:S,isTerminalVisible:W,lastViewportSizeRef:X,terminalSessionId:z,useTouchTerminalInput:h}),{isRestarting:de,handleRestart:ne,handleHardRestart:ue,handleCreateTab:ve,handleSelectTab:Le,handleCloseTab:be}=Fb({terminal:r,effectiveDirectory:k,activeTabId:M,enableTabs:b,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:X,directoryRef:se,activeTabIdRef:we,terminalIdRef:Y,resetTerminalPreviewScan:pe,startStream:V,setConnectionError:q,setIsFatalError:Ie,setIsReconnectPending:U});a.useEffect(()=>{if(!W||h)return;if(typeof window>"u"){ke();return}const ae=window.requestAnimationFrame(()=>{ke()});return()=>{window.cancelAnimationFrame(ae)}},[M,ke,W,h]);const te=a.useMemo(()=>{const ae=wn[_r].stack;if(typeof window>"u")return(wn[c]??wn[_r]).stack;const tt=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return tt&&tt.trim().length>0?tt.trim():(wn[c]??wn[_r]).stack??ae},[c]),xe=a.useMemo(()=>rb(i),[i]),fe=`${k??"no-dir"}::${M??"no-tab"}`;if(a.useEffect(()=>{if(!W||h)return;const ae=ie.current;if(!ae)return;const Fe=()=>{ae.fit()};if(typeof window<"u"){const tt=window.requestAnimationFrame(()=>{Fe(),ke()}),xt=[220,400].map(Qe=>window.setTimeout(Fe,Qe));return()=>{window.cancelAnimationFrame(tt),xt.forEach(Qe=>window.clearTimeout(Qe))}}Fe()},[ke,W,h,ie,fe,z]),a.useEffect(()=>{if(!W||!h)return;let ae=null;const Fe=()=>{ae!==null&&window.cancelAnimationFrame(ae),ae=window.requestAnimationFrame(()=>{ae=null,ie.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Fe),()=>{window.removeEventListener("oc:keyboard-settled",Fe),ae!==null&&window.cancelAnimationFrame(ae)}},[W,ie,fe,h]),!A)return s.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!k)return s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[s.jsx("p",{children:"No working directory available for this session."}),s.jsx("button",{onClick:ne,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const je=!z||R||de||G,Ye=Z,_e=j?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(ga,{items:K,activeId:M,onSelect:Le,onClose:be,onCreate:ve})}),s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:ve,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"h-4 w-4"})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{ne()},disabled:de,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"h-4 w-4"})}),D?s.jsxs(Ne,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{k&&N(k,D)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,De=s.jsx(xb,{isTouchTerminal:m,activeModifier:Q,disabled:je,onKeyPress:H,onModifierToggle:He}),Ve=!n||m||S;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[_e&&n?Kd.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:_e}),n):null,m&&_e&&!n&&j?s.jsx(bb,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(ga,{items:K,activeId:M,onSelect:Le,onClose:be,onCreate:ve})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:ve,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"size-4"})}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:()=>{ne()},disabled:de,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"size-4"})}),D?s.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{k&&N(k,D)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"size-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(P,{name:"close",className:"size-4"})}):null]})}):null,!m&&Ve?s.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[_e&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[_e,t?s.jsx(Ne,{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:s.jsx(P,{name:"close",className:"h-4 w-4"})}):null]}):null,!m&&S&&b&&j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:De}):null,!m&&S&&!j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:De}):null]}):null,s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:xe.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Ye&&k&&j?j.tabs.map(ae=>{const Fe=ae.id===M;return s.jsx(gb,{directory:k,tabId:ae.id,sessionId:ae.terminalSessionId,sessionKey:`${k}::${ae.id}`,isActive:Fe,isTerminalVisible:W,terminal:r,theme:xe,fontFamily:te,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:X,onInput:Se,controllerRef:ie},ae.id)}):null}),!G&&me&&s.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:[s.jsx("span",{children:me}),Ae&&m&&s.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ue,disabled:de,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),m&&S?s.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:s.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:De})}):null]})},Bo=[{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"}],Lb=new Set(Bo.map(e=>e.id)),Ob=e=>typeof e=="string"&&Lb.has(e),Qy=e=>Ob(e)?e:"changes",hc=e=>e==="pull-requests"||e==="issues",Bb=e=>e?Bo:Bo.filter(t=>!hc(t.id)),Jy=(e,t)=>hc(e)?"changes":e,_b=48,Ub=96,vt=(e,...t)=>{try{e?.(...t)}catch{}},to=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},Xy=(e,t)=>{const n=a.useRef(t);n.current=t;const r=t.enabled;a.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"?Ub:_b;let d=!1,u=!1,f=!1,p=null,x=!1,y=0,m=0,h=0,b=0;const g=()=>{d=!1,u=!1,f=!1,p=null},S=()=>{const N=n.current,M=p,L=x;u&&M&&(vt(M==="left"?N.onLeftProgress:N.onRightProgress,L?1:0),vt(N.onDragEnd,M,L)),g()},w=()=>{S(),u||g()},E=N=>{const M=n.current;if(M.enabled===!1){u&&p?S():g();return}if(N.touches.length!==1){u&&p?S():g();return}const L=N.touches[0],K=o.getBoundingClientRect(),z=o.clientWidth,$=!!M.leftOpen,O=!!M.rightOpen,R=D=>Vg(D,o);if($||O){if(R(N.target)){g();return}if($&&O){const D=L.clientX<=K.left+c;L.clientX>=K.right-c?(p="right",x=!0):D?(p="left",x=!0):(p=$?"left":"right",x=!0)}else $?(p="left",x=!0):(p="right",x=!0);b=to(p==="left"?M.leftWidth:M.rightWidth,z),b<10&&(b=z||window.innerWidth||320),b<10&&(b=320),d=!0}else{if(R(N.target)){g();return}p=null,x=!1,b=0,d=!0}y=L.clientX,m=L.clientY,h=Date.now(),u=!1,f=!1},A=N=>{if(!d)return;if(N.touches.length!==1){w();return}const M=N.touches[0],L=M.clientX-y,K=M.clientY-m;if(!f){if(Math.abs(L)<ua&&Math.abs(K)<ua)return;if(Math.abs(K)>Math.abs(L)*An){g();return}if(!p){const O=n.current;p=L>0?"left":"right",b=to(p==="left"?O.leftWidth:O.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(p==="left"){if(!x&&L<=0){g();return}if(x&&L>=0){g();return}}else{if(!x&&L>=0){g();return}if(x&&L<=0){g();return}}f=!0,u=!0,vt(n.current.onDragStart,p)}if(!u)return;N.cancelable&&N.preventDefault();const z=n.current,$=fa(p,x,L,b);vt(p==="left"?z.onLeftProgress:z.onRightProgress,$)},k=(N,M)=>{if(!d){g();return}const L=N-y,K=M-m;if(!p&&!x&&Math.abs(L)>=ar&&Math.abs(K)<=Math.abs(L)*An){const I=n.current;p=L>0?"left":"right",b=to(p==="left"?I.leftWidth:I.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(!p){g();return}const z=Math.max(1,Date.now()-h),$=n.current;if(!u){const I=Math.abs(L),T=Math.abs(K);I>=ar&&T<=I*An?p==="left"&&!x&&L>0?(vt($.onLeftProgress,1),vt($.onLeftOpen)):p==="right"&&!x&&L<0?(vt($.onRightProgress,1),vt($.onRightOpen)):vt(p==="left"?$.onLeftProgress:$.onRightProgress,x?1:0):vt(p==="left"?$.onLeftProgress:$.onRightProgress,x?1:0);const W=p;g(),vt($.onDragEnd,W);return}const O=fa(p,x,L,b),R=qg({side:p,isOpenAtStart:x,dx:L,dt:z,progress:O}),D=p;vt(D==="left"?R?$.onLeftOpen:$.onLeftClose:R?$.onRightOpen:$.onRightClose),g(),vt($.onDragEnd,D,R)},j=N=>{const M=N.changedTouches[0];if(!M){g();return}const L=M.clientX-y,K=M.clientY-m;d&&(u||Math.abs(L)>=ar&&Math.abs(K)<=Math.abs(L)*An)&&N.cancelable&&N.preventDefault(),k(M.clientX,M.clientY)},v=()=>{w()};return o.addEventListener("touchstart",E,{passive:!0}),o.addEventListener("touchmove",A,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",v,{passive:!0}),()=>{try{u&&p&&S()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",E),o.removeEventListener("touchmove",A),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",v)}},[e,r])};function Zy({className:e="h-5 w-5"}){return s.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[s.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),s.jsx(P,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function ya({size:e,className:t,style:n,...r}){return s.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,...n},...r,children:s.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 zb=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,$b=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>Sr(t,n)?null:e,so=()=>Es.filter(e=>go.has(e.id)).map(e=>({...il(e)})),Kb=()=>{if(typeof window>"u")return bo;const e=window.localStorage.getItem("openInAppId");return e&&po(e)?e:bo};let no=!1,Qs=!1,ms=!1,ps=0,Tn=null;const wa=()=>{Tn&&(clearTimeout(Tn),Tn=null)},As=Bs()((e,t)=>({selectedAppId:Kb(),availableApps:so(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(no||typeof window>"u")return;no=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:so(),hasLoadedApps:u});return}const f=new Set(d.map(m=>m.name)),p=new Map(d.map(m=>[m.name,m.iconDataUrl??void 0])),y=Es.filter(m=>f.has(m.appName)||go.has(m.id)).map(m=>({...il(m),iconDataUrl:p.get(m.appName)}));e({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!rn()||!ur()||Qs||t().hasLoadedApps&&!d)return;const f=Es.map(p=>p.appName);wa(),Qs=!0,ms=!1,e({isScanning:!0});try{const{apps:p,success:x,hasCache:y,isCacheStale:m}=await Ri(f,d),h=x&&!y&&p.length===0&&ps<3;if(e({isCacheStale:y?m:!1}),n(p,x?!h:!1),x){if(h){const g=[800,1600,3200][ps]??3200;ps+=1,ms=!0,Tn=setTimeout(()=>{r()},g);return}ps=0,ms=!1;return}if(ps<3){const g=[1e3,3e3,7e3][ps]??7e3;ps+=1,ms=!0,Tn=setTimeout(()=>{r()},g)}}finally{Qs=!1,ms||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&po(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(ps=3,ms=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(no||t().initialize(),!rn()||!ur()||Qs||t().hasLoadedApps&&!n)return;const o=Es.map(i=>i.appName);wa(),n&&e({hasLoadedApps:!1}),Qs=!0,ms=!1,e({isScanning:!0});try{const{apps:i,hasCache:l,isCacheStale:c}=await Ri(o,n),d=new Set(i.map(x=>x.name)),u=new Map(i.map(x=>[x.name,x.iconDataUrl??void 0])),p=Es.filter(x=>d.has(x.appName)||go.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:p.length>0?p:so(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Qs=!1,ms||e({isScanning:!1})}},selectApp:async n=>{po(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await sl({openInAppId:n}))}})),Wb="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",Gb="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",ro=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Wb:e.id==="terminal"?Gb:void 0}),va=({label:e,iconDataUrl:t,fallbackIconDataUrl:n})=>{const[r,o]=a.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",l=t||n;return l&&!r?s.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):s.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})},Hb=({directory:e,className:t})=>{const n=As(m=>m.selectedAppId),r=As(m=>m.availableApps),o=As(m=>m.isCacheStale),i=As(m=>m.isScanning),l=As(m=>m.initialize),c=As(m=>m.loadInstalledApps),d=As(m=>m.selectApp);a.useEffect(()=>{l()},[l]);const u=rn()&&ur(),f=a.useMemo(()=>{const m=r.find(h=>h.id===n)??r.find(h=>h.id===bo)??r[0]??Es[0];return ro(m||Es[0])},[r,n]);if(!u||!e||r.length===0)return null;const p=async m=>{await bf(e,m.id,m.appName)||await rl(e,m.appName)},x=async m=>{await d(m.id),await p(m)},y=async()=>{(await xs(e)).ok&&oe.success("Path copied to clipboard")};return s.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:[s.jsx("button",{type:"button",onClick:()=>{p(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:s.jsx(va,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y()},children:[s.jsx(P,{name:"file-copy",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),s.jsx(nn,{}),r.map(m=>{const h=ro(m);return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[s.jsx(va,{label:m.label,iconDataUrl:m.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:m.label}),f.id===m.id?s.jsx(P,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[s.jsx(P,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},qb="\x1B",Yb=new RegExp(`${qb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Vb=/https?:\/\/[^\s<>'"`]+/gi,It="__pichamber_auto_discover_preview__",Qb=15e3,Jb=e=>{let t="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(t+=e[n])}return t},Xb=e=>{const t=(e||"").trim();if(!t)return null;const n=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Zb=e=>{const n=e.replace(Yb,"").match(Vb);if(!n||n.length===0)return null;const r=n.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const l=new URL(i);l.port&&l.port.length>0&&o.push({raw:i,parsed:l})}catch{}if(o.length>0){const i=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,x=f==="/"||f==="",y=!!(c.search||c.hash);let m=0;return u&&(m+=50),x&&(m+=30),m-=Math.min(p*5,20),y&&(m-=10),m};return o.sort((l,c)=>i(c)-i(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},ex=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],tx=["dev","start","preview","serve"];async function sx(e,t,n){if(!e)return null;const r=ox(t);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=ix(n);if(o){const i=await ax(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 nx(e)){const o=await rx(),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 nx(e){const t=`${e}/index.html`,n=await vr(t,e);return typeof n=="string"&&n.trim().length>0}async function rx(){try{const e=await nt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),n=typeof t?.port=="number"?t.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function ox(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(tx.some(o=>n.includes(o)))return t}return null}function ix(e){for(const{pattern:t}of ex)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function ax(e){const t=await vr(`${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 n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const i=await vr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function vr(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 n=nl()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await nt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function lx(e){try{const t=await vr(`${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 cx=(e,t,n)=>new Promise(r=>{let o=!1,i=null,l=null;const c=d=>{o||(o=!0,l&&clearTimeout(l),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():l=setTimeout(()=>c(!1),n)});function dx({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=Xa(),{terminal:o}=Os(),{isMobile:i}=dn(),l=ce(H=>H.terminalShell),c=ce(H=>H.terminalLoginShells.includes(H.terminalShell)),d=ce(H=>H.setSettingsPage),u=ce(H=>H.setSettingsDialogOpen),f=ce(H=>H.setSettingsProjectsSelectedId),p=ce(H=>H.openContextPreview),x=he(H=>H.ensureDirectory),y=he(H=>H.setTabLabel),m=he(H=>H.setTabIconKey),h=he(H=>H.setActiveTab),b=he(H=>H.setConnecting),g=he(H=>H.setTabSessionId),S=he(H=>H.setTabPreviewUrl),w=he(H=>H.projectActionRuns),E=he(H=>H.setProjectActionRun),A=he(H=>H.updateProjectActionRunStatus),k=he(H=>H.removeProjectActionRun),[j,v]=a.useState([]),[N,M]=a.useState(null),[L,K]=a.useState(!1),z=a.useRef({}),$=a.useRef({}),O=a.useRef({}),R=a.useRef({}),D=a.useRef(new Set),I=a.useRef(0),T=e?.id??null,W=e?.path??"",Z=a.useMemo(()=>T?{id:T,path:W}:null,[T,W]),F=a.useCallback(async H=>{await Oa(H)},[]),me=a.useCallback(async()=>{if(!Z)return;const H=I.current+1;I.current=H,K(!0);try{const de=await ao(Z);if(I.current!==H)return;const ne=de.actions;v(ne),M(ue=>ue===It||ue&&ne.some(ve=>ve.id===ue)?ue:null)}catch{if(I.current!==H)return}finally{I.current===H&&K(!1)}},[Z]),q=a.useMemo(()=>El(t||Z?.path||""),[t,Z?.path]),Ae=a.useMemo(()=>N?j.find(H=>H.id===N)??null:null,[j,N]),Ie=a.useMemo(()=>({id:It,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),G=!i,U=a.useMemo(()=>G?[Ie,...j]:j,[j,Ie,G]);a.useEffect(()=>{me()},[me]),a.useEffect(()=>{if(typeof window>"u")return;const H=de=>{const ne=de.detail;T&&(ne?.projectId&&ne.projectId!==T||me())};return window.addEventListener(jo,H),()=>{window.removeEventListener(jo,H)}},[me,T]),a.useEffect(()=>{N&&(N===It&&G||j.some(H=>H.id===N)||M(null))},[j,G,N]),a.useEffect(()=>{const H=()=>{const de=he.getState(),ne=de.sessions,ue=de.projectActionRuns;for(const[ve,Le]of Object.entries(ue)){const te=ne.get(Le.directory)?.tabs.find(Fe=>Fe.id===Le.tabId);if(!te||te.terminalSessionId!==Le.sessionId){k(ve);continue}const xe=$.current[ve]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};$.current[ve]=xe;const fe=U.find(Fe=>Fe.id===Le.actionId),je=de.getBuffer(Le.directory,Le.tabId).chunks;if(!fe||je.length===0)continue;const Ye=je.filter(Fe=>xe.lastSeenChunkId===null||Fe.id>xe.lastSeenChunkId);if(Ye.length===0)continue;const _e=Ye.map(Fe=>Fe.data).join(""),De=`${xe.tail}${_e}`,Ve=!xe.openedUrl&&fe.autoOpenUrl===!0?Zb(De):null,ae=Ye[Ye.length-1]?.id??xe.lastSeenChunkId;if(xe.lastSeenChunkId=ae,xe.tail=De.slice(-512),Ve)if(xe.openedUrl=!0,xe.openInPreview){const Fe=ue[ve];Fe&&(S(Fe.directory,Fe.tabId,Ve,{locked:!1,autoOpened:!1}),Fe.status==="waiting-for-preview"&&A(ve,"running"),window.clearTimeout(R.current[ve]),delete R.current[ve],p(Fe.directory,Ve))}else F(Ve),oe.success("Opened URL from action output");$.current[ve]=xe}for(const ve of Object.keys($.current))ue[ve]||(delete $.current[ve],window.clearTimeout(R.current[ve]),delete R.current[ve])};return H(),he.subscribe((de,ne)=>{(de.sessions!==ne.sessions||de.buffers!==ne.buffers)&&H()})},[U,p,F,w,k,S,A]);const Y=a.useCallback(async(H,de={})=>{if(!q)throw new Error("No active directory");const ne=as(q,H.id);x(q);const ue=he.getState(),ve=ue.getDirectoryState(q);let Le=z.current[ne]||null;const be=Le?!!ve?.tabs.some(fe=>fe.id===Le):!1;(!Le||!be)&&(Le=ue.createTab(q),z.current[ne]=Le),y(q,Le,`Action: ${H.name}`),m(q,Le,H.icon||"play"),h(q,Le),de.revealTerminal!==!1&&ce.getState().openContextPanelTab(q,{mode:"terminal"});const xe=he.getState().getDirectoryState(q)?.tabs.find(fe=>fe.id===Le);return{key:ne,tabId:Le,sessionId:xe?.terminalSessionId??null}},[x,q,h,m,y]),X=a.useCallback(async H=>{if(!n&&i)return;if(!q){oe.error("No active directory for action");return}const de=as(q,H.id),ne=w[de];if(!(ne&&ne.status==="running")&&!D.current.has(de)){D.current.add(de);try{const ue=H.id===It?await(async()=>{const[De,Ve]=await Promise.all([ao({id:Z?.id??"",path:q}),lx(q)]),ae=await sx(q,De.actions,Ve);if(!ae)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:It,name:"Auto-discover",command:ae.command,icon:"scan-2",autoOpenUrl:!0,openUrl:ae.previewUrlHint||""}})():H,ve=ue.autoOpenUrl===!0&&(ue.openUrl||"").trim().length>0,Le=!ve&&H.id!==It,{key:be,tabId:te,sessionId:xe}=await Y(ue,{revealTerminal:Le});let fe=xe;if(!fe){b(q,te,!0);try{fe=(await o.createSession({cwd:q,sessionId:te,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,g(q,te,fe)}finally{b(q,te,!1)}}if(!fe)throw new Error("Failed to create terminal session");O.current[be]?.(),b(q,te,!0);const je=o.connect(fe,{onEvent:De=>{De.type==="snapshot"&&(he.getState().replaceBuffer(q,te,De.data??"",De.sequence??0),he.getState().setConnecting(q,te,!1)),De.type==="data"&&typeof De.data=="string"&&De.data.length>0&&he.getState().appendToBuffer(q,te,De.data,De.sequence,De.replayData),De.type==="exit"&&(he.getState().setTabLifecycle(q,te,"exited"),he.getState().setConnecting(q,te,!1),he.getState().removeProjectActionRun(be),delete $.current[be],O.current[be]?.(),delete O.current[be],window.clearTimeout(R.current[be]),delete R.current[be])},onError:(De,Ve)=>{he.getState().setConnecting(q,te,!1),Ve&&(he.getState().setTabLifecycle(q,te,"exited"),he.getState().setTabSessionId(q,te,null),he.getState().removeProjectActionRun(be))}});O.current[be]=je.close;const Ye=ue.autoOpenUrl?Xb(ue.openUrl):null;E({key:be,directory:q,actionId:ue.id,tabId:te,sessionId:fe,status:ue.id===It&&!Ye?"waiting-for-preview":"running"}),window.clearTimeout(R.current[be]),delete R.current[be],ue.id===It&&!Ye&&(R.current[be]=window.setTimeout(()=>{const De=he.getState(),Ve=De.projectActionRuns[be];De.updateProjectActionRunStatus(be,"running"),Ve&&(De.setActiveTab(Ve.directory,Ve.tabId),ce.getState().openContextPanelTab(Ve.directory,{mode:"terminal"})),delete R.current[be]},Qb)),$.current[be]={lastSeenChunkId:null,openedUrl:!!Ye||ve,tail:"",openInPreview:ue.id===It};const _e=Jb(ue.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
-
`));await o.sendInput(fe,`${_e}\r`),Ye?(S(q,te,Ye,{locked:!0,autoOpened:!0}),p(q,Ye),oe.success("Opened action URL")):ve?(S(q,te,null,{locked:!0}),oe.error("Invalid custom URL format")):S(q,te,null,{locked:!1,autoOpened:!1})}catch(ue){k(de),delete $.current[de],O.current[de]?.(),delete O.current[de],window.clearTimeout(R.current[de]),delete R.current[de],oe.error(ue instanceof Error?ue.message:"Failed to run action")}finally{D.current.delete(de)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Y,n,i,q,c,l,p,w,k,b,E,S,g,Z?.id,o]),se=a.useCallback(async H=>{const de=as(q,H.id),ne=w[de];if(!ne)return;A(de,"stopping");const ue=cx(o,ne.sessionId,1e3);try{await o.sendInput(ne.sessionId,"")}catch{}const ve=await ue;if(he.getState().getDirectoryState(ne.directory)?.tabs.find(te=>te.id===ne.tabId)?.terminalSessionId===ne.sessionId&&!ve){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ne.sessionId})}catch{}else try{await o.close(ne.sessionId)}catch{}g(ne.directory,ne.tabId,null)}k(de),delete $.current[de],O.current[de]?.(),delete O.current[de],window.clearTimeout(R.current[de]),delete R.current[de]},[q,w,k,g,o,A]),we=a.useCallback(()=>{const H=Ae??U[0];if(!H)return;const de=as(q,H.id),ne=w[de];if(ne?.status!=="stopping"){if(ne){se(H);return}X(H)}},[U,q,X,w,Ae,se]),pe=a.useCallback((H,de=!1)=>{if(M(H.id),!de){X(H);return}const ne=as(q,H.id),ue=w[ne];if(ue?.status!=="stopping"){if(ue){se(H);return}X(H)}},[q,X,w,se]),V=a.useCallback(()=>{Z?.id&&(f(Z.id),d("projects"),u(!0))},[u,d,f,Z?.id]),Q=Ae??U[0]??null,ie=Q?w[as(q,Q.id)]:null,ke=he(H=>ie?H.sessions.get(ie.directory)?.tabs.find(de=>de.id===ie.tabId)?.previewUrl??null:null),Se=!!((n||!i)&&Z&&q),He=Ae??U[0]??null;return{shouldRender:Se,isLoading:L,normalizedDirectory:q,resolvedSelected:He,displayActions:U,projectActionRuns:w,selectedRunPreviewUrl:ke,handlePrimaryClick:we,handleSelectAction:pe,openProjectActionsSettings:V,openContextPreview:p}}const Sa=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:x,handleSelectAction:y,openProjectActionsSettings:m,openContextPreview:h}=dx({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const b=d.icon||"play",g=d.id===It?"scan-2":Mn[b]||"play",S=as(c,d.id),w=f[S],E=w?.status==="stopping",A=w?.status==="waiting-for-preview",k=!!(w&&p),j=()=>{!w||!p||h(w.directory,p)},v=d.id===It;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",disabled:l||E,className:_("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":w?`Stop ${d.name}`:`Run ${d.name}`,children:E||A?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),v?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:j,children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",L=N.id===It?"scan-2":Mn[M]||"play",K=as(c,N.id),z=f[K],$=!!z,O=z?.status==="stopping";return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),O||z?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]}):s.jsxs("div",{className:_("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,disabled:l||E,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":w?`Stop ${d.name}`:`Run ${d.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:E||A?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),v?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j,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:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",L=N.id===It?"scan-2":Mn[M]||"play",K=as(c,N.id),z=f[K],$=!!z,O=z?.status==="stopping";return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),O||z?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.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 cr(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 ux=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 fx({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const u=Je();try{const f=await nt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);u===Je()&&r(p)}catch{u===Je()&&r(null)}},[]);a.useEffect(()=>(o(),Un(()=>{o()})),[o]);const i=cr(n),l=ux(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Gt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(fn,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),s.jsx(We,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(qt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx(P,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:l})]}),c?s.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),s.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[s.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),s.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:()=>{xs(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),s.jsx(P,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const hx=({isMobile:e})=>{const n=Os().github??null,r=kr(i=>i.refresh),o=tm();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(fn,"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:[s.jsx(P,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),s.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},mx=a.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:l,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:p,remoteUpdateError:x,onOpenRemoteUpdate:y}){return s.jsxs(Gt,{open:l,onOpenChange:m=>{c(m),m&&d()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(fn,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),s.jsx(We,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(qt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?s.jsxs("div",{children:[o?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:p?"Looking for updates...":x||"This instance is up to date."})]}),f?.available?s.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:y,children:"Update"}):null]})}),s.jsx(Bu,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),px=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(ts,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(vs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ls,{children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),gx=e=>{const t=e.trim();if(!t)return"";const n=t.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),i=`${r} ${o}`.trim();return n.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},kn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},bx=a.lazy(()=>mt(()=>import("./SessionSwitcherDropdown-CA64t2xd.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),ew=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{Wt("ui.header.render");const c=ce(B=>B.setSessionSwitcherOpen),d=ce(B=>B.toggleSidebar),u=ce(B=>B.isSidebarOpen),f=ce(B=>B.activeMainTab),p=ce(B=>B.setActiveMainTab),x=ce(B=>B.shortcutOverrides);ce(B=>B.timeFormatPreference),Os();const y=Te(B=>!!B.newSessionDraft?.open),m=Te(B=>B.currentSessionId),h=Va(m??""),b=_u(m),g=a.useMemo(()=>{if(!b)return null;const B=b;return{title:b.title??null,directory:B.directory??null,created:b.time?.created??null,slug:B.slug??null,shareUrl:b.share?.url??null,parentId:b.parentID??null,messageCount:typeof b.messageCount=="number"?b.messageCount:null}},[b]),S=ct(oo(B=>{if(!B.activeProjectId)return null;const le=B.projects.find(ye=>ye.id===B.activeProjectId);return le?{id:le.id,path:le.path,label:le.label}:null})),w=on(B=>B.homeDirectory),E=a.useMemo(()=>{if(!S)return null;const B=S.label?.trim();if(B)return B;const le=S.path.split(/[\\/]/).filter(Boolean);return le[le.length-1]??null},[S]),{isMobile:A}=dn(),{enabled:k}=Wo(),j=!!(k&&i&&o!==void 0),v=a.useMemo(()=>[...Bb(l)],[l]),[N,M]=a.useState(!1),L=a.useRef(null),[K,z]=a.useState(()=>typeof window>"u"?!1:rn()),$=a.useMemo(()=>ol(),[]),O=Uu(),[R,D]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),T=Za(),W=a.useMemo(()=>{if(typeof window>"u")return null;const B=window.__PICHAMBER_MACOS_MAJOR__;if(typeof B=="number"&&Number.isFinite(B)&&B>0)return B;if(typeof navigator>"u")return null;const le=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!le)return null;const ye=Number.parseInt(le[1],10),Be=Number.parseInt(le[2],10);return Number.isNaN(ye)?null:ye===10?Be:ye},[]);Re.useEffect(()=>{typeof window>"u"||z(rn())},[]);const Z=ce(B=>B.isSessionSwitcherOpen),[F,me]=a.useState(!1),[q,Ae]=a.useState("Local"),[Ie,G]=a.useState(!0),[U,Y]=a.useState(()=>cr(null)),[X,se]=a.useState(!1),[we,pe]=a.useState(null),[V,Q]=a.useState(!1),[ie,ke]=a.useState(null),Se=a.useRef(0),He=a.useMemo(()=>gx(q),[q]),H=a.useCallback(async()=>{if(typeof window>"u"||!K)return;const B=Je(),le=()=>Je()===B;try{const ye=await nt("/api/version");if(!le())return;const Be=ye.ok?await ye.json().catch(()=>null):null;if(!le())return;if(Y(cr(Be)),ur()){Ae("Local"),G(!0);return}G(!1);const re=await xf();if(!le())return;const qe=yf(),Nt=wf([vf(qe),...re.hosts]);if(Nt.id===Sf){Ae("Local"),G(!0);return}Ae(jf(Nt.label.trim()||"Instance"))}catch{le()&&(Ae("Local"),G(!0),Y(cr(null)))}},[K]);Re.useEffect(()=>(H(),Un(()=>{Se.current+=1,pe(null),ke(null),Q(!1),se(!1),H()})),[H]);const de=a.useCallback(async()=>{const B=Se.current+1;Se.current=B;const le=Je(),ye=()=>Se.current===B&&Je()===le;if(Ie){pe(null),ke(null);return}Q(!0),ke(null);try{const Be=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await nt(`/api/pi/update-check?${Be.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const qe=await re.json();if(!ye())return;pe({available:qe.available??!1,version:qe.version,currentVersion:qe.currentVersion??"unknown",body:qe.body,nextSuggestedCheckInSec:typeof qe.nextSuggestedCheckInSec=="number"?qe.nextSuggestedCheckInSec:void 0,packageManager:qe.packageManager,updateCommand:qe.updateCommand,channel:qe.channel==="rc"?"rc":"stable"})}catch(Be){if(!ye())return;pe(null),ke(Be instanceof Error?Be.message:"Failed to check remote instance updates")}finally{ye()&&Q(!1)}},[Ie]);a.useEffect(()=>Th(()=>{Ie||de()}),[de,Ie]),a.useEffect(()=>{Se.current+=1,pe(null),ke(null),Q(!1),se(!1)},[Ie,q]),a.useEffect(()=>{if(!K||Ie)return;const B=3e3,le=3600*1e3;let ye=!1,Be=null;const re=qe=>{Be=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){re(le);return}de().finally(()=>{ye||re(le)})},qe)};return re(B),()=>{ye=!0,Be!==null&&window.clearTimeout(Be)}},[de,Ie,q,K]);const ne=a.useCallback(()=>{if(we?.available){se(!0);return}de()},[de,we?.available]),ue=m?g??null:null,ve=a.useRef(null),[Le,be]=a.useState(0);a.useEffect(()=>{if(!m){ve.current&&(ve.current=null,be(Be=>Be+1));return}if(ue){ve.current={sessionId:m,session:ue,expiresAt:Date.now()+2e3};return}const B=ve.current;if(!B||B.sessionId!==m)return;const le=B.expiresAt-Date.now();if(le<=0){ve.current=null,be(Be=>Be+1);return}const ye=window.setTimeout(()=>{ve.current?.sessionId===m&&(ve.current=null),be(Be=>Be+1)},le);return()=>{window.clearTimeout(ye)}},[m,ue]);const te=(()=>{if(ue)return ue;if(!m)return null;const B=ve.current;return B&&B.sessionId===m&&B.expiresAt>Date.now()?B.session:null})(),xe=a.useMemo(()=>{const B=typeof te?.directory=="string"?te.directory:"";return kn(B||"")},[te?.directory]),fe=Te(B=>B.newSessionDraft?.open?kn(B.newSessionDraft.directoryOverride??""):""),je=a.useMemo(()=>zb({sessionDirectory:xe,draftDirectory:fe,isNewSessionDraftOpen:y}),[fe,y,xe]),_e=Ya(je||null),De=a.useMemo(()=>$b({activeProjectLabel:E,openDirectory:je,homeDirectory:w}),[E,w,je]),Ve=!!(De||_e),ae=a.useMemo(()=>m?gs(te,"Untitled session"):De??"PiChamber",[te,m,De]),Fe=zu(),tt=Te(B=>B.updateSessionTitle),xt=Te(B=>B.archiveSessions),Qe=Te(B=>B.deleteSessions),[pt,Xe]=a.useState(!1),[Ss,St]=a.useState(!1),st=a.useRef(!1),[Et,Lt]=a.useState(""),[Yt,jt]=a.useState(null),Ot=a.useRef(null);a.useEffect(()=>{st.current=!1,St(!1),Xe(!1),Lt(""),jt(null)},[m]);const yt=a.useCallback(()=>{m&&(Lt(te?.title?.trim()||ae),Xe(!0))},[te?.title,m,ae]),rt=a.useCallback(async()=>{if(!m)return;const B=Et.trim();B&&B!==te?.title?.trim()&&await tt(m,B),Xe(!1)},[te?.title,m,Et,tt]);a.useEffect(()=>{if(!pt)return;const B=le=>{const ye=le.target;(!ye||!Ot.current?.contains(ye))&&rt()};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[pt,rt]);const dt=a.useCallback(()=>{m&&xs(m).then(B=>{oe[B.ok?"success":"error"](B.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[m]),Vt=a.useCallback(async()=>{if(!m||!je){oe.error("Nothing to export");return}try{await Fe.syncSession(m)}catch{oe.error("Failed to load the complete session history");return}const B=[];if(B.length===0){oe.error("Nothing to export");return}const le=oc(B,te?.title??null),ye=lc(te?.title??null);await ac(le,ye)||ic(le,ye),oe.success("Session exported")},[te?.title,m,je,Fe]);h?.type==="busy"||h?.type;const us=a.useCallback(async()=>{if(!m||!Yt)return;const B=$u(),le=[m];for(let qe=0;qe<le.length;qe+=1){const Nt=le[qe];for(const gt of B)gt.parentID===Nt&&!le.includes(gt.id)&&le.push(gt.id)}const ye=Yt;if(jt(null),(ye==="archive"?await xt(le):await Qe(le)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[xt,m,Qe,Yt]),Ce=ce(B=>B.isArchivePageOpen),Ue=a.useMemo(()=>Ce?{title:"Archive",subtitle:null}:null,[Ce]),ge=a.useMemo(()=>kn(je||S?.path||""),[S?.path,je]),Oe=a.useCallback(()=>{ge&&xs(ge).then(B=>{oe[B.ok?"success":"error"](B.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[ge]),Ge=a.useMemo(()=>S?{id:S.id,path:S.path}:null,[S]),it=a.useRef(null);a.useEffect(()=>{!Ge||!ge||(it.current={projectRef:Ge,directory:ge})},[ge,Ge]);const kt=a.useMemo(()=>Ge&&ge?{projectRef:Ge,directory:ge}:it.current,[ge,Ge]),ot=a.useCallback(()=>{if(typeof document>"u")return;const B=document.activeElement;if(!B)return;const le=B.tagName;(le==="INPUT"||le==="TEXTAREA"||le==="SELECT"||B.isContentEditable)&&B.blur()},[]),Bt=a.useCallback(()=>{if(A){ot(),c(!Z);return}d()},[ot,A,Z,c,d]),ns=a.useCallback(()=>{Dn("desktop_open_draft_mini_chat_window",{directory:kn(je||S?.path||""),projectId:S?.id??null,apiBaseUrl:mo(),clientToken:ho()}).catch(B=>{console.warn("[header] failed to open draft mini chat window",B)})},[S?.id,S?.path,je]),Ze=a.useCallback(()=>{if(y){ns();return}m&&Dn("desktop_open_session_mini_chat_window",{sessionId:m,directory:kn(je||S?.path||""),apiBaseUrl:mo(),clientToken:ho()}).catch(B=>{console.warn("[header] failed to open session mini chat window",B)})},[S?.path,m,ns,y,je]),Rt=fn,Dt=dm,wt=a.useMemo(()=>n?"sessions":j?r&&o?o:null:r?"git":f,[f,j,n,r,o]),ut=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&Z&&c(!1)},[Z,n,e,t,r,c]),_s=a.useCallback(()=>{e?.()},[e]),Us=a.useCallback(()=>{t?.()},[t]),js=a.useMemo(()=>K&&I&&!R?"5.5rem":O?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!K||T?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,R,I,O,T]);Re.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",js)},[js]);const ks=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ct=u?"0px":K&&T?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":k?"2.75rem":"2.5rem";Re.useEffect(()=>{if(!K||!I){D(!1);return}let B=!1;const le=async()=>{try{const Be=await Dn("desktop_is_window_fullscreen");B||D(Be===!0)}catch{B||D(!1)}},ye=()=>{le()};return le(),window.addEventListener("pichamber:window-resized",ye),()=>{B=!0,window.removeEventListener("pichamber:window-resized",ye)}},[K,I]);const rs=a.useMemo(()=>!K||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[K,I,W]),At=a.useMemo(()=>{if(!(K&&!T))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,T]),os=a.useCallback(()=>{if(typeof document>"u")return;const B=L.current?.getBoundingClientRect().height;if(B){const le=`${B}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==le&&ye.setProperty("--oc-header-height",le)}},[]);Re.useEffect(()=>{if(typeof window>"u")return;os();const B=L.current;if(!B||typeof ResizeObserver>"u")return()=>{};let le=0;const ye=()=>{le||(le=requestAnimationFrame(()=>{le=0,os()}))},Be=new ResizeObserver(ye);return Be.observe(B),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{le&&cancelAnimationFrame(le),Be.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[os]),Re.useEffect(()=>{os()},[os,A,rs]);const is=a.useCallback(async B=>{const le=B.target;le.closest(".app-region-no-drag")||le.closest("button, a, input, select, textarea")||B.button===0&&K&&await Ku()},[K]),at=a.useMemo(()=>A?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[A]),_t=a.useCallback(B=>Ho(dr(B,x)),[x]);Re.useEffect(()=>{!A&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,A,p]),Re.useEffect(()=>{const B=le=>{if(kf(le)&&!le.shiftKey&&!le.altKey){const ye=parseInt(le.key,10);ye>=1&&ye<=at.length&&(le.preventDefault(),A&&(ot(),ut()),p(at[ye-1].id))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[ot,ut,A,p,at]),Re.useEffect(()=>{const B=le=>{const ye=dr("toggle_services_menu",x);if(Cf(le,ye)){le.preventDefault(),F?me(!1):(me(!0),H());return}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[x,F,H]);const zs=B=>{const le=f===B.id,ye=B.icon==="diff",Be=ye?null:B.icon,re=B.id==="chat",qe=gt=>ye?s.jsx(ya,{size:gt}):Be?s.jsx(P,{name:Be,className:`h-${gt/4} w-${gt/4}`}):null,Nt=s.jsxs("button",{type:"button",onClick:()=>p(B.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",le?"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",re&&!A&&"min-w-[100px] justify-center"),"aria-label":B.label,"aria-selected":le,role:"tab",children:[A?qe(20):s.jsxs(s.Fragment,{children:[qe(16),s.jsx("span",{className:"header-tab-label",children:B.label})]}),B.badge!==void 0&&B.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:B.badge})]});return s.jsx(a.Fragment,{children:Nt},B.id)},Pt=s.jsxs(s.Fragment,{children:[s.jsx(Hb,{directory:ge,className:"mr-1"}),K?s.jsx(mx,{isDesktopApp:K,currentInstanceLabel:q,compactCurrentInstanceLabel:He,currentInstanceIsLocal:Ie,currentInstanceIcon:U,isDesktopServicesOpen:F,setIsDesktopServicesOpen:me,refreshCurrentInstanceLabel:H,shortcutLabel:_t,remoteUpdateInfo:we,remoteUpdateChecking:V,remoteUpdateError:ie,onOpenRemoteUpdate:ne}):s.jsx(fx,{open:F,onOpenChange:me}),s.jsx(hx,{isMobile:A})]}),pn=$&&(y||!!m),$s=()=>s.jsxs("div",{onMouseDown:is,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",rs),style:At,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ks}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ct}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ue?s.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:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Ue.title}),Ue.subtitle?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:Ue.subtitle})]}):null]}):s.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:s.jsx(a.Suspense,{fallback:s.jsx("button",{type:"button",className:Rt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(bx,{align:"start",children:s.jsx("button",{type:"button",className:Rt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[pt?s.jsxs("form",{ref:Ot,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:B=>{B.preventDefault(),rt()},children:[s.jsx("input",{value:Et,onChange:B=>Lt(B.target.value),autoFocus:!0,onKeyDown:B=>{B.stopPropagation(),B.key==="Escape"&&Xe(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>Xe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:y?"New session":ae}),Ve?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[De?s.jsx("span",{className:"truncate",children:De}):null,_e?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(P,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:_e})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!y&&!pt?s.jsxs(Gt,{open:Ss,onOpenChange:St,onOpenChangeComplete:B=>{!B&&st.current&&(st.current=!1,yt())},children:[s.jsx(Ht,{asChild:!0,children:s.jsx(Ne,{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:s.jsx(P,{name:"more",className:"size-4"})})}),s.jsxs(qt,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ht,{onClick:()=>{st.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ht,{onClick:dt,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ht,{onClick:Oe,disabled:!ge,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(nn,{}),s.jsxs(ht,{onClick:()=>{Vt()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(nn,{}),s.jsxs(ht,{onClick:()=>jt("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ht,{className:"text-destructive focus:text-destructive",onClick:()=>jt("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),at.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:at.map(B=>zs(B))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Pl,{}),kt?s.jsx(Sa,{projectRef:kt.projectRef,directory:kt.directory,className:"mr-1"}):null,s.jsx(um,{visible:pn,title:y?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:y?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Ze,className:_(Rt,"mr-1"),Icon:"picture-in-picture-2"}),Pt,s.jsx(Wu,{visible:T})]})]})]}),gn=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ks}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ct}})]}),!k&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:_s,className:_(Dt,wt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(P,{name:"layout-left",className:"h-5 w-5"})}):Z?s.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:s.jsx(P,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Bt,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:s.jsx(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&Z&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!Z||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!j&&s.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:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.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:at.map(B=>{const le=f===B.id,ye=B.icon==="diff",Be=ye?null:B.icon;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{A&&(ot(),ut()),p(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(Dt,"relative rounded-lg",wt===B.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?s.jsx(ya,{className:"h-5 w-5"}):Be?s.jsx(P,{name:Be,className:"h-5 w-5"}):null,B.badge!==void 0&&B.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:B.badge}),B.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),s.jsx(We,{children:s.jsx("p",{children:B.label})})]},B.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[j&&s.jsxs(s.Fragment,{children:[s.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:v.map(B=>{const le=r&&o===B.id;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{A&&(ot(),ut()),M(!1),i?.(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(Dt,"relative h-11 w-11 rounded-lg",le&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:B.icon,className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:B.label})})]},B.id)})}),s.jsx(cm,{open:N,onOpenChange:M,currentSessionId:m,effectiveDirectory:je||null,isNewSessionDraftOpen:y})]}),kt&&s.jsx(Sa,{projectRef:kt.projectRef,directory:kt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!j?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Us,className:_(Dt,"relative",wt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(P,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),fs=_("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:L,className:fs,style:{"--padding-scale":"1"},children:A?gn():$s()}),s.jsx(px,{action:Yt,onClose:()=>jt(null),sessionTitle:ae,onConfirm:()=>{us()}}),s.jsx(jl,{open:X,onOpenChange:se,info:we,downloading:!1,downloaded:!1,progress:null,error:ie,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},ja="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",xx="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",tw=()=>{const e=ce(y=>y.isSidebarOpen),t=ce(y=>y.toggleSidebar),n=ce(y=>y.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Ho(dr("toggle_sidebar",n)),l=Za(),{enabled:c}=Wo(),d=!e,u=l,f=d||u,p=u,x=a.useCallback(()=>{Dn("desktop_show_app_menu").catch(y=>{console.warn("[titlebar] failed to open app menu",y)})},[]);return a.useEffect(()=>{if(typeof document>"u")return;const y=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},m=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const h=o.current,b=r.current;if(!h||!b){y(0),m(0);return}const g=()=>{const w=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(w),m(b.getBoundingClientRect().width)};if(g(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(g);return S.observe(h),S.observe(b),()=>{S.disconnect()}},[p]),f?s.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:s.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(ja,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?xx:ja,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},ka=200,yx="cubic-bezier(0.22, 1, 0.36, 1)",sw=e=>{const t=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=a.useState(e),[o,i]=a.useState(e);return a.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 l=window.setTimeout(()=>i(!1),ka);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${ka}ms ${yx}`}},nw=()=>{al()},rw=e=>{Te.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ce.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),al(),on.getState().resetForRuntimeSwitch(),Gu.getState().resetForRuntimeSwitch(),Hu.getState().resetForRuntimeSwitch(),qu(),Af(),Nf(),Xu(),Yu.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ct.getState().resetForRuntimeSwitch(),Vu(),Qu(),Kf.getState().reset(),If.getState().resetForRuntimeSwitch(),za.getState().resetForRuntimeSwitch(e.runtimeKey),co.getState().resetForRuntimeSwitch(e.runtimeKey),Ef(),Ts.getState().resetForRuntimeSwitch(e.runtimeKey),Ju.getState().resetForRuntimeSwitch(),es.getState().resetForRuntimeSwitch(),bt.getState().resetForRuntimeSwitch(e.runtimeKey),Rf.getState().resetForRuntimeSwitch(e.runtimeKey),Te.getState().restoreForRuntimeSwitch(e.runtimeKey),ce.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=ce.getState();xo({sessionId:Te.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Ph as $,Ny as A,Kx as B,ay as C,ua as D,iy as E,Ux as F,Qx as G,ew as H,Vo as I,Yx as J,Rh as K,Nl as L,Dl as M,Pn as N,_x as O,Jh as P,Wx as Q,Ih as R,Gy as S,Vy as T,jl as U,Mh as V,Fx as W,Xx as X,Al as Y,$n as Z,ty as _,cm as a,Ky as a$,zn as a0,Cl as a1,Jx as a2,$x as a3,Nh as a4,ry as a5,sy as a6,kr as a7,ny as a8,oy as a9,Ay as aA,Cy as aB,uy as aC,jy as aD,Sy as aE,wy as aF,Ar as aG,Nr as aH,Ir as aI,Ps as aJ,Zl as aK,nm as aL,rm as aM,Ui as aN,Zy as aO,As as aP,bs as aQ,es as aR,Xl as aS,zl as aT,_n as aU,Ul as aV,zx as aW,Mx as aX,My as aY,Iy as aZ,Ty as a_,ey as aa,Gx as ab,Hx as ac,qx as ad,vy as ae,Hh as af,Vx as ag,kl as ah,ch as ai,Eh as aj,Lx as ak,dh as al,ah as am,fy as an,cy as ao,ly as ap,dy as aq,yy as ar,xy as as,my as at,hy as au,py as av,sm as aw,by as ax,gy as ay,ky as az,An as b,Wy as b0,tm as b1,Oy as b2,Fy as b3,Ry as b4,Ly as b5,_y as b6,Uy as b7,zy as b8,$y as b9,By as ba,Py as bb,Ey as bc,Ro as bd,Xi as be,Ns as bf,jn as bg,mn as bh,xp as bi,hn as bj,Dy as bk,Hg as c,Hy as d,ar as e,Bb as f,qy as g,bb as h,Vg as i,Qy as j,hc as k,sw as l,Xy as m,tw as n,nw as o,rw as p,Ox as q,Jy as r,Yy as s,Bx as t,am as u,Tx as v,Px as w,Dh as x,Zx as y,Ah as z};
|
|
62
|
+
`));await o.sendInput(fe,`${_e}\r`),Ye?(S(q,te,Ye,{locked:!0,autoOpened:!0}),p(q,Ye),oe.success("Opened action URL")):ve?(S(q,te,null,{locked:!0}),oe.error("Invalid custom URL format")):S(q,te,null,{locked:!1,autoOpened:!1})}catch(ue){k(de),delete $.current[de],O.current[de]?.(),delete O.current[de],window.clearTimeout(R.current[de]),delete R.current[de],oe.error(ue instanceof Error?ue.message:"Failed to run action")}finally{D.current.delete(de)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Y,n,i,q,c,l,p,w,k,b,E,S,g,Z?.id,o]),se=a.useCallback(async H=>{const de=as(q,H.id),ne=w[de];if(!ne)return;A(de,"stopping");const ue=cx(o,ne.sessionId,1e3);try{await o.sendInput(ne.sessionId,"")}catch{}const ve=await ue;if(he.getState().getDirectoryState(ne.directory)?.tabs.find(te=>te.id===ne.tabId)?.terminalSessionId===ne.sessionId&&!ve){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ne.sessionId})}catch{}else try{await o.close(ne.sessionId)}catch{}g(ne.directory,ne.tabId,null)}k(de),delete $.current[de],O.current[de]?.(),delete O.current[de],window.clearTimeout(R.current[de]),delete R.current[de]},[q,w,k,g,o,A]),we=a.useCallback(()=>{const H=Ae??U[0];if(!H)return;const de=as(q,H.id),ne=w[de];if(ne?.status!=="stopping"){if(ne){se(H);return}X(H)}},[U,q,X,w,Ae,se]),pe=a.useCallback((H,de=!1)=>{if(M(H.id),!de){X(H);return}const ne=as(q,H.id),ue=w[ne];if(ue?.status!=="stopping"){if(ue){se(H);return}X(H)}},[q,X,w,se]),V=a.useCallback(()=>{Z?.id&&(f(Z.id),d("projects"),u(!0))},[u,d,f,Z?.id]),Q=Ae??U[0]??null,ie=Q?w[as(q,Q.id)]:null,ke=he(H=>ie?H.sessions.get(ie.directory)?.tabs.find(de=>de.id===ie.tabId)?.previewUrl??null:null),Se=!!((n||!i)&&Z&&q),He=Ae??U[0]??null;return{shouldRender:Se,isLoading:L,normalizedDirectory:q,resolvedSelected:He,displayActions:U,projectActionRuns:w,selectedRunPreviewUrl:ke,handlePrimaryClick:we,handleSelectAction:pe,openProjectActionsSettings:V,openContextPreview:p}}const Sa=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:x,handleSelectAction:y,openProjectActionsSettings:m,openContextPreview:h}=dx({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const b=d.icon||"play",g=d.id===It?"scan-2":Mn[b]||"play",S=as(c,d.id),w=f[S],E=w?.status==="stopping",A=w?.status==="waiting-for-preview",k=!!(w&&p),j=()=>{!w||!p||h(w.directory,p)},v=d.id===It;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",disabled:l||E,className:_("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":w?`Stop ${d.name}`:`Run ${d.name}`,children:E||A?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):w?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),v?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:j,children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",L=N.id===It?"scan-2":Mn[M]||"play",K=as(c,N.id),z=f[K],$=!!z,O=z?.status==="stopping";return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),O||z?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]}):s.jsxs("div",{className:_("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,disabled:l||E,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":w?`Stop ${d.name}`:`Run ${d.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:E||A?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):w?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),v?s.jsx(We,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j,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:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(We,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Gt,{children:[s.jsx(Ht,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ht,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",L=N.id===It?"scan-2":Mn[M]||"play",K=as(c,N.id),z=f[K],$=!!z,O=z?.status==="stopping";return s.jsxs(ht,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:L,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),O||z?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):$?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.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 cr(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 ux=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 fx({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const u=Je();try{const f=await nt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);u===Je()&&r(p)}catch{u===Je()&&r(null)}},[]);a.useEffect(()=>(o(),Un(()=>{o()})),[o]);const i=cr(n),l=ux(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Gt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(fn,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),s.jsx(We,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(qt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx(P,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:l})]}),c?s.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),s.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[s.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),s.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:()=>{xs(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),s.jsx(P,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const hx=({isMobile:e})=>{const n=Os().github??null,r=kr(i=>i.refresh),o=tm();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(fn,"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:[s.jsx(P,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),s.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},mx=a.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:l,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:p,remoteUpdateError:x,onOpenRemoteUpdate:y}){return s.jsxs(Gt,{open:l,onOpenChange:m=>{c(m),m&&d()},children:[s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx(Ht,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(fn,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),s.jsx(We,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(qt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?s.jsxs("div",{children:[o?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:p?"Looking for updates...":x||"This instance is up to date."})]}),f?.available?s.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:y,children:"Update"}):null]})}),s.jsx(Bu,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),px=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(ts,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ss,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(ws,{children:[s.jsx(ds,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(vs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ls,{children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),gx=e=>{const t=e.trim();if(!t)return"";const n=t.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),i=`${r} ${o}`.trim();return n.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},kn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},bx=a.lazy(()=>mt(()=>import("./SessionSwitcherDropdown-CFj9VWSa.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),ew=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{Wt("ui.header.render");const c=ce(B=>B.setSessionSwitcherOpen),d=ce(B=>B.toggleSidebar),u=ce(B=>B.isSidebarOpen),f=ce(B=>B.activeMainTab),p=ce(B=>B.setActiveMainTab),x=ce(B=>B.shortcutOverrides);ce(B=>B.timeFormatPreference),Os();const y=Te(B=>!!B.newSessionDraft?.open),m=Te(B=>B.currentSessionId),h=Va(m??""),b=_u(m),g=a.useMemo(()=>{if(!b)return null;const B=b;return{title:b.title??null,directory:B.directory??null,created:b.time?.created??null,slug:B.slug??null,shareUrl:b.share?.url??null,parentId:b.parentID??null,messageCount:typeof b.messageCount=="number"?b.messageCount:null}},[b]),S=ct(oo(B=>{if(!B.activeProjectId)return null;const le=B.projects.find(ye=>ye.id===B.activeProjectId);return le?{id:le.id,path:le.path,label:le.label}:null})),w=on(B=>B.homeDirectory),E=a.useMemo(()=>{if(!S)return null;const B=S.label?.trim();if(B)return B;const le=S.path.split(/[\\/]/).filter(Boolean);return le[le.length-1]??null},[S]),{isMobile:A}=dn(),{enabled:k}=Wo(),j=!!(k&&i&&o!==void 0),v=a.useMemo(()=>[...Bb(l)],[l]),[N,M]=a.useState(!1),L=a.useRef(null),[K,z]=a.useState(()=>typeof window>"u"?!1:rn()),$=a.useMemo(()=>ol(),[]),O=Uu(),[R,D]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),T=Za(),W=a.useMemo(()=>{if(typeof window>"u")return null;const B=window.__PICHAMBER_MACOS_MAJOR__;if(typeof B=="number"&&Number.isFinite(B)&&B>0)return B;if(typeof navigator>"u")return null;const le=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!le)return null;const ye=Number.parseInt(le[1],10),Be=Number.parseInt(le[2],10);return Number.isNaN(ye)?null:ye===10?Be:ye},[]);Re.useEffect(()=>{typeof window>"u"||z(rn())},[]);const Z=ce(B=>B.isSessionSwitcherOpen),[F,me]=a.useState(!1),[q,Ae]=a.useState("Local"),[Ie,G]=a.useState(!0),[U,Y]=a.useState(()=>cr(null)),[X,se]=a.useState(!1),[we,pe]=a.useState(null),[V,Q]=a.useState(!1),[ie,ke]=a.useState(null),Se=a.useRef(0),He=a.useMemo(()=>gx(q),[q]),H=a.useCallback(async()=>{if(typeof window>"u"||!K)return;const B=Je(),le=()=>Je()===B;try{const ye=await nt("/api/version");if(!le())return;const Be=ye.ok?await ye.json().catch(()=>null):null;if(!le())return;if(Y(cr(Be)),ur()){Ae("Local"),G(!0);return}G(!1);const re=await xf();if(!le())return;const qe=yf(),Nt=wf([vf(qe),...re.hosts]);if(Nt.id===Sf){Ae("Local"),G(!0);return}Ae(jf(Nt.label.trim()||"Instance"))}catch{le()&&(Ae("Local"),G(!0),Y(cr(null)))}},[K]);Re.useEffect(()=>(H(),Un(()=>{Se.current+=1,pe(null),ke(null),Q(!1),se(!1),H()})),[H]);const de=a.useCallback(async()=>{const B=Se.current+1;Se.current=B;const le=Je(),ye=()=>Se.current===B&&Je()===le;if(Ie){pe(null),ke(null);return}Q(!0),ke(null);try{const Be=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await nt(`/api/pi/update-check?${Be.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const qe=await re.json();if(!ye())return;pe({available:qe.available??!1,version:qe.version,currentVersion:qe.currentVersion??"unknown",body:qe.body,nextSuggestedCheckInSec:typeof qe.nextSuggestedCheckInSec=="number"?qe.nextSuggestedCheckInSec:void 0,packageManager:qe.packageManager,updateCommand:qe.updateCommand,channel:qe.channel==="rc"?"rc":"stable"})}catch(Be){if(!ye())return;pe(null),ke(Be instanceof Error?Be.message:"Failed to check remote instance updates")}finally{ye()&&Q(!1)}},[Ie]);a.useEffect(()=>Th(()=>{Ie||de()}),[de,Ie]),a.useEffect(()=>{Se.current+=1,pe(null),ke(null),Q(!1),se(!1)},[Ie,q]),a.useEffect(()=>{if(!K||Ie)return;const B=3e3,le=3600*1e3;let ye=!1,Be=null;const re=qe=>{Be=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){re(le);return}de().finally(()=>{ye||re(le)})},qe)};return re(B),()=>{ye=!0,Be!==null&&window.clearTimeout(Be)}},[de,Ie,q,K]);const ne=a.useCallback(()=>{if(we?.available){se(!0);return}de()},[de,we?.available]),ue=m?g??null:null,ve=a.useRef(null),[Le,be]=a.useState(0);a.useEffect(()=>{if(!m){ve.current&&(ve.current=null,be(Be=>Be+1));return}if(ue){ve.current={sessionId:m,session:ue,expiresAt:Date.now()+2e3};return}const B=ve.current;if(!B||B.sessionId!==m)return;const le=B.expiresAt-Date.now();if(le<=0){ve.current=null,be(Be=>Be+1);return}const ye=window.setTimeout(()=>{ve.current?.sessionId===m&&(ve.current=null),be(Be=>Be+1)},le);return()=>{window.clearTimeout(ye)}},[m,ue]);const te=(()=>{if(ue)return ue;if(!m)return null;const B=ve.current;return B&&B.sessionId===m&&B.expiresAt>Date.now()?B.session:null})(),xe=a.useMemo(()=>{const B=typeof te?.directory=="string"?te.directory:"";return kn(B||"")},[te?.directory]),fe=Te(B=>B.newSessionDraft?.open?kn(B.newSessionDraft.directoryOverride??""):""),je=a.useMemo(()=>zb({sessionDirectory:xe,draftDirectory:fe,isNewSessionDraftOpen:y}),[fe,y,xe]),_e=Ya(je||null),De=a.useMemo(()=>$b({activeProjectLabel:E,openDirectory:je,homeDirectory:w}),[E,w,je]),Ve=!!(De||_e),ae=a.useMemo(()=>m?gs(te,"Untitled session"):De??"PiChamber",[te,m,De]),Fe=zu(),tt=Te(B=>B.updateSessionTitle),xt=Te(B=>B.archiveSessions),Qe=Te(B=>B.deleteSessions),[pt,Xe]=a.useState(!1),[Ss,St]=a.useState(!1),st=a.useRef(!1),[Et,Lt]=a.useState(""),[Yt,jt]=a.useState(null),Ot=a.useRef(null);a.useEffect(()=>{st.current=!1,St(!1),Xe(!1),Lt(""),jt(null)},[m]);const yt=a.useCallback(()=>{m&&(Lt(te?.title?.trim()||ae),Xe(!0))},[te?.title,m,ae]),rt=a.useCallback(async()=>{if(!m)return;const B=Et.trim();B&&B!==te?.title?.trim()&&await tt(m,B),Xe(!1)},[te?.title,m,Et,tt]);a.useEffect(()=>{if(!pt)return;const B=le=>{const ye=le.target;(!ye||!Ot.current?.contains(ye))&&rt()};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[pt,rt]);const dt=a.useCallback(()=>{m&&xs(m).then(B=>{oe[B.ok?"success":"error"](B.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[m]),Vt=a.useCallback(async()=>{if(!m||!je){oe.error("Nothing to export");return}try{await Fe.syncSession(m)}catch{oe.error("Failed to load the complete session history");return}const B=[];if(B.length===0){oe.error("Nothing to export");return}const le=oc(B,te?.title??null),ye=lc(te?.title??null);await ac(le,ye)||ic(le,ye),oe.success("Session exported")},[te?.title,m,je,Fe]);h?.type==="busy"||h?.type;const us=a.useCallback(async()=>{if(!m||!Yt)return;const B=$u(),le=[m];for(let qe=0;qe<le.length;qe+=1){const Nt=le[qe];for(const gt of B)gt.parentID===Nt&&!le.includes(gt.id)&&le.push(gt.id)}const ye=Yt;if(jt(null),(ye==="archive"?await xt(le):await Qe(le)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[xt,m,Qe,Yt]),Ce=ce(B=>B.isArchivePageOpen),Ue=a.useMemo(()=>Ce?{title:"Archive",subtitle:null}:null,[Ce]),ge=a.useMemo(()=>kn(je||S?.path||""),[S?.path,je]),Oe=a.useCallback(()=>{ge&&xs(ge).then(B=>{oe[B.ok?"success":"error"](B.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[ge]),Ge=a.useMemo(()=>S?{id:S.id,path:S.path}:null,[S]),it=a.useRef(null);a.useEffect(()=>{!Ge||!ge||(it.current={projectRef:Ge,directory:ge})},[ge,Ge]);const kt=a.useMemo(()=>Ge&&ge?{projectRef:Ge,directory:ge}:it.current,[ge,Ge]),ot=a.useCallback(()=>{if(typeof document>"u")return;const B=document.activeElement;if(!B)return;const le=B.tagName;(le==="INPUT"||le==="TEXTAREA"||le==="SELECT"||B.isContentEditable)&&B.blur()},[]),Bt=a.useCallback(()=>{if(A){ot(),c(!Z);return}d()},[ot,A,Z,c,d]),ns=a.useCallback(()=>{Dn("desktop_open_draft_mini_chat_window",{directory:kn(je||S?.path||""),projectId:S?.id??null,apiBaseUrl:mo(),clientToken:ho()}).catch(B=>{console.warn("[header] failed to open draft mini chat window",B)})},[S?.id,S?.path,je]),Ze=a.useCallback(()=>{if(y){ns();return}m&&Dn("desktop_open_session_mini_chat_window",{sessionId:m,directory:kn(je||S?.path||""),apiBaseUrl:mo(),clientToken:ho()}).catch(B=>{console.warn("[header] failed to open session mini chat window",B)})},[S?.path,m,ns,y,je]),Rt=fn,Dt=dm,wt=a.useMemo(()=>n?"sessions":j?r&&o?o:null:r?"git":f,[f,j,n,r,o]),ut=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&Z&&c(!1)},[Z,n,e,t,r,c]),_s=a.useCallback(()=>{e?.()},[e]),Us=a.useCallback(()=>{t?.()},[t]),js=a.useMemo(()=>K&&I&&!R?"5.5rem":O?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!K||T?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,R,I,O,T]);Re.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",js)},[js]);const ks=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Ct=u?"0px":K&&T?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":k?"2.75rem":"2.5rem";Re.useEffect(()=>{if(!K||!I){D(!1);return}let B=!1;const le=async()=>{try{const Be=await Dn("desktop_is_window_fullscreen");B||D(Be===!0)}catch{B||D(!1)}},ye=()=>{le()};return le(),window.addEventListener("pichamber:window-resized",ye),()=>{B=!0,window.removeEventListener("pichamber:window-resized",ye)}},[K,I]);const rs=a.useMemo(()=>!K||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[K,I,W]),At=a.useMemo(()=>{if(!(K&&!T))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,T]),os=a.useCallback(()=>{if(typeof document>"u")return;const B=L.current?.getBoundingClientRect().height;if(B){const le=`${B}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==le&&ye.setProperty("--oc-header-height",le)}},[]);Re.useEffect(()=>{if(typeof window>"u")return;os();const B=L.current;if(!B||typeof ResizeObserver>"u")return()=>{};let le=0;const ye=()=>{le||(le=requestAnimationFrame(()=>{le=0,os()}))},Be=new ResizeObserver(ye);return Be.observe(B),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{le&&cancelAnimationFrame(le),Be.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[os]),Re.useEffect(()=>{os()},[os,A,rs]);const is=a.useCallback(async B=>{const le=B.target;le.closest(".app-region-no-drag")||le.closest("button, a, input, select, textarea")||B.button===0&&K&&await Ku()},[K]),at=a.useMemo(()=>A?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[A]),_t=a.useCallback(B=>Ho(dr(B,x)),[x]);Re.useEffect(()=>{!A&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,A,p]),Re.useEffect(()=>{const B=le=>{if(kf(le)&&!le.shiftKey&&!le.altKey){const ye=parseInt(le.key,10);ye>=1&&ye<=at.length&&(le.preventDefault(),A&&(ot(),ut()),p(at[ye-1].id))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[ot,ut,A,p,at]),Re.useEffect(()=>{const B=le=>{const ye=dr("toggle_services_menu",x);if(Cf(le,ye)){le.preventDefault(),F?me(!1):(me(!0),H());return}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[x,F,H]);const zs=B=>{const le=f===B.id,ye=B.icon==="diff",Be=ye?null:B.icon,re=B.id==="chat",qe=gt=>ye?s.jsx(ya,{size:gt}):Be?s.jsx(P,{name:Be,className:`h-${gt/4} w-${gt/4}`}):null,Nt=s.jsxs("button",{type:"button",onClick:()=>p(B.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",le?"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",re&&!A&&"min-w-[100px] justify-center"),"aria-label":B.label,"aria-selected":le,role:"tab",children:[A?qe(20):s.jsxs(s.Fragment,{children:[qe(16),s.jsx("span",{className:"header-tab-label",children:B.label})]}),B.badge!==void 0&&B.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:B.badge})]});return s.jsx(a.Fragment,{children:Nt},B.id)},Pt=s.jsxs(s.Fragment,{children:[s.jsx(Hb,{directory:ge,className:"mr-1"}),K?s.jsx(mx,{isDesktopApp:K,currentInstanceLabel:q,compactCurrentInstanceLabel:He,currentInstanceIsLocal:Ie,currentInstanceIcon:U,isDesktopServicesOpen:F,setIsDesktopServicesOpen:me,refreshCurrentInstanceLabel:H,shortcutLabel:_t,remoteUpdateInfo:we,remoteUpdateChecking:V,remoteUpdateError:ie,onOpenRemoteUpdate:ne}):s.jsx(fx,{open:F,onOpenChange:me}),s.jsx(hx,{isMobile:A})]}),pn=$&&(y||!!m),$s=()=>s.jsxs("div",{onMouseDown:is,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",rs),style:At,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ks}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ct}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ue?s.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:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Ue.title}),Ue.subtitle?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:Ue.subtitle})]}):null]}):s.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:s.jsx(a.Suspense,{fallback:s.jsx("button",{type:"button",className:Rt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(bx,{align:"start",children:s.jsx("button",{type:"button",className:Rt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[pt?s.jsxs("form",{ref:Ot,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:B=>{B.preventDefault(),rt()},children:[s.jsx("input",{value:Et,onChange:B=>Lt(B.target.value),autoFocus:!0,onKeyDown:B=>{B.stopPropagation(),B.key==="Escape"&&Xe(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>Xe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:y?"New session":ae}),Ve?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[De?s.jsx("span",{className:"truncate",children:De}):null,_e?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(P,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:_e})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!y&&!pt?s.jsxs(Gt,{open:Ss,onOpenChange:St,onOpenChangeComplete:B=>{!B&&st.current&&(st.current=!1,yt())},children:[s.jsx(Ht,{asChild:!0,children:s.jsx(Ne,{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:s.jsx(P,{name:"more",className:"size-4"})})}),s.jsxs(qt,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ht,{onClick:()=>{st.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ht,{onClick:dt,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ht,{onClick:Oe,disabled:!ge,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(nn,{}),s.jsxs(ht,{onClick:()=>{Vt()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(nn,{}),s.jsxs(ht,{onClick:()=>jt("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ht,{className:"text-destructive focus:text-destructive",onClick:()=>jt("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),at.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:at.map(B=>zs(B))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Pl,{}),kt?s.jsx(Sa,{projectRef:kt.projectRef,directory:kt.directory,className:"mr-1"}):null,s.jsx(um,{visible:pn,title:y?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:y?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Ze,className:_(Rt,"mr-1"),Icon:"picture-in-picture-2"}),Pt,s.jsx(Wu,{visible:T})]})]})]}),gn=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[k&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ks}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Ct}})]}),!k&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:_s,className:_(Dt,wt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(P,{name:"layout-left",className:"h-5 w-5"})}):Z?s.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:s.jsx(P,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Bt,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:s.jsx(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&Z&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!Z||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!j&&s.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:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.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:at.map(B=>{const le=f===B.id,ye=B.icon==="diff",Be=ye?null:B.icon;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{A&&(ot(),ut()),p(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(Dt,"relative rounded-lg",wt===B.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?s.jsx(ya,{className:"h-5 w-5"}):Be?s.jsx(P,{name:Be,className:"h-5 w-5"}):null,B.badge!==void 0&&B.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:B.badge}),B.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),s.jsx(We,{children:s.jsx("p",{children:B.label})})]},B.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[j&&s.jsxs(s.Fragment,{children:[s.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:v.map(B=>{const le=r&&o===B.id;return s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{A&&(ot(),ut()),M(!1),i?.(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(Dt,"relative h-11 w-11 rounded-lg",le&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:B.icon,className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:B.label})})]},B.id)})}),s.jsx(cm,{open:N,onOpenChange:M,currentSessionId:m,effectiveDirectory:je||null,isNewSessionDraftOpen:y})]}),kt&&s.jsx(Sa,{projectRef:kt.projectRef,directory:kt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!j?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Us,className:_(Dt,"relative",wt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(P,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(We,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),fs=_("header-safe-area relative z-10 bg-background",A&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:L,className:fs,style:{"--padding-scale":"1"},children:A?gn():$s()}),s.jsx(px,{action:Yt,onClose:()=>jt(null),sessionTitle:ae,onConfirm:()=>{us()}}),s.jsx(jl,{open:X,onOpenChange:se,info:we,downloading:!1,downloaded:!1,progress:null,error:ie,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},ja="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",xx="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",tw=()=>{const e=ce(y=>y.isSidebarOpen),t=ce(y=>y.toggleSidebar),n=ce(y=>y.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Ho(dr("toggle_sidebar",n)),l=Za(),{enabled:c}=Wo(),d=!e,u=l,f=d||u,p=u,x=a.useCallback(()=>{Dn("desktop_show_app_menu").catch(y=>{console.warn("[titlebar] failed to open app menu",y)})},[]);return a.useEffect(()=>{if(typeof document>"u")return;const y=w=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(w)}px`)},m=w=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(w)}px`)};if(!p)return;const h=o.current,b=r.current;if(!h||!b){y(0),m(0);return}const g=()=>{const w=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(w),m(b.getBoundingClientRect().width)};if(g(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(g);return S.observe(h),S.observe(b),()=>{S.disconnect()}},[p]),f?s.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:s.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(ja,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs($e,{children:[s.jsx(Ke,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?xx:ja,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(We,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},ka=200,yx="cubic-bezier(0.22, 1, 0.36, 1)",sw=e=>{const t=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=a.useState(e),[o,i]=a.useState(e);return a.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 l=window.setTimeout(()=>i(!1),ka);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${ka}ms ${yx}`}},nw=()=>{al()},rw=e=>{Te.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ce.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),al(),on.getState().resetForRuntimeSwitch(),Gu.getState().resetForRuntimeSwitch(),Hu.getState().resetForRuntimeSwitch(),qu(),Af(),Nf(),Xu(),Yu.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ct.getState().resetForRuntimeSwitch(),Vu(),Qu(),Kf.getState().reset(),If.getState().resetForRuntimeSwitch(),za.getState().resetForRuntimeSwitch(e.runtimeKey),co.getState().resetForRuntimeSwitch(e.runtimeKey),Ef(),Ts.getState().resetForRuntimeSwitch(e.runtimeKey),Ju.getState().resetForRuntimeSwitch(),es.getState().resetForRuntimeSwitch(),bt.getState().resetForRuntimeSwitch(e.runtimeKey),Rf.getState().resetForRuntimeSwitch(e.runtimeKey),Te.getState().restoreForRuntimeSwitch(e.runtimeKey),ce.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=ce.getState();xo({sessionId:Te.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Ph as $,Ny as A,Kx as B,ay as C,ua as D,iy as E,Ux as F,Qx as G,ew as H,Vo as I,Yx as J,Rh as K,Nl as L,Dl as M,Pn as N,_x as O,Jh as P,Wx as Q,Ih as R,Gy as S,Vy as T,jl as U,Mh as V,Fx as W,Xx as X,Al as Y,$n as Z,ty as _,cm as a,Ky as a$,zn as a0,Cl as a1,Jx as a2,$x as a3,Nh as a4,ry as a5,sy as a6,kr as a7,ny as a8,oy as a9,Ay as aA,Cy as aB,uy as aC,jy as aD,Sy as aE,wy as aF,Ar as aG,Nr as aH,Ir as aI,Ps as aJ,Zl as aK,nm as aL,rm as aM,Ui as aN,Zy as aO,As as aP,bs as aQ,es as aR,Xl as aS,zl as aT,_n as aU,Ul as aV,zx as aW,Mx as aX,My as aY,Iy as aZ,Ty as a_,ey as aa,Gx as ab,Hx as ac,qx as ad,vy as ae,Hh as af,Vx as ag,kl as ah,ch as ai,Eh as aj,Lx as ak,dh as al,ah as am,fy as an,cy as ao,ly as ap,dy as aq,yy as ar,xy as as,my as at,hy as au,py as av,sm as aw,by as ax,gy as ay,ky as az,An as b,Wy as b0,tm as b1,Oy as b2,Fy as b3,Ry as b4,Ly as b5,_y as b6,Uy as b7,zy as b8,$y as b9,By as ba,Py as bb,Ey as bc,Ro as bd,Xi as be,Ns as bf,jn as bg,mn as bh,xp as bi,hn as bj,Dy as bk,Hg as c,Hy as d,ar as e,Bb as f,qy as g,bb as h,Vg as i,Qy as j,hc as k,sw as l,Xy as m,tw as n,nw as o,rw as p,Ox as q,Jy as r,Yy as s,Bx as t,am as u,Tx as v,Px as w,Dh as x,Zx as y,Ah as z};
|