@pi-chamber/web 1.0.4-rc.4 → 1.0.4
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--BGR3PRZ.js → DiagramView-BpG1c3Hi.js} +1 -1
- package/dist/assets/{DiffView-hz90_htv.js → DiffView-BxwoRCYx.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-CcrWHRvd.js → FileSaveConflictDialog-DP7k9a-i.js} +1 -1
- package/dist/assets/{FilesView-DaqkPMqx.js → FilesView-D_2QcdUt.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-BZhP67Va.js → GitHubDetailScaffold-UxLAMAOl.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-CJZmDljp.js → GitHubLinkPicker-Bh9RO1yK.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-DhF42guB.js → GitHubListPrimitives-DQyhT5wG.js} +1 -1
- package/dist/assets/{GitView-JK-QCK9R.js → GitView-XBBheKRM.js} +3 -3
- package/dist/assets/{IssuesSurface-CAqQzrsv.js → IssuesSurface-BA1kpvAJ.js} +1 -1
- package/dist/assets/{JsonTreeView-CKTqB1CD.js → JsonTreeView-BAaEPL4O.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-B5kJy9Nt.js → MarkdownRendererImpl-DzgDmUsL.js} +1 -1
- package/dist/assets/{PatchDiff-BQnRFN30.js → PatchDiff-BMEUsgXH.js} +1 -1
- package/dist/assets/{PierreDiffViewer-BeGpdI0x.js → PierreDiffViewer-BW8MO-O6.js} +1 -1
- package/dist/assets/{PullRequestsSurface-D9beq2x9.js → PullRequestsSurface-B3ictm4I.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-DElQ_cjm.js → SessionSwitcherContent-rLoyVqgs.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-JaIDcDIj.js → SessionSwitcherDropdown-CfySKnUu.js} +2 -2
- package/dist/assets/{SessionUnreadDot-Czfvjbdi.js → SessionUnreadDot-CmEF9sxM.js} +1 -1
- package/dist/assets/{SettingsView-C_GC1Mx3.js → SettingsView-BiwlwnTK.js} +3 -3
- package/dist/assets/{SettingsWindow-CAxKgYOu.js → SettingsWindow-j0e99YI0.js} +1 -1
- package/dist/assets/{ToolOutputDialog-lz5exVQ4.js → ToolOutputDialog-VlS12Xyq.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-nIUiNLpP.js → ToolPartDiffPreview-DdSneZws.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-IWqCJNXu.js → VirtualizedFileDiff-BqiXjvP6.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-CyhUKEfv.js → computeVirtualFileMetrics-BJjC-tXV.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-DkjmJ-NU.js → contextFileOpenGuard-BBzqKGei.js} +1 -1
- package/dist/assets/{gitStatusPredicates-DBmUY3kA.js → gitStatusPredicates-Dq-E5DaH.js} +1 -1
- package/dist/assets/{githubLink-BdbPMMAK.js → githubLink-Cryd7GkG.js} +1 -1
- package/dist/assets/{index-CKgYIOis.js → index-BbhXFTId.js} +1 -1
- package/dist/assets/{main-CWdWdhdL.js → main-9O5IAtT_.js} +4 -4
- package/dist/assets/{main-6YKi4QM2.js → main-DWGwALIw.js} +2 -2
- package/dist/assets/{markdownCore-D7V46WY9.js → markdownCore-B9AuEyYi.js} +1 -1
- package/dist/assets/{miniChat-PanPmbEK.js → miniChat-CgOaJfD8.js} +2 -2
- package/dist/assets/{mobile-0LY-2fxw.js → mobile-BbJcYVym.js} +2 -2
- package/dist/assets/{pi-session-focus-preference-BC-ze1oC.js → pi-session-focus-preference-Bmk1iOvn.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-ByZtK9za.js → renderDiffWithHighlighter-CVLsdtQ5.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-DETQLjFi.js → renderElectronMiniChatApp-R5o9NwFC.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-CnN0Tv_8.js → renderFileWithHighlighter-DJ9mk2bZ.js} +1 -1
- package/dist/assets/{renderMobileApp-DS0FDQLg.js → renderMobileApp-CQ9tWYIj.js} +3 -3
- package/dist/assets/{runtimeEndpointReset-BqqXMwE9.js → runtimeEndpointReset-CtK4C_5h.js} +4 -4
- package/dist/assets/{useAppFontEffects-BisjofNZ.js → useAppFontEffects-DviRbaCJ.js} +6 -6
- package/dist/assets/{useFilesViewSearch-BWABG6pS.js → useFilesViewSearch-D2Au5Xgt.js} +1 -1
- package/dist/assets/{useGitHubRemoteSearch-Bsf2YeQP.js → useGitHubRemoteSearch-D-K7aolk.js} +1 -1
- package/dist/assets/{useSwitcherItems-BSTSev5C.js → useSwitcherItems-Dej8BzXI.js} +1 -1
- package/dist/assets/{web-components-CdMfsnXE.js → web-components-C7CmoFxi.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/mini-chat.html +1 -1
- package/dist/mobile.html +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{_ as ht}from"./vendor-vite-runtime-DD1OZmLC.js";import{k as s,b2 as kd,b3 as Ad,b4 as Nd,b5 as Id,b6 as Ed,b7 as Rd,b8 as Dd,aO as Oo,aP as Pn,aQ as Pd,aR as Bo,aS as _o,aV as Md,b9 as Td,ba as Fd,bb as Ld,bc as Sa,bd as ja,be as Ca,bf as ka,bg as Aa,bh as Na,bi as Ia,aT as Ea,a$ as Ra,aY as Da,aZ as Pa,aW as zo,aX as Uo,bj as ro,aL as Od}from"./vendor-boot-Dgb9NVFe.js";import{a as Ee,R as a}from"./vendor-react-DASdDPIk.js";import{aW as Qs,aX as Bd,t as ie,a as ut,h as Te,a4 as an,B as Ne,I as P,ai as Mn,aY as Ma,ak as ns,al as rs,am as vs,an as us,ao as Ss,ap as Ts,aM as Ds,aZ as Ps,a_ as _d,g as Ys,a$ as Or,b0 as wi,b1 as vi,aF as An,e as er,o as Ta,aj as As,b2 as Si,ae as ys,a9 as Ue,aa as $e,ac as Ke,b3 as oo,b4 as zd,b5 as Ud,b6 as $d,b7 as Kd,b8 as Wd,b9 as io,ba as Gd,a8 as Wt,ab as Gt,ad as Ht,H as $t,bb as Hd,bc as qd,bd as Yd,be as Vd,bf as Qd,bg as Jd,aJ as ao,r as Nn,x as $o,at as Xd,aE as Zd,aI as Fa,bh as La,S as ws,bi as eu,bj as tu,bk as su,bl as nu,d as Oa,q as Fs,aD as Ba,bm as wr,bn as ji,bo as _a,bp as pt,bq as ru,aK as za,br as Ua,bs as $a,bt as Ka,af as ft,bu as Wa,ay as ou,i as Ga,k as iu,bv as au,j as lu,bw as Ws,b as Ci,c as cu,bx as du,u as uu,aL as fu,aO as hu,by as lo,bz as mu,bA as pu,aN as gu,bB as bu,bC as xu,V as yu,ag as en,aq as Ha,F as wu,p as vu,bD as Su,m as ju,bE as Cu,bF as qa,bG as ku,bH as Au,bI as Nu,bJ as Iu,bK as Eu,bL as Ru,bM as Du,bN as Pu,bO as Mu,bP as Tu,a5 as Fu,bQ as Lu}from"./useAppFontEffects-BisjofNZ.js";import{_ as ki,D as Ou,$ as Bu,S as tn,a0 as Ya,a1 as Va,a2 as _u,a3 as zu,u as sn,L as Uu,a4 as $u,a5 as Ku,t as le,m as Tt,o as _,a6 as Wu,f as Qe,a as Mt,A as On,C as Ie,a7 as Tn,a8 as Kt,a9 as co,aa as uo,ab as Qa,v as ds,U as Ko,V as lr,ac as Gu,w as Ja,ad as Hu,ae as Xa,H as qu,R as Za,E as In,af as fo,h as ho,d as Kn,ag as Yu,ah as Vu,ai as Qu,aj as Ai,ak as bn,al as Br,am as mo,an as cr,ao as Ns,ap as Ni,aq as po,ar as el,as as go,at as Ju,au as Xu,av as Zu,aw as ef,ax as tf,ay as sf,az as nf,aA as rf,aB as of,Z as tl,aC as af,aD as lf,Q as cf,aE as df,K as uf}from"./index-BnZVqcki.js";import{g as bs,b as ff,c as sl,r as hf,d as nl,s as tr,e as rl,h as Ms,i as nn,j as mf,k as pf,l as gf,m as bf,n as Wo,o as ol,f as xf,a as Ii,S as yf,t as wf,p as vf}from"./SessionUnreadDot-Czfvjbdi.js";import{c as Ls,d as vr,p as il,a as Sf}from"./vendor-zustand-CUi8eEds.js";/* empty css */import{saveOrShareFile as jf}from"./nativeFileSave-BzhtrDoD.js";import{usePermissionStore as Cf}from"./permissionStore-B9Hkrqny.js";const kf="chat";function al(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Qs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Qs.SETTINGS,n),t}return e.tab!==kf&&t.set(Qs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Qs.FILE,e.diffFile),t}function Af(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 Nf(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=al(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Qs.SESSION)&&t.set(Qs.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 bo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Nf(e)))try{const n=al(e),r=Af(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const If=["typescript","javascript","tsx","jsx","json","markdown"],ll={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Ei=null;const cl=()=>(Ei??=Promise.all([ht(()=>import("./index-CKgYIOis.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42])),ht(()=>import("./workerFactory-tw7cIdmV.js"),[]),ht(()=>import("./appThemeRegistry-gegrE2dq.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})),Ei),Fn={},Ri=new Set,xo=new Set;let sr={light:"pierre-light",dark:"pierre-dark"};const Ef=()=>{for(const e of xo)e()},dl=(e,t)=>{t.setRenderOptions({theme:sr,lineDiffType:ll[e].lineDiffType})},yo=e=>{typeof window>"u"||Ri.has(e)||(Ri.add(e),cl().then(t=>{if(Fn[e])return;const n=ll[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:If,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Fn[e]=r,dl(e,r),Ef()}))},Rf=e=>(xo.add(e),()=>xo.delete(e)),Df=e=>{if(!(sr.light===e.light&&sr.dark===e.dark)){sr=e;for(const t of Object.keys(Fn)){const n=Fn[t];n&&dl(t,n)}}},cx=({children:e})=>{const t=Bd(),n=ki(!1),r=ki(!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 Ee.useEffect(()=>{let d=!1;return cl().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Df({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ee.useEffect(()=>{if(typeof window>"u")return;const d=()=>{yo("unified"),yo("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})},dx=(e="unified")=>{const t=Ee.useSyncExternalStore(Rf,()=>Fn[e],()=>{});return Ee.useEffect(()=>{yo(e)},[e]),t};let Wn=null;const ux=()=>{if(typeof window>"u"||typeof document>"u"||Wn)return()=>{};const e=()=>{document.visibilityState!=="hidden"&&Ou()};document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),window.addEventListener("online",e);let t=!1;const n=()=>{t||(t=!0,document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),window.removeEventListener("online",e),Wn===n&&(Wn=null))};return Wn=n,n},Pf=e=>e==="/",rn=e=>e.replace(/\\/g,"/"),on=e=>{if(!e||Pf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},Xs=e=>e.endsWith("/"),dr=e=>{const t=e.trim();return!t||Xs(t)?t:`${t}/`},Go=e=>e.lastIndexOf("/"),ul=e=>{if(Xs(e))return e;const t=Go(e);return t<0?e:e.slice(0,t+1)},fl=e=>{const t=Go(e);return e.slice(t+1)},hl=e=>{const t=on(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Go(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},ml=e=>Xs(e)&&hl(e)!==null,Mf=e=>{if(!ml(e))return null;const t=on(e.trim());return fl(t)||t},Tf=(e,t)=>`${ul(e)}${t}/`,Is=e=>{if(!e)return null;const t=on(rn(e.trim()));return t?t.toLowerCase():null},Di=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},Ff=(e,t)=>{const n=on(rn(e.trim())),r=on(rn(t.trim()));if(!n)return"";if(!r)return dr(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:dr(n)},Lf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,wo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Of=async()=>Bu({fresh:!0}),Bf=()=>{const[e,t]=Ee.useState(!1),[n,r]=Ee.useState(!1);Ee.useEffect(()=>{t(tn()),r(Ya())},[]);const o=Ee.useCallback(async c=>e?await Va(c):{success:!0,path:c},[e]),i=Ee.useCallback(async c=>e?await _u():{success:!0},[e]),l=Ee.useCallback(async c=>e?await zu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function _f({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=sn(se=>se.homeDirectory),{canRequestAccess:o,startAccessing:i}=Bf(),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,v]=a.useState(null),[E,j]=a.useState(0),[k,C]=a.useState(0),[w,N]=a.useState(!1),[T,O]=a.useState(!1),[$,U]=a.useState("right"),K=a.useRef("~/"),L=d||r;a.useEffect(()=>{if(!e)return;p("~/"),y([]),C(0),N(!1),O(!1),K.current="~/",U("right"),n||requestAnimationFrame(()=>wo(l.current));let se=!1;return(async()=>{const Ce=await Of();se||(u(Ce||r||""),n||requestAnimationFrame(()=>wo(l.current)))})(),()=>{se=!0}},[r,e,n]);const D=a.useMemo(()=>ul(f),[f]),R=a.useMemo(()=>Xs(f)?"":fl(f),[f]),I=a.useMemo(()=>L?Di(D,L):"",[D,L]);a.useEffect(()=>{const se=K.current;se!==D&&(U(D.length>=se.length?"right":"left"),K.current=D)},[D]),a.useEffect(()=>{if(!e||!I){y([]),v(null);return}let se=!1;return h(!0),g(!1),v(null),Uu(I).then(ce=>{if(se)return;g(!1),v(null);const Ce=ce.filter(ve=>ve.isDirectory).map(ve=>({name:ve.name,path:rn(ve.path)})).sort((ve,Ge)=>ve.name.localeCompare(Ge.name));y(Ce)}).catch(ce=>{if(!se){y([]);const Ce=$u(ce)?ce.reason:"unknown";v(Ce),g(Ce==="not-found")}}).finally(()=>{se||h(!1)}),()=>{se=!0}},[I,E,e]);const M=a.useMemo(()=>{const se=R.toLowerCase(),ce=T||R.startsWith(".");return x.filter(Ce=>Ce.name.toLowerCase().startsWith(se)&&(ce||!Ce.name.startsWith(".")))},[R,x,T]),W=a.useMemo(()=>Mf(f),[f]),G=a.useMemo(()=>hl(f),[f]),B=a.useMemo(()=>{const se=[],ce=Is(I);ml(f)&&W&&G&&se.push({type:"parent",value:"browse:up",name:W,path:G,alreadyAdded:!!(ce&&t.has(ce))});for(const Ce of M){const ve=Is(Ce.path);se.push({type:"directory",value:`browse:${Ce.path}`,name:Ce.name,path:Ce.path,alreadyAdded:!!(ve&&t.has(ve))})}return se},[t,I,W,M,G,f]);a.useEffect(()=>{C(0)},[f,B.length]);const xe=a.useMemo(()=>L?on(Di(f,L)):"",[L,f]),V=Is(xe),je=!!(V&&t.has(V)),Re=a.useMemo(()=>R?M.find(se=>se.name===R)??null:null,[R,M]),H=!!(xe&&!je&&(S===null||S==="not-found")&&(Xs(f)&&b||!Xs(f)&&R.trim().length>0&&Re===null)),z=B[k]??null,Y=!!z,X=a.useCallback(se=>{p(dr(se))},[]),te=a.useCallback(se=>{p(Tf(f,se.name))},[f]),ue=a.useCallback(se=>{if(se){if(se.type==="parent"){X(se.path);return}te(se)}},[X,te]),he=a.useCallback(async se=>{const ce=await i(se);if(!ce.success)return ie.error("Failed to open directory",{description:ce.error||"Desktop could not grant file access."}),!1;const Ce=L?Ff(se,L):dr(rn(se));return X(Ce),!0},[X,L,i]),Q=a.useCallback(async()=>{if(!w){N(!0);try{if(Ya()){const ce=await Va(xe);if(!ce.success||!ce.path){ce.error&&ce.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:ce.error});return}await he(ce.path);return}const se=await Ku(xe);if(se.status==="cancelled")return;if(se.status!=="picked"){ie.error("Couldn't open a folder picker",{description:se.error});return}await he(se.path)}catch(se){ie.error("Failed to select directory",{description:se instanceof Error?se.message:"Unknown error occurred."})}finally{N(!1)}}},[he,w,xe]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:b,browseErrorReason:S,browseReloadKey:E,setBrowseReloadKey:j,highlightedIndex:k,setHighlightedIndex:C,isPickingLocation:w,showHidden:T,setShowHidden:O,folderEnterFrom:$,explorerRootDirectory:L,browseDirectoryDisplayPath:D,browseDirectoryAbsolutePath:I,browseFilterQuery:R,filteredEntries:M,rows:B,targetPath:xe,isAlreadyAdded:je,shouldCreateTarget:H,highlightedRow:z,hasHighlightedBrowseItem:Y,canRequestAccess:o,browseToDisplayPath:X,browseToEntry:te,executeRow:ue,applyPickedLocation:he,handleBrowseLocation:Q}}function zf({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=ut(O=>O.addProject),p=le(O=>O.setActiveMainTab),x=le(O=>O.setSessionSwitcherOpen),y=Te(O=>O.openNewSessionDraft),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,v]=a.useState("");a.useEffect(()=>{e&&(h(!1),g(!1),v(""))},[e]);const E=a.useCallback((O,$)=>{p("chat"),n&&x(!1),y({selectedProjectId:O,directoryOverride:$}),t()},[n,t,y,p,x]),j=a.useCallback(async O=>{if(!O||m)return;const $=Is(O);if($&&r.has($))return;let U=O;h(!0);try{const K=!b&&i&&Is(O)===Is(o);if(b){const D=S.trim();if(!D){ie.error("Enter a repository URL before cloning.");return}const R=await Tt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:D,destinationPath:O})});if(!R.ok)throw new Error("Failed to clone git repository");U=(await R.json()).path||O}else if(K&&!(await Tt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:O})})).ok)throw new Error("Failed to select directory");const L=f(U);if(!L){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}E(L.id,L.path)}catch(K){ie.error("Failed to select directory",{description:K instanceof Error?K.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,C=k&&S.trim().length>0,w=b?C:k,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:b,setIsCloneMode:g,cloneRemoteUrl:S,setCloneRemoteUrl:v,canSubmit:w,submitActionLabel:d?"Already added":b?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:j}}const Uf=({open:e,onOpenChange:t})=>{const n=ut(Q=>Q.projects),{isMobile:r,isTablet:o}=an(),i=r||o,l=a.useMemo(()=>new Set(n.map(Q=>Is(Q.path)).filter(Q=>!!Q)),[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:v,folderEnterFrom:E,browseDirectoryDisplayPath:j,browseDirectoryAbsolutePath:k,rows:C,targetPath:w,isAlreadyAdded:N,shouldCreateTarget:T,highlightedRow:O,hasHighlightedBrowseItem:$,canRequestAccess:U,executeRow:K,handleBrowseLocation:L}=_f({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:D,isCloneMode:R,setIsCloneMode:I,cloneRemoteUrl:M,setCloneRemoteUrl:W,canSubmit:G,submitActionLabel:B,submitModifierLabel:xe,finalizeSelection:V}=zf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:T,browseErrorReason:y,browseDirectoryAbsolutePath:k,isAlreadyAdded:N,isPickingLocation:g});a.useLayoutEffect(()=>{const Q=d.current;Q&&(Q.scrollLeft=Q.scrollWidth)},[d,f]),a.useLayoutEffect(()=>{!e||i||wo(d.current)},[d,e,i]),a.useLayoutEffect(()=>{const Q=C[h];Q&&u.current.get(Q.value)?.scrollIntoView({block:"nearest"})},[h,u,C]);const je=a.useCallback(Q=>{if(Q.key==="ArrowDown"){Q.preventDefault(),b(se=>Math.min(C.length-1,se+1));return}if(Q.key==="ArrowUp"){Q.preventDefault(),b(se=>Math.max(0,se-1));return}if(Q.key==="Enter"){if(Q.preventDefault(),Lf(Q)){V(w);return}$&&K(O);return}Q.key==="Backspace"&&f===""&&(Q.preventDefault(),c())},[K,V,c,$,O,f,C.length,b,w]),Re=s.jsxs("button",{type:"button",onClick:()=>v(Q=>!Q),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[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"]}),H=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(Mn,{ref:d,value:f,onChange:Q=>p(rn(Q.target.value)),onKeyDown:je,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:D||g,onMouseDown:Q=>Q.preventDefault(),onClick:()=>{L()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(P,{name:"folder-open",className:"h-3.5 w-3.5"}),g?"Opening...":"Browse"]})]})}),z=C.some(Q=>Q.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":R,disabled:D||g,onClick:()=>I(Q=>!Q),children:[s.jsx(P,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),R?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(Mn,{value:M,onChange:Q=>W(Q.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})})]}):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"&&U?s.jsx(Ne,{size:"xs",onClick:()=>{L()},disabled:g,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:()=>m(Q=>Q+1),children:"Try again"})]})]}):C.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:C.map((Q,se)=>{const ce=se===h,Ce=Q.type==="directory"&&z;return s.jsxs("button",{ref:ve=>{ve?u.current.set(Q.value,ve):u.current.delete(Q.value)},type:"button","aria-label":Q.type==="parent"?Q.alreadyAdded?`Go back from ${Q.name}, already added`:`Go back from ${Q.name}`:Q.alreadyAdded?`Open ${Q.name}, already added`:`Open ${Q.name}`,onMouseEnter:()=>b(se),onMouseDown:ve=>ve.preventDefault(),onClick:()=>K(Q),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",ce&&"bg-interactive-selection text-interactive-selection-foreground",!ce&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",Ce&&"pl-4"),children:[Q.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:Q.name})]}),Q.alreadyAdded?s.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",ce?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,Q.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"})]},Q.value)})})},j)]})}),X=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[H,Y]}),te=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:xe}),s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),ue=s.jsx(Ne,{size:r?"xs":"default",onClick:()=>{V(w)},disabled:!G,className:_(r&&"w-full flex-1"),children:B}),he=()=>s.jsxs(s.Fragment,{children:[r?null:te,s.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:ue})]});return r?s.jsx(Ma,{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:he()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Re}),X]})}):s.jsx(ns,{open:e,onOpenChange:t,children:s.jsxs(rs,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(vs,{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(us,{children:"Add folder"}),s.jsx(Ss,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Re]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:X}),s.jsx(Ts,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:he()})]})})},Gn=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,fx=()=>{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=le(k=>k.showDeletionDialog),u=le(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:x}=an(),y=f||p||x;a.useEffect(()=>Wu(()=>{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 T=k.sessions[0];await l(T.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const C=k.sessions.map(T=>T.id),{deletedIds:w,failedIds:N}=await c(C);if(w.length>0){const T=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;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Gn(T)})}N.length>0&&ie.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:Gn("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Ds.onDeleteRequest(k=>{if(!d){b(k);return}m(k)}),[m,d,b]),a.useEffect(()=>Ds.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)){ie.error("Failed to delete session"),i(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=n.sessions.map(T=>T.id),C=await c(k),w=C.deletedIds,N=C.failedIds;if(w.length>0){const T=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;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Gn(T),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(ie.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:Gn("Please try again in a moment.")}),w.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.`:"",v=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:bs(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"})]})]}),j=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(Ma,{open:!!n,onClose:()=>{o||h()},title:j,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}),v]})}):s.jsx(ns,{open:!!n,onOpenChange:k=>{if(!k){if(o)return;h()}},children:s.jsxs(rs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(vs,{children:[s.jsx(us,{children:j}),S&&s.jsx(Ss,{children:S})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),s.jsx(Ts,{className:"mt-2 gap-2 pt-1 pb-1",children:E})]})}),s.jsx(Uf,{open:e,onOpenChange:t})]})},hx=()=>{const e=Ps(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!_d(t)||!t.receipt||(Ps.getState().markNotificationSent(t.key),ie.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},$f=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","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"]}],Kf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Wf(e){const t=e.trim().toLowerCase();return $f.find(n=>n.slug===t)??null}function Gf(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";const n=Kf[t];if(n)return n;const r=Wf(t);return r?r.slug:"home"}function mx(e){switch(e){case"general":return"equalizer";case"projects":return"folders";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 px(){const e=a.useRef(!1),t=a.useRef(!1),n=Te(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),i=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Te.getState().currentSessionId,x=Ys().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==x){const y=Te.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(Gf(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,l]),d=a.useCallback(()=>{const f=Te.getState(),p=Ys().getState(),x=le.getState();return{sessionId:Or({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();bo(p,f)},[d]);a.useEffect(()=>{if(e.current||(e.current=!0,!wi()))return;const f=vi();(async()=>(await c(f),bo({...d(),sessionId:f.sessionId??Or({currentSessionId:Te.getState().currentSessionId,piSelectedSessionId:Ys().getState().selectedSessionId,draft:Te.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),a.useEffect(()=>{const f=()=>{const b=Te.getState(),g=Ys().getState();return Or({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=Ys().subscribe(()=>{y()});return()=>{m(),h()}},[u]),a.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,x=le.getState().settingsPage,y=le.getState().pendingDiffFile;return le.subscribe(h=>{if(t.current)return;const b=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==p,S=h.settingsPage!==x,v=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(b||g||S||v)&&u()})},[u]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=vi();if(wi())c(p);else{const x=le.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function Hf(e=!0){const t=er(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 gx(){const e=An(t=>t.connection==="ready",void 0,"chrome");return Hf(e),null}const Pi=12,qf=[{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"}],Yf=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=qf,onComplete:i})=>{const l=Ee.useRef(!1);Ee.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Ee.useMemo(()=>Array.from({length:Pi},(d,u)=>{const f=Math.PI*2*u/Pi;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},Vf=({durationMs:e=3400}={})=>{const[t,n]=Ee.useState({isActive:!1,cycle:0}),r=Ee.useRef(null),o=Ee.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Ee.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ee.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 Ee.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},pl=a.createContext(void 0),bx=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Vf(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(pl.Provider,{value:i,children:[e,s.jsx(Yf,{isActive:t,burstKey:n})]})},Qf={triggerFireworks:()=>{},dismissFireworks:()=>{}},xx=()=>a.useContext(pl)??Qf,ur=2e3,gl=600*1e3;async function Jf(){try{const e=await Tt("/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 Xf(e,t=Math.ceil(gl/ur),n=ur,r=Qe()){for(let o=0;o<t;o++){if(Qe()!==r)return{applied:!1,stale:!0};try{const i=await Tt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Qe()!==r)return{applied:!1,stale:!0};if(i.ok){const l=await i.json().catch(()=>null);if(Qe()!==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(Qe()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function Zf(e,t,n=Math.ceil(gl/ur),r=ur,o=Qe()){for(let i=0;i<n;i++){if(Qe()!==o)return{applied:!1,stale:!0};try{const l=await Tt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Qe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Qe()!==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(Qe()!==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(Qe()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Mi="https://github.com/RyderAsKing/PiChamber/releases";function eh(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 th(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Ti(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function sh(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 nh(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 bl=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Ee.useState(null),[x,y]=Ee.useState("idle"),[m,h]=Ee.useState(null),[b,g]=Ee.useState(null),[S,v]=Ee.useState({}),E=n?.version?n.releaseUrl||`${Mi}/tag/v${n.version}`:Mi,j=n?.downloadUrl||E,k=i?.total?Math.round(i.downloaded/i.total*100):0,C=u==="web",w=u==="mobile",N=n?.updateCommand||"pichamber update",T=S.version||n?.version,O=S.channel||n?.channel;Ee.useEffect(()=>{e||(y("idle"),h(null),g(null),v({}))},[e]);const $=async(I=N)=>{(await ys(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},U=Ee.useCallback(async I=>{await Ta(I)},[]),K=Ee.useCallback(async()=>{const I=Qe();y("updating"),h(null),g(null),v({});const M=await Jf();if(Qe()!==I)return;if(!M.success){y("error"),h(M.error||"Update failed"),g(M.commands??null);return}if(v({version:M.targetVersion,channel:M.channel}),M.jobId){const G=await Zf(M.jobId,B=>{Qe()===I&&y(B)},void 0,void 0,I);if(G.stale||Qe()!==I)return;if(G.applied){window.location.reload();return}y("error"),h(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(M.autoRestart?"restarting":"reconnecting");const W=await Xf(n?.currentVersion,void 0,void 0,I);if(!(W.stale||Qe()!==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]),L=Ee.useCallback(()=>{U(j)},[U,j]),D=x!=="idle"&&x!=="error",R=Ee.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const M=nh(I);return M.length===0?{kind:"raw",title:"What's new",content:Ti(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((G,B)=>sh(G.version,B.version)).map(G=>({version:G.version,dateLabel:eh(G.date),content:Ti(th(G.raw)||I)}))}},[n?.body]);return s.jsx(ns,{open:e,onOpenChange:D?void 0:t,children:s.jsxs(rs,{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(us,{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||T||C&&O)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||T)&&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&&T&&s.jsx("span",{className:"text-muted-foreground/50","aria-hidden":"true",children:"→"}),T&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:T})]}),C&&O&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:O==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[C&&D&&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."})]}),R&&!D&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(As,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:R.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(),U(W.href))},children:s.jsx(Si,{content:R.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:R.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:M=>{const G=M.target.closest("a");G&&G.href&&(M.preventDefault(),M.stopPropagation(),U(G.href))},children:s.jsx(Si,{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})}),C&&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:()=>{$(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))]}),!C&&!w&&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:[!C&&!w&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!C&&!w&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!C&&!w&&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"]}),w&&s.jsxs(Ne,{onClick:L,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),C&&!D&&s.jsxs(Ne,{onClick:K,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),C&&D&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},xl=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})}),Bn=({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(Ue,{open:r,onOpenChange:o,children:[s.jsx($e,{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(Ke,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},yx="w-full min-w-40 max-w-48",wx="settings",rh="w-full min-w-40 max-w-48",vx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",oh="w-full max-w-[24rem]",Sx="min-w-0 flex-1",jx="flex w-full min-w-0 items-center gap-2",Cx="typography-meta shrink-0 text-muted-foreground tabular-nums",yl="space-y-3.5",ih="space-y-1.5",kx="typography-settings-page-title text-muted-foreground",ah="typography-settings-section-title text-foreground",wl="typography-settings-group-title text-foreground",Ho="typography-settings-field-label text-foreground",lh="typography-settings-description text-muted-foreground",_n="typography-meta text-muted-foreground",Ax="typography-meta font-medium text-foreground",Nx="typography-settings-section-title text-foreground",ch=({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:ah,children:e}):e,n,r!=null?s.jsx(Bn,{children:r}):null]}):null,t!=null?s.jsx("div",{className:lh,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},Ix=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),dh=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(wl,t),children:e}),Ex=({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(dh,{children:e}),n!=null?s.jsx(Bn,{children:n}):null]}):null,t!=null?s.jsx("p",{className:_n,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),En=({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:Ho,children:e}),n!=null?s.jsx(Bn,{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]})},Rx=({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:Ho,children:e}),n!=null?s.jsx(Bn,{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})]}),Dx=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),Px=({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})]}),uh=({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(oo,{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:Ho,children:n}),d,u!=null?s.jsx(Bn,{children:u}):null]}),p?s.jsx("span",{className:_n,children:r}):null]})]})},Mx=({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(xl,{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]})]}),Tx=({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(xl,{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})]})]}),Fx=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(ih,n),children:t});function Lx({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 vo="pichamber:server-update-channel-changed",Ox=()=>{typeof window<"u"&&window.dispatchEvent(new Event(vo))},fh=e=>typeof window>"u"?()=>{}:(window.addEventListener(vo,e),()=>window.removeEventListener(vo,e));class hh 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(zd,{className:"w-full max-w-md",children:[s.jsx(Ud,{className:"text-center",children:s.jsxs($d,{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(Kd,{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 mh(e){return s.jsx(hh,{...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 Bx=({active:e=!0})=>{const t=Te(n=>n.currentSessionId);return s.jsx(mh,{sessionId:t||void 0,children:s.jsx(Wd,{active:e},t??"no-session")})};function ph({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 vl=Ee.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=Ee.useRef(null),h=Ee.useRef(null),[b,g]=Ee.useState(null),S=c??b,v=Ee.useCallback(j=>{const k=m.current;if(!k)return;h.current={startY:j.clientY,startHeight:k.getBoundingClientRect().height};const C=j.currentTarget;C.setPointerCapture(j.pointerId);const w=T=>{const O=h.current;if(!O)return;const $=O.startHeight+(T.clientY-O.startY),U=Math.max(82,$);d?d(U):g(U)},N=()=>{h.current=null,C.removeEventListener("pointermove",w),C.removeEventListener("pointerup",N),C.removeEventListener("pointercancel",N)};C.addEventListener("pointermove",w),C.addEventListener("pointerup",N),C.addEventListener("pointercancel",N),j.preventDefault()},[d]),E=Ee.useCallback(j=>{if(j.target.closest('textarea, button, [role="separator"]'))return;const C=m.current?.querySelector("textarea");C&&document.activeElement!==C&&(j.preventDefault(),C.focus())},[]);return f?s.jsx(As,{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(ph,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});vl.displayName="Textarea";const Sl=[{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"}],Rn=Object.fromEntries(Sl.map(e=>[e.key,e.Icon])),So="pichamber:project-actions-updated",jl=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},ls=(e,t)=>`${jl(e)}::${t}`,Cl=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:d,divider:u=!0})=>s.jsx(ch,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:l}),jo=e=>e.name.trim().length>0&&e.command.trim().length>0,gh=e=>e.name.trim().length===0&&e.command.trim().length===0,bh=e=>!jo(e)&&!gh(e),xh=(e,t)=>e.some(r=>t.has(r.id)&&!jo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(jo)},yh=450,wh=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,vh=()=>({id:wh(),name:"",command:"",icon:"play"}),Sh=({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 io(e);if(g)return;n(S.actions),l(JSON.stringify({actions:S.actions})),d(new Set(S.actions.map(v=>v.id)))}catch{if(g)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=a.useMemo(()=>xh(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 Gd(e,{actions:g,primaryActionId:null})?(l(JSON.stringify({actions:g})),d(new Set(g.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(So,{detail:{projectId:e.id}})),!0):(ie.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}})())},yh);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const m=a.useCallback(()=>{const g=vh();n(S=>[...S,g])},[]),h=a.useCallback(g=>{n(S=>S.filter(v=>v.id!==g))},[]),b=a.useCallback((g,S)=>{n(v=>v.map(E=>E.id===g?S(E):E))},[]);return s.jsx(Cl,{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",oh),children:t.map((g,S)=>{const v=g.icon||"play",E=Rn[v]||"play",j=g.name.trim()||`Action ${S+1}`,k=bh(g);return s.jsxs("div",{className:yl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:wl,children:j}),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 ${j}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(En,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Sl.map(C=>{const w=C.Icon,N=(g.icon||"play")===C.key;return s.jsx("button",{type:"button",onClick:()=>b(g.id,T=>({...T,icon:C.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 ${C.label}`,children:s.jsx(P,{name:w,className:"h-4 w-4"})},C.key)})})})]}),s.jsx(Mn,{value:g.name,onChange:C=>b(g.id,w=>({...w,name:C.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(En,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(vl,{value:g.command,onChange:C=>b(g.id,w=>({...w,command:C.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(uh,{checked:g.autoOpenUrl===!0,onChange:C=>b(g.id,w=>({...w,...C?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${j}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(En,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Mn,{value:g.openUrl||"",onChange:C=>b(g.id,w=>({...w,openUrl:C.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},jh={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)"},Ch=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=$t(w=>w.providers),d=$t(w=>w.modelsMetadata),u=le(w=>w.hiddenModels),f=le(w=>w.isFavoriteModel),p=le(w=>w.toggleFavoriteModel),x=le(w=>w.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:m}=Hd(),[h,b]=a.useState(!1),[g,S]=a.useState("");a.useEffect(()=>{h?$t.getState().ensureModelMetadata():S("")},[h]);const v=e?c.find(w=>w.id===e.providerId):void 0,E=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,j=e?qd(E,e.modelId):t,k=a.useMemo(()=>e?u.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):u,[u,e]),C=a.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),b(!1)},[l]);return s.jsxs(Wt,{modal:!1,open:h,onOpenChange:w=>{r||b(w)},children:[s.jsx(Gt,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(Vd({size:"default"}),rh,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(Yd,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:j})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(Ht,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(Qd,{providers:c,favoriteModels:y,recentModels:m,modelsMetadata:d,searchQuery:g,onSearchQueryChange:S,onSelect:C,labels:{...jh,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:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>p(w.providerID,w.modelID),onReorderFavorite:(w,N)=>x(w.providerID,w.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},_r="w-full max-w-none",kh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=$t(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(Cl,{title:"Project",divider:!1,children:s.jsxs("div",{className:yl,children:[s.jsx(En,{label:"Name",settingsItem:"projects.name",controlClassName:_r,children:s.jsx(Mn,{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(En,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:_r,children:s.jsx(Ch,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:_r,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Ah=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(()=>Jd(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}},Nh=450,Ih=(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{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},Nh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Eh=({project:e,onIdentitySave:t})=>{const n=Ah(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return Ih(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(kh,{form:n}),s.jsx(Sh,{projectRef:r})]})},Rh=6e4,Dh=3e4,xn=new Map;let Fi=0,Li=!1;const Ph=()=>{if(Li||typeof window>"u")return;Li=!0;const e=()=>{const t=Date.now();t-Fi<Dh||typeof document<"u"&&document.hidden||(Fi=t,ht(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-BnZVqcki.js").then(r=>r.cy);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&Sr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},Sr=Ls()(vr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Mt(),resetForRuntimeSwitch:n=>{const r=n??Mt();xn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{Ph();const o=Mt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<Rh)return i.status;const c=xn.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 Mt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Mt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();xn.set(o,u);try{return await u}finally{xn.get(o)===u&&xn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&On(e=>{Sr.getState().resetForRuntimeSwitch(e.runtimeKey)});const Mh=()=>Sr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),Hn=100;function _x(){const e=le(w=>w.isArchivePageOpen),t=le(w=>w.setArchivePageOpen),n=le(w=>w.setActiveMainTab),r=Te(w=>w.setCurrentSession),o=Te(w=>w.unarchiveSession),i=sn(w=>w.homeDirectory),l=ao({archived:!0}),[c,d]=a.useState(""),[u,f]=a.useState(null),[p,x]=a.useState(Hn),y=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((w,N)=>(N.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const w=new Map;for(const N of m){const T=Ie(Nn(N))??"",O=w.get(T);if(O){O.sessions.push(N);continue}w.set(T,{directory:T,label:T?Tn(T,i)||T:"other projects",sessions:[N]})}return[...w.values()].sort((N,T)=>T.sessions.length-N.sessions.length)},[i,m]),b=a.useMemo(()=>y?m.filter(w=>(w.title??"").toLowerCase().includes(y)):u===null?m:h.find(w=>w.directory===u)?.sessions??[],[h,y,u,m]),g=b.slice(0,p),S=b.length-g.length,v=l.length,E=a.useCallback(w=>{f(w),x(Hn)},[]),j=a.useCallback(w=>{const N=Ie(Nn(w));r(w.id,N??void 0),n("chat"),t(!1)},[n,r,t]),k=a.useCallback(w=>{o(w.id).then(N=>{N?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const C=(w,N,T,O,$,U,K)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:$,title:U,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",K?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",O?"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:T})]}),K?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Ds.requestDelete({sessions:K,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity 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(Ke,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return s.jsx(kd,{open:e,onOpenChange:t,children:s.jsxs(Ad,{children:[s.jsx(Nd,{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(Id,{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(Ed,{className:"sr-only",children:"Archived sessions"}),s.jsx(Rd,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Dd,{"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:[C("__all__","All directories",v,u===null,()=>E(null)),h.map(w=>C(w.directory||"__none__",w.label,w.sessions.length,u===w.directory,()=>E(w.directory),w.directory||void 0,w.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:w=>{d(w.target.value),x(Hn)},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(w=>{const N=Ie(Nn(w))??"",T=N?Tn(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:()=>j(w),role:"button",tabIndex:0,onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),j(w))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:bs(w)}),y&&T?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:T}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:ff(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),k(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${bs(w)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),Ds.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${bs(w)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),S>0?s.jsx("button",{type:"button",onClick:()=>x(w=>w+Hn),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 Th=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}},Fh=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},es=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Lh=e=>{if(!e||typeof e!="object")return null;const t=es(e.input),n=es(e.output),r=es(e.cacheRead),o=es(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},Oi=e=>{const t=Lh(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:es(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=es(o.input),l=es(o.output),c=es(o.reasoning),d=es(o.cache?.read),u=es(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:i+l+c+d+u}},kl=380,zr=8,Oh=140;function Bh({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}=$o();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-kl-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)},Oh);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 Bi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},fr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),qn=({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})]}),_h=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=Bh({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(${kl}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(qn,{iconNode:s.jsx(Fa,{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(qn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:fr(r.cacheRead)})}),s.jsx(qn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:fr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(qn,{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-BbhXFTId.js","assets/useAppFontEffects-DviRbaCJ.js","assets/index-BnZVqcki.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BnieExes.css","assets/vendor-boot-Dgb9NVFe.js","assets/runtimeSurface-DBiUWYK2.js","assets/nativeFileSave-BzhtrDoD.js","assets/computeVirtualFileMetrics-BJjC-tXV.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/renderFileWithHighlighter-DJ9mk2bZ.js","assets/renderDiffWithHighlighter-CVLsdtQ5.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-DOPmc7GU.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-capacitor-keyboard-eTtI5go3.js","assets/SessionSwitcherDropdown-CfySKnUu.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as ht}from"./vendor-vite-runtime-DD1OZmLC.js";import{k as s,b2 as kd,b3 as Ad,b4 as Nd,b5 as Id,b6 as Ed,b7 as Rd,b8 as Dd,aO as Oo,aP as Pn,aQ as Pd,aR as Bo,aS as _o,aV as Md,b9 as Td,ba as Fd,bb as Ld,bc as Sa,bd as ja,be as Ca,bf as ka,bg as Aa,bh as Na,bi as Ia,aT as Ea,a$ as Ra,aY as Da,aZ as Pa,aW as zo,aX as Uo,bj as ro,aL as Od}from"./vendor-boot-Dgb9NVFe.js";import{a as Ee,R as a}from"./vendor-react-DASdDPIk.js";import{aW as Qs,aX as Bd,t as ie,a as ut,h as Te,a4 as an,B as Ne,I as P,ai as Mn,aY as Ma,ak as ns,al as rs,am as vs,an as us,ao as Ss,ap as Ts,aM as Ds,aZ as Ps,a_ as _d,g as Ys,a$ as Or,b0 as wi,b1 as vi,aF as An,e as er,o as Ta,aj as As,b2 as Si,ae as ys,a9 as Ue,aa as $e,ac as Ke,b3 as oo,b4 as zd,b5 as Ud,b6 as $d,b7 as Kd,b8 as Wd,b9 as io,ba as Gd,a8 as Wt,ab as Gt,ad as Ht,H as $t,bb as Hd,bc as qd,bd as Yd,be as Vd,bf as Qd,bg as Jd,aJ as ao,r as Nn,x as $o,at as Xd,aE as Zd,aI as Fa,bh as La,S as ws,bi as eu,bj as tu,bk as su,bl as nu,d as Oa,q as Fs,aD as Ba,bm as wr,bn as ji,bo as _a,bp as pt,bq as ru,aK as za,br as Ua,bs as $a,bt as Ka,af as ft,bu as Wa,ay as ou,i as Ga,k as iu,bv as au,j as lu,bw as Ws,b as Ci,c as cu,bx as du,u as uu,aL as fu,aO as hu,by as lo,bz as mu,bA as pu,aN as gu,bB as bu,bC as xu,V as yu,ag as en,aq as Ha,F as wu,p as vu,bD as Su,m as ju,bE as Cu,bF as qa,bG as ku,bH as Au,bI as Nu,bJ as Iu,bK as Eu,bL as Ru,bM as Du,bN as Pu,bO as Mu,bP as Tu,a5 as Fu,bQ as Lu}from"./useAppFontEffects-DviRbaCJ.js";import{_ as ki,D as Ou,$ as Bu,S as tn,a0 as Ya,a1 as Va,a2 as _u,a3 as zu,u as sn,L as Uu,a4 as $u,a5 as Ku,t as le,m as Tt,o as _,a6 as Wu,f as Qe,a as Mt,A as On,C as Ie,a7 as Tn,a8 as Kt,a9 as co,aa as uo,ab as Qa,v as ds,U as Ko,V as lr,ac as Gu,w as Ja,ad as Hu,ae as Xa,H as qu,R as Za,E as In,af as fo,h as ho,d as Kn,ag as Yu,ah as Vu,ai as Qu,aj as Ai,ak as bn,al as Br,am as mo,an as cr,ao as Ns,ap as Ni,aq as po,ar as el,as as go,at as Ju,au as Xu,av as Zu,aw as ef,ax as tf,ay as sf,az as nf,aA as rf,aB as of,Z as tl,aC as af,aD as lf,Q as cf,aE as df,K as uf}from"./index-BnZVqcki.js";import{g as bs,b as ff,c as sl,r as hf,d as nl,s as tr,e as rl,h as Ms,i as nn,j as mf,k as pf,l as gf,m as bf,n as Wo,o as ol,f as xf,a as Ii,S as yf,t as wf,p as vf}from"./SessionUnreadDot-CmEF9sxM.js";import{c as Ls,d as vr,p as il,a as Sf}from"./vendor-zustand-CUi8eEds.js";/* empty css */import{saveOrShareFile as jf}from"./nativeFileSave-BzhtrDoD.js";import{usePermissionStore as Cf}from"./permissionStore-B9Hkrqny.js";const kf="chat";function al(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Qs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Qs.SETTINGS,n),t}return e.tab!==kf&&t.set(Qs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Qs.FILE,e.diffFile),t}function Af(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 Nf(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=al(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Qs.SESSION)&&t.set(Qs.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 bo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Nf(e)))try{const n=al(e),r=Af(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const If=["typescript","javascript","tsx","jsx","json","markdown"],ll={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Ei=null;const cl=()=>(Ei??=Promise.all([ht(()=>import("./index-BbhXFTId.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42])),ht(()=>import("./workerFactory-tw7cIdmV.js"),[]),ht(()=>import("./appThemeRegistry-gegrE2dq.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})),Ei),Fn={},Ri=new Set,xo=new Set;let sr={light:"pierre-light",dark:"pierre-dark"};const Ef=()=>{for(const e of xo)e()},dl=(e,t)=>{t.setRenderOptions({theme:sr,lineDiffType:ll[e].lineDiffType})},yo=e=>{typeof window>"u"||Ri.has(e)||(Ri.add(e),cl().then(t=>{if(Fn[e])return;const n=ll[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:If,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Fn[e]=r,dl(e,r),Ef()}))},Rf=e=>(xo.add(e),()=>xo.delete(e)),Df=e=>{if(!(sr.light===e.light&&sr.dark===e.dark)){sr=e;for(const t of Object.keys(Fn)){const n=Fn[t];n&&dl(t,n)}}},cx=({children:e})=>{const t=Bd(),n=ki(!1),r=ki(!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 Ee.useEffect(()=>{let d=!1;return cl().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Df({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ee.useEffect(()=>{if(typeof window>"u")return;const d=()=>{yo("unified"),yo("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})},dx=(e="unified")=>{const t=Ee.useSyncExternalStore(Rf,()=>Fn[e],()=>{});return Ee.useEffect(()=>{yo(e)},[e]),t};let Wn=null;const ux=()=>{if(typeof window>"u"||typeof document>"u"||Wn)return()=>{};const e=()=>{document.visibilityState!=="hidden"&&Ou()};document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),window.addEventListener("online",e);let t=!1;const n=()=>{t||(t=!0,document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),window.removeEventListener("online",e),Wn===n&&(Wn=null))};return Wn=n,n},Pf=e=>e==="/",rn=e=>e.replace(/\\/g,"/"),on=e=>{if(!e||Pf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},Xs=e=>e.endsWith("/"),dr=e=>{const t=e.trim();return!t||Xs(t)?t:`${t}/`},Go=e=>e.lastIndexOf("/"),ul=e=>{if(Xs(e))return e;const t=Go(e);return t<0?e:e.slice(0,t+1)},fl=e=>{const t=Go(e);return e.slice(t+1)},hl=e=>{const t=on(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Go(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},ml=e=>Xs(e)&&hl(e)!==null,Mf=e=>{if(!ml(e))return null;const t=on(e.trim());return fl(t)||t},Tf=(e,t)=>`${ul(e)}${t}/`,Is=e=>{if(!e)return null;const t=on(rn(e.trim()));return t?t.toLowerCase():null},Di=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},Ff=(e,t)=>{const n=on(rn(e.trim())),r=on(rn(t.trim()));if(!n)return"";if(!r)return dr(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:dr(n)},Lf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,wo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Of=async()=>Bu({fresh:!0}),Bf=()=>{const[e,t]=Ee.useState(!1),[n,r]=Ee.useState(!1);Ee.useEffect(()=>{t(tn()),r(Ya())},[]);const o=Ee.useCallback(async c=>e?await Va(c):{success:!0,path:c},[e]),i=Ee.useCallback(async c=>e?await _u():{success:!0},[e]),l=Ee.useCallback(async c=>e?await zu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function _f({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=sn(se=>se.homeDirectory),{canRequestAccess:o,startAccessing:i}=Bf(),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,v]=a.useState(null),[E,j]=a.useState(0),[k,C]=a.useState(0),[w,N]=a.useState(!1),[T,O]=a.useState(!1),[$,U]=a.useState("right"),K=a.useRef("~/"),L=d||r;a.useEffect(()=>{if(!e)return;p("~/"),y([]),C(0),N(!1),O(!1),K.current="~/",U("right"),n||requestAnimationFrame(()=>wo(l.current));let se=!1;return(async()=>{const Ce=await Of();se||(u(Ce||r||""),n||requestAnimationFrame(()=>wo(l.current)))})(),()=>{se=!0}},[r,e,n]);const D=a.useMemo(()=>ul(f),[f]),R=a.useMemo(()=>Xs(f)?"":fl(f),[f]),I=a.useMemo(()=>L?Di(D,L):"",[D,L]);a.useEffect(()=>{const se=K.current;se!==D&&(U(D.length>=se.length?"right":"left"),K.current=D)},[D]),a.useEffect(()=>{if(!e||!I){y([]),v(null);return}let se=!1;return h(!0),g(!1),v(null),Uu(I).then(ce=>{if(se)return;g(!1),v(null);const Ce=ce.filter(ve=>ve.isDirectory).map(ve=>({name:ve.name,path:rn(ve.path)})).sort((ve,Ge)=>ve.name.localeCompare(Ge.name));y(Ce)}).catch(ce=>{if(!se){y([]);const Ce=$u(ce)?ce.reason:"unknown";v(Ce),g(Ce==="not-found")}}).finally(()=>{se||h(!1)}),()=>{se=!0}},[I,E,e]);const M=a.useMemo(()=>{const se=R.toLowerCase(),ce=T||R.startsWith(".");return x.filter(Ce=>Ce.name.toLowerCase().startsWith(se)&&(ce||!Ce.name.startsWith(".")))},[R,x,T]),W=a.useMemo(()=>Mf(f),[f]),G=a.useMemo(()=>hl(f),[f]),B=a.useMemo(()=>{const se=[],ce=Is(I);ml(f)&&W&&G&&se.push({type:"parent",value:"browse:up",name:W,path:G,alreadyAdded:!!(ce&&t.has(ce))});for(const Ce of M){const ve=Is(Ce.path);se.push({type:"directory",value:`browse:${Ce.path}`,name:Ce.name,path:Ce.path,alreadyAdded:!!(ve&&t.has(ve))})}return se},[t,I,W,M,G,f]);a.useEffect(()=>{C(0)},[f,B.length]);const xe=a.useMemo(()=>L?on(Di(f,L)):"",[L,f]),V=Is(xe),je=!!(V&&t.has(V)),Re=a.useMemo(()=>R?M.find(se=>se.name===R)??null:null,[R,M]),H=!!(xe&&!je&&(S===null||S==="not-found")&&(Xs(f)&&b||!Xs(f)&&R.trim().length>0&&Re===null)),z=B[k]??null,Y=!!z,X=a.useCallback(se=>{p(dr(se))},[]),te=a.useCallback(se=>{p(Tf(f,se.name))},[f]),ue=a.useCallback(se=>{if(se){if(se.type==="parent"){X(se.path);return}te(se)}},[X,te]),he=a.useCallback(async se=>{const ce=await i(se);if(!ce.success)return ie.error("Failed to open directory",{description:ce.error||"Desktop could not grant file access."}),!1;const Ce=L?Ff(se,L):dr(rn(se));return X(Ce),!0},[X,L,i]),Q=a.useCallback(async()=>{if(!w){N(!0);try{if(Ya()){const ce=await Va(xe);if(!ce.success||!ce.path){ce.error&&ce.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:ce.error});return}await he(ce.path);return}const se=await Ku(xe);if(se.status==="cancelled")return;if(se.status!=="picked"){ie.error("Couldn't open a folder picker",{description:se.error});return}await he(se.path)}catch(se){ie.error("Failed to select directory",{description:se instanceof Error?se.message:"Unknown error occurred."})}finally{N(!1)}}},[he,w,xe]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:b,browseErrorReason:S,browseReloadKey:E,setBrowseReloadKey:j,highlightedIndex:k,setHighlightedIndex:C,isPickingLocation:w,showHidden:T,setShowHidden:O,folderEnterFrom:$,explorerRootDirectory:L,browseDirectoryDisplayPath:D,browseDirectoryAbsolutePath:I,browseFilterQuery:R,filteredEntries:M,rows:B,targetPath:xe,isAlreadyAdded:je,shouldCreateTarget:H,highlightedRow:z,hasHighlightedBrowseItem:Y,canRequestAccess:o,browseToDisplayPath:X,browseToEntry:te,executeRow:ue,applyPickedLocation:he,handleBrowseLocation:Q}}function zf({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=ut(O=>O.addProject),p=le(O=>O.setActiveMainTab),x=le(O=>O.setSessionSwitcherOpen),y=Te(O=>O.openNewSessionDraft),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,v]=a.useState("");a.useEffect(()=>{e&&(h(!1),g(!1),v(""))},[e]);const E=a.useCallback((O,$)=>{p("chat"),n&&x(!1),y({selectedProjectId:O,directoryOverride:$}),t()},[n,t,y,p,x]),j=a.useCallback(async O=>{if(!O||m)return;const $=Is(O);if($&&r.has($))return;let U=O;h(!0);try{const K=!b&&i&&Is(O)===Is(o);if(b){const D=S.trim();if(!D){ie.error("Enter a repository URL before cloning.");return}const R=await Tt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:D,destinationPath:O})});if(!R.ok)throw new Error("Failed to clone git repository");U=(await R.json()).path||O}else if(K&&!(await Tt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:O})})).ok)throw new Error("Failed to select directory");const L=f(U);if(!L){ie.error("Failed to add folder",{description:"Please select a valid directory path."});return}E(L.id,L.path)}catch(K){ie.error("Failed to select directory",{description:K instanceof Error?K.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,C=k&&S.trim().length>0,w=b?C:k,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:b,setIsCloneMode:g,cloneRemoteUrl:S,setCloneRemoteUrl:v,canSubmit:w,submitActionLabel:d?"Already added":b?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:j}}const Uf=({open:e,onOpenChange:t})=>{const n=ut(Q=>Q.projects),{isMobile:r,isTablet:o}=an(),i=r||o,l=a.useMemo(()=>new Set(n.map(Q=>Is(Q.path)).filter(Q=>!!Q)),[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:v,folderEnterFrom:E,browseDirectoryDisplayPath:j,browseDirectoryAbsolutePath:k,rows:C,targetPath:w,isAlreadyAdded:N,shouldCreateTarget:T,highlightedRow:O,hasHighlightedBrowseItem:$,canRequestAccess:U,executeRow:K,handleBrowseLocation:L}=_f({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:D,isCloneMode:R,setIsCloneMode:I,cloneRemoteUrl:M,setCloneRemoteUrl:W,canSubmit:G,submitActionLabel:B,submitModifierLabel:xe,finalizeSelection:V}=zf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:T,browseErrorReason:y,browseDirectoryAbsolutePath:k,isAlreadyAdded:N,isPickingLocation:g});a.useLayoutEffect(()=>{const Q=d.current;Q&&(Q.scrollLeft=Q.scrollWidth)},[d,f]),a.useLayoutEffect(()=>{!e||i||wo(d.current)},[d,e,i]),a.useLayoutEffect(()=>{const Q=C[h];Q&&u.current.get(Q.value)?.scrollIntoView({block:"nearest"})},[h,u,C]);const je=a.useCallback(Q=>{if(Q.key==="ArrowDown"){Q.preventDefault(),b(se=>Math.min(C.length-1,se+1));return}if(Q.key==="ArrowUp"){Q.preventDefault(),b(se=>Math.max(0,se-1));return}if(Q.key==="Enter"){if(Q.preventDefault(),Lf(Q)){V(w);return}$&&K(O);return}Q.key==="Backspace"&&f===""&&(Q.preventDefault(),c())},[K,V,c,$,O,f,C.length,b,w]),Re=s.jsxs("button",{type:"button",onClick:()=>v(Q=>!Q),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[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"]}),H=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(Mn,{ref:d,value:f,onChange:Q=>p(rn(Q.target.value)),onKeyDown:je,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:D||g,onMouseDown:Q=>Q.preventDefault(),onClick:()=>{L()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(P,{name:"folder-open",className:"h-3.5 w-3.5"}),g?"Opening...":"Browse"]})]})}),z=C.some(Q=>Q.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":R,disabled:D||g,onClick:()=>I(Q=>!Q),children:[s.jsx(P,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),R?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(Mn,{value:M,onChange:Q=>W(Q.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})})]}):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"&&U?s.jsx(Ne,{size:"xs",onClick:()=>{L()},disabled:g,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:()=>m(Q=>Q+1),children:"Try again"})]})]}):C.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:C.map((Q,se)=>{const ce=se===h,Ce=Q.type==="directory"&&z;return s.jsxs("button",{ref:ve=>{ve?u.current.set(Q.value,ve):u.current.delete(Q.value)},type:"button","aria-label":Q.type==="parent"?Q.alreadyAdded?`Go back from ${Q.name}, already added`:`Go back from ${Q.name}`:Q.alreadyAdded?`Open ${Q.name}, already added`:`Open ${Q.name}`,onMouseEnter:()=>b(se),onMouseDown:ve=>ve.preventDefault(),onClick:()=>K(Q),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",ce&&"bg-interactive-selection text-interactive-selection-foreground",!ce&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",Ce&&"pl-4"),children:[Q.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:Q.name})]}),Q.alreadyAdded?s.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",ce?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,Q.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"})]},Q.value)})})},j)]})}),X=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[H,Y]}),te=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:xe}),s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),ue=s.jsx(Ne,{size:r?"xs":"default",onClick:()=>{V(w)},disabled:!G,className:_(r&&"w-full flex-1"),children:B}),he=()=>s.jsxs(s.Fragment,{children:[r?null:te,s.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:ue})]});return r?s.jsx(Ma,{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:he()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:Re}),X]})}):s.jsx(ns,{open:e,onOpenChange:t,children:s.jsxs(rs,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(vs,{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(us,{children:"Add folder"}),s.jsx(Ss,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Re]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:X}),s.jsx(Ts,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:he()})]})})},Gn=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,fx=()=>{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=le(k=>k.showDeletionDialog),u=le(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:x}=an(),y=f||p||x;a.useEffect(()=>Wu(()=>{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 T=k.sessions[0];await l(T.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const C=k.sessions.map(T=>T.id),{deletedIds:w,failedIds:N}=await c(C);if(w.length>0){const T=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;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Gn(T)})}N.length>0&&ie.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:Gn("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Ds.onDeleteRequest(k=>{if(!d){b(k);return}m(k)}),[m,d,b]),a.useEffect(()=>Ds.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)){ie.error("Failed to delete session"),i(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=n.sessions.map(T=>T.id),C=await c(k),w=C.deletedIds,N=C.failedIds;if(w.length>0){const T=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;ie.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Gn(T),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(ie.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:Gn("Please try again in a moment.")}),w.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.`:"",v=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:bs(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"})]})]}),j=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(Ma,{open:!!n,onClose:()=>{o||h()},title:j,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}),v]})}):s.jsx(ns,{open:!!n,onOpenChange:k=>{if(!k){if(o)return;h()}},children:s.jsxs(rs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(vs,{children:[s.jsx(us,{children:j}),S&&s.jsx(Ss,{children:S})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),s.jsx(Ts,{className:"mt-2 gap-2 pt-1 pb-1",children:E})]})}),s.jsx(Uf,{open:e,onOpenChange:t})]})},hx=()=>{const e=Ps(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!_d(t)||!t.receipt||(Ps.getState().markNotificationSent(t.key),ie.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},$f=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","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"]}],Kf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Wf(e){const t=e.trim().toLowerCase();return $f.find(n=>n.slug===t)??null}function Gf(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";const n=Kf[t];if(n)return n;const r=Wf(t);return r?r.slug:"home"}function mx(e){switch(e){case"general":return"equalizer";case"projects":return"folders";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 px(){const e=a.useRef(!1),t=a.useRef(!1),n=Te(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),i=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Te.getState().currentSessionId,x=Ys().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==x){const y=Te.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(Gf(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,l]),d=a.useCallback(()=>{const f=Te.getState(),p=Ys().getState(),x=le.getState();return{sessionId:Or({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();bo(p,f)},[d]);a.useEffect(()=>{if(e.current||(e.current=!0,!wi()))return;const f=vi();(async()=>(await c(f),bo({...d(),sessionId:f.sessionId??Or({currentSessionId:Te.getState().currentSessionId,piSelectedSessionId:Ys().getState().selectedSessionId,draft:Te.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),a.useEffect(()=>{const f=()=>{const b=Te.getState(),g=Ys().getState();return Or({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=Ys().subscribe(()=>{y()});return()=>{m(),h()}},[u]),a.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,x=le.getState().settingsPage,y=le.getState().pendingDiffFile;return le.subscribe(h=>{if(t.current)return;const b=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==p,S=h.settingsPage!==x,v=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(b||g||S||v)&&u()})},[u]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=vi();if(wi())c(p);else{const x=le.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function Hf(e=!0){const t=er(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 gx(){const e=An(t=>t.connection==="ready",void 0,"chrome");return Hf(e),null}const Pi=12,qf=[{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"}],Yf=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=qf,onComplete:i})=>{const l=Ee.useRef(!1);Ee.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Ee.useMemo(()=>Array.from({length:Pi},(d,u)=>{const f=Math.PI*2*u/Pi;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},Vf=({durationMs:e=3400}={})=>{const[t,n]=Ee.useState({isActive:!1,cycle:0}),r=Ee.useRef(null),o=Ee.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Ee.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ee.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 Ee.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},pl=a.createContext(void 0),bx=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=Vf(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(pl.Provider,{value:i,children:[e,s.jsx(Yf,{isActive:t,burstKey:n})]})},Qf={triggerFireworks:()=>{},dismissFireworks:()=>{}},xx=()=>a.useContext(pl)??Qf,ur=2e3,gl=600*1e3;async function Jf(){try{const e=await Tt("/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 Xf(e,t=Math.ceil(gl/ur),n=ur,r=Qe()){for(let o=0;o<t;o++){if(Qe()!==r)return{applied:!1,stale:!0};try{const i=await Tt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Qe()!==r)return{applied:!1,stale:!0};if(i.ok){const l=await i.json().catch(()=>null);if(Qe()!==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(Qe()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function Zf(e,t,n=Math.ceil(gl/ur),r=ur,o=Qe()){for(let i=0;i<n;i++){if(Qe()!==o)return{applied:!1,stale:!0};try{const l=await Tt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Qe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Qe()!==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(Qe()!==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(Qe()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Mi="https://github.com/RyderAsKing/PiChamber/releases";function eh(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 th(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Ti(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function sh(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 nh(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 bl=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Ee.useState(null),[x,y]=Ee.useState("idle"),[m,h]=Ee.useState(null),[b,g]=Ee.useState(null),[S,v]=Ee.useState({}),E=n?.version?n.releaseUrl||`${Mi}/tag/v${n.version}`:Mi,j=n?.downloadUrl||E,k=i?.total?Math.round(i.downloaded/i.total*100):0,C=u==="web",w=u==="mobile",N=n?.updateCommand||"pichamber update",T=S.version||n?.version,O=S.channel||n?.channel;Ee.useEffect(()=>{e||(y("idle"),h(null),g(null),v({}))},[e]);const $=async(I=N)=>{(await ys(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},U=Ee.useCallback(async I=>{await Ta(I)},[]),K=Ee.useCallback(async()=>{const I=Qe();y("updating"),h(null),g(null),v({});const M=await Jf();if(Qe()!==I)return;if(!M.success){y("error"),h(M.error||"Update failed"),g(M.commands??null);return}if(v({version:M.targetVersion,channel:M.channel}),M.jobId){const G=await Zf(M.jobId,B=>{Qe()===I&&y(B)},void 0,void 0,I);if(G.stale||Qe()!==I)return;if(G.applied){window.location.reload();return}y("error"),h(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(M.autoRestart?"restarting":"reconnecting");const W=await Xf(n?.currentVersion,void 0,void 0,I);if(!(W.stale||Qe()!==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]),L=Ee.useCallback(()=>{U(j)},[U,j]),D=x!=="idle"&&x!=="error",R=Ee.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const M=nh(I);return M.length===0?{kind:"raw",title:"What's new",content:Ti(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((G,B)=>sh(G.version,B.version)).map(G=>({version:G.version,dateLabel:eh(G.date),content:Ti(th(G.raw)||I)}))}},[n?.body]);return s.jsx(ns,{open:e,onOpenChange:D?void 0:t,children:s.jsxs(rs,{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(us,{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||T||C&&O)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||T)&&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&&T&&s.jsx("span",{className:"text-muted-foreground/50","aria-hidden":"true",children:"→"}),T&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:T})]}),C&&O&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:O==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[C&&D&&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."})]}),R&&!D&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(As,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:R.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(),U(W.href))},children:s.jsx(Si,{content:R.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:R.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:M=>{const G=M.target.closest("a");G&&G.href&&(M.preventDefault(),M.stopPropagation(),U(G.href))},children:s.jsx(Si,{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})}),C&&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:()=>{$(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))]}),!C&&!w&&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:[!C&&!w&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!C&&!w&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!C&&!w&&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"]}),w&&s.jsxs(Ne,{onClick:L,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),C&&!D&&s.jsxs(Ne,{onClick:K,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),C&&D&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},xl=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})}),Bn=({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(Ue,{open:r,onOpenChange:o,children:[s.jsx($e,{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(Ke,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},yx="w-full min-w-40 max-w-48",wx="settings",rh="w-full min-w-40 max-w-48",vx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",oh="w-full max-w-[24rem]",Sx="min-w-0 flex-1",jx="flex w-full min-w-0 items-center gap-2",Cx="typography-meta shrink-0 text-muted-foreground tabular-nums",yl="space-y-3.5",ih="space-y-1.5",kx="typography-settings-page-title text-muted-foreground",ah="typography-settings-section-title text-foreground",wl="typography-settings-group-title text-foreground",Ho="typography-settings-field-label text-foreground",lh="typography-settings-description text-muted-foreground",_n="typography-meta text-muted-foreground",Ax="typography-meta font-medium text-foreground",Nx="typography-settings-section-title text-foreground",ch=({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:ah,children:e}):e,n,r!=null?s.jsx(Bn,{children:r}):null]}):null,t!=null?s.jsx("div",{className:lh,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},Ix=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),dh=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(wl,t),children:e}),Ex=({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(dh,{children:e}),n!=null?s.jsx(Bn,{children:n}):null]}):null,t!=null?s.jsx("p",{className:_n,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),En=({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:Ho,children:e}),n!=null?s.jsx(Bn,{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]})},Rx=({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:Ho,children:e}),n!=null?s.jsx(Bn,{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})]}),Dx=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),Px=({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})]}),uh=({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(oo,{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:Ho,children:n}),d,u!=null?s.jsx(Bn,{children:u}):null]}),p?s.jsx("span",{className:_n,children:r}):null]})]})},Mx=({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(xl,{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]})]}),Tx=({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(xl,{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})]})]}),Fx=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(ih,n),children:t});function Lx({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 vo="pichamber:server-update-channel-changed",Ox=()=>{typeof window<"u"&&window.dispatchEvent(new Event(vo))},fh=e=>typeof window>"u"?()=>{}:(window.addEventListener(vo,e),()=>window.removeEventListener(vo,e));class hh 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(zd,{className:"w-full max-w-md",children:[s.jsx(Ud,{className:"text-center",children:s.jsxs($d,{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(Kd,{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 mh(e){return s.jsx(hh,{...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 Bx=({active:e=!0})=>{const t=Te(n=>n.currentSessionId);return s.jsx(mh,{sessionId:t||void 0,children:s.jsx(Wd,{active:e},t??"no-session")})};function ph({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 vl=Ee.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=Ee.useRef(null),h=Ee.useRef(null),[b,g]=Ee.useState(null),S=c??b,v=Ee.useCallback(j=>{const k=m.current;if(!k)return;h.current={startY:j.clientY,startHeight:k.getBoundingClientRect().height};const C=j.currentTarget;C.setPointerCapture(j.pointerId);const w=T=>{const O=h.current;if(!O)return;const $=O.startHeight+(T.clientY-O.startY),U=Math.max(82,$);d?d(U):g(U)},N=()=>{h.current=null,C.removeEventListener("pointermove",w),C.removeEventListener("pointerup",N),C.removeEventListener("pointercancel",N)};C.addEventListener("pointermove",w),C.addEventListener("pointerup",N),C.addEventListener("pointercancel",N),j.preventDefault()},[d]),E=Ee.useCallback(j=>{if(j.target.closest('textarea, button, [role="separator"]'))return;const C=m.current?.querySelector("textarea");C&&document.activeElement!==C&&(j.preventDefault(),C.focus())},[]);return f?s.jsx(As,{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(ph,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});vl.displayName="Textarea";const Sl=[{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"}],Rn=Object.fromEntries(Sl.map(e=>[e.key,e.Icon])),So="pichamber:project-actions-updated",jl=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},ls=(e,t)=>`${jl(e)}::${t}`,Cl=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:d,divider:u=!0})=>s.jsx(ch,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:l}),jo=e=>e.name.trim().length>0&&e.command.trim().length>0,gh=e=>e.name.trim().length===0&&e.command.trim().length===0,bh=e=>!jo(e)&&!gh(e),xh=(e,t)=>e.some(r=>t.has(r.id)&&!jo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(jo)},yh=450,wh=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,vh=()=>({id:wh(),name:"",command:"",icon:"play"}),Sh=({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 io(e);if(g)return;n(S.actions),l(JSON.stringify({actions:S.actions})),d(new Set(S.actions.map(v=>v.id)))}catch{if(g)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=a.useMemo(()=>xh(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 Gd(e,{actions:g,primaryActionId:null})?(l(JSON.stringify({actions:g})),d(new Set(g.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(So,{detail:{projectId:e.id}})),!0):(ie.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}})())},yh);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const m=a.useCallback(()=>{const g=vh();n(S=>[...S,g])},[]),h=a.useCallback(g=>{n(S=>S.filter(v=>v.id!==g))},[]),b=a.useCallback((g,S)=>{n(v=>v.map(E=>E.id===g?S(E):E))},[]);return s.jsx(Cl,{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",oh),children:t.map((g,S)=>{const v=g.icon||"play",E=Rn[v]||"play",j=g.name.trim()||`Action ${S+1}`,k=bh(g);return s.jsxs("div",{className:yl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:wl,children:j}),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 ${j}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(En,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Sl.map(C=>{const w=C.Icon,N=(g.icon||"play")===C.key;return s.jsx("button",{type:"button",onClick:()=>b(g.id,T=>({...T,icon:C.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 ${C.label}`,children:s.jsx(P,{name:w,className:"h-4 w-4"})},C.key)})})})]}),s.jsx(Mn,{value:g.name,onChange:C=>b(g.id,w=>({...w,name:C.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(En,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(vl,{value:g.command,onChange:C=>b(g.id,w=>({...w,command:C.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(uh,{checked:g.autoOpenUrl===!0,onChange:C=>b(g.id,w=>({...w,...C?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${j}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(En,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Mn,{value:g.openUrl||"",onChange:C=>b(g.id,w=>({...w,openUrl:C.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},jh={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)"},Ch=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=$t(w=>w.providers),d=$t(w=>w.modelsMetadata),u=le(w=>w.hiddenModels),f=le(w=>w.isFavoriteModel),p=le(w=>w.toggleFavoriteModel),x=le(w=>w.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:m}=Hd(),[h,b]=a.useState(!1),[g,S]=a.useState("");a.useEffect(()=>{h?$t.getState().ensureModelMetadata():S("")},[h]);const v=e?c.find(w=>w.id===e.providerId):void 0,E=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,j=e?qd(E,e.modelId):t,k=a.useMemo(()=>e?u.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):u,[u,e]),C=a.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),b(!1)},[l]);return s.jsxs(Wt,{modal:!1,open:h,onOpenChange:w=>{r||b(w)},children:[s.jsx(Gt,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(Vd({size:"default"}),rh,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(Yd,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:j})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(Ht,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(Qd,{providers:c,favoriteModels:y,recentModels:m,modelsMetadata:d,searchQuery:g,onSearchQueryChange:S,onSelect:C,labels:{...jh,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:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>p(w.providerID,w.modelID),onReorderFavorite:(w,N)=>x(w.providerID,w.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},_r="w-full max-w-none",kh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=$t(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(Cl,{title:"Project",divider:!1,children:s.jsxs("div",{className:yl,children:[s.jsx(En,{label:"Name",settingsItem:"projects.name",controlClassName:_r,children:s.jsx(Mn,{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(En,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:_r,children:s.jsx(Ch,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:_r,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Ah=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(()=>Jd(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}},Nh=450,Ih=(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{ie.error("Failed to save project settings")}}finally{l.current=!1}})())},Nh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Eh=({project:e,onIdentitySave:t})=>{const n=Ah(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return Ih(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(kh,{form:n}),s.jsx(Sh,{projectRef:r})]})},Rh=6e4,Dh=3e4,xn=new Map;let Fi=0,Li=!1;const Ph=()=>{if(Li||typeof window>"u")return;Li=!0;const e=()=>{const t=Date.now();t-Fi<Dh||typeof document<"u"&&document.hidden||(Fi=t,ht(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-BnZVqcki.js").then(r=>r.cy);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&Sr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},Sr=Ls()(vr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Mt(),resetForRuntimeSwitch:n=>{const r=n??Mt();xn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{Ph();const o=Mt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<Rh)return i.status;const c=xn.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 Mt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Mt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();xn.set(o,u);try{return await u}finally{xn.get(o)===u&&xn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&On(e=>{Sr.getState().resetForRuntimeSwitch(e.runtimeKey)});const Mh=()=>Sr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),Hn=100;function _x(){const e=le(w=>w.isArchivePageOpen),t=le(w=>w.setArchivePageOpen),n=le(w=>w.setActiveMainTab),r=Te(w=>w.setCurrentSession),o=Te(w=>w.unarchiveSession),i=sn(w=>w.homeDirectory),l=ao({archived:!0}),[c,d]=a.useState(""),[u,f]=a.useState(null),[p,x]=a.useState(Hn),y=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((w,N)=>(N.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const w=new Map;for(const N of m){const T=Ie(Nn(N))??"",O=w.get(T);if(O){O.sessions.push(N);continue}w.set(T,{directory:T,label:T?Tn(T,i)||T:"other projects",sessions:[N]})}return[...w.values()].sort((N,T)=>T.sessions.length-N.sessions.length)},[i,m]),b=a.useMemo(()=>y?m.filter(w=>(w.title??"").toLowerCase().includes(y)):u===null?m:h.find(w=>w.directory===u)?.sessions??[],[h,y,u,m]),g=b.slice(0,p),S=b.length-g.length,v=l.length,E=a.useCallback(w=>{f(w),x(Hn)},[]),j=a.useCallback(w=>{const N=Ie(Nn(w));r(w.id,N??void 0),n("chat"),t(!1)},[n,r,t]),k=a.useCallback(w=>{o(w.id).then(N=>{N?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const C=(w,N,T,O,$,U,K)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:$,title:U,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",K?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",O?"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:T})]}),K?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Ds.requestDelete({sessions:K,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity 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(Ke,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return s.jsx(kd,{open:e,onOpenChange:t,children:s.jsxs(Ad,{children:[s.jsx(Nd,{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(Id,{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(Ed,{className:"sr-only",children:"Archived sessions"}),s.jsx(Rd,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Dd,{"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:[C("__all__","All directories",v,u===null,()=>E(null)),h.map(w=>C(w.directory||"__none__",w.label,w.sessions.length,u===w.directory,()=>E(w.directory),w.directory||void 0,w.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:w=>{d(w.target.value),x(Hn)},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(w=>{const N=Ie(Nn(w))??"",T=N?Tn(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:()=>j(w),role:"button",tabIndex:0,onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),j(w))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:bs(w)}),y&&T?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:T}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:ff(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),k(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${bs(w)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),Ds.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${bs(w)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),S>0?s.jsx("button",{type:"button",onClick:()=>x(w=>w+Hn),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 Th=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}},Fh=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},es=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Lh=e=>{if(!e||typeof e!="object")return null;const t=es(e.input),n=es(e.output),r=es(e.cacheRead),o=es(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},Oi=e=>{const t=Lh(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:es(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=es(o.input),l=es(o.output),c=es(o.reasoning),d=es(o.cache?.read),u=es(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:i+l+c+d+u}},kl=380,zr=8,Oh=140;function Bh({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}=$o();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-kl-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)},Oh);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 Bi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},fr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),qn=({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})]}),_h=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=Bh({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(${kl}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(qn,{iconNode:s.jsx(Fa,{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(qn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:fr(r.cacheRead)})}),s.jsx(qn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:fr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(qn,{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]??"",Io=(e,t)=>`${ds(e)}
|
|
18
18
|
${t}`,wn=(e,t)=>`${e}#${t}`,Ym=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},ks=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Qi=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,Ji=10,Vm=(e,t)=>{const n=Js(),r=Js({maxEntries:60}),o=Js(),i=Js(),l=new Map,c=new Map,d=async(L,D)=>{const R=c.get(L);if(R)return await R.catch(()=>null),{ran:!1,result:null};const I=D();c.set(L,I);try{return{ran:!0,result:await I}}finally{c.get(L)===I&&c.delete(L)}},u=(L,D)=>{if(D.length===0)return;const R=e.collectionKeyFor(L,e.openCollection);let I=l.get(R);I||(I=new Map,l.set(R,I));for(const M of D)I.set(M.number,M)},f=L=>{const D=Object.keys(r.snapshot()).filter(I=>Ur(I)===L&&!r.getEntry(I)?.isLoading);if(D.length<=Ji)return;const R=D.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,M)=>I.fetchedAt-M.fetchedAt);for(let I=0;I<R.length-Ji;I+=1)r.remove(R[I].key)},p=L=>{const D=n.getEntry(e.collectionKeyFor(L,e.openCollection))?.data?.items??[],R=n.getEntry(e.collectionKeyFor(L,e.closedCollection))?.data?.items??[],I=Vn(D,R),M=l.get(e.collectionKeyFor(L,e.openCollection));return!M||M.size===0?I:Vn(I,[...M.values()])},x=(L,D,R)=>{const I=Io(L,D),M=t.get().filtersByScope[I]??e.defaultFilters;t.set(W=>({filtersByScope:{...W.filtersByScope,[I]:{...M,...R}}}))},y=(L,D)=>{const R=Io(L,D);t.set(I=>({filtersByScope:{...I.filtersByScope,[R]:{...e.defaultFilters}}}))},m=(L,D,R)=>{const I=ds(L);I&&t.set(M=>({selectionByDirectory:{...M.selectionByDirectory,[I]:{repo:D,number:R}}}))},h=(L,D,R,I)=>{const M=e.collectionKeyFor(D,R);return n.ensure(M,async()=>{const W=await e.fetchList(I,L,D,e.buildCollectionQuery(R));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},b=(L,D,R)=>{const I=e.collectionKeyFor(D,e.closedCollection);n.getEntry(I)?.data||n.getEntry(I)?.isLoading||h(L,D,e.closedCollection,R).catch(()=>null)},g=async(L,D,R,I)=>{const M=R==="open"||R==="both",W=R==="closed"||R==="both",G=[],B=n.getEntry(e.collectionKeyFor(D,e.openCollection)),xe=n.getEntry(e.collectionKeyFor(D,e.closedCollection));M&&(!Qi(B,e.freshWindowMs)||B?.stale)&&G.push(h(L,D,e.openCollection,I)),W&&(!Qi(xe,e.freshWindowMs)||xe?.stale)&&G.push(h(L,D,e.closedCollection,I)),await Promise.all(G.map(V=>V.catch(()=>null))),M&&!n.getEntry(e.collectionKeyFor(D,e.closedCollection))?.data&&b(L,D,I)},S=async(L,D,R,I)=>{const M=e.collectionKeyFor(D,R),W=n.getEntry(M),G=W?.data?.nextCursor??null;if(!G||W?.isLoading)return W;try{const B=await d(`${M}:more`,async()=>{const xe=await e.fetchList(I,L,D,{...e.buildCollectionQuery(R),cursor:G}),V=n.getEntry(M)?.data,je={items:Vn(V?.items??[],xe.items),nextCursor:xe.nextCursor,fetchedAt:xe.fetchedAt};return n.refresh(M,async()=>je)});return B.ran?B.result??n.getEntry(M):n.getEntry(M)}catch(B){return n.setError(M,B)??n.getEntry(M)}},v=async(L,D,R,I)=>{const M=R==="both"?[e.openCollection,e.closedCollection]:[R];await Promise.all(M.map(W=>{const G=e.collectionKeyFor(D,W);return n.refresh(G,async()=>{const B=await e.fetchList(I,L,D,e.buildCollectionQuery(W));return{items:B.items,nextCursor:B.nextCursor,fetchedAt:B.fetchedAt}}).catch(()=>null)}))},E=async(L,D,R,I)=>{const M=e.remoteKeyFor(D,R),W=await r.refresh(M,async()=>{const G=await e.fetchList(I,L,D,e.buildRemoteQuery(R));return{items:G.items,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}});return W.data&&(u(D,W.data.items),f(D)),W},j=async(L,D,R,I)=>{const M=e.remoteKeyFor(D,R),W=r.getEntry(M),G=W?.data?.nextCursor??null;if(!G||W?.isLoading)return W;try{const B=await e.fetchList(I,L,D,e.buildRemoteQuery(R,G)),xe=r.getEntry(M)?.data,V={items:Vn(xe?.items??[],B.items),nextCursor:B.nextCursor,fetchedAt:B.fetchedAt},je=await r.refresh(M,async()=>V);return je.data&&(u(D,je.data.items),f(D)),je}catch(B){return r.setError(M,B)??r.getEntry(M)}},k=L=>{for(const D of Object.keys(r.snapshot()))Ur(D)===L&&r.remove(D);for(const D of[...l.keys()])Ur(D)===L&&l.delete(D)},C=(L,D,R,I)=>{const M=e.detailKeyFor(D,R);return o.refresh(M,async()=>({detail:await e.fetchDetail(I,L,D,R)}))};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:v,searchRemote:E,loadMoreRemote:j,dropRemoteForRepo:k,refreshAllForScope:async(L,D,R)=>{await ks(R,{directory:L,repo:D,kind:e.serverKind}),k(D),await v(L,D,"both",R).catch(()=>null);const I=t.get().selectionByDirectory[ds(L)];I?.repo===D&&typeof I.number=="number"&&await C(L,D,I.number,R).catch(()=>null)},ensureDetail:(L,D,R,I)=>{const M=e.detailKeyFor(D,R);return o.ensure(M,async()=>({detail:await e.fetchDetail(I,L,D,R)}))},refreshDetail:C,ensureComments:(L,D,R,I)=>{const M=e.commentsKeyFor(D,R);return i.ensure(M,async()=>{const W=await e.fetchComments(I,L,D,R);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},loadMoreComments:async(L,D,R,I)=>{const M=e.commentsKeyFor(D,R),W=i.getEntry(M),G=W?.data?.nextCursor??null;if(!G||W?.isLoading)return W;try{const B=await e.fetchComments(I,L,D,R,G),xe=i.getEntry(M)?.data,V={comments:qm(xe?.comments??[],B.comments),nextCursor:B.nextCursor,fetchedAt:B.fetchedAt};return await i.refresh(M,async()=>V)}catch(B){return i.setError(M,B)??i.getEntry(M)}},refreshComments:(L,D,R,I)=>{const M=e.commentsKeyFor(D,R);return i.refresh(M,async()=>{const W=await e.fetchComments(I,L,D,R);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},markCollectionsStale:L=>{n.markStale(e.collectionKeyFor(L,e.openCollection)),n.markStale(e.collectionKeyFor(L,e.closedCollection))},getLocalIndex:p,withSingleFlight:d,resetCore:()=>{n.reset(),r.reset(),l.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:L=>Ym(L,e.errorFallback)}},Eo={state:"open",involvement:"all",search:"",sort:"updated"},Qm=3e4,Jm=100,Xm=50,Kl=(e,t)=>cn([e,"pulls-collection",t]),Wl=(e,t)=>cn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),pr=(e,t)=>cn([e,"pull-detail",t]),Qo=(e,t)=>cn([e,"pull-comments",t]),Ro=(e,t)=>cn([e,"pull-files",t]),Do=(e,t)=>cn([e,"pull-checks",t]),Zm=e=>({state:e,perPage:Jm}),ep=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:Xm,...t?{cursor:t}:{}}),gr=e=>`pichamber:pr-merge-method:${e}`,Gl=new Map,tp=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},sp=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},Gx=e=>{if(!e)return null;const t=tp(gr(e));return t==="merge"||t==="squash"||t==="rebase"?t:Gl.get(gr(e))??null},np=(e,t)=>{if(e){Gl.set(gr(e),t);try{sp(gr(e),t)}catch{}}},rp={set:e=>{typeof e=="function"?xs.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):xs.setState(e)},get:()=>{const e=xs.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},De=Vm({openCollection:"open",closedCollection:"closed",defaultFilters:Eo,freshWindowMs:Qm,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Kl,remoteKeyFor:Wl,detailKeyFor:pr,commentsKeyFor:Qo,buildCollectionQuery:e=>({...Zm(e)}),buildRemoteQuery:(e,t)=>({...ep(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}}},rp),Zt=Js(),rr=Js(),xs=Ls()(vr((e,t)=>({...De.initialState,actionErrorByDetail:{},actingActions:{},setFilters:De.setFilters,resetFilters:De.resetFilters,selectPullRequest:De.select,ensureCollection:De.ensureCollection,ensureCollectionsFresh:De.ensureCollectionsFresh,prefetchClosedCollection:De.prefetchClosedCollection,loadMoreCollection:De.loadMoreCollection,refreshCollections:De.refreshCollections,searchRemote:De.searchRemote,loadMoreRemote:De.loadMoreRemote,dropRemoteForRepo:De.dropRemoteForRepo,refreshAllForScope:De.refreshAllForScope,ensureDetail:De.ensureDetail,refreshDetail:De.refreshDetail,ensureComments:De.ensureComments,loadMoreComments:De.loadMoreComments,refreshComments:De.refreshComments,ensureFiles:(n,r,o,i)=>{const l=Ro(r,o);return Zt.ensure(l,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const l=Ro(r,o),c=Zt.getEntry(l),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await De.withSingleFlight(`${l}:more`,async()=>{const f=await i.pullFiles(n,r,o,d),p=Zt.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 Zt.refresh(l,async()=>y)});return u.ran?u.result??Zt.getEntry(l):Zt.getEntry(l)}catch(u){return Zt.setError(l,u)??Zt.getEntry(l)}},ensureChecks:(n,r,o,i)=>{const l=Do(r,o);return rr.ensure(l,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const l=Do(r,o);return rr.refresh(l,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,l)=>{const c=wn(r,o),d=pr(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=De.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 De.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 ks(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=De.toStoreError(x);return u&&await De.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=wn(r,o),d=pr(r,o),u=De.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 De.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullUpdate(n,r,o,i),await ks(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=De.toStoreError(x);return u&&await De.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=wn(r,o),d=Qo(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},p=De.resources.comments.getEntry(d)?.data??null;if(p){const x={comments:[...p.comments,f],nextCursor:p.nextCursor,fetchedAt:p.fetchedAt};await De.resources.comments.refresh(d,async()=>x).catch(()=>null)}try{return await l.pullComment(n,r,o,u),await ks(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=De.toStoreError(x);return p?await De.resources.comments.refresh(d,async()=>p).catch(()=>null):De.resources.comments.remove(d),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},submitReview:async(n,r,o,i,l)=>{const c=wn(r,o);try{return await l.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await ks(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(d){const u=De.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(n,r,o,i,l,c)=>{const d=wn(r,o);try{return await c.pullThread(n,r,o,i,l),await ks(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=De.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:De.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await ks(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:De.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(l){return{ok:!1,error:De.toStoreError(l)}}},setMergeMethod:(n,r)=>{np(n,r)},notifyAgentTurnComplete:n=>{const r=ds((n||"").trim());if(!r)return;const o=ss.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&&ht(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-BnZVqcki.js").then(f=>f.cy);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"&&(De.markCollectionsStale(i.repo),ht(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-BnZVqcki.js").then(c=>c.cy);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:()=>{De.resetCore(),Zt.reset(),rr.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(On(()=>{xs.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Hx=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return ht(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-BisjofNZ.js").then(l=>l.dR);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&&(xs.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},qx=e=>De.getLocalIndex(e),Yx=(e,t)=>De.getLocalIndex(e).find(n=>n.number===t)??null,Vx=(e,t)=>dn(De.resources.collections,e?Kl(e,t):null),Qx=(e,t)=>dn(De.resources.remote,e?Wl(e,t):null),Jx=(e,t)=>dn(De.resources.details,e!=null&&t!=null?pr(e,t):null),Xx=(e,t)=>dn(De.resources.comments,e!=null&&t!=null?Qo(e,t):null),Zx=(e,t)=>dn(Zt,e!=null&&t!=null?Ro(e,t):null),ey=(e,t)=>dn(rr,e!=null&&t!=null?Do(e,t):null),ty=(e,t)=>xs(n=>!e||!t?Eo:n.filtersByScope[Io(e,t)]??Eo),sy=e=>xs(t=>e?t.selectionByDirectory[ds(e)]??Vi:Vi),Hl=(e,t,n)=>{xs.getState().selectPullRequest(e,t,n);const r=ds(e);ht(async()=>{const{useUIStore:o}=await import("./index-BnZVqcki.js").then(i=>i.cB);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),ht(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-BisjofNZ.js").then(i=>i.dT);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(()=>{})},op=({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(),Hl(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 ip({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:v,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:j=>{(j.key==="Enter"||j.key===" ")&&(j.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:nr(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:nr(e.label,o)}),f,u?s.jsx(op,{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:nr(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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),Ds.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(Ke,{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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),m&&m!==h&&b(m),g("chat"),S&&v(!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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Qn=(e,t)=>t?e.sessions.some(n=>cs(n,t)):!1,ap=(e,t,n)=>e.sessions.some(r=>Pl(r,r,t,n,e.directory,e.directory)),lp=(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)},Xi=(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)},cp=(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)},dp=(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&&ap(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&cp(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&lp(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Qn(e.group,e.editingId)||Qn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Qn(e.group,e.editingId)||Qn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=mr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=mr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&Xi(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&Xi(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 up({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,collectGroupSessions:c}){const d=pt(j=>j.foldersMap),u=e.folderScopeKey??Ie(e.directory??null),f=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),p=a.useMemo(()=>f.flatMap(({scopeKey:j,directory:k})=>(d[j]??[]).map(C=>({folder:C,scopeKey:j,scopeDirectory:k}))),[f,d]),x=a.useMemo(()=>{const j=new Map,k=C=>{C.forEach(w=>{j.set(w.session.id,w),w.children.length>0&&k(w.children)})};return k(t),j},[t]),y=a.useMemo(()=>p.map(({folder:j,scopeKey:k,scopeDirectory:C})=>{const w=Rm(j.sessionIds,x).sort(o);return{folder:j,scopeKey:k,scopeDirectory:C,nodes:w}}),[p,x,o]),m=a.useMemo(()=>{const j=new Map(y.map(N=>[N.folder.id,N])),k=new Map;for(const{folder:N}of y){if(!N.parentId)continue;const T=k.get(N.parentId);T?T.push(N.id):k.set(N.parentId,[N.id])}const C=new Map,w=N=>{const T=C.get(N);if(T!==void 0)return T;const O=j.get(N);if(!O)return C.set(N,!1),!1;const $=k.get(N)??[];if(e.isArchivedBucket&&O.nodes.length===0){const L=$.some(D=>w(D));return C.set(N,L),L}if(!n||O.folder.name.toLowerCase().includes(r)||O.nodes.length>0)return C.set(N,!0),!0;const K=$.some(L=>w(L));return C.set(N,K),K};return y.filter(({folder:N})=>w(N.id))},[y,e.isArchivedBucket,n,r]),h=a.useMemo(()=>new Set(m.flatMap(j=>j.folder.sessionIds)),[m]),b=a.useMemo(()=>t.filter(j=>!h.has(j.session.id)),[t,h]),g=a.useMemo(()=>m.filter(({folder:j})=>!j.parentId),[m]),S=a.useMemo(()=>{const j=new Map;return m.forEach(k=>{if(!k.folder.parentId)return;const C=j.get(k.folder.parentId)??[];C.push(k),j.set(k.folder.parentId,C)}),j},[m]),v=a.useMemo(()=>{const j=new Map(m.map(w=>[w.folder.id,w])),k=new Map,C=(w,N)=>{const T=k.get(w);if(T!==void 0)return T;if(N.has(w))return null;N.add(w);const O=j.get(w);let $=O?Ol(O.nodes,i,l):null;for(const U of S.get(w)??[])if($=Yo($,C(U.folder.id,N)),$==="active")break;return k.set(w,$),$};return m.forEach(({folder:w})=>C(w.id,new Set)),k},[i,m,S,l]),E=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const j=new Map,k=new Map;for(const{folder:w}of m){if(!w.parentId)continue;const N=k.get(w.parentId)??[];N.push(w.id),k.set(w.parentId,N)}const C=(w,N)=>{if(N.has(w))return[];N.add(w);const T=m.find(({folder:U})=>U.id===w),O=T?c(T.nodes):[],$=k.get(w)??[];for(const U of $)O.push(...C(U,N));return O};for(const{folder:w}of m)j.set(w.id,C(w.id,new Set));return j},[m,c,e.isArchivedBucket]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:m,rootFolders:g,ungroupedSessions:b,folderActivityStateById:v,folderSessionsForDeleteById:E}}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:v,mobileVariant:E,alwaysShowActions:j,activeProjectId:k,setActiveProjectIdOnly:C,setActiveMainTab:w,setSessionSwitcherOpen:N,openNewSessionDraft:T,addSessionToFolder:O,createFolderAndStartRename:$,renamingFolderId:U,renameFolderDraft:K,setRenameFolderDraft:L,setRenamingFolderId:D,pinnedSessionIds:R,expandedParents:I,sessionOrderIndex:M,editingId:W,openSidebarMenuKey:G,activeActivitySessionIds:B,unreadActivitySessionIds:xe,onToggleCollapsedGroup:V,dragHandleProps:je,compactBodyPadding:Re=!1,scrollContainerRef:H}=e,z=a.useCallback((ke,He)=>{const Ae=M.get(ke.session.id),Oe=M.get(He.session.id);if(Ae!==void 0||Oe!==void 0){if(Ae===void 0)return 1;if(Oe===void 0)return-1;if(Ae!==Oe)return Ae-Oe}return ru(ke.session,He.session,R,za)},[R,M]),Y=i?c.get(t):null,X=i?!1:u.has(n),te=!t.isMain&&!t.isArchivedBucket&&!o?Ie(t.directory??null):null,ue=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,he=a.useMemo(()=>te&&ue?Ln(te,ue):null,[te,ue]),Q=Tl(he);Fl(te,ue);const se=Q?`var(--pr-${Q.visualState})`:void 0,ce=f?10:5,Ce=Math.max(ce,d??ce),ve=i?Y?.groupMatches===!0:!1,Ge=i,q=a.useMemo(()=>[...Ge?Y?.filteredNodes??[]:t.sessions].sort(z),[z,t.sessions,Y?.filteredNodes,Ge]),ae=a.useCallback(ke=>{const He=[],Ae=Oe=>{Oe.forEach(Fe=>{He.push(Fe.session),Fe.children.length>0&&Ae(Fe.children)})};return Ae(ke),He},[]),{folderScopeKey:ne,folderScopes:me,allFoldersForGroup:fe,rootFolders:Be,ungroupedSessions:Se,folderActivityStateById:ee,folderSessionsForDeleteById:we}=up({group:t,sourceGroupNodes:q,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:z,activeActivitySessionIds:B,unreadActivitySessionIds:xe,collectGroupSessions:ae}),pe="project",ye=a.useMemo(()=>{const ke=new Set;return $i(q,W,ke),fe.forEach(({nodes:He})=>{$i(He,W,ke)}),ke},[q,fe,W]),We=a.useMemo(()=>{if(!G)return null;const ke=mr(q,G,pe,!!t.isArchivedBucket);if(ke)return ke;for(const{nodes:He}of fe){const Ae=mr(He,G,pe,!!t.isArchivedBucket);if(Ae)return Ae}return null},[G,q,fe,t.isArchivedBucket]),qe=a.useCallback(ke=>{const He=new WeakMap,Ae=Oe=>{He.set(Oe,ko(Oe));for(const Fe of Oe.children)Ae(Fe)};return ke.forEach(Ae),He},[]),Pe=a.useMemo(()=>qe(q),[qe,q]),Ye=a.useMemo(()=>{const ke=new WeakMap;return fe.forEach(({nodes:He})=>{He.forEach(Ae=>ke.set(Ae,ko(Ae)))}),ke},[fe]),re=a.useCallback(ke=>Pe.get(ke)??Ye.get(ke)??"",[Pe,Ye]),Le=a.useCallback(ke=>({subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(ke)}),[ye,We,re]),nt=Se.length,at=t.isArchivedBucket||i?Se:Se.slice(0,Ce),Ve=nt-at.length,mt=!t.isArchivedBucket&&!i&&nt>ce&&Ve===0,lt=t.isArchivedBucket===!0&&!i&&at.length>=Om,qt=t.isArchivedBucket?"archived":"active",Yt=lt&&at.some(ke=>{if(ke.children.length===0)return!1;const He=`project:${qt}:${ke.session.id}`;return I.has(He)}),Ze=a.useMemo(()=>ae(q),[ae,q]);if(i&&!ve&&Be.length===0&&Se.length===0)return null;const Ct=!t.isMain&&!!t.branch,Vt=t.branch&&gf(t.branch,t.label)?{label:t.branch,color:null}:null,kt=X?Ol(q,B,xe):null,Ft=kt?s.jsx(Rl,{state:kt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,gt=(ke,He)=>{const{folder:Ae,scopeKey:Oe,scopeDirectory:Fe,nodes:rt}=ke,vt=we.get(Ae.id)??[],Nt=i?!1:p.has(Ae.id);return s.jsx(Im,{folderId:Ae.id,children:(bt,ct)=>s.jsx(Am,{folder:Ae,displayName:He,sessions:rt,isCollapsed:Nt,collapsedActivityState:Nt?ee.get(Ae.id)??null:null,onToggle:()=>x(Ae.id),onRename:tt=>{y(Oe,Ae.id,tt)},onDelete:()=>{if(t.isArchivedBucket){Ds.requestDelete({sessions:vt,mode:"session"});return}if(!h){m(Oe,Ae.id);return}const tt=fe.filter(({folder:Et})=>Et.parentId===Ae.id).length,It=rt.length;b({scopeKey:Oe,folderId:Ae.id,folderName:Ae.name,subFolderCount:tt,sessionCount:It})},renderSessionNode:g,getRenderExtras:re?tt=>({subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(tt),childRenderExtrasFor:Le}):void 0,groupDirectory:Fe??t.directory,projectId:r,mobileVariant:E,alwaysShowActions:j,isRenaming:U===Ae.id,renameDraft:U===Ae.id?K:void 0,onRenameDraftChange:tt=>L(tt),onRenameSave:()=>{const tt=K.trim();tt&&y(Oe,Ae.id,tt),D(null),L("")},onRenameCancel:()=>{D(null),L("")},droppableRef:bt,isDropTarget:ct,depth:0,onNewSession:()=>{r&&r!==k&&C(r),w("chat"),E&&N(!1),T({selectedProjectId:r,directoryOverride:Fe??t.directory,targetFolderId:Ae.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},Ae.id)},wt=()=>{const ke=new Map;for(const Oe of fe){const Fe=Oe.folder.parentId;if(!Fe)continue;const rt=ke.get(Fe);rt?rt.push(Oe):ke.set(Fe,[Oe])}const He=[],Ae=(Oe,Fe)=>{const rt=Fe?`${Fe} / ${Oe.folder.name}`:Oe.folder.name;He.push(gt(Oe,rt)),!(!i&&p.has(Oe.folder.id))&&(ke.get(Oe.folder.id)??[]).forEach(Nt=>Ae(Nt,rt))};return Be.forEach(Oe=>Ae(Oe,"")),He},st=j?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",At=s.jsxs(Em,{scopeKey:me[0]?.scopeKey??ne,hasFolders:fe.length>0,onSessionDroppedOnFolder:(ke,He)=>{const Ae=fe.find(({folder:Fe})=>Fe.id===He);if(!Ae)return;const Oe=pt.getState();for(const{scopeKey:Fe}of me)Fe!==Ae.scopeKey&&Oe.getSessionFolderId(Fe,ke)&&Oe.removeSessionFromFolder(Fe,ke);O(Ae.scopeKey,He,ke)},children:[wt(),t.isArchivedBucket?s.jsx(_m,{visibleSessions:at,shouldVirtualize:lt,hasExpandedParent:Yt,scrollContainerRef:H,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:ke=>({subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(ke),childRenderExtrasFor:Le})}):at.map(ke=>s.jsx(a.Fragment,{children:g(ke,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(ke),childRenderExtrasFor:Le})},ke.session.id)),nt===0&&fe.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(ts,{icon:"chat-new",onClick:()=>{T({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Ve>0?s.jsx(ts,{icon:"arrow-down-s",onClick:()=>S(n,at.length),children:Ve===1?"Show 1 more session":`Show ${Ve} more sessions`}):null,mt?s.jsx(ts,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:At})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(ip,{group:t,groupKey:n,isCollapsed:X,onToggleCollapsedGroup:V,normalizedSessionSearchQuery:l,alwaysShowActions:j,groupHeaderRightPadding:st,dragHandleProps:je,groupPrColor:se,groupPrSummary:Q,groupActivityIndicator:Ft,showBranchSubtitle:Ct,statusLine:Vt,allGroupSessions:Ze,projectId:r,activeProjectId:k,setActiveProjectIdOnly:C,setActiveMainTab:w,mobileVariant:E,setSessionSwitcherOpen:N,openNewSessionDraft:T}),X?null:s.jsx("div",{className:"oc-group-body",children:At})]})}const hp=a.memo(fp,dp);function mp(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:v=!1}=e;if(t)return null;const E=_(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return s.jsx("div",{className:_("select-none flex-shrink-0",v?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",v?"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",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[o?s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!v&&i?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:E,"aria-label":l?`Instances: ${l}`:"Instances",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Instances"})})]}):null,c?s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,v?null:s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),v?null:s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(j=>!j),className:E,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:_(v?"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:j=>m(j.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:j=>{j.key==="Escape"&&(j.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 $r="0.75rem";function pp(e){const t=le(o=>o.toggleSidebar),n=le(o=>o.shortcutOverrides),r=Ko(lr("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, ${$r})`}}),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, ${$r})))`}}),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(${bf} - max(var(--oc-titlebar-left-inset, ${$r}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(tr,"text-current")}),s.jsx("span",{className:rl,children:"New session"})]}),e.showSidebarToggle?s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Cr({...e}){return s.jsx(Sa,{...e})}function kr({...e}){return s.jsx(ja,{...e})}function Ar({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Ca,{children:s.jsx(ka,{className:_("app-region-no-drag z-50",t),children:s.jsx(Aa,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Ua,e),...o,children:n})})})}function Rs({className:e,...t}){return s.jsx(Na,{className:_($a,e),...t})}function ql({className:e,...t}){return s.jsx(Ia,{className:_(Ka,e),...t})}const Yl=500,gp=({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)},Yl)},[p]);return s.jsxs(Cr,{open:c,onOpenChange:d,children:[s.jsxs(kr,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_(br(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:_(Ms(l),"text-muted-foreground")}),s.jsx("span",{className:nn(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(ws,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Ar,{className:"min-w-[160px]",children:s.jsxs(Rs,{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"})]})})]})},br=(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"),bp=({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}=zo({id:e.id,disabled:!c}),[g,S]=a.useState(!1),v=a.useRef(null),E=a.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);a.useEffect(()=>()=>E(),[E]);const j=a.useCallback(()=>{E(),v.current=window.setTimeout(()=>{v.current=null,S(!0)},Yl)},[E]);return s.jsx("div",{ref:y,style:{transform:Uo.Translate.toString(m),transition:h},className:_(b&&"opacity-60"),children:s.jsxs(Cr,{open:g,onOpenChange:S,children:[s.jsxs(kr,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:j,onTouchMove:E,onTouchEnd:E,onTouchCancel:E,style:{touchAction:"manipulation"},className:br(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(P,{name:"folder",className:_(Ms(p),"text-muted-foreground")})}),s.jsx("span",{className:nn(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(ws,{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(Ar,{className:"min-w-[160px]",children:[s.jsxs(Rs,{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(ql,{}),s.jsxs(Rs,{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"})]})]})]})})},xp=({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=ut(j=>j.reorderProjects),S=e.length>1,v=Oo(Pn(Pa,{activationConstraint:{distance:8}}),Pn(Da,{activationConstraint:{delay:200,tolerance:6}})),E=a.useCallback(j=>{const{active:k,over:C}=j;if(!C||k.id===C.id)return;const w=ut.getState().projects,N=w.findIndex(O=>O.id===k.id),T=w.findIndex(O=>O.id===C.id);N<0||T<0||g(N,T)},[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:br(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:Ms(h)}),s.jsx("span",{className:nn(h),children:"All sessions"})]})}),s.jsx(Bo,{sensors:v,collisionDetection:_o,onDragEnd:E,children:s.jsx(Ea,{items:e.map(j=>j.id),strategy:Ra,children:e.map(j=>{const k=t===j.id,C=k&&!n,w=r.get(j.normalizedPath)??[],N=Wo(j.label?.trim()||Tn(j.normalizedPath,y)||j.normalizedPath),T=x?.get(j.id),O=Ie(j.normalizedPath)?.toLowerCase()??"",$=O?T?.has(O)??!1:!1,U=(T?.size??0)>0,K=p?.(j.id)??!1,L=x?k?$:U:K;return s.jsxs(a.Fragment,{children:[s.jsx(bp,{project:j,label:N,isSelected:C,hasActive:L,hasWorktrees:w.length>0,worktreeError:o.get(j.normalizedPath),isExpanded:k,canDrag:S,onSelect:()=>i(j.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),k?w.map(D=>{const R=n===D.path,I=Ie(D.path)?.toLowerCase()??"",M=I?T?.has(I)??!1:!1,W=x?M:!1;return s.jsx(gp,{projectId:j.id,worktree:D,isSelected:R,hasActive:W,onSelect:()=>l?.(j.id,D.path),onClose:c,mobileVariant:h},D.path)}):null]},j.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:br(h,!1),children:[s.jsx(P,{name:"add",className:Ms(h)}),s.jsx("span",{className:nn(h),children:"Add folder"})]})]})},Kr="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 yp({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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:Kr,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:Kr,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Kr,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(Ke,{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 Vl=({projectLabel:e,mobileVariant:t=!1})=>{const n=Ms(t),r=nn(t);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",n),children:s.jsx(P,{name:"folder",className:_(n,"text-muted-foreground/80")})}),s.jsx("span",{className:_(r,"text-foreground"),children:e})]})},Ql=({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:Ms(t)})}),wp=({id:e,disabled:t=!1,projectLabel:n,projectDescription:r,isCollapsed:o,hideDirectoryControls:i,mobileVariant:l,alwaysShowActions:c,stickyHeader:d=!1,onToggle:u,onNewSession:f,onRenameStart:p,onClose:x,children:y,showCreateButtons:m=!0,hideHeader:h=!1,openSidebarMenuKey:b,setOpenSidebarMenuKey:g,statusIndicator:S=null})=>{const{listeners:v,setNodeRef:E,transform:j,transition:k,isDragging:C}=zo({id:e,disabled:t}),w=a.useRef(!1),N=`project:${e}`,T=b===N,[O,$]=a.useState(!1),U=d&&!o,K=a.useCallback(G=>{G&&$(!1),g(G?N:null)},[N,g]),L=G=>s.jsxs(s.Fragment,{children:[m&&!i&&f&&s.jsxs(G,{onClick:f,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(G,{onClick:p,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(G,{onClick:x,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(G=>{G.stopPropagation()},[]),R=a.useCallback(G=>{G.stopPropagation()},[]),I=a.useCallback(G=>{G.stopPropagation()},[]),M=a.useCallback(G=>{(G.button===2||G.button===0&&G.ctrlKey)&&(w.current=!0)},[]),W=a.useCallback(G=>{if(G.currentTarget.blur(),w.current){w.current=!1;return}u()},[u]);return s.jsxs("div",{ref:E,style:{transform:Uo.Translate.toString(j),transition:k},className:_("relative",C&&"opacity-60"),children:[h?null:s.jsxs(Cr,{open:O,onOpenChange:$,children:[s.jsxs(kr,{render:s.jsx("div",{className:_("text-left group/project select-none",U&&"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":U?"true":void 0,onContextMenu:G=>{i||C||(G.preventDefault(),$(!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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!o,style:{touchAction:"manipulation"},onMouseDown:M,onClick:W,...v,className:_(jr,"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(Vl,{id:e,projectLabel:n,mobileVariant:l}),S?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:S}):null,s.jsx(Ql,{isCollapsed:o,mobileVariant:l,className:_("transition-[padding]",c?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(Ke,{side:"right",sideOffset:8,children:r})]}),s.jsx("div",{className:"absolute right-[calc(3.25rem*var(--padding-scale,1))] top-1/2 z-10 -translate-y-1/2",children:i?null:s.jsxs(Wt,{open:T,onOpenChange:K,children:[s.jsx(Gt,{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",T?"opacity-100 pointer-events-auto":c?"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:R,onMouseDown:I,onClick:D,children:s.jsx(P,{name:"more-2",className:"size-4"})})}),s.jsx(Ht,{align:"end",className:"min-w-[180px]",children:L(ft)})]})}),m&&!i&&f?s.jsx("div",{className:"absolute right-7 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),f()},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",c?"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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null]}),U?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(Ar,{className:"min-w-[180px]",children:L(Rs)})]}),y]})},vp=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:l,transition:c,isDragging:d}=zo({id:e,disabled:t}),u=a.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:Uo.Transform.toString(l),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};a.memo(vp);const Zi="pt-0.5 pb-1",Sp=({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:v,openNewSessionDraft:E,openProjectEditDialog:j,removeProject:k,reorderProjects:C,openSidebarMenuKey:w,setOpenSidebarMenuKey:N,onOpenDirectoryDialog:T,emptyState:O,searchEmptyState:$})=>{const U=Oo(Pn(Pa,{activationConstraint:{distance:8}}),Pn(Da,{activationConstraint:{delay:200,tolerance:6}})),K=e.length>1&&!i&&!f,L=a.useCallback(B=>{if(f||i)return;const{active:xe,over:V}=B;if(!V||xe.id===V.id)return;const je=ut.getState().projects,Re=je.findIndex(z=>z.id===xe.id),H=je.findIndex(z=>z.id===V.id);Re<0||H<0||Re===H||C(Re,H)},[f,i,C]),[D,R]=a.useState(5);a.useEffect(()=>{R(5)},[i]);const I=a.useMemo(()=>t?t.groups.filter(B=>!B.isArchivedBucket).flatMap(B=>B.sessions):[],[t]),M=i?I:I.slice(0,D),W=I.length-M.length,G=i?!1:r.has("__home__");return e.length===0&&!t?i?$:O:s.jsxs("div",{className:"space-y-2",children:[s.jsx(Bo,{sensors:U,collisionDetection:_o,onDragEnd:L,children:s.jsx(Ea,{items:e.map(B=>B.project.id),strategy:Ra,children:e.map(B=>{const xe=B.project,V=xe.id,je=ol(xe,n),Re=co(xe.normalizedPath,n),H=i?!1:r.has(V),z=H?[]:m(V,B.groups),Y=H?null:z.find(te=>te.isMain)??null,X=H?[]:Y?z.filter(te=>te.id!==Y.id):z;return s.jsx(wp,{id:V,disabled:!K,projectLabel:je,projectDescription:Re,isCollapsed:H,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,stickyHeader:p,statusIndicator:H?h?.(V,B.groups):null,onToggle:()=>o(V),onNewSession:()=>{V!==l&&g(V),S("chat"),d&&v(!1),E({selectedProjectId:V,directoryOverride:xe.normalizedPath})},onRenameStart:()=>j(V),onClose:()=>k(V),openSidebarMenuKey:w,setOpenSidebarMenuKey:N,children:H?null:s.jsxs("div",{className:Zi,children:[Y?x(Y,`${V}:${Y.id}`,V,!0,null,void 0,b):null,X.map(te=>{const ue=`${V}:${te.id}`,he=z.length===1;return s.jsx(a.Fragment,{children:x(te,ue,V,he,null,void 0,b)},te.id)})]})},V)})})}),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":!G,style:{touchAction:"manipulation"},onClick:()=>o("__home__"),className:`${jr} 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(Vl,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),s.jsx(Ql,{isCollapsed:G,mobileVariant:d})]})}),G?null:s.jsxs("div",{className:Zi,children:[M.map(B=>s.jsx(a.Fragment,{children:y?.(B,0,B.session.directory??"~","__home__",!1,{globalSession:!0},"project")},B.session.id)),!i&&W>0?s.jsx(ts,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>R(B=>B+7),children:W===1?"Show 1 more session":`Show ${W} more sessions`}):null,!i&&D>5&&I.length>5?s.jsx(ts,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>R(5),children:"Show fewer sessions"}):null]})]}):null,!c&&T?s.jsx(ts,{icon:"add",mobileVariant:d,onClick:T,children:"Add folder"}):null]})},jp=a.memo(Sp);function Cp(e){Kt("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,v=S.get(b);if(v&&v.groups===g)return v.ordered;const E=e.getOrderedGroups(b,g);if(S.set(b,{groups:g,ordered:E}),S.size>256){const j=S.keys().next().value;j!==void 0&&S.delete(j)}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 v=ol(S.project,e.homeDirectory);for(const E of S.groups)if(!E.isArchivedBucket)for(const j of E.sessions){const k=!!e.pinnedSessionIds?.has(j.session.id),C=j.session.time?.updated||j.session.time?.created||0;b.push({node:j,project:S.project,projectLabel:v,isPinned:k,timestamp:C,globalSession:S===e.allFoldersOnlySection})}}return b.sort((S,v)=>S.isPinned!==v.isPinned?S.isPinned?-1:1:v.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?Vh(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:x}):[],[n,p,x]);if(e.sharedSessionsOnly)return s.jsx(As,{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(As,{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(As,{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(ts,{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(ts,{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(As,{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(ts,{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 j=`${b.project.id}:${E.id}`,k=E.id===g.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(E,j,b.project.id,k,null,!0,l)},j)})})()}):t==="folder"?s.jsx(qo.Provider,{value:"tree",children:s.jsx(jp,{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=Hh[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:v,project:E,projectLabel:j,globalSession:k})=>{const C=v.session.directory??E.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(v,0,C,E.id,!1,{projectLabel:j,showFolderLabel:!0,globalSession:k},"project")},v.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:v})=>{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:v},"project")},b.session.id)}),h()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const g=b.project.id,S=i(g,b.groups),v=S.find(j=>j.isMain)??null,E=v?S.filter(j=>j.id!==v.id):S;return s.jsxs("div",{children:[v?e.renderGroupSessions(v,`${g}:${v.id}`,g,!0,null,void 0,l):null,E.map(j=>{const k=`${g}:${j.id}`,C=S.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(j,k,g,C,null,void 0,l)},j.id)})]},g)})})]})})})}const kp=a.memo(Cp);let Po=!1;const Mo=new Set;let ea=!1;function Ap(){for(const e of Mo)e()}function Jo(e){Po!==e&&(Po=e,Ap())}function Np(e){e.key==="Shift"&&Jo(!0)}function Ip(e){e.key==="Shift"&&Jo(!1)}function Ep(){Jo(!1)}function Rp(){ea||typeof window>"u"||(ea=!0,window.addEventListener("keydown",Np),window.addEventListener("keyup",Ip),window.addEventListener("blur",Ep))}function Dp(e){return Rp(),Mo.add(e),()=>{Mo.delete(e)}}function Pp(){return Po}function Mp(){return!1}function Tp(){return Ee.useSyncExternalStore(Dp,Pp,Mp)}const Fp=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:d}){const u=Tp(),f=u?n:t,p=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"left",sideOffset:8,children:f})]})}),Lp=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(ns,{open:t,onOpenChange:n,children:s.jsxs(rs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(vs,{children:[s.jsx(us,{children:"Export Markdown"}),s.jsx(Ss,{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(Ts,{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 Op(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 Bp(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Ca,{children:s.jsx(ka,{className:"app-region-no-drag z-50",children:s.jsx(Aa,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Ua,"min-w-[180px]"),children:Op(e,{Item:({className:r,...o})=>s.jsx(Na,{className:_($a,r),...o}),Separator:({className:r,...o})=>s.jsx(Ia,{className:_(Ka,r),...o})})})})})}const Wr=new WeakMap,_p=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Wr.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,Wr.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,Kt("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}),Wr.set(n,c),l=window.requestAnimationFrame(d)};function zp(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 Up(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 $p(e){const t=e.info.role==="user"?"User":"Assistant",n=zp(e.info.time?.created),r=Up(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
20
|
+
`);d&&ht(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-BnZVqcki.js").then(f=>f.cy);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"&&(De.markCollectionsStale(i.repo),ht(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-BnZVqcki.js").then(c=>c.cy);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:()=>{De.resetCore(),Zt.reset(),rr.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(On(()=>{xs.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Hx=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return ht(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-DviRbaCJ.js").then(l=>l.dR);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&&(xs.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},qx=e=>De.getLocalIndex(e),Yx=(e,t)=>De.getLocalIndex(e).find(n=>n.number===t)??null,Vx=(e,t)=>dn(De.resources.collections,e?Kl(e,t):null),Qx=(e,t)=>dn(De.resources.remote,e?Wl(e,t):null),Jx=(e,t)=>dn(De.resources.details,e!=null&&t!=null?pr(e,t):null),Xx=(e,t)=>dn(De.resources.comments,e!=null&&t!=null?Qo(e,t):null),Zx=(e,t)=>dn(Zt,e!=null&&t!=null?Ro(e,t):null),ey=(e,t)=>dn(rr,e!=null&&t!=null?Do(e,t):null),ty=(e,t)=>xs(n=>!e||!t?Eo:n.filtersByScope[Io(e,t)]??Eo),sy=e=>xs(t=>e?t.selectionByDirectory[ds(e)]??Vi:Vi),Hl=(e,t,n)=>{xs.getState().selectPullRequest(e,t,n);const r=ds(e);ht(async()=>{const{useUIStore:o}=await import("./index-BnZVqcki.js").then(i=>i.cB);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),ht(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-DviRbaCJ.js").then(i=>i.dT);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(()=>{})},op=({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(),Hl(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 ip({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:v,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:j=>{(j.key==="Enter"||j.key===" ")&&(j.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:nr(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:nr(e.label,o)}),f,u?s.jsx(op,{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:nr(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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),Ds.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(Ke,{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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),m&&m!==h&&b(m),g("chat"),S&&v(!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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Qn=(e,t)=>t?e.sessions.some(n=>cs(n,t)):!1,ap=(e,t,n)=>e.sessions.some(r=>Pl(r,r,t,n,e.directory,e.directory)),lp=(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)},Xi=(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)},cp=(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)},dp=(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&&ap(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&cp(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&lp(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Qn(e.group,e.editingId)||Qn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Qn(e.group,e.editingId)||Qn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=mr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=mr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&Xi(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&Xi(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 up({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,collectGroupSessions:c}){const d=pt(j=>j.foldersMap),u=e.folderScopeKey??Ie(e.directory??null),f=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),p=a.useMemo(()=>f.flatMap(({scopeKey:j,directory:k})=>(d[j]??[]).map(C=>({folder:C,scopeKey:j,scopeDirectory:k}))),[f,d]),x=a.useMemo(()=>{const j=new Map,k=C=>{C.forEach(w=>{j.set(w.session.id,w),w.children.length>0&&k(w.children)})};return k(t),j},[t]),y=a.useMemo(()=>p.map(({folder:j,scopeKey:k,scopeDirectory:C})=>{const w=Rm(j.sessionIds,x).sort(o);return{folder:j,scopeKey:k,scopeDirectory:C,nodes:w}}),[p,x,o]),m=a.useMemo(()=>{const j=new Map(y.map(N=>[N.folder.id,N])),k=new Map;for(const{folder:N}of y){if(!N.parentId)continue;const T=k.get(N.parentId);T?T.push(N.id):k.set(N.parentId,[N.id])}const C=new Map,w=N=>{const T=C.get(N);if(T!==void 0)return T;const O=j.get(N);if(!O)return C.set(N,!1),!1;const $=k.get(N)??[];if(e.isArchivedBucket&&O.nodes.length===0){const L=$.some(D=>w(D));return C.set(N,L),L}if(!n||O.folder.name.toLowerCase().includes(r)||O.nodes.length>0)return C.set(N,!0),!0;const K=$.some(L=>w(L));return C.set(N,K),K};return y.filter(({folder:N})=>w(N.id))},[y,e.isArchivedBucket,n,r]),h=a.useMemo(()=>new Set(m.flatMap(j=>j.folder.sessionIds)),[m]),b=a.useMemo(()=>t.filter(j=>!h.has(j.session.id)),[t,h]),g=a.useMemo(()=>m.filter(({folder:j})=>!j.parentId),[m]),S=a.useMemo(()=>{const j=new Map;return m.forEach(k=>{if(!k.folder.parentId)return;const C=j.get(k.folder.parentId)??[];C.push(k),j.set(k.folder.parentId,C)}),j},[m]),v=a.useMemo(()=>{const j=new Map(m.map(w=>[w.folder.id,w])),k=new Map,C=(w,N)=>{const T=k.get(w);if(T!==void 0)return T;if(N.has(w))return null;N.add(w);const O=j.get(w);let $=O?Ol(O.nodes,i,l):null;for(const U of S.get(w)??[])if($=Yo($,C(U.folder.id,N)),$==="active")break;return k.set(w,$),$};return m.forEach(({folder:w})=>C(w.id,new Set)),k},[i,m,S,l]),E=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const j=new Map,k=new Map;for(const{folder:w}of m){if(!w.parentId)continue;const N=k.get(w.parentId)??[];N.push(w.id),k.set(w.parentId,N)}const C=(w,N)=>{if(N.has(w))return[];N.add(w);const T=m.find(({folder:U})=>U.id===w),O=T?c(T.nodes):[],$=k.get(w)??[];for(const U of $)O.push(...C(U,N));return O};for(const{folder:w}of m)j.set(w.id,C(w.id,new Set));return j},[m,c,e.isArchivedBucket]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:m,rootFolders:g,ungroupedSessions:b,folderActivityStateById:v,folderSessionsForDeleteById:E}}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:v,mobileVariant:E,alwaysShowActions:j,activeProjectId:k,setActiveProjectIdOnly:C,setActiveMainTab:w,setSessionSwitcherOpen:N,openNewSessionDraft:T,addSessionToFolder:O,createFolderAndStartRename:$,renamingFolderId:U,renameFolderDraft:K,setRenameFolderDraft:L,setRenamingFolderId:D,pinnedSessionIds:R,expandedParents:I,sessionOrderIndex:M,editingId:W,openSidebarMenuKey:G,activeActivitySessionIds:B,unreadActivitySessionIds:xe,onToggleCollapsedGroup:V,dragHandleProps:je,compactBodyPadding:Re=!1,scrollContainerRef:H}=e,z=a.useCallback((ke,He)=>{const Ae=M.get(ke.session.id),Oe=M.get(He.session.id);if(Ae!==void 0||Oe!==void 0){if(Ae===void 0)return 1;if(Oe===void 0)return-1;if(Ae!==Oe)return Ae-Oe}return ru(ke.session,He.session,R,za)},[R,M]),Y=i?c.get(t):null,X=i?!1:u.has(n),te=!t.isMain&&!t.isArchivedBucket&&!o?Ie(t.directory??null):null,ue=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,he=a.useMemo(()=>te&&ue?Ln(te,ue):null,[te,ue]),Q=Tl(he);Fl(te,ue);const se=Q?`var(--pr-${Q.visualState})`:void 0,ce=f?10:5,Ce=Math.max(ce,d??ce),ve=i?Y?.groupMatches===!0:!1,Ge=i,q=a.useMemo(()=>[...Ge?Y?.filteredNodes??[]:t.sessions].sort(z),[z,t.sessions,Y?.filteredNodes,Ge]),ae=a.useCallback(ke=>{const He=[],Ae=Oe=>{Oe.forEach(Fe=>{He.push(Fe.session),Fe.children.length>0&&Ae(Fe.children)})};return Ae(ke),He},[]),{folderScopeKey:ne,folderScopes:me,allFoldersForGroup:fe,rootFolders:Be,ungroupedSessions:Se,folderActivityStateById:ee,folderSessionsForDeleteById:we}=up({group:t,sourceGroupNodes:q,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:z,activeActivitySessionIds:B,unreadActivitySessionIds:xe,collectGroupSessions:ae}),pe="project",ye=a.useMemo(()=>{const ke=new Set;return $i(q,W,ke),fe.forEach(({nodes:He})=>{$i(He,W,ke)}),ke},[q,fe,W]),We=a.useMemo(()=>{if(!G)return null;const ke=mr(q,G,pe,!!t.isArchivedBucket);if(ke)return ke;for(const{nodes:He}of fe){const Ae=mr(He,G,pe,!!t.isArchivedBucket);if(Ae)return Ae}return null},[G,q,fe,t.isArchivedBucket]),qe=a.useCallback(ke=>{const He=new WeakMap,Ae=Oe=>{He.set(Oe,ko(Oe));for(const Fe of Oe.children)Ae(Fe)};return ke.forEach(Ae),He},[]),Pe=a.useMemo(()=>qe(q),[qe,q]),Ye=a.useMemo(()=>{const ke=new WeakMap;return fe.forEach(({nodes:He})=>{He.forEach(Ae=>ke.set(Ae,ko(Ae)))}),ke},[fe]),re=a.useCallback(ke=>Pe.get(ke)??Ye.get(ke)??"",[Pe,Ye]),Le=a.useCallback(ke=>({subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(ke)}),[ye,We,re]),nt=Se.length,at=t.isArchivedBucket||i?Se:Se.slice(0,Ce),Ve=nt-at.length,mt=!t.isArchivedBucket&&!i&&nt>ce&&Ve===0,lt=t.isArchivedBucket===!0&&!i&&at.length>=Om,qt=t.isArchivedBucket?"archived":"active",Yt=lt&&at.some(ke=>{if(ke.children.length===0)return!1;const He=`project:${qt}:${ke.session.id}`;return I.has(He)}),Ze=a.useMemo(()=>ae(q),[ae,q]);if(i&&!ve&&Be.length===0&&Se.length===0)return null;const Ct=!t.isMain&&!!t.branch,Vt=t.branch&&gf(t.branch,t.label)?{label:t.branch,color:null}:null,kt=X?Ol(q,B,xe):null,Ft=kt?s.jsx(Rl,{state:kt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,gt=(ke,He)=>{const{folder:Ae,scopeKey:Oe,scopeDirectory:Fe,nodes:rt}=ke,vt=we.get(Ae.id)??[],Nt=i?!1:p.has(Ae.id);return s.jsx(Im,{folderId:Ae.id,children:(bt,ct)=>s.jsx(Am,{folder:Ae,displayName:He,sessions:rt,isCollapsed:Nt,collapsedActivityState:Nt?ee.get(Ae.id)??null:null,onToggle:()=>x(Ae.id),onRename:tt=>{y(Oe,Ae.id,tt)},onDelete:()=>{if(t.isArchivedBucket){Ds.requestDelete({sessions:vt,mode:"session"});return}if(!h){m(Oe,Ae.id);return}const tt=fe.filter(({folder:Et})=>Et.parentId===Ae.id).length,It=rt.length;b({scopeKey:Oe,folderId:Ae.id,folderName:Ae.name,subFolderCount:tt,sessionCount:It})},renderSessionNode:g,getRenderExtras:re?tt=>({subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(tt),childRenderExtrasFor:Le}):void 0,groupDirectory:Fe??t.directory,projectId:r,mobileVariant:E,alwaysShowActions:j,isRenaming:U===Ae.id,renameDraft:U===Ae.id?K:void 0,onRenameDraftChange:tt=>L(tt),onRenameSave:()=>{const tt=K.trim();tt&&y(Oe,Ae.id,tt),D(null),L("")},onRenameCancel:()=>{D(null),L("")},droppableRef:bt,isDropTarget:ct,depth:0,onNewSession:()=>{r&&r!==k&&C(r),w("chat"),E&&N(!1),T({selectedProjectId:r,directoryOverride:Fe??t.directory,targetFolderId:Ae.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},Ae.id)},wt=()=>{const ke=new Map;for(const Oe of fe){const Fe=Oe.folder.parentId;if(!Fe)continue;const rt=ke.get(Fe);rt?rt.push(Oe):ke.set(Fe,[Oe])}const He=[],Ae=(Oe,Fe)=>{const rt=Fe?`${Fe} / ${Oe.folder.name}`:Oe.folder.name;He.push(gt(Oe,rt)),!(!i&&p.has(Oe.folder.id))&&(ke.get(Oe.folder.id)??[]).forEach(Nt=>Ae(Nt,rt))};return Be.forEach(Oe=>Ae(Oe,"")),He},st=j?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",At=s.jsxs(Em,{scopeKey:me[0]?.scopeKey??ne,hasFolders:fe.length>0,onSessionDroppedOnFolder:(ke,He)=>{const Ae=fe.find(({folder:Fe})=>Fe.id===He);if(!Ae)return;const Oe=pt.getState();for(const{scopeKey:Fe}of me)Fe!==Ae.scopeKey&&Oe.getSessionFolderId(Fe,ke)&&Oe.removeSessionFromFolder(Fe,ke);O(Ae.scopeKey,He,ke)},children:[wt(),t.isArchivedBucket?s.jsx(_m,{visibleSessions:at,shouldVirtualize:lt,hasExpandedParent:Yt,scrollContainerRef:H,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:ke=>({subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(ke),childRenderExtrasFor:Le})}):at.map(ke=>s.jsx(a.Fragment,{children:g(ke,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:ye,menuOpenSessionId:We,nodeStructureKey:re(ke),childRenderExtrasFor:Le})},ke.session.id)),nt===0&&fe.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(ts,{icon:"chat-new",onClick:()=>{T({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Ve>0?s.jsx(ts,{icon:"arrow-down-s",onClick:()=>S(n,at.length),children:Ve===1?"Show 1 more session":`Show ${Ve} more sessions`}):null,mt?s.jsx(ts,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:At})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(ip,{group:t,groupKey:n,isCollapsed:X,onToggleCollapsedGroup:V,normalizedSessionSearchQuery:l,alwaysShowActions:j,groupHeaderRightPadding:st,dragHandleProps:je,groupPrColor:se,groupPrSummary:Q,groupActivityIndicator:Ft,showBranchSubtitle:Ct,statusLine:Vt,allGroupSessions:Ze,projectId:r,activeProjectId:k,setActiveProjectIdOnly:C,setActiveMainTab:w,mobileVariant:E,setSessionSwitcherOpen:N,openNewSessionDraft:T}),X?null:s.jsx("div",{className:"oc-group-body",children:At})]})}const hp=a.memo(fp,dp);function mp(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:v=!1}=e;if(t)return null;const E=_(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return s.jsx("div",{className:_("select-none flex-shrink-0",v?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",v?"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",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[o?s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!v&&i?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:E,"aria-label":l?`Instances: ${l}`:"Instances",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Instances"})})]}):null,c?s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,v?null:s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),v?null:s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(j=>!j),className:E,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:_(v?"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:j=>m(j.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:j=>{j.key==="Escape"&&(j.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 $r="0.75rem";function pp(e){const t=le(o=>o.toggleSidebar),n=le(o=>o.shortcutOverrides),r=Ko(lr("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, ${$r})`}}),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, ${$r})))`}}),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(${bf} - max(var(--oc-titlebar-left-inset, ${$r}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(tr,"text-current")}),s.jsx("span",{className:rl,children:"New session"})]}),e.showSidebarToggle?s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Cr({...e}){return s.jsx(Sa,{...e})}function kr({...e}){return s.jsx(ja,{...e})}function Ar({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Ca,{children:s.jsx(ka,{className:_("app-region-no-drag z-50",t),children:s.jsx(Aa,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Ua,e),...o,children:n})})})}function Rs({className:e,...t}){return s.jsx(Na,{className:_($a,e),...t})}function ql({className:e,...t}){return s.jsx(Ia,{className:_(Ka,e),...t})}const Yl=500,gp=({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)},Yl)},[p]);return s.jsxs(Cr,{open:c,onOpenChange:d,children:[s.jsxs(kr,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_(br(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:_(Ms(l),"text-muted-foreground")}),s.jsx("span",{className:nn(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(ws,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Ar,{className:"min-w-[160px]",children:s.jsxs(Rs,{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"})]})})]})},br=(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"),bp=({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}=zo({id:e.id,disabled:!c}),[g,S]=a.useState(!1),v=a.useRef(null),E=a.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);a.useEffect(()=>()=>E(),[E]);const j=a.useCallback(()=>{E(),v.current=window.setTimeout(()=>{v.current=null,S(!0)},Yl)},[E]);return s.jsx("div",{ref:y,style:{transform:Uo.Translate.toString(m),transition:h},className:_(b&&"opacity-60"),children:s.jsxs(Cr,{open:g,onOpenChange:S,children:[s.jsxs(kr,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:j,onTouchMove:E,onTouchEnd:E,onTouchCancel:E,style:{touchAction:"manipulation"},className:br(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(P,{name:"folder",className:_(Ms(p),"text-muted-foreground")})}),s.jsx("span",{className:nn(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(ws,{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(Ar,{className:"min-w-[160px]",children:[s.jsxs(Rs,{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(ql,{}),s.jsxs(Rs,{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"})]})]})]})})},xp=({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=ut(j=>j.reorderProjects),S=e.length>1,v=Oo(Pn(Pa,{activationConstraint:{distance:8}}),Pn(Da,{activationConstraint:{delay:200,tolerance:6}})),E=a.useCallback(j=>{const{active:k,over:C}=j;if(!C||k.id===C.id)return;const w=ut.getState().projects,N=w.findIndex(O=>O.id===k.id),T=w.findIndex(O=>O.id===C.id);N<0||T<0||g(N,T)},[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:br(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:Ms(h)}),s.jsx("span",{className:nn(h),children:"All sessions"})]})}),s.jsx(Bo,{sensors:v,collisionDetection:_o,onDragEnd:E,children:s.jsx(Ea,{items:e.map(j=>j.id),strategy:Ra,children:e.map(j=>{const k=t===j.id,C=k&&!n,w=r.get(j.normalizedPath)??[],N=Wo(j.label?.trim()||Tn(j.normalizedPath,y)||j.normalizedPath),T=x?.get(j.id),O=Ie(j.normalizedPath)?.toLowerCase()??"",$=O?T?.has(O)??!1:!1,U=(T?.size??0)>0,K=p?.(j.id)??!1,L=x?k?$:U:K;return s.jsxs(a.Fragment,{children:[s.jsx(bp,{project:j,label:N,isSelected:C,hasActive:L,hasWorktrees:w.length>0,worktreeError:o.get(j.normalizedPath),isExpanded:k,canDrag:S,onSelect:()=>i(j.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),k?w.map(D=>{const R=n===D.path,I=Ie(D.path)?.toLowerCase()??"",M=I?T?.has(I)??!1:!1,W=x?M:!1;return s.jsx(gp,{projectId:j.id,worktree:D,isSelected:R,hasActive:W,onSelect:()=>l?.(j.id,D.path),onClose:c,mobileVariant:h},D.path)}):null]},j.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:br(h,!1),children:[s.jsx(P,{name:"add",className:Ms(h)}),s.jsx("span",{className:nn(h),children:"Add folder"})]})]})},Kr="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 yp({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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:Kr,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:Kr,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Kr,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(Ke,{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 Vl=({projectLabel:e,mobileVariant:t=!1})=>{const n=Ms(t),r=nn(t);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",n),children:s.jsx(P,{name:"folder",className:_(n,"text-muted-foreground/80")})}),s.jsx("span",{className:_(r,"text-foreground"),children:e})]})},Ql=({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:Ms(t)})}),wp=({id:e,disabled:t=!1,projectLabel:n,projectDescription:r,isCollapsed:o,hideDirectoryControls:i,mobileVariant:l,alwaysShowActions:c,stickyHeader:d=!1,onToggle:u,onNewSession:f,onRenameStart:p,onClose:x,children:y,showCreateButtons:m=!0,hideHeader:h=!1,openSidebarMenuKey:b,setOpenSidebarMenuKey:g,statusIndicator:S=null})=>{const{listeners:v,setNodeRef:E,transform:j,transition:k,isDragging:C}=zo({id:e,disabled:t}),w=a.useRef(!1),N=`project:${e}`,T=b===N,[O,$]=a.useState(!1),U=d&&!o,K=a.useCallback(G=>{G&&$(!1),g(G?N:null)},[N,g]),L=G=>s.jsxs(s.Fragment,{children:[m&&!i&&f&&s.jsxs(G,{onClick:f,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(G,{onClick:p,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(G,{onClick:x,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(G=>{G.stopPropagation()},[]),R=a.useCallback(G=>{G.stopPropagation()},[]),I=a.useCallback(G=>{G.stopPropagation()},[]),M=a.useCallback(G=>{(G.button===2||G.button===0&&G.ctrlKey)&&(w.current=!0)},[]),W=a.useCallback(G=>{if(G.currentTarget.blur(),w.current){w.current=!1;return}u()},[u]);return s.jsxs("div",{ref:E,style:{transform:Uo.Translate.toString(j),transition:k},className:_("relative",C&&"opacity-60"),children:[h?null:s.jsxs(Cr,{open:O,onOpenChange:$,children:[s.jsxs(kr,{render:s.jsx("div",{className:_("text-left group/project select-none",U&&"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":U?"true":void 0,onContextMenu:G=>{i||C||(G.preventDefault(),$(!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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!o,style:{touchAction:"manipulation"},onMouseDown:M,onClick:W,...v,className:_(jr,"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(Vl,{id:e,projectLabel:n,mobileVariant:l}),S?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:S}):null,s.jsx(Ql,{isCollapsed:o,mobileVariant:l,className:_("transition-[padding]",c?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(Ke,{side:"right",sideOffset:8,children:r})]}),s.jsx("div",{className:"absolute right-[calc(3.25rem*var(--padding-scale,1))] top-1/2 z-10 -translate-y-1/2",children:i?null:s.jsxs(Wt,{open:T,onOpenChange:K,children:[s.jsx(Gt,{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",T?"opacity-100 pointer-events-auto":c?"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:R,onMouseDown:I,onClick:D,children:s.jsx(P,{name:"more-2",className:"size-4"})})}),s.jsx(Ht,{align:"end",className:"min-w-[180px]",children:L(ft)})]})}),m&&!i&&f?s.jsx("div",{className:"absolute right-7 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),f()},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",c?"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(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null]}),U?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(Ar,{className:"min-w-[180px]",children:L(Rs)})]}),y]})},vp=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:l,transition:c,isDragging:d}=zo({id:e,disabled:t}),u=a.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:Uo.Transform.toString(l),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};a.memo(vp);const Zi="pt-0.5 pb-1",Sp=({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:v,openNewSessionDraft:E,openProjectEditDialog:j,removeProject:k,reorderProjects:C,openSidebarMenuKey:w,setOpenSidebarMenuKey:N,onOpenDirectoryDialog:T,emptyState:O,searchEmptyState:$})=>{const U=Oo(Pn(Pa,{activationConstraint:{distance:8}}),Pn(Da,{activationConstraint:{delay:200,tolerance:6}})),K=e.length>1&&!i&&!f,L=a.useCallback(B=>{if(f||i)return;const{active:xe,over:V}=B;if(!V||xe.id===V.id)return;const je=ut.getState().projects,Re=je.findIndex(z=>z.id===xe.id),H=je.findIndex(z=>z.id===V.id);Re<0||H<0||Re===H||C(Re,H)},[f,i,C]),[D,R]=a.useState(5);a.useEffect(()=>{R(5)},[i]);const I=a.useMemo(()=>t?t.groups.filter(B=>!B.isArchivedBucket).flatMap(B=>B.sessions):[],[t]),M=i?I:I.slice(0,D),W=I.length-M.length,G=i?!1:r.has("__home__");return e.length===0&&!t?i?$:O:s.jsxs("div",{className:"space-y-2",children:[s.jsx(Bo,{sensors:U,collisionDetection:_o,onDragEnd:L,children:s.jsx(Ea,{items:e.map(B=>B.project.id),strategy:Ra,children:e.map(B=>{const xe=B.project,V=xe.id,je=ol(xe,n),Re=co(xe.normalizedPath,n),H=i?!1:r.has(V),z=H?[]:m(V,B.groups),Y=H?null:z.find(te=>te.isMain)??null,X=H?[]:Y?z.filter(te=>te.id!==Y.id):z;return s.jsx(wp,{id:V,disabled:!K,projectLabel:je,projectDescription:Re,isCollapsed:H,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,stickyHeader:p,statusIndicator:H?h?.(V,B.groups):null,onToggle:()=>o(V),onNewSession:()=>{V!==l&&g(V),S("chat"),d&&v(!1),E({selectedProjectId:V,directoryOverride:xe.normalizedPath})},onRenameStart:()=>j(V),onClose:()=>k(V),openSidebarMenuKey:w,setOpenSidebarMenuKey:N,children:H?null:s.jsxs("div",{className:Zi,children:[Y?x(Y,`${V}:${Y.id}`,V,!0,null,void 0,b):null,X.map(te=>{const ue=`${V}:${te.id}`,he=z.length===1;return s.jsx(a.Fragment,{children:x(te,ue,V,he,null,void 0,b)},te.id)})]})},V)})})}),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":!G,style:{touchAction:"manipulation"},onClick:()=>o("__home__"),className:`${jr} 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(Vl,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),s.jsx(Ql,{isCollapsed:G,mobileVariant:d})]})}),G?null:s.jsxs("div",{className:Zi,children:[M.map(B=>s.jsx(a.Fragment,{children:y?.(B,0,B.session.directory??"~","__home__",!1,{globalSession:!0},"project")},B.session.id)),!i&&W>0?s.jsx(ts,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>R(B=>B+7),children:W===1?"Show 1 more session":`Show ${W} more sessions`}):null,!i&&D>5&&I.length>5?s.jsx(ts,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>R(5),children:"Show fewer sessions"}):null]})]}):null,!c&&T?s.jsx(ts,{icon:"add",mobileVariant:d,onClick:T,children:"Add folder"}):null]})},jp=a.memo(Sp);function Cp(e){Kt("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,v=S.get(b);if(v&&v.groups===g)return v.ordered;const E=e.getOrderedGroups(b,g);if(S.set(b,{groups:g,ordered:E}),S.size>256){const j=S.keys().next().value;j!==void 0&&S.delete(j)}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 v=ol(S.project,e.homeDirectory);for(const E of S.groups)if(!E.isArchivedBucket)for(const j of E.sessions){const k=!!e.pinnedSessionIds?.has(j.session.id),C=j.session.time?.updated||j.session.time?.created||0;b.push({node:j,project:S.project,projectLabel:v,isPinned:k,timestamp:C,globalSession:S===e.allFoldersOnlySection})}}return b.sort((S,v)=>S.isPinned!==v.isPinned?S.isPinned?-1:1:v.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?Vh(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:x}):[],[n,p,x]);if(e.sharedSessionsOnly)return s.jsx(As,{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(As,{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(As,{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(ts,{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(ts,{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(As,{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(ts,{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 j=`${b.project.id}:${E.id}`,k=E.id===g.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(E,j,b.project.id,k,null,!0,l)},j)})})()}):t==="folder"?s.jsx(qo.Provider,{value:"tree",children:s.jsx(jp,{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=Hh[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:v,project:E,projectLabel:j,globalSession:k})=>{const C=v.session.directory??E.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(v,0,C,E.id,!1,{projectLabel:j,showFolderLabel:!0,globalSession:k},"project")},v.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:v})=>{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:v},"project")},b.session.id)}),h()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const g=b.project.id,S=i(g,b.groups),v=S.find(j=>j.isMain)??null,E=v?S.filter(j=>j.id!==v.id):S;return s.jsxs("div",{children:[v?e.renderGroupSessions(v,`${g}:${v.id}`,g,!0,null,void 0,l):null,E.map(j=>{const k=`${g}:${j.id}`,C=S.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(j,k,g,C,null,void 0,l)},j.id)})]},g)})})]})})})}const kp=a.memo(Cp);let Po=!1;const Mo=new Set;let ea=!1;function Ap(){for(const e of Mo)e()}function Jo(e){Po!==e&&(Po=e,Ap())}function Np(e){e.key==="Shift"&&Jo(!0)}function Ip(e){e.key==="Shift"&&Jo(!1)}function Ep(){Jo(!1)}function Rp(){ea||typeof window>"u"||(ea=!0,window.addEventListener("keydown",Np),window.addEventListener("keyup",Ip),window.addEventListener("blur",Ep))}function Dp(e){return Rp(),Mo.add(e),()=>{Mo.delete(e)}}function Pp(){return Po}function Mp(){return!1}function Tp(){return Ee.useSyncExternalStore(Dp,Pp,Mp)}const Fp=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:d}){const u=Tp(),f=u?n:t,p=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs(Ue,{children:[s.jsx($e,{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(Ke,{side:"left",sideOffset:8,children:f})]})}),Lp=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(ns,{open:t,onOpenChange:n,children:s.jsxs(rs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(vs,{children:[s.jsx(us,{children:"Export Markdown"}),s.jsx(Ss,{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(Ts,{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 Op(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 Bp(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Ca,{children:s.jsx(ka,{className:"app-region-no-drag z-50",children:s.jsx(Aa,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Ua,"min-w-[180px]"),children:Op(e,{Item:({className:r,...o})=>s.jsx(Na,{className:_($a,r),...o}),Separator:({className:r,...o})=>s.jsx(Ia,{className:_(Ka,r),...o})})})})})}const Wr=new WeakMap,_p=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Wr.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,Wr.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,Kt("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}),Wr.set(n,c),l=window.requestAnimationFrame(d)};function zp(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 Up(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 $p(e){const t=e.info.role==="user"?"User":"Assistant",n=zp(e.info.time?.created),r=Up(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
21
21
|
|
|
22
22
|
*${o}*`:`**${t}**`}function Kp(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function Jl(e){const t=$p(e),n=Kp(e.parts).trim();return n?`${t}
|
|
23
23
|
|
|
@@ -59,4 +59,4 @@ ${n}`:""}function Xl(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=nb(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),rb(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const p=ge.getState().getDirectoryState(t)?.tabs.find(x=>x.id===n);!p||p.previewUrlLocked||p.previewUrl===d||o(t,n,d,{locked:!1,autoOpened:!1})})}}const cb=(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"?oc(o):null};function db({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=ge(z=>z.ensureDirectory),h=ge(z=>z.setTabSessionId),b=ge(z=>z.setTabLifecycle),g=ge(z=>z.setConnecting),S=ge(z=>z.appendToBuffer),v=ge(z=>z.replaceBuffer),E=ge(z=>z.setTabPreviewUrl),[j,k]=a.useState(null),[C,w]=a.useState(!1),[N,T]=a.useState(!1),O=a.useRef(new Map),$=a.useRef(null),U=a.useRef(n),K=a.useRef(r),L=a.useRef(t),D=a.useRef(null),R=a.useRef(new Set),I=a.useRef(new Map),M=a.useRef(y),W=a.useRef(l),G=a.useRef(i),B=a.useRef(e);M.current=y,W.current=l,G.current=i,B.current=e;const xe=a.useCallback(()=>{const z=U.current;z&&I.current.get(z)?.reset()},[]);a.useEffect(()=>{K.current=r},[r]),a.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),a.useEffect(()=>{U.current=n},[n]),a.useEffect(()=>{L.current=t},[t]);const V=a.useCallback(()=>{for(const z of O.current.values())try{z()}catch{}O.current.clear(),$.current=null,T(!1)},[]);a.useEffect(()=>()=>{V(),K.current=null},[V]);const je=a.useCallback((z,Y,X)=>{let te=I.current.get(Y);te||(te=new lb,I.current.set(Y,te)),te.scan(z,Y,X,E)},[E]),Re=a.useCallback((z,Y,X)=>{if(O.current.has(X)){$.current=X;return}const te=Ai(),ue=()=>Ai()===te&&L.current===z&&ge.getState().getDirectoryState(z)?.tabs.find(Q=>Q.id===Y)?.terminalSessionId===X,he=e.connect(X,{onEvent:Q=>{if(ue())switch(Q.type){case"snapshot":{U.current===Y&&K.current===X?(g(z,Y,!1),k(null),w(!1),T(!1),x()):g(z,Y,!1),v(z,Y,Q.data??"",Q.sequence??0),je(z,Y,Q.data??""),Q.status==="exited"&&b(z,Y,"exited");break}case"reconnecting":{U.current===Y&&(k(null),w(!1),T(!0));break}case"data":{Q.data&&(S(z,Y,Q.data,Q.sequence,Q.replayData),je(z,Y,Q.data));break}case"exit":{const se=typeof Q.exitCode=="number"?Q.exitCode:null,ce=typeof Q.signal=="number"?Q.signal:null,ve=!!ge.getState().getDirectoryState(z)?.tabs.find(Ge=>Ge.id===Y)?.label?.startsWith("Action:");S(z,Y,`\\r\\n[Process exited${se!==null?` with code ${se}`:""}${ce!==null?` (signal ${ce})`:""}]\\r\\n`),b(z,Y,"exited"),U.current===Y&&(g(z,Y,!1),k(ve?null:"Terminal session ended"),w(!1),T(!1));break}}},onError:(Q,se)=>{if(!ue())return;const ce=U.current===Y;if(!se){ce&&(k(null),w(!1));return}if(Q.code==="SESSION_NOT_FOUND"&&!ge.getState().getDirectoryState(z)?.tabs.find(ve=>ve.id===Y)?.label?.startsWith("Action:")){ce&&(k(null),w(!1),g(z,Y,!1),T(!1)),h(z,Y,null),b(z,Y,"idle");return}ce&&(T(!1),k(`Connection failed: ${Q.message}`),w(!0),g(z,Y,!1),b(z,Y,"exited"),h(z,Y,null))}});O.current.set(X,()=>he.close()),$.current=X},[S,x,v,je,g,b,h,e]),H=a.useMemo(()=>y.map(z=>`${z.id}:${z.terminalSessionId??""}`).join(","),[y]);return a.useEffect(()=>{if(!l||!i||!t)return;const z=t,Y=new Set;for(const X of y)X.terminalSessionId&&(Y.add(X.terminalSessionId),Re(z,X.id,X.terminalSessionId));for(const[X,te]of O.current)if(!Y.has(X)){try{te()}catch{}O.current.delete(X)}},[H,y,t,l,i,Re]),a.useEffect(()=>Qu(()=>{if(!W.current||!G.current)return;const z=L.current;if(!z)return;const Y=[];for(const te of M.current){if(!te.terminalSessionId)continue;ge.getState().getDirectoryState(z)?.tabs.find(he=>he.id===te.id)?.terminalSessionId===te.terminalSessionId&&Y.push({id:te.id,terminalSessionId:te.terminalSessionId})}if(O.current.clear(),$.current=null,Y.length===0)return;T(!0),k(null),w(!1);for(const te of Y)Re(z,te.id,te.terminalSessionId);const X=D.current;if(X)for(const te of Y)B.current.resize({sessionId:te.terminalSessionId,...X}).catch(()=>{})}),[Re]),a.useEffect(()=>{let z=!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(!L.current||L.current!==X)return;if(!ge.getState().getDirectoryState(X)){m(X);return}const ue=ge.getState().getDirectoryState(X);if(!ue||ue.tabs.length===0)return;const he=ue.activeTabId??ue.tabs[0]?.id??null;if(!he)return;const Q=ue.tabs.find(q=>q.id===he)??ue.tabs[0],se=Q?.terminalSessionId??null,ce=Q?.lifecycle??"idle",Ce=!!Q?.label?.startsWith("Action:"),ve=ge.getState().getBuffer(X,he),Ge=ve.byteLength>0||ve.chunks.length>0;if(!se){if(ce==="exited"){g(X,he,!1);return}if(Ce&&Ge){g(X,he,!1);return}const q=`${X}\0${he}`;if(R.current.has(q))return;const ae=D.current??ic;R.current.add(q),k(null),w(!1),T(!1),g(X,he,!0);try{const ne=await e.createSession({cwd:X,sessionId:he,cols:ae.cols,rows:ae.rows,shell:c,loginShell:d,...u.current});if(!ge.getState().getDirectoryState(X)?.tabs.find(Be=>Be.id===he)){try{await e.close(ne.sessionId)}catch{}return}h(X,he,ne.sessionId);const fe=D.current;fe&&(fe.cols!==ae.cols||fe.rows!==ae.rows)&&e.resize({sessionId:ne.sessionId,...fe}).catch(()=>{});return}catch(ne){const me=ge.getState().getDirectoryState(X)?.tabs.find(fe=>fe.id===he);if(!me||me.terminalSessionId||(g(X,he,!1),L.current!==X||U.current!==he))return;k(ne instanceof Error?ne.message:"Failed to start terminal session"),w(!0),T(!1);return}finally{R.current.delete(q)}}!se||z||(K.current=se)})(),()=>{z=!0}},[p,t,r,o,n,i,f,l,m,g,b,h,e,d,c,u]),{connectionError:j,setConnectionError:k,isFatalError:C,setIsFatalError:w,isReconnectPending:N,setIsReconnectPending:T,terminalIdRef:K,lastViewportSizeRef:D,directoryRef:L,activeTabIdRef:U,disconnectStream:V,resetTerminalPreviewScan:xe,startStream:Re}}function ub({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(v=>{if(!v||n)return;let E=v,j=!1;u&&v.length>0&&(E=ab(v,u),j=!0);const k=t.current;k&&(e.sendInput(k,E).catch(C=>{n||r(C instanceof Error?C.message:"Failed to send input")}),j&&(f(null),x()))},[u,x,n,r,e,t]),h=a.useCallback((v,E)=>{const j=l.current;if((!j||j.cols!==v||j.rows!==E)&&(l.current={cols:v,rows:E}),!i)return;const k=t.current;k&&e.resize({sessionId:k,cols:v,rows:E}).catch(()=>{})},[i,l,e,t]),b=a.useCallback(v=>{f(E=>E===v?null:v),x()},[x]),g=a.useCallback(v=>{const E=ib(v,u);E&&(m(E),f(null),x())},[u,x,m]),S=a.useCallback(v=>{if(v.repeat)return;const E=v.key;if(!E||E==="Control"||E==="Meta"||E==="Alt"||E==="Shift")return;const j=E.length===1?E.toLowerCase():E;if(j in pa){v.preventDefault(),v.stopPropagation(),g(pa[j]);return}const k=cb(v,u);k&&(v.preventDefault(),v.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=ge($=>$.createTab),g=ge($=>$.setActiveTab),S=ge($=>$.closeTab),v=ge($=>$.setTabSessionId),E=ge($=>$.setTabLifecycle),[j,k]=a.useState(!1),C=a.useCallback(async()=>{if(!t||j)return;const $=ge.getState().getDirectoryState(t),U=n??$?.activeTabId??$?.tabs[0]?.id??null;if(!U)return;const K=$?.tabs.find(L=>L.id===U)?.terminalSessionId??null;if(!(!K||!e.restartSession)){k(!0),y(null),m(!1),h(!1),p();try{const L=c.current??ic,D=await e.restartSession(K,{cwd:t,shell:o,loginShell:i,...L,...l.current});if(ge.getState().getDirectoryState(t)?.tabs.find(I=>I.id===U)?.terminalSessionId!==K||(v(t,U,D.sessionId),E(t,U,"running"),d.current!==t||u.current!==U))return;f.current=D.sessionId,x(t,U,D.sessionId)}catch(L){if(ge.getState().getDirectoryState(t)?.tabs.find(R=>R.id===U)?.terminalSessionId!==K||d.current!==t||u.current!==U)return;y(L instanceof Error?L.message:"Failed to restart terminal"),m(!1),h(!1),f.current=K,x(t,U,K)}finally{k(!1)}}},[n,u,d,t,r,j,c,p,y,m,h,E,v,x,e,l,f,i,o]),w=a.useCallback(async()=>{await C()},[C]),N=a.useCallback(()=>{if(!t)return;const $=b(t);g(t,$),y(null),m(!1),h(!1)},[b,t,g,y,m,h]),T=a.useCallback($=>{t&&(g(t,$),y(null),m(!1),h(!1))},[t,g,y,m,h]),O=a.useCallback($=>{if(!t)return;y(null),m(!1),h(!1);const U=ge.getState().getDirectoryState(t)?.tabs.find(K=>K.id===$)?.terminalSessionId;(async()=>{U&&await e.close(U),S(t,$)})().catch(K=>y(K instanceof Error?K.message:"Terminal session ended"))},[S,t,y,m,h,e]);return{isRestarting:j,handleRestart:C,handleHardRestart:w,handleCreateTab:N,handleSelectTab:T,handleCloseTab:O}}const ay=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Fs(),{currentTheme:i}=Ha(),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}=wu(),d=le(re=>re.terminalFontSize),u=le(re=>re.terminalShell),f=le(re=>re.terminalLoginShells.includes(re.terminalShell)),{isMobile:p,isTablet:x,hasTouchOnlyPointer:y}=an(),m=p||x,h=(m||y)&&o.platform==="web",b=!0,g=le(re=>re.showTerminalQuickKeysOnDesktop),S=m||g,v=Te(re=>re.currentSessionId),E=Te(re=>re.newSessionDraft),j=v!==null||E?.open===!0,k=vu()??null,C=ge(re=>k?re.sessions.get(k):void 0),w=ge(re=>re.hasHydrated),N=le(re=>re.openContextPreview),T=a.useMemo(()=>C?C.activeTabId??C.tabs[0]?.id??null:null,[C,b]),O=a.useMemo(()=>{if(C)return T?C.tabs.find(re=>re.id===T)??C.tabs[0]:C.tabs[0]},[C,T]),$=a.useMemo(()=>(C?.tabs??[]).map(re=>({icon:(()=>{const Le=re.iconKey?Rn[re.iconKey]??"terminal":"terminal";return s.jsx(P,{name:Le,className:"h-4 w-4"})})(),id:re.id,label:re.label,title:re.label,closeLabel:"Close tab"})),[C?.tabs]),U=O?.terminalSessionId??null,K=O?.lifecycle??"idle",L=a.useMemo(()=>(C?.tabs??[]).map(re=>({id:re.id,terminalSessionId:re.terminalSessionId,label:re.label})),[C?.tabs]),D=O?.isConnecting??!1,R=O?.previewUrl??null,M=le(re=>re.activeMainTab)==="terminal",W=e??M,[G,B]=a.useState(W);a.useEffect(()=>{W&&B(!0)},[W]);const{connectionError:xe,setConnectionError:V,isFatalError:je,setIsFatalError:Re,isReconnectPending:H,setIsReconnectPending:z,terminalIdRef:Y,lastViewportSizeRef:X,directoryRef:te,activeTabIdRef:ue,resetTerminalPreviewScan:he,startStream:Q}=db({terminal:r,effectiveDirectory:k,activeTabId:T,terminalSessionId:U,terminalLifecycle:K,hasOpenedTerminalViewport:G,terminalHydrated:w,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:b,hasActiveContext:j,tabs:L,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ce.current?.focus()}}),{activeModifier:se,terminalControllerRef:ce,focusTerminalWhenWindowActive:Ce,handleViewportInput:ve,handleModifierToggle:Ge,handleMobileKeyPress:q}=ub({terminal:r,terminalIdRef:Y,isReconnectPending:H,setConnectionError:V,showQuickKeys:S,isTerminalVisible:W,lastViewportSizeRef:X,terminalSessionId:U,useTouchTerminalInput:h}),{isRestarting:ae,handleRestart:ne,handleHardRestart:me,handleCreateTab:fe,handleSelectTab:Be,handleCloseTab:Se}=fb({terminal:r,effectiveDirectory:k,activeTabId:T,enableTabs:b,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:X,directoryRef:te,activeTabIdRef:ue,terminalIdRef:Y,resetTerminalPreviewScan:he,startStream:Q,setConnectionError:V,setIsFatalError:Re,setIsReconnectPending:z});a.useEffect(()=>{if(!W||h)return;if(typeof window>"u"){Ce();return}const re=window.requestAnimationFrame(()=>{Ce()});return()=>{window.cancelAnimationFrame(re)}},[T,Ce,W,h]);const ee=a.useMemo(()=>{const re=bn[Br].stack;if(typeof window>"u")return(bn[c]??bn[Br]).stack;const nt=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return nt&&nt.trim().length>0?nt.trim():(bn[c]??bn[Br]).stack??re},[c]),we=a.useMemo(()=>Fg(i),[i]),pe=`${k??"no-dir"}::${T??"no-tab"}`;if(a.useEffect(()=>{if(!W||h)return;const re=ce.current;if(!re)return;const Le=()=>{re.fit()};if(typeof window<"u"){const nt=window.requestAnimationFrame(()=>{Le(),Ce()}),at=[220,400].map(Ve=>window.setTimeout(Le,Ve));return()=>{window.cancelAnimationFrame(nt),at.forEach(Ve=>window.clearTimeout(Ve))}}Le()},[Ce,W,h,ce,pe,U]),a.useEffect(()=>{if(!W||!h)return;let re=null;const Le=()=>{re!==null&&window.cancelAnimationFrame(re),re=window.requestAnimationFrame(()=>{re=null,ce.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Le),()=>{window.removeEventListener("oc:keyboard-settled",Le),re!==null&&window.cancelAnimationFrame(re)}},[W,ce,pe,h]),!j)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 ye=!U||D||ae||H,We=G,qe=C?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(ha,{items:$,activeId:T,onSelect:Be,onClose:Se,onCreate:fe})}),s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:fe,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:ae,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"h-4 w-4"})}),R?s.jsxs(Ne,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{k&&N(k,R)},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,Pe=s.jsx(Vg,{isTouchTerminal:m,activeModifier:se,disabled:ye,onKeyPress:q,onModifierToggle:Ge}),Ye=!n||m||S;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[qe&&n?Od.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:qe}),n):null,m&&qe&&!n&&C?s.jsx(Yg,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(ha,{items:$,activeId:T,onSelect:Be,onClose:Se,onCreate:fe})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:fe,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:ae,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"size-4"})}),R?s.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{k&&N(k,R)},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&&Ye?s.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[qe&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[qe,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&&C?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Pe}):null,!m&&S&&!C?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Pe}):null]}):null,s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:we.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:We&&k&&C?C.tabs.map(re=>{const Le=re.id===T;return s.jsx(qg,{directory:k,tabId:re.id,sessionId:re.terminalSessionId,sessionKey:`${k}::${re.id}`,isActive:Le,isTerminalVisible:W,terminal:r,theme:we,fontFamily:ee,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:X,onInput:ve,controllerRef:ce},re.id)}):null}),!H&&xe&&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:xe}),je&&m&&s.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:me,disabled:ae,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:Pe})}):null]})},Lo=[{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"}],hb=new Set(Lo.map(e=>e.id)),mb=e=>typeof e=="string"&&hb.has(e),ly=e=>mb(e)?e:"changes",ac=e=>e==="pull-requests"||e==="issues",pb=e=>e?Lo:Lo.filter(t=>!ac(t.id)),cy=(e,t)=>ac(e)?"changes":e,gb=48,bb=96,yt=(e,...t)=>{try{e?.(...t)}catch{}},eo=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},dy=(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"?bb:gb;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,T=p,O=x;u&&T&&(yt(T==="left"?N.onLeftProgress:N.onRightProgress,O?1:0),yt(N.onDragEnd,T,O)),g()},v=()=>{S(),u||g()},E=N=>{const T=n.current;if(T.enabled===!1){u&&p?S():g();return}if(N.touches.length!==1){u&&p?S():g();return}const O=N.touches[0],$=o.getBoundingClientRect(),U=o.clientWidth,K=!!T.leftOpen,L=!!T.rightOpen,D=R=>Ag(R,o);if(K||L){if(D(N.target)){g();return}if(K&&L){const R=O.clientX<=$.left+c;O.clientX>=$.right-c?(p="right",x=!0):R?(p="left",x=!0):(p=K?"left":"right",x=!0)}else K?(p="left",x=!0):(p="right",x=!0);b=eo(p==="left"?T.leftWidth:T.rightWidth,U),b<10&&(b=U||window.innerWidth||320),b<10&&(b=320),d=!0}else{if(D(N.target)){g();return}p=null,x=!1,b=0,d=!0}y=O.clientX,m=O.clientY,h=Date.now(),u=!1,f=!1},j=N=>{if(!d)return;if(N.touches.length!==1){v();return}const T=N.touches[0],O=T.clientX-y,$=T.clientY-m;if(!f){if(Math.abs(O)<la&&Math.abs($)<la)return;if(Math.abs($)>Math.abs(O)*jn){g();return}if(!p){const L=n.current;p=O>0?"left":"right",b=eo(p==="left"?L.leftWidth:L.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(p==="left"){if(!x&&O<=0){g();return}if(x&&O>=0){g();return}}else{if(!x&&O>=0){g();return}if(x&&O<=0){g();return}}f=!0,u=!0,yt(n.current.onDragStart,p)}if(!u)return;N.cancelable&&N.preventDefault();const U=n.current,K=ca(p,x,O,b);yt(p==="left"?U.onLeftProgress:U.onRightProgress,K)},k=(N,T)=>{if(!d){g();return}const O=N-y,$=T-m;if(!p&&!x&&Math.abs(O)>=or&&Math.abs($)<=Math.abs(O)*jn){const I=n.current;p=O>0?"left":"right",b=eo(p==="left"?I.leftWidth:I.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(!p){g();return}const U=Math.max(1,Date.now()-h),K=n.current;if(!u){const I=Math.abs(O),M=Math.abs($);I>=or&&M<=I*jn?p==="left"&&!x&&O>0?(yt(K.onLeftProgress,1),yt(K.onLeftOpen)):p==="right"&&!x&&O<0?(yt(K.onRightProgress,1),yt(K.onRightOpen)):yt(p==="left"?K.onLeftProgress:K.onRightProgress,x?1:0):yt(p==="left"?K.onLeftProgress:K.onRightProgress,x?1:0);const W=p;g(),yt(K.onDragEnd,W);return}const L=ca(p,x,O,b),D=Cg({side:p,isOpenAtStart:x,dx:O,dt:U,progress:L}),R=p;yt(R==="left"?D?K.onLeftOpen:K.onLeftClose:D?K.onRightOpen:K.onRightClose),g(),yt(K.onDragEnd,R,D)},C=N=>{const T=N.changedTouches[0];if(!T){g();return}const O=T.clientX-y,$=T.clientY-m;d&&(u||Math.abs(O)>=or&&Math.abs($)<=Math.abs(O)*jn)&&N.cancelable&&N.preventDefault(),k(T.clientX,T.clientY)},w=()=>{v()};return o.addEventListener("touchstart",E,{passive:!0}),o.addEventListener("touchmove",j,{passive:!1}),o.addEventListener("touchend",C,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{u&&p&&S()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",E),o.removeEventListener("touchmove",j),o.removeEventListener("touchend",C),o.removeEventListener("touchcancel",w)}},[e,r])};function uy({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 ga({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 xb=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,yb=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>wr(t,n)?null:e,to=()=>Ns.filter(e=>po.has(e.id)).map(e=>({...el(e)})),wb=()=>{if(typeof window>"u")return go;const e=window.localStorage.getItem("openInAppId");return e&&mo(e)?e:go};let so=!1,qs=!1,ps=!1,gs=0,Dn=null;const ba=()=>{Dn&&(clearTimeout(Dn),Dn=null)},Cs=Ls()((e,t)=>({selectedAppId:wb(),availableApps:to(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(so||typeof window>"u")return;so=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:to(),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=Ns.filter(m=>f.has(m.appName)||po.has(m.id)).map(m=>({...el(m),iconDataUrl:p.get(m.appName)}));e({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!tn()||!cr()||qs||t().hasLoadedApps&&!d)return;const f=Ns.map(p=>p.appName);ba(),qs=!0,ps=!1,e({isScanning:!0});try{const{apps:p,success:x,hasCache:y,isCacheStale:m}=await Ni(f,d),h=x&&!y&&p.length===0&&gs<3;if(e({isCacheStale:y?m:!1}),n(p,x?!h:!1),x){if(h){const g=[800,1600,3200][gs]??3200;gs+=1,ps=!0,Dn=setTimeout(()=>{r()},g);return}gs=0,ps=!1;return}if(gs<3){const g=[1e3,3e3,7e3][gs]??7e3;gs+=1,ps=!0,Dn=setTimeout(()=>{r()},g)}}finally{qs=!1,ps||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&mo(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)&&(gs=3,ps=!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(so||t().initialize(),!tn()||!cr()||qs||t().hasLoadedApps&&!n)return;const o=Ns.map(i=>i.appName);ba(),n&&e({hasLoadedApps:!1}),qs=!0,ps=!1,e({isScanning:!0});try{const{apps:i,hasCache:l,isCacheStale:c}=await Ni(o,n),d=new Set(i.map(x=>x.name)),u=new Map(i.map(x=>[x.name,x.iconDataUrl??void 0])),p=Ns.filter(x=>d.has(x.appName)||po.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:p.length>0?p:to(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{qs=!1,ps||e({isScanning:!1})}},selectApp:async n=>{mo(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Qa({openInAppId:n}))}})),vb="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",Sb="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",no=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?vb:e.id==="terminal"?Sb:void 0}),xa=({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})},jb=({directory:e,className:t})=>{const n=Cs(m=>m.selectedAppId),r=Cs(m=>m.availableApps),o=Cs(m=>m.isCacheStale),i=Cs(m=>m.isScanning),l=Cs(m=>m.initialize),c=Cs(m=>m.loadInstalledApps),d=Cs(m=>m.selectApp);a.useEffect(()=>{l()},[l]);const u=tn()&&cr(),f=a.useMemo(()=>{const m=r.find(h=>h.id===n)??r.find(h=>h.id===go)??r[0]??Ns[0];return no(m||Ns[0])},[r,n]);if(!u||!e||r.length===0)return null;const p=async m=>{await Ju(e,m.id,m.appName)||await Xa(e,m.appName)},x=async m=>{await d(m.id),await p(m)},y=async()=>{(await ys(e)).ok&&ie.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(xa,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{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(en,{}),r.map(m=>{const h=no(m);return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[s.jsx(xa,{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(ft,{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]})]})]})},Cb="\x1B",kb=new RegExp(`${Cb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ab=/https?:\/\/[^\s<>'"`]+/gi,jt="__pichamber_auto_discover_preview__",Nb=15e3,Ib=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},Eb=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}},Rb=e=>{const n=e.replace(kb,"").match(Ab);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},Db=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Pb=["dev","start","preview","serve"];async function Mb(e,t,n){if(!e)return null;const r=Lb(t);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Ob(n);if(o){const i=await Bb(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 Tb(e)){const o=await Fb(),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 Tb(e){const t=`${e}/index.html`,n=await yr(t,e);return typeof n=="string"&&n.trim().length>0}async function Fb(){try{const e=await Tt("/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 Lb(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(Pb.some(o=>n.includes(o)))return t}return null}function Ob(e){for(const{pattern:t}of Db)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function Bb(e){const t=await yr(`${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 yr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function yr(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await Tt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Ja()?.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 Tt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function _b(e){try{const t=await yr(`${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 zb=(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 Ub({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=Ha(),{terminal:o}=Fs(),{isMobile:i}=an(),l=le(q=>q.terminalShell),c=le(q=>q.terminalLoginShells.includes(q.terminalShell)),d=le(q=>q.setSettingsPage),u=le(q=>q.setSettingsDialogOpen),f=le(q=>q.setSettingsProjectsSelectedId),p=le(q=>q.openContextPreview),x=ge(q=>q.ensureDirectory),y=ge(q=>q.setTabLabel),m=ge(q=>q.setTabIconKey),h=ge(q=>q.setActiveTab),b=ge(q=>q.setConnecting),g=ge(q=>q.setTabSessionId),S=ge(q=>q.setTabPreviewUrl),v=ge(q=>q.projectActionRuns),E=ge(q=>q.setProjectActionRun),j=ge(q=>q.updateProjectActionRunStatus),k=ge(q=>q.removeProjectActionRun),[C,w]=a.useState([]),[N,T]=a.useState(null),[O,$]=a.useState(!1),U=a.useRef({}),K=a.useRef({}),L=a.useRef({}),D=a.useRef({}),R=a.useRef(new Set),I=a.useRef(0),M=e?.id??null,W=e?.path??"",G=a.useMemo(()=>M?{id:M,path:W}:null,[M,W]),B=a.useCallback(async q=>{await Ta(q)},[]),xe=a.useCallback(async()=>{if(!G)return;const q=I.current+1;I.current=q,$(!0);try{const ae=await io(G);if(I.current!==q)return;const ne=ae.actions;w(ne),T(me=>me===jt||me&&ne.some(fe=>fe.id===me)?me:null)}catch{if(I.current!==q)return}finally{I.current===q&&$(!1)}},[G]),V=a.useMemo(()=>jl(t||G?.path||""),[t,G?.path]),je=a.useMemo(()=>N?C.find(q=>q.id===N)??null:null,[C,N]),Re=a.useMemo(()=>({id:jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),H=!i,z=a.useMemo(()=>H?[Re,...C]:C,[C,Re,H]);a.useEffect(()=>{xe()},[xe]),a.useEffect(()=>{if(typeof window>"u")return;const q=ae=>{const ne=ae.detail;M&&(ne?.projectId&&ne.projectId!==M||xe())};return window.addEventListener(So,q),()=>{window.removeEventListener(So,q)}},[xe,M]),a.useEffect(()=>{N&&(N===jt&&H||C.some(q=>q.id===N)||T(null))},[C,H,N]),a.useEffect(()=>{const q=()=>{const ae=ge.getState(),ne=ae.sessions,me=ae.projectActionRuns;for(const[fe,Be]of Object.entries(me)){const ee=ne.get(Be.directory)?.tabs.find(Le=>Le.id===Be.tabId);if(!ee||ee.terminalSessionId!==Be.sessionId){k(fe);continue}const we=K.current[fe]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};K.current[fe]=we;const pe=z.find(Le=>Le.id===Be.actionId),ye=ae.getBuffer(Be.directory,Be.tabId).chunks;if(!pe||ye.length===0)continue;const We=ye.filter(Le=>we.lastSeenChunkId===null||Le.id>we.lastSeenChunkId);if(We.length===0)continue;const qe=We.map(Le=>Le.data).join(""),Pe=`${we.tail}${qe}`,Ye=!we.openedUrl&&pe.autoOpenUrl===!0?Rb(Pe):null,re=We[We.length-1]?.id??we.lastSeenChunkId;if(we.lastSeenChunkId=re,we.tail=Pe.slice(-512),Ye)if(we.openedUrl=!0,we.openInPreview){const Le=me[fe];Le&&(S(Le.directory,Le.tabId,Ye,{locked:!1,autoOpened:!1}),Le.status==="waiting-for-preview"&&j(fe,"running"),window.clearTimeout(D.current[fe]),delete D.current[fe],p(Le.directory,Ye))}else B(Ye),ie.success("Opened URL from action output");K.current[fe]=we}for(const fe of Object.keys(K.current))me[fe]||(delete K.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe])};return q(),ge.subscribe((ae,ne)=>{(ae.sessions!==ne.sessions||ae.buffers!==ne.buffers)&&q()})},[z,p,B,v,k,S,j]);const Y=a.useCallback(async(q,ae={})=>{if(!V)throw new Error("No active directory");const ne=ls(V,q.id);x(V);const me=ge.getState(),fe=me.getDirectoryState(V);let Be=U.current[ne]||null;const Se=Be?!!fe?.tabs.some(pe=>pe.id===Be):!1;(!Be||!Se)&&(Be=me.createTab(V),U.current[ne]=Be),y(V,Be,`Action: ${q.name}`),m(V,Be,q.icon||"play"),h(V,Be),ae.revealTerminal!==!1&&le.getState().openContextPanelTab(V,{mode:"terminal"});const we=ge.getState().getDirectoryState(V)?.tabs.find(pe=>pe.id===Be);return{key:ne,tabId:Be,sessionId:we?.terminalSessionId??null}},[x,V,h,m,y]),X=a.useCallback(async q=>{if(!n&&i)return;if(!V){ie.error("No active directory for action");return}const ae=ls(V,q.id),ne=v[ae];if(!(ne&&ne.status==="running")&&!R.current.has(ae)){R.current.add(ae);try{const me=q.id===jt?await(async()=>{const[Pe,Ye]=await Promise.all([io({id:G?.id??"",path:V}),_b(V)]),re=await Mb(V,Pe.actions,Ye);if(!re)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:jt,name:"Auto-discover",command:re.command,icon:"scan-2",autoOpenUrl:!0,openUrl:re.previewUrlHint||""}})():q,fe=me.autoOpenUrl===!0&&(me.openUrl||"").trim().length>0,Be=!fe&&q.id!==jt,{key:Se,tabId:ee,sessionId:we}=await Y(me,{revealTerminal:Be});let pe=we;if(!pe){b(V,ee,!0);try{pe=(await o.createSession({cwd:V,sessionId:ee,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,g(V,ee,pe)}finally{b(V,ee,!1)}}if(!pe)throw new Error("Failed to create terminal session");L.current[Se]?.(),b(V,ee,!0);const ye=o.connect(pe,{onEvent:Pe=>{Pe.type==="snapshot"&&(ge.getState().replaceBuffer(V,ee,Pe.data??"",Pe.sequence??0),ge.getState().setConnecting(V,ee,!1)),Pe.type==="data"&&typeof Pe.data=="string"&&Pe.data.length>0&&ge.getState().appendToBuffer(V,ee,Pe.data,Pe.sequence,Pe.replayData),Pe.type==="exit"&&(ge.getState().setTabLifecycle(V,ee,"exited"),ge.getState().setConnecting(V,ee,!1),ge.getState().removeProjectActionRun(Se),delete K.current[Se],L.current[Se]?.(),delete L.current[Se],window.clearTimeout(D.current[Se]),delete D.current[Se])},onError:(Pe,Ye)=>{ge.getState().setConnecting(V,ee,!1),Ye&&(ge.getState().setTabLifecycle(V,ee,"exited"),ge.getState().setTabSessionId(V,ee,null),ge.getState().removeProjectActionRun(Se))}});L.current[Se]=ye.close;const We=me.autoOpenUrl?Eb(me.openUrl):null;E({key:Se,directory:V,actionId:me.id,tabId:ee,sessionId:pe,status:me.id===jt&&!We?"waiting-for-preview":"running"}),window.clearTimeout(D.current[Se]),delete D.current[Se],me.id===jt&&!We&&(D.current[Se]=window.setTimeout(()=>{const Pe=ge.getState(),Ye=Pe.projectActionRuns[Se];Pe.updateProjectActionRunStatus(Se,"running"),Ye&&(Pe.setActiveTab(Ye.directory,Ye.tabId),le.getState().openContextPanelTab(Ye.directory,{mode:"terminal"})),delete D.current[Se]},Nb)),K.current[Se]={lastSeenChunkId:null,openedUrl:!!We||fe,tail:"",openInPreview:me.id===jt};const qe=Ib(me.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
-
`));await o.sendInput(pe,`${qe}\r`),We?(S(V,ee,We,{locked:!0,autoOpened:!0}),p(V,We),ie.success("Opened action URL")):fe?(S(V,ee,null,{locked:!0}),ie.error("Invalid custom URL format")):S(V,ee,null,{locked:!1,autoOpened:!1})}catch(me){k(ae),delete K.current[ae],L.current[ae]?.(),delete L.current[ae],window.clearTimeout(D.current[ae]),delete D.current[ae],ie.error(me instanceof Error?me.message:"Failed to run action")}finally{R.current.delete(ae)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Y,n,i,V,c,l,p,v,k,b,E,S,g,G?.id,o]),te=a.useCallback(async q=>{const ae=ls(V,q.id),ne=v[ae];if(!ne)return;j(ae,"stopping");const me=zb(o,ne.sessionId,1e3);try{await o.sendInput(ne.sessionId,"")}catch{}const fe=await me;if(ge.getState().getDirectoryState(ne.directory)?.tabs.find(ee=>ee.id===ne.tabId)?.terminalSessionId===ne.sessionId&&!fe){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(ae),delete K.current[ae],L.current[ae]?.(),delete L.current[ae],window.clearTimeout(D.current[ae]),delete D.current[ae]},[V,v,k,g,o,j]),ue=a.useCallback(()=>{const q=je??z[0];if(!q)return;const ae=ls(V,q.id),ne=v[ae];if(ne?.status!=="stopping"){if(ne){te(q);return}X(q)}},[z,V,X,v,je,te]),he=a.useCallback((q,ae=!1)=>{if(T(q.id),!ae){X(q);return}const ne=ls(V,q.id),me=v[ne];if(me?.status!=="stopping"){if(me){te(q);return}X(q)}},[V,X,v,te]),Q=a.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),se=je??z[0]??null,ce=se?v[ls(V,se.id)]:null,Ce=ge(q=>ce?q.sessions.get(ce.directory)?.tabs.find(ae=>ae.id===ce.tabId)?.previewUrl??null:null),ve=!!((n||!i)&&G&&V),Ge=je??z[0]??null;return{shouldRender:ve,isLoading:O,normalizedDirectory:V,resolvedSelected:Ge,displayActions:z,projectActionRuns:v,selectedRunPreviewUrl:Ce,handlePrimaryClick:ue,handleSelectAction:he,openProjectActionsSettings:Q,openContextPreview:p}}const ya=({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}=Ub({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const b=d.icon||"play",g=d.id===jt?"scan-2":Rn[b]||"play",S=ls(c,d.id),v=f[S],E=v?.status==="stopping",j=v?.status==="waiting-for-preview",k=!!(v&&p),C=()=>{!v||!p||h(v.directory,p)},w=d.id===jt;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs(Ue,{children:[s.jsx($e,{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":v?`Stop ${d.name}`:`Run ${d.name}`,children:E||j?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),w?s.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs(Ue,{children:[s.jsx($e,{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:C,children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{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(en,{}),u.map(N=>{const T=N.icon||"play",O=N.id===jt?"scan-2":Rn[T]||"play",$=ls(c,N.id),U=f[$],K=!!U,L=U?.status==="stopping";return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:O,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),L||U?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?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(Ue,{children:[s.jsx($e,{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":v?`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||j?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),w?s.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:C,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(Ke,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{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(en,{}),u.map(N=>{const T=N.icon||"play",O=N.id===jt?"scan-2":Rn[T]||"play",$=ls(c,N.id),U=f[$],K=!!U,L=U?.status==="stopping";return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:O,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),L||U?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]})},Ut={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function ar(e){return e?.deploymentKind==="docker"?{name:Ut.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:Ut.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:Ut.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:Ut.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:Ut.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:Ut.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:Ut.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:Ut.centos,color:"#932279"}:{name:Ut.linux}:e?.serverPlatform==="darwin"?{name:Ut.darwin}:{name:Ut.unknown}}const $b=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 Kb({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const u=Qe();try{const f=await Tt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);u===Qe()&&r(p)}catch{u===Qe()&&r(null)}},[]);a.useEffect(()=>(o(),On(()=>{o()})),[o]);const i=ar(n),l=$b(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Wt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(ln,"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(Ke,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(Ht,{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:()=>{ys(d).then(u=>{u.ok?ie.success("Server address copied"):ie.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 Wb=({isMobile:e})=>{const n=Fs().github??null,r=Sr(i=>i.refresh),o=Mh();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(ln,"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]})]})},Gb=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(Wt,{open:l,onOpenChange:m=>{c(m),m&&d()},children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(ln,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(Ke,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(Ht,{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(Su,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),Hb=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(ns,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(rs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(vs,{children:[s.jsx(us,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(Ss,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ts,{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"})]})]})}),qb=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},vn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},Yb=a.lazy(()=>ht(()=>import("./SessionSwitcherDropdown-JaIDcDIj.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),fy=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{Kt("ui.header.render");const c=le(F=>F.setSessionSwitcherOpen),d=le(F=>F.toggleSidebar),u=le(F=>F.isSidebarOpen),f=le(F=>F.activeMainTab),p=le(F=>F.setActiveMainTab),x=le(F=>F.shortcutOverrides);le(F=>F.timeFormatPreference),Fs();const y=Te(F=>!!F.newSessionDraft?.open),m=Te(F=>F.currentSessionId),h=Ga(m??""),b=ju(m),g=a.useMemo(()=>{if(!b)return null;const F=b;return{title:b.title??null,directory:F.directory??null,created:b.time?.created??null,slug:F.slug??null,shareUrl:b.share?.url??null,parentId:b.parentID??null}},[b]),S=ut(ro(F=>{if(!F.activeProjectId)return null;const oe=F.projects.find(be=>be.id===F.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),v=sn(F=>F.homeDirectory),E=a.useMemo(()=>{if(!S)return null;const F=S.label?.trim();if(F)return F;const oe=S.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[S]),{isMobile:j}=an(),{enabled:k}=$o(),C=!!(k&&i&&o!==void 0),w=a.useMemo(()=>[...pb(l)],[l]),[N,T]=a.useState(!1),O=a.useRef(null),[$,U]=a.useState(()=>typeof window>"u"?!1:tn()),K=a.useMemo(()=>Za(),[]),L=Cu(),[D,R]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=qa(),W=a.useMemo(()=>{if(typeof window>"u")return null;const F=window.__PICHAMBER_MACOS_MAJOR__;if(typeof F=="number"&&Number.isFinite(F)&&F>0)return F;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const be=Number.parseInt(oe[1],10),_e=Number.parseInt(oe[2],10);return Number.isNaN(be)?null:be===10?_e:be},[]);Ee.useEffect(()=>{typeof window>"u"||U(tn())},[]);const G=le(F=>F.isSessionSwitcherOpen),[B,xe]=a.useState(!1),[V,je]=a.useState("Local"),[Re,H]=a.useState(!0),[z,Y]=a.useState(()=>ar(null)),[X,te]=a.useState(!1),[ue,he]=a.useState(null),[Q,se]=a.useState(!1),[ce,Ce]=a.useState(null),ve=a.useRef(0),Ge=a.useMemo(()=>qb(V),[V]),q=a.useCallback(async()=>{if(typeof window>"u"||!$)return;const F=Qe(),oe=()=>Qe()===F;try{const be=await Tt("/api/version");if(!oe())return;const _e=be.ok?await be.json().catch(()=>null):null;if(!oe())return;if(Y(ar(_e)),cr()){je("Local"),H(!0);return}H(!1);const Je=await Xu();if(!oe())return;const Xe=Zu(),hs=ef([tf(Xe),...Je.hosts]);if(hs.id===sf){je("Local"),H(!0);return}je(nf(hs.label.trim()||"Instance"))}catch{oe()&&(je("Local"),H(!0),Y(ar(null)))}},[$]);Ee.useEffect(()=>(q(),On(()=>{ve.current+=1,he(null),Ce(null),se(!1),te(!1),q()})),[q]);const ae=a.useCallback(async()=>{const F=ve.current+1;ve.current=F;const oe=Qe(),be=()=>ve.current===F&&Qe()===oe;if(Re){he(null),Ce(null);return}se(!0),Ce(null);try{const _e=new URLSearchParams({appType:"web",instanceMode:"remote"}),Je=await Tt(`/api/pi/update-check?${_e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!Je.ok)throw new Error(`Server responded with ${Je.status}`);const Xe=await Je.json();if(!be())return;he({available:Xe.available??!1,version:Xe.version,currentVersion:Xe.currentVersion??"unknown",body:Xe.body,nextSuggestedCheckInSec:typeof Xe.nextSuggestedCheckInSec=="number"?Xe.nextSuggestedCheckInSec:void 0,packageManager:Xe.packageManager,updateCommand:Xe.updateCommand,channel:Xe.channel==="rc"?"rc":"stable"})}catch(_e){if(!be())return;he(null),Ce(_e instanceof Error?_e.message:"Failed to check remote instance updates")}finally{be()&&se(!1)}},[Re]);a.useEffect(()=>fh(()=>{Re||ae()}),[ae,Re]),a.useEffect(()=>{ve.current+=1,he(null),Ce(null),se(!1),te(!1)},[Re,V]),a.useEffect(()=>{if(!$||Re)return;const F=3e3,oe=3600*1e3;let be=!1,_e=null;const Je=Xe=>{_e=window.setTimeout(()=>{if(be||typeof document<"u"&&document.visibilityState!=="visible"){Je(oe);return}ae().finally(()=>{be||Je(oe)})},Xe)};return Je(F),()=>{be=!0,_e!==null&&window.clearTimeout(_e)}},[ae,Re,V,$]);const ne=a.useCallback(()=>{if(ue?.available){te(!0);return}ae()},[ae,ue?.available]),me=m?g??null:null,fe=a.useRef(null),[Be,Se]=a.useState(0);a.useEffect(()=>{if(!m){fe.current&&(fe.current=null,Se(_e=>_e+1));return}if(me){fe.current={sessionId:m,session:me,expiresAt:Date.now()+2e3};return}const F=fe.current;if(!F||F.sessionId!==m)return;const oe=F.expiresAt-Date.now();if(oe<=0){fe.current=null,Se(_e=>_e+1);return}const be=window.setTimeout(()=>{fe.current?.sessionId===m&&(fe.current=null),Se(_e=>_e+1)},oe);return()=>{window.clearTimeout(be)}},[m,me]);const ee=(()=>{if(me)return me;if(!m)return null;const F=fe.current;return F&&F.sessionId===m&&F.expiresAt>Date.now()?F.session:null})(),we=a.useMemo(()=>{const F=typeof ee?.directory=="string"?ee.directory:"";return vn(F||"")},[ee?.directory]),pe=Te(F=>F.newSessionDraft?.open?vn(F.newSessionDraft.directoryOverride??""):""),ye=a.useMemo(()=>xb({sessionDirectory:we,draftDirectory:pe,isNewSessionDraftOpen:y}),[pe,y,we]),qe=Wa(ye||null),Pe=a.useMemo(()=>yb({activeProjectLabel:E,openDirectory:ye,homeDirectory:v}),[E,v,ye]),Ye=!!(Pe||qe),re=a.useMemo(()=>m?bs(ee):Pe??"PiChamber",[ee,m,Pe]),Le=ku(),nt=Te(F=>F.updateSessionTitle),at=Te(F=>F.archiveSessions),Ve=Te(F=>F.deleteSessions),[mt,lt]=a.useState(!1),[qt,Yt]=a.useState(!1),Ze=a.useRef(!1),[Ct,Vt]=a.useState(""),[kt,Ft]=a.useState(null),gt=a.useRef(null);a.useEffect(()=>{Ze.current=!1,Yt(!1),lt(!1),Vt(""),Ft(null)},[m]);const wt=a.useCallback(()=>{m&&(Vt(ee?.title?.trim()||re),lt(!0))},[ee?.title,m,re]),st=a.useCallback(async()=>{if(!m)return;const F=Ct.trim();F&&F!==ee?.title?.trim()&&await nt(m,F),lt(!1)},[ee?.title,m,Ct,nt]);a.useEffect(()=>{if(!mt)return;const F=oe=>{const be=oe.target;(!be||!gt.current?.contains(be))&&st()};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[mt,st]);const At=a.useCallback(()=>{m&&ys(m).then(F=>{ie[F.ok?"success":"error"](F.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[m]),ke=a.useCallback(async()=>{if(!m||!ye){ie.error("Nothing to export");return}try{await Le.syncSession(m)}catch{ie.error("Failed to load the complete session history");return}const F=[];if(F.length===0){ie.error("Nothing to export");return}const oe=Zl(F,ee?.title??null),be=sc(ee?.title??null);await tc(oe,be)||ec(oe,be),ie.success("Session exported")},[ee?.title,m,ye,Le]);h?.type==="busy"||h?.type;const He=a.useCallback(async()=>{if(!m||!kt)return;const F=Au(),oe=[m];for(let Xe=0;Xe<oe.length;Xe+=1){const hs=oe[Xe];for(const Bt of F)Bt.parentID===hs&&!oe.includes(Bt.id)&&oe.push(Bt.id)}const be=kt;if(Ft(null),(be==="archive"?await at(oe):await Ve(oe)).failedIds.length>0){ie.error(be==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(be==="archive"?"Session archived":"Session deleted")},[at,m,Ve,kt]),Ae=le(F=>F.isArchivePageOpen),Oe=a.useMemo(()=>Ae?{title:"Archive",subtitle:null}:null,[Ae]),Fe=a.useMemo(()=>vn(ye||S?.path||""),[S?.path,ye]),rt=a.useCallback(()=>{Fe&&ys(Fe).then(F=>{ie[F.ok?"success":"error"](F.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ie.error("Failed to copy working directory"))},[Fe]),vt=a.useMemo(()=>S?{id:S.id,path:S.path}:null,[S]),Nt=a.useRef(null);a.useEffect(()=>{!vt||!Fe||(Nt.current={projectRef:vt,directory:Fe})},[Fe,vt]);const bt=a.useMemo(()=>vt&&Fe?{projectRef:vt,directory:Fe}:Nt.current,[Fe,vt]),ct=a.useCallback(()=>{if(typeof document>"u")return;const F=document.activeElement;if(!F)return;const oe=F.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||F.isContentEditable)&&F.blur()},[]),tt=a.useCallback(()=>{if(j){ct(),c(!G);return}d()},[ct,j,G,c,d]),It=a.useCallback(()=>{In("desktop_open_draft_mini_chat_window",{directory:vn(ye||S?.path||""),projectId:S?.id??null,apiBaseUrl:ho(),clientToken:fo()}).catch(F=>{console.warn("[header] failed to open draft mini chat window",F)})},[S?.id,S?.path,ye]),Et=a.useCallback(()=>{if(y){It();return}m&&In("desktop_open_session_mini_chat_window",{sessionId:m,directory:vn(ye||S?.path||""),apiBaseUrl:ho(),clientToken:fo()}).catch(F=>{console.warn("[header] failed to open session mini chat window",F)})},[S?.path,m,It,y,ye]),os=ln,Qt=Uh,Jt=a.useMemo(()=>n?"sessions":C?r&&o?o:null:r?"git":f,[f,C,n,r,o]),xt=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&G&&c(!1)},[G,n,e,t,r,c]),Os=a.useCallback(()=>{e?.()},[e]),un=a.useCallback(()=>{t?.()},[t]),Bs=a.useMemo(()=>$&&I&&!D?"5.5rem":L?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!$||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[$,D,I,L,M]);Ee.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Bs)},[Bs]);const _s=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Lt=u?"0px":$&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":k?"2.75rem":"2.5rem";Ee.useEffect(()=>{if(!$||!I){R(!1);return}let F=!1;const oe=async()=>{try{const _e=await In("desktop_is_window_fullscreen");F||R(_e===!0)}catch{F||R(!1)}},be=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",be),()=>{F=!0,window.removeEventListener("pichamber:window-resized",be)}},[$,I]);const fs=a.useMemo(()=>!$||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[$,I,W]),St=a.useMemo(()=>{if(!($&&!M))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[$,M]),is=a.useCallback(()=>{if(typeof document>"u")return;const F=O.current?.getBoundingClientRect().height;if(F){const oe=`${F}px`,be=document.documentElement.style;be.getPropertyValue("--oc-header-height")!==oe&&be.setProperty("--oc-header-height",oe)}},[]);Ee.useEffect(()=>{if(typeof window>"u")return;is();const F=O.current;if(!F||typeof ResizeObserver>"u")return()=>{};let oe=0;const be=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,is()}))},_e=new ResizeObserver(be);return _e.observe(F),window.addEventListener("resize",be),window.addEventListener("orientationchange",be),()=>{oe&&cancelAnimationFrame(oe),_e.disconnect(),window.removeEventListener("resize",be),window.removeEventListener("orientationchange",be)}},[is]),Ee.useEffect(()=>{is()},[is,j,fs]);const as=a.useCallback(async F=>{const oe=F.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||F.button===0&&$&&await Nu()},[$]),ot=a.useMemo(()=>j?[{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"}]:[],[j]),Ot=a.useCallback(F=>Ko(lr(F,x)),[x]);Ee.useEffect(()=>{!j&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,j,p]),Ee.useEffect(()=>{const F=oe=>{if(rf(oe)&&!oe.shiftKey&&!oe.altKey){const be=parseInt(oe.key,10);be>=1&&be<=ot.length&&(oe.preventDefault(),j&&(ct(),xt()),p(ot[be-1].id))}};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[ct,xt,j,p,ot]),Ee.useEffect(()=>{const F=oe=>{const be=lr("toggle_services_menu",x);if(of(oe,be)){oe.preventDefault(),B?xe(!1):(xe(!0),q());return}};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[x,B,q]);const js=F=>{const oe=f===F.id,be=F.icon==="diff",_e=be?null:F.icon,Je=F.id==="chat",Xe=Bt=>be?s.jsx(ga,{size:Bt}):_e?s.jsx(P,{name:_e,className:`h-${Bt/4} w-${Bt/4}`}):null,hs=s.jsxs("button",{type:"button",onClick:()=>p(F.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",oe?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",Je&&!j&&"min-w-[100px] justify-center"),"aria-label":F.label,"aria-selected":oe,role:"tab",children:[j?Xe(20):s.jsxs(s.Fragment,{children:[Xe(16),s.jsx("span",{className:"header-tab-label",children:F.label})]}),F.badge!==void 0&&F.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:F.badge})]});return s.jsx(a.Fragment,{children:hs},F.id)},Rt=s.jsxs(s.Fragment,{children:[s.jsx(jb,{directory:Fe,className:"mr-1"}),$?s.jsx(Gb,{isDesktopApp:$,currentInstanceLabel:V,compactCurrentInstanceLabel:Ge,currentInstanceIsLocal:Re,currentInstanceIcon:z,isDesktopServicesOpen:B,setIsDesktopServicesOpen:xe,refreshCurrentInstanceLabel:q,shortcutLabel:Ot,remoteUpdateInfo:ue,remoteUpdateChecking:Q,remoteUpdateError:ce,onOpenRemoteUpdate:ne}):s.jsx(Kb,{open:B,onOpenChange:xe}),s.jsx(Wb,{isMobile:j})]}),fn=K&&(y||!!m),zs=()=>s.jsxs("div",{onMouseDown:as,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",fs),style:St,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:_s}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Lt}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Oe?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:Oe.title}),Oe.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:Oe.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:os,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(Yb,{align:"start",children:s.jsx("button",{type:"button",className:os,"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:[mt?s.jsxs("form",{ref:gt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:F=>{F.preventDefault(),st()},children:[s.jsx("input",{value:Ct,onChange:F=>Vt(F.target.value),autoFocus:!0,onKeyDown:F=>{F.stopPropagation(),F.key==="Escape"&<(!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:()=>lt(!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":re}),Ye?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:[Pe?s.jsx("span",{className:"truncate",children:Pe}):null,qe?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:qe})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!y&&!mt?s.jsxs(Wt,{open:qt,onOpenChange:Yt,onOpenChangeComplete:F=>{!F&&Ze.current&&(Ze.current=!1,wt())},children:[s.jsx(Gt,{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(Ht,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ft,{onClick:()=>{Ze.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ft,{onClick:At,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ft,{onClick:rt,disabled:!Fe,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(en,{}),s.jsxs(ft,{onClick:()=>{ke()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(en,{}),s.jsxs(ft,{onClick:()=>Ft("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ft,{className:"text-destructive focus:text-destructive",onClick:()=>Ft("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),ot.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:ot.map(F=>js(F))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Al,{}),bt?s.jsx(ya,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,s.jsx($h,{visible:fn,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:Et,className:_(os,"mr-1"),Icon:"picture-in-picture-2"}),Rt,s.jsx(Iu,{visible:M})]})]})]}),hn=()=>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:_s}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Lt}})]}),!k&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:Os,className:_(Qt,Jt==="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"})}):G?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:tt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:s.jsx(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&G&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!G||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!C&&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:ot.map(F=>{const oe=f===F.id,be=F.icon==="diff",_e=be?null:F.icon;return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{j&&(ct(),xt()),p(F.id)},"aria-label":F.label,"aria-selected":oe,role:"tab",className:_(Qt,"relative rounded-lg",Jt===F.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[be?s.jsx(ga,{className:"h-5 w-5"}):_e?s.jsx(P,{name:_e,className:"h-5 w-5"}):null,F.badge!==void 0&&F.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:F.badge}),F.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(Ke,{children:s.jsx("p",{children:F.label})})]},F.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[C&&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:w.map(F=>{const oe=r&&o===F.id;return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{j&&(ct(),xt()),T(!1),i?.(F.id)},"aria-label":F.label,"aria-selected":oe,role:"tab",className:_(Qt,"relative h-11 w-11 rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:F.icon,className:"h-5 w-5"})})}),s.jsx(Ke,{children:s.jsx("p",{children:F.label})})]},F.id)})}),s.jsx(zh,{open:N,onOpenChange:T,currentSessionId:m,effectiveDirectory:ye||null,isNewSessionDraftOpen:y})]}),bt&&s.jsx(ya,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!C?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:un,className:_(Qt,"relative",Jt==="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(Ke,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),de=_("header-safe-area relative z-10 bg-background",j&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:O,className:de,style:{"--padding-scale":"1"},children:j?hn():zs()}),s.jsx(Hb,{action:kt,onClose:()=>Ft(null),sessionTitle:re,onConfirm:()=>{He()}}),s.jsx(bl,{open:X,onOpenChange:te,info:ue,downloading:!1,downloaded:!1,progress:null,error:ce,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},wa="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",Vb="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",hy=()=>{const e=le(y=>y.isSidebarOpen),t=le(y=>y.toggleSidebar),n=le(y=>y.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Ko(lr("toggle_sidebar",n)),l=qa(),{enabled:c}=$o(),d=!e,u=l,f=d||u,p=u,x=a.useCallback(()=>{In("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=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},m=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!p)return;const h=o.current,b=r.current;if(!h||!b){y(0),m(0);return}const g=()=>{const v=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(v),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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(wa,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?Vb:wa,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},va=200,Qb="cubic-bezier(0.22, 1, 0.36, 1)",my=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),va);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${va}ms ${Qb}`}},py=()=>{tl()},gy=e=>{Te.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ge.getState().clearAll(),tl(),sn.getState().resetForRuntimeSwitch(),Eu.getState().resetForRuntimeSwitch(),Ru.getState().resetForRuntimeSwitch(),Du(),af(),lf(),Lu(),Pu.getState().resetForRuntimeSwitch(),$t.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ut.getState().resetForRuntimeSwitch(),Mu(),Tu(),Cf.getState().reset(),cf.getState().resetForRuntimeSwitch(),Ba.getState().resetForRuntimeSwitch(e.runtimeKey),lo.getState().resetForRuntimeSwitch(e.runtimeKey),df(),Ps.getState().resetForRuntimeSwitch(e.runtimeKey),Fu.getState().resetForRuntimeSwitch(),ss.getState().resetForRuntimeSwitch(),pt.getState().resetForRuntimeSwitch(e.runtimeKey),uf.getState().resetForRuntimeSwitch(e.runtimeKey),Te.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=le.getState();bo({sessionId:Te.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Gx as $,_x as A,Ar as B,Bx as C,la as D,Rs as E,bx as F,ql as G,fy as H,Th as I,Fh as J,Oi as K,uy as L,kl as M,$f as N,mx as O,Cs as P,xs as Q,ss as R,ny as S,ay as T,Hl as U,Fl as V,hx as W,Ln as X,Tl as Y,xx as Z,vl as _,zh as a,dx as a$,zx as a0,Hx as a1,ty as a2,sy as a3,Mh as a4,Vx as a5,qx as a6,$x as a7,Yx as a8,Jx as a9,xl as aA,dh as aB,Bn as aC,_n as aD,vx as aE,uh as aF,yl as aG,Ix as aH,En as aI,yx as aJ,oh as aK,ih as aL,Ex as aM,Fx as aN,Mx as aO,Tx as aP,Lx as aQ,Dx as aR,Sx as aS,jx as aT,Cx as aU,Px as aV,Ch as aW,Ax as aX,Wf as aY,ah as aZ,Gf as a_,Xx as aa,Zx as ab,ey as ac,Qx as ad,Io as ae,Vi as af,ks as ag,wn as ah,dn as ai,Vm as aj,cn as ak,Kx as al,Sr as am,Wx as an,Ux as ao,ch as ap,Rx as aq,rh as ar,wx as as,Ox as at,Nx as au,bl as av,Ho as aw,kx as ax,lh as ay,Eh as az,jn as b,jg as c,ry as d,or as e,pb as f,oy as g,Yg as h,Ag as i,ly as j,ac as k,my as l,dy as m,hy as n,py as o,gy as p,px as q,cy as r,iy as s,gx as t,Bh as u,fx as v,cx as w,ux as x,Cr as y,kr as z};
|
|
62
|
+
`));await o.sendInput(pe,`${qe}\r`),We?(S(V,ee,We,{locked:!0,autoOpened:!0}),p(V,We),ie.success("Opened action URL")):fe?(S(V,ee,null,{locked:!0}),ie.error("Invalid custom URL format")):S(V,ee,null,{locked:!1,autoOpened:!1})}catch(me){k(ae),delete K.current[ae],L.current[ae]?.(),delete L.current[ae],window.clearTimeout(D.current[ae]),delete D.current[ae],ie.error(me instanceof Error?me.message:"Failed to run action")}finally{R.current.delete(ae)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Y,n,i,V,c,l,p,v,k,b,E,S,g,G?.id,o]),te=a.useCallback(async q=>{const ae=ls(V,q.id),ne=v[ae];if(!ne)return;j(ae,"stopping");const me=zb(o,ne.sessionId,1e3);try{await o.sendInput(ne.sessionId,"")}catch{}const fe=await me;if(ge.getState().getDirectoryState(ne.directory)?.tabs.find(ee=>ee.id===ne.tabId)?.terminalSessionId===ne.sessionId&&!fe){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(ae),delete K.current[ae],L.current[ae]?.(),delete L.current[ae],window.clearTimeout(D.current[ae]),delete D.current[ae]},[V,v,k,g,o,j]),ue=a.useCallback(()=>{const q=je??z[0];if(!q)return;const ae=ls(V,q.id),ne=v[ae];if(ne?.status!=="stopping"){if(ne){te(q);return}X(q)}},[z,V,X,v,je,te]),he=a.useCallback((q,ae=!1)=>{if(T(q.id),!ae){X(q);return}const ne=ls(V,q.id),me=v[ne];if(me?.status!=="stopping"){if(me){te(q);return}X(q)}},[V,X,v,te]),Q=a.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),se=je??z[0]??null,ce=se?v[ls(V,se.id)]:null,Ce=ge(q=>ce?q.sessions.get(ce.directory)?.tabs.find(ae=>ae.id===ce.tabId)?.previewUrl??null:null),ve=!!((n||!i)&&G&&V),Ge=je??z[0]??null;return{shouldRender:ve,isLoading:O,normalizedDirectory:V,resolvedSelected:Ge,displayActions:z,projectActionRuns:v,selectedRunPreviewUrl:Ce,handlePrimaryClick:ue,handleSelectAction:he,openProjectActionsSettings:Q,openContextPreview:p}}const ya=({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}=Ub({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const b=d.icon||"play",g=d.id===jt?"scan-2":Rn[b]||"play",S=ls(c,d.id),v=f[S],E=v?.status==="stopping",j=v?.status==="waiting-for-preview",k=!!(v&&p),C=()=>{!v||!p||h(v.directory,p)},w=d.id===jt;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs(Ue,{children:[s.jsx($e,{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":v?`Stop ${d.name}`:`Run ${d.name}`,children:E||j?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),w?s.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs(Ue,{children:[s.jsx($e,{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:C,children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{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(en,{}),u.map(N=>{const T=N.icon||"play",O=N.id===jt?"scan-2":Rn[T]||"play",$=ls(c,N.id),U=f[$],K=!!U,L=U?.status==="stopping";return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:O,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),L||U?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?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(Ue,{children:[s.jsx($e,{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":v?`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||j?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),w?s.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:C,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(Ke,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Wt,{children:[s.jsx(Gt,{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(Ht,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{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(en,{}),u.map(N=>{const T=N.icon||"play",O=N.id===jt?"scan-2":Rn[T]||"play",$=ls(c,N.id),U=f[$],K=!!U,L=U?.status==="stopping";return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:O,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),L||U?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]})},Ut={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function ar(e){return e?.deploymentKind==="docker"?{name:Ut.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:Ut.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:Ut.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:Ut.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:Ut.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:Ut.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:Ut.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:Ut.centos,color:"#932279"}:{name:Ut.linux}:e?.serverPlatform==="darwin"?{name:Ut.darwin}:{name:Ut.unknown}}const $b=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 Kb({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const u=Qe();try{const f=await Tt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);u===Qe()&&r(p)}catch{u===Qe()&&r(null)}},[]);a.useEffect(()=>(o(),On(()=>{o()})),[o]);const i=ar(n),l=$b(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Wt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(ln,"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(Ke,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(Ht,{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:()=>{ys(d).then(u=>{u.ok?ie.success("Server address copied"):ie.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 Wb=({isMobile:e})=>{const n=Fs().github??null,r=Sr(i=>i.refresh),o=Mh();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(ln,"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]})]})},Gb=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(Wt,{open:l,onOpenChange:m=>{c(m),m&&d()},children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(ln,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(Ke,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(Ht,{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(Su,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),Hb=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(ns,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(rs,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(vs,{children:[s.jsx(us,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(Ss,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ts,{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"})]})]})}),qb=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},vn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},Yb=a.lazy(()=>ht(()=>import("./SessionSwitcherDropdown-CfySKnUu.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),fy=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{Kt("ui.header.render");const c=le(F=>F.setSessionSwitcherOpen),d=le(F=>F.toggleSidebar),u=le(F=>F.isSidebarOpen),f=le(F=>F.activeMainTab),p=le(F=>F.setActiveMainTab),x=le(F=>F.shortcutOverrides);le(F=>F.timeFormatPreference),Fs();const y=Te(F=>!!F.newSessionDraft?.open),m=Te(F=>F.currentSessionId),h=Ga(m??""),b=ju(m),g=a.useMemo(()=>{if(!b)return null;const F=b;return{title:b.title??null,directory:F.directory??null,created:b.time?.created??null,slug:F.slug??null,shareUrl:b.share?.url??null,parentId:b.parentID??null}},[b]),S=ut(ro(F=>{if(!F.activeProjectId)return null;const oe=F.projects.find(be=>be.id===F.activeProjectId);return oe?{id:oe.id,path:oe.path,label:oe.label}:null})),v=sn(F=>F.homeDirectory),E=a.useMemo(()=>{if(!S)return null;const F=S.label?.trim();if(F)return F;const oe=S.path.split(/[\\/]/).filter(Boolean);return oe[oe.length-1]??null},[S]),{isMobile:j}=an(),{enabled:k}=$o(),C=!!(k&&i&&o!==void 0),w=a.useMemo(()=>[...pb(l)],[l]),[N,T]=a.useState(!1),O=a.useRef(null),[$,U]=a.useState(()=>typeof window>"u"?!1:tn()),K=a.useMemo(()=>Za(),[]),L=Cu(),[D,R]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=qa(),W=a.useMemo(()=>{if(typeof window>"u")return null;const F=window.__PICHAMBER_MACOS_MAJOR__;if(typeof F=="number"&&Number.isFinite(F)&&F>0)return F;if(typeof navigator>"u")return null;const oe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!oe)return null;const be=Number.parseInt(oe[1],10),_e=Number.parseInt(oe[2],10);return Number.isNaN(be)?null:be===10?_e:be},[]);Ee.useEffect(()=>{typeof window>"u"||U(tn())},[]);const G=le(F=>F.isSessionSwitcherOpen),[B,xe]=a.useState(!1),[V,je]=a.useState("Local"),[Re,H]=a.useState(!0),[z,Y]=a.useState(()=>ar(null)),[X,te]=a.useState(!1),[ue,he]=a.useState(null),[Q,se]=a.useState(!1),[ce,Ce]=a.useState(null),ve=a.useRef(0),Ge=a.useMemo(()=>qb(V),[V]),q=a.useCallback(async()=>{if(typeof window>"u"||!$)return;const F=Qe(),oe=()=>Qe()===F;try{const be=await Tt("/api/version");if(!oe())return;const _e=be.ok?await be.json().catch(()=>null):null;if(!oe())return;if(Y(ar(_e)),cr()){je("Local"),H(!0);return}H(!1);const Je=await Xu();if(!oe())return;const Xe=Zu(),hs=ef([tf(Xe),...Je.hosts]);if(hs.id===sf){je("Local"),H(!0);return}je(nf(hs.label.trim()||"Instance"))}catch{oe()&&(je("Local"),H(!0),Y(ar(null)))}},[$]);Ee.useEffect(()=>(q(),On(()=>{ve.current+=1,he(null),Ce(null),se(!1),te(!1),q()})),[q]);const ae=a.useCallback(async()=>{const F=ve.current+1;ve.current=F;const oe=Qe(),be=()=>ve.current===F&&Qe()===oe;if(Re){he(null),Ce(null);return}se(!0),Ce(null);try{const _e=new URLSearchParams({appType:"web",instanceMode:"remote"}),Je=await Tt(`/api/pi/update-check?${_e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!Je.ok)throw new Error(`Server responded with ${Je.status}`);const Xe=await Je.json();if(!be())return;he({available:Xe.available??!1,version:Xe.version,currentVersion:Xe.currentVersion??"unknown",body:Xe.body,nextSuggestedCheckInSec:typeof Xe.nextSuggestedCheckInSec=="number"?Xe.nextSuggestedCheckInSec:void 0,packageManager:Xe.packageManager,updateCommand:Xe.updateCommand,channel:Xe.channel==="rc"?"rc":"stable"})}catch(_e){if(!be())return;he(null),Ce(_e instanceof Error?_e.message:"Failed to check remote instance updates")}finally{be()&&se(!1)}},[Re]);a.useEffect(()=>fh(()=>{Re||ae()}),[ae,Re]),a.useEffect(()=>{ve.current+=1,he(null),Ce(null),se(!1),te(!1)},[Re,V]),a.useEffect(()=>{if(!$||Re)return;const F=3e3,oe=3600*1e3;let be=!1,_e=null;const Je=Xe=>{_e=window.setTimeout(()=>{if(be||typeof document<"u"&&document.visibilityState!=="visible"){Je(oe);return}ae().finally(()=>{be||Je(oe)})},Xe)};return Je(F),()=>{be=!0,_e!==null&&window.clearTimeout(_e)}},[ae,Re,V,$]);const ne=a.useCallback(()=>{if(ue?.available){te(!0);return}ae()},[ae,ue?.available]),me=m?g??null:null,fe=a.useRef(null),[Be,Se]=a.useState(0);a.useEffect(()=>{if(!m){fe.current&&(fe.current=null,Se(_e=>_e+1));return}if(me){fe.current={sessionId:m,session:me,expiresAt:Date.now()+2e3};return}const F=fe.current;if(!F||F.sessionId!==m)return;const oe=F.expiresAt-Date.now();if(oe<=0){fe.current=null,Se(_e=>_e+1);return}const be=window.setTimeout(()=>{fe.current?.sessionId===m&&(fe.current=null),Se(_e=>_e+1)},oe);return()=>{window.clearTimeout(be)}},[m,me]);const ee=(()=>{if(me)return me;if(!m)return null;const F=fe.current;return F&&F.sessionId===m&&F.expiresAt>Date.now()?F.session:null})(),we=a.useMemo(()=>{const F=typeof ee?.directory=="string"?ee.directory:"";return vn(F||"")},[ee?.directory]),pe=Te(F=>F.newSessionDraft?.open?vn(F.newSessionDraft.directoryOverride??""):""),ye=a.useMemo(()=>xb({sessionDirectory:we,draftDirectory:pe,isNewSessionDraftOpen:y}),[pe,y,we]),qe=Wa(ye||null),Pe=a.useMemo(()=>yb({activeProjectLabel:E,openDirectory:ye,homeDirectory:v}),[E,v,ye]),Ye=!!(Pe||qe),re=a.useMemo(()=>m?bs(ee):Pe??"PiChamber",[ee,m,Pe]),Le=ku(),nt=Te(F=>F.updateSessionTitle),at=Te(F=>F.archiveSessions),Ve=Te(F=>F.deleteSessions),[mt,lt]=a.useState(!1),[qt,Yt]=a.useState(!1),Ze=a.useRef(!1),[Ct,Vt]=a.useState(""),[kt,Ft]=a.useState(null),gt=a.useRef(null);a.useEffect(()=>{Ze.current=!1,Yt(!1),lt(!1),Vt(""),Ft(null)},[m]);const wt=a.useCallback(()=>{m&&(Vt(ee?.title?.trim()||re),lt(!0))},[ee?.title,m,re]),st=a.useCallback(async()=>{if(!m)return;const F=Ct.trim();F&&F!==ee?.title?.trim()&&await nt(m,F),lt(!1)},[ee?.title,m,Ct,nt]);a.useEffect(()=>{if(!mt)return;const F=oe=>{const be=oe.target;(!be||!gt.current?.contains(be))&&st()};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[mt,st]);const At=a.useCallback(()=>{m&&ys(m).then(F=>{ie[F.ok?"success":"error"](F.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[m]),ke=a.useCallback(async()=>{if(!m||!ye){ie.error("Nothing to export");return}try{await Le.syncSession(m)}catch{ie.error("Failed to load the complete session history");return}const F=[];if(F.length===0){ie.error("Nothing to export");return}const oe=Zl(F,ee?.title??null),be=sc(ee?.title??null);await tc(oe,be)||ec(oe,be),ie.success("Session exported")},[ee?.title,m,ye,Le]);h?.type==="busy"||h?.type;const He=a.useCallback(async()=>{if(!m||!kt)return;const F=Au(),oe=[m];for(let Xe=0;Xe<oe.length;Xe+=1){const hs=oe[Xe];for(const Bt of F)Bt.parentID===hs&&!oe.includes(Bt.id)&&oe.push(Bt.id)}const be=kt;if(Ft(null),(be==="archive"?await at(oe):await Ve(oe)).failedIds.length>0){ie.error(be==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(be==="archive"?"Session archived":"Session deleted")},[at,m,Ve,kt]),Ae=le(F=>F.isArchivePageOpen),Oe=a.useMemo(()=>Ae?{title:"Archive",subtitle:null}:null,[Ae]),Fe=a.useMemo(()=>vn(ye||S?.path||""),[S?.path,ye]),rt=a.useCallback(()=>{Fe&&ys(Fe).then(F=>{ie[F.ok?"success":"error"](F.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ie.error("Failed to copy working directory"))},[Fe]),vt=a.useMemo(()=>S?{id:S.id,path:S.path}:null,[S]),Nt=a.useRef(null);a.useEffect(()=>{!vt||!Fe||(Nt.current={projectRef:vt,directory:Fe})},[Fe,vt]);const bt=a.useMemo(()=>vt&&Fe?{projectRef:vt,directory:Fe}:Nt.current,[Fe,vt]),ct=a.useCallback(()=>{if(typeof document>"u")return;const F=document.activeElement;if(!F)return;const oe=F.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||F.isContentEditable)&&F.blur()},[]),tt=a.useCallback(()=>{if(j){ct(),c(!G);return}d()},[ct,j,G,c,d]),It=a.useCallback(()=>{In("desktop_open_draft_mini_chat_window",{directory:vn(ye||S?.path||""),projectId:S?.id??null,apiBaseUrl:ho(),clientToken:fo()}).catch(F=>{console.warn("[header] failed to open draft mini chat window",F)})},[S?.id,S?.path,ye]),Et=a.useCallback(()=>{if(y){It();return}m&&In("desktop_open_session_mini_chat_window",{sessionId:m,directory:vn(ye||S?.path||""),apiBaseUrl:ho(),clientToken:fo()}).catch(F=>{console.warn("[header] failed to open session mini chat window",F)})},[S?.path,m,It,y,ye]),os=ln,Qt=Uh,Jt=a.useMemo(()=>n?"sessions":C?r&&o?o:null:r?"git":f,[f,C,n,r,o]),xt=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&G&&c(!1)},[G,n,e,t,r,c]),Os=a.useCallback(()=>{e?.()},[e]),un=a.useCallback(()=>{t?.()},[t]),Bs=a.useMemo(()=>$&&I&&!D?"5.5rem":L?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!$||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[$,D,I,L,M]);Ee.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Bs)},[Bs]);const _s=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Lt=u?"0px":$&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":k?"2.75rem":"2.5rem";Ee.useEffect(()=>{if(!$||!I){R(!1);return}let F=!1;const oe=async()=>{try{const _e=await In("desktop_is_window_fullscreen");F||R(_e===!0)}catch{F||R(!1)}},be=()=>{oe()};return oe(),window.addEventListener("pichamber:window-resized",be),()=>{F=!0,window.removeEventListener("pichamber:window-resized",be)}},[$,I]);const fs=a.useMemo(()=>!$||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[$,I,W]),St=a.useMemo(()=>{if(!($&&!M))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[$,M]),is=a.useCallback(()=>{if(typeof document>"u")return;const F=O.current?.getBoundingClientRect().height;if(F){const oe=`${F}px`,be=document.documentElement.style;be.getPropertyValue("--oc-header-height")!==oe&&be.setProperty("--oc-header-height",oe)}},[]);Ee.useEffect(()=>{if(typeof window>"u")return;is();const F=O.current;if(!F||typeof ResizeObserver>"u")return()=>{};let oe=0;const be=()=>{oe||(oe=requestAnimationFrame(()=>{oe=0,is()}))},_e=new ResizeObserver(be);return _e.observe(F),window.addEventListener("resize",be),window.addEventListener("orientationchange",be),()=>{oe&&cancelAnimationFrame(oe),_e.disconnect(),window.removeEventListener("resize",be),window.removeEventListener("orientationchange",be)}},[is]),Ee.useEffect(()=>{is()},[is,j,fs]);const as=a.useCallback(async F=>{const oe=F.target;oe.closest(".app-region-no-drag")||oe.closest("button, a, input, select, textarea")||F.button===0&&$&&await Nu()},[$]),ot=a.useMemo(()=>j?[{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"}]:[],[j]),Ot=a.useCallback(F=>Ko(lr(F,x)),[x]);Ee.useEffect(()=>{!j&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,j,p]),Ee.useEffect(()=>{const F=oe=>{if(rf(oe)&&!oe.shiftKey&&!oe.altKey){const be=parseInt(oe.key,10);be>=1&&be<=ot.length&&(oe.preventDefault(),j&&(ct(),xt()),p(ot[be-1].id))}};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[ct,xt,j,p,ot]),Ee.useEffect(()=>{const F=oe=>{const be=lr("toggle_services_menu",x);if(of(oe,be)){oe.preventDefault(),B?xe(!1):(xe(!0),q());return}};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[x,B,q]);const js=F=>{const oe=f===F.id,be=F.icon==="diff",_e=be?null:F.icon,Je=F.id==="chat",Xe=Bt=>be?s.jsx(ga,{size:Bt}):_e?s.jsx(P,{name:_e,className:`h-${Bt/4} w-${Bt/4}`}):null,hs=s.jsxs("button",{type:"button",onClick:()=>p(F.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",oe?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",Je&&!j&&"min-w-[100px] justify-center"),"aria-label":F.label,"aria-selected":oe,role:"tab",children:[j?Xe(20):s.jsxs(s.Fragment,{children:[Xe(16),s.jsx("span",{className:"header-tab-label",children:F.label})]}),F.badge!==void 0&&F.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:F.badge})]});return s.jsx(a.Fragment,{children:hs},F.id)},Rt=s.jsxs(s.Fragment,{children:[s.jsx(jb,{directory:Fe,className:"mr-1"}),$?s.jsx(Gb,{isDesktopApp:$,currentInstanceLabel:V,compactCurrentInstanceLabel:Ge,currentInstanceIsLocal:Re,currentInstanceIcon:z,isDesktopServicesOpen:B,setIsDesktopServicesOpen:xe,refreshCurrentInstanceLabel:q,shortcutLabel:Ot,remoteUpdateInfo:ue,remoteUpdateChecking:Q,remoteUpdateError:ce,onOpenRemoteUpdate:ne}):s.jsx(Kb,{open:B,onOpenChange:xe}),s.jsx(Wb,{isMobile:j})]}),fn=K&&(y||!!m),zs=()=>s.jsxs("div",{onMouseDown:as,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",fs),style:St,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:_s}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Lt}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Oe?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:Oe.title}),Oe.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:Oe.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:os,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(Yb,{align:"start",children:s.jsx("button",{type:"button",className:os,"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:[mt?s.jsxs("form",{ref:gt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:F=>{F.preventDefault(),st()},children:[s.jsx("input",{value:Ct,onChange:F=>Vt(F.target.value),autoFocus:!0,onKeyDown:F=>{F.stopPropagation(),F.key==="Escape"&<(!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:()=>lt(!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":re}),Ye?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:[Pe?s.jsx("span",{className:"truncate",children:Pe}):null,qe?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:qe})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!y&&!mt?s.jsxs(Wt,{open:qt,onOpenChange:Yt,onOpenChangeComplete:F=>{!F&&Ze.current&&(Ze.current=!1,wt())},children:[s.jsx(Gt,{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(Ht,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ft,{onClick:()=>{Ze.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ft,{onClick:At,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ft,{onClick:rt,disabled:!Fe,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(en,{}),s.jsxs(ft,{onClick:()=>{ke()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(en,{}),s.jsxs(ft,{onClick:()=>Ft("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ft,{className:"text-destructive focus:text-destructive",onClick:()=>Ft("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),ot.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:ot.map(F=>js(F))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Al,{}),bt?s.jsx(ya,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,s.jsx($h,{visible:fn,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:Et,className:_(os,"mr-1"),Icon:"picture-in-picture-2"}),Rt,s.jsx(Iu,{visible:M})]})]})]}),hn=()=>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:_s}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Lt}})]}),!k&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:Os,className:_(Qt,Jt==="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"})}):G?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:tt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:s.jsx(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&G&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!G||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!C&&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:ot.map(F=>{const oe=f===F.id,be=F.icon==="diff",_e=be?null:F.icon;return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{j&&(ct(),xt()),p(F.id)},"aria-label":F.label,"aria-selected":oe,role:"tab",className:_(Qt,"relative rounded-lg",Jt===F.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[be?s.jsx(ga,{className:"h-5 w-5"}):_e?s.jsx(P,{name:_e,className:"h-5 w-5"}):null,F.badge!==void 0&&F.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:F.badge}),F.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(Ke,{children:s.jsx("p",{children:F.label})})]},F.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[C&&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:w.map(F=>{const oe=r&&o===F.id;return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{j&&(ct(),xt()),T(!1),i?.(F.id)},"aria-label":F.label,"aria-selected":oe,role:"tab",className:_(Qt,"relative h-11 w-11 rounded-lg",oe&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:F.icon,className:"h-5 w-5"})})}),s.jsx(Ke,{children:s.jsx("p",{children:F.label})})]},F.id)})}),s.jsx(zh,{open:N,onOpenChange:T,currentSessionId:m,effectiveDirectory:ye||null,isNewSessionDraftOpen:y})]}),bt&&s.jsx(ya,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!C?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:un,className:_(Qt,"relative",Jt==="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(Ke,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),de=_("header-safe-area relative z-10 bg-background",j&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:O,className:de,style:{"--padding-scale":"1"},children:j?hn():zs()}),s.jsx(Hb,{action:kt,onClose:()=>Ft(null),sessionTitle:re,onConfirm:()=>{He()}}),s.jsx(bl,{open:X,onOpenChange:te,info:ue,downloading:!1,downloaded:!1,progress:null,error:ce,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},wa="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",Vb="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",hy=()=>{const e=le(y=>y.isSidebarOpen),t=le(y=>y.toggleSidebar),n=le(y=>y.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Ko(lr("toggle_sidebar",n)),l=qa(),{enabled:c}=$o(),d=!e,u=l,f=d||u,p=u,x=a.useCallback(()=>{In("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=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},m=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!p)return;const h=o.current,b=r.current;if(!h||!b){y(0),m(0);return}const g=()=>{const v=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(v),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(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(wa,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?Vb:wa,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},va=200,Qb="cubic-bezier(0.22, 1, 0.36, 1)",my=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),va);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${va}ms ${Qb}`}},py=()=>{tl()},gy=e=>{Te.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ge.getState().clearAll(),tl(),sn.getState().resetForRuntimeSwitch(),Eu.getState().resetForRuntimeSwitch(),Ru.getState().resetForRuntimeSwitch(),Du(),af(),lf(),Lu(),Pu.getState().resetForRuntimeSwitch(),$t.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ut.getState().resetForRuntimeSwitch(),Mu(),Tu(),Cf.getState().reset(),cf.getState().resetForRuntimeSwitch(),Ba.getState().resetForRuntimeSwitch(e.runtimeKey),lo.getState().resetForRuntimeSwitch(e.runtimeKey),df(),Ps.getState().resetForRuntimeSwitch(e.runtimeKey),Fu.getState().resetForRuntimeSwitch(),ss.getState().resetForRuntimeSwitch(),pt.getState().resetForRuntimeSwitch(e.runtimeKey),uf.getState().resetForRuntimeSwitch(e.runtimeKey),Te.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=le.getState();bo({sessionId:Te.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Gx as $,_x as A,Ar as B,Bx as C,la as D,Rs as E,bx as F,ql as G,fy as H,Th as I,Fh as J,Oi as K,uy as L,kl as M,$f as N,mx as O,Cs as P,xs as Q,ss as R,ny as S,ay as T,Hl as U,Fl as V,hx as W,Ln as X,Tl as Y,xx as Z,vl as _,zh as a,dx as a$,zx as a0,Hx as a1,ty as a2,sy as a3,Mh as a4,Vx as a5,qx as a6,$x as a7,Yx as a8,Jx as a9,xl as aA,dh as aB,Bn as aC,_n as aD,vx as aE,uh as aF,yl as aG,Ix as aH,En as aI,yx as aJ,oh as aK,ih as aL,Ex as aM,Fx as aN,Mx as aO,Tx as aP,Lx as aQ,Dx as aR,Sx as aS,jx as aT,Cx as aU,Px as aV,Ch as aW,Ax as aX,Wf as aY,ah as aZ,Gf as a_,Xx as aa,Zx as ab,ey as ac,Qx as ad,Io as ae,Vi as af,ks as ag,wn as ah,dn as ai,Vm as aj,cn as ak,Kx as al,Sr as am,Wx as an,Ux as ao,ch as ap,Rx as aq,rh as ar,wx as as,Ox as at,Nx as au,bl as av,Ho as aw,kx as ax,lh as ay,Eh as az,jn as b,jg as c,ry as d,or as e,pb as f,oy as g,Yg as h,Ag as i,ly as j,ac as k,my as l,dy as m,hy as n,py as o,gy as p,px as q,cy as r,iy as s,gx as t,Bh as u,fx as v,cx as w,ux as x,Cr as y,kr as z};
|