@pi-chamber/web 1.0.6-rc.6 → 1.0.7-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/assets/{DiagramView-BxBfOrN5.js → DiagramView-DyF8zzYx.js} +1 -1
  2. package/dist/assets/{DiffView-CSC9GMrb.js → DiffView-C3rA5DfE.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-C_MNWp6w.js → FileSaveConflictDialog-CC4F--8H.js} +1 -1
  4. package/dist/assets/{FilesView-DeN6KmNt.js → FilesView-Dsg-QTJu.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-CrtJwlqV.js → GitHubDetailScaffold-C9WuBMGr.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-g6w8K95J.js → GitHubLinkPicker-BkVdYxZT.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-lAi2ywE3.js → GitHubListPrimitives-CcVlv_rJ.js} +1 -1
  8. package/dist/assets/{GitView-D9_em8Vx.js → GitView-OpFCss_4.js} +3 -3
  9. package/dist/assets/{IssuesSurface-DCiHe6TE.js → IssuesSurface-DD6Gz5Ox.js} +2 -2
  10. package/dist/assets/{JsonTreeView-D64mTfTx.js → JsonTreeView-Dj75jgH6.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-DwE90rTA.js → MarkdownRendererImpl-CnIzmT1p.js} +1 -1
  12. package/dist/assets/{PatchDiff-CcIwURzW.js → PatchDiff-DND5RBnF.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-tN7awL0-.js → PierreDiffViewer-Cq5CIrmH.js} +1 -1
  14. package/dist/assets/{PullRequestsSurface-iX4r3QlS.js → PullRequestsSurface-g8HAvbFg.js} +2 -2
  15. package/dist/assets/{SessionSwitcherContent-DrrM0ObM.js → SessionSwitcherContent-CUz6Cc1-.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-B9_0JwY7.js → SessionSwitcherDropdown-COZ50Y5a.js} +2 -2
  17. package/dist/assets/{SessionUnreadDot-Bpgp2gLO.js → SessionUnreadDot-DOUcgBw6.js} +1 -1
  18. package/dist/assets/{SettingsView-C4hec1iy.js → SettingsView-AFymxZYC.js} +3 -3
  19. package/dist/assets/{SettingsWindow-Bepcpy0R.js → SettingsWindow-J6YOvGcV.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-Dl9-vpvL.js → ToolOutputDialog-5Tc7HM4z.js} +1 -1
  21. package/dist/assets/{ToolPartDiffPreview-CLlHEPYD.js → ToolPartDiffPreview-7GiFbVl7.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-D9OpUpR3.js → VirtualizedFileDiff-Dq8pyTGy.js} +1 -1
  23. package/dist/assets/{collapsible-ZT74WYMA.js → collapsible-D6qdoq7-.js} +1 -1
  24. package/dist/assets/{computeVirtualFileMetrics-CDv_UBXL.js → computeVirtualFileMetrics-uXZ9uhI_.js} +1 -1
  25. package/dist/assets/{contextFileOpenGuard-BJ2sAhZG.js → contextFileOpenGuard-CckKFYjI.js} +1 -1
  26. package/dist/assets/{fileTreeStatus-B2PDFobt.js → fileTreeStatus-C_7jbeGv.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-BDdOjxH_.js → gitStatusPredicates-CNLvdt2V.js} +1 -1
  28. package/dist/assets/{githubLink-wwC2_C_9.js → githubLink-0EoMGZKd.js} +1 -1
  29. package/dist/assets/{index-MXKT8Ir9.js → index-DD0xW5WE.js} +1 -1
  30. package/dist/assets/{index-fmzQmSSv.js → index-I2QYqABE.js} +3 -3
  31. package/dist/assets/{main-CnW7qm2b.js → main-BnWf2tm9.js} +2 -2
  32. package/dist/assets/{main-DmHVgAh0.js → main-yQe-k30g.js} +4 -4
  33. package/dist/assets/{markdownCore-DOFhfL5i.js → markdownCore-C-Ulh4n9.js} +1 -1
  34. package/dist/assets/{miniChat-D_Wl2jlx.js → miniChat-DKK1hotU.js} +2 -2
  35. package/dist/assets/{mobile-Cl-KcfGW.js → mobile-BuAWpKj9.js} +2 -2
  36. package/dist/assets/{nativeFileSave-B4Rg6n8u.js → nativeFileSave-Cp9i5QGd.js} +1 -1
  37. package/dist/assets/{pi-session-focus-preference-BqEU9Iq6.js → pi-session-focus-preference-DaWQ2rEE.js} +1 -1
  38. package/dist/assets/{renderDiffWithHighlighter-U7WjeGm9.js → renderDiffWithHighlighter-DD-iWWus.js} +1 -1
  39. package/dist/assets/{renderElectronMiniChatApp-BJxNc9OP.js → renderElectronMiniChatApp-CKuFQBRo.js} +2 -2
  40. package/dist/assets/{renderFileWithHighlighter-DiwpFgMp.js → renderFileWithHighlighter-B0pofdV1.js} +1 -1
  41. package/dist/assets/{renderMobileApp-d5KpyvBc.js → renderMobileApp-B3P_bita.js} +3 -3
  42. package/dist/assets/runtimeEndpointReset-DutinXZK.js +62 -0
  43. package/dist/assets/{runtimeSurface-X62LLBLv.js → runtimeSurface-CFwnvks_.js} +1 -1
  44. package/dist/assets/{useAppFontEffects-FKnY7Fe2.js → useAppFontEffects-DQlUEhzN.js} +85 -87
  45. package/dist/assets/{useGitHubRemoteSearch-4QMXIODG.js → useGitHubRemoteSearch-BoZvJAk3.js} +1 -1
  46. package/dist/assets/{useSwitcherItems-DtCNsq8u.js → useSwitcherItems-Dy2yumiU.js} +1 -1
  47. package/dist/assets/{web-components-D5QImbWv.js → web-components-DB-GDG7P.js} +1 -1
  48. package/dist/index.html +3 -3
  49. package/dist/mini-chat.html +2 -2
  50. package/dist/mobile.html +2 -2
  51. package/package.json +1 -1
  52. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -3
  53. package/server/lib/pi/session-daemon/extension-custom-host.js +37 -4
  54. package/server/lib/pi/session-daemon/extension-custom-host.test.js +231 -2
  55. package/server/lib/pi/session-daemon/session-daemon-list-live.test.js +115 -1
  56. package/server/lib/pi/session-daemon/session-daemon.js +52 -12
  57. package/server/lib/pi/session-daemon/session-engine-router.js +5 -1
  58. package/server/lib/pi/session-daemon/session-engine-router.test.js +21 -0
  59. package/dist/assets/runtimeEndpointReset-Cd4yJDsk.js +0 -62
@@ -1,62 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-MXKT8Ir9.js","assets/useAppFontEffects-FKnY7Fe2.js","assets/index-fmzQmSSv.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-BaLCg7tL.css","assets/vendor-boot-3SaHYVb1.js","assets/runtimeSurface-X62LLBLv.js","assets/nativeFileSave-B4Rg6n8u.js","assets/computeVirtualFileMetrics-CDv_UBXL.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/renderFileWithHighlighter-DiwpFgMp.js","assets/renderDiffWithHighlighter-U7WjeGm9.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-BbiDqlyL.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/vendor-capacitor-keyboard-CgrHt8iN.js","assets/SessionSwitcherDropdown-B9_0JwY7.js"])))=>i.map(i=>d[i]);
2
- import{_ as ht}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as n,aS as Ju,aT as Xu,aU as Zu,aV as ed,aW as td,aX as nd,aY as sd,aZ as Or,a_ as cs,a$ as Za,b0 as Br,b1 as pi,b2 as el,b3 as rd,b4 as tl,b5 as nl,b6 as sl,b7 as Io,b8 as Eo,b9 as Do,ba as rl,bb as ol,bc as il,bd as al,be as ll,bf as cl,bg as mi,bh as gi,bi as od,bj as id,bk as ad,bl as Ro,aP as ld}from"./vendor-boot-3SaHYVb1.js";import{a as Te,R as l}from"./vendor-react-Bz1tRBxM.js";import{aq as ss,ar as cd,a as ct,h as Fe,t as oe,as as ps,I as D,at as Gs,au as Os,av as en,aw as tn,ax as mn,ay as Cn,B as Ae,az as Hs,v as dn,aA as ud,aB as zn,aC as ms,aD as Bn,aE as dd,g as ts,aF as no,aG as Ki,aH as Wi,aI as Bs,e as xr,aJ as fd,aK as hd,aL as pd,aM as md,aN as gd,aO as bd,o as ul,aP as Mn,aQ as Gi,ah as fn,aR as Ke,aS as We,aT as Ge,aU as xd,aV as yd,aW as wd,aX as vd,aY as Sd,aZ as Po,a_ as jd,a$ as Gt,b0 as Ht,b1 as qt,b2 as To,O as Kt,b3 as kd,b4 as Cd,b5 as Ad,b6 as Nd,b7 as Id,b8 as Ed,b9 as Mo,r as _s,G as bi,ba as Dd,bb as Rd,bc as dl,bd as fl,Z as jn,be as Pd,bf as Td,bg as Md,bh as Fd,d as hl,b as qs,bi as Zs,z as Un,bj as pl,bk as _r,bl as Hi,bm as ml,bn as gt,bo as Ld,bp as Od,bq as gl,br as Fo,bs as bl,bt as xl,bu as xi,bv as ut,bw as Bd,bx as _d,by as zd,bz as Ys,bA as Ud,bB as $d,bC as Kd,bD as Wd,bE as Lo,bF as Gd,i as yl,p as Hd,j as qd,u as wl,k as Yd,m as Vd,bG as vl,n as Qd,bH as Jd,q as qi,bI as Xd,bJ as Jn,c as Zd,bK as ef,bL as tf,bM as nf,bN as Oo,bO as sf,bP as rf,bQ as of,bR as af,bS as lf,a4 as cf,bT as us,bU as Sl,M as uf,y as df,bV as ff,w as hf,bW as pf,bX as mf,bY as jl,bZ as gf,aj as bf,b_ as xf,b$ as yf,c0 as wf,c1 as vf,c2 as Sf,c3 as jf,c4 as kf,c5 as Cf,c6 as Af,c7 as Nf}from"./useAppFontEffects-FKnY7Fe2.js";import{A as Yi,f as _,B as If,h as de,z as tt,a as ds,C as kl,D as Cl,E as Ef,F as Df,u as fs,G as Rf,H as Pf,I as Tf,J as Mf,K as Ze,b as Tt,p as gs,L as Ff,M as Lf,N as Of,O as Bf,n as De,P as Vi,Q as Wt,R as Bo,T as Qi,U as _o,V as Al,j as hn,W as yi,X as Ar,e as rs,Y as _f,v as Nl,Z as zf,_ as Il,$ as Uf,a0 as El,a1 as zs,a2 as zo,k as Uo,a3 as $f,a4 as Kf,a5 as Wf,a6 as Ji,a7 as Is,a8 as so,a9 as $o,aa as Nr,ab as Fn,ac as Xi,ad as Ko,ae as Dl,af as Wo,ag as Gf,ah as Hf,ai as qf,aj as Yf,ak as Vf,al as Qf,am as Jf,an as Xf,ao as Zf,ap as Rl,aq as eh,ar as th,as as nh,at as sh,au as rh}from"./index-fmzQmSSv.js";import{b as oh,d as Pl,s as yr,c as Tl,e as _n,g as hs,h as ih,i as ah,j as lh,k as ch,l as er,f as uh,a as Zi,S as dh,t as fh,m as hh}from"./SessionUnreadDot-Bpgp2gLO.js";import{c as $n,d as zr,p as Ml,a as ph}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{saveOrShareFile as mh}from"./nativeFileSave-B4Rg6n8u.js";import{usePermissionStore as gh}from"./permissionStore-zIpxq9Pq.js";const bh="chat";function Fl(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(ss.SESSION,e.sessionId),e.isSettingsOpen){const s=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(ss.SETTINGS,s),t}return e.tab!==bh&&t.set(ss.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(ss.FILE,e.diffFile),t}function xh(e,t){const s=typeof window<"u"?window.location.pathname:"/",r=s.startsWith("/session")||s.startsWith("/s/")?"/":s,o=e.toString();return o?`${r}?${o}`:r}function yh(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),s=Fl(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(ss.SESSION)&&t.set(ss.SESSION,o);const i=[...t.entries()].sort((c,u)=>c[0].localeCompare(u[0])),a=[...s.entries()].sort((c,u)=>c[0].localeCompare(u[0]));if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==a[c][0]||i[c][1]!==a[c][1])return!1;return!0}catch{return!0}}function Go(e,t={}){if(!(typeof window>"u")&&!(!t.force&&yh(e)))try{const s=Fl(e),r=xh(s);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const wh=["typescript","javascript","tsx","jsx","json","markdown"],Ll={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ea=null;const Ol=()=>(ea??=Promise.all([ht(()=>import("./index-MXKT8Ir9.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42])),ht(()=>import("./workerFactory-DlGfNFqf.js"),[]),ht(()=>import("./appThemeRegistry-Ca8eGRB9.js"),__vite__mapDeps([43,44,30,31,5,15,16,17,18,19,20,21,22,23,24,25,26,27,28]))]).then(([e,t,s])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:s.ensurePierreThemeRegistered})),ea),Vs={},ta=new Set,Ho=new Set;let wr={light:"pierre-light",dark:"pierre-dark"};const vh=()=>{for(const e of Ho)e()},Bl=(e,t)=>{t.setRenderOptions({theme:wr,lineDiffType:Ll[e].lineDiffType})},qo=e=>{typeof window>"u"||ta.has(e)||(ta.add(e),Ol().then(t=>{if(Vs[e])return;const s=Ll[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:s.poolSize,totalASTLRUCacheSize:s.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:wh,lineDiffType:s.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Vs[e]=r,Bl(e,r),vh()}))},Sh=e=>(Ho.add(e),()=>Ho.delete(e)),jh=e=>{if(!(wr.light===e.light&&wr.dark===e.dark)){wr=e;for(const t of Object.keys(Vs)){const s=Vs[t];s&&Bl(t,s)}}},Ly=({children:e})=>{const t=cd(),s=Yi(!1),r=Yi(!0),o=t?.lightThemeId??s.metadata.id,i=t?.darkThemeId??r.metadata.id,a=t?.availableThemes.find(u=>u.metadata.id===o)??s,c=t?.availableThemes.find(u=>u.metadata.id===i)??r;return Te.useEffect(()=>{let u=!1;return Ol().then(d=>{u||(d.ensurePierreThemeRegistered(a),d.ensurePierreThemeRegistered(c),jh({light:a.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,a]),Te.useEffect(()=>{if(typeof window>"u")return;const u=()=>{qo("unified"),qo("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(u,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const d=window.setTimeout(u,2e3);return()=>window.clearTimeout(d)},[]),n.jsx(n.Fragment,{children:e})},Oy=(e="unified")=>{const t=Te.useSyncExternalStore(Sh,()=>Vs[e],()=>{});return Te.useEffect(()=>{qo(e)},[e]),t},kh=e=>{const t=e.trim();return t&&(t.split(/[?#]/,1)[0]||t).match(/([^/:]+?)(?:\.git)?\/?$/)?.[1]?.trim()||""},Ch=e=>{const t=e.trim();return t?/[/\\]/.test(t)?"A name can’t contain / or \\.":t==="."||t===".."?"Choose a different name.":null:"Enter a name for the folder."},na=(e,t)=>e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t,Yo=({children:e,className:t})=>n.jsx("kbd",{className:_("inline-flex h-4 min-w-4 normal-case items-center justify-center rounded border border-border bg-[var(--surface-muted)] px-1 font-sans typography-micro text-muted-foreground",t),children:e}),Ah=({hints:e})=>n.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",children:e.map(t=>{const s=n.jsxs(n.Fragment,{children:[t.keys.map(r=>n.jsx(Yo,{children:r},r)),n.jsx("span",{children:t.label})]});return t.onSelect?n.jsx("button",{type:"button",onClick:t.onSelect,className:"-mx-1 flex items-center gap-1 rounded px-1 transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s},t.label):n.jsx("span",{className:"flex items-center gap-1",children:s},t.label)})}),_l=l.forwardRef(({id:e,active:t,onSelect:s,onHover:r,ariaLabel:o,ariaChecked:i,className:a,quiet:c=!1,children:u},d)=>n.jsx("div",{ref:d,id:e,role:"option","aria-selected":t,"aria-checked":i,"aria-label":o,onMouseMove:t?void 0:r,onMouseDown:f=>f.preventDefault(),onClick:s,className:_("flex w-full cursor-pointer select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left typography-ui-label text-foreground",t&&(c?"group-focus-within/palette:bg-interactive-hover":"group-focus-within/palette:bg-interactive-selection group-focus-within/palette:text-interactive-selection-foreground"),!t&&"hover:bg-interactive-hover/60",a),children:u}));_l.displayName="PaletteRow";const Nh=e=>e==="/",kn=e=>e.replace(/\\/g,"/"),pn=e=>{if(!e||Nh(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},is=e=>e.endsWith("/"),Us=e=>{const t=e.trim();return!t||is(t)?t:`${t}/`},wi=e=>e.lastIndexOf("/"),Ih=e=>{if(is(e))return e;const t=wi(e);return t<0?e:e.slice(0,t+1)},Eh=e=>{const t=wi(e);return e.slice(t+1)},zl=e=>{const t=pn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const s=wi(t);return s<0?null:t.startsWith("~/")&&s<=1?"~/":s===0?"/":`${t.slice(0,s)}/`},Dh=e=>is(e)&&zl(e)!==null,vr=e=>{if(!e)return null;const t=pn(kn(e.trim()));return t?t.toLowerCase():null},ro=(e,t)=>{const s=e.trim();return s==="~"?t:s.startsWith("~/")?`${t}${s.slice(1)}`:s},Rh=(e,t)=>{const s=pn(kn(e.trim())),r=pn(kn(t.trim()));if(!s)return"";if(!r)return Us(s);if(s.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return s.toLowerCase().startsWith(o.toLowerCase())?`~/${s.slice(r.length+1)}/`:Us(s)},Ul=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),Ph=e=>Ul()?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Th=()=>Ul()?"⌘":"Ctrl",Mh=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Fh=async()=>If({fresh:!0}),lr=async(e,t)=>{try{const s=await e.json();if(typeof s.error=="string"&&s.error.trim())return s.error.trim()}catch{}return t},oo=(e,t,s)=>tt(e,{method:"POST",headers:{"Content-Type":"application/json"},query:s,body:JSON.stringify(t)});function Lh({open:e,onClose:t,isMobile:s}){const r=ct(y=>y.addProject),o=de(y=>y.setActiveMainTab),i=de(y=>y.setSessionSwitcherOpen),a=Fe(y=>y.openNewSessionDraft),[c,u]=l.useState(null),[d,f]=l.useState(null);l.useEffect(()=>{e&&(u(null),f(null))},[e]);const m=l.useCallback(y=>{const v=r(y);return v?(o("chat"),s&&i(!1),a({selectedProjectId:v.id,directoryOverride:v.path}),t(),!0):(f("PiChamber couldn’t add this folder. Check that the path is a folder."),!1)},[r,s,t,a,o,i]),b=l.useCallback(async(y,v)=>{if(!c){u(y),f(null);try{await v()}catch(x){f(x instanceof Error&&x.message?x.message:"Something went wrong. Try again.")}finally{u(null)}}},[c]),g=l.useCallback((y,v)=>b("add",async()=>{if(v.create){const x=await oo("/api/fs/mkdir",{path:y},{directory:v.location});if(!x.ok)throw new Error(await lr(x,"Couldn’t create the folder."))}m(y)}),[m,b]),h=l.useCallback((y,v)=>b("clone",async()=>{const x=await oo("/api/fs/clone",{remoteUrl:y.trim(),destinationPath:`${pn(v)}/`});if(!x.ok){const j=(await lr(x,"The clone failed.")).replace(/^Cloning into '[^']*'\.\.\.\s*/,"").replace(/^fatal:\s*/,"");throw new Error(j.charAt(0).toUpperCase()+j.slice(1))}const A=await x.json();if(typeof A.path!="string"||!A.path)throw new Error("The clone finished, but the server didn’t say where. Add the folder from Folder on this server.");m(A.path)}),[m,b]),p=l.useCallback((y,v,x)=>b("create",async()=>{const A=`${pn(y)}/${v.trim()}`,j=await oo("/api/fs/mkdir",{path:A},{directory:y});if(!j.ok)throw new Error(await lr(j,"Couldn’t create the folder."));if(x){const k=await tt("/api/git/init",{method:"POST",query:{directory:A}});if(!k.ok){const w=await lr(k,"git init failed.");throw new Error(`The folder was created, but git init failed: ${w}`)}}m(A)}),[m,b]),S=l.useCallback(()=>f(null),[]);return{pending:c,error:d,clearError:S,addFolder:g,cloneRepository:h,createProject:p}}const Oh=()=>{const[e,t]=Te.useState(!1),[s,r]=Te.useState(!1);Te.useEffect(()=>{t(ds()),r(kl())},[]);const o=Te.useCallback(async c=>e?await Cl(c):{success:!0,path:c},[e]),i=Te.useCallback(async c=>e?await Ef():{success:!0},[e]),a=Te.useCallback(async c=>e?await Df():{success:!0},[e]);return{isDesktop:e,canRequestAccess:s,requestAccess:o,startAccessing:i,stopAccessing:a}},io=async(e,t)=>{try{const r=(await Pf(t)).filter(o=>o.isDirectory).map(o=>({name:o.name,path:kn(o.path)})).sort((o,i)=>o.name.localeCompare(i.name));return{displayDir:e,absoluteDir:t,entries:r,error:null}}catch(s){return{displayDir:e,absoluteDir:t,entries:[],error:Tf(s)?s.reason:"unknown"}}},Bh=250;function _h({open:e,addedProjectPaths:t}){const s=fs(K=>K.homeDirectory),{canRequestAccess:r,startAccessing:o}=Oh(),[i,a]=l.useState(""),[c,u]=l.useState("~/"),[d,f]=l.useState(null),[m,b]=l.useState(!1),[g,h]=l.useState(!1),[p,S]=l.useState(!1),y=l.useRef(0),v=i||s;l.useEffect(()=>{if(!e)return;y.current+=1,u("~/"),f(null),h(!1),S(!1);let K=!1;return(async()=>{const ae=await Fh();K||a(ae||s||"")})(),()=>{K=!0}},[s,e]);const x=l.useMemo(()=>Ih(c),[c]),A=l.useMemo(()=>is(c)?"":Eh(c),[c]),j=l.useMemo(()=>v?ro(x,v):"",[x,v]),k=!!(d&&d.displayDir===x&&d.absoluteDir===j);l.useEffect(()=>{if(!e||!j||k)return;const K=++y.current;io(x,j).then(O=>{K===y.current&&f(O)})},[j,x,k,e]),l.useEffect(()=>{if(k||!j){b(!1);return}const K=window.setTimeout(()=>b(!0),Bh);return()=>window.clearTimeout(K)},[j,k]);const w=l.useCallback(async K=>{const O=Us(K);if(!v)return u(O),!0;const ae=++y.current,X=await io(O,ro(O,v));return ae!==y.current?!1:(f(X),u(O),!0)},[v]),C=l.useCallback(()=>{if(!j)return;const K=++y.current;io(x,j).then(O=>{K===y.current&&f(O)})},[j,x]),R=l.useMemo(()=>k?A:!d||!c.startsWith(d.displayDir)?"":c.slice(d.displayDir.length).split("/")[0]??"",[A,k,d,c]),L=l.useMemo(()=>{if(!d)return[];const K=R.toLowerCase(),O=p||R.startsWith(".");return d.entries.filter(ae=>ae.name.toLowerCase().startsWith(K)&&(O||!ae.name.startsWith(".")))},[R,d,p]),U=l.useMemo(()=>{if(!d||d.error)return[];const K=[],O=Dh(d.displayDir)?zl(d.displayDir):null;if(O){const ae=vr(d.absoluteDir);K.push({type:"parent",value:"browse:up",name:"..",path:d.absoluteDir,target:O,alreadyAdded:!!(ae&&t.has(ae))})}for(const ae of L){const X=vr(ae.path);K.push({type:"directory",value:`browse:${ae.path}`,name:ae.name,path:ae.path,target:`${Us(d.displayDir)}${ae.name}/`,alreadyAdded:!!(X&&t.has(X))})}return K},[t,L,d]),G=k?d?.error??null:null,$=l.useMemo(()=>k&&d?d.entries:[],[k,d]),q=l.useMemo(()=>v?pn(ro(c,v)):"",[v,c]),F=vr(q),E=!!(F&&t.has(F)),T=l.useMemo(()=>A?$.find(K=>K.name===A)??null:null,[A,$]),I=!!(k&&q&&!E&&(G===null||G==="not-found")&&(is(c)&&G==="not-found"||!is(c)&&A.trim().length>0&&T===null)),M=l.useCallback(async K=>{const O=await o(K);if(!O.success)return oe.error("Failed to open directory",{description:O.error||"Desktop could not grant file access."}),!1;const ae=v?Rh(K,v):Us(kn(K));return await w(ae),!0},[v,w,o]),W=l.useCallback(async()=>{if(!g){h(!0);try{if(kl()){const O=await Cl(q);if(!O.success||!O.path){O.error&&O.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:O.error});return}await M(O.path);return}const K=await Rf(q);if(K.status==="cancelled")return;if(K.status!=="picked"){oe.error("Couldn't open a folder picker",{description:K.error});return}await M(K.path)}catch(K){oe.error("Failed to select directory",{description:K instanceof Error?K.message:"Unknown error occurred."})}finally{h(!1)}}},[M,g,q]);return{query:c,setQuery:u,isSettled:k,showLoading:m,browseErrorReason:G,reload:C,isPickingLocation:g,showHidden:p,setShowHidden:S,explorerRootDirectory:v,browseDirectoryDisplayPath:x,browseDirectoryAbsolutePath:j,browseFilterQuery:A,entries:$,rows:U,targetPath:q,isAlreadyAdded:E,shouldCreateTarget:I,canRequestAccess:r,navigate:w,handleBrowseLocation:W}}const zh={folder:"source","clone-url":"source","clone-location":"clone-url","new-name":"source","new-location":"new-name"},zt=e=>e==="folder"||e==="clone-location"||e==="new-location",Uh=[{step:"folder",icon:"folder-6",title:"Folder on this server",description:"Pick a folder that’s already here."},{step:"clone-url",icon:"download-cloud",title:"Clone a repository",description:"Copy a Git repository from a URL."},{step:"new-name",icon:"folder-add",title:"New project",description:"Start an empty folder, with Git if you want it."}],$h={folder:"Open folder","clone-url":"Clone","clone-location":"Clone","new-name":"New project","new-location":"New project"},Kh={source:"Choose where the project comes from, type a folder path, or paste a Git URL.",folder:"Pick a folder on this server or type its path.","clone-url":"Paste the URL of the repository to clone.","clone-location":"Pick the folder the repository is cloned into.","new-name":"Name the new project.","new-location":"Pick the folder the new project goes in."},Wh={source:"Filter sources, type a folder path, or paste a Git URL",folder:"Folder path","clone-url":"Repository URL","clone-location":"Location","new-name":"Project name","new-location":"Location"},Gh={source:"Choose a source, type a path, or paste a Git URL",folder:"~/","clone-url":"https://github.com/owner/repo.git","clone-location":"~/","new-name":"Project name","new-location":"~/"},Hh=e=>/^(~|\/|[a-zA-Z]:[\\/])/.test(e),qh=e=>/^(https?:\/\/|ssh:\/\/|git:\/\/|git@)/i.test(e)||/^[\w.-]+@[\w.-]+:/.test(e),Yh=e=>pn(kn(e)).split("/").pop()??"",Vh=({open:e,onOpenChange:t})=>{const s=ct(z=>z.projects),{isMobile:r,isTablet:o}=ps(),i=r||o,[a,c]=l.useState("source"),[u,d]=l.useState(""),[f,m]=l.useState(""),[b,g]=l.useState(""),[h,p]=l.useState(!0),[S,y]=l.useState(null),v=l.useRef(null),x=l.useRef(new Map),A=l.useId(),j=l.useMemo(()=>new Set(s.map(z=>vr(z.path)).filter(z=>!!z)),[s]),k=l.useCallback(()=>t(!1),[t]),w=_h({open:e,addedProjectPaths:j}),{pending:C,error:R,clearError:L,addFolder:U,cloneRepository:G,createProject:$}=Lh({open:e,onClose:k,isMobile:r});l.useEffect(()=>{e&&(c("source"),d(""),m(""),g(""),p(!0),y(null))},[e]),l.useEffect(()=>{L()},[w.query,L,b,f,a]),l.useLayoutEffect(()=>{e&&(i&&a!=="clone-url"&&a!=="new-name"||Mh(v.current))},[i,e,a]);const q=l.useCallback(z=>{c(z),y(null)},[]),F=l.useCallback(()=>{C||a==="source"||q(zh[a])},[q,C,a]),{navigate:E}=w,T=l.useCallback(z=>{const pe=z.type==="parent"?`dir:${Yh(z.path)}`:null;E(z.target).then(ne=>{ne&&y(pe)})},[E]),I=l.useMemo(()=>new Set(w.entries.map(z=>z.name)),[w.entries]),M=w.browseDirectoryDisplayPath,W=w.browseErrorReason==="not-found"?"This folder doesn’t exist. Pick a location that does.":w.browseErrorReason?"PiChamber can’t read this location.":null,K=!w.isSettled||w.isPickingLocation,O=kh(f),ae=b.trim(),X=Ch(ae);let ue=!1,Ie="",V="",P=null;if(a==="folder"){V="Adding…";const z=pn(w.query.trim())||w.query.trim();if(w.isAlreadyAdded)Ie="Added",z&&(P={tone:"outcome",text:"Already added:",path:z});else{Ie=w.shouldCreateTarget?"Create and add":"Add";const pe=w.browseErrorReason&&w.browseErrorReason!=="not-found";ue=!!w.targetPath&&!pe&&!K,z&&!pe&&(P={tone:"outcome",text:w.shouldCreateTarget?"Creates and adds":"Adds",path:z})}}else if(a==="clone-location"){Ie="Clone",V="Cloning…";const z=na(M,O);W?P={tone:"problem",text:W}:I.has(O)?P={tone:"problem",text:"Already exists:",path:z}:(P={tone:"outcome",text:"Clones into",path:z},ue=!!O&&!K)}else if(a==="new-location"){Ie="Create",V="Creating…";const z=na(M,ae);W?P={tone:"problem",text:W}:X?P={tone:"problem",text:X,path:z}:I.has(ae)?P={tone:"problem",text:"Already exists:",path:z}:(P={tone:"outcome",text:"Creates",path:z},ue=!K)}ue=ue&&C===null;const H=()=>{ue&&(a==="folder"?U(w.targetPath,{create:w.shouldCreateTarget,location:w.browseDirectoryAbsolutePath}):a==="clone-location"?G(f,w.browseDirectoryAbsolutePath):a==="new-location"&&$(w.browseDirectoryAbsolutePath,ae,h))},Q=a==="clone-url"?!!O:a==="new-name"?!!ae&&!X:!1,re=()=>{Q&&q(a==="clone-url"?"clone-location":"new-location")},ie=[];if(a==="source"){const z=u.trim().toLowerCase();for(const pe of Uh)z&&!`${pe.title} ${pe.description}`.toLowerCase().includes(z)||ie.push({key:`source:${pe.step}`,kind:"source",select:()=>q(pe.step),content:n.jsxs(n.Fragment,{children:[n.jsx(D,{name:pe.icon,className:"size-4 shrink-0 text-muted-foreground"}),n.jsxs("span",{className:"flex min-w-0 flex-1 flex-col py-0.5",children:[n.jsx("span",{className:"truncate",children:pe.title}),n.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:pe.description})]})]})})}else if(zt(a)){a==="new-location"&&ie.push({key:"toggle:git",kind:"toggle",select:()=>p(z=>!z),ariaChecked:h,ariaLabel:"Initialize a Git repository",content:n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"pointer-events-none flex size-4 shrink-0 items-center justify-center",children:n.jsx(Gs,{checked:h,onChange:p})}),n.jsx("span",{className:"flex-1 truncate",children:"Initialize a Git repository"})]})});for(const z of w.rows){const pe=z.type==="parent";ie.push({key:pe?"browse:up":`dir:${z.name}`,kind:pe?"parent":"directory",select:()=>T(z),ariaLabel:pe?`Up to ${z.target}`:`${z.name}${z.alreadyAdded?", already added":""}`,content:n.jsxs(n.Fragment,{children:[n.jsx(D,{name:pe?"arrow-up-s":"folder-6",className:"size-4 shrink-0 text-muted-foreground"}),pe?n.jsxs("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[n.jsx("span",{className:"shrink-0",children:"Up to"}),n.jsx(Os,{value:z.target,className:"min-w-0 font-mono typography-meta text-muted-foreground"})]}):n.jsx("span",{className:"min-w-0 flex-1 truncate",children:z.name}),!pe&&z.alreadyAdded?n.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:"Added"}):null]})})}}const ge=zt(a)?ie.findIndex(z=>z.kind==="directory"):ie.length>0?0:-1,me=S?ie.findIndex(z=>z.key===S):-1,Ce=me>=0?me:ge,je=Ce>=0?ie[Ce]:void 0,Le=je?.key,we=z=>`${A}-option-${z}`;l.useLayoutEffect(()=>{Le&&x.current.get(Le)?.scrollIntoView({block:"nearest"})},[Le]);const Re=z=>{if(ie.length===0)return;const pe=Ce>=0?Ce:z>0?-1:ie.length,ne=Math.min(ie.length-1,Math.max(0,pe+z));y(ie[ne]?.key??null)},Y=a==="source"?u:a==="clone-url"?f:a==="new-name"?b:w.query,fe=z=>{if(y(null),a==="source"){const pe=z.trimStart();if(qh(pe)){d(""),m(pe),q("clone-url");return}if(Hh(pe)){d(""),w.setQuery(pe==="~"?"~/":kn(pe)),q("folder");return}d(z);return}if(a==="clone-url"){m(z);return}if(a==="new-name"){g(z);return}w.setQuery(kn(z).replace(/\/{2,}/g,"/"))},be=z=>{if(!z.nativeEvent.isComposing){if(z.key==="ArrowDown"||z.key==="ArrowUp"){if(ie.length===0)return;z.preventDefault(),Re(z.key==="ArrowDown"?1:-1);return}if(z.key==="Enter"){if(z.preventDefault(),C)return;if(zt(a)&&Ph(z)){H();return}if(a==="clone-url"||a==="new-name"){re();return}je?je.select():zt(a)&&H();return}if(z.key==="Tab"&&!z.shiftKey&&je?.kind==="directory"){z.preventDefault(),je.select();return}z.key==="Backspace"&&Y===""&&a!=="source"&&(z.preventDefault(),F())}},ee=Th(),se=[];ie.length>1&&se.push({keys:["↑","↓"],label:"Navigate"}),a==="source"?je&&se.push({keys:["↵"],label:"Select"}):a==="clone-url"||a==="new-name"?se.push({keys:["↵"],label:"Continue"}):je?se.push({keys:["↵"],label:je.kind==="toggle"?"Toggle":"Open"}):se.push({keys:["↵"],label:Ie}),a!=="source"&&Y===""&&se.push({keys:["⌫"],label:"Back"}),se.push({keys:["Esc"],label:"Close",onSelect:()=>t(!1)});const _e=zt(a)&&je?[ee,"↵"]:["↵"];let ke=null;zt(a)?ke=n.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!ue,onMouseDown:z=>z.preventDefault(),onClick:H,children:[C?V:Ie,!r&&!C&&ue?n.jsx("span",{className:"flex items-center gap-0.5",children:_e.map(z=>n.jsx(Yo,{className:"border-current/30 bg-transparent text-current",children:z},z))}):null]}):(a==="clone-url"||a==="new-name")&&(ke=n.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!Q,onMouseDown:z=>z.preventDefault(),onClick:re,children:["Continue",!r&&Q?n.jsx(Yo,{className:"border-current/30 bg-transparent text-current",children:"↵"}):null]}));let J=null;const ve=ie.filter(z=>z.kind==="directory").length;a==="source"&&ie.length===0?J={tone:"quiet",text:"Nothing matches. Type a folder path, or paste a Git URL."}:a==="clone-url"?f.trim()?O?J={tone:"quiet",text:n.jsxs(n.Fragment,{children:["Clones as ",n.jsx("span",{className:"font-mono text-foreground",children:O}),". Press Enter to choose where it goes."]})}:J={tone:"problem",text:"This URL doesn’t name a repository."}:J={tone:"quiet",text:"Paste the repository’s HTTPS or SSH URL, then press Enter to choose where it goes."}:a==="new-name"?ae?X?J={tone:"problem",text:X}:J={tone:"quiet",text:n.jsxs(n.Fragment,{children:["Press Enter to choose where ",n.jsx("span",{className:"font-mono text-foreground",children:ae})," goes."]})}:J={tone:"quiet",text:"Name the project, then press Enter to choose where it goes."}:zt(a)&&(w.browseErrorReason==="not-found"?J=a==="folder"?{tone:"quiet",text:"This folder doesn’t exist yet. Adding it creates it."}:{tone:"problem",text:"This folder doesn’t exist. Pick a location that does."}:w.browseErrorReason?J={tone:"problem",text:w.browseErrorReason==="os-permission"?"PiChamber needs access to this folder.":"Couldn’t read this folder.",actions:n.jsxs(n.Fragment,{children:[w.browseErrorReason==="os-permission"&&w.canRequestAccess?n.jsx(Ae,{size:"xs",onClick:()=>{w.handleBrowseLocation()},disabled:w.isPickingLocation,children:"Grant access"}):null,n.jsx(Ae,{variant:"outline",size:"xs",onClick:w.reload,children:"Try again"})]})}:w.showLoading&&ve===0?J={tone:"quiet",text:"Loading folders…"}:w.isSettled&&ve===0&&(J={tone:"quiet",text:w.browseFilterQuery?a==="folder"?n.jsxs(n.Fragment,{children:["No folder named ",n.jsx("span",{className:"font-mono text-foreground",children:w.browseFilterQuery})," here. Adding it creates it."]}):"No folders match.":"No folders in here."}));const he=R?n.jsx("p",{role:"alert",className:"border-b border-border/60 px-4 py-2 typography-meta text-[var(--status-error)] text-pretty",children:R}):null,Se=(z,pe)=>n.jsx("button",{type:"button",onClick:F,disabled:C!==null,"aria-label":pe,className:"ml-auto shrink-0 rounded px-1 typography-ui-label text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:pointer-events-none disabled:opacity-50",children:z}),qe=P?n.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/60 px-4 py-2",children:[a==="new-location"?n.jsxs("div",{className:"flex min-w-0 items-center gap-2 typography-ui-label",children:[n.jsx("label",{htmlFor:"new-project-name",className:"shrink-0 text-muted-foreground",children:"Name"}),n.jsx("input",{value:b,onChange:z=>g(z.target.value),onKeyDown:z=>{z.nativeEvent.isComposing||z.key==="Enter"&&(z.preventDefault(),H())},id:"new-project-name",spellCheck:!1,autoComplete:"off",disabled:C!==null,className:"h-7 min-w-0 flex-1 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-1.5 font-mono text-foreground outline-none focus-visible:border-[var(--interactive-focus)] focus-visible:ring-2 focus-visible:ring-primary/30"})]}):null,n.jsxs("p",{className:_("flex min-w-0 items-baseline gap-1.5 typography-ui-label",P.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:[n.jsx("span",{className:"shrink-0",children:P.text}),P.path?n.jsx(Os,{value:P.path,className:"min-w-0 font-mono text-foreground"}):null]}),a==="clone-location"?n.jsxs("p",{className:"flex min-w-0 items-baseline gap-1.5 typography-ui-label text-muted-foreground",children:[n.jsx("span",{className:"shrink-0",children:"From"}),n.jsx(Os,{value:f.trim(),className:"min-w-0 font-mono text-foreground"}),Se("Change","Change the repository URL")]}):null]}):null,Ue=a!=="source"&&a!=="new-name";return n.jsx(en,{open:e,onOpenChange:t,children:n.jsxs(tn,{showCloseButton:!1,initialFocus:i?!1:v,className:_("group/palette w-full max-w-xl gap-0 self-start overflow-hidden rounded-2xl p-0","mt-[max(env(safe-area-inset-top),0.25rem)] max-h-[calc(100%-0.5rem)] sm:mt-[10vh] sm:max-h-[80vh]"),children:[n.jsx(mn,{className:"sr-only",children:"Add folder"}),n.jsx(Cn,{className:"sr-only",children:Kh[a]}),n.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-border/60 pl-2.5 pr-2",children:[a==="source"?n.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center text-muted-foreground",children:n.jsx(D,{name:"folder-add",className:"size-4"})}):n.jsx(Ae,{variant:"ghost",size:"icon",className:"size-7 shrink-0",onMouseDown:z=>z.preventDefault(),onClick:F,disabled:C!==null,"aria-label":"Back",title:"Back",children:n.jsx(D,{name:"arrow-left-s",className:"size-4"})}),a!=="source"?n.jsxs("span",{className:"flex shrink-0 items-center gap-2 typography-ui-label font-medium text-foreground","aria-hidden":"true",children:[$h[a],n.jsx("span",{className:"h-4 w-px bg-border"})]}):null,n.jsx("input",{ref:v,value:Y,onChange:z=>fe(z.target.value),onKeyDown:be,readOnly:C!==null,"aria-busy":C!==null||void 0,"aria-label":Wh[a],placeholder:Gh[a],role:"combobox","aria-expanded":ie.length>0,"aria-controls":A,"aria-autocomplete":"list","aria-activedescendant":Ce>=0?we(Ce):void 0,"aria-invalid":J?.tone==="problem"&&!zt(a)?!0:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("min-w-0 flex-1 text-foreground outline-none placeholder:text-muted-foreground",a==="source"?"h-full bg-transparent":"h-8 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2","typography-markdown md:typography-ui-label",Ue&&"font-mono")}),ke]}),qe,he,n.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain sm:max-h-[min(24rem,52vh)]",children:[ie.length>0?n.jsx("div",{id:A,role:"listbox","aria-label":a==="source"?"Sources":"Folders",className:"flex flex-col gap-px p-1.5",children:ie.map((z,pe)=>n.jsxs(l.Fragment,{children:[pe>0&&ie[pe-1]?.kind==="toggle"?n.jsx("div",{role:"presentation",className:"mx-2.5 my-1 h-px bg-border/60"}):null,n.jsx(_l,{ref:ne=>{ne?x.current.set(z.key,ne):x.current.delete(z.key)},id:we(pe),active:pe===Ce,onSelect:z.select,onHover:()=>y(z.key),ariaLabel:z.ariaLabel,ariaChecked:z.ariaChecked,className:z.kind==="source"?"py-2":void 0,quiet:zt(a),children:z.content})]},z.key))}):null,J?n.jsxs("div",{className:_("flex flex-col items-center gap-3 px-6 text-center",ie.length>0?"pb-6 pt-3":"py-8"),children:[n.jsx("p",{className:_("typography-meta text-balance",J.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:J.text}),J.actions?n.jsx("div",{className:"flex items-center gap-2",children:J.actions}):null]}):null]}),!r||zt(a)?n.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-3 border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:[r?n.jsx("span",{}):n.jsx(Ah,{hints:se}),zt(a)?n.jsxs("span",{className:"flex shrink-0 items-center gap-3",children:[n.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5",children:[n.jsx(Gs,{checked:w.showHidden,onChange:w.setShowHidden,ariaLabel:"Show hidden folders"}),"Hidden"]}),n.jsx(Ae,{variant:"ghost",size:"xs",disabled:C!==null||w.isPickingLocation,onMouseDown:z=>z.preventDefault(),onClick:()=>{w.handleBrowseLocation()},title:"Pick a folder with the system dialog",children:w.isPickingLocation?"Opening…":"Browse…"})]}):null]}):null]})})},cr=e=>e?n.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,By=()=>{const[e,t]=l.useState(!1),[s,r]=l.useState(null),[o,i]=l.useState(!1),a=Fe(k=>k.deleteSession),c=Fe(k=>k.deleteSessions),u=de(k=>k.showDeletionDialog),d=de(k=>k.setShowDeletionDialog),{isMobile:f,isTablet:m,hasTouchInput:b}=ps(),g=f||m||b;l.useEffect(()=>Mf(()=>{t(!1)}),[]);const h=l.useCallback(k=>{r({sessions:k.sessions,dateLabel:k.dateLabel})},[]),p=l.useCallback(()=>{r(null),i(!1)},[]),S=l.useCallback(async k=>{if(k.sessions.length===0)return;if(k.sessions.length===1){const L=k.sessions[0];await a(L.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const w=k.sessions.map(L=>L.id),{deletedIds:C,failedIds:R}=await c(w);if(C.length>0){const L=R.length>0?R.length===1?`${R.length} session could not be deleted.`:`${R.length} sessions could not be deleted.`:k.dateLabel?`Removed all sessions from ${k.dateLabel}.`:void 0;oe.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:cr(L)})}R.length>0&&oe.error(R.length===1?`Failed to delete ${R.length} session`:`Failed to delete ${R.length} sessions`,{description:cr("Please try again in a moment.")})},[a,c]);l.useEffect(()=>Hs.onDeleteRequest(k=>{if(!u){S(k);return}h(k)}),[h,u,S]),l.useEffect(()=>Hs.onDirectoryRequest(()=>{t(!0)}),[]);const y=l.useCallback(async()=>{if(s){i(!0);try{if(s.sessions.length===1){const k=s.sessions[0];if(!await a(k.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const k=s.sessions.map(L=>L.id),w=await c(k),C=w.deletedIds,R=w.failedIds;if(C.length>0){const L=R.length>0?R.length===1?`${R.length} session could not be deleted.`:`${R.length} sessions could not be deleted.`:s.dateLabel?`Removed all sessions from ${s.dateLabel}.`:void 0;oe.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:cr(L),action:{label:"OK",onClick:()=>{}}})}if(R.length>0&&(oe.error(R.length===1?`Failed to delete ${R.length} session`:`Failed to delete ${R.length} sessions`,{description:cr("Please try again in a moment.")}),C.length===0)){i(!1);return}}p()}finally{i(!1)}}},[s,a,c,p]),v=s?s.sessions.length===1?s.dateLabel?`This action permanently removes 1 session from ${s.dateLabel}.`:"This action permanently removes 1 session.":s.dateLabel?`This action permanently removes ${s.sessions.length} sessions from ${s.dateLabel}.`:`This action permanently removes ${s.sessions.length} sessions.`:"",x=s?n.jsxs("div",{className:"space-y-2",children:[s.sessions.length>0&&n.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:n.jsxs("ul",{className:"space-y-0.5",children:[s.sessions.slice(0,5).map(k=>n.jsx("li",{className:"typography-micro text-subtle-foreground",children:n.jsx("span",{className:"truncate",children:dn(k)})},k.id)),s.sessions.length>5&&n.jsx("li",{className:"typography-micro text-subtle-foreground",children:`+${s.sessions.length-5} more`})]})}),n.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:n.jsx("p",{className:"typography-meta text-subtle-foreground",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=n.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[n.jsxs("button",{type:"button",onClick:()=>d(!u),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!u,children:[u?n.jsx(D,{name:"checkbox-blank",className:"size-4"}):n.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ae,{variant:"ghost",onClick:p,disabled:o,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",onClick:y,disabled:o,children:o?"Deleting…":s?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),j=s?.sessions.length===1?"Delete session":"Delete sessions";return n.jsxs(n.Fragment,{children:[g?n.jsx(ud,{open:!!s,onClose:()=>{o||p()},title:j,footer:n.jsx("div",{className:"flex justify-end gap-2",children:A}),children:n.jsxs("div",{className:"space-y-2 pb-2",children:[v&&n.jsx("p",{className:"typography-meta text-subtle-foreground",children:v}),x]})}):n.jsx(en,{open:!!s,onOpenChange:k=>{if(!k){if(o)return;p()}},children:n.jsxs(tn,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:j}),v&&n.jsx(Cn,{children:v})]}),n.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:x}),n.jsx(ms,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),n.jsx(Vh,{open:e,onOpenChange:t})]})},_y=()=>{const e=Bn(t=>t.entries);return l.useEffect(()=>{for(const t of e.values())!dd(t)||!t.receipt||(Bn.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},Qh=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-access",title:"Remote access",group:"projects",kind:"single",description:"How other devices reach this computer.",keywords:["remote","access","mobile","phone","pair","qr","device","devices","tailscale","funnel","lan","network","wifi","password","passkey"],isAvailable:e=>!e.isMobile&&(e.isDesktop||e.isWeb)},{slug:"servers",title:"Servers",group:"projects",kind:"single",description:"Which PiChamber server this app uses.",keywords:["server","servers","instance","switch","connect","import link","host"],isAvailable:e=>!e.isMobile&&e.isDesktop||e.isMobile&&e.isCapacitor===!0},{slug:"remote-instances",title:"Remote instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"],isAvailable:()=>!1},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","ssh","commit","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Jh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Xh(e){const t=e.trim().toLowerCase();return Qh.find(s=>s.slug===t)??null}function Zh(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const s=Jh[t];if(s)return s;const r=Xh(t);return r?r.slug:"home"}function zy(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-access":return"server";case"servers":return"server";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function Uy(){const e=l.useRef(!1),t=l.useRef(!1),s=Fe(f=>f.setCurrentSession),r=de(f=>f.setActiveMainTab),o=de(f=>f.setSettingsDialogOpen),i=de(f=>f.setSettingsPage),a=de(f=>f.navigateToDiff),c=l.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const m=Fe.getState().currentSessionId,b=ts().getState().selectedSessionId;if(f.sessionId!==m||f.sessionId!==b){const g=Fe.getState().getDirectoryForSession(f.sessionId);s(f.sessionId,g)}}if(f.settingsPath){i(Zh(f.settingsPath)),o(!0);return}de.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&a(f.diffFile)}finally{t.current=!1}}},[s,r,o,i,a]),u=l.useCallback(()=>{const f=Fe.getState(),m=ts().getState(),b=de.getState();return{sessionId:no({currentSessionId:f.currentSessionId,piSelectedSessionId:m.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),d=l.useCallback((f={})=>{if(t.current)return;const m=u();Go(m,f)},[u]);l.useEffect(()=>{if(e.current||(e.current=!0,!Ki()))return;const f=Wi();(async()=>(await c(f),Go({...u(),sessionId:f.sessionId??no({currentSessionId:Fe.getState().currentSessionId,piSelectedSessionId:ts().getState().selectedSessionId,draft:Fe.getState().newSessionDraft}),tab:f.tab??de.getState().activeMainTab,settingsPath:f.settingsPath??de.getState().settingsPage,diffFile:f.diffFile??de.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),l.useEffect(()=>{const f=()=>{const S=Fe.getState(),y=ts().getState();return no({currentSessionId:S.currentSessionId,piSelectedSessionId:y.selectedSessionId,draft:S.newSessionDraft})};let m=f(),b=Fe.getState().newSessionDraft?.open===!0;const g=()=>{const S=Fe.getState(),y=f(),v=S.newSessionDraft?.open===!0;y===m&&v===b||t.current||(m=y,b=v,d({replace:!0}))},h=Fe.subscribe(()=>{g()}),p=ts().subscribe(()=>{g()});return()=>{h(),p()}},[d]),l.useEffect(()=>{let f=de.getState().activeMainTab,m=de.getState().isSettingsDialogOpen,b=de.getState().settingsPage,g=de.getState().pendingDiffFile;return de.subscribe(p=>{if(t.current)return;const S=p.activeMainTab!==f,y=p.isSettingsDialogOpen!==m,v=p.settingsPage!==b,x=p.pendingDiffFile!==g&&p.activeMainTab==="diff";f=p.activeMainTab,m=p.isSettingsDialogOpen,b=p.settingsPage,g=p.pendingDiffFile,(S||y||v||x)&&d()})},[d]),l.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const m=Wi();if(Ki())c(m);else{const b=de.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function ep(e=!0){const t=xr(r=>r.checkForUpdates),s=l.useRef(t);l.useEffect(()=>{s.current=t},[t]),l.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,a=1440*60*1e3;let c=!1,u=null;const d=m=>{const b=Math.round(m*1e3);return Math.max(i,Math.min(a,b))},f=m=>{c||(u=window.setTimeout(async()=>{const b=await s.current(),g=typeof b=="number"&&Number.isFinite(b)?d(b):o;f(g)},m))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function $y(){const e=Bs(t=>t.connection==="ready",void 0,"chrome");return ep(e),null}const tp=200,np=15e3,sp=e=>{const{id:t,url:s}=e.payload,r=hd(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=pd(md(s),r.target,{isMobile:de.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:np});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{gd(r.target,s,bd()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},Ky=()=>(l.useEffect(()=>{const e=new Set;return fd(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>tp){const s=e.values().next().value;s!==void 0&&e.delete(s)}sp(t)}})},[]),null),sa=12,rp=[{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"}],op=({isActive:e,burstKey:t=0,className:s,durationMs:r=900,bursts:o=rp,onComplete:i})=>{const a=Te.useRef(!1);Te.useEffect(()=>{!e&&a.current&&i?.(),e&&(a.current=!0)},[e,i]);const c=Te.useMemo(()=>Array.from({length:sa},(u,d)=>{const f=Math.PI*2*d/sa;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?n.jsx("div",{className:_("fireworks-overlay pointer-events-none",s),"aria-hidden":"true","data-burst-key":t,children:o.map(u=>{const d={"--burst-delay":`${u.delay}ms`,"--burst-x":`${u.x}%`,"--burst-y":`${u.y}%`,"--firework-color":`var(${u.colorVar})`,"--firework-duration":`${r}ms`};return n.jsx("div",{className:"firework-burst",style:d,children:c.map((f,m)=>{const b=f.x*u.radius,g=f.y*u.radius,h={"--translate-x":`${b}px`,"--translate-y":`${g}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return n.jsx("span",{className:"firework-particle",style:h},`${u.id}-${m}-${t}`)})},`${u.id}-${t}`)})}):null},ip=({durationMs:e=3400}={})=>{const[t,s]=Te.useState({isActive:!1,cycle:0}),r=Te.useRef(null),o=Te.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Te.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),a=Te.useCallback(()=>{o(),s(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{s(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Te.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:a,dismissFireworks:i}},$l=l.createContext(void 0),Wy=({children:e})=>{const{isActive:t,burstKey:s,triggerFireworks:r,dismissFireworks:o}=ip(),i=l.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return n.jsxs($l.Provider,{value:i,children:[e,n.jsx(op,{isActive:t,burstKey:s})]})},ap={triggerFireworks:()=>{},dismissFireworks:()=>{}},Gy=()=>l.useContext($l)??ap,Ir=2e3,Kl=600*1e3;async function lp(){try{const e=await tt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const s=await e.json().catch(()=>({}));return{success:!1,error:s.error||`Server error: ${e.status}`,commands:Array.isArray(s.commands)?s.commands.filter(r=>typeof r=="string"):void 0}}const t=await e.json().catch(()=>({}));return{success:!0,autoRestart:t.autoRestart!==!1,jobId:typeof t.jobId=="string"?t.jobId:void 0,channel:t.channel==="rc"?"rc":t.channel==="stable"?"stable":void 0,targetVersion:typeof t.targetVersion=="string"?t.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function cp(e,t=Math.ceil(Kl/Ir),s=Ir,r=Ze()){for(let o=0;o<t;o++){if(Ze()!==r)return{applied:!1,stale:!0};try{const i=await tt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Ze()!==r)return{applied:!1,stale:!0};if(i.ok){const a=await i.json().catch(()=>null);if(Ze()!==r)return{applied:!1,stale:!0};if(typeof a?.error=="string"&&a.error.length>0)return{applied:!1,error:a.error};if(a&&a.available===!1)return{applied:!0};if(a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Ze()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,s))}return{applied:!1}}async function up(e,t,s=Math.ceil(Kl/Ir),r=Ir,o=Ze()){for(let i=0;i<s;i++){if(Ze()!==o)return{applied:!1,stale:!0};try{const a=await tt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Ze()!==o)return{applied:!1,stale:!0};if(a.ok){const c=await a.json().catch(()=>null);if(Ze()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?t("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&t("updating")}else{if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(a.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(a.status===503){const c=await a.json().catch(()=>null);if(Ze()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};t("reconnecting")}else t("reconnecting")}}catch{if(Ze()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(a=>setTimeout(a,r))}return{applied:!1}}const ra="https://github.com/RyderAsKing/PiChamber/releases";function dp(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 fp(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function oa(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function hp(e,t){const s=d=>{const f=d.indexOf("-");return f<0?[d,""]:[d.slice(0,f),d.slice(f+1)]},[r,o]=s(e),[i,a]=s(t),c=r.split(".").map(d=>Number.parseInt(d,10)),u=i.split(".").map(d=>Number.parseInt(d,10));for(let d=0;d<3;d+=1){const f=Number.isFinite(c[d])?c[d]:0,m=Number.isFinite(u[d])?u[d]:0;if(f!==m)return m-f}return!o||!a?(o?1:0)-(a?1:0):a.localeCompare(o,void 0,{numeric:!0})}function pp(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,s=[];let r;for(;(r=t.exec(e))!==null;)s.push({version:r[1]??"",date:r[2]??"",start:r.index});return s.length===0?[]:s.map((o,i)=>{const a=s[i+1]?.start??e.length,c=e.slice(o.start,a).trim();return{version:o.version,date:o.date,start:o.start,end:a,raw:c}})}const Wl=({open:e,onOpenChange:t,info:s,downloading:r,downloaded:o,progress:i,error:a,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,m]=Te.useState(null),[b,g]=Te.useState("idle"),[h,p]=Te.useState(null),[S,y]=Te.useState(null),[v,x]=Te.useState({}),A=s?.version?s.releaseUrl||`${ra}/tag/v${s.version}`:ra,j=s?.downloadUrl||A,k=i?.total?Math.round(i.downloaded/i.total*100):0,w=d==="web",C=d==="mobile",R=s?.updateCommand||"pichamber update",L=v.version||s?.version,U=v.channel||s?.channel;Te.useEffect(()=>{e||(g("idle"),p(null),y(null),x({}))},[e]);const G=async(I=R)=>{(await fn(I)).ok&&(m(I),setTimeout(()=>m(null),2e3))},$=Te.useCallback(async I=>{await ul(I)},[]),q=Te.useCallback(async()=>{const I=Ze();g("updating"),p(null),y(null),x({});const M=await lp();if(Ze()!==I)return;if(!M.success){g("error"),p(M.error||"Update failed"),y(M.commands??null);return}if(x({version:M.targetVersion,channel:M.channel}),M.jobId){const K=await up(M.jobId,O=>{Ze()===I&&g(O)},void 0,void 0,I);if(K.stale||Ze()!==I)return;if(K.applied){window.location.reload();return}g("error"),p(K.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}g(M.autoRestart?"restarting":"reconnecting");const W=await cp(s?.currentVersion,void 0,void 0,I);if(!(W.stale||Ze()!==I)){if(W.applied){window.location.reload();return}g("error"),p(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[s?.currentVersion]),F=Te.useCallback(()=>{$(j)},[$,j]),E=b!=="idle"&&b!=="error",T=Te.useMemo(()=>{if(!s?.body)return null;const I=s.body.trim();if(!I)return null;const M=pp(I);return M.length===0?{kind:"raw",title:"What's new",content:oa(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((K,O)=>hp(K.version,O.version)).map(K=>({version:K.version,dateLabel:dp(K.date),content:oa(fp(K.raw)||I)}))}},[s?.body]);return n.jsx(en,{open:e,onOpenChange:E?void 0:t,children:n.jsxs(tn,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[n.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[n.jsxs(mn,{className:"flex items-center gap-2.5",children:[n.jsx(D,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),n.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(s?.currentVersion||L||w&&U)&&n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(s?.currentVersion||L)&&n.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[s?.currentVersion&&n.jsx("span",{className:"text-muted-foreground",children:s.currentVersion}),s?.currentVersion&&L&&n.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"→"}),L&&n.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:L})]}),w&&U&&n.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:U==="rc"?"RC channel":"Stable channel"})]})]}),n.jsxs("div",{className:"space-y-2",children:[w&&E&&n.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(D,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),n.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="reconnecting"&&"Waiting for server..."]})]}),n.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!E&&n.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:n.jsx(Mn,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:T.kind==="raw"?n.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:I=>{const W=I.target.closest("a");W&&W.href&&(I.preventDefault(),I.stopPropagation(),$(W.href))},children:n.jsx(Gi,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):n.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(I=>n.jsxs("div",{className:"p-4",children:[n.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[n.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",I.version]}),n.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),n.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:M=>{const K=M.target.closest("a");K&&K.href&&(M.preventDefault(),M.stopPropagation(),$(K.href))},children:n.jsx(Gi,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(a||h)&&n.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:n.jsx("p",{className:"text-sm text-[var(--status-error)]",children:a||h})}),w&&b==="error"&&(S??[R]).length>0&&n.jsxs("div",{className:"space-y-2 mt-4",children:[n.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[n.jsx(D,{name:"terminal",className:"h-4 w-4"}),n.jsx("span",{children:S?"Run these commands:":"Or update via terminal:"})]}),(S??[R]).map(I=>n.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[n.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),n.jsx(Ae,{variant:"ghost",size:"icon",onClick:()=>{G(I)},className:f===I?"text-[var(--status-success)]":void 0,title:f===I?"Copied!":"Copy command","aria-label":f===I?"Copied!":"Copy command",children:f===I?n.jsx(D,{name:"check",className:"h-4 w-4"}):n.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!w&&!C&&r&&n.jsxs("div",{className:"space-y-2 mt-4",children:[n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),n.jsxs("span",{className:"font-mono text-foreground",children:[k,"%"]})]}),n.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:n.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${k}%`}})})]})]}),n.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[n.jsxs("a",{href:A,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[n.jsx(D,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),n.jsxs("div",{className:"flex-1 flex justify-end",children:[!w&&!C&&!o&&!r&&n.jsxs(Ae,{onClick:c,children:[n.jsx(D,{name:"download",className:"h-4 w-4"}),"Download update"]}),!w&&!C&&r&&n.jsxs(Ae,{disabled:!0,children:[n.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!w&&!C&&o&&n.jsxs("button",{onClick:u,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[n.jsx(D,{name:"restart",className:"h-4 w-4"}),"Restart to update"]}),C&&n.jsxs(Ae,{onClick:F,size:"default",children:[n.jsx(D,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),w&&!E&&n.jsxs(Ae,{onClick:q,children:[n.jsx(D,{name:"download",className:"h-4 w-4"}),"Update now"]}),w&&E&&n.jsxs(Ae,{disabled:!0,children:[n.jsx(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Gl=l.memo(function({checked:t,onChange:s,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:a,iconClassName:c}){const u=l.useCallback(b=>{b.preventDefault(),b.stopPropagation(),!r&&!t&&s()},[t,r,s]),d=l.useCallback(b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),!r&&!t&&s())},[t,r,s]),f=n.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),m=_("relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full","transition-[background-color,box-shadow] duration-200 ease-out",t?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none":"bg-background shadow-[inset_0_0_0_1px_var(--interactive-border-hover)]");return i?n.jsx("span",{"aria-hidden":!0,className:_(m,r&&"opacity-50",a),children:f}):n.jsx("button",{type:"button",role:"radio",onClick:u,onKeyDown:d,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",m,t?"hover:bg-[var(--primary-base)]":"hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:f})}),tr=({children:e,className:t,contentClassName:s})=>{const[r,o]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>{if(!r)return;const a=c=>{const u=i.current;u&&c.target instanceof Node&&u.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[r]),n.jsxs(Ke,{open:r,onOpenChange:o,children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:a=>{a.preventDefault(),a.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-subtle-foreground hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:n.jsx(D,{name:"information",className:"h-3.5 w-3.5"})})}),n.jsx(Ge,{sideOffset:8,className:_("max-w-sm",s),children:e})]})},Hy="w-full min-w-40 max-w-48",qy="settings",mp="w-full min-w-40 max-w-48",Yy="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",gp="w-full max-w-[24rem]",Vy="min-w-0 flex-1",Qy="flex w-full min-w-0 items-center gap-2",Jy="typography-meta shrink-0 text-muted-foreground tabular-nums",Hl="space-y-3.5",bp="space-y-1.5",Xy="typography-settings-page-title text-foreground",xp="typography-settings-section-title text-foreground",ql="typography-settings-group-title text-foreground",vi="typography-settings-field-label text-foreground",yp="typography-settings-description text-muted-foreground",nr="typography-meta text-muted-foreground",Zy="typography-meta font-medium text-foreground",wp=({title:e,description:t,titleAccessory:s,info:r,headerAction:o,children:i,divider:a=!0,className:c,contentClassName:u,settingsItem:d})=>{const f=e!=null||t!=null||o!=null||r!=null;return n.jsxs("section",{"data-settings-item":d,className:_("space-y-4",a?"border-t border-border/60 py-6":"pb-6",c),children:[f?n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?n.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?n.jsx("h2",{className:xp,children:e}):e,s,r!=null?n.jsx(tr,{children:r}):null]}):null,t!=null?n.jsx("div",{className:yp,children:t}):null]}),o?n.jsx("div",{className:"shrink-0",children:o}):null]}):null,n.jsx("div",{className:_(u),children:i})]})},ew=({children:e,className:t})=>n.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),vp=({children:e,className:t,as:s="h3"})=>n.jsx(s,{className:_(ql,t),children:e}),tw=({title:e,description:t,info:s,children:r,className:o,contentClassName:i,settingsItem:a})=>n.jsxs("div",{"data-settings-item":a,className:_("space-y-2",o),children:[e!=null||t!=null||s!=null?n.jsxs("div",{className:"space-y-0.5",children:[e!=null?n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(vp,{children:e}),s!=null?n.jsx(tr,{children:s}):null]}):null,t!=null?n.jsx("p",{className:nr,children:t}):null]}):null,n.jsx("div",{className:_(i),children:r})]}),$s=({label:e,description:t,info:s,descriptionPlacement:r="before",children:o,settingsItem:i,className:a,controlClassName:c})=>{const u=t!=null?n.jsx("p",{className:nr,children:t}):null;return n.jsxs("div",{"data-settings-item":i,className:_("space-y-2",a),children:[n.jsxs("div",{className:"space-y-0.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:vi,children:e}),s!=null?n.jsx(tr,{children:s}):null]}),r==="before"?u:null]}),n.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},nw=({label:e,description:t,info:s,children:r,settingsItem:o,className:i,labelClassName:a,controlClassName:c,alignEnd:u=!0})=>n.jsxs("div",{"data-settings-item":o,className:_("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",i),children:[n.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",a),children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("div",{className:vi,children:e}),s!=null?n.jsx(tr,{children:s}):null]}),t!=null?n.jsx("p",{className:_(nr,"mt-0.5"),children:t}):null]}),n.jsx("div",{className:_("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",u&&"@xl:justify-end",c),children:r})]}),sw=({children:e,className:t,settingsItem:s})=>n.jsx("div",{"data-settings-item":s,className:_("pt-4",t),children:e}),rw=({label:e,children:t,divider:s=!0,className:r,contentClassName:o,defaultOpen:i=!1})=>{const[a]=l.useState(i);return n.jsxs("details",{open:a||void 0,className:_("group/disclosure",s?"border-t border-border/60 py-6":"pb-6",r),children:[n.jsxs("summary",{className:"flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md typography-ui-label text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] [&::-webkit-details-marker]:hidden",children:[n.jsx(D,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),n.jsx("div",{className:_("pt-4",o),children:t})]})},Sp=({checked:e,onChange:t,label:s,description:r,disabled:o=!1,ariaLabel:i,settingsItem:a,className:c,labelAccessory:u,info:d})=>{const f=()=>{o||t(!e)},m=r!=null;return n.jsxs("div",{"data-settings-item":a,className:_("group flex cursor-pointer gap-2 py-0.5",m?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[n.jsx(Gs,{checked:e,onChange:t,disabled:o,ariaLabel:i}),n.jsxs("div",{className:"flex min-w-0 flex-col",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx("span",{className:vi,children:s}),u,d!=null?n.jsx(tr,{children:d}):null]}),m?n.jsx("span",{className:nr,children:r}):null]})]})},ow=({selected:e,onSelect:t,label:s,description:r,ariaLabel:o,disabled:i=!1,className:a})=>n.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",a),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[n.jsx(Gl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),n.jsxs("div",{className:"flex min-w-0 flex-col",children:[n.jsx("span",{className:_("typography-settings-field-label font-normal","text-foreground"),children:s}),r!=null?n.jsx("span",{className:nr,children:r}):null]})]}),iw=({selected:e,onSelect:t,label:s,preview:r,description:o,ariaLabel:i,disabled:a=!1,className:c})=>{const u=l.useId();return n.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",a&&"cursor-not-allowed opacity-60",c),role:"radio",tabIndex:a?-1:0,"aria-checked":e,"aria-label":i,"aria-describedby":o?u:void 0,"aria-disabled":a||void 0,onClick:()=>{a||t()},onKeyDown:d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),a||t())},children:[n.jsx("div",{"aria-hidden":!0,className:_("aspect-[4/3] overflow-hidden rounded-lg border transition-colors",e?"border-[var(--primary-base)] ring-1 ring-[var(--primary-base)]":"border-[var(--interactive-border)] group-hover/preview:border-foreground/30"),children:r}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx(Gl,{checked:e,onChange:t,disabled:a,decorative:!0}),n.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal","text-foreground"),children:s})]}),o?n.jsx("p",{id:u,className:"-mt-1 pl-[20px] typography-meta text-muted-foreground text-pretty",children:o}):null]})},aw=({"aria-label":e,children:t,className:s})=>n.jsx("div",{role:"radiogroup","aria-label":e,className:_(bp,s),children:t});function lw({value:e,options:t,onChange:s,className:r,"aria-label":o}){return n.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>n.jsx(Ae,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>s(i.value),children:i.label},i.value))})}const Vo="pichamber:server-update-channel-changed",cw=()=>{typeof window<"u"&&window.dispatchEvent(new Event(Vo))},jp=e=>typeof window>"u"?()=>{}:(window.addEventListener(Vo,e),()=>window.removeEventListener(Vo,e));class kp extends l.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,s){this.setState({error:t,errorInfo:s})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?n.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:n.jsxs(xd,{className:"w-full max-w-md",children:[n.jsx(yd,{className:"text-center",children:n.jsxs(wd,{className:"flex items-center justify-center gap-2 text-destructive",children:[n.jsx(D,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),n.jsxs(vd,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&n.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&n.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[n.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),n.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),n.jsx("div",{className:"flex gap-2",children:n.jsxs(Ae,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[n.jsx(D,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),n.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Cp(e){return n.jsx(kp,{...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 uw=({active:e=!0})=>{const t=Fe(s=>s.currentSessionId);return n.jsx(Cp,{sessionId:t||void 0,children:n.jsx(Sd,{active:e},t??"no-session")})};function Ap({onResizeStart:e,ariaLabel:t}){return n.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":t,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:n.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const Yl=Te.forwardRef(({className:e,outerClassName:t,scrollbarClassName:s,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:a,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:m,...b},g)=>{const h=Te.useRef(null),p=Te.useRef(null),[S,y]=Te.useState(null),v=c??S,x=Te.useCallback(j=>{const k=h.current;if(!k)return;p.current={startY:j.clientY,startHeight:k.getBoundingClientRect().height};const w=j.currentTarget;w.setPointerCapture(j.pointerId);const C=L=>{const U=p.current;if(!U)return;const G=U.startHeight+(L.clientY-U.startY),$=Math.max(82,G);u?u($):y($)},R=()=>{p.current=null,w.removeEventListener("pointermove",C),w.removeEventListener("pointerup",R),w.removeEventListener("pointercancel",R)};w.addEventListener("pointermove",C),w.addEventListener("pointerup",R),w.addEventListener("pointercancel",R),j.preventDefault()},[u]),A=Te.useCallback(j=>{if(j.target.closest('textarea, button, [role="separator"]'))return;const w=h.current?.querySelector("textarea");w&&document.activeElement!==w&&(j.preventDefault(),w.focus())},[]);return f?n.jsx(Mn,{as:"textarea",ref:g,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:s,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}):n.jsx("div",{ref:h,onPointerDown:A,style:v!==null?{height:`${v}px`}:void 0,className:_("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!a&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],a&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[n.jsx("textarea",{ref:g,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",!d&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],d&&"text-subtle-foreground placeholder:text-subtle-foreground",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}),n.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,n.jsx(Ap,{onResizeStart:x,ariaLabel:"Resize textarea"})]})]})})});Yl.displayName="Textarea";const Vl=[{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"}],Ks=Object.fromEntries(Vl.map(e=>[e.key,e.Icon])),Qo="pichamber:project-actions-updated",Ql=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},cn=(e,t)=>`${Ql(e)}::${t}`,Jl=({title:e,description:t,info:s,settingsItem:r,titleAccessory:o,headerAction:i,children:a,className:c,contentClassName:u,divider:d=!0})=>n.jsx(wp,{title:e,description:t,info:s,settingsItem:r,titleAccessory:o,headerAction:i,divider:d,className:c,contentClassName:u,children:a}),Jo=e=>e.name.trim().length>0&&e.command.trim().length>0,Np=e=>e.name.trim().length===0&&e.command.trim().length===0,Ip=e=>!Jo(e)&&!Np(e),Ep=(e,t)=>e.some(r=>t.has(r.id)&&!Jo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Jo)},Dp=450,Rp=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Pp=()=>({id:Rp(),name:"",command:"",icon:"play"}),Tp=({projectRef:e})=>{const[t,s]=l.useState([]),[r,o]=l.useState(!1),[i,a]=l.useState(null),[c,u]=l.useState(new Set),d=l.useRef(!1);l.useEffect(()=>{let y=!1;return o(!0),(async()=>{try{const v=await Po(e);if(y)return;s(v.actions),a(JSON.stringify({actions:v.actions})),u(new Set(v.actions.map(x=>x.id)))}catch{if(y)return;s([]),a(JSON.stringify({actions:[]})),u(new Set)}finally{y||o(!1)}})(),()=>{y=!0}},[e]);const f=l.useMemo(()=>Ep(t,c),[t,c]),m=l.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=i!==null&&f.canPersist&&m!==i,g=l.useCallback(async y=>await jd(e,{actions:y,primaryActionId:null})?(a(JSON.stringify({actions:y})),u(new Set(y.map(x=>x.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Qo,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);l.useEffect(()=>{if(!b||r||d.current)return;const y=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await g(f.actions)}finally{d.current=!1}})())},Dp);return()=>{window.clearTimeout(y)}},[b,r,g,f.actions]);const h=l.useCallback(()=>{const y=Pp();s(v=>[...v,y])},[]),p=l.useCallback(y=>{s(v=>v.filter(x=>x.id!==y))},[]),S=l.useCallback((y,v)=>{s(x=>x.map(A=>A.id===y?v(A):A))},[]);return n.jsx(Jl,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:n.jsxs(Ae,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:h,children:[n.jsx(D,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):n.jsx("div",{className:_("space-y-6",gp),children:t.map((y,v)=>{const x=y.icon||"play",A=Ks[x]||"play",j=y.name.trim()||`Action ${v+1}`,k=Ip(y);return n.jsxs("div",{className:Hl,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("h3",{className:ql,children:j}),n.jsx(Ae,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>p(y.id),"aria-label":`Delete ${j}`,children:n.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),n.jsxs($s,{label:"Name",controlClassName:"w-full max-w-none",children:[n.jsxs(Gt,{children:[n.jsx(Ht,{asChild:!0,children:n.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:n.jsx(D,{name:A,className:"h-4 w-4"})})}),n.jsx(qt,{align:"start",className:"w-56 p-2",children:n.jsx("div",{className:"grid grid-cols-6 gap-1",children:Vl.map(w=>{const C=w.Icon,R=(y.icon||"play")===w.key;return n.jsx("button",{type:"button",onClick:()=>S(y.id,L=>({...L,icon:w.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",R&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${w.label}`,children:n.jsx(D,{name:C,className:"h-4 w-4"})},w.key)})})})]}),n.jsx(To,{value:y.name,onChange:w=>S(y.id,C=>({...C,name:w.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),n.jsx($s,{label:"Command",controlClassName:"w-full max-w-none",children:n.jsx(Yl,{value:y.command,onChange:w=>S(y.id,C=>({...C,command:w.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),k?n.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,n.jsx(Sp,{checked:y.autoOpenUrl===!0,onChange:w=>S(y.id,C=>({...C,...w?{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}`}),y.autoOpenUrl===!0?n.jsx(n.Fragment,{children:n.jsx($s,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:n.jsx(To,{value:y.openUrl||"",onChange:w=>S(y.id,C=>({...C,openUrl:w.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},y.id)})})})},Mp={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)"},Fp=({value:e,noneLabel:t,ariaLabel:s,disabled:r=!1,className:o,isModelAllowed:i,onChange:a})=>{const c=Kt(C=>C.providers),u=Kt(C=>C.modelsMetadata),d=de(C=>C.hiddenModels),f=de(C=>C.isFavoriteModel),m=de(C=>C.toggleFavoriteModel),b=de(C=>C.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:h}=kd(),[p,S]=l.useState(!1),[y,v]=l.useState("");l.useEffect(()=>{p?Kt.getState().ensureModelMetadata():v("")},[p]);const x=e?c.find(C=>C.id===e.providerId):void 0,A=e&&x?(Array.isArray(x.models)?x.models:[]).find(C=>C.id===e.modelId):void 0,j=e?Cd(A,e.modelId):t,k=l.useMemo(()=>e?d.filter(C=>!(C.providerID===e.providerId&&C.modelID===e.modelId)):d,[d,e]),w=l.useCallback(C=>{a({providerId:C.providerID,modelId:C.modelID}),S(!1)},[a]);return n.jsxs(Gt,{modal:!1,open:p,onOpenChange:C=>{r||S(C)},children:[n.jsx(Ht,{asChild:!0,disabled:r,children:n.jsxs("button",{type:"button","aria-label":s,disabled:r,className:_(Nd({size:"default"}),mp,"min-w-0",o),children:[n.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?n.jsx(Ad,{providerId:e.providerId,className:"size-4 shrink-0"}):null,n.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:j})]}),n.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),n.jsx(qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:n.jsx(Id,{providers:c,favoriteModels:g,recentModels:h,modelsMetadata:u,searchQuery:y,onSearchQueryChange:v,onSelect:w,labels:{...Mp,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:k,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{a(null),S(!1)},disabled:r,autoFocus:!0,onEscape:()=>S(!1),isFavorite:C=>f(C.providerID,C.modelID),onToggleFavorite:C=>m(C.providerID,C.modelID),onReorderFavorite:(C,R)=>b(C.providerID,C.modelID,R.providerID,R.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ao="w-full max-w-none",Lp=({form:e})=>{const{name:t,setName:s,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,a=Kt(c=>c.loadProviders);return l.useEffect(()=>{a({source:"projectSettings"})},[a]),i?n.jsx(Jl,{title:"Project",divider:!1,children:n.jsxs("div",{className:Hl,children:[n.jsx($s,{label:"Name",settingsItem:"projects.name",controlClassName:ao,children:n.jsx(To,{value:t,onChange:c=>s(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),n.jsx($s,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ao,children:n.jsx(Fp,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ao,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Op=e=>{const[t,s]=l.useState(""),[r,o]=l.useState(void 0);l.useEffect(()=>{if(!e){s(""),o(void 0);return}s(e.label??""),o(e.defaultModel)},[e]);const i=l.useMemo(()=>Ed(r),[r]),a=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=l.useCallback((d,f)=>{o(d&&f?`${d}/${f}`:void 0)},[]),u=l.useCallback(async()=>{if(!e)return null;const d=t.trim();return d?{label:d,defaultModel:r??null}:null},[r,t,e]);return{name:t,setName:s,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:a,prepareSaveData:u,project:e}},Bp=450,_p=(e,t)=>{const{hasChanges:s,name:r,defaultModel:o,prepareSaveData:i}=e,a=l.useRef(!1);l.useEffect(()=>{if(!s||!r.trim()||a.current)return;const c=window.setTimeout(()=>{a.current||(a.current=!0,(async()=>{try{const u=await i();if(u)try{await t(u)}catch{oe.error("Failed to save project settings")}}finally{a.current=!1}})())},Bp);return()=>{window.clearTimeout(c)}},[o,s,r,t,i])},zp=({project:e,onIdentitySave:t})=>{const s=Op(e),r=l.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=l.useCallback(async i=>{await t(i)},[t]);return _p(s,o),!e||!r?null:n.jsxs("div",{className:"space-y-0",children:[n.jsx(Lp,{form:s}),n.jsx(Tp,{projectRef:r})]})},Up=6e4,$p=3e4,Es=new Map;let ia=0,aa=!1;const Kp=()=>{if(aa||typeof window>"u")return;aa=!0;const e=()=>{const t=Date.now();t-ia<$p||typeof document<"u"&&document.hidden||(ia=t,ht(async()=>{const{getRegisteredRuntimeAPIs:s}=await import("./index-fmzQmSSv.js").then(r=>r.cJ);return{getRegisteredRuntimeAPIs:s}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:s})=>{const r=s()?.github;r&&Ur.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},Ur=$n()(zr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Tt(),resetForRuntimeSwitch:s=>{const r=s??Tt();Es.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(s,r)=>{Kp();const o=Tt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),a=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&a-i.fetchedAt<Up)return i.status;const c=Es.get(o);if(c)return c;const u=s??null;if(!u)return t().status;const d=(async()=>{e({isLoading:!0});try{const f=await u.status();return Tt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Tt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();Es.set(o,d);try{return await d}finally{Es.get(o)===d&&Es.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&gs(e=>{Ur.getState().resetForRuntimeSwitch(e.runtimeKey)});const Wp=()=>Ur(e=>(e.status?.hosts??[]).find(s=>s.authenticated)?.login??null),dw=e=>{if(e.byteLength<4)return null;const t=new DataView(e).getUint32(0);if(t<=0||4+t>e.byteLength)return null;try{const s=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(s?.width)||!Number.isFinite(s?.height)?null:{header:s,jpeg:new Uint8Array(e,4+t)}}catch{return null}},fw=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},hw=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",pw=50*1024*1024-1,mw=[250,1e3,2e3,4e3,8e3],Gp=(e,t)=>{const s=r=>{let o=r>>>0;for(const i of`${e}\0${t}`)o^=i.codePointAt(0)??0,o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0")};return`tab-${s(2166136261)}${s(16777619)}`},gw=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),bw=(e,t,s,r)=>{if(s.width<=0||s.height<=0)return null;const o=(e-s.left)/s.width*r.width,i=(t-s.top)/s.height*r.height;return{x:Math.round(Math.max(0,Math.min(r.width-1,o))*100)/100,y:Math.round(Math.max(0,Math.min(r.height-1,i))*100)/100}},xw=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,yw=(e,t)=>{const s=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(s)&&s>0?s:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},bs=async(e,t)=>{const s=await e.json().catch(()=>null);return new Error(typeof s?.error=="string"?s.error:t)},ww=async()=>{const e=await tt("/api/server-browser/status");if(!e.ok)throw await bs(e,"Could not check the server browser");return await e.json()},vw=async e=>{const t=await tt("/api/server-browser/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await bs(t,"Could not save the server browser settings");return await t.json()},Sw=async(e,t)=>{const s=await tt("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!s.ok)throw await bs(s,"Could not find dev servers");const r=await s.json();return Array.isArray(r.servers)?r.servers:[]},jw=async(e,t,s)=>{const r=await tt("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:s});if(!r.ok)return{framing:"unknown"};const o=await r.json().catch(()=>null);return o?.framing==="refused"||o?.framing==="allowed"?{framing:o.framing,reason:o.reason==="frame-ancestors"?"frame-ancestors":"x-frame-options"}:{framing:"unknown"}},kw=async()=>{const e=await tt("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await bs(e,"Could not clear browsing data")},Cw=(e,t)=>{const s=Gp(e,t);tt(`/api/server-browser/tabs/${encodeURIComponent(s)}`,{method:"DELETE"}).catch(()=>{})},Aw=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),s=await tt(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!s.ok)throw await bs(s,`Could not upload ${e.name}`);const r=await s.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},Nw=async(e,t)=>{const s=await tt(`/api/server-browser/downloads/${encodeURIComponent(e)}`);if(!s.ok)throw await bs(s,`Could not download ${t}`);const r=await s.blob(),o=URL.createObjectURL(r);try{const i=document.createElement("a");i.href=o,i.download=t,i.rel="noopener",document.body.appendChild(i),i.click(),i.remove()}finally{setTimeout(()=>URL.revokeObjectURL(o),6e4)}},Iw=async(e,t,s)=>{const r=await Lf();return{socket:Of(Bf().websocket("/api/server-browser/ws",{tab:e,url:t,popup:s},r)),urlAuthToken:r}},Ew=e=>{Ff(e)},ur=100;function Dw(){const e=de(C=>C.isArchivePageOpen),t=de(C=>C.setArchivePageOpen),s=de(C=>C.setActiveMainTab),r=Fe(C=>C.setCurrentSession),o=Fe(C=>C.unarchiveSession),i=fs(C=>C.homeDirectory),a=Mo({archived:!0}),[c,u]=l.useState(""),[d,f]=l.useState(null),[m,b]=l.useState(ur),g=c.trim().toLowerCase(),h=l.useMemo(()=>e?[...a].sort((C,R)=>(R.time?.archived??0)-(C.time?.archived??0)):[],[a,e]),p=l.useMemo(()=>{const C=new Map;for(const R of h){const L=De(_s(R))??"",U=C.get(L);if(U){U.sessions.push(R);continue}C.set(L,{directory:L,label:L?Vi(L,i)||L:"other projects",sessions:[R]})}return[...C.values()].sort((R,L)=>L.sessions.length-R.sessions.length)},[i,h]),S=l.useMemo(()=>g?h.filter(C=>(C.title??"").toLowerCase().includes(g)):d===null?h:p.find(C=>C.directory===d)?.sessions??[],[p,g,d,h]),y=S.slice(0,m),v=S.length-y.length,x=a.length,A=l.useCallback(C=>{f(C),b(ur)},[]),j=l.useCallback(C=>{const R=De(_s(C));r(C.id,R??void 0),s("chat"),t(!1)},[s,r,t]),k=l.useCallback(C=>{o(C.id).then(R=>{R?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const w=(C,R,L,U,G,$,q)=>n.jsxs("div",{className:"group/dir relative",children:[n.jsxs("button",{type:"button",onClick:G,title:$,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",q?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",U?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[n.jsx("span",{className:"min-w-0 flex-1 truncate",children:R}),n.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:L})]}),q?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>Hs.requestDelete({sessions:q,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 ${R}`,children:n.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},C);return n.jsx(Ju,{open:e,onOpenChange:t,children:n.jsxs(Xu,{children:[n.jsx(Zu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:n.jsxs(ed,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[n.jsx(td,{className:"sr-only",children:"Archived sessions"}),n.jsx(nd,{className:"sr-only",children:"Browse and restore archived sessions."}),n.jsx(sd,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:n.jsx(D,{name:"close",className:"size-4"})}),n.jsxs("div",{className:"flex min-h-0 flex-1",children:[n.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:n.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[w("__all__","All directories",x,d===null,()=>A(null)),p.map(C=>w(C.directory||"__none__",C.label,C.sessions.length,d===C.directory,()=>A(C.directory),C.directory||void 0,C.sessions))]})}),n.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[n.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[n.jsxs("div",{className:"relative min-w-0 flex-1",children:[n.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),n.jsx("input",{value:c,onChange:C=>{u(C.target.value),b(ur)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),n.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:S.length===1?`${S.length} archived session`:`${S.length} archived sessions`})]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:n.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[y.length===0?n.jsx("div",{className:"py-10 text-center text-muted-foreground",children:n.jsx("p",{className:"typography-ui-label font-semibold",children:g?"No matching archived sessions":"No archived sessions"})}):y.map(C=>{const R=De(_s(C))??"",L=R?Vi(R,i)||R:null;return n.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>j(C),role:"button",tabIndex:0,onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),j(C))},children:[n.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:dn(C)}),g&&L?n.jsx("span",{className:"max-w-40 flex-shrink-0 truncate typography-micro text-subtle-foreground",title:R,children:L}):null,n.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:oh(C.time?.archived??C.time?.updated??C.time?.created??Date.now())}),n.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),k(C)},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 ${dn(C)}`,children:n.jsx(D,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),n.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),Hs.requestDelete({sessions:[C],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 ${dn(C)}`,children:n.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},C.id)}),v>0?n.jsx("button",{type:"button",onClick:()=>b(C=>C+ur),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-subtle-foreground leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const Hp=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,s=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+s+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,s);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},qp=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,s=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+s+r},Jt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Yp=e=>{if(!e||typeof e!="object")return null;const t=Jt(e.input),s=Jt(e.output),r=Jt(e.cacheRead),o=Jt(e.cacheWrite);return{input:t,output:s,reasoning:null,cacheRead:r,cacheWrite:o,total:t+s+r+o}},la=e=>{const t=Yp(e.info.usage);if(t)return t;const s=e.info.tokens,r=s!==void 0?s:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Jt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=Jt(o.input),a=Jt(o.output),c=Jt(o.reasoning),u=Jt(o.cache?.read),d=Jt(o.cache?.write);return{input:i,output:a,reasoning:c,cacheRead:u,cacheWrite:d,total:i+a+c+u+d}},Xl=380,lo=8,Vp=140;function Qp({open:e,onClose:t,anchorRef:s,closeOnWheel:r=!1}){const o=l.useRef(null),i=l.useRef(null),[a,c]=l.useState(e),[u,d]=l.useState(!1),[f,m]=l.useState(null),{enabled:b}=bi();return l.useLayoutEffect(()=>{if(!e||!b||!a)return;const g=()=>{const S=s.current?.getBoundingClientRect(),y=i.current?.getBoundingClientRect();if(!S||!y){m(null);return}const v=S.left-y.left;m(Math.min(Math.max(v,lo),Math.max(lo,y.width-Xl-lo)))};g();const h=i.current;if(typeof ResizeObserver>"u"||!h)return;const p=new ResizeObserver(g);return p.observe(h),()=>p.disconnect()},[s,b,e,a]),l.useEffect(()=>{if(e){c(!0),d(!1);return}if(!a)return;d(!0);const g=window.setTimeout(()=>{c(!1),d(!1)},Vp);return()=>window.clearTimeout(g)},[e,a]),l.useEffect(()=>{if(!e)return;const g=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[t,e]),l.useEffect(()=>{if(!e)return;const g=h=>{const p=h.target;if(!(p instanceof Node)){t();return}o.current?.contains(p)||s.current?.contains(p)||t()};return document.addEventListener("pointerdown",g,!0),r&&document.addEventListener("wheel",g,!0),()=>{document.removeEventListener("pointerdown",g,!0),r&&document.removeEventListener("wheel",g,!0)}},[s,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:u,anchorLeft:f,isPopover:b&&f!==null}}const ca=(e,t)=>{if(!e||typeof e!="object")return;const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0},Er=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),dr=({icon:e,iconNode:t,label:s,children:r})=>n.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[n.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?n.jsx(D,{name:e,className:"size-[18px]"}):null)}),n.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:s}),n.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Jp=({open:e,onClose:t,anchorRef:s,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:c,anchorLeft:u,isPopover:d}=Qp({open:e,onClose:t,anchorRef:s,closeOnWheel:!0});return a?n.jsxs("div",{ref:i,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[n.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:_("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",d?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...d?{top:8,left:u??8,width:`min(${Xl}px, calc(100% - 16px))`}:null},children:n.jsx("div",{className:"space-y-1",children:r?n.jsxs(n.Fragment,{children:[n.jsx(dr,{iconNode:n.jsx(dl,{percentage:r.percentage}),label:"Context",children:n.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[n.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),n.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?n.jsxs(n.Fragment,{children:[n.jsx(dr,{icon:"stack",label:"Cache read",children:n.jsx("span",{className:"tabular-nums",children:Er(r.cacheRead)})}),n.jsx(dr,{icon:"edit",label:"Cache write",children:n.jsx("span",{className:"tabular-nums",children:Er(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?n.jsx(dr,{icon:"check",label:"Cache hit",children:n.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):n.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),n.jsx("style",{children:`
3
- @keyframes session-metadata-in {
4
- from { opacity: 0; transform: translateY(-8px) scale(0.985); }
5
- to { opacity: 1; transform: translateY(0) scale(1); }
6
- }
7
- @keyframes session-metadata-out {
8
- from { opacity: 1; transform: translateY(0) scale(1); }
9
- to { opacity: 0; transform: translateY(-6px) scale(0.985); }
10
- }
11
- `})]}):null},Xp=l.memo(function({open:t,onOpenChange:s,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const a=l.useRef(null),c=Dd(r??""),u=Kt(E=>E.providers),d=Kt(E=>E.currentProviderId),f=Kt(E=>E.currentModelId),m=Kt(E=>E.getCurrentModel()),b=Kt(E=>E.getModelMetadata);Kt(E=>E.modelsMetadata.size);const g=Rd(l.useCallback(E=>r?E.sessionModelSelections.get(r)??null:null,[r])),h=l.useMemo(()=>{for(let E=c.length-1;E>=0;E-=1){const T=c[E]?.info;if(T.role!=="user")continue;const I=T.model,M=I?.providerID??I?.providerId,W=I?.modelID??I?.modelId,K=typeof M=="string"&&M.trim().length>0?M:void 0,O=typeof W=="string"&&W.trim().length>0?W:void 0;if(K&&O)return{providerID:K,modelID:O}}return null},[c]),p=l.useMemo(()=>{for(let E=c.length-1;E>=0;E-=1){const T=c[E];if(T?.info.role==="assistant"&&la(T).total>0)return T}return null},[c]),S=h??(()=>{const E=p?.info.model,T=E?.providerID??E?.providerId,I=E?.modelID??E?.modelId;return T&&I?{providerID:T,modelID:I}:null})()??(g?{providerID:g.providerId,modelID:g.modelId}:null)??(d&&f?{providerID:d,modelID:f}:null),v=(S?u.find(E=>E.id===S.providerID):void 0)?.models.find(E=>E.id===S?.modelID),x=S?b(S.providerID,S.modelID):void 0,A=ca(v?.limit,"context")??x?.limit?.context??ca(m?.limit,"context")??0,j=p?la(p):null,k=p?.info?.usage,w=k?qp(k):j?.total??0,C=!i&&w>0&&A>0?Math.min(w/A*100,999):null,R=C!==null?`${Er(w)}/${Er(A)}`:null,L=C===null?"":C>=90?"text-[var(--status-error)]":C>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",U=j?.cacheRead??null,G=j?.cacheWrite??null,$=j?Hp({input:j.input,cache:{read:j.cacheRead,write:j.cacheWrite}}):{percent:0,hasInput:!1},q=$.hasInput?$.percent:null,F=C!==null&&R?{percentage:C,tokens:R,colorClass:L,cacheRead:U,cacheWrite:G,cacheHitPercent:q}:null;return n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:a,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":t,onClick:()=>s(E=>!E),style:{touchAction:"manipulation"},children:F?n.jsx(dl,{percentage:F.percentage,size:20,className:"size-5 -rotate-90"}):n.jsx(D,{name:"pie-chart",className:"size-5"})}),n.jsx(Jp,{open:t,onClose:()=>s(!1),anchorRef:a,contextDisplay:F})]})}),xs="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Zp="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",em=l.memo(function({visible:t=!0,title:s,ariaLabel:r,onClick:o,className:i,Icon:a,iconClassName:c,pressed:u=!1}){return t?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":u,className:_(i??xs,u&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(D,{name:a,className:c??"h-[18px] w-[18px]"})})}),n.jsx(Ge,{children:n.jsx("p",{children:s})})]}):null}),tm=e=>{let t=2166136261;for(let s=0;s<e.length;s+=1)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return(t>>>0).toString(36).padStart(7,"0").slice(-6)},Zl=({variant:e="desktop"})=>{const t=Bn(f=>f.entries),[s,r]=l.useState(!1),o=l.useRef(null),i=l.useMemo(()=>[...t.values()].sort((f,m)=>m.startedAt-f.startedAt),[t]),a=i.filter(f=>f.state&&f.state.phase!=="failed"||fl(f)).length,c=l.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),u=l.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(l.useEffect(()=>()=>c(),[c]),i.length===0)return null;const d=f=>{if(!Fd(f))return;const m=f.receipt;if(!m)return;const b=Fe.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:m.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:m.path}),Bn.getState().clearEntry(f.key),de.getState().setActiveMainTab("chat"),r(!1)};return n.jsxs(Gt,{open:s,onOpenChange:r,children:[n.jsx(Ht,{asChild:!0,children:n.jsxs("button",{type:"button",className:_(e==="desktop"?xs:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&u()},children:[a>0?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner"}):n.jsx(D,{name:"task",className:"size-[18px]"}),n.jsx("span",{children:"Background tasks"})]})}),n.jsxs(qt,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:u,children:[n.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[n.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),n.jsx("p",{className:"typography-micro text-muted-foreground",children:a===1?"1 worktree is being created":`${a} worktrees are being created`})]}),n.jsx("div",{className:"divide-y divide-border",children:i.map(f=>n.jsx(nm,{entry:f,onOpen:()=>d(f)},f.key))})]})]})},nm=({entry:e,onOpen:t})=>{const s=e.state?.phase==="failed",r=!!(e.state&&!s),o=fl(e),i=Pd(e),a=s?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":o?"Sending prompt...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return n.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[n.jsx("div",{className:"mt-0.5 shrink-0",children:r||o?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner"}):s?n.jsx(D,{name:"alert",className:"size-4 text-[var(--status-error)]"}):n.jsx(D,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),n.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:s?e.state?.error:e.path??e.intent.sourceDirectory})]}),s?n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.failedSend?n.jsx(Ae,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${tm(e.key)})`,onClick:()=>{const c=Td(e.key),u=Md(c,"background-task");u&&oe.error(u.title,{description:u.description})},children:"Restore draft"}):null,n.jsx(Ae,{type:"button",variant:"ghost",size:"xs",onClick:()=>Bn.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(Ae,{type:"button",size:"xs",onClick:t,children:"Open"}),n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Bn.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:n.jsx(D,{name:"close",className:"size-3.5"})})]}):null]})},sm=["pinned","today","yesterday","thisWeek","lastWeek","older"],rm={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},om=(e,t)=>{if(e==="sunday")return 0;if(e==="monday")return 1;try{const s=t||(typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().locale:"en-US");if(typeof Intl<"u"&&typeof Intl.Locale=="function"){const r=new Intl.Locale(s),i=(typeof r.getWeekInfo=="function"?r.getWeekInfo():r.weekInfo)?.firstDay;if(i===7||i===0)return 0;if(i!==void 0)return 1}}catch{}return 1},Xo=(e,t)=>{const s=new Date(e);s.setHours(0,0,0,0);const r=s.getTime(),o=new Date(r);o.setDate(o.getDate()-1),o.setHours(0,0,0,0);const i=o.getTime(),c=(s.getDay()-t+7)%7,u=new Date(r);u.setDate(u.getDate()-c),u.setHours(0,0,0,0);const d=u.getTime(),f=new Date(d);f.setDate(f.getDate()-7),f.setHours(0,0,0,0);const m=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:d,startOfLastWeek:m}},im=(e,t)=>!Number.isFinite(e)||e<=0?"older":e>=t.startOfToday?"today":e>=t.startOfYesterday?"yesterday":e>=t.startOfThisWeek?"thisWeek":e>=t.startOfLastWeek?"lastWeek":"older",am=(e,t)=>{const s={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,a=e.length;for(let u=0;u<a;u++){const d=e[u];if(o(d))s.pinned.push(d);else{const f=r(d),m=im(f,i);s[m].push(d)}}const c=[];for(const u of sm){const d=s[u];d.length>0&&c.push({id:u,items:d})}return c},lm=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},cm=(e,t)=>{const[s,r]=l.useState(0),o=l.useMemo(()=>e?Xo(Date.now(),t):null,[e,t,s]),i=o?.startOfToday??null;return l.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const a=Date.now(),c=window.setTimeout(()=>{r(d=>d+1)},Math.max(50,lm(a)-a+50)),u=()=>{document.visibilityState==="visible"&&Xo(Date.now(),t).startOfToday!==i&&r(d=>d+1)};return document.addEventListener("visibilitychange",u),()=>{window.clearTimeout(c),document.removeEventListener("visibilitychange",u)}},[i,t,s]),o},um=e=>({getOrderedGroups:l.useCallback((s,r)=>{const o=e.get(s);if(!o||o.length===0)return r;const i=new Map(r.map(u=>[u.id,u])),a=[];o.forEach(u=>{const d=i.get(u);d&&(a.push(d),i.delete(u))});const c=[];return r.forEach(u=>{i.has(u.id)&&c.push(u)}),[...c,...a]},[e])}),dm=[],fm=e=>{const{normalizedProjects:t,getSessionsForProject:s,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:c,buildGroupedSessions:u,hasSessionSearchQuery:d,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:m,buildGroupSearchText:b,foldersMap:g,alwaysIncludeArchived:h=!1}=e,p=l.useRef(new Map),S=d||h,y=l.useMemo(()=>{const R=p.current,L=new Map;let U=0,G=0;const $=(F,E)=>F.length===E.length&&F.every((T,I)=>T===E[I]),q=t.map(F=>{const E=s(F.id),T=S?r(F.id):dm,I=i.has(F.id)?!!i.get(F.id):c,M=a.get(F.id)??null,W=o.get(F.normalizedPath)??[],K=R.get(F.id);if(K&&K.project===F&&$(K.activeSessions,E)&&$(K.archivedSessions,T)&&K.rootBranch===M&&K.isRepo===I&&K.worktrees===W&&K.buildGroupedSessions===u)return U+=1,L.set(F.id,K),K.section;G+=1;const O=Pl([...E,...T]),ae=u(O,F.normalizedPath,W,M,I),X={project:F,groups:ae};return L.set(F.id,{project:F,activeSessions:E,archivedSessions:T,rootBranch:M,isRepo:I,worktrees:W,buildGroupedSessions:u,section:X}),X});return p.current=L,U>0&&Wt("ui.sidebar.project_section.reused",U),G>0&&Wt("ui.sidebar.project_section.rebuilt",G),q},[t,s,r,S,o,i,c,u,a]),v=l.useMemo(()=>y,[y]),x=l.useMemo(()=>{const R=new WeakMap;if(!d)return R;const L=U=>U.reduce((G,$)=>G+1+L($.children),0);return v.forEach(U=>{U.groups.forEach(G=>{const $=m(G.sessions,f),q=L($),F=b(G).includes(f),E=De(G.directory??null),I=(E?g[E]??[]:[]).filter(M=>M.name.toLowerCase().includes(f)).length;R.set(G,{filteredNodes:$,matchedSessionCount:q,folderNameMatchCount:I,groupMatches:F,hasMatch:F||q>0||I>0})})}),R},[d,v,m,f,b,g]),A=l.useMemo(()=>d?v.map(R=>({...R,groups:R.groups.filter(L=>x.get(L)?.hasMatch===!0)})).filter(R=>R.groups.length>0):v,[d,v,x]),j=d?A:v,k=l.useRef(new WeakMap),w=l.useMemo(()=>{const R=k.current;return j.map(L=>{const U=R.get(L);if(U&&U.query===f)return U.section;const G=L.groups,$=G.flatMap(I=>d?x.get(I)?.filteredNodes??[]:I.sessions),q=G.map(I=>({scopeKey:I.folderScopeKey??De(I.directory??null),directory:I.directory??null})).filter(I=>!!I.scopeKey),F=G.find(I=>I.isMain)??null,E={id:"flat",label:F?.label??"",branch:F?.branch??null,description:F?.description??null,isMain:!0,directory:F?.directory??L.project.normalizedPath,folderScopeKey:F?.folderScopeKey??L.project.normalizedPath,folderScopes:q,sessions:$};if(d){const I=G.map(M=>x.get(M)).filter(M=>!!M);x.set(E,{filteredNodes:$,matchedSessionCount:I.reduce((M,W)=>M+W.matchedSessionCount,0),folderNameMatchCount:I.reduce((M,W)=>M+W.folderNameMatchCount,0),groupMatches:I.some(M=>M.groupMatches),hasMatch:I.some(M=>M.hasMatch)})}const T={project:L.project,groups:[E]};return R.set(L,{query:f,section:T}),T})},[x,d,f,j]),C=l.useMemo(()=>d?j.reduce((R,L)=>R+L.groups.reduce((U,G)=>{const $=x.get(G);if(!$)return U;const q=$.folderNameMatchCount+($.groupMatches?1:0);return U+$.matchedSessionCount+q},0),0):0,[d,j,x]);return{projectSections:y,visibleProjectSections:v,groupSearchDataByGroup:x,searchableProjectSections:A,sectionsForRender:j,flatSectionsForRender:w,searchMatchCount:C}},hm=e=>{const{projectSections:t,activeProjectId:s,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:a,newSessionDraftOpen:c,mobileVariant:u,openNewSessionDraft:d,setActiveMainTab:f,setSessionSwitcherOpen:m}=e,b=l.useMemo(()=>{const h=new Map,p=new Map,S=(y,v,x,A)=>{h.has(y)||h.set(y,new Map);const j=h.get(y);A.forEach(k=>{const w=De(k.session.directory??x??v);j.set(k.session.id,{directory:w}),p.has(y)||p.set(y,{id:k.session.id,directory:w}),k.children.length>0&&S(y,v,w,k.children)})};return t.forEach(y=>{y.groups.forEach(v=>{S(y.project.id,y.project.normalizedPath,v.directory,v.sessions)})}),{metaByProject:h,firstSessionByProject:p}},[t]),g=l.useRef(null);l.useLayoutEffect(()=>{if(!s)return;if(c){g.current=s;return}if(g.current===s)return;const h=t.find(k=>k.project.id===s);if(!h)return;g.current=s;const p=b.metaByProject.get(s);if(i&&p&&p.has(i)){o(k=>{if(k.get(s)===i)return k;const w=new Map(k);return w.set(s,i),w});return}const S=i?Array.from(b.metaByProject.entries()).some(([k,w])=>k!==s&&w.has(i)):!1;if(i&&p&&!S)return;if(!p||p.size===0){f("chat"),u&&m(!1),d({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath});return}const y=r.get(s),v=y&&p.has(y)?y:null,x=b.firstSessionByProject.get(s)?.id??null,A=v??x;if(!A||A===i)return;const j=p.get(A)?.directory??null;a(A,j,{keepPanelOpen:!0})},[s,r,i,a,c,u,d,t,b,f,m,o]),l.useEffect(()=>{if(!s||!i)return;const h=b.metaByProject.get(s);!h||!h.has(i)||o(p=>{if(p.get(s)===i)return p;const S=new Map(p);return S.set(s,i),S})},[s,i,b,o])},pm=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...s})=>{const r=Fe(c=>c.currentSessionId),o=Fe(c=>!!c.newSessionDraft?.open),[i,a]=l.useState(()=>new Map(e));return hm({...s,activeSessionByProject:i,setActiveSessionByProject:a,currentSessionId:r,newSessionDraftOpen:o}),l.useEffect(()=>{t(i)},[i,t]),null},ua=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],mm=e=>{let t=5381;for(let s=0;s<e.length;s+=1)t=t*33^e.charCodeAt(s);return t>>>0},gm=(e,t,s)=>(s.get(e)??0)>0?e:t.get(e)??null,ec=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=mm(e.trim())%ua.length;return ua[t]},bm=(e,t)=>{const s=ec(e);return s?t?.active?`color-mix(in srgb, ${s} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${s} 18%, transparent)`:null},da=e=>!!e.time?.archived,xm=e=>{const t=l.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),s=l.useCallback(i=>{const a=De(i.directory??null)??"";return`${dn(i)} ${a}`.toLowerCase()},[]),r=l.useCallback((i,a)=>a?i.flatMap(c=>{if(s(c.session).includes(a))return[c];const d=r(c.children,a);return d.length===0?[]:[{...c,children:d}]}):i,[s]),o=l.useCallback((i,a,c=[],u,d)=>{const f=De(a??null),m=Pl(i).sort(hl(e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(m.map(k=>[k.id,k])),g=new Map,h=new Map;m.forEach(k=>{const w=k.parentID??null,C=w?b.get(w):null,R=C&&da(C)===da(k)?w:null;g.set(k.id,R),R&&h.set(R,(h.get(R)??0)+1)});const p=c.map(k=>({worktree:k,directory:De(k.path)})).filter(k=>!!k.directory&&!k.worktree.isPrimary).sort((k,w)=>w.directory.length-k.directory.length),S=(k,w)=>w===k||w.startsWith(`${k}/`),y=k=>{const w=De(k.directory??null);return w?p.find(C=>S(C.directory,w))?.worktree??null:null},v=(k,w)=>{const C=gm(k.id,g,h);return{session:k,children:[],worktree:w,forkColorId:C}},x=[],A=new Map;for(const k of p)A.set(k.directory,[]);m.forEach(k=>{const w=y(k),C=v(k,w);w?A.get(De(w.path)??"")?.push(C):x.push(C)});const j=[{id:"root",label:d&&u&&u!=="HEAD"?`project root: ${u}`:"project root",branch:u??null,description:f?Bo(f,e.homeDirectory):null,isMain:!0,worktree:null,directory:f,folderScopeKey:f,sessions:x}];for(const{worktree:k,directory:w}of p)j.push({id:`worktree:${w}`,label:k.branch||(k.detached?"Detached HEAD":k.name),branch:k.branch,description:Bo(w,e.homeDirectory),isMain:!1,worktree:k,directory:w,folderScopeKey:w,sessions:A.get(w)??[]});return j},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:s,filterSessionNodesForSearch:r,buildGroupedSessions:o}},ym=({mobileVariant:e,isTablet:t})=>!e&&!t,wm=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:s,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{l.useEffect(()=>{if(!e||!t||typeof window>"u")return;const i=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(i)},[e,t,r]),l.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=a=>{o.current&&(o.current.contains(a.target)||s(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,s,o])},co=(e,t)=>t===1?`Could not ${e} the session`:`Could not ${e} the sessions`,fa=(e,t)=>{if(!e.directory)return;const s=qs.getState();Zs(s.ids,e.directory,e.sessionId)!==t&&s.toggle({directory:e.directory,sessionId:e.sessionId})},tc=async(e,t={})=>{if(e.length===0)return;const s=qs.getState(),r=new Set(e.filter(g=>Zs(s.ids,g.directory,g.sessionId)).map(g=>g.sessionId));for(const g of e)r.has(g.sessionId)&&fa(g,!1);const o=g=>{for(const h of g)r.has(h.sessionId)&&fa(h,!0)},i=[...new Set(e.flatMap(g=>[g.sessionId,...g.forkIds]))];let a;try{a=await Fe.getState().archiveSessions(i)}catch(g){console.warn("[session-archive] archive failed",g),a={archivedIds:[],failedIds:i}}const c=new Set(a.archivedIds),u=e.filter(g=>c.has(g.sessionId));if(o(e.filter(g=>!c.has(g.sessionId))),u.length===0){c.size>0&&Fe.getState().unarchiveSessions([...c]),oe.error(co("archive",e.length));return}const f=e.length===1&&t.title?`Archived “${t.title}”`:`Archived ${Qi(u.length)}`,m=a.archivedIds;oe.success(f,{action:{label:"Undo",onClick:()=>{o(u),Fe.getState().unarchiveSessions(m).then(({failedIds:g})=>{g.length>0&&oe.error(co("unarchive",m.length))}).catch(g=>{console.warn("[session-archive] undo failed",g),oe.error(co("unarchive",m.length))})}}});const b=i.length-c.size;b>0&&oe.error(`Could not archive ${Qi(b)}`)},vm=e=>{const[t,s]=l.useState(null),r=l.useRef(null);l.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=l.useCallback((x,A,j)=>{_o("navigation.session_select"),de.getState().closeMainSurfaces();const k=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},w=j?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),x===Fe.getState().currentSessionId){e.allowReselect&&w&&e.onSessionSelected?.(x),k();return}_o("navigation.session_state_set"),e.setCurrentSession(x,A??null),w&&e.onSessionSelected?.(x),k()},[e]),i=l.useCallback((x,A)=>{e.setEditingId(x),e.setEditTitle(A)},[e]),a=l.useCallback(async x=>{if(!e.editingId)return;const A=(x??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=l.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),u=l.useCallback(async(x,A)=>{try{return(await fn(x)).ok?(s(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{s(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),d=l.useCallback(async x=>{const A=await e.shareSession(x.id);if(!A?.share?.url){oe.error("Unable to share session");return}const j=await u(A.share.url,x.id);oe[j?"success":"warning"]("Session shared",{description:j?"Share link copied to clipboard.":"Failed to copy URL"})},[e,u]),f=l.useCallback((x,A)=>{u(x,A).then(j=>{j||oe.error("Failed to copy URL")})},[u]),m=l.useCallback(x=>{fn(x).then(A=>{if(A.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),b=l.useCallback(async x=>{await e.unshareSession(x)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),g=l.useCallback(x=>{const A=[],j=k=>{(e.childrenMap.get(k)??[]).forEach(C=>{A.push(C),j(C.id)})};return j(x),A},[e.childrenMap]),h=l.useCallback((x,A)=>A?x:x.filter(j=>!j.time?.archived),[]),p=l.useCallback(async(x,A)=>{const j=A?.descendantIds??h(g(x.id),!0).map(C=>C.id);if(j.length===0){await e.deleteSession(x.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const{deletedIds:k,failedIds:w}=await e.deleteSessions([x.id,...j]);if(w.length===0){const C=k.length;oe.success(C===1?`Deleted ${C} session`:`Deleted ${C} sessions`)}else oe.error("Failed to delete session")},[e,g,h]),S=l.useCallback((x,A)=>{const j=A?.archivedBucket===!0||A?.hardDelete===!0,k=h(g(x.id),j).map(w=>w.id);if(!j){tc([{sessionId:x.id,directory:x.directory??null,forkIds:k}],{title:dn(x,"Untitled session")});return}if(!e.showDeletionDialog||A?.skipConfirm===!0){p(x,{descendantIds:k});return}e.setDeleteSessionConfirm({session:x,descendantCount:k.length,descendantIds:k})},[e,g,p,h]),y=l.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:x,descendantIds:A}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await p(x,{descendantIds:A})},[e,p]),v=l.useCallback(async x=>{await e.unarchiveSession(x.id)?oe.success("Session unarchived"):oe.error("Could not unarchive the session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:a,handleCancelEdit:c,handleShareSession:d,handleCopyShareUrl:f,handleCopySessionId:m,handleUnshareSession:b,handleDeleteSession:S,handleRestoreSession:v,confirmDeleteSession:y}},Sm=e=>{const{safeStorage:t,keys:s,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:a}=e,c=l.useRef(null),u=l.useRef(null),d=l.useCallback(()=>{const m=u.current;if(u.current=null,c.current=null,!m)return;const{projects:b}=ct.getState(),g=b.map(h=>({...h,sidebarCollapsed:m.has(h.id)}));Al({projects:g}).catch(()=>{})},[]),f=l.useCallback(m=>{typeof window>"u"||(u.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{d()},700))},[d]);return l.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,u.current=null},[]),l.useEffect(()=>{try{const m=t.getItem(s.sessionExpanded);if(m){const g=JSON.parse(m);Array.isArray(g)&&i(new Set(g.filter(h=>typeof h=="string")))}const b=t.getItem(s.projectCollapse);if(b){const g=JSON.parse(b);Array.isArray(g)&&a(new Set(g.filter(h=>typeof h=="string")))}}catch{}},[s.projectCollapse,s.sessionExpanded,t,a,i]),l.useEffect(()=>{try{const m=Object.fromEntries(r.entries());t.setItem(s.groupOrder,JSON.stringify(m))}catch{}},[r,s.groupOrder,t]),l.useEffect(()=>{try{t.setItem(s.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,s.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},jm=3;let Dr=0;const nc=[],km=()=>Dr<jm?(Dr+=1,Promise.resolve()):new Promise(e=>{nc.push(e)}),Cm=()=>{const e=nc.shift();if(e){e();return}Dr=Math.max(0,Dr-1)},Am=async e=>{await km();try{return await e()}finally{Cm()}},Nm=5*6e4,Im=e=>{const{normalizedProjects:t,enabled:s=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:a}=Un(),c=pl(h=>h.ensureStatus),u=l.useMemo(()=>t.map(h=>h.normalizedPath).slice().sort().join("\0"),[t]),d=l.useRef(null);l.useEffect(()=>{if(!s||!a||t.length===0){d.current=null,o(new Map);return}const h=`${Tt()}\0${u}`;d.current!==h&&(d.current=h,t.forEach(p=>{Am(()=>c(p.normalizedPath,a))}))},[s,t,u,a,c,o]);const f=l.useRef(null);l.useEffect(()=>{if(!s){f.current=null;return}const h=new Map;t.forEach(S=>{h.set(S.id,r.get(S.normalizedPath)?.isGitRepo??null)});const p=t.map(S=>`${S.id}:${String(h.get(S.id))}`).join("|");f.current!==p&&(f.current=p,o(h))},[s,t,u,r,o]);const m=l.useMemo(()=>t.map(h=>{const p=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${p}`}).join("|"),[t,r]),b=l.useRef(new Map),g=l.useRef(new Map);l.useEffect(()=>{if(!s)return;let h=!1;const p=setTimeout(()=>{(async()=>{const y=new Set(t.map(k=>k.id));for(const k of b.current.keys())y.has(k)||(b.current.delete(k),g.current.delete(k));const v=Date.now();if(t.filter(k=>{const w=r.get(k.normalizedPath);if(w?.isGitRepo===!1)return b.current.delete(k.id),g.current.delete(k.id),!1;if(w?.isGitRepo!==!0||w.branch===null)return!1;const C=w.branch.trim(),R=`${k.normalizedPath}\0${C}`,L=b.current.get(k.id);if(L===R){const U=g.current.get(k.id);return U&&(U.at=v),!1}return!(L!==void 0&&v-(g.current.get(k.id)?.at??0)<Nm)}).length===0)return;const A=[];if(t.forEach(k=>{const w=r.get(k.normalizedPath)?.branch?.trim()??"",C=`${k.normalizedPath}\0${w}`;w&&A.push({id:k.id,inputKey:C,branch:w})}),h||A.length===0)return;const j=Date.now();i(k=>{const w=new Map(k);return A.forEach(({id:C,branch:R})=>{R&&w.set(C,R)}),w}),A.forEach(({id:k,inputKey:w,branch:C})=>{b.current.set(k,w),C&&g.current.set(k,{branch:C,at:j})})})()},150);return()=>{h=!0,clearTimeout(p)}},[s,t,m,r,i])},Em=e=>{const{ownership:t}=e,s=l.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=l.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:s,getArchivedSessionsForProject:r}},Dm=e=>{const t=new Map;for(const s of e){const r=_s(s);r&&t.set(s.id,{directory:r,sessionId:s.id})}return t},Rm=(e,t)=>{if(!e)return[];const s=[];return e.forEach((r,o)=>{t.has(o)||s.push(r)}),s},Pm=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:s,sessions:r}=e,o=l.useRef(null);l.useEffect(()=>{if(!t||!s)return;const i=Tt(),a=Dm(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const u of Rm(c,a))ts().commitMissedDeletion(u.sessionId,u.directory);o.current={runtimeKey:i,identities:a}},[t,s,r])},Tm=(e,t)=>e?t.kind!==e.kind?t.kind==="project":t.projectRoot.length!==e.projectRoot.length?t.projectRoot.length>e.projectRoot.length:t.projectId.localeCompare(e.projectId)<0:!0,ha=(e,t,s)=>{Tm(e.get(t),s)&&e.set(t,s)},sc=e=>{const t=e;return De(t.directory)??De(t.project?.worktree)},Mm=(e,t,s)=>{if(e.time?.archived)return!0;const r=sc(e);if(!r)return s?.allowUnknownDirectory??!0;if(_r(r,s?.homeDirectory))return!0;if(t.size===0)return s?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(De(i)?.toLowerCase()===o)return!0;return!1},Fm=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const t=e.lastIndexOf("/");return t<0?null:t===0?"/":t===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,t)},Lm=(e,t,s,r=[])=>{const o=new Map,i=new Map;for(const g of t){const h=De(g.normalizedPath);if(!h)continue;const p=i.get(h);(!p||g.id.localeCompare(p.id)<0)&&i.set(h,g),ha(o,h,{projectId:g.id,projectRoot:h,scopeDirectory:h,kind:"project"})}if(s)for(const[g,h]of s){const p=De(g),S=p?i.get(p):void 0;if(!(!S||!p))for(const y of h||[]){const v=De(y?.path);v&&ha(o,v,{projectId:S.id,projectRoot:p,scopeDirectory:v,kind:"worktree"})}}const a=new Map,c=new Map,u=new Map,d=new Map,f=new Map,m=g=>{if(!g)return null;if(a.has(g))return a.get(g)??null;const h=[];let p=g,S=null;for(;p;){if(a.has(p)){S=a.get(p)??null;break}if(h.push(p),S=o.get(p)??null,S)break;p=Fm(p)}for(const y of h)a.set(y,S);return S},b=(g,h,p)=>{for(const S of g){const y=sc(S);if(_r(y))continue;const v=m(y);if(!v)continue;c.set(S.id,v);const x=h.get(v.projectId);if(x?x.push(S):h.set(v.projectId,[S]),!p)continue;const A=p.get(v.scopeDirectory);A?A.add(S.id):p.set(v.scopeDirectory,new Set([S.id]))}};return b(e,u,f),b(r,d),{bySessionId:c,sessionsByProject:u,archivedSessionsByProject:d,sessionsByScope:f,directoryResolutions:a.size}};function rc({state:e,activeLabel:t,unreadLabel:s,inputLabel:r,className:o}){if(e==="input"){const i=r??"Needs input";return n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":i,title:i,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return e==="unread"?n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":s??t,title:s??t,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):n.jsx("span",{className:_("inline-flex items-center",o),"aria-label":t,title:t,children:n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Om=({folder:e,displayName:t,sessions:s,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:a,onRename:c,onDelete:u,renderSessionNode:d,getRenderExtras:f,groupDirectory:m,projectId:b,mobileVariant:g=!1,alwaysShowActions:h=g,isRenaming:p=!1,renameDraft:S="",onRenameDraftChange:y,onRenameSave:v,onRenameCancel:x,droppableRef:A,isDropTarget:j=!1,onNewSession:k,depth:w=0,hideActions:C=!1,archivedBucket:R=!1})=>{const[L,U]=l.useState(!1),[G,$]=l.useState(""),q=l.useRef(null),F=p||L,E=p?S:G,T=l.useCallback(()=>{$(e.name),U(!0)},[e.name]),I=l.useCallback(()=>{const O=E.trim();O&&O!==e.name&&c(O),p&&v&&v(),U(!1),$("")},[E,e.name,p,c,v]),M=l.useCallback(()=>{p&&x&&x(),U(!1),$("")},[p,x]),W=l.useCallback(O=>{p&&y?y(O):$(O)},[p,y]);l.useEffect(()=>{if(!p)return;const O=()=>{const ue=q.current;ue&&(ue.focus(),ue.select())},ae=requestAnimationFrame(O),X=window.setTimeout(O,0);return()=>{cancelAnimationFrame(ae),window.clearTimeout(X)}},[p]);const K=o?"folder":"folder-open";return n.jsxs("div",{className:"oc-folder",children:[n.jsxs("div",{ref:A,className:_("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",j&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:F?void 0:O=>{O.currentTarget.blur(),a()},role:F?void 0:"button",tabIndex:F?void 0:0,onKeyDown:F?void 0:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),a())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[n.jsxs("div",{className:_("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",R?h?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":h?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[n.jsx(D,{name:K,className:_(yr,j?"text-primary":"text-muted-foreground")}),F?n.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),onSubmit:O=>{O.preventDefault(),I()},children:[n.jsx("input",{ref:q,value:E,onChange:O=>W(O.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:O=>O.stopPropagation(),onPointerDown:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),onKeyDown:O=>{if(O.key==="Escape"){O.stopPropagation(),M();return}(O.key===" "||O.key==="Enter")&&O.stopPropagation()}}),n.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:O=>O.stopPropagation(),onPointerDown:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),children:n.jsx(D,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),M()},onPointerDown:O=>O.stopPropagation(),onMouseDown:O=>O.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(D,{name:"close",className:"size-4"})})]}):n.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("span",{className:_(Tl,j?"text-primary":"text-muted-foreground"),children:t??e.name})}),n.jsx(Ge,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),n.jsxs("span",{className:"typography-micro text-subtle-foreground flex-shrink-0",children:["• ",s.length]}),i?n.jsx(rc,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?n.jsx(D,{name:"arrow-right-s",className:_(yr,"text-muted-foreground")}):n.jsx(D,{name:"arrow-down-s",className:_(yr,"text-muted-foreground")})]})]}),!F&&(!C||R)?n.jsx("div",{className:_("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",h?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:n.jsxs("div",{className:"flex items-center gap-0.5",children:[!R&&k?n.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),k()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${e.name}`,title:"New session",children:n.jsx(D,{name:"add",className:"size-4"})}):null,R?null:n.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),T()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:n.jsx(D,{name:"pencil-ai",className:"size-4"})}),n.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),u()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":R?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:n.jsx(D,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:n.jsxs("div",{className:"pb-1",children:[r,s.length>0?s.map(O=>n.jsx(l.Fragment,{children:d(O,0,m??null,b??null,R,void 0,"project",f?.(O))},O.session.id)):r?null:n.jsx("div",{className:"py-1 px-3 text-left typography-micro text-subtle-foreground",children:"Empty folder"})]})]})},Bm=l.memo(Om),$r=l.createContext(null),_m=({sessionId:e,sessionDirectory:t,sessionTitle:s,children:r})=>{const{attributes:o,listeners:i,setNodeRef:a,isDragging:c}=rd({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:s}}),u=l.useCallback(d=>{d.stopPropagation(),i?.onPointerDown&&i.onPointerDown(d)},[i]);return n.jsx("div",{ref:a,...o,onPointerDown:u,className:c?"opacity-30":void 0,children:r})},zm=({folderId:e,children:t})=>{const{setNodeRef:s,isOver:r}=tl({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return n.jsx(n.Fragment,{children:t(s,r)})},Um=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:s,children:r})=>{const o=Or(cs(Za,{activationConstraint:{distance:8}})),[i,a]=l.useState(null),[c,u]=l.useState("Session"),[d,f]=l.useState(null),[m,b]=l.useState(null);if(!e)return n.jsx(n.Fragment,{children:r});const g=h=>{a(null),f(null),b(null);const{active:p,over:S}=h;if(!S)return;const y=p.data.current,v=S.data.current;y?.type==="session"&&y.sessionId&&v?.type==="folder"&&v.folderId&&s(y.sessionId,v.folderId)};return n.jsxs(Br,{sensors:o,collisionDetection:pi,onDragStart:h=>{const p=h.active.data.current;if(p?.type==="session"&&p.sessionId){a(p.sessionId),u(p.sessionTitle??"Session");const S=h.active.rect.current.initial?.width,y=h.active.rect.current.initial?.height;f(typeof S=="number"?S:null),b(typeof y=="number"?y:null)}},onDragCancel:()=>{a(null),f(null),b(null)},onDragEnd:g,children:[r,n.jsx(el,{children:i&&t?n.jsxs("div",{style:{width:d?`${d}px`:"auto",height:m?`${m}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[n.jsx(D,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),n.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Kr="gap-2",oc="my-0.5 rounded-lg py-1.5",Qs=l.createContext("card"),Xt=({icon:e,children:t,onClick:s,className:r,mobileVariant:o=!1})=>{const i=l.useContext(Qs)==="tree";return n.jsxs("button",{type:"button",onClick:s,"data-sidebar-tree-row":i?"":void 0,className:_(o?ih:ah,i&&Kr,i&&oc,r),children:[n.jsx(D,{name:e,className:_(_n(o),"text-muted-foreground")}),n.jsx("span",{className:_(hs(o),"flex-1 text-muted-foreground"),children:t})]})},$m="select-none px-3 pb-1 typography-ui-label font-semibold text-muted-foreground",as=({label:e,first:t=!1,count:s,expanded:r,onToggle:o})=>{const i=t?"pt-1":"pt-3",a=typeof s=="number"?n.jsx("span",{className:"font-normal tabular-nums text-subtle-foreground",children:s}):null;return o?n.jsx("div",{role:"heading","aria-level":3,className:i,children:n.jsxs("button",{type:"button","aria-expanded":r,onClick:o,className:"group/heading flex h-7 w-full select-none items-center gap-1.5 rounded-md px-3 text-left typography-ui-label font-semibold text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e,a,n.jsx(D,{name:r?"arrow-down-s":"arrow-right-s",className:"ml-auto size-4 shrink-0 text-muted-foreground group-hover/heading:text-foreground"})]})}):n.jsxs("div",{role:"heading","aria-level":3,className:_($m,i,"flex items-center gap-1.5"),children:[e,a]})},pa=(e,t,s)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const a of o.children)i=r(a)||i;return i&&s.add(o.session.id),i};for(const o of e)r(o)},un=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const s of e.children)if(un(s,t))return!0;return!1},Km=(e,t)=>{const s=new Set(e);return e.map(r=>t.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let i=r.session.parentID??null;for(;i&&!o.has(i);){if(s.has(i)&&t.has(i))return!1;o.add(i),i=t.get(i)?.session?.parentID??null}return!0})},ma=new WeakMap;let ga=1;const Wm=e=>{const t=ma.get(e);if(t!==void 0)return t;const s=ga;return ga+=1,ma.set(e,s),s},Zo=e=>e.children.length===0?"":e.children.map(s=>{const r=Wm(s.session);return s.children.length===0?`${s.session.id}@${r}`:`${s.session.id}@${r}:${Zo(s)}`}).join("|"),ic=(e,t,s,r,o,i)=>{const a=Tt(),c=(u,d)=>{if(u.session.id!==d.session.id||u.children.length!==d.children.length)return!0;const f=u.session.directory??o,m=d.session.directory??i,b=Hi(a,f??"",u.session.id),g=Hi(a,m??"",d.session.id);return(b?s.has(b):!1)!==(g?r.has(g):!1)?!0:u.children.some((h,p)=>c(h,d.children[p]))};return c(e,t)},Js=(e,t)=>`${e}:${t.time?.archived?"archived":"active"}:${t.id}`,Rr=(e,t,s)=>{if(!t)return null;let r=null;const o=i=>{if(Js(s,i.session)===t)return r=i.session.id,!0;for(const c of i.children)if(o(c))return!0;return!1};return e.forEach(i=>o(i)),r},Gm=5*6e4,Hm=6e4,ba=5*6e4,xa=100,Ds=new Map,ns=new Map,Ln=new Map,ls=new Map,Xs=(e,t)=>{const s=hn((e??"").trim()),r=(t??"").trim();return!s||!r?"":`${Tt()}
12
- ${s}
13
- ${r}`},ya=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),qm=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},Ym=e=>{const t=Object.keys(e);if(t.length<=xa)return e;const s=t.sort((o,i)=>(ls.get(o)??0)-(ls.get(i)??0)),r={...e};for(let o=0;o<s.length-xa;o+=1){const i=s[o];delete r[i],ls.delete(i),ns.delete(i);const a=Ln.get(i);a!==void 0&&(clearTimeout(a),Ln.delete(i))}return r},ac=e=>e.pr?e.pr.state!=="open"?ba:e.checks?.state==="pending"?Hm:ba:Gm,ei=(e,t,s,r)=>{if(typeof window>"u"||Ln.has(e))return;const o=Zt.getState().results[e];if(!o)return;const i=ac(o),a=setTimeout(()=>{if(Ln.delete(e),!!Zt.getState().results[e]){if(typeof document<"u"&&document.hidden){ei(e,t,s,r);return}Zt.getState().refresh(t,s,r)}},i);typeof a=="object"&&a!==null&&typeof a.unref=="function"&&a.unref(),Ln.set(e,a)},Zt=$n()(zr((e,t)=>({results:{},refresh:async(s,r,o,i)=>{const a=hn((s||"").trim()),c=(r||"").trim();if(!a||!c)return null;const u=Xs(a,c);if(!u)return null;const d=Ds.get(u);if(d&&!i?.force)return d;const f=o??null;if(!f)return t().results[u]??null;const m=(ns.get(u)??0)+1;ns.set(u,m);const b=t().results[u]??ya();e(h=>({results:{...h.results,[u]:{...b,isLoading:!0}}}));const g=(async()=>{try{const h=await f.prStatus(a,c);if(ns.get(u)!==m||Tt()!==u.split(`
14
- `)[0])return t().results[u]??null;const p={pr:h.pr??null,checks:h.checks??null,checksStale:h.checksStale,defaultBranch:h.defaultBranch??null,skippedDefaultBranch:h.skippedDefaultBranch,fetchedAt:h.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return ls.set(u,Date.now()),e(S=>({results:Ym({...S.results,[u]:p})})),ei(u,a,c,f),p}catch(h){if(ns.get(u)!==m)return t().results[u]??null;const p=qm(h),S=b.pr||b.fetchedAt?{...b,isLoading:!1,stale:!0,error:p}:{...ya(),error:p};return e(y=>({results:{...y.results,[u]:S}})),ei(u,a,c,f),S}})();Ds.set(u,g);try{return await g}finally{Ds.get(u)===g&&Ds.delete(u)}},load:async(s,r,o)=>{const i=hn((s||"").trim()),a=(r||"").trim();if(!i||!a)return null;const c=Xs(i,a);ls.set(c,Date.now());const u=t().results[c];return u&&(u.pr||u.fetchedAt)?(t().refresh(i,a,o),u):t().refresh(i,a,o)},resetForRuntimeSwitch:()=>{Ds.clear(),ns.clear(),ls.clear(),Ts=null;for(const s of Ln.values())clearTimeout(s);Ln.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(gs(()=>{Zt.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await ht(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-fmzQmSSv.js").then(o=>o.cJ);return{getRegisteredRuntimeAPIs:r}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:r})=>r()?.github??null).catch(()=>null);if(!e)return;const t=Date.now(),s=Object.entries(Zt.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=ac(r)).map(([r])=>r);for(const r of s){const[,o,i]=r.split(`
15
- `);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await Zt.getState().refresh(o,i,e).catch(()=>null)}}})()}));let Ts=null;const Rw=e=>{if(Ts&&Ts.results===e)return Ts.index;const t=new Map;for(const s of Object.values(e)){const r=s.pr?.url;!r||t.has(r)||t.set(r,s.checks?.state??null)}return Ts={results:e,index:t},t},Vm=e=>{const t=e?.pr;if(!t)return null;if(t.state==="merged")return{visualState:"merged",number:t.number,draft:t.draft,title:t.title};if(t.state==="closed")return{visualState:"closed",number:t.number,draft:t.draft,title:t.title};if(t.draft)return{visualState:"draft",number:t.number,draft:!0,title:t.title,mergeableState:t.mergeableState??void 0,checks:e?.checks?{state:e.checks.state}:void 0};const s=e?.checks?.state,r=t.mergeableState??void 0;return r==="dirty"||r==="blocked"||s==="failure"?{visualState:"blocked",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}:{visualState:"open",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}},lc=e=>{const t=Zt(s=>e?s.results[e]??null:null);return l.useMemo(()=>Vm(t),[t])},cc=(e,t,s)=>{const r=l.useMemo(()=>Xs(e,t),[e,t]),o=s??null;l.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return ht(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-fmzQmSSv.js").then(c=>c.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{if(i)return;const c=o??a()?.github??null;c&&Zt.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},uc=new Set,Si=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,ti=(e,t,s,r=uc)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(ti(i,t,s,r)==="input")return"input";return"active"}let o=s.has(e.session.id)?"unread":null;for(const i of e.children)if(o=Si(o,ti(i,t,s,r)),o==="input")return o;return o},dc=(e,t,s,r=uc)=>{let o=null;for(const i of e)if(o=Si(o,ti(i,t,s,r)),o==="input")return o;return o},ni=(e,t)=>{if(!t)return e;const s=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let a=0,c=s.indexOf(r,a);for(;c!==-1;){c>a&&i.push(e.slice(a,c));const u=e.slice(c,c+o);i.push(n.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:u},`${c}-${u}`)),a=c+o,c=s.indexOf(r,a)}return a<e.length&&i.push(e.slice(a)),i.length>0?i:e},ys=e=>[Tt(),...e.map(t=>(t??"").toString())].join(`
16
- `),fr=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},Qm=200,os=(e={})=>{const t=e.maxEntries??Qm,s=new Map,r=new Map,o=new Map;let i=0;const a=new Map,c=new Map,u=p=>{const S=s.get(p)??null;return S&&a.set(p,i+=1),S},d=p=>{const S=c.get(p);if(S)for(const y of[...S])try{y()}catch{}},f=()=>{if(s.size<=t)return;const p=[...s.keys()].filter(y=>!r.has(y)&&(c.get(y)?.size??0)===0).sort((y,v)=>(a.get(y)??0)-(a.get(v)??0)),S=s.size-t;for(let y=0;y<S&&y<p.length;y+=1){const v=p[y];s.delete(v),a.delete(v),o.set(v,(o.get(v)??0)+1)}};let m=!1;const b=()=>{if(m||s.size<=t)return;m=!0;const p=()=>{m=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(p):setTimeout(p,0)},g=(p,S)=>{const v={...s.get(p)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(p)??0},...S};return s.set(p,v),a.set(p,i+=1),b(),d(p),v},h=async(p,S)=>{const y=r.get(p);if(y)return y;const v=(o.get(p)??0)+1;o.set(p,v);const x=s.get(p);g(p,{isLoading:!0,generation:v});const A=(async()=>{try{const j=await S();return o.get(p)!==v?s.get(p)??{data:j,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:v}:g(p,{data:j,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:v})}catch(j){return o.get(p)!==v?s.get(p)??{data:x?.data??null,fetchedAt:x?.fetchedAt??null,isLoading:!1,stale:!0,error:fr(j),generation:v}:x?.data!=null?g(p,{isLoading:!1,stale:!0,error:fr(j),generation:v}):g(p,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:fr(j),generation:v})}})();r.set(p,A);try{return await A}finally{r.get(p)===A&&r.delete(p),e.onSettle?.(p)}};return{getEntry:u,snapshot:()=>Object.fromEntries(s),subscribe:(p,S)=>{let y=c.get(p);return y||(y=new Set,c.set(p,y)),y.add(S),()=>{const v=c.get(p);v&&(v.delete(S),v.size===0&&c.delete(p))}},ensure:(p,S,y)=>!y?.force&&r.has(p)?r.get(p):!y?.force&&s.get(p)?.data!=null&&s.get(p)?.isLoading?r.get(p)??Promise.resolve(s.get(p)):!y?.force&&s.get(p)?.data!=null?(h(p,S),Promise.resolve(s.get(p))):h(p,S),refresh:(p,S)=>h(p,S),invalidate:async(p,S,y)=>{if(y?.exact??!0)return o.set(p,(o.get(p)??0)+1),s.delete(p),a.delete(p),r.has(p)&&r.delete(p),d(p),S?h(p,S):null;for(const x of[...s.keys()])(x===p||x.startsWith(p))&&(o.set(x,(o.get(x)??0)+1),s.delete(x),a.delete(x),r.delete(x),d(x));return null},markStale:p=>{const S=s.get(p);S?.data&&(S.stale||g(p,{stale:!0}))},setError:(p,S)=>{const y=s.get(p);return y?.data?g(p,{isLoading:!1,stale:!0,error:fr(S)}):y??null},remove:p=>{o.set(p,(o.get(p)??0)+1),s.delete(p),a.delete(p),r.delete(p),d(p)},reset:()=>{const p=[...s.keys()];s.clear(),r.clear(),o.clear(),a.clear();for(const S of p)d(S)}}},ws=(e,t)=>Te.useSyncExternalStore(s=>t?e.subscribe(t,s):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),Pw=e=>{const t=e.trim().match(/^#?(\d{1,7})$/);if(!t)return null;const s=Number(t[1]);return Number.isSafeInteger(s)&&s>0?s:null},fc=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),si=e=>{if(!e)return[];const t=[];for(const s of e)s?.login&&t.push(s.login.toLowerCase());return t},hc=e=>{const t=[],s=[];for(const r of e.trim().toLowerCase().split(/\s+/))r&&(r.startsWith("label:")&&r.length>6?s.push(r.slice(6)):t.push(r));return{tokens:t,labelTokens:s}},ji=e=>{if(!e)return[];const t=[];for(const s of e)s?.name&&t.push(s.name.toLowerCase());return t},pc=(e,t,s)=>{const r=ji(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...s])if(!r.some(a=>a===i||a.includes(i)))return!1;return!0},Jm=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const s of ji(e.labels))t.push(s);return t},Xm=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const s of ji(e.labels))t.push(s);return t},mc=(e,t)=>{for(const s of t){let r=!1;for(const o of e)if(o.includes(s)){r=!0;break}if(!r)return!1}return!0},wa=e=>e.state==="merged"||!!e.mergedAt,Zm=(e,t)=>t==="all"?e:t==="open"?e.filter(s=>s.state==="open"):t==="merged"?e.filter(s=>wa(s)):e.filter(s=>s.state==="closed"&&!wa(s)),eg=(e,t)=>t==="all"?e:e.filter(s=>s.state===t),tg=(e,t,s)=>t==="all"||!s?!0:t==="mine"?fc(e.author?.login,s):t==="review"?si(e.requestedReviewers).includes(s.toLowerCase()):si(e.assignees).includes(s.toLowerCase()),ng=(e,t,s)=>t==="all"||!s||t==="mentioned"?!0:t==="mine"?fc(e.author?.login,s):si(e.assignees).includes(s.toLowerCase()),Xn=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},gc=(e,t)=>{const s=[...e];return t==="newest"?(s.sort((r,o)=>Xn(o.createdAt)-Xn(r.createdAt)||o.number-r.number),s):t==="oldest"?(s.sort((r,o)=>Xn(r.createdAt)-Xn(o.createdAt)||r.number-o.number),s):(s.sort((r,o)=>Xn(o.updatedAt)-Xn(r.updatedAt)||o.number-r.number),s)},Tw=(e,t)=>{const{tokens:s,labelTokens:r}=hc(t.search),o=[];for(const i of Zm(e,t.state))tg(i,t.involvement,t.viewerLogin)&&pc(i.labels,"",r)&&mc(Jm(i),s)&&o.push(i);return gc(o,t.sort)},Mw=(e,t)=>{const{tokens:s,labelTokens:r}=hc(t.search),o=[];for(const i of eg(e,t.state))ng(i,t.involvement,t.viewerLogin)&&pc(i.labels,t.labels,r)&&mc(Xm(i),s)&&o.push(i);return gc(o,t.sort)},hr=(e,t)=>{if(t.length===0)return e;const s=new Map;for(const i of t)s.set(i.number,i);const r=e.map(i=>s.get(i.number)??i),o=new Set(e.map(i=>i.number));for(const i of t)o.has(i.number)||r.push(i);return r},Fw=(e,t)=>e.filter(s=>!t.has(s.number)),sg=(e,t)=>{if(t.length===0)return e;const s=new Set(e.map(o=>o.id)),r=[...e];for(const o of t)s.has(o.id)||(s.add(o.id),r.push(o));return r},va=Object.freeze({repo:null,number:null}),uo=e=>e.split(`
17
- `)[1]??"",ri=(e,t)=>`${hn(e)}
18
- ${t}`,Rs=(e,t)=>`${e}#${t}`,rg=(e,t)=>{const s=e?.body;return s&&typeof s.kind=="string"?s:{kind:"failed",message:e instanceof Error?e.message:t}},Tn=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Sa=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,ja=10,og=(e,t)=>{const s=os(),r=os({maxEntries:60}),o=os(),i=os(),a=new Map,c=new Map,u=async(F,E)=>{const T=c.get(F);if(T)return await T.catch(()=>null),{ran:!1,result:null};const I=E();c.set(F,I);try{return{ran:!0,result:await I}}finally{c.get(F)===I&&c.delete(F)}},d=(F,E)=>{if(E.length===0)return;const T=e.collectionKeyFor(F,e.openCollection);let I=a.get(T);I||(I=new Map,a.set(T,I));for(const M of E)I.set(M.number,M)},f=F=>{const E=Object.keys(r.snapshot()).filter(I=>uo(I)===F&&!r.getEntry(I)?.isLoading);if(E.length<=ja)return;const T=E.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,M)=>I.fetchedAt-M.fetchedAt);for(let I=0;I<T.length-ja;I+=1)r.remove(T[I].key)},m=F=>{const E=s.getEntry(e.collectionKeyFor(F,e.openCollection))?.data?.items??[],T=s.getEntry(e.collectionKeyFor(F,e.closedCollection))?.data?.items??[],I=hr(E,T),M=a.get(e.collectionKeyFor(F,e.openCollection));return!M||M.size===0?I:hr(I,[...M.values()])},b=(F,E,T)=>{const I=ri(F,E),M=t.get().filtersByScope[I]??e.defaultFilters;t.set(W=>({filtersByScope:{...W.filtersByScope,[I]:{...M,...T}}}))},g=(F,E)=>{const T=ri(F,E);t.set(I=>({filtersByScope:{...I.filtersByScope,[T]:{...e.defaultFilters}}}))},h=(F,E,T)=>{const I=hn(F);I&&t.set(M=>({selectionByDirectory:{...M.selectionByDirectory,[I]:{repo:E,number:T}}}))},p=(F,E,T,I)=>{const M=e.collectionKeyFor(E,T);return s.ensure(M,async()=>{const W=await e.fetchList(I,F,E,e.buildCollectionQuery(T));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},S=(F,E,T)=>{const I=e.collectionKeyFor(E,e.closedCollection);s.getEntry(I)?.data||s.getEntry(I)?.isLoading||p(F,E,e.closedCollection,T).catch(()=>null)},y=async(F,E,T,I)=>{const M=T==="open"||T==="both",W=T==="closed"||T==="both",K=[],O=s.getEntry(e.collectionKeyFor(E,e.openCollection)),ae=s.getEntry(e.collectionKeyFor(E,e.closedCollection));M&&(!Sa(O,e.freshWindowMs)||O?.stale)&&K.push(p(F,E,e.openCollection,I)),W&&(!Sa(ae,e.freshWindowMs)||ae?.stale)&&K.push(p(F,E,e.closedCollection,I)),await Promise.all(K.map(X=>X.catch(()=>null))),M&&!s.getEntry(e.collectionKeyFor(E,e.closedCollection))?.data&&S(F,E,I)},v=async(F,E,T,I)=>{const M=e.collectionKeyFor(E,T),W=s.getEntry(M),K=W?.data?.nextCursor??null;if(!K||W?.isLoading)return W;try{const O=await u(`${M}:more`,async()=>{const ae=await e.fetchList(I,F,E,{...e.buildCollectionQuery(T),cursor:K}),X=s.getEntry(M)?.data,ue={items:hr(X?.items??[],ae.items),nextCursor:ae.nextCursor,fetchedAt:ae.fetchedAt};return s.refresh(M,async()=>ue)});return O.ran?O.result??s.getEntry(M):s.getEntry(M)}catch(O){return s.setError(M,O)??s.getEntry(M)}},x=async(F,E,T,I)=>{const M=T==="both"?[e.openCollection,e.closedCollection]:[T];await Promise.all(M.map(W=>{const K=e.collectionKeyFor(E,W);return s.refresh(K,async()=>{const O=await e.fetchList(I,F,E,e.buildCollectionQuery(W));return{items:O.items,nextCursor:O.nextCursor,fetchedAt:O.fetchedAt}}).catch(()=>null)}))},A=async(F,E,T,I)=>{const M=e.remoteKeyFor(E,T),W=await r.refresh(M,async()=>{const K=await e.fetchList(I,F,E,e.buildRemoteQuery(T));return{items:K.items,nextCursor:K.nextCursor,fetchedAt:K.fetchedAt}});return W.data&&(d(E,W.data.items),f(E)),W},j=async(F,E,T,I)=>{const M=e.remoteKeyFor(E,T),W=r.getEntry(M),K=W?.data?.nextCursor??null;if(!K||W?.isLoading)return W;try{const O=await e.fetchList(I,F,E,e.buildRemoteQuery(T,K)),ae=r.getEntry(M)?.data,X={items:hr(ae?.items??[],O.items),nextCursor:O.nextCursor,fetchedAt:O.fetchedAt},ue=await r.refresh(M,async()=>X);return ue.data&&(d(E,ue.data.items),f(E)),ue}catch(O){return r.setError(M,O)??r.getEntry(M)}},k=F=>{for(const E of Object.keys(r.snapshot()))uo(E)===F&&r.remove(E);for(const E of[...a.keys()])uo(E)===F&&a.delete(E)},w=(F,E,T,I)=>{const M=e.detailKeyFor(E,T);return o.refresh(M,async()=>({detail:await e.fetchDetail(I,F,E,T)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:s,remote:r,details:o,comments:i},setFilters:b,resetFilters:g,select:h,ensureCollection:p,ensureCollectionsFresh:y,prefetchClosedCollection:S,loadMoreCollection:v,refreshCollections:x,searchRemote:A,loadMoreRemote:j,dropRemoteForRepo:k,refreshAllForScope:async(F,E,T)=>{await Tn(T,{directory:F,repo:E,kind:e.serverKind}),k(E),await x(F,E,"both",T).catch(()=>null);const I=t.get().selectionByDirectory[hn(F)];I?.repo===E&&typeof I.number=="number"&&await w(F,E,I.number,T).catch(()=>null)},ensureDetail:(F,E,T,I)=>{const M=e.detailKeyFor(E,T);return o.ensure(M,async()=>({detail:await e.fetchDetail(I,F,E,T)}))},refreshDetail:w,ensureComments:(F,E,T,I)=>{const M=e.commentsKeyFor(E,T);return i.ensure(M,async()=>{const W=await e.fetchComments(I,F,E,T);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},loadMoreComments:async(F,E,T,I)=>{const M=e.commentsKeyFor(E,T),W=i.getEntry(M),K=W?.data?.nextCursor??null;if(!K||W?.isLoading)return W;try{const O=await e.fetchComments(I,F,E,T,K),ae=i.getEntry(M)?.data,X={comments:sg(ae?.comments??[],O.comments),nextCursor:O.nextCursor,fetchedAt:O.fetchedAt};return await i.refresh(M,async()=>X)}catch(O){return i.setError(M,O)??i.getEntry(M)}},refreshComments:(F,E,T,I)=>{const M=e.commentsKeyFor(E,T);return i.refresh(M,async()=>{const W=await e.fetchComments(I,F,E,T);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},markCollectionsStale:F=>{s.markStale(e.collectionKeyFor(F,e.openCollection)),s.markStale(e.collectionKeyFor(F,e.closedCollection))},getLocalIndex:m,withSingleFlight:u,resetCore:()=>{s.reset(),r.reset(),a.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:F=>rg(F,e.errorFallback)}},oi={state:"open",involvement:"all",search:"",sort:"updated"},ig=3e4,ag=100,lg=50,bc=(e,t)=>ys([e,"pulls-collection",t]),xc=(e,t)=>ys([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),Pr=(e,t)=>ys([e,"pull-detail",t]),ki=(e,t)=>ys([e,"pull-comments",t]),ii=(e,t)=>ys([e,"pull-files",t]),ai=(e,t)=>ys([e,"pull-checks",t]),cg=e=>({state:e,perPage:ag}),ug=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:lg,...t?{cursor:t}:{}}),Tr=e=>`pichamber:pr-merge-method:${e}`,yc=new Map,dg=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},fg=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},Lw=e=>{if(!e)return null;const t=dg(Tr(e));return t==="merge"||t==="squash"||t==="rebase"?t:yc.get(Tr(e))??null},hg=(e,t)=>{if(e){yc.set(Tr(e),t);try{fg(Tr(e),t)}catch{}}},pg={set:e=>{typeof e=="function"?Sn.setState(t=>{const s={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(s)}):Sn.setState(e)},get:()=>{const e=Sn.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Me=og({openCollection:"open",closedCollection:"closed",defaultFilters:oi,freshWindowMs:ig,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:bc,remoteKeyFor:xc,detailKeyFor:Pr,commentsKeyFor:ki,buildCollectionQuery:e=>({...cg(e)}),buildRemoteQuery:(e,t)=>({...ug(e,t)}),fetchList:async(e,t,s,r)=>{const o=await e.pullsList(t,s,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,s,r)=>e.pullGet(t,s,r),fetchComments:async(e,t,s,r,o)=>{const i=await e.pullComments(t,s,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},pg),Qt=os(),Sr=os(),Sn=$n()(zr((e,t)=>({...Me.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Me.setFilters,resetFilters:Me.resetFilters,selectPullRequest:Me.select,ensureCollection:Me.ensureCollection,ensureCollectionsFresh:Me.ensureCollectionsFresh,prefetchClosedCollection:Me.prefetchClosedCollection,loadMoreCollection:Me.loadMoreCollection,refreshCollections:Me.refreshCollections,searchRemote:Me.searchRemote,loadMoreRemote:Me.loadMoreRemote,dropRemoteForRepo:Me.dropRemoteForRepo,refreshAllForScope:Me.refreshAllForScope,ensureDetail:Me.ensureDetail,refreshDetail:Me.refreshDetail,ensureComments:Me.ensureComments,loadMoreComments:Me.loadMoreComments,refreshComments:Me.refreshComments,ensureFiles:(s,r,o,i)=>{const a=ii(r,o);return Qt.ensure(a,async()=>i.pullFiles(s,r,o))},loadMoreFiles:async(s,r,o,i)=>{const a=ii(r,o),c=Qt.getEntry(a),u=c?.data?.nextCursor??null;if(!u||c?.isLoading)return c;try{const d=await Me.withSingleFlight(`${a}:more`,async()=>{const f=await i.pullFiles(s,r,o,u),m=Qt.getEntry(a)?.data,b=new Set((m?.files??[]).map(h=>h.filename)),g={repo:f.repo,number:f.number,files:[...m?.files??[],...f.files.filter(h=>!b.has(h.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Qt.refresh(a,async()=>g)});return d.ran?d.result??Qt.getEntry(a):Qt.getEntry(a)}catch(d){return Qt.setError(a,d)??Qt.getEntry(a)}},ensureChecks:(s,r,o,i)=>{const a=ai(r,o);return Sr.ensure(a,async()=>i.pullChecks(s,r,o,!0))},refreshChecks:(s,r,o,i)=>{const a=ai(r,o);return Sr.refresh(a,async()=>i.pullChecks(s,r,o,!0))},performAction:async(s,r,o,i,a)=>{const c=Rs(r,o),u=Pr(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(b=>({actingActions:{...b.actingActions,[c]:!0},actionErrorByDetail:{...b.actionErrorByDetail,[c]:null}}));const d=Me.resources.details.getEntry(u)?.data?.detail??null,f=d?.pr??null,m=f?{...f,state:i==="close"?"closed":i==="reopen"?"open":i==="merge"||i==="squash"||i==="rebase"?"merged":f.state,draft:i==="ready"?!1:i==="draft"?!0:f.draft}:null;m&&d&&await Me.resources.details.refresh(u,async()=>({detail:{...d,pr:m}})).catch(()=>null);try{return await a.pullAction(s,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(s,r,"both",a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),await t().refreshChecks(s,r,o,a).catch(()=>null),e(b=>({actingActions:{...b.actingActions,[c]:!1}})),{ok:!0}}catch(b){const g=Me.toStoreError(b);return d&&await Me.resources.details.refresh(u,async()=>({detail:d})).catch(()=>null),e(h=>({actingActions:{...h.actingActions,[c]:!1},actionErrorByDetail:{...h.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},updateTitleBody:async(s,r,o,i,a)=>{const c=Rs(r,o),u=Pr(r,o),d=Me.resources.details.getEntry(u)?.data?.detail??null,f=d?.pr??null,m=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;m&&d&&await Me.resources.details.refresh(u,async()=>({detail:{...d,pr:m}})).catch(()=>null);try{return await a.pullUpdate(s,r,o,i),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(s,r,"both",a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(b){const g=Me.toStoreError(b);return d&&await Me.resources.details.refresh(u,async()=>({detail:d})).catch(()=>null),e(h=>({actionErrorByDetail:{...h.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},addComment:async(s,r,o,i,a)=>{const c=Rs(r,o),u=ki(r,o),d=i.trim(),f={id:-Date.now(),url:"",body:d,author:null,createdAt:new Date().toISOString(),updatedAt:null},m=Me.resources.comments.getEntry(u)?.data??null;if(m){const b={comments:[...m.comments,f],nextCursor:m.nextCursor,fetchedAt:m.fetchedAt};await Me.resources.comments.refresh(u,async()=>b).catch(()=>null)}try{return await a.pullComment(s,r,o,d),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshComments(s,r,o,a).catch(()=>null),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(b){const g=Me.toStoreError(b);return m?await Me.resources.comments.refresh(u,async()=>m).catch(()=>null):Me.resources.comments.remove(u),e(h=>({actionErrorByDetail:{...h.actionErrorByDetail,[c]:g}})),{ok:!1,error:g}}},submitReview:async(s,r,o,i,a)=>{const c=Rs(r,o);try{return await a.pullReview(s,r,o,{event:i.event,body:i.body,comments:i.comments}),await Tn(a,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshDetail(s,r,o,a).catch(()=>null),{ok:!0}}catch(u){const d=Me.toStoreError(u);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:d}})),{ok:!1,error:d}}},threadAction:async(s,r,o,i,a,c)=>{const u=Rs(r,o);try{return await c.pullThread(s,r,o,i,a),await Tn(c,{directory:s,repo:r,kind:"pulls",number:o}),await t().refreshDetail(s,r,o,c).catch(()=>null),{ok:!0}}catch(d){const f=Me.toStoreError(d);return e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[u]:f}})),{ok:!1,error:f}}},checkout:async(s,r,o,i,a)=>{try{const c=await a.pullCheckout(s,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Me.toStoreError(c)}}},createPullRequest:async(s,r)=>{try{const o=await r.pullCreate(s);return await Tn(r,{directory:s.directory,repo:s.repo,kind:"pulls"}),t().dropRemoteForRepo(s.repo),await t().refreshCollections(s.directory,s.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Me.toStoreError(o)}}},rerunFailedChecks:async(s,r,o,i)=>{try{return await i.checksRerun(s,r,o),{ok:!0}}catch(a){return{ok:!1,error:Me.toStoreError(a)}}},setMergeMethod:(s,r)=>{hg(s,r)},notifyAgentTurnComplete:s=>{const r=hn((s||"").trim());if(!r)return;const o=Zt.getState();for(const a of Object.keys(o.results)){const[,c]=a.split(`
19
- `);if(c!==r)continue;const[,,u]=a.split(`
20
- `);u&&ht(async()=>{const{getRegisteredRuntimeAPIs:d}=await import("./index-fmzQmSSv.js").then(f=>f.cJ);return{getRegisteredRuntimeAPIs:d}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:d})=>{const f=d()?.github??null;if(f)return o.refresh(r,u,f,{force:!0})}).catch(()=>{})}const i=t().selectionByDirectory[r];i?.repo&&typeof i.number=="number"&&(Me.markCollectionsStale(i.repo),ht(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-fmzQmSSv.js").then(c=>c.cJ);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{const c=a()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Me.resetCore(),Qt.reset(),Sr.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(gs(()=>{Sn.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Ow=e=>{if(typeof window>"u")return()=>{};let t=new Set,s=!1,r=!1,o=null;return ht(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-FKnY7Fe2.js").then(a=>a.ey);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const a=()=>{const c=i.getState().list,u=new Set(c.map(d=>`${d.type}:${d.session??""}:${d.time}`));if(!s){t=u,s=!0;return}for(const d of c){const f=`${d.type}:${d.session??""}:${d.time}`;t.has(f)||(t.add(f),d.type==="turn-complete"&&d.directory&&(Sn.getState().notifyAgentTurnComplete(d.directory),e?.(d.directory)))}};a(),o=i.subscribe(a)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},Bw=e=>Me.getLocalIndex(e),_w=(e,t)=>Me.getLocalIndex(e).find(s=>s.number===t)??null,zw=(e,t)=>ws(Me.resources.collections,e?bc(e,t):null),Uw=(e,t)=>ws(Me.resources.remote,e?xc(e,t):null),$w=(e,t)=>ws(Me.resources.details,e!=null&&t!=null?Pr(e,t):null),Kw=(e,t)=>ws(Me.resources.comments,e!=null&&t!=null?ki(e,t):null),Ww=(e,t)=>ws(Qt,e!=null&&t!=null?ii(e,t):null),Gw=(e,t)=>ws(Sr,e!=null&&t!=null?ai(e,t):null),Hw=(e,t)=>Sn(s=>!e||!t?oi:s.filtersByScope[ri(e,t)]??oi),qw=e=>Sn(t=>e?t.selectionByDirectory[hn(e)]??va:va),wc=(e,t,s)=>{Sn.getState().selectPullRequest(e,t,s);const r=hn(e);ht(async()=>{const{useUIStore:o}=await import("./index-fmzQmSSv.js").then(i=>i.cM);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),ht(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-FKnY7Fe2.js").then(i=>i.eA);return{useGitHubScopeStore:o}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useGitHubScopeStore:o})=>{o.getState().setSelectedRepo(e,t)}).catch(()=>{})},mg=({directory:e,number:t,color:s})=>{const r=ml(e);return!e||!r?n.jsxs("span",{className:"ml-auto flex-shrink-0 typography-micro font-medium leading-none",style:s?{color:s}:void 0,children:["#",t]}):n.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),wc(e,r,t)},className:"ml-auto flex-shrink-0 rounded typography-micro font-medium leading-none hover:bg-interactive-hover",style:s?{color:s}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function gg({group:e,groupKey:t,isCollapsed:s,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:a,dragHandleProps:c,groupPrColor:u,groupPrSummary:d,groupActivityIndicator:f,showBranchSubtitle:m,statusLine:b,projectId:g,activeProjectId:h,setActiveProjectIdOnly:p,setActiveMainTab:S,mobileVariant:y,setSessionSwitcherOpen:v,openNewSessionDraft:x}){return n.jsxs("div",{className:_("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(t),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),r(t))},"aria-label":s?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!s,children:[n.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",a),...c?.listeners??{},children:n.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[n.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground",children:!e.isMain||e.worktree?n.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[n.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[n.jsx(D,{name:"git-branch",className:_("size-4 shrink-0",!u&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:u?{color:u}:void 0}),n.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:s?n.jsx(D,{name:"arrow-right-s",className:"size-4"}):n.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),n.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:ni(e.label,o)}),f,d?n.jsx(mg,{directory:e.directory??null,number:d.number,color:u}):null]}):n.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[n.jsx("span",{className:"min-w-0 truncate",children:ni(e.label,o)}),f]})}),m&&b?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[n.jsx(D,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),n.jsx("span",{className:"min-w-0 truncate typography-micro font-medium text-subtle-foreground",children:b.label})]}):null]})}),e.directory?n.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),g&&g!==h&&p(g),S("chat"),y&&v(!1),x({selectedProjectId:g,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:n.jsx(D,{name:"add",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"New draft session"})})]})}):null]})}const pr=(e,t)=>t?e.sessions.some(s=>un(s,t)):!1,bg=(e,t,s)=>e.sessions.some(r=>ic(r,r,t,s,e.directory,e.directory)),xg=(e,t,s)=>{const r=o=>{const i=o.session.id;return t.get(i)!==s.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},ka=(e,t,s)=>{const r=o=>t.has(o.session.id)!==s.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},yg=(e,t,s)=>{const r=o=>{const i=Js("project",o.session);return t.has(i)!==s.has(i)?!0:o.children.some(r)};return e.sessions.some(r)},wg=(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&&bg(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&yg(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&xg(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(pr(e.group,e.editingId)||pr(t.group,t.editingId))||e.editTitle!==t.editTitle&&(pr(e.group,e.editingId)||pr(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const s=Rr(e.group.sessions,e.openSidebarMenuKey,"project"),r=Rr(t.group.sessions,t.openSidebarMenuKey,"project");if(s||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&ka(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&ka(t.group,e.unreadActivitySessionIds,t.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===t.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===t.normalizedSessionSearchQuery&&e.hideDirectoryControls===t.hideDirectoryControls&&e.collapsedFolderIds===t.collapsedFolderIds&&e.toggleFolderCollapse===t.toggleFolderCollapse&&e.renameFolder===t.renameFolder&&e.deleteFolder===t.deleteFolder&&e.showDeletionDialog===t.showDeletionDialog&&e.setDeleteFolderConfirm===t.setDeleteFolderConfirm&&e.renderSessionNode===t.renderSessionNode&&e.showMoreGroupSessions===t.showMoreGroupSessions&&e.resetGroupSessionLimit===t.resetGroupSessionLimit&&e.mobileVariant===t.mobileVariant&&e.alwaysShowActions===t.alwaysShowActions&&e.activeProjectId===t.activeProjectId&&e.setActiveProjectIdOnly===t.setActiveProjectIdOnly&&e.setActiveMainTab===t.setActiveMainTab&&e.setSessionSwitcherOpen===t.setSessionSwitcherOpen&&e.openNewSessionDraft===t.openNewSessionDraft&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.renamingFolderId===t.renamingFolderId&&e.renameFolderDraft===t.renameFolderDraft&&e.setRenameFolderDraft===t.setRenameFolderDraft&&e.setRenamingFolderId===t.setRenamingFolderId&&e.onToggleCollapsedGroup===t.onToggleCollapsedGroup&&e.dragHandleProps===t.dragHandleProps};function vg({group:e,sourceGroupNodes:t,hasSessionSearchQuery:s,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:a,inputActivitySessionIds:c}){const u=gt(A=>A.foldersMap),d=e.folderScopeKey??De(e.directory??null),f=l.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:d?[{scopeKey:d,directory:e.directory??null}]:[],[d,e.directory,e.folderScopes]),m=l.useMemo(()=>f.flatMap(({scopeKey:A,directory:j})=>(u[A]??[]).map(k=>({folder:k,scopeKey:A,scopeDirectory:j}))),[f,u]),b=l.useMemo(()=>{const A=new Map,j=k=>{k.forEach(w=>{A.set(w.session.id,w),w.children.length>0&&j(w.children)})};return j(t),A},[t]),g=l.useMemo(()=>m.map(({folder:A,scopeKey:j,scopeDirectory:k})=>{const w=Km(A.sessionIds,b).sort(o);return{folder:A,scopeKey:j,scopeDirectory:k,nodes:w}}),[m,b,o]),h=l.useMemo(()=>{const A=new Map(g.map(C=>[C.folder.id,C])),j=new Map;for(const{folder:C}of g){if(!C.parentId)continue;const R=j.get(C.parentId);R?R.push(C.id):j.set(C.parentId,[C.id])}const k=new Map,w=C=>{const R=k.get(C);if(R!==void 0)return R;const L=A.get(C);if(!L)return k.set(C,!1),!1;const U=j.get(C)??[];if(!s||L.folder.name.toLowerCase().includes(r)||L.nodes.length>0)return k.set(C,!0),!0;const $=U.some(q=>w(q));return k.set(C,$),$};return g.filter(({folder:C})=>w(C.id))},[g,s,r]),p=l.useMemo(()=>new Set(h.flatMap(A=>A.folder.sessionIds)),[h]),S=l.useMemo(()=>t.filter(A=>!p.has(A.session.id)),[t,p]),y=l.useMemo(()=>h.filter(({folder:A})=>!A.parentId),[h]),v=l.useMemo(()=>{const A=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const k=A.get(j.folder.parentId)??[];k.push(j),A.set(j.folder.parentId,k)}),A},[h]),x=l.useMemo(()=>{const A=new Map(h.map(w=>[w.folder.id,w])),j=new Map,k=(w,C)=>{const R=j.get(w);if(R!==void 0)return R;if(C.has(w))return null;C.add(w);const L=A.get(w);let U=L?dc(L.nodes,i,a,c):null;for(const G of v.get(w)??[])if(U=Si(U,k(G.folder.id,C)),U==="input")break;return j.set(w,U),U};return h.forEach(({folder:w})=>k(w.id,new Set)),j},[i,h,v,c,a]);return{folderScopeKey:d,folderScopes:f,allFoldersForGroup:h,rootFolders:y,ungroupedSessions:S,folderActivityStateById:x}}function Sg(e){const{group:t,groupKey:s,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,groupSearchDataByGroup:c,visibleSessionCount:u,collapsedGroups:d,hideDirectoryControls:f,collapsedFolderIds:m,toggleFolderCollapse:b,renameFolder:g,deleteFolder:h,showDeletionDialog:p,setDeleteFolderConfirm:S,renderSessionNode:y,showMoreGroupSessions:v,resetGroupSessionLimit:x,mobileVariant:A,alwaysShowActions:j,activeProjectId:k,setActiveProjectIdOnly:w,setActiveMainTab:C,setSessionSwitcherOpen:R,openNewSessionDraft:L,addSessionToFolder:U,createFolderAndStartRename:G,renamingFolderId:$,renameFolderDraft:q,setRenameFolderDraft:F,setRenamingFolderId:E,pinnedSessionIds:T,sessionOrderIndex:I,editingId:M,openSidebarMenuKey:W,activeActivitySessionIds:K,unreadActivitySessionIds:O,onToggleCollapsedGroup:ae,dragHandleProps:X,compactBodyPadding:ue=!1}=e,Ie=l.useCallback((Ee,Ve)=>{const Ne=I.get(Ee.session.id),Pe=I.get(Ve.session.id);if(Ne!==void 0||Pe!==void 0){if(Ne===void 0)return 1;if(Pe===void 0)return-1;if(Ne!==Pe)return Ne-Pe}return Ld(Ee.session,Ve.session,T,gl)},[T,I]),V=i?c.get(t):null,P=i?!1:d.has(s),H=!t.isMain&&!o?De(t.directory??null):null,Q=!t.isMain&&!o&&t.branch?.trim()||null,re=l.useMemo(()=>H&&Q?Xs(H,Q):null,[H,Q]),ie=lc(re);cc(H,Q);const ge=ie?`var(--pr-${ie.visualState})`:void 0,me=l.useContext($r)!==null,Ce=f?10:5,je=Math.max(Ce,u??Ce),Le=i?V?.groupMatches===!0:!1,we=i,Re=l.useMemo(()=>[...we?V?.filteredNodes??[]:t.sessions].sort(Ie),[Ie,t.sessions,V?.filteredNodes,we]),Y=Od(),fe=l.useMemo(()=>new Set(Y.map(Ee=>Ee.sessionId)),[Y]),{folderScopeKey:be,folderScopes:ee,allFoldersForGroup:se,rootFolders:_e,ungroupedSessions:ke,folderActivityStateById:J}=vg({group:t,sourceGroupNodes:Re,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,compareSessionNodes:Ie,activeActivitySessionIds:K,unreadActivitySessionIds:O,inputActivitySessionIds:fe}),ve="project",he=l.useMemo(()=>{const Ee=new Set;return pa(Re,M,Ee),se.forEach(({nodes:Ve})=>{pa(Ve,M,Ee)}),Ee},[Re,se,M]),Se=l.useMemo(()=>{if(!W)return null;const Ee=Rr(Re,W,ve);if(Ee)return Ee;for(const{nodes:Ve}of se){const Ne=Rr(Ve,W,ve);if(Ne)return Ne}return null},[W,Re,se]),qe=l.useCallback(Ee=>{const Ve=new WeakMap,Ne=Pe=>{Ve.set(Pe,Zo(Pe));for(const He of Pe.children)Ne(He)};return Ee.forEach(Ne),Ve},[]),Ue=l.useMemo(()=>qe(Re),[qe,Re]),z=l.useMemo(()=>{const Ee=new WeakMap;return se.forEach(({nodes:Ve})=>{Ve.forEach(Ne=>Ee.set(Ne,Zo(Ne)))}),Ee},[se]),pe=l.useCallback(Ee=>Ue.get(Ee)??z.get(Ee)??"",[Ue,z]),ne=l.useCallback(Ee=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:pe(Ee)}),[he,Se,pe]),ze=ke.length,st=me||i?ke:ke.slice(0,je),pt=ze-st.length,Xe=!me&&!i&&ze>Ce&&pt===0;if(i&&!Le&&_e.length===0&&ke.length===0)return null;const Yt=!t.isMain&&!!t.branch,mt=t.branch&&lh(t.branch,t.label)?{label:t.branch,color:null}:null,Nt=P?dc(Re,K,O,fe):null,nn=Nt?n.jsx(rc,{state:Nt,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,Je=(Ee,Ve)=>{const{folder:Ne,scopeKey:Pe,scopeDirectory:He,nodes:dt}=Ee,sn=i?!1:m.has(Ne.id);return n.jsx(zm,{folderId:Ne.id,children:(Lt,Ot)=>n.jsx(Bm,{folder:Ne,displayName:Ve,sessions:dt,isCollapsed:sn,collapsedActivityState:sn?J.get(Ne.id)??null:null,onToggle:()=>b(Ne.id),onRename:Ye=>{g(Pe,Ne.id,Ye)},onDelete:()=>{if(!p){h(Pe,Ne.id);return}const Ye=se.filter(({folder:An})=>An.parentId===Ne.id).length,rn=dt.length;S({scopeKey:Pe,folderId:Ne.id,folderName:Ne.name,subFolderCount:Ye,sessionCount:rn})},renderSessionNode:y,getRenderExtras:pe?Ye=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:pe(Ye),childRenderExtrasFor:ne}):void 0,groupDirectory:He??t.directory,projectId:r,mobileVariant:A,alwaysShowActions:j,isRenaming:$===Ne.id,renameDraft:$===Ne.id?q:void 0,onRenameDraftChange:Ye=>F(Ye),onRenameSave:()=>{const Ye=q.trim();Ye&&g(Pe,Ne.id,Ye),E(null),F("")},onRenameCancel:()=>{E(null),F("")},droppableRef:Lt,isDropTarget:Ot,depth:0,onNewSession:()=>{r&&r!==k&&w(r),C("chat"),A&&R(!1),L({selectedProjectId:r,directoryOverride:He??t.directory,targetFolderId:Ne.id})},hideActions:!1})},Ne.id)},Mt=()=>{const Ee=new Map;for(const Pe of se){const He=Pe.folder.parentId;if(!He)continue;const dt=Ee.get(He);dt?dt.push(Pe):Ee.set(He,[Pe])}const Ve=[],Ne=(Pe,He)=>{const dt=He?`${He} / ${Pe.folder.name}`:Pe.folder.name;Ve.push(Je(Pe,dt)),!(!i&&m.has(Pe.folder.id))&&(Ee.get(Pe.folder.id)??[]).forEach(Lt=>Ne(Lt,dt))};return _e.forEach(Pe=>Ne(Pe,"")),Ve},Ft=j?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",vt=n.jsxs(Um,{scopeKey:ee[0]?.scopeKey??be,hasFolders:se.length>0,onSessionDroppedOnFolder:(Ee,Ve)=>{const Ne=se.find(({folder:He})=>He.id===Ve);if(!Ne)return;const Pe=gt.getState();for(const{scopeKey:He}of ee)He!==Ne.scopeKey&&Pe.getSessionFolderId(He,Ee)&&Pe.removeSessionFromFolder(He,Ee);U(Ne.scopeKey,Ve,Ee)},children:[Mt(),st.map(Ee=>n.jsx(l.Fragment,{children:y(Ee,0,t.directory,r,!1,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:pe(Ee),childRenderExtrasFor:ne})},Ee.session.id)),ze===0&&se.length===0&&!me?n.jsx(Xt,{icon:"chat-new",onClick:()=>{L({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,pt>0?n.jsx(Xt,{icon:"arrow-down-s",onClick:()=>v(s,st.length),children:pt===1?"Show 1 more session":`Show ${pt} more sessions`}):null,Xe?n.jsx(Xt,{icon:"arrow-up-s",onClick:()=>x(s),children:"Show fewer sessions"}):null]});return o?n.jsx("div",{className:"oc-group",children:n.jsx("div",{className:"oc-group-body",children:vt})}):n.jsxs("div",{className:"oc-group",children:[n.jsx(gg,{group:t,groupKey:s,isCollapsed:P,onToggleCollapsedGroup:ae,normalizedSessionSearchQuery:a,alwaysShowActions:j,groupHeaderRightPadding:Ft,dragHandleProps:X,groupPrColor:ge,groupPrSummary:ie,groupActivityIndicator:nn,showBranchSubtitle:Yt,statusLine:mt,projectId:r,activeProjectId:k,setActiveProjectIdOnly:w,setActiveMainTab:C,mobileVariant:A,setSessionSwitcherOpen:R,openNewSessionDraft:L}),P?null:n.jsx("div",{className:"oc-group-body",children:vt})]})}const jg=l.memo(Sg,wg);function kg(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:s,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:a,onOpenUpdate:c,headerActionIconClass:u,headerActionButtonClass:d,isSessionSearchOpen:f,setIsSessionSearchOpen:m,sessionSearchInputRef:b,sessionSearchQuery:g,setSessionSearchQuery:h,hasSessionSearchQuery:p,searchMatchCount:S,selectionModeEnabled:y,onToggleSelectionMode:v,mobileVariant:x=!1,onClose:A}=e;if(t)return null;const j=_(d,"text-muted-foreground hover:text-foreground",!x&&"hover:bg-transparent"),k=o?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,className:j,"aria-label":"Settings",children:n.jsx(D,{name:"settings-3",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Settings"})})]}):null,w=c?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:c,className:j,"aria-label":"Update",children:n.jsx(D,{name:"download",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Update"})})]}):null;return n.jsx("div",{className:_("select-none flex-shrink-0",x?"px-2":"px-2 py-1"),children:n.jsxs("div",{className:_("flex flex-col",x?"gap-0":"h-auto min-h-8 gap-1"),children:[n.jsxs("div",{className:_("flex items-center justify-between",x?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[n.jsxs("div",{className:_("flex min-w-0 items-center",x?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":x?"true":void 0,children:[x?n.jsx("h2",{className:"truncate pl-2 typography-ui-header font-semibold text-foreground",children:"Sessions"}):n.jsxs(n.Fragment,{children:[k,w]}),!x&&i?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:i,className:j,"aria-label":a?`Servers: ${a}`:"Servers",children:n.jsx(D,{name:"server",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:a||"Servers"})})]}):null,x?null:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:j,"aria-label":"Add folder",children:n.jsx(D,{name:"folder-add",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Add folder"})})]}),x?null:n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:r,className:j,"aria-label":"Archive",children:n.jsx(D,{name:"archive",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Archive"})})]})]}),n.jsxs("div",{className:_("flex shrink-0 items-center",x?"gap-1":"gap-1.5"),children:[x?n.jsxs(n.Fragment,{children:[k,w]}):null,n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>m(C=>!C),className:j,"aria-label":"Search sessions","aria-expanded":f,children:n.jsx(D,{name:"search",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"Search sessions"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:v,className:_(j,y&&"bg-interactive-hover text-primary"),"aria-label":y?"Exit selection":"Select sessions","aria-pressed":y,children:n.jsx(D,{name:"checkbox-multiple",className:u})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:y?"Exit selection":"Select sessions"})})]}),x&&A?n.jsx("button",{type:"button",onClick:A,className:j,"aria-label":"Close sessions",children:n.jsx(D,{name:"close",className:u})}):null]})]}),f?n.jsxs("div",{className:_(x?"pb-2":"pb-1"),children:[n.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-subtle-foreground",children:p?n.jsx("span",{children:S===1?`${S} match`:`${S} matches`}):n.jsx("span",{})}),n.jsxs("div",{className:"relative",children:[n.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),n.jsx("input",{ref:b,value:g,onChange:C=>h(C.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:C=>{C.key==="Escape"&&(C.stopPropagation(),p?h(""):m(!1))}}),g.length>0?n.jsx("button",{type:"button",onClick:()=>h(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:n.jsx(D,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const fo="0.75rem";function Cg(e){const t=de(o=>o.toggleSidebar),s=de(o=>o.shortcutOverrides),r=yi(Ar("toggle_sidebar",s));return n.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${fo})`}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${fo})))`}}),n.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsxs("button",{type:"button",onClick:e.onNewSession,className:_("group flex min-w-0 flex-1 items-center gap-1.5 text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),style:{paddingLeft:`max(3px, calc(${ch} - max(var(--oc-titlebar-left-inset, ${fo}), var(--oc-titlebar-overlay-width, 0px))))`},children:[n.jsx(D,{name:"chat-new",className:_(yr,"text-current")}),n.jsx("span",{className:Tl,children:"New session"})]}),e.showSidebarToggle?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Hide sessions",children:n.jsx(D,{name:"layout-left",className:"size-4"})})}),n.jsx(Ge,{children:n.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Wr({...e}){return n.jsx(nl,{...e})}function Gr({...e}){return n.jsx(sl,{...e})}function Hr({className:e,positionerClassName:t,children:s,style:r,...o}){return n.jsx(Io,{children:n.jsx(Eo,{className:_("app-region-no-drag z-50",t),children:n.jsx(Do,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Fo,e),...o,children:s})})})}function On({className:e,...t}){return n.jsx(rl,{className:_(bl,e),...t})}function vc({className:e,...t}){return n.jsx(ol,{className:_(xl,e),...t})}const Sc=500,Ag=({projectId:e,worktree:t,isSelected:s,hasActive:r,onSelect:o,onClose:i,mobileVariant:a=!1})=>{const[c,u]=l.useState(!1),d=l.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),m=l.useCallback(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]);l.useEffect(()=>()=>m(),[m]);const b=l.useCallback(()=>{m(),d.current=window.setTimeout(()=>{d.current=null,u(!0)},Sc)},[m]);return n.jsxs(Wr,{open:c,onOpenChange:u,children:[n.jsxs(Gr,{render:n.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:m,onTouchEnd:m,onTouchCancel:m,style:{touchAction:"manipulation"},className:_(Mr(a,s),"pl-6"),"aria-pressed":s,title:t.path}),children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsx(D,{name:"git-branch",className:_(_n(a),"text-muted-foreground")}),t.branch?n.jsx(Os,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):n.jsx("span",{className:hs(a),children:f})]}),n.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),n.jsx(Hr,{className:"min-w-[160px]",children:n.jsxs(On,{disabled:!i,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>i?.(e,t),className:"text-destructive focus:text-destructive",children:[n.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Close worktree"})]})})]})},Mr=(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"),Ng=({project:e,label:t,isSelected:s,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:a,canDrag:c,onSelect:u,onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:m=!1})=>{const{listeners:b,setNodeRef:g,transform:h,transition:p,isDragging:S}=mi({id:e.id,disabled:!c}),[y,v]=l.useState(!1),x=l.useRef(null),A=l.useCallback(()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null)},[]);l.useEffect(()=>()=>A(),[A]);const j=l.useCallback(()=>{A(),x.current=window.setTimeout(()=>{x.current=null,v(!0)},Sc)},[A]);return n.jsx("div",{ref:g,style:{transform:gi.Translate.toString(h),transition:p},className:_(S&&"opacity-60"),children:n.jsxs(Wr,{open:y,onOpenChange:v,children:[n.jsxs(Gr,{render:n.jsx("button",{type:"button",onClick:()=>{y||u()},onTouchStart:j,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Mr(m,s),"aria-pressed":s}),children:[n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[n.jsx("span",{className:_("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${t}`:void 0,...c?b:{},children:n.jsx(xi,{directory:e.normalizedPath,label:t,className:_n(m)})}),n.jsx("span",{className:hs(m),children:t})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?n.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:n.jsx(D,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?n.jsx(D,{name:a?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),n.jsxs(Hr,{className:"min-w-[160px]",children:[n.jsxs(On,{onClick:()=>d(e.id),children:[n.jsx(D,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Edit folder"})]}),n.jsx(vc,{}),n.jsxs(On,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[n.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),n.jsx("span",{children:"Close folder"})]})]})]})})},Ig=({projects:e,selectedProjectId:t,selectedWorktreePath:s=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:a,onCloseWorktree:c,onOpenDirectoryDialog:u,onOpenProjectEditDialog:d,onRemoveProject:f,hasActiveSessionByProject:m,activeDirectoriesByProject:b,homeDirectory:g,className:h,mobileVariant:p=!1})=>{const S=t===null,y=ct(j=>j.reorderProjects),v=e.length>1,x=Or(cs(cl,{activationConstraint:{distance:8}}),cs(ll,{activationConstraint:{delay:200,tolerance:6}})),A=l.useCallback(j=>{const{active:k,over:w}=j;if(!w||k.id===w.id)return;const C=ct.getState().projects,R=C.findIndex(U=>U.id===k.id),L=C.findIndex(U=>U.id===w.id);R<0||L<0||y(R,L)},[y]);return n.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",h),children:[n.jsx("button",{type:"button",onClick:()=>i(null),className:Mr(p,S),"aria-pressed":S,children:n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[n.jsx(D,{name:"chat-history",className:_n(p)}),n.jsx("span",{className:hs(p),children:"All sessions"})]})}),n.jsx(Br,{sensors:x,collisionDetection:pi,onDragEnd:A,children:n.jsx(il,{items:e.map(j=>j.id),strategy:al,children:e.map(j=>{const k=t===j.id,w=k&&!s,C=r.get(j.normalizedPath)??[],R=er(j,g),L=b?.get(j.id),U=De(j.normalizedPath)?.toLowerCase()??"",G=U?L?.has(U)??!1:!1,$=(L?.size??0)>0,q=m?.(j.id)??!1,F=b?k?G:$:q;return n.jsxs(l.Fragment,{children:[n.jsx(Ng,{project:j,label:R,isSelected:w,hasActive:F,hasWorktrees:C.length>0,worktreeError:o.get(j.normalizedPath),isExpanded:k,canDrag:v,onSelect:()=>i(j.id),onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:p}),k?C.map(E=>{const T=s===E.path,I=De(E.path)?.toLowerCase()??"",M=I?L?.has(I)??!1:!1,W=b?M:!1;return n.jsx(Ag,{projectId:j.id,worktree:E,isSelected:T,hasActive:W,onSelect:()=>a?.(j.id,E.path),onClose:c,mobileVariant:p},E.path)}):null]},j.id)})})}),n.jsxs("button",{type:"button",onClick:u,className:Mr(p,!1),children:[n.jsx(D,{name:"add",className:_n(p)}),n.jsx("span",{className:hs(p),children:"Add folder"})]})]})},ho="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 Eg({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:s,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:n.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?n.jsxs(n.Fragment,{children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:e,className:ho,"aria-label":"Settings",children:n.jsx(D,{name:"settings-3",className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Settings"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,className:ho,"aria-label":"Shortcuts",children:n.jsx(D,{name:"command",className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Shortcuts"})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:ho,"aria-label":"About PiChamber",children:n.jsx(D,{name:"information",className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"About PiChamber"})})]})]}):null,i?n.jsx(Ae,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:r,children:"Update"}):null]})}const Ca="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-[opacity,background-color,color] hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Aa="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",jc=({projectLabel:e,projectPath:t=null,mobileVariant:s=!1})=>{const r=_n(s),o=hs(s);return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?n.jsx(xi,{directory:t,label:e,className:r}):n.jsx(D,{name:"folder",className:_(r,"text-subtle-foreground")})}),n.jsx("span",{className:_(o,"font-medium text-foreground"),children:e})]})},kc=({isCollapsed:e,mobileVariant:t=!1,className:s})=>n.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",s),children:n.jsx(D,{name:e?"arrow-right-s":"arrow-down-s",className:_n(t)})}),Dg=({id:e,disabled:t=!1,projectLabel:s,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:a,mobileVariant:c,alwaysShowActions:u,stickyHeader:d=!1,onToggle:f,onNewSession:m,onRenameStart:b,onClose:g,children:h,showCreateButtons:p=!0,hideHeader:S=!1,openSidebarMenuKey:y,setOpenSidebarMenuKey:v,statusIndicator:x=null,sessionCount:A=null,isEmpty:j=!1})=>{const{listeners:k,setNodeRef:w,transform:C,transition:R,isDragging:L}=mi({id:e,disabled:t}),U=l.useRef(!1),G=`project:${e}`,$=y===G,[q,F]=l.useState(!1),E=d&&!i,T=!a&&!u,I=l.useCallback(ue=>{ue&&F(!1),v(ue?G:null)},[G,v]),M=ue=>n.jsxs(n.Fragment,{children:[p&&!a&&m&&n.jsxs(ue,{onClick:m,children:[n.jsx(D,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),n.jsxs(ue,{onClick:b,children:[n.jsx(D,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),n.jsxs(ue,{onClick:g,className:"text-destructive focus:text-destructive",children:[n.jsx(D,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),W=l.useCallback(ue=>{ue.stopPropagation()},[]),K=l.useCallback(ue=>{ue.stopPropagation()},[]),O=l.useCallback(ue=>{ue.stopPropagation()},[]),ae=l.useCallback(ue=>{(ue.button===2||ue.button===0&&ue.ctrlKey)&&(U.current=!0)},[]),X=l.useCallback(ue=>{if(ue.currentTarget.blur(),U.current){U.current=!1;return}f()},[f]);return n.jsxs("div",{ref:w,style:{transform:gi.Translate.toString(C),transition:R},className:_("relative",L&&"opacity-60"),children:[S?null:n.jsxs(Wr,{open:q,onOpenChange:F,children:[n.jsxs(Gr,{render:n.jsx("div",{className:_("text-left group/project select-none",E&&"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":E?"true":void 0,onContextMenu:ue=>{a||L||(ue.preventDefault(),F(!0))}}),children:[n.jsxs("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:ae,onClick:X,...k,className:_(Kr,"flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing"),children:[n.jsx(jc,{id:e,projectLabel:s,projectPath:r,mobileVariant:c}),A?n.jsx("span",{className:"shrink-0 typography-micro text-subtle-foreground tabular-nums","aria-label":A===1?"1 session":`${A} sessions`,children:A}):null,x?n.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:x}):null,n.jsx(kc,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",j&&"invisible",T&&"group-hover/project:pl-14 group-focus-within/project:pl-14","pl-2")})]})}),u?null:n.jsx(Ge,{side:"right",sideOffset:8,children:o})]}),T?n.jsxs("div",{className:_("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5",j?"right-2":"right-7"),children:[p&&m?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:ue=>{ue.stopPropagation(),m()},className:_(Ca,Aa),"aria-label":"New session",children:n.jsx(D,{name:"add",className:"size-4"})})}),n.jsx(Ge,{side:"bottom",sideOffset:4,children:n.jsx("p",{children:"New session"})})]}):null,n.jsxs(Gt,{open:$,onOpenChange:I,children:[n.jsx(Ht,{asChild:!0,children:n.jsx("button",{type:"button",className:_(Ca,$?"opacity-100 pointer-events-auto bg-interactive-active text-foreground":Aa),"aria-label":"Folder menu",onPointerDown:K,onMouseDown:O,onClick:W,children:n.jsx(D,{name:"more-fill",className:"size-4"})})}),n.jsx(qt,{align:"end",className:"min-w-[180px]",children:M(ut)})]})]}):null]}),E?n.jsx("span",{"aria-hidden":!0,className:"oc-sidebar-sticky-header-fade pointer-events-none absolute inset-x-0 top-full h-4 bg-gradient-to-b from-sidebar to-transparent"}):null]}),n.jsx(Hr,{className:"min-w-[180px]",children:M(On)})]}),h]})},Rg=({id:e,disabled:t=!1,children:s})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:u}=mi({id:e,disabled:t}),d=l.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return n.jsx("div",{ref:o,style:{transform:gi.Transform.toString(a),transition:c},className:_("space-y-0.5 rounded-md",u&&"opacity-50"),children:typeof s=="function"?s(d):s})};l.memo(Rg);const Pg=e=>e.session.time?.updated||e.session.time?.created||0,Tg=(e,t)=>{const s={pinned:[],active:[],working:[],snoozed:[]},r=new Map,o=new Set;for(const a of e){const c=a.node.session.id,u=t.entries[c],d={entry:u,pinned:a.isPinned,working:t.working.has(c),needsInput:t.needsInput.has(c),updatedAt:Pg(a.node),now:t.now,workingShelf:t.workingShelf},f=Bd(d);r.set(c,f),f!=="snoozed"&&_d(u,t.now)&&o.add(c);const m=f==="snoozed"?-(u?.snoozedUntil??0):zd(d);s[f].push({item:a,key:m})}const i=a=>s[a].sort((c,u)=>u.key-c.key).map(({item:c})=>c);return{pinned:i("pinned"),active:i("active"),working:i("working"),snoozed:i("snoozed"),sectionById:r,wokeIds:o}},Mg=(e,t)=>{const s=(r,o)=>r.length===o.length&&r.every((i,a)=>i===o[a]);if(e.wokeIds.size!==t.wokeIds.size)return!1;for(const r of e.wokeIds)if(!t.wokeIds.has(r))return!1;return s(e.pinned,t.pinned)&&s(e.active,t.active)&&s(e.working,t.working)&&s(e.snoozed,t.snoozed)},Fg=6e4,Lg=1500,Og=(e,t)=>{const[s,r]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!e||typeof document>"u")return;let o=null;const i=()=>{r(Date.now()),o===null&&(o=window.setInterval(()=>r(Date.now()),Fg))},a=()=>{o!==null&&window.clearInterval(o),o=null},c=()=>document.visibilityState==="visible"?i():a();return c(),document.addEventListener("visibilitychange",c),()=>{a(),document.removeEventListener("visibilitychange",c)}},[e]),l.useEffect(()=>{if(!e||t===null)return;const o=Math.min(Math.max(0,t-Date.now())+50,2**31-1),i=window.setTimeout(()=>r(Date.now()),o);return()=>window.clearTimeout(i)},[e,t]),s},Bg=(e,t)=>{const s=Ys(o=>o.load);l.useEffect(()=>{if(!e)return;s();const o=()=>{document.visibilityState==="visible"&&s()};document.addEventListener("visibilitychange",o);const i=gs(()=>{s()});return()=>{document.removeEventListener("visibilitychange",o),i()}},[e,s]);const r=l.useRef(t);l.useEffect(()=>{const o=r.current;if(r.current=t,!e)return;let i=!1;for(const c of t)if(!o.has(c)){i=!0;break}if(!i)return;const a=window.setTimeout(()=>{s()},Lg);return()=>window.clearTimeout(a)},[e,t,s])},_g=(e,{enabled:t,workingShelf:s})=>{const r=Ys(b=>t?b.entries:zg),{working:o,needsInput:i}=Ud(t),a=l.useMemo(()=>$d(r,Date.now()),[r]),c=Og(t,a);Bg(t,o);const u=l.useRef(null),d=l.useMemo(()=>{if(!t)return null;const b=Tg(e,{entries:r,working:o,needsInput:i,now:c,workingShelf:s});return u.current&&Mg(u.current,b)&&u.current.sectionById.size===b.sectionById.size&&[...b.sectionById].every(([h,p])=>u.current.sectionById.get(h)===p)?u.current:b},[t,e,r,o,i,c,s]);u.current=d;const f=Fe(b=>b.currentSessionId),m=!!(t&&f&&d?.wokeIds.has(f));return l.useEffect(()=>{!m||!f||Ys.getState().update(f,{snoozedUntil:null}).catch(b=>console.warn("[session-shelf] could not clear a finished snooze",b))},[m,f]),d},zg=Object.freeze({}),li=(e,t,s,r)=>{Ys.getState().update(e,t,s??void 0).catch(o=>{console.warn("[session-shelf] update failed",o),oe.error(r)})},Na={snoozed:"Snoozed"},Cc="oc.sidebar.shelves.expanded",Ug=()=>{try{const e=rs().getItem(Cc),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(s=>s==="snoozed")):new Set}catch{return new Set}},$g=()=>{const[e,t]=l.useState(Ug),s=l.useCallback(r=>{t(o=>{const i=new Set(o);i.has(r)?i.delete(r):i.add(r);try{rs().setItem(Cc,JSON.stringify([...i]))}catch{}return i})},[]);return{expanded:e,toggle:s}},Ia=({target:e,dragging:t,className:s,children:r})=>{const{setNodeRef:o,isOver:i}=tl({id:`shelf-drop:${e}`,data:{type:"shelf",target:e}});return n.jsx("div",{ref:o,"data-shelf-drop":e,className:_("rounded-xl transition-colors",t&&"outline outline-1 -outline-offset-1 outline-transparent",t&&i&&"bg-interactive-hover outline-[var(--interactive-border)]",s),children:r})},Kg=["snoozed"],Ac=({shelfIds:e,shelves:t,renderItem:s,hasSessionSearchQuery:r,className:o})=>{const{expanded:i,toggle:a}=$g(),c=d=>r||i.has(d),u=e.filter(d=>t[d].length>0);return u.length===0?null:n.jsx("div",{className:o,children:u.map(d=>{const f=t[d],m=c(d);return n.jsxs("section",{"aria-label":Na[d],"data-session-shelf":d,children:[n.jsx(as,{label:Na[d],count:f.length,expanded:m,onToggle:()=>a(d)}),m?f.map(s):null]},d)})})},Wg=({items:e,shelves:t,renderSessionNode:s,hasSessionSearchQuery:r,mobileVariant:o,emptyState:i,searchEmptyState:a})=>{const[c,u]=l.useState(null),d=Or(cs(Za,{activationConstraint:{distance:8}})),f=l.useMemo(()=>({sectionById:t.sectionById,wokeIds:t.wokeIds}),[t.sectionById,t.wokeIds]),m=x=>n.jsx(l.Fragment,{children:s(x.node,0,x.node.session.directory??x.project.normalizedPath,x.project.id,!1,{projectLabel:x.projectLabel,showFolderLabel:!0,globalSession:x.globalSession},"project")},x.node.session.id),b=x=>{const A=x.active.data.current;if(A?.type!=="session"||!A.sessionId)return;const j=x.active.rect.current.initial?.width;u({sessionId:A.sessionId,title:A.sessionTitle??"Session",width:typeof j=="number"?j:null})},g=x=>{u(null);const A=x.active.data.current,j=x.over?.data.current;if(A?.type!=="session"||!A.sessionId||j?.type!=="shelf"||!j.target)return;const k=A.sessionId,w=A.sessionDirectory??null,C=t.sectionById.get(k);C&&Gg(k,w,C,j.target)};if(e.length===0)return n.jsx(n.Fragment,{children:r?a:i});const h=!!c,p=t.pinned.length>0||h,S=t.working.length>0,y=p||S||t.snoozed.length>0,v=n.jsxs("div",{className:"flex min-h-full flex-1 flex-col","data-sidebar-threads":"",children:[p?n.jsxs(Ia,{target:"pinned",dragging:h,children:[n.jsx(as,{label:"Pinned",first:!0}),t.pinned.map(m),h&&t.pinned.length===0?n.jsx("div",{className:"px-3 py-2 typography-micro text-subtle-foreground",children:"Drop here to pin"}):null]}):null,S?n.jsxs("section",{"aria-label":"Working","data-session-shelf":"working",children:[n.jsx(as,{label:"Working",first:!p}),t.working.map(m)]}):null,n.jsxs(Ia,{target:"active",dragging:h,children:[y?n.jsx(as,{label:"Recent",first:!p&&!S}):null,t.active.map(m),t.active.length===0&&!r?n.jsx("div",{className:"px-3 py-1.5 typography-micro text-subtle-foreground",children:h?"Drop here to keep it in the list":t.snoozed.length>0?"Nothing recent. Snoozed sessions are below.":"Nothing recent."}):null]}),n.jsx(Ac,{shelfIds:Kg,shelves:t,renderItem:m,hasSessionSearchQuery:r,className:"mt-auto border-t border-border pt-1"})]});return n.jsx($r.Provider,{value:f,children:o?v:n.jsxs(Br,{sensors:d,collisionDetection:od,onDragStart:b,onDragCancel:()=>u(null),onDragEnd:g,children:[v,n.jsx(el,{children:c?n.jsx("div",{style:{width:c.width?`${c.width}px`:"auto"},className:"pointer-events-none flex items-center rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2",children:n.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:c.title})}):null})]})})},Gg=(e,t,s,r)=>{const o=qs.getState(),i=Zs(o.ids,t,e),a=c=>{!t||i===c||o.toggle({directory:t,sessionId:e})};s==="snoozed"&&li(e,{snoozedUntil:null},t,"Could not wake the session"),a(r==="pinned")},Hg=l.memo(Wg),qg=["snoozed"],Ea=(e,t)=>{let s=!1;const r=e.groups.map(o=>{const i=o.sessions.filter(a=>!t.has(a.session.id));return i.length===o.sessions.length?o:(s=!0,{...o,sessions:i})});return s?{...e,groups:r}:e},Da=e=>e.groups.reduce((t,s)=>t+s.sessions.length,0),Ra="pt-0.5 pb-1",Yg=({shelves:e=null,sections:t,homeSection:s,homeDirectory:r,collapsedProjects:o,toggleProject:i,hasSessionSearchQuery:a,activeProjectId:c,hideDirectoryControls:u,mobileVariant:d,alwaysShowActions:f,isInlineEditing:m,stickyFolderHeaders:b,renderGroupSessions:g,renderSessionNode:h,getOrderedGroups:p,renderProjectStatusIndicator:S,setActiveProjectIdOnly:y,setActiveMainTab:v,setSessionSwitcherOpen:x,openNewSessionDraft:A,openProjectEditDialog:j,removeProject:k,reorderProjects:w,openSidebarMenuKey:C,setOpenSidebarMenuKey:R,onOpenDirectoryDialog:L,emptyState:U,searchEmptyState:G})=>{const $=a?null:e,q=l.useMemo(()=>{if(!$)return null;const P=new Set;for(const H of[...$.pinned,...$.snoozed])P.add(H.node.session.id);return P},[$]),F=l.useMemo(()=>q?t.map(P=>Ea(P,q)):t,[t,q]),E=l.useMemo(()=>q&&s?Ea(s,q):s,[s,q]),T=l.useMemo(()=>e?{sectionById:e.sectionById,wokeIds:e.wokeIds}:null,[e]),I=P=>n.jsx(l.Fragment,{children:h?.(P.node,0,P.node.session.directory??P.project.normalizedPath,P.project.id,!1,{projectLabel:P.projectLabel,showFolderLabel:!0,globalSession:P.globalSession},"project")},P.node.session.id),M=Or(cs(cl,{activationConstraint:{distance:8}}),cs(ll,{activationConstraint:{delay:200,tolerance:6}})),W=F.length>1&&!a&&!m,K=l.useCallback(P=>{if(m||a)return;const{active:H,over:Q}=P;if(!Q||H.id===Q.id)return;const re=ct.getState().projects,ie=re.findIndex(me=>me.id===H.id),ge=re.findIndex(me=>me.id===Q.id);ie<0||ge<0||ie===ge||w(ie,ge)},[m,a,w]),[O,ae]=l.useState(5);l.useEffect(()=>{ae(5)},[a]);const X=l.useMemo(()=>E?E.groups.flatMap(P=>P.sessions):[],[E]),ue=a||$?X:X.slice(0,O),Ie=X.length-ue.length,V=a?!1:o.has("__home__");return F.length===0&&!E?a?G:U:n.jsx($r.Provider,{value:T,children:n.jsxs("div",{className:$?"flex min-h-full flex-1 flex-col gap-1":"space-y-1",children:[$&&$.pinned.length>0?n.jsx(Qs.Provider,{value:"card",children:n.jsxs("section",{"aria-label":"Pinned","data-session-shelf":"pinned",children:[n.jsx(as,{label:"Pinned",first:!0}),$.pinned.map(I)]})}):null,n.jsx(Br,{sensors:M,collisionDetection:pi,onDragEnd:K,children:n.jsx(il,{items:F.map(P=>P.project.id),strategy:al,children:F.map(P=>{const H=P.project,Q=H.id,re=er(H,r),ie=Bo(H.normalizedPath,r),ge=a?!1:o.has(Q),me=ge?[]:p(Q,P.groups),Ce=ge?null:me.find(Le=>Le.isMain)??null,je=ge?[]:Ce?me.filter(Le=>Le.id!==Ce.id):me;return n.jsx(Dg,{id:Q,disabled:!W,projectLabel:re,projectPath:H.normalizedPath,projectDescription:ie,isCollapsed:ge,hideDirectoryControls:u,mobileVariant:d,alwaysShowActions:f,stickyHeader:b,statusIndicator:ge?S?.(Q,P.groups):null,sessionCount:ge?Da(P):null,isEmpty:!!$&&Da(P)===0,onToggle:()=>i(Q),onNewSession:()=>{Q!==c&&y(Q),v("chat"),d&&x(!1),A({selectedProjectId:Q,directoryOverride:H.normalizedPath})},onRenameStart:()=>j(Q),onClose:()=>k(Q),openSidebarMenuKey:C,setOpenSidebarMenuKey:R,children:ge?null:n.jsxs("div",{className:Ra,children:[Ce?g(Ce,`${Q}:${Ce.id}`,Q,!0,null):null,je.map(Le=>{const we=`${Q}:${Le.id}`,Re=me.length===1;return n.jsx(l.Fragment,{children:g(Le,we,Q,Re,null)},Le.id)})]})},Q)})})}),E?n.jsxs("div",{children:[n.jsx("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:n.jsxs("button",{type:"button","aria-expanded":!V,style:{touchAction:"manipulation"},onClick:()=>i("__home__"),className:`${Kr} flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md`,children:[n.jsx(jc,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),n.jsx(kc,{isCollapsed:V,mobileVariant:d})]})}),V?null:n.jsxs("div",{className:Ra,children:[ue.map(P=>n.jsx(l.Fragment,{children:h?.(P,0,P.session.directory??"~","__home__",!1,{globalSession:!0},"project")},P.session.id)),!a&&Ie>0?n.jsx(Xt,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>ae(P=>P+7),children:Ie===1?"Show 1 more session":`Show ${Ie} more sessions`}):null,!a&&O>5&&X.length>5?n.jsx(Xt,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>ae(5),children:"Show fewer sessions"}):null]})]}):null,!u&&L?n.jsx(Xt,{icon:"add",mobileVariant:d,onClick:L,children:"Add folder"}):null,$?n.jsx(Qs.Provider,{value:"card",children:n.jsx(Ac,{shelfIds:qg,shelves:$,renderItem:I,hasSessionSearchQuery:a,className:"mt-auto border-t border-border pt-1"})}):null]})})},Vg=l.memo(Yg);function Qg(e){Wt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",s=t==="timeline",r=l.useRef(new Map),o=l.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(v,x)=>{const A=r.current,j=A.get(v);if(j&&j.groups===x)return j.ordered;const k=e.getOrderedGroups(v,x);if(A.set(v,{groups:x,ordered:k}),A.size>256){const w=A.keys().next().value;w!==void 0&&A.delete(w)}return k},a=t==="threads",c=t==="folder",u=!!(e.isAllFoldersView||s||a||c),d=l.useMemo(()=>{if(!u)return[];const v=[],x=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const A of x){const j=er(A.project,e.homeDirectory);for(const k of A.groups)for(const w of k.sessions){const C=e.pinnedSessionIds?Zs(e.pinnedSessionIds,w.session.directory??A.project.normalizedPath,w.session.id):!1,R=w.session.time?.updated||w.session.time?.created||0;v.push({node:w,project:A.project,projectLabel:j,isPinned:C,timestamp:R,globalSession:A===e.allFoldersOnlySection})}}return v.sort((A,j)=>A.isPinned!==j.isPinned?A.isPinned?-1:1:j.timestamp-A.timestamp),v},[e.allFoldersOnlySection,u,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),f=_g(d,{enabled:a||c,workingShelf:a}),[m,b]=l.useState(30);l.useEffect(()=>{b(30)},[e.hasSessionSearchQuery]);const g=l.useMemo(()=>d.slice(0,m),[d,m]),h=l.useMemo(()=>e.timelineBoundaries??Xo(Date.now(),1),[e.timelineBoundaries]),p=l.useMemo(()=>s?am(g,{getTimestamp:v=>v.timestamp,isPinned:v=>v.isPinned,boundaries:h}):[],[s,g,h]);if(e.sharedSessionsOnly)return n.jsx(Mn,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const S=(e.isAllFoldersView||t==="timeline"||t==="folder")&&!!e.allFoldersOnlySection;if(e.projectSections.length===0&&!S)return n.jsx(Mn,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!S)return n.jsx(Mn,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:n.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const y=()=>{const v=d.length-g.length;return n.jsxs(n.Fragment,{children:[v>0?n.jsx(Xt,{icon:"arrow-down-s",onClick:()=>b(x=>x+30),children:v===1?"Show 1 more session":`Show ${v} more sessions`}):null,m>30&&d.length>30?n.jsx(Xt,{icon:"arrow-up-s",onClick:()=>b(30),children:"Show fewer sessions"}):null]})};return n.jsx("div",{className:"relative flex min-h-0 flex-1",children:n.jsx(Mn,{useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",children:n.jsxs("div",{className:_((a||c&&f&&!e.hasSessionSearchQuery)&&!e.showOnlyMainWorkspace?"flex min-h-full flex-col gap-1 px-2":"space-y-1 px-2"),children:[e.topContent,e.showOnlyMainWorkspace?n.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const v=e.sectionsForRender.find(j=>j.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!v)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const x=v.groups.find(j=>j.isMain&&j.sessions.length>0)??v.groups.find(j=>j.sessions.length>0)??v.groups.find(j=>j.isMain)??v.groups[0];if(!x)return n.jsx(Xt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:v.project.id,directoryOverride:v.project.normalizedPath}),children:"New session"});const A=`${v.project.id}:${x.id}`;return n.jsx(l.Fragment,{children:e.renderGroupSessions(x,A,v.project.id,!0,null,!0)},A)})()}):a&&f&&e.renderSessionNode?n.jsx(Hg,{items:d,shelves:f,renderSessionNode:e.renderSessionNode,hasSessionSearchQuery:e.hasSessionSearchQuery,mobileVariant:e.mobileVariant,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState}):t==="folder"?n.jsx(Qs.Provider,{value:"tree",children:n.jsx(Vg,{shelves:f,sections:e.sectionsForRender,homeSection:e.allFoldersOnlySection,homeDirectory:e.homeDirectory,collapsedProjects:e.collapsedProjects,toggleProject:e.toggleProject,hasSessionSearchQuery:e.hasSessionSearchQuery,activeProjectId:e.activeProjectId,hideDirectoryControls:e.hideDirectoryControls,mobileVariant:e.mobileVariant,alwaysShowActions:e.alwaysShowActions,isInlineEditing:e.isInlineEditing,stickyFolderHeaders:e.stickyFolderHeaders,renderGroupSessions:e.renderGroupSessions,renderSessionNode:e.renderSessionNode,getOrderedGroups:i,renderProjectStatusIndicator:e.renderProjectStatusIndicator,setActiveProjectIdOnly:e.setActiveProjectIdOnly,setActiveMainTab:e.setActiveMainTab,setSessionSwitcherOpen:e.setSessionSwitcherOpen,openNewSessionDraft:e.openNewSessionDraft,openProjectEditDialog:e.openProjectEditDialog,removeProject:e.removeProject,reorderProjects:e.reorderProjects,openSidebarMenuKey:e.openSidebarMenuKey,setOpenSidebarMenuKey:e.setOpenSidebarMenuKey,onOpenDirectoryDialog:e.onOpenDirectoryDialog,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState})}):t==="timeline"&&e.renderSessionNode?n.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:n.jsxs(n.Fragment,{children:[p.map((v,x)=>{const A=rm[v.id];return n.jsxs("section",{"aria-label":A,"data-timeline-bucket":v.id,children:[n.jsx(as,{label:A,first:x===0}),v.items.map(({node:j,project:k,projectLabel:w,globalSession:C})=>{const R=j.session.directory??k.normalizedPath;return n.jsx(l.Fragment,{children:e.renderSessionNode(j,0,R,k.id,!1,{projectLabel:w,showFolderLabel:!0,globalSession:C},"project")},j.session.id)})]},v.id)}),y()]})}):e.isAllFoldersView&&e.renderSessionNode?n.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:n.jsxs(n.Fragment,{children:[g.map(({node:v,project:x,projectLabel:A,globalSession:j})=>{const k=v.session.directory??x.normalizedPath;return n.jsx(l.Fragment,{children:e.renderSessionNode(v,0,k,x.id,!1,{projectLabel:A,showFolderLabel:!0,globalSession:j},"project")},v.session.id)}),y()]})}):n.jsx("div",{children:e.sectionsForRender.map(v=>{const x=v.project.id,A=i(x,v.groups),j=A.find(w=>w.isMain)??null,k=j?A.filter(w=>w.id!==j.id):A;return n.jsxs("div",{children:[j?e.renderGroupSessions(j,`${x}:${j.id}`,x,!0,null):null,k.map(w=>{const C=`${x}:${w.id}`,R=A.length===1;return n.jsx(l.Fragment,{children:e.renderGroupSessions(w,C,x,R,null)},w.id)})]},x)})})]})})})}const Jg=l.memo(Qg);let ci=!1;const ui=new Set;let Pa=!1;function Xg(){for(const e of ui)e()}function Ci(e){ci!==e&&(ci=e,Xg())}function Zg(e){e.key==="Shift"&&Ci(!0)}function eb(e){e.key==="Shift"&&Ci(!1)}function tb(){Ci(!1)}function nb(){Pa||typeof window>"u"||(Pa=!0,window.addEventListener("keydown",Zg),window.addEventListener("keyup",eb),window.addEventListener("blur",tb))}function sb(e){return nb(),ui.add(e),()=>{ui.delete(e)}}function rb(){return ci}function ob(){return!1}function ib(){return Te.useSyncExternalStore(sb,rb,ob)}const ab=l.memo(function({archiveLabel:t,deleteLabel:s,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:a,onArchive:c,onDelete:u}){const d=ib(),f=d?s:t,m=b=>{if(d||b.shiftKey){u(b);return}c(b)};return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",className:_("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",d?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:i,onMouseDown:a,onClick:m,onKeyDown:b=>b.stopPropagation(),children:n.jsx(D,{name:d?"delete-bin":"archive",className:o})})}),n.jsx(Ge,{side:"left",sideOffset:8,children:f})]})}),lb=l.memo(function({open:t,onOpenChange:s,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:a}){return n.jsx(en,{open:t,onOpenChange:s,children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Export Markdown"}),n.jsx(Cn,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} sub-agent tasks. Include them in the export?`})]}),n.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:o,onChange:c=>i(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),n.jsxs(ms,{children:[n.jsx(Ae,{type:"button",onClick:()=>s(!1),variant:"outline",size:"sm",children:"Cancel"}),n.jsx(Ae,{type:"button",onClick:()=>{s(!1),a(o)},size:"sm",children:"Export"})]})]})})});function cb(e,t){const{session:s,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:a,isElectron:c,pendingRenameRef:u,handleCopySessionId:d,togglePinnedSession:f,handleExportSession:m,handleOpenMiniChatWindow:b,handleDeleteSession:g,handleRestoreSession:h,shelfActions:p}=e,{Item:S,Separator:y,Sub:v,SubTrigger:x,SubContent:A}=t;return n.jsxs(n.Fragment,{children:[n.jsxs(S,{onClick:()=>{u.current={id:s.id,title:r}},className:"[&>svg]:mr-1",children:[n.jsx(D,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),n.jsxs(S,{onClick:()=>d(s.id),className:"[&>svg]:mr-1",children:[n.jsx(D,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),n.jsxs(S,{onClick:()=>o&&f({directory:o,sessionId:s.id}),className:"[&>svg]:mr-1",children:[i?n.jsx(D,{name:"unpin",className:"mr-1 h-4 w-4"}):n.jsx(D,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),p&&!a?n.jsx(n.Fragment,{children:p.section==="snoozed"?n.jsxs(S,{onClick:p.onWake,className:"[&>svg]:mr-1",children:[n.jsx(D,{name:"alarm",className:"mr-1 h-4 w-4"}),"Wake session"]}):n.jsxs(v,{children:[n.jsxs(x,{className:"[&>svg:first-child]:mr-1",children:[n.jsx(D,{name:"alarm",className:"mr-1 h-4 w-4"}),"Snooze"]}),n.jsx(A,{className:"min-w-[200px]",children:Kd(new Date).map(j=>n.jsxs(S,{onClick:()=>p.onSnooze(j.snoozedUntil),children:[n.jsx("span",{className:"flex-1",children:j.label}),n.jsx("span",{className:"ml-4 typography-micro text-muted-foreground tabular-nums",children:j.whenLabel})]},j.id))})]})}):null,n.jsxs(S,{onClick:()=>{m()},className:"[&>svg]:mr-1",children:[n.jsx(D,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?n.jsxs(S,{disabled:!o,onClick:b,className:"[&>svg]:mr-1",children:[n.jsx(D,{name:"window",className:"mr-1 h-4 w-4"}),n.jsx("span",{className:"truncate",children:"Open in Mini Chat window"})]}):null,n.jsx(y,{}),a?null:n.jsxs(S,{className:"[&>svg]:mr-1",onClick:()=>g(s,{archivedBucket:a}),children:[n.jsx(D,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?n.jsxs(S,{className:"[&>svg]:mr-1",onClick:()=>h(s),children:[n.jsx(D,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Unarchive"]}):null,n.jsxs(S,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>g(s,{archivedBucket:a,hardDelete:!0}),children:[n.jsx(D,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function ub(e){const{renamingFolderId:t,editingIdRef:s}=e;return n.jsx(Io,{children:n.jsx(Eo,{className:"app-region-no-drag z-50",children:n.jsx(Do,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||s.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Fo,"min-w-[180px]"),children:cb(e,{Item:({className:r,...o})=>n.jsx(rl,{className:_(bl,r),...o}),Separator:({className:r,...o})=>n.jsx(ol,{className:_(xl,r),...o}),Sub:id,SubTrigger:({className:r,children:o,...i})=>n.jsxs(ad,{className:_(Wd,r),...i,children:[o,n.jsx(D,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:r,children:o,...i})=>n.jsx(Io,{children:n.jsx(Eo,{className:"app-region-no-drag z-50",children:n.jsx(Do,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:_(Fo,r),...i,children:o})})})})})})})}const po=new WeakMap,db=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),s=t?.closest(".overlay-scrollbar-container");if(!t||!s)return;po.get(s)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,a=null;const c=()=>{i=!0,a!==null&&window.cancelAnimationFrame(a),a=null,po.delete(s),s.removeEventListener("wheel",c),s.removeEventListener("touchstart",c)},u=()=>{if(i||!t.isConnected||!s.isConnected){c();return}const d=t.getBoundingClientRect().top-r;if(Math.abs(d)>.5&&(s.scrollTop+=d,Wt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}a=window.requestAnimationFrame(u)};s.addEventListener("wheel",c,{passive:!0}),s.addEventListener("touchstart",c,{passive:!0}),po.set(s,c),a=window.requestAnimationFrame(u)};function fb(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const s=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${s} ${r}, ${o}, ${i}:${a}`}function hb(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",s=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&s?`${t}/${s}`:s||t}function pb(e){const t=e.info.role==="user"?"User":"Assistant",s=fb(e.info.time?.created),r=hb(e),o=s&&r?`${s} (${r})`:s||r;return o?`**${t}**
21
-
22
- *${o}*`:`**${t}**`}function mb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function Nc(e){const t=pb(e),s=mb(e.parts).trim();return s?`${t}
23
-
24
- ${s}`:""}function Ic(e,t){const s="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${s} Sub-agent: ${e.title}${r}
25
-
26
- ---
27
-
28
- `,i=e.records.map(Nc).filter(Boolean).join(`
29
-
30
- ---
31
-
32
- `),a=[o+i];for(const c of e.children)a.push(Ic(c,t+1));return a.join(`
33
-
34
- ---
35
-
36
- `)}function Ec(e,t,s){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
37
-
38
- *Exported on ${o}*
39
-
40
- ---
41
-
42
- `,a=e.map(Nc).filter(Boolean).join(`
43
-
44
- ---
45
-
46
- `);let c=i+a;if(s&&s.length>0){const u=s.map(d=>Ic(d,1)).join(`
47
-
48
- ---
49
-
50
- `);c+=`
51
-
52
- ---
53
-
54
- `+u}return c}function Dc(e,t){mh({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(s=>console.warn("[export] Markdown save failed",s))}async function Rc(e,t){const s=await _f(t,e);return s||null}async function gb(e){const t=Nl()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await zf(e)?!0:Il(e)}function bb(){return Uf()}function Pc(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const Fr=e=>{const t=[],s=r=>{r.children.forEach(o=>{t.push(o.session.id),s(o)})};return s(e),t};function xb(e,t){const[s,r]=l.useState(!1),[o,i]=l.useState(!0),a=e.session,c=l.useMemo(()=>Fr(e).length,[e]),u=l.useCallback(async b=>{const g=[];let h=0;for(const p of b)try{if(!t)throw new Error("Session directory is required for export");const S=[],y=p.session.title||"Untitled Sub-agent",v=typeof p.session.agent=="string"?p.session.agent:void 0,x=await u(p.children);h+=x.skipped,g.push({title:y,agent:v,records:S,children:x.children})}catch{h+=Fr(p).length+1}return{children:g,skipped:h}},[t]),d=l.useCallback(b=>{b<=0||oe.warning(b===1?`Exported session, but skipped ${b} sub-agent task that could not be loaded.`:`Exported session, but skipped ${b} sub-agent tasks that could not be loaded.`)},[]),f=l.useCallback(async b=>{if(!t){oe.error("Nothing to export");return}const g=[];if(g.length===0){oe.error("Nothing to export");return}let h,p=0;if(b&&e.children.length>0){const x=await u(e.children);h=x.children,p=x.skipped}const S=Ec(g,a.title??null,h),y=Pc(a.title??null),v=await Rc(S,y);if(v){oe.success("Session exported",{action:{label:bb(),onClick:()=>{gb(v).then(x=>{x||oe.error("Failed to reveal path")})}}}),d(p);return}Dc(S,y),oe.success("Session exported"),d(p)},[u,e.children,a.title,t,d]),m=l.useCallback(async()=>{if(e.children.length>0){i(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:s,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,descendantCount:c,handleExportSession:m,doExportSession:f}}const yb=(e,t)=>{if(!t)return Array.from(e);const s=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),s.push(o));const i=t.get(o);if(i)for(const a of i)r.has(a)||(r.add(a),s.push(a))}return s},lt=$n()((e,t)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{t().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{t().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(s,r,o)=>{const i=t(),a=new Set(i.selectedIds);let c=i.scopeKey,u=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(a.clear(),c=r,u=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[s,...o]:[s];if(a.has(s)){for(const b of f)a.delete(b);u===s&&(u=null)}else{for(const b of f)a.add(b);u=s}a.size===0?e({selectedIds:a,scopeKey:null,anchorId:null}):e({selectedIds:a,scopeKey:c,anchorId:u})},setRange:(s,r,o,i,a)=>{const c=t();if(o.length===0)return;const u=s&&o.includes(s)?s:o[0],d=o.indexOf(u),f=o.indexOf(r);if(d<0||f<0)return;const[m,b]=d<=f?[d,f]:[f,d],g=o.slice(m,b+1),h=yb(g,a),S=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const y of h)S.add(y);e({selectedIds:S,scopeKey:i??c.scopeKey,anchorId:u})},replaceAll:(s,r)=>{if(s.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(s),scopeKey:r,anchorId:s[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:s=>{const r=t();if(r.selectedIds.size===0||s.length===0)return;const o=new Set(r.selectedIds);for(const i of s)o.delete(i);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),Ta=e=>De(e.session.directory??null),wb=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),vb=e=>{if(!e.openSidebarMenuKey)return null;const t=e.renderContext??"project",[s,,...r]=e.openSidebarMenuKey.split(":");return s===t&&r.length>0?r.join(":"):null},mr=e=>e.menuOpenSessionId??vb(e),gr=(e,t,s)=>t?s.has(e.node.session.id)?!0:un(e.node,t):!1,di=(e,t,s,r,o)=>{if(e.session.id!==t.session.id)return!0;const i=o(e);if(s.has(i)!==r.has(i)||e.children.length!==t.children.length)return!0;for(let a=0;a<e.children.length;a+=1)if(di(e.children[a],t.children[a],s,r,o))return!0;return!1},Sb=(e,t)=>e.hasSessionSearchQuery||t.hasSessionSearchQuery?!1:di(e.node,t.node,e.expandedParents,t.expandedParents,s=>Js(e.renderContext??"project",s.session))||di(e.node,t.node,e.expandedParents,t.expandedParents,s=>Js(t.renderContext??"project",s.session)),jb=(e,t)=>{if(e.node.session.id!==t.node.session.id||e.node.session!==t.node.session||e.depth!==t.depth||e.groupDirectory!==t.groupDirectory||e.projectId!==t.projectId||e.archivedBucket!==t.archivedBucket||(e.renderContext??"project")!==(t.renderContext??"project")||e.mobileVariant!==t.mobileVariant||e.alwaysShowActions!==t.alwaysShowActions||e.allowQuickArchiveAction!==t.allowQuickArchiveAction||e.hasSessionSearchQuery!==t.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==t.normalizedSessionSearchQuery||e.nodeStructureKey!==t.nodeStructureKey||Ta(e.node)!==Ta(t.node)||!wb(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&ic(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&Sb(e,t)||e.editingId!==t.editingId&&(gr(e,e.editingId,e.subtreeContainsEditing)||gr(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(gr(e,e.editingId,e.subtreeContainsEditing)||gr(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(un(e.node,e.copiedSessionId)||un(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const s=mr(e),r=mr(t);if(un(e.node,s)||un(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const s=mr(e),r=mr(t);if(un(e.node,s)||un(t.node,r))return!1}return e.setEditingId===t.setEditingId&&e.setEditTitle===t.setEditTitle&&e.handleSaveEdit===t.handleSaveEdit&&e.handleCancelEdit===t.handleCancelEdit&&e.toggleParent===t.toggleParent&&e.handleSessionSelect===t.handleSessionSelect&&e.handleSessionDoubleClick===t.handleSessionDoubleClick&&e.togglePinnedSession===t.togglePinnedSession&&e.handleShareSession===t.handleShareSession&&e.handleCopyShareUrl===t.handleCopyShareUrl&&e.handleCopySessionId===t.handleCopySessionId&&e.handleUnshareSession===t.handleUnshareSession&&e.setOpenSidebarMenuKey===t.setOpenSidebarMenuKey&&e.getFoldersForScope===t.getFoldersForScope&&e.getSessionFolderId===t.getSessionFolderId&&e.removeSessionFromFolder===t.removeSessionFromFolder&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.handleDeleteSession===t.handleDeleteSession&&e.handleRestoreSession===t.handleRestoreSession&&e.renderSessionNode===t.renderSessionNode};function kb({node:e,groupDirectory:t,projectId:s,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:a,hasSessionSearchQuery:c}){const u=e.session,d=De(u.directory??null)??De(t??null),f=Fe(we=>we.currentSessionId===u.id),m=Lo(d),b=Gd(d),g=ct(l.useCallback(we=>{if(r?.projectLabel||!s)return null;const Re=we.projects.find(Y=>Y.id===s);return Re?er({label:Re.label,normalizedPath:De(Re.path)??Re.path},null):null},[s,r?.projectLabel])),h=r?.projectLabel??g,p=ct(l.useCallback(we=>s?we.projects.find(Re=>Re.id===s)?.path??null:null,[s])),S=e.worktree,y=r?.branchLabel??S?.branch??(m&&m!=="HEAD"?m:null),v=De(p),x=Lo(v),j=!!v&&d===v||!!y&&y===x,k=j?null:y,w=!j&&(b===!0||!!(y||S)),C=e.children.length,R=u.agent,L=S?.branch?.trim()||y?.trim()||null,U=De(S?.path??d),G=l.useMemo(()=>L&&U?Xs(U,L):null,[L,U]),$=lc(G);cc(U,L);const q=$?`var(--pr-${$.visualState})`:void 0,F=l.useMemo(()=>{if(!$)return null;switch($.visualState){case"merged":return"Merged";case"open":return $.canMerge===!0||$.mergeableState==="clean"||$.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return $.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[$]),E=s??d??null,T=lt(we=>we.enabled),I=lt(l.useCallback(we=>we.selectedIds.has(u.id),[u.id])),M=lt(we=>we.toggleSelected),W=lt(we=>we.setRange),O=yl(u.id)?.type??"idle",ae=O==="busy"||O==="retry",X=Hd(u.id,ae),ue=dn(u,"Untitled session"),Ie=e.children.length>0,V=Zs(o,d,u.id),P=c?!0:i.has(a),H=qd(u.id);wl(l.useCallback(we=>we.index.session.unseenHasError[u.id]??!1,[u.id]));const Q=Yd(u.id),re=Vd({pendingInput:Q,isStreaming:ae,unseenCount:H,isActive:f}),ie=H>0||vl(Q),ge=u.time?.updated||u.time?.created||Date.now(),me=uh(ge),Ce=l.useMemo(()=>ec(e.forkColorId),[e.forkColorId]),Le=l.useMemo(()=>bm(e.forkColorId,{active:f||I}),[e.forkColorId,f,I]);return{session:u,sessionDirectory:d,prDirectory:U,prBranch:L,prNumber:$?.number??null,isActive:f,tooltipProjectLabel:h,projectPath:p,tooltipBranchLabel:k,isGitRepo:w,subtaskCount:C,agentName:R,prSummary:$,prIconColor:q,prStatusLabel:F,selectionScopeKey:E,selectionModeEnabled:T,isRowSelected:I,toggleRowSelected:M,setRowRange:W,isStreaming:ae,hasActivityDuration:X,sessionTitle:ue,hasChildren:Ie,isPinnedSession:V,isExpanded:P,needsAttention:ie,pendingInput:Q,attention:re,sessionCompactUpdatedLabel:me,forkSolid:Ce,rowBackground:Le}}const Cb=({prDirectory:e,prNumber:t,prStatusLabel:s,prIconColor:r})=>{const o=ml(e);if(!e||!o)return n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",style:r?{color:r}:void 0,title:s?`PR #${t} — ${s}`:`PR #${t}`,children:[n.jsx(D,{name:"git-pull-request",className:"size-3.5 shrink-0"}),n.jsxs("span",{children:["#",t]})]});const i=a=>{a.stopPropagation(),a.preventDefault(),wc(e,o,t)};return n.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:a=>{a.stopPropagation(),a.preventDefault()},onKeyDown:a=>{if(!(a.key!=="Enter"&&a.key!==" ")){if(a.repeat){a.stopPropagation(),a.preventDefault();return}i(a)}},className:"inline-flex shrink-0 cursor-pointer items-center gap-1 rounded hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",style:r?{color:r}:void 0,title:s?`PR #${t} — ${s}. Open in Pull requests`:`Open PR #${t} in Pull requests`,"aria-label":s?`Open pull request #${t}, ${s}, in Pull requests`:`Open pull request #${t} in Pull requests`,children:[n.jsx(D,{name:"git-pull-request",className:"size-3.5 shrink-0"}),n.jsxs("span",{children:["#",t]})]})};function Ab(e){Wt("ui.sidebar_session_node.render");const{node:t,depth:s=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:a,expandedParents:c,hasSessionSearchQuery:u,normalizedSessionSearchQuery:d,editingId:f,setEditingId:m,editTitle:b,setEditTitle:g,handleSaveEdit:h,handleCancelEdit:p,toggleParent:S,handleSessionSelect:y,handleSessionDoubleClick:v,togglePinnedSession:x,handleShareSession:A,copiedSessionId:j,handleCopyShareUrl:k,handleCopySessionId:w,handleUnshareSession:C,openSidebarMenuKey:R,setOpenSidebarMenuKey:L,renamingFolderId:U,getFoldersForScope:G,getSessionFolderId:$,removeSessionFromFolder:q,addSessionToFolder:F,createFolderAndStartRename:E,handleDeleteSession:T,handleRestoreSession:I,alwaysShowActions:M,allowQuickArchiveAction:W,renderSessionNode:K,secondaryMeta:O,renderContext:ae="project",subtreeContainsEditing:X,menuOpenSessionId:ue,childRenderExtrasFor:Ie}=e,V=i||!!t.session.time?.archived,P=l.useContext(Qs)==="tree",H="size-3 shrink-0",Q=l.useMemo(()=>El(),[]),re=!V&&W,ie=l.useRef(!1),ge=l.useRef(f);ge.current=f;const me=l.useRef(null),Ce=l.useRef(h);Ce.current=h;const[je,Le]=l.useState(b),we=l.useRef(je);we.current=je;const Re=l.useRef(null),Y=l.useRef(null),be=Js(ae,t.session),{session:ee,sessionDirectory:se,prDirectory:_e,prNumber:ke,isActive:J,tooltipProjectLabel:ve,projectPath:he,tooltipBranchLabel:Se,isGitRepo:qe,subtaskCount:Ue,agentName:z,prSummary:pe,prIconColor:ne,prStatusLabel:ze,selectionScopeKey:st,selectionModeEnabled:pt,isRowSelected:Xe,toggleRowSelected:Yt,setRowRange:mt,isStreaming:Nt,hasActivityDuration:nn,sessionTitle:Je,hasChildren:Mt,isPinnedSession:Ft,isExpanded:vt,pendingInput:Ee,attention:Ve,sessionCompactUpdatedLabel:Ne,forkSolid:Pe,rowBackground:He}=kb({node:t,groupDirectory:r,projectId:o,secondaryMeta:O,pinnedSessionIds:a,expandedParents:c,expansionKey:be,hasSessionSearchQuery:u}),{exportDialogOpen:dt,setExportDialogOpen:sn,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:Ot,descendantCount:Ye,handleExportSession:rn,doExportSession:An}=xb(t,se),[It,Kn]=l.useState(!1),bt=l.useContext($r),rt=s===0&&!V?bt?.sectionById.get(ee.id)??null:null,Vt=Ys(l.useCallback(ce=>rt==="snoozed"?ce.entries[ee.id]?.snoozedUntil??null:null,[rt,ee.id])),Bt=rt==="snoozed"||V,gn=rt!==null&&rt!=="snoozed"&&!!bt?.wokeIds.has(ee.id),on=l.useMemo(()=>{if(!rt)return null;const ce=se??null;return{section:rt,onSnooze:_t=>li(ee.id,{snoozedUntil:_t},ce,"Could not snooze the session"),onWake:()=>li(ee.id,{snoozedUntil:null},ce,"Could not wake the session")}},[rt,ee.id,se]),xt=on?.section==="snoozed"?{label:"Wake",hint:"Wake now: back to the list",icon:"alarm",run:on.onWake}:null,St=l.useCallback(()=>{se&&zs("desktop_open_session_mini_chat_window",{sessionId:ee.id,directory:se,apiBaseUrl:Uo(),clientToken:zo()}).catch(ce=>{console.warn("[session-sidebar] failed to open mini chat window",ce)})},[ee.id,se]);l.useEffect(()=>{if(f!==ee.id)return;const ce=_t=>{const ks=_t.target?.closest?.(`[data-session-rename-form="${CSS.escape(ee.id)}"]`);Y.current&&!ks&&Ce.current(we.current)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[f,ee.id]),l.useLayoutEffect(()=>{if(f!==ee.id){Re.current===ee.id&&(Re.current=null);return}Re.current!==ee.id&&(Re.current=ee.id,Le(b))},[f,b,ee.id]);const Et=Ve==="needs-input",Wn=Et&&Ee?Qd(Ee.kind,Ee.count):null,Nn=Ve==="unread",In=Vt!==null?Jd(Vt,Date.now()):gn?"Woke":Ne,jt=Nt&&nn,an=re&&(M||It),nt=Nt&&!P&&!an&&f!==ee.id,ln=!!(O?.showFolderLabel&&ve),yt=!!Se||qe,kt=!!(z&&z!=="default"),ot=!!pe&&ke!=null,En=jt&&!nt,it=ln&&yt||ot||Ue>0||kt||En,Gn=ce=>Se?n.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",ce?"shrink":"flex-1"),children:[n.jsx(D,{name:"git-branch",className:H,style:ne?{color:ne}:void 0}),n.jsx(Os,{value:Se})]}):qe?n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[n.jsx(D,{name:"git-repository",className:H}),n.jsx("span",{children:"git"})]}):null,Hn=Ft,vs=n.jsx(D,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),Dn=Hn?n.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:vs}):null,Ss=Mt?n.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),S(be)},onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),ce.stopPropagation(),S(be))},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-label":vt?"Collapse subsessions":"Expand subsessions",children:vt?n.jsx(D,{name:"arrow-down-s",className:"h-3 w-3"}):n.jsx(D,{name:"arrow-right-s",className:"h-3 w-3"})}):null,B=ce=>{if(!ce&&me.current){const{id:_t,title:qn}=me.current;me.current=null,m(_t),g(qn)}},le=ce=>{Kn(ce)},xe=ce=>{ce.preventDefault(),ce.stopPropagation()},$e=ce=>{ce.preventDefault(),ce.stopPropagation()},ft=ce=>{ce.preventDefault(),ce.stopPropagation(),L(null),T(ee,{archivedBucket:V})},Qe=ce=>{ce.preventDefault(),ce.stopPropagation(),L(null),T(ee,{archivedBucket:V,hardDelete:!0,skipConfirm:!0})},Ct=ce=>{if(ie.current){ie.current=!1;return}if(pt){if(ce?.preventDefault(),ce?.stopPropagation(),ce?.shiftKey){const qn=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Yn=>Yn.getAttribute("data-session-row")).filter(Yn=>typeof Yn=="string"&&Yn.length>0),ks=lt.getState().anchorId,rr=new Map;rr.set(ee.id,Fr(t)),mt(ks,ee.id,qn,st,rr);return}Yt(ee.id,st,Fr(t));return}ce?.currentTarget&&db(ce.currentTarget),y(ee.id,se)},Dt=ce=>{ce.defaultPrevented||ce.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Ct(ce)},bn=ce=>{(ce.button===2||ce.button===0&&ce.ctrlKey&&!pt)&&(ie.current=!0)},js={session:ee,sessionTitle:Je,sessionDirectory:se,isPinnedSession:Ft,archivedBucket:V,isElectron:Q,renamingFolderId:U,editingIdRef:ge,pendingRenameRef:me,handleCopySessionId:w,togglePinnedSession:x,handleExportSession:rn,handleOpenMiniChatWindow:St,handleDeleteSession:T,handleRestoreSession:I,shelfActions:on},sr=n.jsx(ub,{...js});return n.jsxs(l.Fragment,{children:[n.jsx(_m,{sessionId:ee.id,sessionDirectory:se??null,sessionTitle:Je,children:n.jsxs(nl,{open:It,onOpenChange:le,onOpenChangeComplete:B,children:[n.jsxs(sl,{render:n.jsx("div",{"data-session-row":ee.id,"data-session-scope":st??"","data-session-archived":V?"1":"0","data-fork-color":Pe?t.forkColorId:void 0,"data-global-session":O?.globalSession?"1":void 0,"data-sidebar-tree-row":P?"":void 0,onClick:Dt,style:{...s>0?{marginLeft:`${s*14}px`}:void 0,...He?{backgroundColor:He}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",P?oc:"my-0.5 rounded-xl py-2",!He&&s>0?"bg-secondary/30 hover:bg-interactive-hover":He?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!He&&J&&!Xe&&"bg-interactive-selection",!He&&Xe&&"bg-interactive-selection")}),children:[n.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",nt&&"oc-session-row-working-fade"),"data-clear-on-hover":nt&&re?"true":void 0,"data-working-duration":nt&&jt?"true":void 0,children:[n.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",P?Kr:"gap-1.5"),children:[P?n.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:Nt&&!Et?n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,Ss,Dn,f===ee.id?n.jsxs("form",{ref:Y,"data-session-rename-form":ee.id,className:_("flex min-w-0 flex-1 items-center gap-2",P?"min-h-5":"min-h-8"),onPointerDown:ce=>ce.stopPropagation(),onMouseDown:ce=>ce.stopPropagation(),onSubmit:ce=>{ce.preventDefault(),h(je)},children:[n.jsx("input",{value:je,onChange:ce=>Le(ce.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:ce=>{ce.stopPropagation(),ce.key==="Escape"&&p()}}),n.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:n.jsx(D,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:p,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:n.jsx(D,{name:"close",className:"size-4"})})]}):n.jsxs("button",{type:"button",onMouseDown:bn,onClick:ce=>Ct(ce),onDoubleClick:ce=>{ce.stopPropagation(),v(ee.id,Je)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[n.jsxs("div",{className:_("flex w-full min-w-0 flex-1 gap-1.5 overflow-hidden",P?"items-center":"items-start"),children:[n.jsx("div",{className:_("min-w-0 flex-1 typography-ui-label",P?"block truncate":"line-clamp-2 text-pretty [overflow-wrap:anywhere]",J?"font-medium text-foreground":"font-normal",!J&&(Bt?"text-muted-foreground group-hover:text-foreground":"text-foreground")),children:ni(Je,d)}),Ft?n.jsx(D,{name:"star-fill",className:_("h-3 w-3 text-primary shrink-0",!P&&"mt-1")}):null,n.jsx("span",{"aria-hidden":"true",className:_("invisible ml-1 min-w-6 shrink-0 whitespace-nowrap typography-micro",(Vt!==null||gn)&&!Nn&&"pl-4"),children:Nn?null:In})]}),!P&&(ln||yt||it)?n.jsxs("div",{className:_("flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden typography-micro leading-4 font-normal",Bt?"text-subtle-foreground":"text-muted-foreground"),children:[ln?n.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",it?"max-w-[60%] shrink-0":"flex-1"),children:[he?n.jsx(xi,{directory:he,label:ve??"",className:H}):n.jsx(D,{name:"folder",className:H}),n.jsx("span",{className:"truncate",children:ve})]}):Gn(!1),it?n.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",ln?"flex-1":"shrink-0"),children:[ln?Gn(!0):null,ot?n.jsx(Cb,{prDirectory:_e,prNumber:ke,prStatusLabel:ze,prIconColor:ne}):null,Ue>0?n.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[n.jsx(D,{name:"node-tree",className:H}),n.jsx("span",{children:Ue})]}):null,kt?n.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:z}):null,En?n.jsx(Zi,{sessionId:ee.id,running:Nt,className:"shrink-0 text-subtle-foreground"}):null]}):null]}):null]})]}),n.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",P?"top-1/2 -translate-y-1/2":"top-2",f===ee.id&&"hidden"),children:[n.jsx("div",{className:_("flex items-center justify-end",an?"opacity-0":re?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Et&&!nt?n.jsx(qi,{label:Wn??"Needs input"}):Nn?n.jsx(dh,{label:"Session complete"}):Vt!==null||gn?n.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro text-muted-foreground whitespace-nowrap",title:Vt!==null?`Snoozed until ${new Date(Vt).toLocaleString()}`:"Back from snooze",children:[n.jsx(D,{name:"alarm",className:"size-3 shrink-0"}),In]}):n.jsx("span",{className:"typography-micro text-subtle-foreground whitespace-nowrap",children:Ne})}),re?n.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",M||It?"opacity-100":"pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100"),children:xt?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":xt.label,className:"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:xe,onMouseDown:$e,onKeyDown:ce=>ce.stopPropagation(),onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),L(null),xt.run()},children:n.jsx(D,{name:xt.icon,className:"size-4"})})}),n.jsx(Ge,{side:"top",sideOffset:6,children:xt.hint})]}):n.jsx(ab,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:xe,onMouseDown:$e,onArchive:ft,onDelete:Qe})}):null]})]}),nt?n.jsxs("span",{"data-session-working":!0,className:_("pointer-events-none absolute inset-y-0 right-0 flex items-center rounded-r-[inherit] pr-3 transition-opacity",re&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[Et?null:n.jsx("span",{"aria-hidden":"true",className:"oc-session-row-working-aura absolute inset-y-0 right-0 w-24 rounded-r-[inherit] bg-gradient-to-l from-primary/15 to-transparent"}),n.jsxs("span",{className:"relative flex flex-col items-end gap-1",children:[n.jsx("span",{className:"flex h-5 items-center",children:Et?n.jsx("span",{className:"inline-flex size-3 shrink-0 items-center justify-center",children:n.jsx(qi,{label:Wn??"Needs input"})}):n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}),jt?n.jsx(Zi,{sessionId:ee.id,running:Nt,className:"typography-micro leading-4"}):null]})]}):null]}),sr]})}),Mt&&vt?t.children.map(ce=>{const _t=Ie?Ie(ce):{subtreeContainsEditing:X,menuOpenSessionId:ue,nodeStructureKey:""};return n.jsx(l.Fragment,{children:K(ce,s+1,se??r,o,V,O?.globalSession?{globalSession:!0}:void 0,ae,_t)},ce.session.id)}):null,n.jsx(lb,{open:dt,onOpenChange:sn,descendantCount:Ye,exportIncludeSubtasks:Lt,setExportIncludeSubtasks:Ot,onExport:An})]},ee.id)}const Nb=l.memo(Ab,jb),Ib=({open:e,onOpenChange:t,project:s,onSave:r})=>n.jsx(en,{open:e,onOpenChange:t,children:n.jsx(tn,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:n.jsx(Mn,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:n.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&s?n.jsx(zp,{project:s,onIdentitySave:r}):null})})})});function Tc(e){const{showDeletionDialog:t,setShowDeletionDialog:s,onCancel:r,onConfirm:o,confirmLabel:i}=e;return n.jsxs(ms,{className:"w-full sm:items-center sm:justify-between",children:[n.jsxs("button",{type:"button",onClick:()=>s(!t),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!t,children:[t?n.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}):n.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),n.jsx("button",{type:"button",onClick:()=>{o()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:i})]})]})}function Eb(e){const{value:t,setValue:s,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=c=>dn(c);return n.jsx(en,{open:!!t,onOpenChange:c=>{c||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Delete session?"}),n.jsx(Cn,{children:t&&t.descendantCount>0?t.descendantCount===1?`"${a(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${a(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:`"${t?.session?a(t.session):"Untitled Session"}" will be permanently deleted.`})]}),n.jsx(Tc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>s(null),onConfirm:i,confirmLabel:"Delete"})]})})}function Db(e){const{value:t,setValue:s,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=t?.sessionCount??0,c=a===1?"Delete session?":"Delete sessions?",u=a===1?`${a} session will be permanently deleted.`:`${a} sessions will be permanently deleted.`;return n.jsx(en,{open:!!t,onOpenChange:d=>{d||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:c}),n.jsx(Cn,{children:u})]}),n.jsx(Tc,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>s(null),onConfirm:i,confirmLabel:"Delete"})]})})}function Rb(e){const{value:t,setValue:s,onConfirm:r}=e,{git:o}=Un(),[i,a]=l.useState(null),[c,u]=l.useState(!1),[d,f]=l.useState(!1),[m,b]=l.useState(!1),g=t?.worktree.path??null;l.useEffect(()=>{let j=!1;return a(null),u(!1),f(!1),b(!1),!t||!g?()=>{j=!0}:(o.getGitStatus(g).then(k=>{if(!j){if(typeof k?.isClean!="boolean"){u(!0);return}a(k)}}).catch(()=>{j||u(!0)}),()=>{j=!0})},[o,t,g]);const h=i?.isClean===!1,p=(i?.ahead??0)>0,S=p&&!t?.worktree.branch,y=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",v=!!(t&&i&&!c&&!t.hasActiveSession&&(!h&&!S||d)&&!m),x=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",A=async()=>{if(v){b(!0);try{await r({force:h})}finally{b(!1)}}};return n.jsx(en,{open:!!t,onOpenChange:j=>{!j&&!m&&s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-md gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Close worktree?"}),n.jsx(Cn,{children:`Closing "${x}" removes its worktree directory. ${y}`})]}),c?n.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3",children:[n.jsx(D,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):i===null?n.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,t?.hasActiveSession?n.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,h?n.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),n.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[n.jsx(Gs,{checked:d,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),n.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,p?n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"typography-ui-label text-muted-foreground",children:i?.ahead===1?`This worktree has 1 unpushed commit. ${y}`:`This worktree has ${i?.ahead} unpushed commits. ${y}`}),S?n.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),n.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),n.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[n.jsx(Gs,{checked:d,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),n.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,n.jsxs(ms,{className:"sm:justify-end",children:[n.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>s(null),disabled:m,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!v,children:m?"Closing…":"Close worktree"})]})]})})}function Pb(e){const{value:t,setValue:s,onConfirm:r}=e;return n.jsx(en,{open:!!t,onOpenChange:o=>{o||s(null)},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:"Delete folder?"}),n.jsx(Cn,{children:t&&(t.subFolderCount>0||t.sessionCount>0)?t.subFolderCount>0?t.subFolderCount===1?`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted. Sessions inside will not be deleted.`:`"${t?.folderName??""}" will be permanently deleted.`})]}),n.jsxs(ms,{children:[n.jsx("button",{type:"button",onClick:()=>s(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),n.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})}const Tb=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:s,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:a,setDeleteSessionConfirm:c,showDeletionDialog:u,setShowDeletionDialog:d,confirmDeleteSession:f,deleteFolderConfirm:m,setDeleteFolderConfirm:b,confirmDeleteFolder:g,closeWorktreeConfirm:h,setCloseWorktreeConfirm:p,confirmCloseWorktree:S,bulkDeleteConfirm:y,setBulkDeleteConfirm:v,confirmBulkDelete:x})=>n.jsxs(n.Fragment,{children:[n.jsx(Wl,{open:e,onOpenChange:t,info:s.info,downloading:s.downloading,downloaded:s.downloaded,progress:s.progress,error:s.error,onDownload:s.downloadUpdate,onRestart:s.restartToUpdate,runtimeType:s.runtimeType}),n.jsx(Ib,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:i}),n.jsx(Eb,{value:a,setValue:c,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:f}),n.jsx(Pb,{value:m,setValue:b,onConfirm:g}),n.jsx(Rb,{value:h,setValue:p,onConfirm:S}),n.jsx(Db,{value:y,setValue:v,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:x})]}),Mb=({directories:e})=>{const t=l.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=De(o)?.toLowerCase();i&&r.add(i)}),r},[e]),s=Bs(r=>{let o=0,i=!1;for(const a of r.catalog.byId.values()){const c=De(a.directory)?.toLowerCase();!c||!t.has(c)||(vl(a.pendingInput)?o+=1:(a.lifecycle==="busy"||a.lifecycle==="retry")&&(i=!0))}return{inputCount:o,hasBusySession:i}},(r,o)=>r.inputCount===o.inputCount&&r.hasBusySession===o.hasBusySession,"catalog");if(s.inputCount>0){const r=Xd(s.inputCount);return n.jsx("span",{className:"inline-flex items-center","aria-label":r,title:r,children:n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return s.hasBusySession?n.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:n.jsx(jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},qr=e=>!!e.session.time?.archived,Mc=e=>{let t=0;for(const s of e)qr(s)||(t+=1);return t},Fb=e=>{let t=0;for(const s of e)for(const r of s.groups)t+=Mc(r.sessions);return t},Lb=e=>{const t=new Map;for(const s of e){let r=0;for(const o of s.groups)r+=Mc(o.sessions);t.set(s.project.id,r)}return t},Ob=(e,t)=>e.groups.some(s=>s.sessions.some(r=>!qr(r)&&t.has(r.session.id))),Bb=(e,t)=>e.groups.some(s=>s.sessions.some(r=>!qr(r)&&t.has(r.session.id))),_b=(e,t)=>{const s=new Map;for(const r of e){const o=new Set;for(const i of r.groups)if(i.sessions.some(c=>!qr(c)&&t.has(c.session.id))&&i.directory){const c=De(i.directory)?.toLowerCase();c&&o.add(c)}o.size>0&&s.set(r.project.id,o)}return s},zb=(e,t,s,r)=>{if(!s)return t;const o=e.find(c=>c.project.id===s);if(!o)return[];const i=De(r??o.project.normalizedPath),a=o.groups.find(c=>De(c.directory)===i);return a?[{...o,groups:[a]}]:[]},Ub=(e,t)=>{const s=new Map,r=new Map;return e.forEach(o=>{const i=er(o.project,t);o.groups.forEach(a=>{const c=a.branch&&a.branch!=="HEAD"&&a.branch!==i?a.branch:null,u={projectLabel:i,branchLabel:c},d=f=>{f.forEach(m=>{const b=o.project.normalizedPath.length,g=r.get(m.session.id)??-1;b<g||(s.set(m.session.id,{node:m,projectId:o.project.id,groupDirectory:a.directory,secondaryMeta:u}),r.set(m.session.id,b),m.children.length>0&&d(m.children))})};d(a.sessions)})}),s};function $b({projectSections:e,flatSectionsForRender:t,sectionsForRender:s,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:a,unreadSessionIdSet:c}){const u=l.useMemo(()=>Ub(e,i),[e,i]),d=t,f=l.useMemo(()=>zb(s,d,r,o),[s,d,r,o]),m=l.useMemo(()=>Fb(e),[e]),b=l.useMemo(()=>Lb(e),[e]),g=l.useCallback(S=>{const y=e.find(v=>v.project.id===S);return y?Ob(y,a):!1},[a,e]),h=l.useMemo(()=>_b(e,a),[a,e]),p=l.useCallback(S=>{const y=e.find(v=>v.project.id===S);return y?Bb(y,c):!1},[e,c]);return{sessionSidebarMetaById:u,sectionsForSidebarRender:d,filteredSectionsForSidebarRender:f,totalSessionCount:m,sessionCountByProject:b,hasActiveSessionByProject:g,activeDirectoriesByProject:h,hasUnseenByProject:p}}const Kb=({selectedCount:e,archivedBucket:t,onRestore:s,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",a="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";return n.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border pl-5 pr-3.5 py-1.5",children:[n.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),n.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[t?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:s,className:a,"aria-label":"Unarchive",children:n.jsx(D,{name:"inbox-unarchive",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Unarchive"})})]}):null,n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:r,className:_(t?"inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50":a),"aria-label":i,children:n.jsx(D,{name:t?"delete-bin":"inbox-archive",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:i})})]}),n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:o,className:a,"aria-label":"Exit selection",children:n.jsx(D,{name:"close",className:"h-4 w-4"})})}),n.jsx(Ge,{side:"top",sideOffset:4,children:n.jsx("p",{children:"Exit selection"})})]})]})]})},Wb=e=>{if(typeof document>"u")return!1;const t=document.querySelectorAll(`[data-session-row="${CSS.escape(e)}"]`);if(t.length===0)return!1;for(const s of t)if(s.getAttribute("data-session-archived")!=="1")return!1;return!0},Gb=e=>{const{isInlineEditing:t,showDeletionDialog:s,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:a,createFolderAndStartRename:c,resolveSessionDirectory:u,unarchiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:m}=e,b=lt(T=>T.enabled),g=lt(T=>T.selectedIds.size),h=g>0,p=lt(T=>T.selectedIds),S=lt(T=>T.scopeKey),y=l.useCallback(()=>{lt.getState().toggleMode()},[]),v=l.useCallback(()=>{lt.getState().disable()},[]),x=l.useMemo(()=>{if(!h||typeof document>"u")return!1;let T=!1,I=!1;for(const M of p){const W=document.querySelectorAll(`[data-session-row="${CSS.escape(M)}"]`);for(const K of W)K.getAttribute("data-session-archived")==="1"?I=!0:T=!0}return I&&!T},[h,p]),A=l.useMemo(()=>{if(S)return S;if(!h||typeof document>"u")return null;for(const T of p){const M=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(M&&M.length>0)return M}return null},[h,p,S]),j=l.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(I=>I.scopeKey):[A]},[A,o]),k=l.useMemo(()=>j.flatMap(T=>r[T]??[]),[r,j]),w=l.useCallback(T=>{for(const I of j)if((r[I]??[]).some(M=>M.id===T))return I;return null},[r,j]),C=l.useMemo(()=>{if(!h)return!1;for(const T of j)for(const I of r[T]??[])for(const M of I.sessionIds)if(p.has(M))return!0;return!1},[r,j,h,p]),R=l.useCallback((T,I)=>{const M=Array.from(p);for(const W of j)W!==T&&a(W,M);i(T,I,M)},[i,a,p,j]),L=l.useCallback(T=>{if(!h)return;const I=w(T);I&&R(I,T)},[h,R,w]),U=l.useCallback(()=>{const T=j[0];if(!T||!h)return;const I=c(T);I&&R(T,I.id)},[c,h,R,j]),G=l.useCallback(()=>{if(!h)return;const T=Array.from(p);for(const I of j)a(I,T)},[a,p,j,h]),$=l.useCallback(async()=>{const T=Array.from(p);if(T.length===0)return;const{deletedIds:I,failedIds:M}=await f(T);I.length>0&&oe.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Failed to delete ${M.length} session`:`Failed to delete ${M.length} sessions`),lt.getState().clear()},[f,p]),q=l.useCallback(()=>{if(h){if(!x){const T=Array.from(p).filter(I=>!Wb(I)).map(I=>({sessionId:I,directory:u(I),forkIds:[]}));lt.getState().clear(),tc(T);return}if(!s){$();return}m({sessionCount:p.size})}},[x,$,u,p,s,m,h]),F=l.useCallback(async()=>{if(!h||!x)return;const T=Array.from(p),{restoredIds:I,failedIds:M}=await d(T);I.length>0&&oe.success(I.length===1?`Unarchived ${I.length} session`:`Unarchived ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Could not unarchive ${M.length} session`:`Could not unarchive ${M.length} sessions`),lt.getState().clear()},[x,h,p,d]),E=l.useCallback(async()=>{m(null),await $()},[$]);return l.useEffect(()=>{if(!b)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=M=>{if(t)return;const W=M.target;if(W&&(W.tagName==="INPUT"||W.tagName==="TEXTAREA"||W.isContentEditable))return;const K=T?M.metaKey:M.ctrlKey;if(M.key==="Escape"){M.preventDefault(),lt.getState().disable();return}if(K&&M.key==="Backspace"){M.preventDefault(),q();return}if(K&&(M.key==="a"||M.key==="A")){const O=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(O.length===0)return;M.preventDefault();const X=lt.getState().scopeKey??O[0]?.getAttribute("data-session-scope")??null,ue=V=>X?V.getAttribute("data-session-scope")===X:!0,Ie=O.filter(ue).map(V=>V.getAttribute("data-session-row")).filter(V=>typeof V=="string"&&V.length>0);if(Ie.length===0)return;lt.getState().replaceAll(Ie,X||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[q,t,b]),{selectionModeEnabled:b,hasSelection:h,selectedIdsSize:g,bulkScopeIsArchived:x,derivedSelectionScope:A,bulkScopeFolders:k,bulkCanRemoveFromFolder:C,handleToggleSelectionMode:y,handleExitSelectionMode:v,handleBulkMoveToFolder:L,handleBulkCreateFolderAndMove:U,handleBulkRemoveFromFolder:G,handleBulkDelete:q,handleBulkRestore:F,confirmBulkDelete:E}},Hb=(e,t)=>{const s=e??{};return delete s.projectSortOrder,delete s.showArchivedSessions,t<4&&delete s.displayMode,t<5&&delete s.sessionGroupingMode,s},qb=$n()(Ml(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,setShowRecentSection:t=>e({showRecentSection:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection}))}),{name:"pichamber:session-display-settings",version:7,migrate:Hb})),Ma="oc.sessions.projectCollapse",Fa="oc.sessions.groupOrder",La="oc.sessions.groupCollapse",Oa="oc.sessions.activeSessionByProject",Ba="oc.sessions.expandedParents.v3",Yb=new Set,mo=[],Rt=e=>{const t=l.useRef(e);return t.current=e,l.useCallback((...s)=>t.current(...s),[])},Vb=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:s,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:a=!1})=>{_o("react.session_sidebar_render"),Wt("ui.session_sidebar.render"),Wt(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),Wt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,u]=l.useState(!1),[d,f]=l.useState(""),m=l.useRef(null),b=l.useRef(null),[g,h]=l.useState(null),[p,S]=l.useState(""),[y,v]=l.useState(null),[x,A]=l.useState(new Set),j=l.useMemo(()=>rs(),[]),[k,w]=l.useState(new Set),C=Jn(N=>N.selectedSpaceId),R=Jn(N=>N.selectedWorktreePath),[L,U]=l.useState(new Map),[G,$]=l.useState(new Map),[q,F]=l.useState(!1),[E,T]=l.useState(null),[I,M]=l.useState(null),[W,K]=l.useState(""),[O,ae]=l.useState(null),[X,ue]=l.useState(null),[Ie,V]=l.useState(null),[P,H]=l.useState(null),Q=qs(N=>N.ids),re=Zd(l.useCallback(N=>e?N.rankById:gl,[e])),ie=Bs(N=>e?ef(N.catalog):"",void 0,"catalog"),ge=l.useMemo(()=>ie?ie.split("|"):mo,[ie]),me=l.useMemo(()=>new Set(ge),[ge]),Ce=wl(Ro(N=>e?Object.entries(N.index.session.unseenCount).filter(([,Z])=>Z>0).map(([Z])=>Z).sort():mo)),je=l.useMemo(()=>new Set(Ce),[Ce]),Le=qs(N=>N.toggle),[we,Re]=l.useState(()=>{try{const N=rs().getItem(La);if(!N)return new Set;const Z=JSON.parse(N);return new Set(Array.isArray(Z)?Z.filter(te=>typeof te=="string"):[])}catch{return new Set}}),[Y,fe]=l.useState(()=>{try{const N=rs().getItem(Fa);if(!N)return new Map;const Z=JSON.parse(N),te=new Map;return Object.entries(Z).forEach(([Oe,Be])=>{Array.isArray(Be)&&te.set(Oe,Be.filter(et=>typeof et=="string"))}),te}catch{return new Map}}),be=l.useMemo(()=>{try{const N=rs().getItem(Oa);if(!N)return new Map;const Z=JSON.parse(N),te=new Map;return Object.entries(Z).forEach(([Oe,Be])=>{typeof Be=="string"&&Be.length>0&&te.set(Oe,Be)}),te}catch{return new Map}},[]),ee=l.useCallback(N=>{try{j.setItem(Oa,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[j]),[se,_e]=l.useState(new Map),ke=l.useRef(0),J=fs(N=>N.homeDirectory),ve=fs(N=>N.currentDirectory),he=ct(N=>N.projects),Se=ct(N=>N.activeProjectId),qe=ct(N=>N.removeProject),Ue=ct(N=>N.setActiveProjectIdOnly),z=ct(N=>N.updateProjectMeta),pe=ct(N=>N.reorderProjects),ne=de(N=>N.setActiveMainTab),ze=de(N=>N.setSettingsDialogOpen),st=de(N=>N.setSettingsPage),pt=de(N=>N.toggleHelpDialog),Xe=de(N=>N.setSessionSwitcherOpen),Yt=de(N=>N.setArchivePageOpen),mt=de(N=>N.showDeletionDialog),Nt=de(N=>N.setShowDeletionDialog),nn=de(N=>N.sidebarViewMode),Je=i||a||!$f(nn)?"workspace":nn,Mt=de(N=>N.weekStartPreference),Ft=l.useMemo(()=>om(Mt),[Mt]),vt=cm(e&&Je==="timeline",Ft),Ee=qb(N=>N.stickyZoneHeaders),Ve=tf(d,120),Ne=l.useMemo(()=>Ve.trim().toLowerCase(),[Ve]),Pe=Ne.length>0,He=gt(N=>N.collapsedFolderIds),dt=gt(N=>N.foldersMap),sn=gt(N=>N.getFoldersForScope),Lt=gt(N=>N.createFolder),Ot=gt(N=>N.renameFolder),Ye=gt(N=>N.deleteFolder),rn=gt(N=>N.addSessionToFolder),An=gt(N=>N.addSessionsToFolder),It=gt(N=>N.removeSessionFromFolder),Kn=gt(N=>N.removeSessionsFromFolders),bt=gt(N=>N.toggleFolderCollapse),rt=gt(N=>N.getSessionFolderId);wm({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchContainerRef:m});const Vt=nf(e),{git:Bt}=Un(),gn=Bs(N=>N.connection,void 0,"chrome"),on=Bs(N=>{for(const Z of N.catalog.listStatusByDirectory.values())if(Z==="ready")return!0;return!1},void 0,"catalog"),xt=Mo({archived:!1}),St=Mo({archived:!0}),Et=Fe(N=>N.setCurrentSession),Wn=Fe(N=>N.updateSessionTitle),Nn=Fe(N=>N.shareSession),In=Fe(N=>N.unshareSession),jt=Oo(N=>N.projects),an=Oo(N=>N.refreshProject),nt=l.useMemo(()=>sf(he,{projects:jt}),[he,jt]),ln=l.useMemo(()=>{const N=new Map;for(const Z of he){const te=De(Z.path);if(!te)continue;const Oe=jt.get(te)?.error;Oe&&N.set(te,Oe)}return N},[he,jt]);l.useEffect(()=>{if(!C)return;const N=he.find(te=>te.id===C);if(!N){Jn.getState().clearSpaceSelection();return}if(!R)return;(nt.get(De(N.path)??N.path)??[]).some(te=>De(te.path)===De(R))||(Jn.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[nt,he,C,R]);const yt=Fe(N=>N.openNewSessionDraft),kt=l.useCallback(N=>{de.getState().closeMainSurfaces(),yt(N),r?.()},[r,yt]),ot=xr(Ro(N=>({checkForUpdates:N.checkForUpdates,available:N.available,runtimeType:N.runtimeType,info:N.info,downloading:N.downloading,downloaded:N.downloaded,progress:N.progress,error:N.error,downloadUpdate:N.downloadUpdate,restartToUpdate:N.restartToUpdate}))),En=l.useMemo(()=>rf(he,nt,{includeWorktrees:!0}),[nt,he]),it=l.useMemo(()=>xt.filter(N=>Mm(N,En,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:J})),[xt,J,En]),Gn=l.useMemo(()=>[...it,...St],[St,it]),Hn=Tt(),vs=l.useMemo(()=>`${Hn}|${he.map(N=>`${N.id}:${De(N.path)??""}`).join("|")}`,[he,Hn]),Dn=l.useMemo(()=>{const N=new Set;let Z=!0;for(const te of he){const Oe=De(te.path);if(!Oe)continue;const Be=jt.get(Oe)?.status??"idle";Be==="failed"&&N.add(Oe),(Be==="idle"||Be==="loading")&&(Z=!1)}return{complete:Z,unresolved:N}},[he,jt]),Ss=Dn.complete?vs:null;Dn.complete;const B=Dn.unresolved,{isTablet:le}=ps(),xe=t||le,$e=ym({mobileVariant:t,isTablet:le}),{buildGroupSearchText:ft,filterSessionNodesForSearch:Qe,buildGroupedSessions:Ct}=xm({homeDirectory:J,pinnedSessionIds:Q,sessionOrderRanks:re}),{scheduleCollapsedProjectsPersist:Dt}=Sm({safeStorage:j,keys:{sessionExpanded:Ba,projectCollapse:Ma,groupOrder:Fa,groupCollapse:La},groupOrderByProject:Y,collapsedGroups:we,setExpandedParents:A,setCollapsedProjects:w}),bn=l.useMemo(()=>of(it,Q,re),[Q,re,it]),js=l.useMemo(()=>bn.map(N=>N.id).join("|"),[bn]),sr=l.useRef(null),ce=l.useMemo(()=>{const N=sr.current;if(N&&N.signature===js)return N.map;const Z=new Map(bn.map((te,Oe)=>[te.id,Oe]));return sr.current={signature:js,map:Z},Z},[bn,js]),_t=l.useMemo(()=>{const N=new Map;bn.forEach(te=>{const Oe=te.parentID;if(!Oe)return;const Be=N.get(Oe)??[];Be.push(te),N.set(Oe,Be)});const Z=hl(Q,re);return N.forEach(te=>te.sort(Z)),N},[bn,Q,re]),qn=l.useMemo(()=>n.jsx(Xt,{icon:"chat-new",mobileVariant:t,onClick:()=>kt(),children:"New session"}),[t,kt]),ks=l.useMemo(()=>he.find(N=>N.id===y)??null,[he,y]),rr=l.useCallback(N=>{y&&z(y,{label:N.label,defaultModel:N.defaultModel??null})},[y,z]),Yn=l.useCallback(()=>{const N=xr.getState();if(N.available&&N.info){F(!0);return}ot.checkForUpdates().then(()=>{const{available:Z,error:te}=xr.getState();if(te){oe.error("Failed to check for updates",{description:te});return}if(!Z){oe.success("You are on the latest version");return}F(!0)})},[ot]),Vn=af(),Ai=l.useCallback(()=>{if(t&&Xe(!1),r?.(),Vn?.openSettings){Vn.openSettings();return}ze(!0)},[Vn,t,r,Xe,ze]),_c=ot.available&&(ot.runtimeType==="desktop"||ot.runtimeType==="web"),zc=Fe(N=>N.deleteSession),Ni=Fe(N=>N.deleteSessions),Uc=Fe(N=>N.unarchiveSession),$c=Fe(N=>N.unarchiveSessions),{copiedSessionId:Kc,handleSessionSelect:Wc,handleSessionDoubleClick:Gc,handleSaveEdit:Hc,handleCancelEdit:qc,handleShareSession:Yc,handleCopyShareUrl:Vc,handleCopySessionId:Qc,handleUnshareSession:Jc,handleDeleteSession:Xc,handleRestoreSession:Zc,confirmDeleteSession:eu}=vm({mobileVariant:t,allowReselect:o,onSessionSelected:s,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:u,setActiveMainTab:ne,setSessionSwitcherOpen:Xe,setCurrentSession:Et,updateSessionTitle:Wn,shareSession:Nn,unshareSession:In,deleteSession:zc,deleteSessions:Ni,unarchiveSession:Uc,childrenMap:_t,showDeletionDialog:mt,setDeleteSessionConfirm:ae,deleteSessionConfirm:O,setEditingId:h,setEditTitle:S,editingId:g,editTitle:p}),tu=l.useCallback(()=>{if(!X)return;const{scopeKey:N,folderId:Z}=X;ue(null),Ye(N,Z)},[X,Ye]),Yr=l.useCallback(()=>{Hs.requestDirectoryDialog()},[]),nu=l.useCallback(N=>{A(Z=>{const te=fh(Z,N);try{j.setItem(Ba,JSON.stringify(Array.from(te)))}catch{}return te})},[j]),Ii=l.useCallback((N,Z)=>{if(!N)return null;Z&&He.has(Z)&&bt(Z);const te=Lt(N,"New folder",Z);return M(te.id),K(te.name),te},[He,bt,Lt]),Cs=Rt(Wc),su=Rt(Gc),ru=Rt(Hc),ou=Rt(qc),iu=Rt(Yc),au=Rt(Vc),lu=Rt(Qc),cu=Rt(Jc),uu=Rt(Xc),du=Rt(Zc),Vr=Rt(Ii),Ei=l.useCallback((N,Z)=>{$(te=>{const Oe=new Map(te);return Oe.set(N,Z+7),Oe})},[]),or=l.useCallback(N=>{$(Z=>{if(!Z.has(N))return Z;const te=new Map(Z);return te.delete(N),te})},[]),Di=l.useCallback(N=>{$(Z=>{let te=!1;const Oe=new Map(Z),Be=`${N}:`;for(const et of Oe.keys())et.startsWith(Be)&&(Oe.delete(et),te=!0);return te?Oe:Z})},[]),Qr=l.useCallback(N=>{ke.current=Date.now()+150,Di(N),w(Z=>{const te=new Set(Z);te.has(N)?te.delete(N):te.add(N);try{j.setItem(Ma,JSON.stringify(Array.from(te)))}catch{}return Dt(te),te})},[Di,j,Dt]),Ri=l.useRef(null);l.useEffect(()=>{const N=Ri.current;Ri.current=Se,Je==="folder"&&(!N||!Se||N===Se||k.has(Se)&&Qr(Se))},[Se,k,Je,Qr]);const Rn=l.useMemo(()=>he.map(N=>({...N,normalizedPath:De(N.path)})).filter(N=>!!N.normalizedPath),[he]),fu=l.useMemo(()=>Rn.map(N=>N.normalizedPath),[Rn]),Pi=lf(e?fu:mo);Im({enabled:e,normalizedProjects:Rn,gitRepoStatus:Pi,setProjectRepoStatus:U,setProjectRootBranches:_e});const hu=l.useMemo(()=>Lm(it,Rn,nt,St),[St,nt,Rn,it]);Pm({enabled:e,hasAuthoritativeGlobalSessions:on,sessions:Gn});const{getSessionsForProject:pu,getArchivedSessionsForProject:mu}=Em({ownership:hu}),Ti=l.useRef(!1);Se&&L.has(Se)&&(Ti.current=!!L.get(Se));const Jr=ct(N=>N.manualProjectOrder),Mi=l.useRef(new Set),ir=hh(Mi.current,x,"project");Mi.current=ir;const Xr={isVisible:e,mobileVariant:t,onSessionSelected:s,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:a,isTablet:le,catalogSessions:xt,archivedSessions:St,projects:he,activeProjectId:Se,manualProjectOrder:Jr,currentDirectory:ve,availableWorktreesByProject:nt,pinnedSessionIds:Q,sessionOrderRanks:re,foldersMap:dt,collapsedFolderIds:He,gitBranches:Vt,gitRepoStatus:Pi,updateStore:ot,projectRepoStatus:L,projectRootBranches:se,resolvedWorktreeTopologyKey:Ss,unresolvedWorktreeProjectPaths:B,isSessionSearchOpen:c,sessionSearchQuery:d,editingId:g,editTitle:p,editingProjectDialogId:y,expandedParents:x,collapsedProjects:k,visibleSessionCountByGroup:G,updateDialogOpen:q,openSidebarMenuKey:E,renamingFolderId:I,renameFolderDraft:W,deleteSessionConfirm:O,deleteFolderConfirm:X,bulkDeleteConfirm:P,collapsedGroups:we},Fi=l.useRef(null),Li=Fi.current;if(Li){let N=!1;for(const Z of Object.keys(Xr))Object.is(Li[Z],Xr[Z])||(Wt(`ui.session_sidebar.source.${Z}`),N=!0);N||Wt("ui.session_sidebar.source.parent_or_context")}Fi.current=Xr;const gu=l.useMemo(()=>{const N=new Map(Jr.map((Z,te)=>[Z,te]));return[...Rn].sort((Z,te)=>(N.get(Z.id)??1/0)-(N.get(te.id)??1/0))},[Jr,Rn]),{projectSections:xn,groupSearchDataByGroup:Oi,sectionsForRender:bu,flatSectionsForRender:Zr,searchMatchCount:xu}=fm({normalizedProjects:gu,getSessionsForProject:pu,getArchivedSessionsForProject:mu,availableWorktreesByProject:nt,projectRepoStatus:L,projectRootBranches:se,lastRepoStatus:Ti.current,buildGroupedSessions:Ct,hasSessionSearchQuery:Pe,normalizedSessionSearchQuery:Ne,filterSessionNodesForSearch:Qe,buildGroupSearchText:ft,foldersMap:dt,alwaysIncludeArchived:Je==="timeline"}),As=l.useMemo(()=>{const te=(Pe||Je==="timeline"?[...it,...St]:it).filter(Be=>_r(_s(Be),J));if(te.length===0)return null;const Oe=Ct(te,"~",[],null,!1).map(Be=>Pe?{...Be,sessions:Qe(Be.sessions,Ne)}:Be).filter(Be=>Be.sessions.length>0);return Oe.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Oe}},[St,Ct,Qe,Pe,J,Ne,it,Je]),yu=l.useMemo(()=>{if(!Pe||!As)return 0;const N=Z=>Z.reduce((te,Oe)=>te+1+N(Oe.children),0);return As.groups.reduce((Z,te)=>Z+N(te.sessions),0)},[As,Pe]),wu=l.useMemo(()=>n.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[n.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),n.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:vu}=um(Y),{sectionsForSidebarRender:Su,filteredSectionsForSidebarRender:ju,totalSessionCount:ku,sessionCountByProject:Cu,hasActiveSessionByProject:Au,activeDirectoriesByProject:Ns,hasUnseenByProject:Nu}=$b({projectSections:xn,flatSectionsForRender:Zr,sectionsForRender:bu,selectedSpaceId:C,selectedWorktreePath:R,homeDirectory:J,activeSessionIdSet:me,unreadSessionIdSet:je}),eo=l.useCallback(N=>{if(Jn.getState().selectSpace(N),!N)return;Ue(N);const Z=xn.find(Be=>Be.project.id===N),te=Z?.groups.find(Be=>Be.isMain),Oe=te?.sessions[0]?.session;Oe?Cs(Oe.id,te?.directory??Z?.project.normalizedPath??null,{keepPanelOpen:!0}):Z&&kt({selectedProjectId:N,directoryOverride:Z.project.normalizedPath})},[kt,xn,Ue,Cs]),Iu=t?"flex size-10 shrink-0 items-center justify-center rounded-full leading-none text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Eu=t?"size-5":"size-4",ar=Rt((N,Z=0,te,Oe,Be=!1,et,yn="project",Qn)=>n.jsx(Nb,{node:N,depth:Z,groupDirectory:te,projectId:Oe,archivedBucket:Be,pinnedSessionIds:Q,expandedParents:ir,hasSessionSearchQuery:Pe,normalizedSessionSearchQuery:Ne,editingId:g,setEditingId:h,editTitle:p,setEditTitle:S,handleSaveEdit:ru,handleCancelEdit:ou,toggleParent:nu,handleSessionSelect:Cs,handleSessionDoubleClick:su,togglePinnedSession:Le,handleShareSession:iu,copiedSessionId:Kc,handleCopyShareUrl:au,handleCopySessionId:lu,handleUnshareSession:cu,openSidebarMenuKey:E,setOpenSidebarMenuKey:T,renamingFolderId:I,getFoldersForScope:sn,getSessionFolderId:rt,removeSessionFromFolder:It,addSessionToFolder:rn,createFolderAndStartRename:Vr,handleDeleteSession:uu,handleRestoreSession:du,mobileVariant:t,alwaysShowActions:xe,allowQuickArchiveAction:$e,renderSessionNode:ar,secondaryMeta:et,renderContext:yn,subtreeContainsEditing:Qn?.subtreeContainsEditing??Yb,menuOpenSessionId:Qn?.menuOpenSessionId??null,nodeStructureKey:Qn?.nodeStructureKey??"",childRenderExtrasFor:Qn?.childRenderExtrasFor})),Du=l.useMemo(()=>{const N=new Map;return Zr.forEach(Z=>{const te=Z.groups[0];te?.folderScopes&&te.folderScopes.length>0&&N.set(Z.project.id,te.folderScopes)}),N},[Zr]),Ru=l.useCallback((N,Z)=>{const te=[];return Z.forEach(Oe=>{te.push(Oe.directory),Oe.folderScopes?.forEach(Be=>te.push(Be.directory))}),n.jsx(Mb,{directories:te})},[]),Bi=l.useCallback(N=>{or(N),Re(Z=>{const te=new Set(Z);return te.has(N)?te.delete(N):te.add(N),te})},[or]),Pu=l.useCallback((N,Z,te,Oe,Be,et)=>n.jsx(jg,{group:N,groupKey:Z,projectId:te,hideGroupLabel:Oe,dragHandleProps:Be,compactBodyPadding:et,hasSessionSearchQuery:Pe,normalizedSessionSearchQuery:Ne,groupSearchDataByGroup:Oi,visibleSessionCount:G.get(Z),collapsedGroups:we,hideDirectoryControls:i,collapsedFolderIds:He,toggleFolderCollapse:bt,renameFolder:Ot,deleteFolder:Ye,showDeletionDialog:mt,setDeleteFolderConfirm:ue,renderSessionNode:ar,showMoreGroupSessions:Ei,resetGroupSessionLimit:or,mobileVariant:t,alwaysShowActions:xe,activeProjectId:Se,setActiveProjectIdOnly:Ue,setActiveMainTab:ne,setSessionSwitcherOpen:Xe,openNewSessionDraft:kt,addSessionToFolder:rn,createFolderAndStartRename:Vr,renamingFolderId:I,renameFolderDraft:W,setRenameFolderDraft:K,setRenamingFolderId:M,pinnedSessionIds:Q,expandedParents:ir,sessionOrderIndex:ce,editingId:g,editTitle:p,openSidebarMenuKey:E,activeActivitySessionIds:me,unreadActivitySessionIds:je,onToggleCollapsedGroup:Bi}),[Pe,Ne,Oi,G,we,i,He,bt,Ot,Ye,mt,ar,Ei,or,t,xe,Se,Ue,ne,Xe,kt,rn,Vr,I,W,Q,ir,ce,g,p,E,me,je,Bi]),_i=!!(I||g||y),zi=l.useRef(it);zi.current=it;const Tu=l.useCallback(N=>zi.current.find(Z=>Z.id===N)?.directory??null,[]),{selectionModeEnabled:to,hasSelection:Ui,selectedIdsSize:Mu,bulkScopeIsArchived:Fu,derivedSelectionScope:Lu,bulkScopeFolders:Ou,bulkCanRemoveFromFolder:Bu,handleToggleSelectionMode:_u,handleExitSelectionMode:zu,handleBulkMoveToFolder:Uu,handleBulkCreateFolderAndMove:$u,handleBulkRemoveFromFolder:Ku,handleBulkDelete:Wu,handleBulkRestore:Gu,confirmBulkDelete:Hu}=Gb({isInlineEditing:_i,showDeletionDialog:mt,foldersMap:dt,folderScopesByProject:Du,addSessionsToFolder:An,removeSessionsFromFolders:Kn,createFolderAndStartRename:Ii,resolveSessionDirectory:Tu,unarchiveSessions:$c,deleteSessions:Ni,setBulkDeleteConfirm:H}),$i=l.useCallback(()=>{de.getState().closeMainSurfaces(),ne("chat"),t&&Xe(!1),yt(),r?.()},[t,r,yt,ne,Xe]),qu=l.useCallback((N,Z)=>{const te=he.find(et=>et.id===N);if(!te)return;const Oe=De(Z.path)?.toLowerCase(),Be=!!(Oe&&Ns.get(N)?.has(Oe));V({projectId:N,projectPath:te.path,worktree:Z,hasActiveSession:Be})},[Ns,he]),Yu=l.useCallback(async({force:N})=>{const Z=Ie;if(!Z)return;const te=De(Z.worktree.path)?.toLowerCase();if(!!(te&&Ns.get(Z.projectId)?.has(te))){V({...Z,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!Bt.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Bt.deleteGitWorktree(Z.projectPath,{directory:Z.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let et=await an(Z.projectPath,Bt,{force:!0});const yn=De(Z.worktree.path);et!==null&&yn!==null&&et.some(Qu=>De(Qu.path)===yn)&&(et=await an(Z.projectPath,Bt,{force:!0}));const Qn=yn!==null&&De(ve)===yn,Vu=yn!==null&&C===Z.projectId&&De(R)===yn;(Qn||Vu)&&eo(Z.projectId),V(null),et===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(Be){const et=Be instanceof Error?Be.message:"Try again.";oe.error("Failed to close worktree.",{description:et})}},[Ns,Ie,ve,Bt,eo,an,C,R]);return n.jsx(cf,{delay:400,closeDelay:150,timeout:600,children:n.jsxs("div",{ref:m,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[n.jsx(pm,{projectSections:xn,activeProjectId:Se,initialActiveSessionByProject:be,persistActiveSessionByProject:ee,handleSessionSelect:Cs,mobileVariant:t,openNewSessionDraft:yt,setActiveMainTab:ne,setSessionSwitcherOpen:Xe}),!i&&!t?n.jsx(Cg,{onNewSession:$i,showSidebarToggle:!0}):null,n.jsx(kg,{hideDirectoryControls:i,handleOpenDirectoryDialog:Yr,onOpenArchive:()=>{t&&Xe(!1),Yt(!0)},onOpenSettings:t?Ai:void 0,onOpenInstances:t?Vn?.openInstances:void 0,instanceLabel:t?Vn?.instanceLabel:void 0,onOpenUpdate:t?Vn?.openUpdate:void 0,headerActionIconClass:Eu,headerActionButtonClass:Iu,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:Pe,searchMatchCount:xu+(Je!=="workspace"||C===null?yu:0),selectionModeEnabled:to,onToggleSelectionMode:_u,mobileVariant:t,onClose:t?()=>Xe(!1):void 0}),gn==="error"||gn==="unavailable"?n.jsx("div",{role:"alert",className:"mx-2 mb-2 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-2 text-xs text-foreground",children:"Unable to reach server"}):null,!i&&xn.length>0&&Je==="workspace"?n.jsx(Ig,{projects:xn.map(N=>N.project),selectedProjectId:C,selectedWorktreePath:R,worktreesByProject:nt,worktreeErrorsByProject:ln,onSelectProject:eo,onSelectWorktree:(N,Z)=>{Jn.getState().selectWorktree(N,Z),Ue(N);const Be=xn.find(et=>et.project.id===N)?.groups.find(et=>De(et.directory)===De(Z))?.sessions[0]?.session;Be?Cs(Be.id,Z,{keepPanelOpen:!0}):kt({selectedProjectId:N,directoryOverride:Z})},onCloseWorktree:qu,onOpenDirectoryDialog:Yr,onOpenProjectEditDialog:v,onRemoveProject:qe,totalSessionCount:ku,getSessionCountForProject:N=>Cu.get(N)??0,hasActiveSessionByProject:Au,activeDirectoriesByProject:Ns,hasUnseenByProject:Nu,homeDirectory:J,mobileVariant:t}):null,n.jsx(Jg,{viewMode:Je,timelineBoundaries:vt,onOpenDirectoryDialog:Yr,stickyFolderHeaders:Ee,sectionsForRender:Je==="workspace"?ju:Su,allFoldersOnlySection:Je==="workspace"?C===null?As:null:As,isAllFoldersView:Je==="workspace"?C===null:Je==="timeline",projectSections:xn,activeProjectId:Se,showOnlyMainWorkspace:a,hasSessionSearchQuery:Pe,emptyState:qn,searchEmptyState:wu,pinnedSessionIds:Q,renderSessionNode:ar,renderGroupSessions:Pu,homeDirectory:J,collapsedProjects:k,hideDirectoryControls:i,projectRepoStatus:L,mobileVariant:t,alwaysShowActions:xe,toggleProject:Qr,setActiveProjectIdOnly:Ue,setActiveMainTab:ne,setSessionSwitcherOpen:Xe,openNewSessionDraft:kt,openProjectEditDialog:v,removeProject:qe,reorderProjects:pe,getOrderedGroups:vu,setGroupOrderByProject:fe,renderProjectStatusIndicator:Ru,openSidebarMenuKey:E,setOpenSidebarMenuKey:T,isInlineEditing:_i}),t&&!(to&&Ui)?n.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-2",children:[n.jsx(Zl,{variant:"mobile"}),n.jsxs(Ae,{type:"button",variant:"default",size:"lg",className:"w-full",onClick:$i,children:[n.jsx(D,{name:"chat-new",className:"size-4"}),"New session"]})]}):null,to&&Ui?n.jsx(Kb,{selectedCount:Mu,scopeKey:Lu,scopeFolders:Ou,archivedBucket:Fu,onMoveToFolder:Uu,onCreateFolderAndMove:$u,onRemoveFromFolder:Ku,canRemoveFromFolder:Bu,onRestore:Gu,onDelete:Wu,onDone:zu}):null,t?null:n.jsx(Eg,{onOpenSettings:Ai,onOpenShortcuts:pt,onOpenAbout:()=>{st("about"),ze(!0)},onOpenUpdate:Yn,showRuntimeButtons:!0,showUpdateButton:_c}),n.jsx(Tb,{updateDialogOpen:q,setUpdateDialogOpen:F,updateStore:ot,editingProject:ks,setEditingProjectDialogId:v,handleSaveProjectEdit:rr,deleteSessionConfirm:O,setDeleteSessionConfirm:ae,showDeletionDialog:mt,setShowDeletionDialog:Nt,confirmDeleteSession:eu,deleteFolderConfirm:X,setDeleteFolderConfirm:ue,confirmDeleteFolder:tu,closeWorktreeConfirm:Ie,setCloseWorktreeConfirm:V,confirmCloseWorktree:Yu,bulkDeleteConfirm:P,setBulkDeleteConfirm:H,confirmBulkDelete:Hu})]})})},Yw=l.memo(Vb),_a=6,Pt=.18,Ms=1.2,Fs=.38,jr=48,Qb=(e,t)=>e==="left"?t<0:t>0,Vw=(e,t,s)=>Math.min(1,Math.max(0,e==="left"?1+t/s:1-t/s)),Qw=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,za=(e,t,s,r)=>e==="left"?t?Math.min(1,Math.max(0,1+s/r)):Math.min(1,Math.max(0,s/r)):t?Math.min(1,Math.max(0,1-s/r)):Math.min(1,Math.max(0,-s/r)),Jw=e=>{const{side:t,dx:s,dy:r,dt:o,progress:i,isDragging:a}=e,c=s/Math.max(1,o);if(a){const u=t==="left"?c<-Pt:c>Pt,d=t==="left"?c>Pt:c<-Pt;return u||!d&&i<Fs}return Math.abs(s)>=jr&&Math.abs(r)<=Math.abs(s)*Ms&&Qb(t,s)},Jb=e=>{const{side:t,isOpenAtStart:s,dx:r,dt:o,progress:i}=e,a=r/Math.max(1,o);return t==="left"?s?a<-Pt?!1:a>Pt?!0:i>Fs:a>Pt?!0:a<-Pt?!1:i>Fs:s?a>Pt?!1:a<-Pt?!0:i>Fs:a<-Pt?!0:a>Pt?!1:i>Fs},Xb='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Zb=(e,t,s)=>{if(!(e instanceof Element))return!1;if(s?.excludeInteractive??!0){const i=e.closest(Xb);if(i&&t.contains(i))return!0}else{const i=e.closest("[data-no-drawer-swipe]");if(i&&t.contains(i))return!0}let o=e;for(;o&&o!==t;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const i=getComputedStyle(o).overflowX;if(i==="auto"||i==="scroll")return!0}o=o.parentElement}return!1},kr=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),fi=512*1024,ex=new TextEncoder,tx=new TextDecoder,go=e=>{const t=ex.encode(e);if(t.byteLength<=fi)return{text:e,byteLength:t.byteLength};let s=t.byteLength-fi;for(;s<t.byteLength&&(t[s]&192)===128;)s+=1;const r=t.subarray(s);return{text:tx.decode(r),byteLength:r.byteLength}},Zn=(e,t)=>`${e}\0${t}`,bo=(e,t)=>{let s=null;for(const r of e.keys())t(r)&&(s??=new Map(e),s.delete(r));return s},nx="terminal-store";let Ua=!1,$a=0;const br=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:($a+=1,`tab-${Date.now().toString(36)}-${$a.toString(36)}`),xo=e=>typeof e=="object"&&e!==null,sx=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const s=Number(t[1]);return Number.isFinite(s)?s:null};function at(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const rx=/^Terminal(?: (\d+))?$/,ox=e=>{let t=0;for(const s of e){const r=rx.exec(s.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},yo=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),wo=e=>({tabs:[e],activeTabId:e.id}),Ut=(e,t)=>e.tabs.findIndex(s=>s.id===t);let vo=null,So=null;const ix=e=>{if(So&&vo?.sessions===e.sessions&&vo.nextTabId===e.nextTabId)return So;const t={sessions:Array.from(e.sessions.entries()).map(([s,r])=>[s,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return vo={sessions:e.sessions,nextTabId:e.nextTabId},So=t,t},ax=()=>{const e=ph(()=>Kf());if(!e)return;let t=null;return{getItem:s=>e.getItem(s),setItem:(s,r)=>{if(r.state!==t)return t=r.state,e.setItem(s,r)},removeItem:s=>(t=null,e.removeItem(s))}},ye=$n()(zr(Ml((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:s=>{const r=at(s);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),a=br(),c=yo(a,"Terminal");return i.set(r,wo(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:s=>{const r=at(s);return t().sessions.get(r)},getActiveTab:s=>{const r=at(s),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(a=>a.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(s,r)=>t().buffers.get(Zn(at(s),r))??kr,createTab:s=>{const r=at(s);if(!r)return"tab-invalid";const o=br();return e(i=>{const a=new Map(i.sessions),c=a.get(r),u=i.nextTabId+1,d=ox(c?.tabs??[]),f=yo(o,d);return c?a.set(r,{...c,tabs:[...c.tabs,f]}):a.set(r,wo(f)),{sessions:a,nextTabId:u}}),o},setActiveTab:(s,r)=>{const o=at(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);return!c||c.activeTabId===r||Ut(c,r)<0?i:(a.set(o,{...c,activeTabId:r}),{sessions:a})})},setTabLabel:(s,r,o)=>{const i=at(s),a=o.trim();a&&e(c=>{const u=new Map(c.sessions),d=u.get(i);if(!d)return c;const f=Ut(d,r);if(f<0||d.tabs[f]?.label===a)return c;const m=[...d.tabs];return m[f]={...m[f],label:a},u.set(i,{...d,tabs:m}),{sessions:u}})},setTabIconKey:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),u=c.get(i);if(!u)return a;const d=Ut(u,r);if(d<0)return a;const f=o?.trim()||null;if(u.tabs[d]?.iconKey===f)return a;const m=[...u.tabs];return m[d]={...m[d],iconKey:f},c.set(i,{...u,tabs:m}),{sessions:c}})},closeTab:(s,r)=>{const o=at(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const u=Ut(c,r);if(u<0)return i;const d=c.tabs.filter(p=>p.id!==r),f=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,p])=>!(p.directory===o&&p.tabId===r))),m=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,b=Zn(o,r),g=i.buffers.has(b)?bo(i.buffers,p=>p===b):null;if(d.length===0){const p=br(),S=yo(p,"Terminal");return a.set(o,wo(S)),{sessions:a,nextTabId:i.nextTabId+1,...g?{buffers:g}:{},...m?{projectActionRuns:f}:{}}}let h=c.activeTabId;return c.activeTabId===r&&(h=d[Math.min(u,d.length-1)]?.id??d[0]?.id??null),a.set(o,{...c,tabs:d,activeTabId:h}),{sessions:a,...g?{buffers:g}:{},...m?{projectActionRuns:f}:{}}})},setTabSessionId:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),u=c.get(i);if(!u)return a;const d=Ut(u,r);if(d<0)return a;const f=u.tabs[d],m=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,g={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},h=Zn(i,r),p=m&&a.buffers.has(h)?bo(a.buffers,y=>y===h):null,S=[...u.tabs];return S[d]=g,c.set(i,{...u,tabs:S}),{sessions:c,...p?{buffers:p}:{}}})},setTabLifecycle:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),u=c.get(i);if(!u)return a;const d=Ut(u,r);if(d<0)return a;const f=[...u.tabs];return f[d]={...f[d],lifecycle:o,isConnecting:!1},c.set(i,{...u,tabs:f}),{sessions:c}})},setConnecting:(s,r,o)=>{const i=at(s);e(a=>{const c=new Map(a.sessions),u=c.get(i);if(!u)return a;const d=Ut(u,r);if(d<0)return a;const f=[...u.tabs];return f[d]={...f[d],isConnecting:o},c.set(i,{...u,tabs:f}),{sessions:c}})},replaceBuffer:(s,r,o,i)=>{const a=at(s);e(c=>{const u=c.sessions.get(a);if(!u||Ut(u,r)<0)return c;const d=Zn(a,r),f=c.buffers.get(d)??kr;if(f.lastSequence>i)return c;const m=go(o);if(f.lastSequence===i&&f.byteLength===m.byteLength&&f.chunks.map(h=>h.data).join("")===m.text)return c;const b=c.nextChunkId,g=new Map(c.buffers);return g.set(d,{chunks:m.text?[{id:b,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:i}),{buffers:g,nextChunkId:m.text?b+1:b}})},appendToBuffer:(s,r,o,i,a)=>{if(!o)return;const c=at(s);e(u=>{const d=u.sessions.get(c);if(!d||Ut(d,r)<0)return u;const f=Zn(c,r),m=u.buffers.get(f)??kr;if(i!==void 0&&i<=m.lastSequence)return u;const b=u.nextChunkId,g=go(o),h=a!==void 0&&a!==o?go(a).text:void 0,p={id:b,data:g.text,...h!==void 0?{replayData:h}:{},byteLength:g.byteLength},S=[...m.chunks,p];let y=m.byteLength+p.byteLength;for(;y>fi&&S.length>1;){const x=S.shift();if(!x)break;y-=x.byteLength}const v=new Map(u.buffers);return v.set(f,{chunks:S,byteLength:y,lastSequence:i??m.lastSequence}),{buffers:v,nextChunkId:b+1}})},setTabPreviewUrl:(s,r,o,i={})=>{const a=at(s);e(c=>{const u=new Map(c.sessions),d=u.get(a);if(!d)return c;const f=Ut(d,r);if(f<0)return c;const m=d.tabs[f],b=i.autoOpened??m.previewAutoOpened,g=i.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===b&&m.previewUrlLocked===g)return c;const h=[...d.tabs];return h[f]={...m,previewUrl:o,previewAutoOpened:b,previewUrlLocked:g},u.set(a,{...d,tabs:h}),{sessions:u}})},markPreviewAutoOpened:(s,r)=>{const o=at(s);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const u=Ut(c,r);if(u<0)return i;const d=c.tabs[u];if(!d.previewUrl||d.previewAutoOpened)return i;const f=[...c.tabs];return f[u]={...d,previewAutoOpened:!0},a.set(o,{...c,tabs:f}),{sessions:a}})},setProjectActionRun:s=>{e(r=>{const o=r.projectActionRuns[s.key];return o&&o.directory===s.directory&&o.actionId===s.actionId&&o.tabId===s.tabId&&o.sessionId===s.sessionId&&o.status===s.status?r:{projectActionRuns:{...r.projectActionRuns,[s.key]:s}}})},updateProjectActionRunStatus:(s,r)=>{e(o=>{const i=o.projectActionRuns[s];return!i||i.status===r?o:{projectActionRuns:{...o.projectActionRuns,[s]:{...i,status:r}}}})},removeProjectActionRun:s=>{e(r=>{if(!r.projectActionRuns[s])return r;const o={...r.projectActionRuns};return delete o[s],{projectActionRuns:o}})},removeDirectory:s=>{const r=at(s);e(o=>{const i=new Map(o.sessions);i.delete(r);const a=Zn(r,""),c=bo(o.buffers,d=>d.startsWith(a)),u=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,d])=>d.directory!==r));return{sessions:i,...c?{buffers:c}:{},projectActionRuns:u}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:nx,storage:ax(),partialize:ix,merge:(e,t)=>{if(!xo(e))return t;const s=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of s){if(!Array.isArray(c)||c.length!==2)continue;const[u,d]=c;if(typeof u!="string"||!xo(d))continue;const f=Array.isArray(d.tabs)?d.tabs:[],m=[],b=new Map;for(const S of f){if(!xo(S))continue;const y=typeof S.id=="string"?S.id:null;if(!y)continue;const v=sx(y);v!==null&&(o=Math.max(o,v));const x=v===null?y:br();b.set(y,x),m.push({id:x,label:typeof S.label=="string"?S.label:"Terminal",iconKey:typeof S.iconKey=="string"?S.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof S.createdAt=="number"?S.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const g=typeof d.activeTabId=="string"?d.activeTabId:null,h=g?b.get(g)??g:null,p=h?m.some(S=>S.id===h):!1;r.set(u,{tabs:m,activeTabId:p?h:m[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,a=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:a,hasHydrated:!0}}})));if(typeof window<"u"&&!Ua){Ua=!0;const e=ye.persist,t=()=>{ye.getState().hasHydrated||ye.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}function lx(e){const{colors:t}=e,s=t.syntax.base;return{background:t.surface.background,foreground:s.foreground,cursor:t.interactive.cursor,cursorAccent:t.surface.background,selectionBackground:t.interactive.selection,selectionForeground:t.interactive.selectionForeground,selectionInactiveBackground:t.interactive.selection+"50",black:t.surface.muted,red:t.status.error,green:t.status.success,yellow:t.status.warning,blue:s.function,magenta:s.keyword,cyan:s.type,white:s.foreground,brightBlack:s.comment,brightRed:t.status.error,brightGreen:t.status.success,brightYellow:t.status.warning,brightBlue:s.function,brightMagenta:s.keyword,brightCyan:s.type,brightWhite:t.surface.elevatedForeground}}function jo(e,t,s){const o=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",cursorInactiveStyle:"none",fontSize:t,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:s.background,foreground:s.foreground,cursor:s.cursor,cursorAccent:s.cursorAccent,selectionBackground:s.selectionBackground,selectionForeground:s.selectionForeground,selectionInactiveBackground:s.selectionInactiveBackground,black:s.black,red:s.red,green:s.green,yellow:s.yellow,blue:s.blue,magenta:s.magenta,cyan:s.cyan,white:s.white,brightBlack:s.brightBlack,brightRed:s.brightRed,brightGreen:s.brightGreen,brightYellow:s.brightYellow,brightBlue:s.brightBlue,brightMagenta:s.brightMagenta,brightCyan:s.brightCyan,brightWhite:s.brightWhite}}}const cx=(e,t)=>{const s=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(s)?"mac":"other"},ux=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),dx=(e,t,s)=>{if(e.altKey)return null;const r=ux(e);return t==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?s?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?s?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?s?"copy":"ignore":null},Ls=e=>typeof e=="string"&&e.trim().length>0;async function Ka(e){return Ls(e)?(await fn(e)).ok:!1}async function fx(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const hx=(e,t,s,r,o)=>{if(s.width<=0||s.height<=0||r<=0||o<=0)return null;const i=Math.floor((e-s.left)/s.width*r),a=Math.floor((t-s.top)/s.height*o);return{column:Math.max(0,Math.min(r-1,i)),row:Math.max(0,Math.min(o-1,a))}},px=(e,t)=>{const s=Math.max(0,Math.min(e.length-1,t)),r=a=>!!(a&&!/^\s+$/u.test(a));if(!r(e[s]))return{startColumn:s,endColumn:s};let o=s,i=s;for(;o>0&&r(e[o-1]);)o-=1;for(;i<e.length-1&&r(e[i+1]);)i+=1;return{startColumn:o,endColumn:i}};let mx=null;const gx=()=>mx??=Promise.all([ht(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),ht(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),bx=2e3,xx=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(t=>setTimeout(t,bx))]).then(()=>{})},yx=(e,t,s)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${s}px ${t}`;const o=r.measureText("M"),i=Math.ceil(o.width),a=Math.ceil((o.actualBoundingBoxAscent||s*.8)+(o.actualBoundingBoxDescent||s*.2))+2;if(i<1||a<1)return null;const c=window.getComputedStyle(e),u=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),d=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-u-15)/i)),rows:Math.max(1,Math.floor((e.clientHeight-d)/a))}},Fc=l.forwardRef(({sessionKey:e,chunks:t,onInput:s,onResize:r,theme:o,fontFamily:i,fontSize:a,className:c,enableTouchScroll:u=!1,autoFocus:d=!0,isVisible:f=!0},m)=>{const b=l.useRef(null),g=l.useRef(null),h=l.useRef(null),p=l.useRef(s),S=l.useRef(r),y=l.useRef(o),v=l.useRef(i),x=l.useRef(a),A=l.useRef(null),j=l.useRef(null),k=l.useRef(null),w=l.useRef(""),C=l.useRef(!1),R=l.useRef(0),L=l.useRef(f),U=l.useRef(!1),[G,$]=l.useState(0),[q,F]=l.useState(0),[E,T]=l.useState(!1),[I,M]=l.useState(!1);p.current=s,S.current=r,L.current=f,y.current=o,v.current=i,x.current=a,l.useLayoutEffect(()=>{const V=b.current;if(!V)return;const P=yx(V,i,a);j.current=P,P&&S.current(P.cols,P.rows)},[i,a]);const W=l.useCallback(()=>{const V=b.current,P=g.current;if(!V||!P||!h.current||!L.current)return;const H=V.getBoundingClientRect();if(!(H.width<24||H.height<24))try{h.current.fit();const Q={cols:P.cols,rows:P.rows};(!A.current||A.current.cols!==Q.cols||A.current.rows!==Q.rows)&&(A.current=Q,S.current(Q.cols,Q.rows)),U.current||(U.current=!0,$(re=>re+1))}catch{}},[]),K=l.useCallback(()=>{if(C.current||!w.current||!g.current)return;const V=g.current,P=w.current;if(w.current="",!P)return;C.current=!0;const H=R.current;V.write(P,()=>{g.current!==V||R.current!==H||(C.current=!1,w.current&&K())})},[]),O=l.useCallback(()=>{k.current=null,w.current="",C.current=!1,R.current+=1;const V=g.current;if(!V){F(P=>P+1);return}try{V.reset()}catch{F(P=>P+1)}},[]),ae=l.useCallback(V=>{V?.preventDefault(),M(Ls(g.current?.getSelection())),T(!0)},[]),X=l.useCallback(V=>{V.stopPropagation();const P=g.current,H=P?.getSelection()??"";P?.focus(),Ls(H)&&Ka(H)},[]),ue=l.useCallback(V=>{V.stopPropagation();const P=g.current;P?.focus(),fx().then(H=>{H&&g.current===P&&P&&P.paste(H)})},[]),Ie=l.useCallback(V=>{V.stopPropagation();const P=g.current;P?.focus();try{P?.selectAll()}catch{}M(Ls(P?.getSelection()))},[]);return l.useEffect(()=>{const V=b.current;if(!V)return;let P=!1,H=null,Q=null,re=null,ie=null,ge=[];const me=()=>{H&&L.current&&(H.options.cursorBlink=!0)},Ce=we=>{we.relatedTarget instanceof Node&&V.contains(we.relatedTarget)||H&&(H.options.cursorBlink=!1)},je=()=>{H&&L.current&&V.contains(document.activeElement)&&(H.options.cursorBlink=!0)},Le=()=>{H&&(H.options.cursorBlink=!1)};return V.addEventListener("focusin",me),V.addEventListener("focusout",Ce),window.addEventListener("focus",je),window.addEventListener("blur",Le),Promise.all([gx(),xx()]).then(([{Xterm:we,Fit:Re}])=>{if(P)return;const Y=y.current,fe=v.current,be=x.current;H=new we.Terminal({...jo(fe,be,Y),...j.current??{}});const ee=new Re.FitAddon;H.loadAddon(ee),H.open(V),g.current=H,h.current=ee;const se=typeof navigator>"u"?"other":cx(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),_e=H;H.attachCustomKeyEventHandler(ke=>{if(ke.type!=="keydown")return!0;const J=_e.getSelection(),ve=dx({key:ke.key,code:ke.code,ctrlKey:ke.ctrlKey,shiftKey:ke.shiftKey,metaKey:ke.metaKey,altKey:ke.altKey},se,Ls(J));return ve==="copy"?(Ka(J),!1):ve!=="ignore"}),ge=[H.onData(ke=>p.current(ke))],Q=new ResizeObserver(()=>{re&&clearTimeout(re),re=setTimeout(W,80)}),Q.observe(V),W(),ie=requestAnimationFrame(W)}),()=>{P=!0;const we=document.activeElement;we instanceof HTMLElement&&V.contains(we)&&(we.blur(),window.Capacitor?.getPlatform?.()==="android"&&ht(async()=>{const{Keyboard:Y}=await import("./vendor-capacitor-keyboard-CgrHt8iN.js");return{Keyboard:Y}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:Y})=>Y.hide()).catch(()=>{})),Q?.disconnect(),re&&clearTimeout(re),ie!==null&&cancelAnimationFrame(ie),V.removeEventListener("focusin",me),V.removeEventListener("focusout",Ce),window.removeEventListener("focus",je),window.removeEventListener("blur",Le),ge.forEach(Re=>Re.dispose()),H?.dispose(),g.current=null,h.current=null,A.current=null,k.current=null,w.current="",C.current=!1,R.current+=1,U.current=!1}},[W,q]),l.useEffect(()=>{const V=g.current;V&&(V.options.theme=jo(i,a,o).theme,V.options.fontFamily=jo(i,a,o).fontFamily,V.options.fontSize=a)},[i,a,o]),l.useEffect(()=>{const V=g.current,P=b.current;!V||!P||(V.options.cursorBlink=f&&document.hasFocus()&&P.contains(document.activeElement))},[f,G]),l.useEffect(()=>{if(!g.current)return;if(t.length===0){k.current!==null&&O();return}const P=k.current;let H=-1;if(P!==null){for(let ie=t.length-1;ie>=0;ie-=1){const ge=t[ie].id;if(ge===P){H=ie;break}if(ge<P)break}if(H<0){O();return}}const Q=H<0,re=H>=0?t.slice(H+1):t;w.current+=re.map(ie=>Q?ie.replayData??ie.data:ie.data).join(""),k.current=t.at(-1)?.id??null,K()},[t,K,G,O]),l.useEffect(()=>{if(!d||!f)return;const V=requestAnimationFrame(()=>g.current?.focus());return()=>cancelAnimationFrame(V)},[d,f,G,e]),l.useEffect(()=>{const V=b.current,P=g.current;if(!u||!V||!P)return;let H=null,Q=null,re="idle",ie=0,ge=0,me=0,Ce=0,je=null;const Le=Math.max(12,a+2),we=()=>{window.Capacitor?.getPlatform?.()==="android"&&ht(async()=>{const{Keyboard:ve}=await import("./vendor-capacitor-keyboard-CgrHt8iN.js");return{Keyboard:ve}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:ve})=>ve.show()).catch(()=>{})},Re=()=>{Q&&(clearTimeout(Q),Q=null)},Y=(J,ve)=>{const he=V.querySelector("canvas");return he?hx(J,ve,he.getBoundingClientRect(),P.cols,P.rows):null},fe=(J,ve)=>{const he=V.querySelector("canvas");if(!he)return;const Se=he.getBoundingClientRect(),qe=Se.left+(ve.column+.5)/P.cols*Se.width,Ue=Se.top+(ve.row+.5)/P.rows*Se.height;he.dispatchEvent(new MouseEvent(J,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:qe,clientY:Ue}))},be=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ee=J=>{J.pointerType!=="touch"||H!==null||(H=J.pointerId,re="pending",ie=J.clientX,ge=J.clientY,me=J.clientY,Ce=0,je=null,V.setPointerCapture(J.pointerId),Q=setTimeout(()=>{if(Q=null,H!==J.pointerId||re!=="pending")return;const ve=Y(ie,ge);if(!ve)return;const he=P.buffer.active,Se=Math.max(0,he.length-P.rows-he.viewportY+ve.row),qe=he.getLine(Se),Ue=Array.from({length:P.cols},(ne,ze)=>qe?.getCell(ze)?.getChars()??""),z=px(Ue,ve.column),pe={column:z.startColumn,row:ve.row};je={column:z.endColumn,row:ve.row},re="selecting",fe("mousedown",pe),fe("mousemove",je)},350))},se=J=>{if(H!==J.pointerId)return;if(re==="selecting"){const Se=Y(J.clientX,J.clientY);Se&&(!je||Se.column!==je.column||Se.row!==je.row)&&(je=Se,fe("mousemove",Se)),J.cancelable&&J.preventDefault();return}if(re==="pending"){if(Math.hypot(J.clientX-ie,J.clientY-ge)<8)return;Re(),re="scrolling"}if(re!=="scrolling")return;const ve=me-J.clientY;me=J.clientY,Ce+=ve;const he=Math.trunc(Ce/Le);he&&(P.scrollLines(he),Ce-=he*Le),J.cancelable&&J.preventDefault()},_e=J=>{if(H!==J.pointerId)return;const ve=re==="pending",he=re==="selecting";Re(),V.hasPointerCapture(J.pointerId)&&V.releasePointerCapture(J.pointerId),H=null,re="idle",he&&be(),ve&&(P.focus(),we())},ke=J=>{if(H!==J.pointerId)return;const ve=re==="selecting";Re(),V.hasPointerCapture(J.pointerId)&&V.releasePointerCapture(J.pointerId),H=null,re="idle",ve&&be()};return V.addEventListener("pointerdown",ee),V.addEventListener("pointermove",se,{passive:!1}),V.addEventListener("pointerup",_e),V.addEventListener("pointercancel",ke),()=>{Re(),V.removeEventListener("pointerdown",ee),V.removeEventListener("pointermove",se),V.removeEventListener("pointerup",_e),V.removeEventListener("pointercancel",ke)}},[u,a,G]),l.useImperativeHandle(m,()=>({focus:()=>g.current?.focus(),fit:W,getSelection:()=>{const V=g.current,P=V?.getSelectionPosition(),H=V?.getSelection()??"";return!P||!H.trim()?null:{text:H,startLine:P.start.y+1,endLine:P.end.y+1}}}),[W]),n.jsxs(Wr,{open:E,onOpenChange:T,children:[n.jsx(Gr,{render:n.jsx("div",{ref:b,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:ae})}),n.jsxs(Hr,{className:"min-w-[180px]",children:[n.jsxs(On,{disabled:!I,onClick:X,children:[n.jsx(D,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),n.jsxs(On,{onClick:ue,children:[n.jsx(D,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),n.jsx(vc,{}),n.jsx(On,{onClick:Ie,children:"Select all"})]})]})});Fc.displayName="TerminalViewport";const wx=({directory:e,tabId:t,sessionId:s,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:a,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,lastViewportSizeRef:m,onInput:b,controllerRef:g})=>{const h=ye(x=>e&&t?x.getBuffer(e,t).chunks:kr.chunks),p=l.useRef(null),S=o&&i,y=l.useCallback(x=>{p.current=x,g&&(g.current=o?x:g.current),!o&&g&&g.current===x&&(g.current=null)},[g,o]);l.useEffect(()=>{if(!o||!i)return;const x=requestAnimationFrame(()=>{p.current?.fit()});return()=>cancelAnimationFrame(x)},[o,i,r,s]);const v=l.useCallback((x,A)=>{if(!o)return;const j=m.current;(!j||j.cols!==x||j.rows!==A)&&(m.current={cols:x,rows:A}),s&&a.resize({sessionId:s,cols:x,rows:A}).catch(()=>{})},[o,m,s,a]);return n.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:n.jsx(Fc,{ref:y,sessionKey:r,chunks:h,onInput:b,onResize:v,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,autoFocus:S,isVisible:S},r)})},Wa=({items:e,activeId:t,onSelect:s,onClose:r,onCreate:o,disabled:i=!1})=>{const a=e.find(c=>c.id===t)??e[0]??null;return n.jsxs(Gt,{modal:!1,children:[n.jsx(Ht,{asChild:!0,children:n.jsxs(Ae,{type:"button",variant:"ghost",size:"sm",disabled:i,title:a?`Switch terminal, current: ${a.label}`:"Switch terminal","aria-label":a?`Switch terminal, current: ${a.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[a?.icon??n.jsx(D,{name:"terminal",className:"size-4 shrink-0"}),n.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:a?.label??"Terminal"}),n.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),n.jsxs(qt,{align:"start",className:"w-64",children:[e.map(c=>{const u=c.id===(a?.id??t);return n.jsxs(ut,{title:c.title??c.label,onClick:()=>s(c.id),className:"group/tab min-w-0",children:[n.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,n.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),u?n.jsx(D,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,n.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:d=>{d.preventDefault(),d.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:n.jsx(D,{name:"close",className:"size-3"})})]},c.id)}),n.jsx(us,{}),n.jsxs(ut,{onClick:o,children:[n.jsx(D,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},vx=({leading:e,icon:t,title:s,actions:r,className:o})=>n.jsxs("header",{className:_("flex h-11 shrink-0 items-center gap-1 border-b border-border bg-background pl-3 pr-2",o),children:[e,s!=null?typeof s=="string"?n.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[typeof t=="string"?n.jsx(D,{name:t,className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):t??null,n.jsx("h2",{className:"truncate typography-ui-label font-medium text-foreground",children:s})]}):n.jsx("div",{className:"min-w-0 flex-1",children:s}):null,r?n.jsx("div",{className:"flex shrink-0 items-center gap-1",children:r}):null]}),Sx=({isTouchTerminal:e,activeModifier:t,disabled:s,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",a=e?"w-10 p-0":"w-9 p-0",c=u=>{e&&u.preventDefault()};return n.jsxs(n.Fragment,{children:[n.jsx(Ae,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:s,children:"Esc"}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("tab"),disabled:s,children:[n.jsx(D,{name:"arrow-right",className:"h-4 w-4"}),n.jsx("span",{className:"sr-only",children:"Tab"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"chip","aria-pressed":t==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:s,children:[n.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),n.jsx("span",{className:"sr-only",children:"Control modifier"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"chip","aria-pressed":t==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:s,children:[n.jsx("span",{className:"text-xs font-medium",children:"Alt"}),n.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:s,children:[n.jsx(D,{name:"arrow-up"}),n.jsx("span",{className:"sr-only",children:"Arrow up"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:s,children:[n.jsx(D,{name:"arrow-left"}),n.jsx("span",{className:"sr-only",children:"Arrow left"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:s,children:[n.jsx(D,{name:"arrow-down"}),n.jsx("span",{className:"sr-only",children:"Arrow down"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:s,children:[n.jsx(D,{name:"arrow-right"}),n.jsx("span",{className:"sr-only",children:"Arrow right"})]}),n.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("enter"),disabled:s,children:[n.jsx(D,{name:"arrow-go-back"}),n.jsx("span",{className:"sr-only",children:"Enter"})]})]})},jx="\x1B",kx=new RegExp(`${jx}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Cx=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Ax=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Nx=/Serving HTTP on .*? port (\d{2,5})/i,Ix=new Set([".",",",";",":","!","?"]),Ex=e=>{let t=e;for(;t.length>0;){const s=t[t.length-1];if(s===")"||s==="]"||s==="}"||s===">"){const r=s===")"?"(":s==="]"?"[":s==="}"?"{":"<",o=t.slice(0,-1),i=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,a=(o.match(new RegExp(`\\${s}`,"g"))||[]).length;if(i>a)break;t=o;continue}if(Ix.has(s)){t=t.slice(0,-1);continue}break}return t},Ga=e=>{let t=Ex(e);return t=t.replace("0.0.0.0","127.0.0.1"),t=t.replace("[::1]","127.0.0.1"),t=t.replace("[::]","127.0.0.1"),t},Dx=e=>{if(!e)return null;const t=e.replace(kx,""),s=t.match(Nx);if(s?.[1]){const o=Number.parseInt(s[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=t.split(`
55
- `);for(const o of r){if(!Ax.test(o))continue;const i=Array.from(o.matchAll(Cx));if(i.length===0)continue;const a=i.find(c=>{try{return!!new URL(Ga(c[1])).port}catch{return!1}});return Ga((a??i[0])[1])}return null},Rx=async(e,t=1500)=>{if(!e||typeof window>"u")return!1;let s;try{s=new URL(e)}catch{return!1}if(s.protocol!=="http:"&&s.protocol!=="https:")return!1;const r=s.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,i=window.setTimeout(()=>o.abort(),t);try{const a=await tt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:s.toString()}),cache:"no-store",signal:o.signal});return a.ok?(await a.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},Px={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Tx=(e,t)=>{if(t&&e.startsWith("arrow-")){const s=t==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${s}${r}`}return Px[e]},Lc=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},Mx=(e,t)=>e&&(t==="ctrl"?Lc(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Oc={cols:80,rows:24},Ha={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class Fx{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(t,s,r,o){if(!r)return;const i=`${this.tail}${r}`.replace(/\r\n|\r/g,`
56
- `),a=i.split(`
57
- `),c=i.endsWith(`
58
- `)?a.join(`
59
- `):a.slice(0,-1).join(`
60
- `);if(this.tail=i.endsWith(`
61
- `)?"":(a[a.length-1]??"").slice(-1024),!c)return;const u=Dx(c);if(!u||this.pendingUrls.has(u))return;const d=this.probeGeneration;this.pendingUrls.add(u),Rx(u).then(f=>{if(this.pendingUrls.delete(u),!f||this.probeGeneration!==d)return;const m=ye.getState().getDirectoryState(t)?.tabs.find(b=>b.id===s);!m||m.previewUrlLocked||m.previewUrl===u||o(t,s,u,{locked:!1,autoOpened:!1})})}}const Lx=(e,t)=>{if(t!=="ctrl")return null;const s=e.key,r=e.code??"",o=s.length===1&&/[a-zA-Z]/.test(s)?s.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Lc(o):null};function Ox({terminal:e,effectiveDirectory:t,activeTabId:s,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:a,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:d,enableTabs:f,hasActiveContext:m,focusTerminalWhenWindowActive:b,tabs:g}){const h=ye(P=>P.ensureDirectory),p=ye(P=>P.setTabSessionId),S=ye(P=>P.setTabLifecycle),y=ye(P=>P.setConnecting),v=ye(P=>P.appendToBuffer),x=ye(P=>P.replaceBuffer),A=ye(P=>P.setTabPreviewUrl),[j,k]=l.useState(null),[w,C]=l.useState(!1),[R,L]=l.useState(!1),U=l.useRef(new Map),G=l.useRef(null),$=l.useRef(s),q=l.useRef(r),F=l.useRef(t),E=l.useRef(null),T=l.useRef(new Set),I=l.useRef(new Map),M=l.useRef(g),W=l.useRef(a),K=l.useRef(i),O=l.useRef(e);M.current=g,W.current=a,K.current=i,O.current=e;const ae=l.useCallback(()=>{const P=$.current;P&&I.current.get(P)?.reset()},[]);l.useEffect(()=>{q.current=r},[r]),l.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,d.current).catch(()=>{})},[d,e,r]),l.useEffect(()=>{$.current=s},[s]),l.useEffect(()=>{F.current=t},[t]);const X=l.useCallback(()=>{for(const P of U.current.values())try{P()}catch{}U.current.clear(),G.current=null,L(!1)},[]);l.useEffect(()=>()=>{X(),q.current=null},[X]);const ue=l.useCallback((P,H,Q)=>{let re=I.current.get(H);re||(re=new Fx,I.current.set(H,re)),re.scan(P,H,Q,A)},[A]),Ie=l.useCallback((P,H,Q)=>{if(U.current.has(Q)){G.current=Q;return}const re=Ji(),ie=()=>Ji()===re&&F.current===P&&ye.getState().getDirectoryState(P)?.tabs.find(me=>me.id===H)?.terminalSessionId===Q,ge=e.connect(Q,{onEvent:me=>{if(ie())switch(me.type){case"snapshot":{$.current===H&&q.current===Q?(y(P,H,!1),k(null),C(!1),L(!1),b()):y(P,H,!1),x(P,H,me.data??"",me.sequence??0),ue(P,H,me.data??""),me.status==="exited"&&S(P,H,"exited");break}case"reconnecting":{$.current===H&&(k(null),C(!1),L(!0));break}case"data":{me.data&&(v(P,H,me.data,me.sequence,me.replayData),ue(P,H,me.data));break}case"exit":{const Ce=typeof me.exitCode=="number"?me.exitCode:null,je=typeof me.signal=="number"?me.signal:null,we=!!ye.getState().getDirectoryState(P)?.tabs.find(Re=>Re.id===H)?.label?.startsWith("Action:");v(P,H,`\\r\\n[Process exited${Ce!==null?` with code ${Ce}`:""}${je!==null?` (signal ${je})`:""}]\\r\\n`),S(P,H,"exited"),$.current===H&&(y(P,H,!1),k(we?null:"Terminal session ended"),C(!1),L(!1));break}}},onError:(me,Ce)=>{if(!ie())return;const je=$.current===H;if(!Ce){je&&(k(null),C(!1));return}if(me.code==="SESSION_NOT_FOUND"&&!ye.getState().getDirectoryState(P)?.tabs.find(we=>we.id===H)?.label?.startsWith("Action:")){je&&(k(null),C(!1),y(P,H,!1),L(!1)),p(P,H,null),S(P,H,"idle");return}je&&(L(!1),k(`Connection failed: ${me.message}`),C(!0),y(P,H,!1),S(P,H,"exited"),p(P,H,null))}});U.current.set(Q,()=>ge.close()),G.current=Q},[v,b,x,ue,y,S,p,e]),V=l.useMemo(()=>g.map(P=>`${P.id}:${P.terminalSessionId??""}`).join(","),[g]);return l.useEffect(()=>{if(!a||!i||!t)return;const P=t,H=new Set;for(const Q of g)Q.terminalSessionId&&(H.add(Q.terminalSessionId),Ie(P,Q.id,Q.terminalSessionId));for(const[Q,re]of U.current)if(!H.has(Q)){try{re()}catch{}U.current.delete(Q)}},[V,g,t,a,i,Ie]),l.useEffect(()=>Wf(()=>{if(!W.current||!K.current)return;const P=F.current;if(!P)return;const H=[];for(const re of M.current){if(!re.terminalSessionId)continue;ye.getState().getDirectoryState(P)?.tabs.find(ge=>ge.id===re.id)?.terminalSessionId===re.terminalSessionId&&H.push({id:re.id,terminalSessionId:re.terminalSessionId})}if(U.current.clear(),G.current=null,H.length===0)return;L(!0),k(null),C(!1);for(const re of H)Ie(P,re.id,re.terminalSessionId);const Q=E.current;if(Q)for(const re of H)O.current.resize({sessionId:re.terminalSessionId,...Q}).catch(()=>{})}),[Ie]),l.useEffect(()=>{let P=!1;if(!a||!i)return;if(!t){k(m?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const Q=t;if(!F.current||F.current!==Q)return;if(!ye.getState().getDirectoryState(Q)){h(Q);return}const ie=ye.getState().getDirectoryState(Q);if(!ie||ie.tabs.length===0)return;const ge=ie.activeTabId??ie.tabs[0]?.id??null;if(!ge)return;const me=ie.tabs.find(Y=>Y.id===ge)??ie.tabs[0],Ce=me?.terminalSessionId??null,je=me?.lifecycle??"idle",Le=!!me?.label?.startsWith("Action:"),we=ye.getState().getBuffer(Q,ge),Re=we.byteLength>0||we.chunks.length>0;if(!Ce){if(je==="exited"){y(Q,ge,!1);return}if(Le&&Re){y(Q,ge,!1);return}const Y=`${Q}\0${ge}`;if(T.current.has(Y))return;const fe=E.current??Oc;T.current.add(Y),k(null),C(!1),L(!1),y(Q,ge,!0);try{const be=await e.createSession({cwd:Q,sessionId:ge,cols:fe.cols,rows:fe.rows,shell:c,loginShell:u,...d.current});if(!ye.getState().getDirectoryState(Q)?.tabs.find(_e=>_e.id===ge)){try{await e.close(be.sessionId)}catch{}return}p(Q,ge,be.sessionId);const se=E.current;se&&(se.cols!==fe.cols||se.rows!==fe.rows)&&e.resize({sessionId:be.sessionId,...se}).catch(()=>{});return}catch(be){const ee=ye.getState().getDirectoryState(Q)?.tabs.find(se=>se.id===ge);if(!ee||ee.terminalSessionId||(y(Q,ge,!1),F.current!==Q||$.current!==ge))return;k(be instanceof Error?be.message:"Failed to start terminal session"),C(!0),L(!1);return}finally{T.current.delete(Y)}}!Ce||P||(q.current=Ce)})(),()=>{P=!0}},[m,t,r,o,s,i,f,a,h,y,S,p,e,u,c,d]),{connectionError:j,setConnectionError:k,isFatalError:w,setIsFatalError:C,isReconnectPending:R,setIsReconnectPending:L,terminalIdRef:q,lastViewportSizeRef:E,directoryRef:F,activeTabIdRef:$,disconnectStream:X,resetTerminalPreviewScan:ae,startStream:Ie}}function Bx({terminal:e,terminalIdRef:t,isReconnectPending:s,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:a,terminalSessionId:c,useTouchTerminalInput:u}){const[d,f]=l.useState(null),m=l.useRef(null),b=l.useCallback(()=>{u||m.current?.focus()},[u]),g=l.useCallback(()=>{u||typeof document<"u"&&!document.hasFocus()||m.current?.focus()},[u]);l.useEffect(()=>{!o&&d!==null&&f(null)},[o,d]),l.useEffect(()=>{!c&&d!==null&&f(null)},[c,d]);const h=l.useCallback(x=>{if(!x||s)return;let A=x,j=!1;d&&x.length>0&&(A=Mx(x,d),j=!0);const k=t.current;k&&(e.sendInput(k,A).catch(w=>{s||r(w instanceof Error?w.message:"Failed to send input")}),j&&(f(null),b()))},[d,b,s,r,e,t]),p=l.useCallback((x,A)=>{const j=a.current;if((!j||j.cols!==x||j.rows!==A)&&(a.current={cols:x,rows:A}),!i)return;const k=t.current;k&&e.resize({sessionId:k,cols:x,rows:A}).catch(()=>{})},[i,a,e,t]),S=l.useCallback(x=>{f(A=>A===x?null:x),b()},[b]),y=l.useCallback(x=>{const A=Tx(x,d);A&&(h(A),f(null),b())},[d,b,h]),v=l.useCallback(x=>{if(x.repeat)return;const A=x.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const j=A.length===1?A.toLowerCase():A;if(j in Ha){x.preventDefault(),x.stopPropagation(),y(Ha[j]);return}const k=Lx(x,d);k&&(x.preventDefault(),x.stopPropagation(),h(k),f(null),b())},[d,b,y,h]);return l.useEffect(()=>{if(!(!o||!d||!c))return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[d,v,o,c]),{activeModifier:d,setActiveModifier:f,terminalControllerRef:m,focusTerminalController:b,focusTerminalWhenWindowActive:g,handleViewportInput:h,handleViewportResize:p,handleModifierToggle:S,handleMobileKeyPress:y}}function _x({terminal:e,effectiveDirectory:t,activeTabId:s,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:a,lastViewportSizeRef:c,directoryRef:u,activeTabIdRef:d,terminalIdRef:f,resetTerminalPreviewScan:m,startStream:b,setConnectionError:g,setIsFatalError:h,setIsReconnectPending:p}){const S=ye(G=>G.createTab),y=ye(G=>G.setActiveTab),v=ye(G=>G.closeTab),x=ye(G=>G.setTabSessionId),A=ye(G=>G.setTabLifecycle),[j,k]=l.useState(!1),w=l.useCallback(async()=>{if(!t||j)return;const G=ye.getState().getDirectoryState(t),$=s??G?.activeTabId??G?.tabs[0]?.id??null;if(!$)return;const q=G?.tabs.find(F=>F.id===$)?.terminalSessionId??null;if(!(!q||!e.restartSession)){k(!0),g(null),h(!1),p(!1),m();try{const F=c.current??Oc,E=await e.restartSession(q,{cwd:t,shell:o,loginShell:i,...F,...a.current});if(ye.getState().getDirectoryState(t)?.tabs.find(I=>I.id===$)?.terminalSessionId!==q||(x(t,$,E.sessionId),A(t,$,"running"),u.current!==t||d.current!==$))return;f.current=E.sessionId,b(t,$,E.sessionId)}catch(F){if(ye.getState().getDirectoryState(t)?.tabs.find(T=>T.id===$)?.terminalSessionId!==q||u.current!==t||d.current!==$)return;g(F instanceof Error?F.message:"Failed to restart terminal"),h(!1),p(!1),f.current=q,b(t,$,q)}finally{k(!1)}}},[s,d,u,t,r,j,c,m,g,h,p,A,x,b,e,a,f,i,o]),C=l.useCallback(async()=>{await w()},[w]),R=l.useCallback(()=>{if(!t)return;const G=S(t);y(t,G),g(null),h(!1),p(!1)},[S,t,y,g,h,p]),L=l.useCallback(G=>{t&&(y(t,G),g(null),h(!1),p(!1))},[t,y,g,h,p]),U=l.useCallback(G=>{if(!t)return;g(null),h(!1),p(!1);const $=ye.getState().getDirectoryState(t)?.tabs.find(q=>q.id===G)?.terminalSessionId;(async()=>{$&&await e.close($),v(t,G)})().catch(q=>g(q instanceof Error?q.message:"Terminal session ended"))},[v,t,g,h,p,e]);return{isRestarting:j,handleRestart:w,handleHardRestart:C,handleCreateTab:R,handleSelectTab:L,handleCloseTab:U}}const Xw=({visible:e,onCloseView:t,terminalHeaderSlot:s})=>{const{terminal:r,runtime:o}=Un(),{currentTheme:i}=Sl(),a=l.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});a.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=uf(),u=de(ne=>ne.terminalFontSize),d=de(ne=>ne.terminalShell),f=de(ne=>ne.terminalLoginShells.includes(ne.terminalShell)),{isMobile:m,isTablet:b,hasTouchOnlyPointer:g}=ps(),h=m||b,p=(h||g)&&o.platform==="web",S=!0,y=de(ne=>ne.showTerminalQuickKeysOnDesktop),v=h||y,x=Fe(ne=>ne.currentSessionId),A=Fe(ne=>ne.newSessionDraft),j=x!==null||A?.open===!0,k=df()??null,w=ye(ne=>k?ne.sessions.get(k):void 0),C=ye(ne=>ne.hasHydrated),R=de(ne=>ne.openContextPreview),L=l.useMemo(()=>w?w.activeTabId??w.tabs[0]?.id??null:null,[w,S]),U=l.useMemo(()=>{if(w)return L?w.tabs.find(ne=>ne.id===L)??w.tabs[0]:w.tabs[0]},[w,L]),G=l.useMemo(()=>(w?.tabs??[]).map(ne=>({icon:(()=>{const ze=ne.iconKey?Ks[ne.iconKey]??"terminal":"terminal";return n.jsx(D,{name:ze,className:"h-4 w-4"})})(),id:ne.id,label:ne.label,title:ne.label,closeLabel:"Close tab"})),[w?.tabs]),$=U?.terminalSessionId??null,q=U?.lifecycle??"idle",F=l.useMemo(()=>(w?.tabs??[]).map(ne=>({id:ne.id,terminalSessionId:ne.terminalSessionId,label:ne.label})),[w?.tabs]),E=U?.isConnecting??!1,T=U?.previewUrl??null,M=de(ne=>ne.activeMainTab)==="terminal",W=e??M,[K,O]=l.useState(W);l.useEffect(()=>{W&&O(!0)},[W]);const{connectionError:ae,setConnectionError:X,isFatalError:ue,setIsFatalError:Ie,isReconnectPending:V,setIsReconnectPending:P,terminalIdRef:H,lastViewportSizeRef:Q,directoryRef:re,activeTabIdRef:ie,resetTerminalPreviewScan:ge,startStream:me}=Ox({terminal:r,effectiveDirectory:k,activeTabId:L,terminalSessionId:$,terminalLifecycle:q,hasOpenedTerminalViewport:K,terminalHydrated:C,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:a,enableTabs:S,hasActiveContext:j,tabs:F,focusTerminalWhenWindowActive:()=>{!p&&typeof document<"u"&&document.hasFocus()&&je.current?.focus()}}),{activeModifier:Ce,terminalControllerRef:je,focusTerminalWhenWindowActive:Le,handleViewportInput:we,handleModifierToggle:Re,handleMobileKeyPress:Y}=Bx({terminal:r,terminalIdRef:H,isReconnectPending:V,setConnectionError:X,showQuickKeys:v,isTerminalVisible:W,lastViewportSizeRef:Q,terminalSessionId:$,useTouchTerminalInput:p}),{isRestarting:fe,handleRestart:be,handleHardRestart:ee,handleCreateTab:se,handleSelectTab:_e,handleCloseTab:ke}=_x({terminal:r,effectiveDirectory:k,activeTabId:L,enableTabs:S,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:a,lastViewportSizeRef:Q,directoryRef:re,activeTabIdRef:ie,terminalIdRef:H,resetTerminalPreviewScan:ge,startStream:me,setConnectionError:X,setIsFatalError:Ie,setIsReconnectPending:P});l.useEffect(()=>{if(!W||p)return;if(typeof window>"u"){Le();return}const ne=window.requestAnimationFrame(()=>{Le()});return()=>{window.cancelAnimationFrame(ne)}},[L,Le,W,p]);const J=l.useMemo(()=>{const ne=Is[so].stack;if(typeof window>"u")return(Is[c]??Is[so]).stack;const st=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return st&&st.trim().length>0?st.trim():(Is[c]??Is[so]).stack??ne},[c]),ve=l.useMemo(()=>lx(i),[i]),he=`${k??"no-dir"}::${L??"no-tab"}`;if(l.useEffect(()=>{if(!W||p)return;const ne=je.current;if(!ne)return;const ze=()=>{ne.fit()};if(typeof window<"u"){const st=window.requestAnimationFrame(()=>{ze(),Le()}),pt=[220,400].map(Xe=>window.setTimeout(ze,Xe));return()=>{window.cancelAnimationFrame(st),pt.forEach(Xe=>window.clearTimeout(Xe))}}ze()},[Le,W,p,je,he,$]),l.useEffect(()=>{if(!W||!p)return;let ne=null;const ze=()=>{ne!==null&&window.cancelAnimationFrame(ne),ne=window.requestAnimationFrame(()=>{ne=null,je.current?.fit()})};return window.addEventListener("oc:keyboard-settled",ze),()=>{window.removeEventListener("oc:keyboard-settled",ze),ne!==null&&window.cancelAnimationFrame(ne)}},[W,je,he,p]),!j)return n.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!k)return n.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{children:"No working directory available for this session."}),n.jsx("button",{onClick:be,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Se=!$||E||fe||V,qe=K,Ue=w?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"min-w-0 flex-1",children:n.jsx(Wa,{items:G,activeId:L,onSelect:_e,onClose:ke,onCreate:se})}),n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:se,title:"New tab","aria-label":"New tab",children:n.jsx(D,{name:"add",className:"h-4 w-4"})}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{be()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:n.jsx(D,{name:"restart",className:"h-4 w-4"})}),T?n.jsxs(Ae,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{k&&R(k,T)},title:"Open preview pane",children:[n.jsx(D,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),n.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,z=n.jsx(Sx,{isTouchTerminal:h,activeModifier:Ce,disabled:Se,onKeyPress:Y,onModifierToggle:Re}),pe=!s||h||v;return n.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[Ue&&s?ld.createPortal(n.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ue}),s):null,h&&Ue&&!s&&w?n.jsx(vx,{leading:n.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:n.jsx(Wa,{items:G,activeId:L,onSelect:_e,onClose:ke,onCreate:se})}),actions:n.jsxs(n.Fragment,{children:[n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:se,title:"New tab","aria-label":"New tab",children:n.jsx(D,{name:"add",className:"size-4"})}),n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:()=>{be()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:n.jsx(D,{name:"restart",className:"size-4"})}),T?n.jsxs(Ae,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{k&&R(k,T)},title:"Open preview pane",children:[n.jsx(D,{name:"global",className:"size-3.5 shrink-0"}),n.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?n.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:n.jsx(D,{name:"close",className:"size-4"})}):null]})}):null,!h&&pe?n.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[Ue&&!s?n.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ue,t?n.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:n.jsx(D,{name:"close",className:"h-4 w-4"})}):null]}):null,!h&&v&&S&&w?n.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:z}):null,!h&&v&&!w?n.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:z}):null]}):null,n.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:ve.background},children:[n.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:qe&&k&&w?w.tabs.map(ne=>{const ze=ne.id===L;return n.jsx(wx,{directory:k,tabId:ne.id,sessionId:ne.terminalSessionId,sessionKey:`${k}::${ne.id}`,isActive:ze,isTerminalVisible:W,terminal:r,theme:ve,fontFamily:J,fontSize:u,enableTouchScroll:p,lastViewportSizeRef:Q,onInput:we,controllerRef:je},ne.id)}):null}),!V&&ae&&n.jsxs("div",{className:"absolute inset-x-0 bottom-0 border-t border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 text-xs text-foreground flex items-center justify-between gap-2",children:[n.jsx("span",{children:ae}),ue&&h&&n.jsx(Ae,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ee,disabled:fe,title:"Force kill and create fresh session",type:"button",children:"Hard restart"})]})]}),h&&v?n.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:n.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:z})}):null]})},hi=[{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"}],zx=new Set(hi.map(e=>e.id)),Ux=e=>typeof e=="string"&&zx.has(e),Zw=e=>Ux(e)?e:"changes",Bc=e=>e==="pull-requests"||e==="issues",$x=e=>e?hi:hi.filter(t=>!Bc(t.id)),ev=(e,t)=>Bc(e)?"changes":e,Kx=48,Wx=96,wt=(e,...t)=>{try{e?.(...t)}catch{}},ko=(e,t)=>{if(typeof e=="function"){const s=e();return s>0?s:t}return typeof e=="number"&&e>0?e:t},tv=(e,t)=>{const s=l.useRef(t);s.current=t;const r=t.enabled;l.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const i=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?Wx:Kx;let u=!1,d=!1,f=!1,m=null,b=!1,g=0,h=0,p=0,S=0;const y=()=>{u=!1,d=!1,f=!1,m=null},v=()=>{const R=s.current,L=m,U=b;d&&L&&(wt(L==="left"?R.onLeftProgress:R.onRightProgress,U?1:0),wt(R.onDragEnd,L,U)),y()},x=()=>{v(),d||y()},A=R=>{const L=s.current;if(L.enabled===!1){d&&m?v():y();return}if(R.touches.length!==1){d&&m?v():y();return}const U=R.touches[0],G=o.getBoundingClientRect(),$=o.clientWidth,q=!!L.leftOpen,F=!!L.rightOpen,E=T=>Zb(T,o);if(q||F){if(E(R.target)){y();return}if(q&&F){const T=U.clientX<=G.left+c;U.clientX>=G.right-c?(m="right",b=!0):T?(m="left",b=!0):(m=q?"left":"right",b=!0)}else q?(m="left",b=!0):(m="right",b=!0);S=ko(m==="left"?L.leftWidth:L.rightWidth,$),S<10&&(S=$||window.innerWidth||320),S<10&&(S=320),u=!0}else{if(E(R.target)){y();return}m=null,b=!1,S=0,u=!0}g=U.clientX,h=U.clientY,p=Date.now(),d=!1,f=!1},j=R=>{if(!u)return;if(R.touches.length!==1){x();return}const L=R.touches[0],U=L.clientX-g,G=L.clientY-h;if(!f){if(Math.abs(U)<_a&&Math.abs(G)<_a)return;if(Math.abs(G)>Math.abs(U)*Ms){y();return}if(!m){const F=s.current;m=U>0?"left":"right",S=ko(m==="left"?F.leftWidth:F.rightWidth,o.clientWidth),S<10&&(S=window.innerWidth||320)}if(m==="left"){if(!b&&U<=0){y();return}if(b&&U>=0){y();return}}else{if(!b&&U>=0){y();return}if(b&&U<=0){y();return}}f=!0,d=!0,wt(s.current.onDragStart,m)}if(!d)return;R.cancelable&&R.preventDefault();const $=s.current,q=za(m,b,U,S);wt(m==="left"?$.onLeftProgress:$.onRightProgress,q)},k=(R,L)=>{if(!u){y();return}const U=R-g,G=L-h;if(!m&&!b&&Math.abs(U)>=jr&&Math.abs(G)<=Math.abs(U)*Ms){const I=s.current;m=U>0?"left":"right",S=ko(m==="left"?I.leftWidth:I.rightWidth,o.clientWidth),S<10&&(S=window.innerWidth||320)}if(!m){y();return}const $=Math.max(1,Date.now()-p),q=s.current;if(!d){const I=Math.abs(U),M=Math.abs(G);I>=jr&&M<=I*Ms?m==="left"&&!b&&U>0?(wt(q.onLeftProgress,1),wt(q.onLeftOpen)):m==="right"&&!b&&U<0?(wt(q.onRightProgress,1),wt(q.onRightOpen)):wt(m==="left"?q.onLeftProgress:q.onRightProgress,b?1:0):wt(m==="left"?q.onLeftProgress:q.onRightProgress,b?1:0);const W=m;y(),wt(q.onDragEnd,W);return}const F=za(m,b,U,S),E=Jb({side:m,isOpenAtStart:b,dx:U,dt:$,progress:F}),T=m;wt(T==="left"?E?q.onLeftOpen:q.onLeftClose:E?q.onRightOpen:q.onRightClose),y(),wt(q.onDragEnd,T,E)},w=R=>{const L=R.changedTouches[0];if(!L){y();return}const U=L.clientX-g,G=L.clientY-h;u&&(d||Math.abs(U)>=jr&&Math.abs(G)<=Math.abs(U)*Ms)&&R.cancelable&&R.preventDefault(),k(L.clientX,L.clientY)},C=()=>{x()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",j,{passive:!1}),o.addEventListener("touchend",w,{passive:!1}),o.addEventListener("touchcancel",C,{passive:!0}),()=>{try{d&&m&&v()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",j),o.removeEventListener("touchend",w),o.removeEventListener("touchcancel",C)}},[e,r])};function nv({className:e="h-5 w-5"}){return n.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[n.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),n.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),n.jsx(D,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function qa({size:e,className:t,style:s,...r}){return n.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:t,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...s},...r,children:n.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const Gx=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:s})=>s?t:e,Hx=({activeProjectLabel:e,openDirectory:t,homeDirectory:s})=>_r(t,s)?null:e,Co=()=>Fn.filter(e=>Ko.has(e.id)).map(e=>({...Dl(e)})),qx=()=>{if(typeof window>"u")return Wo;const e=window.localStorage.getItem("openInAppId");return e&&$o(e)?e:Wo};let Ao=!1,es=!1,wn=!1,vn=0,Ws=null;const Ya=()=>{Ws&&(clearTimeout(Ws),Ws=null)},Pn=$n()((e,t)=>({selectedAppId:qx(),availableApps:Co(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Ao||typeof window>"u")return;Ao=!0;const s=(u,d=!0)=>{if(!Array.isArray(u)||u.length===0){e({availableApps:Co(),hasLoadedApps:d});return}const f=new Set(u.map(h=>h.name)),m=new Map(u.map(h=>[h.name,h.iconDataUrl??void 0])),g=Fn.filter(h=>f.has(h.appName)||Ko.has(h.id)).map(h=>({...Dl(h),iconDataUrl:m.get(h.appName)}));e({availableApps:g,hasLoadedApps:!0})},r=async u=>{if(!ds()||!Nr()||es||t().hasLoadedApps&&!u)return;const f=Fn.map(m=>m.appName);Ya(),es=!0,wn=!1,e({isScanning:!0});try{const{apps:m,success:b,hasCache:g,isCacheStale:h}=await Xi(f,u),p=b&&!g&&m.length===0&&vn<3;if(e({isCacheStale:g?h:!1}),s(m,b?!p:!1),b){if(p){const y=[800,1600,3200][vn]??3200;vn+=1,wn=!0,Ws=setTimeout(()=>{r()},y);return}vn=0,wn=!1;return}if(vn<3){const y=[1e3,3e3,7e3][vn]??7e3;vn+=1,wn=!0,Ws=setTimeout(()=>{r()},y)}}finally{es=!1,wn||e({isScanning:!1})}};r();const o=u=>{const d=u.detail,f=d&&typeof d.openInAppId=="string"&&d.openInAppId.length>0&&$o(d.openInAppId)?d.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},a=u=>{const d=u.detail;Array.isArray(d)&&(vn=3,wn=!1,e({isScanning:!1,isCacheStale:!1}),s(d))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",a),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async s=>{if(Ao||t().initialize(),!ds()||!Nr()||es||t().hasLoadedApps&&!s)return;const o=Fn.map(i=>i.appName);Ya(),s&&e({hasLoadedApps:!1}),es=!0,wn=!1,e({isScanning:!0});try{const{apps:i,hasCache:a,isCacheStale:c}=await Xi(o,s),u=new Set(i.map(b=>b.name)),d=new Map(i.map(b=>[b.name,b.iconDataUrl??void 0])),m=Fn.filter(b=>u.has(b.appName)||Ko.has(b.id)).map(b=>({...b,iconDataUrl:d.get(b.appName)}));e({availableApps:m.length>0?m:Co(),hasLoadedApps:m.length>0,isCacheStale:a?c:!1})}finally{es=!1,wn||e({isScanning:!1})}},selectApp:async s=>{$o(s)&&(e({selectedAppId:s}),typeof window<"u"&&window.localStorage.setItem("openInAppId",s),await Al({openInAppId:s}))}})),Yx="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",Vx="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"?Yx:e.id==="terminal"?Vx:void 0}),Va=({label:e,iconDataUrl:t,fallbackIconDataUrl:s})=>{const[r,o]=l.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",a=t||s;return a&&!r?n.jsx("img",{src:a,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):n.jsx("span",{className:_("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},Qx=({directory:e,className:t})=>{const s=Pn(h=>h.selectedAppId),r=Pn(h=>h.availableApps),o=Pn(h=>h.isCacheStale),i=Pn(h=>h.isScanning),a=Pn(h=>h.initialize),c=Pn(h=>h.loadInstalledApps),u=Pn(h=>h.selectApp);l.useEffect(()=>{a()},[a]);const d=ds()&&Nr(),f=l.useMemo(()=>{const h=r.find(p=>p.id===s)??r.find(p=>p.id===Wo)??r[0]??Fn[0];return No(h||Fn[0])},[r,s]);if(!d||!e||r.length===0)return null;const m=async h=>{await Gf(e,h.id,h.appName)||await Il(e,h.appName)},b=async h=>{await u(h.id),await m(h)},g=async()=>{(await fn(e)).ok&&oe.success("Path copied to clipboard")};return n.jsxs("div",{className:_("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",t),children:[n.jsx("button",{type:"button",onClick:()=>{m(f)},className:_("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",i&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:n.jsx(Va,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),n.jsxs(Gt,{children:[n.jsx(Ht,{asChild:!0,children:n.jsx("button",{type:"button",className:_("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:n.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),n.jsxs(qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g()},children:[n.jsx(D,{name:"file-copy",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy path"})]}),n.jsx(us,{}),r.map(h=>{const p=No(h);return n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{b(h)},children:[n.jsx(Va,{label:h.label,iconDataUrl:h.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl}),n.jsx("span",{className:"typography-ui-label text-foreground",children:h.label}),f.id===h.id?n.jsx(D,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},h.id)}),o?n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[n.jsx(D,{name:"refresh",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh apps"})]}):null]})]})]})},Jx="\x1B",Xx=new RegExp(`${Jx}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Zx=/https?:\/\/[^\s<>'"`]+/gi,At="__pichamber_auto_discover_preview__",ey=15e3,ty=e=>{let t="";for(let s=0;s<e.length;s+=1){const r=e.charCodeAt(s);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(t+=e[s])}return t},ny=e=>{const t=(e||"").trim();if(!t)return null;const s=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(s);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},sy=e=>{const s=e.replace(Xx,"").match(Zx);if(!s||s.length===0)return null;const r=s.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const a=new URL(i);a.port&&a.port.length>0&&o.push({raw:i,parsed:a})}catch{}if(o.length>0){const i=a=>{const{parsed:c}=a,u=c.hostname.toLowerCase(),d=u==="localhost"||u==="127.0.0.1"||u==="0.0.0.0"||u==="::1",f=c.pathname||"/",m=f.split("/").filter(Boolean).length,b=f==="/"||f==="",g=!!(c.search||c.hash);let h=0;return d&&(h+=50),b&&(h+=30),h-=Math.min(m*5,20),g&&(h-=10),h};return o.sort((a,c)=>i(c)-i(a)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},ry=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],oy=["dev","start","preview","serve"];async function iy(e,t,s){if(!e)return null;const r=cy(t);if(r)return{command:r.command,label:r.name||"Start preview",actionId:r.id,previewUrlHint:r.openUrl};if(s){const o=uy(s);if(o){const i=await dy(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 ay(e)){const o=await ly(),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 ay(e){const t=`${e}/index.html`,s=await Lr(t,e);return typeof s=="string"&&s.trim().length>0}async function ly(){try{const e=await tt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),s=typeof t?.port=="number"?t.port:null;return s&&Number.isFinite(s)?s:null}catch{return null}}function cy(e){for(const t of e){const s=`${t.name} ${t.command}`.toLowerCase();if(oy.some(o=>s.includes(o)))return t}return null}function uy(e){for(const{pattern:t}of ry)for(const s of Object.keys(e))if(t.test(s))return s;return null}async function dy(e){const t=await Lr(`${e}/package.json`,e);if(t)try{const r=JSON.parse(t),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const s=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of s){const i=await Lr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function Lr(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 s=Nl()?.files;if(s?.readFile)try{const r=await s.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await tt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function fy(e){try{const t=await Lr(`${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 hy=(e,t,s)=>new Promise(r=>{let o=!1,i=null,a=null;const c=u=>{o||(o=!0,a&&clearTimeout(a),i?.close(),r(u))};i=e.connect(t,{onEvent:u=>{(u.type==="exit"||u.type==="snapshot"&&u.status==="exited")&&c(!0)},onError:(u,d)=>{d&&c(!0)}}),o?i.close():a=setTimeout(()=>c(!1),s)});function py({projectRef:e,directory:t,allowMobile:s=!1}){const{currentTheme:r}=Sl(),{terminal:o}=Un(),{isMobile:i}=ps(),a=de(Y=>Y.terminalShell),c=de(Y=>Y.terminalLoginShells.includes(Y.terminalShell)),u=de(Y=>Y.setSettingsPage),d=de(Y=>Y.setSettingsDialogOpen),f=de(Y=>Y.setSettingsProjectsSelectedId),m=de(Y=>Y.openContextPreview),b=ye(Y=>Y.ensureDirectory),g=ye(Y=>Y.setTabLabel),h=ye(Y=>Y.setTabIconKey),p=ye(Y=>Y.setActiveTab),S=ye(Y=>Y.setConnecting),y=ye(Y=>Y.setTabSessionId),v=ye(Y=>Y.setTabPreviewUrl),x=ye(Y=>Y.projectActionRuns),A=ye(Y=>Y.setProjectActionRun),j=ye(Y=>Y.updateProjectActionRunStatus),k=ye(Y=>Y.removeProjectActionRun),[w,C]=l.useState([]),[R,L]=l.useState(null),[U,G]=l.useState(!1),$=l.useRef({}),q=l.useRef({}),F=l.useRef({}),E=l.useRef({}),T=l.useRef(new Set),I=l.useRef(0),M=e?.id??null,W=e?.path??"",K=l.useMemo(()=>M?{id:M,path:W}:null,[M,W]),O=l.useCallback(async Y=>{await ul(Y)},[]),ae=l.useCallback(async()=>{if(!K)return;const Y=I.current+1;I.current=Y,G(!0);try{const fe=await Po(K);if(I.current!==Y)return;const be=fe.actions;C(be),L(ee=>ee===At||ee&&be.some(se=>se.id===ee)?ee:null)}catch{if(I.current!==Y)return}finally{I.current===Y&&G(!1)}},[K]),X=l.useMemo(()=>Ql(t||K?.path||""),[t,K?.path]),ue=l.useMemo(()=>R?w.find(Y=>Y.id===R)??null:null,[w,R]),Ie=l.useMemo(()=>({id:At,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),V=!i,P=l.useMemo(()=>V?[Ie,...w]:w,[w,Ie,V]);l.useEffect(()=>{ae()},[ae]),l.useEffect(()=>{if(typeof window>"u")return;const Y=fe=>{const be=fe.detail;M&&(be?.projectId&&be.projectId!==M||ae())};return window.addEventListener(Qo,Y),()=>{window.removeEventListener(Qo,Y)}},[ae,M]),l.useEffect(()=>{R&&(R===At&&V||w.some(Y=>Y.id===R)||L(null))},[w,V,R]),l.useEffect(()=>{const Y=()=>{const fe=ye.getState(),be=fe.sessions,ee=fe.projectActionRuns;for(const[se,_e]of Object.entries(ee)){const J=be.get(_e.directory)?.tabs.find(ze=>ze.id===_e.tabId);if(!J||J.terminalSessionId!==_e.sessionId){k(se);continue}const ve=q.current[se]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};q.current[se]=ve;const he=P.find(ze=>ze.id===_e.actionId),Se=fe.getBuffer(_e.directory,_e.tabId).chunks;if(!he||Se.length===0)continue;const qe=Se.filter(ze=>ve.lastSeenChunkId===null||ze.id>ve.lastSeenChunkId);if(qe.length===0)continue;const Ue=qe.map(ze=>ze.data).join(""),z=`${ve.tail}${Ue}`,pe=!ve.openedUrl&&he.autoOpenUrl===!0?sy(z):null,ne=qe[qe.length-1]?.id??ve.lastSeenChunkId;if(ve.lastSeenChunkId=ne,ve.tail=z.slice(-512),pe)if(ve.openedUrl=!0,ve.openInPreview){const ze=ee[se];ze&&(v(ze.directory,ze.tabId,pe,{locked:!1,autoOpened:!1}),ze.status==="waiting-for-preview"&&j(se,"running"),window.clearTimeout(E.current[se]),delete E.current[se],m(ze.directory,pe))}else O(pe),oe.success("Opened URL from action output");q.current[se]=ve}for(const se of Object.keys(q.current))ee[se]||(delete q.current[se],window.clearTimeout(E.current[se]),delete E.current[se])};return Y(),ye.subscribe((fe,be)=>{(fe.sessions!==be.sessions||fe.buffers!==be.buffers)&&Y()})},[P,m,O,x,k,v,j]);const H=l.useCallback(async(Y,fe={})=>{if(!X)throw new Error("No active directory");const be=cn(X,Y.id);b(X);const ee=ye.getState(),se=ee.getDirectoryState(X);let _e=$.current[be]||null;const ke=_e?!!se?.tabs.some(he=>he.id===_e):!1;(!_e||!ke)&&(_e=ee.createTab(X),$.current[be]=_e),g(X,_e,`Action: ${Y.name}`),h(X,_e,Y.icon||"play"),p(X,_e),fe.revealTerminal!==!1&&de.getState().openContextPanelTab(X,{mode:"terminal"});const ve=ye.getState().getDirectoryState(X)?.tabs.find(he=>he.id===_e);return{key:be,tabId:_e,sessionId:ve?.terminalSessionId??null}},[b,X,p,h,g]),Q=l.useCallback(async Y=>{if(!s&&i)return;if(!X){oe.error("No active directory for action");return}const fe=cn(X,Y.id),be=x[fe];if(!(be&&be.status==="running")&&!T.current.has(fe)){T.current.add(fe);try{const ee=Y.id===At?await(async()=>{const[z,pe]=await Promise.all([Po({id:K?.id??"",path:X}),fy(X)]),ne=await iy(X,z.actions,pe);if(!ne)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:At,name:"Auto-discover",command:ne.command,icon:"scan-2",autoOpenUrl:!0,openUrl:ne.previewUrlHint||""}})():Y,se=ee.autoOpenUrl===!0&&(ee.openUrl||"").trim().length>0,_e=!se&&Y.id!==At,{key:ke,tabId:J,sessionId:ve}=await H(ee,{revealTerminal:_e});let he=ve;if(!he){S(X,J,!0);try{he=(await o.createSession({cwd:X,sessionId:J,shell:a,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,y(X,J,he)}finally{S(X,J,!1)}}if(!he)throw new Error("Failed to create terminal session");F.current[ke]?.(),S(X,J,!0);const Se=o.connect(he,{onEvent:z=>{z.type==="snapshot"&&(ye.getState().replaceBuffer(X,J,z.data??"",z.sequence??0),ye.getState().setConnecting(X,J,!1)),z.type==="data"&&typeof z.data=="string"&&z.data.length>0&&ye.getState().appendToBuffer(X,J,z.data,z.sequence,z.replayData),z.type==="exit"&&(ye.getState().setTabLifecycle(X,J,"exited"),ye.getState().setConnecting(X,J,!1),ye.getState().removeProjectActionRun(ke),delete q.current[ke],F.current[ke]?.(),delete F.current[ke],window.clearTimeout(E.current[ke]),delete E.current[ke])},onError:(z,pe)=>{ye.getState().setConnecting(X,J,!1),pe&&(ye.getState().setTabLifecycle(X,J,"exited"),ye.getState().setTabSessionId(X,J,null),ye.getState().removeProjectActionRun(ke))}});F.current[ke]=Se.close;const qe=ee.autoOpenUrl?ny(ee.openUrl):null;A({key:ke,directory:X,actionId:ee.id,tabId:J,sessionId:he,status:ee.id===At&&!qe?"waiting-for-preview":"running"}),window.clearTimeout(E.current[ke]),delete E.current[ke],ee.id===At&&!qe&&(E.current[ke]=window.setTimeout(()=>{const z=ye.getState(),pe=z.projectActionRuns[ke];z.updateProjectActionRunStatus(ke,"running"),pe&&(z.setActiveTab(pe.directory,pe.tabId),de.getState().openContextPanelTab(pe.directory,{mode:"terminal"})),delete E.current[ke]},ey)),q.current[ke]={lastSeenChunkId:null,openedUrl:!!qe||se,tail:"",openInPreview:ee.id===At};const Ue=ty(ee.command.trim().replace(/\r\n|\r/g,`
62
- `));await o.sendInput(he,`${Ue}\r`),qe?(v(X,J,qe,{locked:!0,autoOpened:!0}),m(X,qe),oe.success("Opened action URL")):se?(v(X,J,null,{locked:!0}),oe.error("Invalid custom URL format")):v(X,J,null,{locked:!1,autoOpened:!1})}catch(ee){k(fe),delete q.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(E.current[fe]),delete E.current[fe],oe.error(ee instanceof Error?ee.message:"Failed to run action")}finally{T.current.delete(fe)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,H,s,i,X,c,a,m,x,k,S,A,v,y,K?.id,o]),re=l.useCallback(async Y=>{const fe=cn(X,Y.id),be=x[fe];if(!be)return;j(fe,"stopping");const ee=hy(o,be.sessionId,1e3);try{await o.sendInput(be.sessionId,"")}catch{}const se=await ee;if(ye.getState().getDirectoryState(be.directory)?.tabs.find(J=>J.id===be.tabId)?.terminalSessionId===be.sessionId&&!se){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:be.sessionId})}catch{}else try{await o.close(be.sessionId)}catch{}y(be.directory,be.tabId,null)}k(fe),delete q.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(E.current[fe]),delete E.current[fe]},[X,x,k,y,o,j]),ie=l.useCallback(()=>{const Y=ue??P[0];if(!Y)return;const fe=cn(X,Y.id),be=x[fe];if(be?.status!=="stopping"){if(be){re(Y);return}Q(Y)}},[P,X,Q,x,ue,re]),ge=l.useCallback((Y,fe=!1)=>{if(L(Y.id),!fe){Q(Y);return}const be=cn(X,Y.id),ee=x[be];if(ee?.status!=="stopping"){if(ee){re(Y);return}Q(Y)}},[X,Q,x,re]),me=l.useCallback(()=>{K?.id&&(f(K.id),u("projects"),d(!0))},[d,u,f,K?.id]),Ce=ue??P[0]??null,je=Ce?x[cn(X,Ce.id)]:null,Le=ye(Y=>je?Y.sessions.get(je.directory)?.tabs.find(fe=>fe.id===je.tabId)?.previewUrl??null:null),we=!!((s||!i)&&K&&X),Re=ue??P[0]??null;return{shouldRender:we,isLoading:U,normalizedDirectory:X,resolvedSelected:Re,displayActions:P,projectActionRuns:x,selectedRunPreviewUrl:Le,handlePrimaryClick:ie,handleSelectAction:ge,openProjectActionsSettings:me,openContextPreview:m}}const Qa=({projectRef:e,directory:t,className:s,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:a,normalizedDirectory:c,resolvedSelected:u,displayActions:d,projectActionRuns:f,selectedRunPreviewUrl:m,handlePrimaryClick:b,handleSelectAction:g,openProjectActionsSettings:h,openContextPreview:p}=py({projectRef:e,directory:t,allowMobile:o});if(!i||!u)return null;const S=u.icon||"play",y=u.id===At?"scan-2":Ks[S]||"play",v=cn(c,u.id),x=f[v],A=x?.status==="stopping",j=x?.status==="waiting-for-preview",k=!!(x&&m),w=()=>{!x||!m||p(x.directory,m)},C=u.id===At;return r?n.jsxs("div",{className:"inline-flex items-center",children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",disabled:a||A,className:_("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",s),onClick:b,"aria-label":x?`Stop ${u.name}`:`Run ${u.name}`,children:A||j?n.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):x?n.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):n.jsx(D,{name:y,className:"h-5 w-5"})})}),C?n.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open preview",onClick:w,children:n.jsx(D,{name:"global",className:"h-4 w-4"})})}),n.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,n.jsxs(Gt,{children:[n.jsx(Ht,{asChild:!0,children:n.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:n.jsx(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),n.jsxs(qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[n.jsxs(ut,{className:"flex items-center gap-2",onClick:h,children:[n.jsx(D,{name:"add",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),n.jsx(us,{}),d.map(R=>{const L=R.icon||"play",U=R.id===At?"scan-2":Ks[L]||"play",G=cn(c,R.id),$=f[G],q=!!$,F=$?.status==="stopping";return n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g(R,!0)},children:[n.jsx(D,{name:U,className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground truncate",children:R.name}),F||$?.status==="waiting-for-preview"?n.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):q?n.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},R.id)})]})]})]}):n.jsxs("div",{className:_("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",s),children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:b,disabled:a||A,className:_("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":x?`Stop ${u.name}`:`Run ${u.name}`,children:n.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||j?n.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):x?n.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):n.jsx(D,{name:y,className:"h-4 w-4"})})})}),C?n.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),k?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:w,className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open preview",children:n.jsx(D,{name:"global",className:"h-4 w-4"})})}),n.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,n.jsxs(Gt,{children:[n.jsx(Ht,{asChild:!0,children:n.jsx("button",{type:"button",className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:n.jsx(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),n.jsxs(qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[n.jsxs(ut,{className:"flex items-center gap-2",onClick:h,children:[n.jsx(D,{name:"add",className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),n.jsx(us,{}),d.map(R=>{const L=R.icon||"play",U=R.id===At?"scan-2":Ks[L]||"play",G=cn(c,R.id),$=f[G],q=!!$,F=$?.status==="stopping";return n.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g(R,!0)},children:[n.jsx(D,{name:U,className:"h-4 w-4"}),n.jsx("span",{className:"typography-ui-label text-foreground truncate",children:R.name}),F||$?.status==="waiting-for-preview"?n.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):q?n.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},R.id)})]})]})]})},$t={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function Cr(e){return e?.deploymentKind==="docker"?{name:$t.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:$t.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:$t.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:$t.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:$t.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:$t.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:$t.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:$t.centos,color:"#932279"}:{name:$t.linux}:e?.serverPlatform==="darwin"?{name:$t.darwin}:{name:$t.unknown}}const my=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 gy({open:e,onOpenChange:t}){const[s,r]=l.useState(null),o=l.useCallback(async()=>{const d=Ze();try{const f=await tt("/api/version");if(!f.ok)throw new Error("Version request failed");const m=await f.json().catch(()=>null);d===Ze()&&r(m)}catch{d===Ze()&&r(null)}},[]);l.useEffect(()=>(o(),gs(()=>{o()})),[o]);const i=Cr(s),a=my(s),c=typeof s?.pichamberVersion=="string"?s.pichamberVersion:null,u=typeof window<"u"?window.location.origin:"";return n.jsxs(Gt,{open:e,onOpenChange:d=>{t(d),d&&o()},children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx(Ht,{asChild:!0,children:n.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(xs,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[n.jsx(D,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),n.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),n.jsx(Ge,{children:n.jsx("p",{children:"Connected server information"})})]}),n.jsxs(qt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-4",children:[n.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[n.jsx(D,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),n.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:a})]}),c?n.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),n.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:n.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[n.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),n.jsxs("button",{type:"button",className:"ml-auto flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:`Copy ${u}`,"aria-label":"Copy server address",onClick:()=>{fn(u).then(d=>{d.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[n.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:u}),n.jsx(D,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const by=({isMobile:e})=>{const s=Un().github??null,r=Ur(i=>i.refresh),o=Wp();return l.useEffect(()=>{!s||e||r(s)},[s,e,r]),e||!s||!o?null:n.jsxs("span",{className:_(xs,"app-region-no-drag inline-flex w-auto cursor-default gap-1.5 px-2"),title:`${o} via GitHub CLI`,"aria-label":`Signed in to GitHub as ${o} via GitHub CLI`,children:[n.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),n.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},xy=l.memo(function({isDesktopApp:t,currentInstanceLabel:s,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:u,shortcutLabel:d,remoteUpdateInfo:f,remoteUpdateChecking:m,remoteUpdateError:b,onOpenRemoteUpdate:g}){return n.jsxs(Gt,{open:a,onOpenChange:h=>{c(h),h&&u()},children:[n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx(Ht,{asChild:!0,children:n.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${s})`:"Open services, usage and MCP",className:_(xs,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[n.jsx(D,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?n.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),n.jsx(Ge,{children:n.jsx("p",{children:`Current instance: ${s} (${d("toggle_services_menu")})`})})]}),n.jsx(qt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?n.jsxs("div",{children:[o?null:n.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),n.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:m?"Looking for updates...":b||"This instance is up to date."})]}),f?.available?n.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:g,children:"Update"}):null]})}),n.jsx(ff,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),yy=({action:e,onClose:t,sessionTitle:s,onConfirm:r})=>n.jsx(en,{open:e!==null,onOpenChange:o=>{o||t()},children:n.jsxs(tn,{showCloseButton:!1,className:"max-w-sm gap-5",children:[n.jsxs(zn,{children:[n.jsx(mn,{children:e==="delete"?"Delete session?":"Archive session?"}),n.jsx(Cn,{children:e==="delete"?`"${s}" will be permanently deleted.`:`"${s}" will be archived.`})]}),n.jsxs(ms,{children:[n.jsx(Ae,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),n.jsx(Ae,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),wy=e=>{const t=e.trim();if(!t)return"";const s=t.split(/\s+/).filter(Boolean);if(s.length>=2){const r=s[0],o=s[1].slice(0,3),i=`${r} ${o}`.trim();return s.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},Ps=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},vy=l.lazy(()=>ht(()=>import("./SessionSwitcherDropdown-B9_0JwY7.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),sv=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:s,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:a=!1})=>{Wt("ui.header.render");const c=de(B=>B.setSessionSwitcherOpen),u=de(B=>B.toggleSidebar),d=de(B=>B.isSidebarOpen),f=de(B=>B.activeMainTab),m=de(B=>B.setActiveMainTab),b=de(B=>B.shortcutOverrides);de(B=>B.timeFormatPreference),Un();const g=Fe(B=>!!B.newSessionDraft?.open),h=Fe(B=>B.currentSessionId),p=yl(h??""),S=hf(h),y=l.useMemo(()=>{if(!S)return null;const B=S;return{title:S.title??null,directory:B.directory??null,created:S.time?.created??null,slug:B.slug??null,shareUrl:S.share?.url??null,parentId:S.parentID??null,messageCount:typeof S.messageCount=="number"?S.messageCount:null}},[S]),v=ct(Ro(B=>{if(!B.activeProjectId)return null;const le=B.projects.find(xe=>xe.id===B.activeProjectId);return le?{id:le.id,path:le.path,label:le.label}:null})),x=fs(B=>B.homeDirectory),A=l.useMemo(()=>v?pf(v):null,[v]),{isMobile:j}=ps(),{enabled:k}=bi(),w=!!(k&&i&&o!==void 0),C=l.useMemo(()=>[...$x(a)],[a]),[R,L]=l.useState(!1),U=l.useRef(null),[G,$]=l.useState(()=>typeof window>"u"?!1:ds()),q=l.useMemo(()=>El(),[]),F=mf(),[E,T]=l.useState(!1),I=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=jl(),W=l.useMemo(()=>{if(typeof window>"u")return null;const B=window.__PICHAMBER_MACOS_MAJOR__;if(typeof B=="number"&&Number.isFinite(B)&&B>0)return B;if(typeof navigator>"u")return null;const le=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!le)return null;const xe=Number.parseInt(le[1],10),$e=Number.parseInt(le[2],10);return Number.isNaN(xe)?null:xe===10?$e:xe},[]);Te.useEffect(()=>{typeof window>"u"||$(ds())},[]);const K=de(B=>B.isSessionSwitcherOpen),[O,ae]=l.useState(!1),[X,ue]=l.useState("Local"),[Ie,V]=l.useState(!0),[P,H]=l.useState(()=>Cr(null)),[Q,re]=l.useState(!1),[ie,ge]=l.useState(null),[me,Ce]=l.useState(!1),[je,Le]=l.useState(null),we=l.useRef(0),Re=l.useMemo(()=>wy(X),[X]),Y=l.useCallback(async()=>{if(typeof window>"u"||!G)return;const B=Ze(),le=()=>Ze()===B;try{const xe=await tt("/api/version");if(!le())return;const $e=xe.ok?await xe.json().catch(()=>null):null;if(!le())return;if(H(Cr($e)),Nr()){ue("Local"),V(!0);return}V(!1);const ft=await Hf();if(!le())return;const Qe=qf(),Ct=Yf([Vf(Qe),...ft.hosts]);if(Ct.id===Qf){ue("Local"),V(!0);return}ue(Jf(Ct.label.trim()||"Instance"))}catch{le()&&(ue("Local"),V(!0),H(Cr(null)))}},[G]);Te.useEffect(()=>(Y(),gs(()=>{we.current+=1,ge(null),Le(null),Ce(!1),re(!1),Y()})),[Y]);const fe=l.useCallback(async()=>{const B=we.current+1;we.current=B;const le=Ze(),xe=()=>we.current===B&&Ze()===le;if(Ie){ge(null),Le(null);return}Ce(!0),Le(null);try{const $e=new URLSearchParams({appType:"web",instanceMode:"remote"}),ft=await tt(`/api/pi/update-check?${$e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ft.ok)throw new Error(`Server responded with ${ft.status}`);const Qe=await ft.json();if(!xe())return;ge({available:Qe.available??!1,version:Qe.version,currentVersion:Qe.currentVersion??"unknown",body:Qe.body,nextSuggestedCheckInSec:typeof Qe.nextSuggestedCheckInSec=="number"?Qe.nextSuggestedCheckInSec:void 0,packageManager:Qe.packageManager,updateCommand:Qe.updateCommand,channel:Qe.channel==="rc"?"rc":"stable"})}catch($e){if(!xe())return;ge(null),Le($e instanceof Error?$e.message:"Failed to check remote instance updates")}finally{xe()&&Ce(!1)}},[Ie]);l.useEffect(()=>jp(()=>{Ie||fe()}),[fe,Ie]),l.useEffect(()=>{we.current+=1,ge(null),Le(null),Ce(!1),re(!1)},[Ie,X]),l.useEffect(()=>{if(!G||Ie)return;const B=3e3,le=3600*1e3;let xe=!1,$e=null;const ft=Qe=>{$e=window.setTimeout(()=>{if(xe||typeof document<"u"&&document.visibilityState!=="visible"){ft(le);return}fe().finally(()=>{xe||ft(le)})},Qe)};return ft(B),()=>{xe=!0,$e!==null&&window.clearTimeout($e)}},[fe,Ie,X,G]);const be=l.useCallback(()=>{if(ie?.available){re(!0);return}fe()},[fe,ie?.available]),ee=h?y??null:null,se=l.useRef(null),[_e,ke]=l.useState(0);l.useEffect(()=>{if(!h){se.current&&(se.current=null,ke($e=>$e+1));return}if(ee){se.current={sessionId:h,session:ee,expiresAt:Date.now()+2e3};return}const B=se.current;if(!B||B.sessionId!==h)return;const le=B.expiresAt-Date.now();if(le<=0){se.current=null,ke($e=>$e+1);return}const xe=window.setTimeout(()=>{se.current?.sessionId===h&&(se.current=null),ke($e=>$e+1)},le);return()=>{window.clearTimeout(xe)}},[h,ee]);const J=(()=>{if(ee)return ee;if(!h)return null;const B=se.current;return B&&B.sessionId===h&&B.expiresAt>Date.now()?B.session:null})(),ve=l.useMemo(()=>{const B=typeof J?.directory=="string"?J.directory:"";return Ps(B||"")},[J?.directory]),he=Fe(B=>B.newSessionDraft?.open?Ps(B.newSessionDraft.directoryOverride??""):""),Se=l.useMemo(()=>Gx({sessionDirectory:ve,draftDirectory:he,isNewSessionDraftOpen:g}),[he,g,ve]),Ue=Lo(Se||null),z=l.useMemo(()=>Hx({activeProjectLabel:A,openDirectory:Se,homeDirectory:x}),[A,x,Se]),pe=!!(z||Ue),ne=l.useMemo(()=>h?dn(J,"Untitled session"):z??"PiChamber",[J,h,z]),ze=gf(),st=Fe(B=>B.updateSessionTitle),pt=Fe(B=>B.archiveSessions),Xe=Fe(B=>B.deleteSessions),[Yt,mt]=l.useState(!1),[Nt,nn]=l.useState(!1),Je=l.useRef(!1),[Mt,Ft]=l.useState(""),[vt,Ee]=l.useState(null),Ve=l.useRef(null);l.useEffect(()=>{Je.current=!1,nn(!1),mt(!1),Ft(""),Ee(null)},[h]);const Ne=l.useCallback(()=>{h&&(Ft(J?.title?.trim()||ne),mt(!0))},[J?.title,h,ne]),Pe=l.useCallback(async()=>{if(!h)return;const B=Mt.trim();B&&B!==J?.title?.trim()&&await st(h,B),mt(!1)},[J?.title,h,Mt,st]);l.useEffect(()=>{if(!Yt)return;const B=le=>{const xe=le.target;(!xe||!Ve.current?.contains(xe))&&Pe()};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[Yt,Pe]);const He=l.useCallback(()=>{h&&fn(h).then(B=>{oe[B.ok?"success":"error"](B.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[h]),dt=l.useCallback(async()=>{if(!h||!Se){oe.error("Nothing to export");return}try{await ze.syncSession(h)}catch{oe.error("Failed to load the complete session history");return}const B=[];if(B.length===0){oe.error("Nothing to export");return}const le=Ec(B,J?.title??null),xe=Pc(J?.title??null);await Rc(le,xe)||Dc(le,xe),oe.success("Session exported")},[J?.title,h,Se,ze]);p?.type==="busy"||p?.type;const sn=l.useCallback(async()=>{if(!h||!vt)return;const B=bf(),le=[h];for(let Qe=0;Qe<le.length;Qe+=1){const Ct=le[Qe];for(const Dt of B)Dt.parentID===Ct&&!le.includes(Dt.id)&&le.push(Dt.id)}const xe=vt;if(Ee(null),(xe==="archive"?await pt(le):await Xe(le)).failedIds.length>0){oe.error(xe==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(xe==="archive"?"Session archived":"Session deleted")},[pt,h,Xe,vt]),Lt=de(B=>B.isArchivePageOpen),Ot=l.useMemo(()=>Lt?{title:"Archive",subtitle:null}:null,[Lt]),Ye=l.useMemo(()=>Ps(Se||v?.path||""),[v?.path,Se]),rn=l.useCallback(()=>{Ye&&fn(Ye).then(B=>{oe[B.ok?"success":"error"](B.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[Ye]),An=l.useCallback(()=>{Ue&&fn(Ue).then(B=>{oe[B.ok?"success":"error"](B.ok?"Branch name copied":"Failed to copy branch name")}).catch(()=>oe.error("Failed to copy branch name"))},[Ue]),It=l.useMemo(()=>v?{id:v.id,path:v.path}:null,[v]),Kn=l.useRef(null);l.useEffect(()=>{!It||!Ye||(Kn.current={projectRef:It,directory:Ye})},[Ye,It]);const bt=l.useMemo(()=>It&&Ye?{projectRef:It,directory:Ye}:Kn.current,[Ye,It]),rt=l.useCallback(()=>{if(typeof document>"u")return;const B=document.activeElement;if(!B)return;const le=B.tagName;(le==="INPUT"||le==="TEXTAREA"||le==="SELECT"||B.isContentEditable)&&B.blur()},[]),Vt=l.useCallback(()=>{if(j){rt(),c(!K);return}u()},[rt,j,K,c,u]),Bt=l.useCallback(()=>{zs("desktop_open_draft_mini_chat_window",{directory:Ps(Se||v?.path||""),projectId:v?.id??null,apiBaseUrl:Uo(),clientToken:zo()}).catch(B=>{console.warn("[header] failed to open draft mini chat window",B)})},[v?.id,v?.path,Se]),gn=l.useCallback(()=>{if(g){Bt();return}h&&zs("desktop_open_session_mini_chat_window",{sessionId:h,directory:Ps(Se||v?.path||""),apiBaseUrl:Uo(),clientToken:zo()}).catch(B=>{console.warn("[header] failed to open session mini chat window",B)})},[v?.path,h,Bt,g,Se]),on=xs,xt=Zp,St=l.useMemo(()=>s?"sessions":w?r&&o?o:null:r?"git":f,[f,w,s,r,o]),Et=l.useCallback(()=>{s&&e&&e(),r&&t&&t(),!e&&K&&c(!1)},[K,s,e,t,r,c]),Wn=l.useCallback(()=>{e?.()},[e]),Nn=l.useCallback(()=>{t?.()},[t]),In=l.useMemo(()=>G&&I&&!E?"5.5rem":F?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!G||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[G,E,I,F,M]);Te.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",In)},[In]);const jt=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",an=d?"0px":G&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":k?"2.75rem":"2.5rem";Te.useEffect(()=>{if(!G||!I){T(!1);return}let B=!1;const le=async()=>{try{const $e=await zs("desktop_is_window_fullscreen");B||T($e===!0)}catch{B||T(!1)}},xe=()=>{le()};return le(),window.addEventListener("pichamber:window-resized",xe),()=>{B=!0,window.removeEventListener("pichamber:window-resized",xe)}},[G,I]);const nt=l.useMemo(()=>!G||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[G,I,W]),ln=l.useMemo(()=>{if(!(G&&!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))"}},[G,M]),yt=l.useCallback(()=>{if(typeof document>"u")return;const B=U.current?.getBoundingClientRect().height;if(B){const le=`${B}px`,xe=document.documentElement.style;xe.getPropertyValue("--oc-header-height")!==le&&xe.setProperty("--oc-header-height",le)}},[]);Te.useEffect(()=>{if(typeof window>"u")return;yt();const B=U.current;if(!B||typeof ResizeObserver>"u")return()=>{};let le=0;const xe=()=>{le||(le=requestAnimationFrame(()=>{le=0,yt()}))},$e=new ResizeObserver(xe);return $e.observe(B),window.addEventListener("resize",xe),window.addEventListener("orientationchange",xe),()=>{le&&cancelAnimationFrame(le),$e.disconnect(),window.removeEventListener("resize",xe),window.removeEventListener("orientationchange",xe)}},[yt]),Te.useEffect(()=>{yt()},[yt,j,nt]);const kt=l.useCallback(async B=>{const le=B.target;le.closest(".app-region-no-drag")||le.closest("button, a, input, select, textarea")||B.button===0&&G&&await xf()},[G]),ot=l.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]),En=l.useCallback(B=>yi(Ar(B,b)),[b]);Te.useEffect(()=>{!j&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&m("chat")},[f,j,m]),Te.useEffect(()=>{const B=le=>{if(Xf(le)&&!le.shiftKey&&!le.altKey){const xe=parseInt(le.key,10);xe>=1&&xe<=ot.length&&(le.preventDefault(),j&&(rt(),Et()),m(ot[xe-1].id))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[rt,Et,j,m,ot]),Te.useEffect(()=>{const B=le=>{const xe=Ar("toggle_services_menu",b);if(Zf(le,xe)){le.preventDefault(),O?ae(!1):(ae(!0),Y());return}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[b,O,Y]);const it=B=>{const le=f===B.id,xe=B.icon==="diff",$e=xe?null:B.icon,ft=B.id==="chat",Qe=Dt=>xe?n.jsx(qa,{size:Dt}):$e?n.jsx(D,{name:$e,className:`h-${Dt/4} w-${Dt/4}`}):null,Ct=n.jsxs("button",{type:"button",onClick:()=>m(B.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",le?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",ft&&!j&&"min-w-[100px] justify-center"),"aria-label":B.label,"aria-selected":le,role:"tab",children:[j?Qe(20):n.jsxs(n.Fragment,{children:[Qe(16),n.jsx("span",{className:"header-tab-label",children:B.label})]}),B.badge!==void 0&&B.badge>0&&n.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:B.badge})]});return n.jsx(l.Fragment,{children:Ct},B.id)},Gn=n.jsxs(n.Fragment,{children:[n.jsx(Qx,{directory:Ye,className:"mr-1"}),G?n.jsx(xy,{isDesktopApp:G,currentInstanceLabel:X,compactCurrentInstanceLabel:Re,currentInstanceIsLocal:Ie,currentInstanceIcon:P,isDesktopServicesOpen:O,setIsDesktopServicesOpen:ae,refreshCurrentInstanceLabel:Y,shortcutLabel:En,remoteUpdateInfo:ie,remoteUpdateChecking:me,remoteUpdateError:je,onOpenRemoteUpdate:be}):n.jsx(gy,{open:O,onOpenChange:ae}),n.jsx(by,{isMobile:j})]}),Hn=q&&(g||!!h),vs=()=>n.jsxs("div",{onMouseDown:kt,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",nt),style:ln,role:"tablist","aria-label":"Main navigation",children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:jt}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:an}}),n.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ot?n.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[n.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:Ot.title}),Ot.subtitle?n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),n.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-subtle-foreground max-w-full",children:Ot.subtitle})]}):null]}):n.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:n.jsx(l.Suspense,{fallback:n.jsx("button",{type:"button",className:on,"aria-label":"Open session switcher",children:n.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})}),children:n.jsx(vy,{align:"start",children:n.jsx("button",{type:"button",className:on,"aria-label":"Open session switcher",children:n.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})})})}),n.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Yt?n.jsxs("form",{ref:Ve,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:B=>{B.preventDefault(),Pe()},children:[n.jsx("input",{value:Mt,onChange:B=>Ft(B.target.value),autoFocus:!0,onKeyDown:B=>{B.stopPropagation(),B.key==="Escape"&&mt(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),n.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(D,{name:"check",className:"size-4"})}),n.jsx("button",{type:"button",onClick:()=>mt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:n.jsx(D,{name:"close",className:"size-4"})})]}):n.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:g?"New session":ne}),pe?n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),n.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-subtle-foreground",children:[z?n.jsx("span",{className:"truncate",children:z}):null,Ue?n.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[n.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-subtle-foreground"}),n.jsx("span",{className:"truncate",children:Ue})]}):null]})]}):null]}),n.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:h&&!g&&!Yt?n.jsxs(Gt,{open:Nt,onOpenChange:nn,onOpenChangeComplete:B=>{!B&&Je.current&&(Je.current=!1,Ne())},children:[n.jsx(Ht,{asChild:!0,children:n.jsx(Ae,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:n.jsx(D,{name:"more",className:"size-4"})})}),n.jsxs(qt,{align:"end",className:"min-w-[190px]",children:[n.jsxs(ut,{onClick:()=>{Je.current=!0},children:[n.jsx(D,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),n.jsxs(ut,{onClick:He,children:[n.jsx(D,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),n.jsxs(ut,{onClick:rn,disabled:!Ye,children:[n.jsx(D,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),Ue?n.jsxs(ut,{onClick:An,children:[n.jsx(D,{name:"git-branch",className:"mr-2 size-4"}),"Copy branch name"]}):null,n.jsx(us,{}),n.jsxs(ut,{onClick:()=>{dt()},children:[n.jsx(D,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),n.jsx(us,{}),n.jsxs(ut,{onClick:()=>Ee("archive"),children:[n.jsx(D,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),n.jsxs(ut,{className:"text-destructive focus:text-destructive",onClick:()=>Ee("delete"),children:[n.jsx(D,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),ot.length>0&&n.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:ot.map(B=>it(B))}),n.jsx("div",{className:"flex-1"}),n.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[n.jsx(Zl,{}),bt?n.jsx(Qa,{projectRef:bt.projectRef,directory:bt.directory,className:"mr-1"}):null,n.jsx(em,{visible:Hn,title:g?"New Mini Chat window":"Open session in Mini Chat",ariaLabel:g?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:gn,className:_(on,"mr-1"),Icon:"picture-in-picture-2"}),Gn,n.jsx(yf,{visible:M})]})]})]}),Dn=()=>n.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[k&&n.jsxs(n.Fragment,{children:[n.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:jt}}),n.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:an}})]}),!k&&n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?n.jsx("button",{type:"button",onClick:Wn,className:_(xt,St==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":s?"Close sessions":"Open sessions",children:n.jsx(D,{name:"layout-left",className:"h-5 w-5"})}):K?n.jsx("button",{type:"button",onClick:()=>c(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:n.jsx(D,{name:"arrow-left-s",className:"h-5 w-5"})}):n.jsx("button",{type:"button",onClick:Vt,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:n.jsx(D,{name:"play-list-add",className:"h-5 w-5"})}),!e&&K&&n.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!K||!!e)&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!w&&n.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:n.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:n.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:ot.map(B=>{const le=f===B.id,xe=B.icon==="diff",$e=xe?null:B.icon;return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsxs("button",{type:"button",onClick:()=>{j&&(rt(),Et()),m(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(xt,"relative rounded-lg",St===B.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[xe?n.jsx(qa,{className:"h-5 w-5"}):$e?n.jsx(D,{name:$e,className:"h-5 w-5"}):null,B.badge!==void 0&&B.badge>0&&n.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:B.badge}),B.showDot&&n.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),n.jsx(Ge,{children:n.jsx("p",{children:B.label})})]},B.id)})})})})}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:C.map(B=>{const le=r&&o===B.id;return n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:()=>{j&&(rt(),Et()),L(!1),i?.(B.id)},"aria-label":B.label,"aria-selected":le,role:"tab",className:_(xt,"relative h-11 w-11 rounded-lg",le&&"bg-interactive-selection text-interactive-selection-foreground"),children:n.jsx(D,{name:B.icon,className:"h-5 w-5"})})}),n.jsx(Ge,{children:n.jsx("p",{children:B.label})})]},B.id)})}),n.jsx(Xp,{open:R,onOpenChange:L,currentSessionId:h,effectiveDirectory:Se||null,isNewSessionDraftOpen:g})]}),bt&&n.jsx(Qa,{projectRef:bt.projectRef,directory:bt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!w?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:Nn,className:_(xt,"relative",St==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:n.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),n.jsx(Ge,{children:n.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Ss=_("header-safe-area relative z-10 bg-background",j&&"border-b border-border/50");return n.jsxs(n.Fragment,{children:[n.jsx("header",{ref:U,className:Ss,style:{"--padding-scale":"1"},children:j?Dn():vs()}),n.jsx(yy,{action:vt,onClose:()=>Ee(null),sessionTitle:ne,onConfirm:()=>{sn()}}),n.jsx(Wl,{open:Q,onOpenChange:re,info:ie,downloading:!1,downloaded:!1,progress:null,error:je,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ja="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",Sy="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",rv=()=>{const e=de(g=>g.isSidebarOpen),t=de(g=>g.toggleSidebar),s=de(g=>g.shortcutOverrides),r=l.useRef(null),o=l.useRef(null),i=yi(Ar("toggle_sidebar",s)),a=jl(),{enabled:c}=bi(),u=!e,d=a,f=u||d,m=d,b=l.useCallback(()=>{zs("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return l.useEffect(()=>{if(typeof document>"u")return;const g=x=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(x)}px`)},h=x=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(x)}px`)};if(!m)return;const p=o.current,S=r.current;if(!p||!S){g(0),h(0);return}const y=()=>{const x=Math.max(p.getBoundingClientRect().width,p.scrollWidth);g(x),h(S.getBoundingClientRect().width)};if(y(),typeof ResizeObserver>"u")return;const v=new ResizeObserver(y);return v.observe(p),v.observe(S),()=>{v.disconnect()}},[m]),f?n.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:n.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[d?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:b,"aria-label":"Open PiChamber menu",className:_(Ja,"shrink-0"),children:n.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),n.jsx(Ge,{children:n.jsx("p",{children:"PiChamber menu"})})]}):null,u?n.jsxs(Ke,{children:[n.jsx(We,{asChild:!0,children:n.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?Sy:Ja,"shrink-0"),children:n.jsx(D,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),n.jsx(Ge,{children:n.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},Xa=200,jy="cubic-bezier(0.22, 1, 0.36, 1)",ov=e=>{const t=l.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[s,r]=l.useState(e),[o,i]=l.useState(e);return l.useLayoutEffect(()=>{if(t){i(e),r(e);return}if(e){i(!0),r(!1);let c=0;const u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const a=window.setTimeout(()=>i(!1),Xa);return()=>window.clearTimeout(a)},[e,t]),{slidIn:s,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${Xa}ms ${jy}`}},iv=()=>{Rl()},av=e=>{Fe.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),de.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ye.getState().clearAll(),Rl(),fs.getState().resetForRuntimeSwitch(),wf.getState().resetForRuntimeSwitch(),vf.getState().resetForRuntimeSwitch(),Sf(),eh(),th(),Nf(),jf.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ct.getState().resetForRuntimeSwitch(),kf(),Cf(),gh.getState().reset(),nh.getState().resetForRuntimeSwitch(),pl.getState().resetForRuntimeSwitch(e.runtimeKey),Oo.getState().resetForRuntimeSwitch(e.runtimeKey),sh(),Bn.getState().resetForRuntimeSwitch(e.runtimeKey),Af.getState().resetForRuntimeSwitch(),Zt.getState().resetForRuntimeSwitch(),gt.getState().resetForRuntimeSwitch(e.runtimeKey),rh.getState().resetForRuntimeSwitch(e.runtimeKey),Fe.getState().restoreForRuntimeSwitch(e.runtimeKey),de.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=de.getState();Go({sessionId:Fe.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{tr as $,Dw as A,wp as B,uw as C,_a as D,nw as E,Wy as F,vi as G,sv as H,Xy as I,yp as J,Yl as K,$s as L,Xl as M,Yy as N,Ky as O,zp as P,bp as Q,Sp as R,Yw as S,Xw as T,Wl as U,tw as V,_y as W,ql as X,nr as Y,rw as Z,vp as _,Xp as a,Hw as a$,Hl as a0,ew as a1,Hy as a2,gp as a3,aw as a4,ow as a5,Ur as a6,iw as a7,lw as a8,sw as a9,Iw as aA,pw as aB,Aw as aC,Cw as aD,jw as aE,Wr as aF,Gr as aG,Hr as aH,On as aI,vc as aJ,Hp as aK,qp as aL,la as aM,nv as aN,Ah as aO,Pn as aP,Sn as aQ,Zt as aR,wc as aS,cc as aT,Xs as aU,lc as aV,Gy as aW,Oy as aX,Lw as aY,Rw as aZ,Ow as a_,Vy as aa,Qy as ab,Jy as ac,kw as ad,Fp as ae,Zy as af,Gl as ag,Xh as ah,xp as ai,zy as aj,Zh as ak,Qh as al,mw as am,fw as an,dw as ao,hw as ap,Sw as aq,vw as ar,bw as as,gw as at,xw as au,Gp as av,ww as aw,yw as ax,Nw as ay,Ew as az,Ms as b,qw as b0,Wp as b1,zw as b2,Bw as b3,Tw as b4,_w as b5,$w as b6,Kw as b7,Ww as b8,Gw as b9,Uw as ba,Fw as bb,Pw as bc,ri as bd,va as be,Tn as bf,Rs as bg,ws as bh,og as bi,ys as bj,Mw as bk,Qb as c,Vw as d,jr as e,$x as f,Qw as g,vx as h,Zb as i,Zw as j,Bc as k,ov as l,tv as m,rv as n,iv as o,av as p,Uy as q,ev as r,Jw as s,$y as t,Qp as u,By as v,Ly as w,qy as x,mp as y,cw as z};