@pi-chamber/web 0.1.8 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.test.js +48 -0
- package/bin/lib/DOCUMENTATION.md +2 -2
- package/bin/lib/cli-args.js +38 -11
- package/bin/lib/cli-startup.js +60 -13
- package/bin/lib/commands-startup.js +20 -5
- package/bin/lib/commands-update.js +91 -34
- package/bin/lib/commands-update.test.js +57 -42
- package/dist/assets/CommitSection-LewzHfDH.js +1 -0
- package/dist/assets/DiagramEditor-BOIJVnh3.js +1 -0
- package/dist/assets/DiagramView-CdNHezna.js +1 -0
- package/dist/assets/{DiffView-BHS4m_K7.js → DiffView-Cmw-RHIH.js} +2 -2
- package/dist/assets/{FilesView-DmZcdwl-.js → FilesView-BODbL0Xm.js} +6 -6
- package/dist/assets/GitView-DqYF-n_h.js +6 -0
- package/dist/assets/JsonTreeView-DzEjA1ht.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-B07lHhBl.js → MarkdownRendererImpl-Bfq0bOSM.js} +2 -2
- package/dist/assets/PatchDiff-CtVByTC4.js +1 -0
- package/dist/assets/{PierreDiffViewer-Bo0_BCT7.js → PierreDiffViewer-Cwoewmiu.js} +2 -2
- package/dist/assets/{useAppFontEffects-DXASDavv.js → SessionSwitcherDropdown-DNjCJjzF.js} +97 -97
- package/dist/assets/{SettingsView-CtsS4oDI.js → SettingsView-BtLvHlj4.js} +3 -3
- package/dist/assets/SettingsWindow-CPd7JmJs.js +1 -0
- package/dist/assets/{ToolOutputDialog-iZG2ey4T.js → ToolOutputDialog-CFFC5eI-.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-yFq1DKSA.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-DD5IznIe.js → VirtualizedFileDiff-CC5lTPJS.js} +4 -4
- package/dist/assets/collapsible-D_555Hw_.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-BcVuV0Ic.js +3 -0
- package/dist/assets/contextFileOpenGuard-BygvjHuE.js +1 -0
- package/dist/assets/index-C9CLY-is.js +1 -0
- package/dist/assets/index-DQr8-8RF.js +8 -0
- package/dist/assets/index-DYrJXRkU.css +1 -0
- package/dist/assets/isDiffPlainText-Bher0UxW.js +1 -0
- package/dist/assets/isFilePlainText-EIViqOlI.js +1 -0
- package/dist/assets/main-1bIgjP48.js +2 -0
- package/dist/assets/main-JDtt2bQS.js +133 -0
- package/dist/assets/{markdownCore-BULtt6Xa.js → markdownCore-Bm4FxtK1.js} +2 -2
- package/dist/assets/miniChat-B7kKqKHH.js +2 -0
- package/dist/assets/mobile-DZPRce5z.js +2 -0
- package/dist/assets/renderElectronMiniChatApp-Dq0GdThJ.js +1 -0
- package/dist/assets/renderMobileApp-DlKnjObC.js +23 -0
- package/dist/assets/runtimeSurface-B6sKTjo7.js +1 -0
- package/dist/assets/{useInlineCommentController-KJFe98HG.js → useInlineCommentController-CSR_Ju0a.js} +2 -2
- package/dist/assets/usePanelSlide-BkonU4LS.js +47 -0
- package/dist/assets/{useWindowTitle-BcwmWC0M.js → useWindowTitle-rt_8xbd9.js} +3 -3
- package/dist/assets/{vendor-codemirror-language-data-CFVH0pe8.js → vendor-codemirror-language-data-Be-zDX0u.js} +2 -2
- package/dist/assets/{web-components-CNPQSzpa.js → web-components-DgFD1Jms.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/package-manager.js +44 -65
- package/server/lib/package-manager.test.js +27 -0
- package/server/lib/pi/routes.js +6 -0
- package/server/lib/pi/routes.test.js +32 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-daemon/session-daemon.js +11 -4
- package/server/lib/pi/session-daemon/session-daemon.test.js +24 -0
- package/dist/assets/CommitSection-DGGArAb2.js +0 -1
- package/dist/assets/DiagramEditor-ig5nYV6t.js +0 -1
- package/dist/assets/DiagramView-8Qr6pwwI.js +0 -1
- package/dist/assets/GitView-gfHxmc66.js +0 -6
- package/dist/assets/JsonTreeView-DbFqka3P.js +0 -1
- package/dist/assets/PatchDiff-DD9pAs47.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-t7WZX24f.js +0 -1
- package/dist/assets/SettingsWindow-DIRGn3eQ.js +0 -1
- package/dist/assets/TerminalView-DUwO1CCY.js +0 -46
- package/dist/assets/ToolPartDiffPreview-FTexlZSz.js +0 -8
- package/dist/assets/collapsible-ODWWxk4f.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DdXkLFAD.js +0 -3
- package/dist/assets/contextFileOpenGuard-uC4OerzL.js +0 -1
- package/dist/assets/index-CRB7i1S2.js +0 -8
- package/dist/assets/index-C_Mo87uS.css +0 -1
- package/dist/assets/index-MSKFS67y.js +0 -1
- package/dist/assets/isDiffPlainText-CeCQwHA2.js +0 -1
- package/dist/assets/isFilePlainText-BcfhE9FH.js +0 -1
- package/dist/assets/main-CPygRDd9.js +0 -134
- package/dist/assets/main-DZg4qzOe.js +0 -2
- package/dist/assets/miniChat-BFotDgpO.js +0 -2
- package/dist/assets/mobile-3LLzhN5Q.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-DGmmT9Wf.js +0 -1
- package/dist/assets/renderMobileApp-Dd8P9hvM.js +0 -23
- package/dist/assets/runtimeSurface-Cnqjhb6Y.js +0 -1
- package/dist/assets/useOpenInAppsStore-DHAeT9zx.js +0 -1
- /package/dist/assets/{TerminalView-BV3KOtdA.css → usePanelSlide-BV3KOtdA.css} +0 -0
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-MSKFS67y.js","assets/useAppFontEffects-DXASDavv.js","assets/index-CRB7i1S2.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-C_Mo87uS.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DwfTg5wD.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-Cnqjhb6Y.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BuDklWi8.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-Wdz6Qsow.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-pXtfpqbT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-CrbeaEAU.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-3xMyV7a2.js","assets/vendor-codemirror-lang-json-BTvAjwkJ.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-C4jEScp7.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-C1Svvdey.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-BloD9GN-.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-CFVH0pe8.js","assets/vendor-codemirror-lang-python-CR2g6ukK.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-Bzf12ODH.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-dWA7qvjr.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/computeVirtualFileMetrics-DdXkLFAD.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-BcfhE9FH.js","assets/isDiffPlainText-CeCQwHA2.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-B-cPXHXW.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as Ms}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ue,j as t,R as i}from"./vendor-react-DYyjh7Q0.js";import{bz as ti,bA as Ts,bB as il,av as al,o as ll,D as os,C as is,G as us,I as k,a$ as ps,bC as Vr,f as F,B as Ee,aE as nr,T as et,y as tt,z as st,bD as si,bE as cl,bF as dl,bG as ul,bH as fl,m as Me,bI as hl,bJ as Yr,bK as ml,bL as pl,bM as Jr,bN as gl,bO as xl,bP as bl,bQ as yl,aH as vl,bR as wl,t as oe,az as as,aA as ls,aB as Xt,a1 as Ls,bS as Sl,bT as jl,bU as kl,bV as Cl,bW as Zr,h as Vt,bX as Nl,bY as Il,bZ as Dl,b_ as Pl,b$ as Tl,c0 as El,c1 as rr,c2 as ni,c3 as ri,c4 as Ml,c5 as Al,c6 as Rl,c7 as Fl,c8 as Ll,c9 as Ol,bk as or,r as As,ca as xs,cb as oi,bm as bs,bp as Bl,bq as _l,br as $l,bs as zl,bt as $n,bu as Us,cc as Xr,aC as Rt,b as Pt,aG as Vs,cd as ii,E as vs,H as Bs,J as _s,ce as Ul,cf as Ds,cg as eo,ch as to,ci as Kl,cj as ai,ck as Gl,cl as li,e as jn,cm as Hl,K as ci,R as Wl,cn as ql,aa as Ot,bb as di,c as ir,co as Ql,cp as Vl,cq as Gs,cr as gn,cs as ui,a3 as Hs,a4 as Ws,a2 as Yl,ct as Jl,cu as so,bl as fi,cv as Zl,cw as hi,aT as Xl,aU as ec,cx as no,cy as In,aZ as tc,aP as sc,N as nc,aQ as mi,cz as rc,cA as oc,p as ic,s as ac,cB as lc,cC as cc,q as dc,aR as ro,w as zn,S as oo,aW as uc,cD as fc,cE as hc,v as mc,aD as pi,cF as pc,cG as gc,cH as xc,d as bc,cI as xn,cJ as yc,a as vc,a_ as wc,bo as Sc,cK as jc,bn as kc,cL as Cc,cM as Nc,cN as Ic,cO as Dc,am as Pc,cP as io,cQ as Tc,bc as Ec,cR as Mc,cS as Ac,cT as on,cU as ao,i as Rc,cV as Fc,cW as lo,cX as co,cY as Lc,aF as Oc,ab as Bc,L as _c}from"./useAppFontEffects-DXASDavv.js";import{R as uo,S as $c,T as fo,U as zc,V as Uc,Q as Kc,r as rs,u as ue,v as Gc,t as vr,W as Hc,X as ss,Y as gi,n as xi,h as ys,Z as qe,_ as wr,$ as Sr,a0 as Wc,a1 as qc,J as Qc,a2 as Vc,a3 as Yc,a4 as Jc,y as Zt,a5 as ar,a as Dn,a6 as Zc,a7 as Xc,a8 as ed,a9 as td,x as sd,z as nd,C as rd,E as od,d as id,b as an,aa as ad,ab as ld,ac as Ks,ad as Un}from"./index-CRB7i1S2.js";import{C as bi,a as yi,M as lr,b as cr,c as dr,d as vi,S as wi,D as cd,e as dd,f as ud,g as fd,h as hd,i as md,j as pd,k as gd}from"./vendor-base-ui-DwfTg5wD.js";import{c as ws,d as Si,p as jr,u as ho,a as xd}from"./vendor-zustand-CnsBKjP5.js";import{u as bd}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as Pn,d as qs,P as kr,D as Tn,e as En,f as ji,b as yd,a as vd,T as wd,M as Sd}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as Cr,v as ki,u as Mn,a as jd,h as kd}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as An}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{i as Cd,g as Nd}from"./runtimeSurface-Cnqjhb6Y.js";const Id=3;let kn=0;const Ci=[],Dd=()=>kn<Id?(kn+=1,Promise.resolve()):new Promise(e=>{Ci.push(e)}),Pd=()=>{const e=Ci.shift();if(e){e();return}kn=Math.max(0,kn-1)},Td=async e=>{await Dd();try{return await e()}finally{Pd()}},Ed="chat";function Ni(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ts.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ts.SETTINGS,n),s}return e.tab!==Ed&&s.set(Ts.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ts.FILE,e.diffFile),s}function Md(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Ad(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Ni(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ts.SESSION)&&s.set(Ts.SESSION,o);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function mo(e,s={}){if(!(typeof window>"u")&&!ti()&&!(!s.force&&Ad(e)))try{const n=Ni(e),r=Md(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Rd=["typescript","javascript","tsx","jsx","json","markdown"],Ii={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let po=null;const Di=()=>(po??=Promise.all([Ms(()=>import("./index-MSKFS67y.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,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),Ms(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ms(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,8,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),po),Qs={},go=new Set,ur=new Set;let bn={light:"pierre-light",dark:"pierre-dark"};const Fd=()=>{for(const e of ur)e()},Pi=(e,s)=>{s.setRenderOptions({theme:bn,lineDiffType:Ii[e].lineDiffType})},fr=e=>{typeof window>"u"||go.has(e)||(go.add(e),Di().then(s=>{if(Qs[e])return;const n=Ii[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Rd,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Qs[e]=r,Pi(e,r),Fd()}))},Ld=e=>(ur.add(e),()=>ur.delete(e)),Od=e=>{if(!(bn.light===e.light&&bn.dark===e.dark)){bn=e;for(const s of Object.keys(Qs)){const n=Qs[s];n&&Pi(s,n)}}},Jm=({children:e})=>{const s=il(),n=uo(!1),r=uo(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===o)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Ue.useEffect(()=>{let d=!1;return Di().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Od({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ue.useEffect(()=>{if(typeof window>"u")return;const d=()=>{fr("unified"),fr("split")};if(typeof window.requestIdleCallback=="function"){const y=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(y)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},Zm=(e="unified")=>{const s=Ue.useSyncExternalStore(Ld,()=>Qs[e],()=>{});return Ue.useEffect(()=>{fr(e)},[e]),s},xo="pichamber.update-install-id";function Bd(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const e=window.localStorage.getItem(xo)?.trim();if(e)return e;const s=crypto.randomUUID();return window.localStorage.setItem(xo,s),s}catch{return}}function _d(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=al();return e}catch{return"unknown"}}function $d(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function zd(){const e=Nd();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function Ud(e){const s=ue.getState().reportUsage,n=new URLSearchParams({reportUsage:s?"true":"false"});if(n.set("deviceClass",_d()),n.set("arch",$d()),n.set("platform",zd()),s&&(e==="desktop"||e==="mobile")){const r=Bd();r&&n.set("installId",r)}return e==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",Gc()?"local":"remote"),n):e==="mobile"?(n.set("appType","mobile-capacitor"),n.set("instanceMode","remote"),n):(n.set("appType","web"),n.set("instanceMode","unknown"),n)}async function Kn(e,s){try{const n=Ud(e);s&&n.set("currentVersion",s);const r=await rs(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Kd(){return Cd()?"mobile":Uc()?"desktop":Kc()?"web":null}const bo={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},yn=ws()((e,s)=>({...bo,checkForUpdates:async()=>{const n=Kd();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.1.8",[l,c]=await Promise.allSettled([fo(),Kn("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await Kn("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await Kn("mobile","0.1.8"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await fo();if(!o?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await zc(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await $c())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(bo)}})),yo="https://github.com/RyderAsKing/PiChamber/releases";function Gd(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function Hd(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function vo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Wd(e,s){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(a!==l)return l-a}return 0}function qd(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const wo=2e3,Qd=600*1e3;async function Vd(){try{const e=await rs("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Yd(){try{return(await rs("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function Jd(e,s=Math.ceil(Qd/wo),n=wo){for(let r=0;r<s;r++){try{const o=await rs("/api/pi/update-check?reportUsage=false",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await Yd())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const Zd=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[y,m]=Ue.useState(!1),[w,x]=Ue.useState("idle"),[v,g]=Ue.useState(null),j=n?.version?n.releaseUrl||`${yo}/tag/v${n.version}`:yo,C=n?.downloadUrl||j,N=a?.total?Math.round(a.downloaded/a.total*100):0,b=u==="web",h=u==="mobile",f=n?.updateCommand||"pichamber update";Ue.useEffect(()=>{e||(x("idle"),g(null))},[e]);const I=async()=>{(await nr(f)).ok&&(m(!0),setTimeout(()=>m(!1),2e3))},M=Ue.useCallback(async z=>{await ll(z)},[]),T=Ue.useCallback(async()=>{x("updating"),g(null);const z=await Vd();if(!z.success){x("error"),g(z.error||"Update failed");return}z.autoRestart&&(x("restarting"),await new Promise(ne=>setTimeout(ne,2e3))),x("reconnecting"),await Jd(n?.currentVersion)?window.location.reload():(x("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),O=Ue.useCallback(()=>{M(C)},[M,C]),P=w!=="idle"&&w!=="error",B=Ue.useMemo(()=>{if(!n?.body)return null;const z=n.body.trim();if(!z)return null;const U=qd(z);return U.length===0?{kind:"raw",title:"What's new",content:vo(z)}:{kind:"sections",title:"What's new",sections:[...U].sort((se,K)=>Wd(se.version,K.version)).map(se=>({version:se.version,dateLabel:Gd(se.date),content:vo(Hd(se.raw)||z)}))}},[n?.body]);return t.jsx(os,{open:e,onOpenChange:P?void 0:s,children:t.jsxs(is,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(us,{className:"flex items-center gap-2.5",children:[t.jsx(k,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:w==="restarting"||w==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[b&&P&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(k,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[w==="updating"&&"Installing update...",w==="restarting"&&"Server restarting...",w==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),B&&!P&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ps,{className:"max-h-[400px] p-0",fillContainer:!1,children:B.kind==="raw"?t.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:z=>{const ne=z.target.closest("a");ne&&ne.href&&(z.preventDefault(),z.stopPropagation(),M(ne.href))},children:t.jsx(Vr,{content:B.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:B.sections.map(z=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.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",z.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:z.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:U=>{const se=U.target.closest("a");se&&se.href&&(U.preventDefault(),U.stopPropagation(),M(se.href))},children:t.jsx(Vr,{content:z.content,disableLinkSafety:!0,enableFileReferences:!1})})]},z.version))})})}),b&&w==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(k,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.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:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:f}),t.jsx("button",{onClick:I,className:F("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",y&&"text-[var(--status-success)]"),title:y?"Copied!":"Copy command",children:y?t.jsx(k,{name:"check",className:"h-4 w-4"}):t.jsx(k,{name:"clipboard",className:"h-4 w-4"})})]})]}),!b&&!h&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[N,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${N}%`}})})]}),(l||v)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||v})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:j,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:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!b&&!h&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!b&&!h&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!b&&!h&&o&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),h&&t.jsxs(Ee,{onClick:O,size:"default",children:[t.jsx(k,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),b&&!P&&t.jsxs("button",{onClick:T,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(k,{name:"download",className:"h-4 w-4"}),"Update Now"]}),b&&P&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(k,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Xd=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=i.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":o,className:F("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] 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:t.jsx("span",{"aria-hidden":!0,className:F("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),Ys=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(et,{open:r,onOpenChange:o,children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:F("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(k,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(st,{sideOffset:8,className:F("max-w-sm",n),children:e})]})},Xm="w-full min-w-40 max-w-48",eu="settings",tu="w-full min-w-40 max-w-48",ep="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",su="w-full max-w-[24rem]",tp="min-w-0 flex-1",sp="flex w-full min-w-0 items-center gap-2",np="typography-meta shrink-0 text-muted-foreground tabular-nums",Ti="space-y-3.5",nu="space-y-1.5",rp="typography-settings-page-title text-muted-foreground",ru="typography-settings-section-title text-foreground",op="typography-settings-section-title text-foreground",Ei="typography-settings-group-title text-foreground",Nr="typography-settings-field-label text-foreground",ou="typography-settings-description text-muted-foreground",Js="typography-meta text-muted-foreground",ip="typography-meta font-medium text-foreground",ap="typography-settings-section-title text-foreground",iu=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const y=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:F("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[y?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:ru,children:e}):e,n,r!=null?t.jsx(Ys,{children:r}):null]}):null,s!=null?t.jsx("div",{className:ou,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:F(d),children:a})]})},lp=({children:e,className:s})=>t.jsx("div",{className:F("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),au=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:F(Ei,s),children:e}),cp=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:F("space-y-2",o),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(au,{children:e}),n!=null?t.jsx(Ys,{children:n}):null]}):null,s!=null?t.jsx("p",{className:Js,children:s}):null]}):null,t.jsx("div",{className:F(a),children:r})]}),Es=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:Js,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:F("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:Nr,children:e}),n!=null?t.jsx(Ys,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:F("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},dp=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:F("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:Nr,children:e}),n!=null?t.jsx(Ys,{children:n}):null]}),s!=null?t.jsx("p",{className:F(Js,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:F("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),up=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:F("pt-4",s),children:e}),lu=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const y=()=>{o||s(!e)},m=r!=null;return t.jsxs("div",{"data-settings-item":l,className:F("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:y,onKeyDown:w=>{(w.key===" "||w.key==="Enter")&&(w.preventDefault(),y())},children:[t.jsx(si,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:Nr,children:n}),d,u!=null?t.jsx(Ys,{children:u}):null]}),m?t.jsx("span",{className:Js,children:r}):null]})]})},fp=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,disabled:a=!1,className:l})=>t.jsxs("div",{className:F("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(Xd,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:F("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:Js,children:r}):null]})]}),hp=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:F(nu,n),children:s});function mp({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:F("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Ee,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class cu extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(cl,{className:"w-full max-w-md",children:[t.jsx(dl,{className:"text-center",children:t.jsxs(ul,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(k,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(fl,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Ee,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(k,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function du(e){return t.jsx(cu,{...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 pp=({active:e=!0,readOnly:s=!1})=>{const n=Me(r=>r.currentSessionId);return t.jsx(du,{sessionId:n||void 0,children:t.jsx(hl,{active:e,readOnly:s},n??"no-session")})};function uu({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,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:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const Ir=Ue.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:y,endSlot:m,...w},x)=>{const v=Ue.useRef(null),g=Ue.useRef(null),[j,C]=Ue.useState(null),N=c??j,b=Ue.useCallback(f=>{const I=v.current;if(!I)return;g.current={startY:f.clientY,startHeight:I.getBoundingClientRect().height};const M=f.currentTarget;M.setPointerCapture(f.pointerId);const T=P=>{const B=g.current;if(!B)return;const z=B.startHeight+(P.clientY-B.startY),U=Math.max(82,z);d?d(U):C(U)},O=()=>{g.current=null,M.removeEventListener("pointermove",T),M.removeEventListener("pointerup",O),M.removeEventListener("pointercancel",O)};M.addEventListener("pointermove",T),M.addEventListener("pointerup",O),M.addEventListener("pointercancel",O),f.preventDefault()},[d]),h=Ue.useCallback(f=>{if(f.target.closest('textarea, button, [role="separator"]'))return;const M=v.current?.querySelector("textarea");M&&document.activeElement!==M&&(f.preventDefault(),M.focus())},[]);return y?t.jsx(ps,{as:"textarea",ref:x,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:F("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...w}):t.jsx("div",{ref:v,onPointerDown:h,style:N!==null?{height:`${N}px`}:void 0,className:F("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:x,className:F("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...w}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,t.jsx(uu,{onResizeStart:b,ariaLabel:"Resize textarea"})]})]})})});Ir.displayName="Textarea";const So=(e,s)=>s.updatedAtMs-e.updatedAtMs,jo=ws((e,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){e({isLoading:!0,error:null});try{const[n,r]=await Promise.all([xl(),Jr()]),o={};for(const a of r.sort(So))o[a.id]=a;s().listenerReady||await bl(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:o,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){e({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!s().isImportsLoading){e({isImportsLoading:!0,error:null});try{const n=await gl();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Jr(),r={};for(const o of n.sort(So))r[o.id]=o;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await pl({instances:n}),e({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw e({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,o=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(o)},createFromCommand:async(n,r,o)=>{const a=yl(n,r);o&&o.trim()&&(a.nickname=o.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await Yr(n).catch(()=>{});const r=s().instances.filter(o=>o.id!==n);await s().setInstances(r),e(o=>{const a={...o.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await ml(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},disconnect:async n=>{e({error:null});try{await Yr(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},retry:async n=>{await s().connect(n)},getStatus:n=>s().statusesById[n]||null,clearError:()=>e({error:null})})),Mi=[{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"}],Ai=Object.fromEntries(Mi.map(e=>[e.key,e.Icon])),fu="pichamber:project-actions-updated",hu=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},gp=(e,s)=>`${hu(e)}::${s}`,mu=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ko=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},pu=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ko(s.localPort),r=ko(s.remotePort);if(!n||!r)return null;const o=mu(s.localHost||e.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(e.nickname||e.id||"instance").trim();return{id:`${e.id}::${s.id}`,label:`${l} - ${o}:${n} -> ${a}:${r}`,url:`http://${o}:${n}`}},Ri=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const o=pu(n,r);o&&s.push(o)}return s},xp=(e,s)=>{const n=(e||"").trim();return n&&Ri(s).find(a=>a.id===n)?.url||null},gu=su,Fi=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(iu,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),hr=e=>e.name.trim().length>0&&e.command.trim().length>0,xu=e=>e.name.trim().length===0&&e.command.trim().length===0,bu=e=>!hr(e)&&!xu(e),yu=(e,s)=>e.some(r=>s.has(r.id)&&!hr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(hr)},vu=450,wu=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Su=()=>({id:wu(),name:"",command:"",icon:"play"}),ju=({projectRef:e})=>{const s=i.useMemo(()=>vr(),[]),n=jo(f=>f.instances),r=jo(f=>f.load),[o,a]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[y,m]=i.useState(new Set),w=i.useRef(!1);i.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),i.useEffect(()=>{let f=!1;return c(!0),(async()=>{try{const I=await vl(e);if(f)return;a(I.actions),u(JSON.stringify({actions:I.actions})),m(new Set(I.actions.map(M=>M.id)))}catch{if(f)return;a([]),u(JSON.stringify({actions:[]})),m(new Set)}finally{f||c(!1)}})(),()=>{f=!0}},[e]);const x=i.useMemo(()=>s?Ri(n):[],[n,s]),v=i.useMemo(()=>yu(o,y),[o,y]),g=i.useMemo(()=>JSON.stringify({actions:v.actions}),[v.actions]),j=d!==null&&v.canPersist&&g!==d,C=i.useCallback(async f=>await wl(e,{actions:f,primaryActionId:null})?(u(JSON.stringify({actions:f})),m(new Set(f.map(M=>M.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(fu,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!j||l||w.current)return;const f=window.setTimeout(()=>{w.current||(w.current=!0,(async()=>{try{await C(v.actions)}finally{w.current=!1}})())},vu);return()=>{window.clearTimeout(f)}},[j,l,C,v.actions]);const N=i.useCallback(()=>{const f=Su();a(I=>[...I,f])},[]),b=i.useCallback(f=>{a(I=>I.filter(M=>M.id!==f))},[]),h=i.useCallback((f,I)=>{a(M=>M.map(T=>T.id===f?I(T):T))},[]);return t.jsx(Fi,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Ee,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:N,children:[t.jsx(k,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):o.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:F("space-y-6",gu),children:o.map((f,I)=>{const M=f.icon||"play",T=Ai[M]||"play",O=f.name.trim()||`Action ${I+1}`,P=bu(f);return t.jsxs("div",{className:Ti,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ei,children:O}),t.jsx(Ee,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>b(f.id),"aria-label":`Delete ${O}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Es,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:t.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:t.jsx(k,{name:T,className:"h-4 w-4"})})}),t.jsx(Xt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Mi.map(B=>{const z=B.Icon,U=(f.icon||"play")===B.key;return t.jsx("button",{type:"button",onClick:()=>h(f.id,ne=>({...ne,icon:B.key})),className:F("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",U&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${B.label}`,children:t.jsx(k,{name:z,className:"h-4 w-4"})},B.key)})})})]}),t.jsx(Ls,{value:f.name,onChange:B=>h(f.id,z=>({...z,name:B.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Es,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(Ir,{value:f.command,onChange:B=>h(f.id,z=>({...z,command:B.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),P?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(lu,{checked:f.autoOpenUrl===!0,onChange:B=>h(f.id,z=>({...z,...B?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0,desktopOpenSshForward: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 ${O}`}),f.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Es,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Ls,{value:f.openUrl||"",onChange:B=>h(f.id,z=>({...z,openUrl:B.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Es,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:x.length>0?t.jsxs(Sl,{value:f.desktopOpenSshForward&&x.some(B=>B.id===f.desktopOpenSshForward)?f.desktopOpenSshForward:"__none__",onValueChange:B=>{h(f.id,z=>({...z,...B==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:B}}))},children:[t.jsx(jl,{size:eu,className:"w-full",children:t.jsx(kl,{placeholder:"Use output/manual URL"})}),t.jsxs(Cl,{children:[t.jsx(Zr,{value:"__none__",children:"Use output/manual URL"}),x.map(B=>t.jsx(Zr,{value:B.id,children:B.label},B.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},f.id)})})})},ku={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Cu=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Vt(P=>P.providers),d=Vt(P=>P.modelsMetadata),u=ue(P=>P.hiddenModels),y=ue(P=>P.providerOrder),m=ue(P=>P.setProviderOrder),w=ue(P=>P.isFavoriteModel),x=ue(P=>P.toggleFavoriteModel),v=ue(P=>P.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:j}=Nl(),[C,N]=i.useState(!1),[b,h]=i.useState("");i.useEffect(()=>{C||h("")},[C]);const f=e?c.find(P=>P.id===e.providerId):void 0,I=e&&f?(Array.isArray(f.models)?f.models:[]).find(P=>P.id===e.modelId):void 0,M=e?Il(I,e.modelId):s,T=i.useMemo(()=>e?u.filter(P=>!(P.providerID===e.providerId&&P.modelID===e.modelId)):u,[u,e]),O=i.useCallback(P=>{l({providerId:P.providerID,modelId:P.modelID}),N(!1)},[l]);return t.jsxs(as,{modal:!1,open:C,onOpenChange:P=>{r||N(P)},children:[t.jsx(ls,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:F(Pl({size:"default"}),tu,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Dl,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:F("truncate",e?"text-foreground":"text-muted-foreground"),children:M})]}),t.jsx(k,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Xt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Tl,{providers:c,favoriteModels:g,recentModels:j,modelsMetadata:d,searchQuery:b,onSearchQueryChange:h,onSelect:O,labels:{...ku,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:T,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),N(!1)},disabled:r,autoFocus:!0,onEscape:()=>N(!1),isFavorite:P=>w(P.providerID,P.modelID),onToggleFavorite:P=>x(P.providerID,P.modelID),onReorderFavorite:(P,B)=>v(P.providerID,P.modelID,B.providerID,B.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:y,onReorderProvider:m,reorderProviderTitle:"Drag to reorder provider"})})]})},Gn="w-full max-w-none",Nu=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Vt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Fi,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ti,children:[t.jsx(Es,{label:"Name",settingsItem:"projects.name",controlClassName:Gn,children:t.jsx(Ls,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(Es,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:Gn,children:t.jsx(Cu,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:Gn,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Iu=e=>{const[s,n]=i.useState(""),[r,o]=i.useState(void 0);i.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const a=i.useMemo(()=>El(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((u,y)=>{o(u&&y?`${u}/${y}`:void 0)},[]),d=i.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Du=450,Pu=(e,s)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:a}=e,l=i.useRef(!1);i.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},Du);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},Tu=({project:e,onIdentitySave:s})=>{const n=Iu(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Pu(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Nu,{form:n}),t.jsx(ju,{projectRef:r})]})};function Eu({...e}){return t.jsx(bi,{...e})}function Mu({...e}){return t.jsx(yi,{...e})}function Au({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(lr,{children:t.jsx(cr,{className:F("app-region-no-drag z-50",s),children:t.jsx(dr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:F(rr,e),...o,children:n})})})}function Co({className:e,...s}){return t.jsx(vi,{className:F(ni,e),...s})}function Ru({className:e,...s}){return t.jsx(wi,{className:F(ri,e),...s})}const ms=ws()(Si(jr((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=await Ol();return e({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await Ll();if(n&&n.userName&&n.userEmail){const r={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:r})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await Fl();return e({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const o=r.trim();return o.length>0?o:null};try{let r=null;if(r===null){const o=xi()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await rs("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await gi({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return ss("saving"),await Rl(r),ss("saved"),await s().loadProfiles(),!0}catch(r){return ss("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(l=>l.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};return ss("saving"),await Al(n,a),ss("saved"),await s().loadProfiles(),!0}catch(o){return ss("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{return ss("saving"),await Ml(n),ss("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ss("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:o}=s();return n==="global"?o||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(o=>!n.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Hc(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ms);const Fu=[{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:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"content",kind:"split",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"content",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"content",kind:"split",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","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:"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:"magic-prompts",title:"Magic Prompts",group:"content",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request"]},{slug:"snippets",title:"Snippets",group:"content",kind:"split",keywords:["prompt","templates","multi-run","strategy","approach"]},{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"]},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Lu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Ou(e){const s=e.trim().toLowerCase();return Fu.find(n=>n.slug===s)??null}function Bu(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=Lu[s];if(n)return n;const r=Ou(s);return r?r.slug:"home"}function bp(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"magic-prompts":return"ai-generate-2";case"snippets":return"chat-thread";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const ln=100;function yp(){const e=ue(T=>T.isArchivePageOpen),s=ue(T=>T.setArchivePageOpen),n=ue(T=>T.setActiveMainTab),r=Me(T=>T.setCurrentSession),o=Me(T=>T.unarchiveSession),a=ys(T=>T.homeDirectory),l=or({archived:!0}),[c,d]=i.useState(""),[u,y]=i.useState(null),[m,w]=i.useState(ln),x=c.trim().toLowerCase(),v=i.useMemo(()=>e?[...l].sort((T,O)=>(O.time?.archived??0)-(T.time?.archived??0)):[],[l,e]),g=i.useMemo(()=>{const T=new Map;for(const O of v){const P=qe(As(O))??"",B=T.get(P);if(B){B.sessions.push(O);continue}T.set(P,{directory:P,label:P?xs(P,a)||P:"other projects",sessions:[O]})}return[...T.values()].sort((O,P)=>P.sessions.length-O.sessions.length)},[a,v]),j=i.useMemo(()=>x?v.filter(T=>(T.title??"").toLowerCase().includes(x)):u===null?v:g.find(T=>T.directory===u)?.sessions??[],[g,x,u,v]),C=j.slice(0,m),N=j.length-C.length,b=l.length,h=i.useCallback(T=>{y(T),w(ln)},[]),f=i.useCallback(T=>{const O=qe(As(T));r(T.id,O??void 0),n("chat"),s(!1)},[n,r,s]),I=i.useCallback(T=>{o(T.id).then(O=>{O?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const M=(T,O,P,B,z,U,ne)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:z,title:U,className:F("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",ne?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",B?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:O}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:P})]}),ne?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>bs.requestDelete({sessions:ne,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 ${O}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},T);return t.jsx(cd,{open:e,onOpenChange:s,children:t.jsxs(dd,{children:[t.jsx(ud,{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"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs(fd,{className:"pointer-events-auto 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:[t.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between border-b border-border/70 bg-sidebar px-4",children:[t.jsxs(hd,{className:"flex items-center gap-2 typography-ui-label font-medium text-foreground",children:[t.jsx(k,{name:"archive",className:"size-4 text-muted-foreground"}),"Archived sessions"]}),t.jsx("button",{type:"button",onClick:()=>s(!1),className:"inline-flex size-8 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":"Close archived sessions",children:t.jsx(k,{name:"close",className:"size-4"})})]}),t.jsx(md,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[M("__all__","All directories",b,u===null,()=>h(null)),g.map(T=>M(T.directory||"__none__",T.label,T.sessions.length,u===T.directory,()=>h(T.directory),T.directory||void 0,T.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:T=>{d(T.target.value),w(ln)},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"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:j.length===1?`${j.length} archived session`:`${j.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[C.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:x?"No matching archived sessions":"No archived sessions"})}):C.map(T=>{const O=qe(As(T))??"",P=O?xs(O,a)||O:null;return t.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:()=>f(T),role:"button",tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),f(T))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:T.title||"Untitled Session"}),x&&P?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:O,children:P}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:oi(T.time?.archived??T.time?.updated??T.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),I(T)},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 ${T.title||"Untitled Session"}`,children:t.jsx(k,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),bs.requestDelete({sessions:[T],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 ${T.title||"Untitled Session"}`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},T.id)}),N>0?t.jsx("button",{type:"button",onClick:()=>w(T=>T+ln),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const _u=()=>{const[e,s]=Ue.useState(!1),[n,r]=Ue.useState(!1);Ue.useEffect(()=>{s(vr()),r(wr())},[]);const o=Ue.useCallback(async c=>e?await Sr(c):{success:!0,path:c},[e]),a=Ue.useCallback(async c=>e?await Wc():{success:!0},[e]),l=Ue.useCallback(async c=>e?await qc():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}},$u=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),zu=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:o,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=i.useState(!1),[y,m]=i.useState(""),[w,x]=i.useState(!1),[v,g]=i.useState(!1),[j,C]=i.useState(""),[N,b]=i.useState(!1),h=i.useRef(null),f=i.useCallback(K=>{K.stopPropagation()},[]),I=l.length>1,M=i.useMemo(()=>$u(j),[j]),T=i.useMemo(()=>{const K=y.toLowerCase();return K?s.filter(G=>G.toLowerCase().includes(K)):s},[y,s]),O=i.useMemo(()=>{const K=y.toLowerCase();return K?n.filter(G=>G.toLowerCase().includes(K)):n},[y,n]),P=K=>{if(K===e){u(!1);return}o(K),u(!1),m("")},B=()=>{x(!0),setTimeout(()=>h.current?.focus(),50)},z=async()=>{if(!(!M||N)){if(I){g(!0);return}b(!0);try{await a(M,l[0]),C(""),x(!1),u(!1)}finally{b(!1)}}},U=async K=>{if(!(!M||N)){b(!0);try{await a(M,K),C(""),x(!1),g(!1),u(!1)}finally{b(!1)}}},ne=()=>{g(!1)},se=()=>{C(""),x(!1),g(!1)};return i.useEffect(()=>{d||(m(""),x(!1),g(!1),C(""))},[d]),t.jsxs(as,{open:d,onOpenChange:u,children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Current branch"})]}),t.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(Bl,{className:"h-full min-h-0",children:[t.jsx(_l,{placeholder:"Search branches...",value:y,onValueChange:m,onKeyDown:f}),t.jsxs($l,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(zl,{children:"No branches found."}),t.jsx($n,{children:v?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:ne,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:M})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(K=>t.jsxs("button",{type:"button",onClick:()=>U(K),disabled:N,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[N?t.jsx(k,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,K.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:K.pushUrl})]},K.name))})]}):w?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:h,placeholder:"New branch name",value:j,onChange:K=>C(K.target.value),onClick:K=>K.stopPropagation(),onKeyDown:K=>{f(K),K.key==="Enter"?(K.preventDefault(),z()):K.key==="Escape"&&(K.preventDefault(),se())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:z,disabled:!M||N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:N?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:se,disabled:N,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(Us,{onSelect:B,children:[t.jsx(k,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Xr,{}),t.jsxs($n,{heading:"Local branches",children:[T.map(K=>t.jsxs(Us,{onSelect:()=>P(K),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:K}),(r?.[K]?.ahead||r?.[K]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[K].ahead||0," ahead ·"," ",r[K].behind||0," behind"]})]}),e===K&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${K}`)),T.length===0&&t.jsx(Us,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Xr,{}),t.jsxs($n,{heading:"Remote branches",children:[O.map(K=>t.jsx(Us,{onSelect:()=>P(K),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:K})},`remote-${K}`)),O.length===0&&t.jsx(Us,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Uu=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Ku=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,o]=i.useState(!1),[a,l]=i.useState(e||""),[c,d]=i.useState(!1),u=i.useRef(null),y=()=>{!e||!s||(l(e),o(!0),setTimeout(()=>u.current?.focus(),0))},m=async()=>{if(!e||!s||!a.trim())return;const v=Uu(a);if(v===e){o(!1);return}d(!0);try{await s(e,v),o(!1),l("")}finally{d(!1)}},w=()=>{o(!1),l("")},x=v=>{v.key==="Enter"?(v.preventDefault(),m()):v.key==="Escape"&&(v.preventDefault(),w())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:v=>{v.preventDefault(),m()},children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:v=>l(v.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:x,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:w,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(k,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(k,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Ee,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:y,title:"Rename branch",children:t.jsx(k,{name:"edit",className:"size-4"})})]})]})},Gu=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:o,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:y=!1})=>{const m=i.useRef(!1),w=!!l,x=s.find(f=>f.name===u)??s[0],v=d>0&&y,g=a||e!==null||w||!x||v,j=a||e!==null||w||s.length===0,C=c>0||d>0,N=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),b=v?"Commit or stash your changes before syncing":x?C?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",h=()=>{x&&r(x)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:v?0:void 0,children:t.jsxs("button",{type:"button",onClick:h,disabled:g,className:F("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(k,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:N})]})})}),t.jsx(st,{sideOffset:8,children:b})]}),t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:t.jsx("button",{type:"button",className:F("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] 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 disabled:opacity-50"),disabled:j,"aria-label":"More sync actions",children:t.jsx(k,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Xt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(f=>t.jsx(Rt,{onSelect:I=>{if(m.current){I.preventDefault(),m.current=!1;return}n(f)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(k,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${f.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:f.fetchUrl})]})}),o&&f.name!==u?t.jsx(Ee,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||w,onPointerDown:I=>{m.current=!0,I.preventDefault(),I.stopPropagation()},onClick:I=>{m.current=!0,I.preventDefault(),I.stopPropagation(),o(f)},"aria-label":`Remove remote ${f.name}`,title:`Remove remote ${f.name}`,children:l===f.name?t.jsx(k,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(k,{name:"close",className:"size-3.5"})}):null]})},f.name))})]})]})},Hu={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Wu={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Li(e){return e&&Wu[e]||"var(--primary)"}const No=({icon:e,className:s,colorToken:n})=>{const r=Hu[e??"branch"]??"user-3";return t.jsx(k,{name:r,className:s,style:{color:Li(n)}})},Oi=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(as,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:Li(e?.color)},disabled:a,children:[r?t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(No,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(k,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(st,{sideOffset:8,children:"Git identity"})]}),t.jsx(Xt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(Rt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(No,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(k,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},qu=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,o=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(et,{delayDuration:n,children:[t.jsx(tt,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(k,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),o?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(st,{sideOffset:8,children:a})]})},vp=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:y,onCreateBranch:m,onRenameBranch:w,activeIdentityProfile:x,availableIdentities:v,onSelectIdentity:g,isApplyingIdentity:j,isWorktreeMode:C,onOpenHistory:N,onOpenGraph:b,onOpenStashes:h,onOpenUpdateBranch:f,onOpenReintegrateCommits:I,pullRequest:M,prChecks:T,onOpenPullRequest:O})=>{if(!e)return null;const P=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:N||b||h||f?t.jsxs(as,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsx(Ee,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(k,{name:"more-fill",className:"size-4"})})})}),t.jsx(st,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Xt,{align:"end",children:[N?t.jsxs(Rt,{onSelect:N,children:[t.jsx(k,{name:"history",className:"size-4"}),"History"]}):null,b?t.jsxs(Rt,{onSelect:b,children:[t.jsx(k,{name:"git-branch",className:"size-4"}),"Graph"]}):null,h?t.jsxs(Rt,{onSelect:h,children:[t.jsx(k,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,f?t.jsxs(Rt,{onSelect:f,children:[t.jsx(k,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,I?t.jsxs(Rt,{onSelect:I,children:[t.jsx(k,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),B=T?T.state==="success"?"var(--status-success)":T.state==="failure"?"var(--status-error)":"var(--status-warning)":null,z=M?M.state==="merged"?"merged":M.state==="closed"?"closed":M.draft?"draft":T?.state==="failure"||M.mergeable===!1||M.mergeableState==="blocked"||M.mergeableState==="dirty"?"blocked":"open":null,U=M&&O?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs(Ee,{variant:"ghost",size:"sm",onClick:O,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(k,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${z})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${M.number}`}),B?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:B}}):null]})}),t.jsx(st,{sideOffset:8,children:"Open pull request"})]}):null,ne=t.jsx(Gu,{syncAction:o,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),se=e.upstreamComparison?t.jsx(qu,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,K=t.jsx(Oi,{activeProfile:x,identities:v,onSelect:g,isApplying:j,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:C?t.jsx(Ku,{currentBranch:e.current,onRename:w}):t.jsx(zu,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:y,onCreate:m,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:K})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[U?t.jsx("div",{className:"shrink-0",children:U}):null,t.jsx("div",{className:"min-w-0 flex-1"}),se?t.jsx("div",{className:"min-w-0 shrink",children:se}):null,P,t.jsx("div",{className:"shrink-0",children:ne})]})]})},Qu=e=>e==="/",Rs=e=>e.replace(/\\/g,"/"),Os=e=>{if(!e||Qu(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Fs=e=>e.endsWith("/"),Cn=e=>{const s=e.trim();return!s||Fs(s)?s:`${s}/`},Dr=e=>e.lastIndexOf("/"),Bi=e=>{if(Fs(e))return e;const s=Dr(e);return s<0?e:e.slice(0,s+1)},_i=e=>{const s=Dr(e);return e.slice(s+1)},$i=e=>{const s=Os(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=Dr(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},zi=e=>Fs(e)&&$i(e)!==null,Vu=e=>{if(!zi(e))return null;const s=Os(e.trim());return _i(s)||s},Yu=(e,s)=>`${Bi(e)}${s}/`,hs=e=>{if(!e)return null;const s=Os(Rs(e.trim()));return s?s.toLowerCase():null},Io=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},Ju=(e,s)=>{const n=Os(Rs(e.trim())),r=Os(Rs(s.trim()));if(!n)return"";if(!r)return Cn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Cn(n)},Zu=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Hn=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Xu=async()=>Jc(),ef=({open:e,onOpenChange:s})=>{const n=ys(D=>D.homeDirectory),r=Pt(D=>D.projects),o=Pt(D=>D.addProject),a=ue(D=>D.setActiveMainTab),l=ue(D=>D.setSessionSwitcherOpen),c=Me(D=>D.openNewSessionDraft),d=ms(D=>D.profiles),u=ms(D=>D.globalIdentity),y=ms(D=>D.defaultGitIdentityId),m=ms(D=>D.loadProfiles),w=ms(D=>D.loadGlobalIdentity),x=ms(D=>D.loadDefaultGitIdentityId),{canRequestAccess:v,startAccessing:g}=_u(),{isMobile:j}=Vs(),C=i.useRef(null),N=i.useRef(new Map),[b,h]=i.useState(""),[f,I]=i.useState("~/"),[M,T]=i.useState([]),[O,P]=i.useState(!1),[B,z]=i.useState(!1),[U,ne]=i.useState(null),[se,K]=i.useState(0),[G,R]=i.useState(0),[A,V]=i.useState(!1),[le,$]=i.useState(!1),[ke,Ie]=i.useState(!1),[_e,Ge]=i.useState(""),[Fe,ve]=i.useState(null),[Pe,me]=i.useState(!1),[He,we]=i.useState("right"),xe=i.useRef("~/"),Ce=b||n,Qe=i.useMemo(()=>new Set(r.map(D=>hs(D.path)).filter(D=>!!D)),[r]);i.useEffect(()=>{if(!e)return;I("~/"),T([]),R(0),V(!1),$(!1),Ie(!1),Ge(""),ve(null),me(!1),xe.current="~/",we("right"),requestAnimationFrame(()=>Hn(C.current));let D=!1;return(async()=>{const Ne=await Xu();D||(h(Ne||n||""),requestAnimationFrame(()=>Hn(C.current)))})(),()=>{D=!0}},[n,e]),i.useEffect(()=>{e&&(m(),w(),x())},[x,m,w,e]);const Be=i.useMemo(()=>{const D=new Map;u&&D.set(u.id,u);for(const fe of d)D.set(fe.id,fe);return Array.from(D.values())},[d,u]);i.useEffect(()=>{if(!e||!ke||Fe!==null)return;const D=typeof y=="string"?y.trim():"";if(D&&Be.some(Ne=>Ne.id===D)){ve(D);return}const fe=Be.find(Ne=>Ne.authType==="ssh"||Ne.sshKey);fe&&ve(fe.id)},[Be,y,ke,e,Fe]);const W=i.useMemo(()=>Be.find(D=>D.id===Fe)??null,[Be,Fe]),H=i.useMemo(()=>Bi(f),[f]),ie=i.useMemo(()=>Fs(f)?"":_i(f),[f]),pe=i.useMemo(()=>Ce?Io(H,Ce):"",[H,Ce]);i.useEffect(()=>{const D=xe.current;D!==H&&(we(H.length>=D.length?"right":"left"),xe.current=H)},[H]),i.useEffect(()=>{if(!e||!pe){T([]),ne(null);return}let D=!1;return P(!0),z(!1),ne(null),Qc(pe).then(fe=>{if(D)return;z(!1),ne(null);const Ne=fe.filter(Le=>Le.isDirectory).map(Le=>({name:Le.name,path:Rs(Le.path)})).sort((Le,We)=>Le.name.localeCompare(We.name));T(Ne)}).catch(fe=>{if(!D){T([]);const Ne=Vc(fe)?fe.reason:"unknown";ne(Ne),z(Ne==="not-found")}}).finally(()=>{D||P(!1)}),()=>{D=!0}},[pe,se,e]);const Se=i.useMemo(()=>{const D=ie.toLowerCase(),fe=Pe||ie.startsWith(".");return M.filter(Ne=>Ne.name.toLowerCase().startsWith(D)&&(fe||!Ne.name.startsWith(".")))},[ie,M,Pe]),Y=i.useMemo(()=>Vu(f),[f]),be=i.useMemo(()=>$i(f),[f]),de=i.useMemo(()=>{const D=[],fe=hs(pe);zi(f)&&Y&&be&&D.push({type:"parent",value:"browse:up",name:Y,path:be,alreadyAdded:!!(fe&&Qe.has(fe))});for(const Ne of Se){const Le=hs(Ne.path);D.push({type:"directory",value:`browse:${Ne.path}`,name:Ne.name,path:Ne.path,alreadyAdded:!!(Le&&Qe.has(Le))})}return D},[Qe,pe,Y,Se,be,f]);i.useEffect(()=>{R(0)},[f,de.length]);const Ve=i.useMemo(()=>Ce?Os(Io(f,Ce)):"",[Ce,f]),at=hs(Ve),ze=!!(at&&Qe.has(at)),je=i.useMemo(()=>ie?Se.find(D=>D.name===ie)??null:null,[ie,Se]),Ae=!!(Ve&&!ze&&(U===null||U==="not-found")&&(Fs(f)&&B||!Fs(f)&&ie.trim().length>0&&je===null)),ot=!A&&!le&&!ze&&U!=="os-permission"&&U!=="invalid-response"&&U!=="unknown"&&!!Ve,ht=ot&&_e.trim().length>0,pt=de[G]??null,ge=!!pt,Ye=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Tt=ze?"Already added":ke?A?"Cloning...":"Clone & add":A?"Adding...":Ae?"Create & add":"Add folder",S=ke?ht:ot;i.useLayoutEffect(()=>{const D=C.current;D&&(D.scrollLeft=D.scrollWidth)},[f]),i.useLayoutEffect(()=>{e&&Hn(C.current)},[e]),i.useLayoutEffect(()=>{const D=de[G];D&&N.current.get(D.value)?.scrollIntoView({block:"nearest"})},[G,de]);const Z=i.useCallback(()=>{s(!1)},[s]),ae=i.useCallback((D,fe)=>{a("chat"),j&&l(!1),c({selectedProjectId:D,directoryOverride:fe}),Z()},[Z,j,c,a,l]),ye=i.useCallback(async D=>{if(!D||A)return;const fe=hs(D);if(fe&&Qe.has(fe))return;let Ne=D;V(!0);try{const Le=!ke&&Ae&&hs(D)===hs(Ve);if(ke){const kt=_e.trim();if(!kt){oe.error("Enter a repository URL before cloning.");return}const E=await rs("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:kt,destinationPath:D,gitIdentityId:W?.id??null})});if(!E.ok)throw new Error("Failed to clone git repository");Ne=(await E.json()).path||D}else if(Le&&!(await rs("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:pe?{directory:pe}:void 0,body:JSON.stringify({path:D})})).ok)throw new Error("Failed to select directory");const We=o(Ne);if(!We){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}ae(We.id,We.path)}catch(Le){oe.error("Failed to select directory",{description:Le instanceof Error?Le.message:"Unknown error occurred."})}finally{V(!1)}},[o,Qe,pe,_e,ke,A,ae,W?.id,Ae,Ve]),Re=i.useCallback(D=>{I(Cn(D))},[]),Ke=i.useCallback(D=>{I(Yu(f,D.name))},[f]),nt=i.useCallback(D=>{if(D){if(D.type==="parent"){Re(D.path);return}Ke(D)}},[Re,Ke]),ct=i.useCallback(async D=>{const fe=await g(D);if(!fe.success)return oe.error("Failed to open directory",{description:fe.error||"Desktop could not grant file access."}),!1;const Ne=Ce?Ju(D,Ce):Cn(Rs(D));return Re(Ne),!0},[Re,Ce,g]),Gt=i.useCallback(async()=>{if(!le){$(!0);try{if(wr()){const fe=await Sr(Ve);if(!fe.success||!fe.path){fe.error&&fe.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:fe.error});return}await ct(fe.path);return}const D=await Yc(Ve);if(D.status==="cancelled")return;if(D.status!=="picked"){oe.error("Couldn't open a folder picker",{description:D.error});return}await ct(D.path)}catch(D){oe.error("Failed to select directory",{description:D instanceof Error?D.message:"Unknown error occurred."})}finally{$(!1)}}},[ct,le,Ve]),it=i.useCallback(D=>{if(D.key==="ArrowDown"){D.preventDefault(),R(fe=>Math.min(de.length-1,fe+1));return}if(D.key==="ArrowUp"){D.preventDefault(),R(fe=>Math.max(0,fe-1));return}if(D.key==="Enter"){if(D.preventDefault(),Zu(D)){ye(Ve);return}ge&&nt(pt);return}D.key==="Backspace"&&f===""&&(D.preventDefault(),Z())},[nt,ye,Z,ge,pt,f,de.length,Ve]),gt=t.jsxs("button",{type:"button",onClick:()=>me(D=>!D),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[Pe?t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),yt=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(k,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(Ls,{ref:C,value:f,onChange:D=>I(Rs(D.target.value)),onKeyDown:it,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Ee,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:A||le,onMouseDown:D=>D.preventDefault(),onClick:()=>{Gt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(k,{name:"folder-open",className:"h-3.5 w-3.5"}),le?"Opening...":"Browse"]})]})}),Je=de.some(D=>D.type==="parent"),Bt=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Ee,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":ke,disabled:A||le,onClick:()=>Ie(D=>!D),children:[t.jsx(k,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),ke?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{value:_e,onChange:D=>Ge(D.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(Oi,{activeProfile:W,identities:Be,onSelect:D=>ve(D.id),isApplying:A,iconOnly:!0})]})]}):null,ze?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:F("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",He==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:O?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):U&&U!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:U==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[U==="os-permission"&&v?t.jsx(Ee,{size:"xs",onClick:()=>{Gt()},disabled:le,children:"Grant access"}):null,t.jsx(Ee,{variant:"outline",size:"xs",onClick:()=>K(D=>D+1),children:"Try again"})]})]}):de.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:de.map((D,fe)=>{const Ne=fe===G,Le=D.type==="directory"&&Je;return t.jsxs("button",{ref:We=>{We?N.current.set(D.value,We):N.current.delete(D.value)},type:"button","aria-label":D.type==="parent"?D.alreadyAdded?`Go back from ${D.name}, already added`:`Go back from ${D.name}`:D.alreadyAdded?`Open ${D.name}, already added`:`Open ${D.name}`,onMouseEnter:()=>R(fe),onMouseDown:We=>We.preventDefault(),onClick:()=>nt(D),className:F("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Ne&&"bg-interactive-selection text-interactive-selection-foreground",!Ne&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:F("flex min-w-0 flex-1 items-center gap-2",Le&&"pl-4"),children:[D.type==="parent"?t.jsx(k,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(k,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:D.name})]}),D.alreadyAdded?t.jsx("span",{className:F("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Ne?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,D.type==="parent"?t.jsx(k,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(k,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},D.value)})})},H)]})}),_t=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[yt,Bt]}),Et=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(k,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:Ye}),t.jsx(k,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),xt=t.jsx(Ee,{size:j?"xs":"default",onClick:()=>{ye(Ve)},disabled:!S,className:F(j&&"w-full flex-1"),children:Tt}),Mt=()=>t.jsxs(t.Fragment,{children:[j?null:Et,t.jsx("div",{className:F("flex w-full flex-row justify-end gap-2 sm:w-auto",j&&"justify-stretch"),children:xt})]});return j?t.jsx(ii,{open:e,onClose:Z,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:Mt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:gt}),_t]})}):t.jsx(os,{open:e,onOpenChange:s,children:t.jsxs(is,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(vs,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(us,{children:"Add folder"}),t.jsx(Bs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),gt]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:_t}),t.jsx(_s,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:Mt()})]})})},cn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,wp=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(!1),[o,a]=i.useState(null),[l,c]=i.useState(!1),d=Ul,u=Me(P=>P.deleteSessions),y=ue(P=>P.showDeletionDialog),m=ue(P=>P.setShowDeletionDialog),w=ys(P=>P.isHomeReady),x=Pt(P=>P.projects),{isMobile:v,isTablet:g,hasTouchInput:j}=Vs(),C=v||g||j;i.useEffect(()=>{n||!w||x.length>0||(r(!0),s(!0))},[n,w,x.length]);const N=i.useCallback(P=>{a({sessions:P.sessions,dateLabel:P.dateLabel})},[]),b=i.useCallback(()=>{a(null),c(!1)},[]),h=i.useCallback(async P=>{if(P.sessions.length===0)return;if(P.sessions.length===1){const ne=P.sessions[0];await d(ne.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const B=P.sessions.map(ne=>ne.id),{deletedIds:z,failedIds:U}=await u(B);if(z.length>0){const ne=U.length>0?U.length===1?`${U.length} session could not be deleted.`:`${U.length} sessions could not be deleted.`:P.dateLabel?`Removed all sessions from ${P.dateLabel}.`:void 0;oe.success(z.length===1?"Deleted {count} session":`Deleted ${z.length} sessions`,{description:cn(ne)})}U.length>0&&oe.error(U.length===1?`Failed to delete ${U.length} session`:`Failed to delete ${U.length} sessions`,{description:cn("Please try again in a moment.")})},[d,u]);i.useEffect(()=>bs.onDeleteRequest(P=>{if(!y){h(P);return}N(P)}),[N,y,h]),i.useEffect(()=>bs.onDirectoryRequest(()=>{s(!0)}),[]);const f=i.useCallback(async()=>{if(o){c(!0);try{if(o.sessions.length===1){const P=o.sessions[0];if(!await d(P.id)){oe.error("Failed to delete session"),c(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const P=o.sessions.map(ne=>ne.id),B=await u(P),z=B.deletedIds,U=B.failedIds;if(z.length>0){const ne=U.length>0?U.length===1?`${U.length} session could not be deleted.`:`${U.length} sessions could not be deleted.`:o.dateLabel?`Removed all sessions from ${o.dateLabel}.`:void 0;oe.success(z.length===1?"Deleted {count} session":`Deleted ${z.length} sessions`,{description:cn(ne),action:{label:"OK",onClick:()=>{}}})}if(U.length>0&&(oe.error(U.length===1?`Failed to delete ${U.length} session`:`Failed to delete ${U.length} sessions`,{description:cn("Please try again in a moment.")}),z.length===0)){c(!1);return}}b()}finally{c(!1)}}},[o,d,u,b]),I=o?o.sessions.length===1?o.dateLabel?`This action permanently removes 1 session from ${o.dateLabel}.`:"This action permanently removes 1 session.":o.dateLabel?`This action permanently removes ${o.sessions.length} sessions from ${o.dateLabel}.`:`This action permanently removes ${o.sessions.length} sessions.`:"",M=o?t.jsxs("div",{className:"space-y-2",children:[o.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[o.sessions.slice(0,5).map(P=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})},P.id)),o.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${o.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,T=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>m(!y),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":!y,children:[y?t.jsx(k,{name:"checkbox-blank",className:"size-4"}):t.jsx(k,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ee,{variant:"ghost",onClick:b,disabled:l,children:"Cancel"}),t.jsx(Ee,{variant:"destructive",onClick:f,disabled:l,children:l?"Deleting…":o?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),O=o?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[C?t.jsx(ii,{open:!!o,onClose:()=>{l||b()},title:O,footer:t.jsx("div",{className:"flex justify-end gap-2",children:T}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),M]})}):t.jsx(os,{open:!!o,onOpenChange:P=>{if(!P){if(l)return;b()}},children:t.jsxs(is,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(vs,{children:[t.jsx(us,{children:O}),I&&t.jsx(Bs,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:M}),t.jsx(_s,{className:"mt-2 gap-2 pt-1 pb-1",children:T})]})}),t.jsx(ef,{open:e,onOpenChange:s})]})};function Sp(){const e=i.useMemo(()=>ti(),[]),s=i.useRef(!1),n=i.useRef(!1),r=Me(m=>m.setCurrentSession),o=ue(m=>m.setActiveMainTab),a=ue(m=>m.setSettingsDialogOpen),l=ue(m=>m.setSettingsPage),c=ue(m=>m.navigateToDiff),d=i.useCallback(async m=>{if(!n.current){n.current=!0;try{if(m.sessionId){const w=Me.getState().currentSessionId,x=Ds().getState().selectedSessionId;if(m.sessionId!==w||m.sessionId!==x){const g=(e&&typeof window<"u"?new URLSearchParams(window.location.search).get("directory"):null)||Me.getState().getDirectoryForSession(m.sessionId);r(m.sessionId,g)}}if(m.settingsPath){l(Bu(m.settingsPath)),a(!0);return}ue.getState().isSettingsDialogOpen&&a(!1),m.tab&&o(m.tab),m.diffFile&&(m.tab==="diff"||!m.tab)&&c(m.diffFile)}finally{n.current=!1}}},[e,r,o,a,l,c]),u=i.useCallback(()=>{const m=Me.getState(),w=Ds().getState(),x=ue.getState();return{sessionId:m.currentSessionId??w.selectedSessionId,tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),y=i.useCallback((m={})=>{if(e||n.current)return;const w=u();mo(w,m)},[e,u]);i.useEffect(()=>{if(s.current||(s.current=!0,!eo()))return;const m=to();(async()=>(await d(m),e||mo({...u(),sessionId:m.sessionId??Me.getState().currentSessionId??Ds().getState().selectedSessionId,tab:m.tab??ue.getState().activeMainTab,settingsPath:m.settingsPath??ue.getState().settingsPage,diffFile:m.diffFile??ue.getState().pendingDiffFile},{replace:!0,force:!0})))()},[d,u,e]),i.useEffect(()=>{if(e)return;let m=Me.getState().currentSessionId??Ds().getState().selectedSessionId;const w=g=>{!g||g===m||n.current||(m=g,y({replace:!0}))},x=Me.subscribe(g=>{w(g.currentSessionId)}),v=Ds().subscribe(()=>{w(Ds().getState().selectedSessionId)});return()=>{x(),v()}},[e,y]),i.useEffect(()=>{if(e)return;let m=ue.getState().activeMainTab,w=ue.getState().isSettingsDialogOpen,x=ue.getState().settingsPage,v=ue.getState().pendingDiffFile;return ue.subscribe(j=>{if(n.current)return;const C=j.activeMainTab!==m,N=j.isSettingsDialogOpen!==w,b=j.settingsPage!==x,h=j.pendingDiffFile!==v&&j.activeMainTab==="diff";m=j.activeMainTab,w=j.isSettingsDialogOpen,x=j.settingsPage,v=j.pendingDiffFile,(C||N||b||h)&&y()})},[e,y]),i.useEffect(()=>{if(typeof window>"u"||e)return;const m=()=>{const w=to();if(eo())d(w);else{const x=ue.getState();x.isSettingsDialogOpen&&a(!1),x.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",m),()=>{window.removeEventListener("popstate",m)}},[d,e,o,a])}function jp(){const e=yn(n=>n.checkForUpdates),s=i.useRef(e);i.useEffect(()=>{s.current=e},[e]),i.useEffect(()=>{let l=!1,c=null;const d=y=>{const m=Math.round(y*1e3);return Math.max(3e5,Math.min(864e5,m))},u=y=>{l||(c=window.setTimeout(async()=>{const m=await s.current(),w=typeof m=="number"&&Number.isFinite(m)?d(m):36e5;u(w)},y))};return u(3e3),()=>{l=!0,c!==null&&window.clearTimeout(c)}},[])}const Do=12,tf=[{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"}],sf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=tf,onComplete:a})=>{const l=Ue.useRef(!1);Ue.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Ue.useMemo(()=>Array.from({length:Do},(d,u)=>{const y=Math.PI*2*u/Do;return{x:Math.cos(y),y:Math.sin(y),delay:u*18}}),[]);return e?t.jsx("div",{className:F("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((y,m)=>{const w=y.x*d.radius,x=y.y*d.radius,v={"--translate-x":`${w}px`,"--translate-y":`${x}px`,"--particle-delay":`${y.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:v},`${d.id}-${m}-${s}`)})},`${d.id}-${s}`)})}):null},nf=({durationMs:e=3400}={})=>{const[s,n]=Ue.useState({isActive:!1,cycle:0}),r=Ue.useRef(null),o=Ue.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ue.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ue.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Ue.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Ui=i.createContext(void 0),kp=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=nf(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(Ui.Provider,{value:a,children:[e,t.jsx(sf,{isActive:s,burstKey:n})]})},rf={triggerFireworks:()=>{},dismissFireworks:()=>{}},Cp=()=>i.useContext(Ui)??rf,Po=600,of=1,af=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},lf=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:o})=>{const a=i.useRef(new Map),l=i.useRef([]),c=i.useRef(new Set),d=i.useRef(0),u=!1,y=i.useCallback(v=>`${v.directory}
|
|
3
|
-
${v.sessionId}`,[]),m=i.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(v=>window.clearTimeout(v)),a.current.clear()},[]),w=i.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<of&&l.current.length>0;){const v=l.current.shift();if(!v)break;v.generation!==d.current||Me.getState().currentSessionId===v.sessionId||Kl(v.sessionId,v.directory).renderable}},[e,u,o,y]),x=i.useCallback(v=>{const g=v?.id,j=af(v);if(!e||u||!g||!j||g===s||typeof window>"u")return;const C={sessionId:g,directory:j,generation:d.current};y(C)},[s,e,u,w,y]);i.useEffect(()=>{m()},[m,s,e,u]),i.useEffect(()=>{if(!e||u||!s||n.length===0)return;const v=window.setTimeout(()=>{const g=n.findIndex(j=>j.id===s);g<0||(x(n[g-1]),x(n[g+1]))},Po);return()=>window.clearTimeout(v)},[s,e,u,x,n]),i.useEffect(()=>{if(!e||u||!s||r.length===0)return;const v=window.setTimeout(()=>{const g=r.findIndex(j=>j.id===s);g<0||(x(r[g-1]),x(r[g+1]))},Po);return()=>window.clearTimeout(v)},[s,e,u,r,x]),i.useEffect(()=>m,[m])},cf=e=>{const s=Me(n=>n.currentSessionId);return lf({...e,currentSessionId:s}),null},df=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:o,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:y}=e;i.useEffect(()=>{!n||o||!a||l||s.forEach(m=>{if(c.has(m.normalizedPath))return;const w=ai(m.normalizedPath),x=r.archivedSessionsByProject.get(m.id)??[],v=d[w]??[],g=new Map(v.map(j=>[j.name.toLowerCase(),j]));x.forEach(j=>{const C=Gl(j,m.normalizedPath),N=C.toLowerCase();let b=g.get(N);b||(b=u(w,C),g.set(N,b)),b.sessionIds.includes(j.id)||y(w,b.id,j.id)})})},[s,n,r,o,a,l,c,d,u,y])},uf=e=>({getOrderedGroups:i.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];o.forEach(u=>{const y=a.get(u);y&&(l.push(y),a.delete(u))});const c=[],d=[];return r.forEach(u=>{a.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[e])}),ff=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,projectRepoStatus:o,projectRootBranches:a,lastRepoStatus:l,buildGroupedSessions:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:y,buildGroupSearchText:m,foldersMap:w}=e,x=i.useRef(new Map),v=i.useMemo(()=>{const I=x.current,M=new Map;let T=0,O=0;const P=(z,U)=>z.length===U.length&&z.every((ne,se)=>ne===U[se]),B=s.map(z=>{const U=n(z.id),ne=r(z.id),se=o.has(z.id)?!!o.get(z.id):l,K=a.get(z.id)??null,G=I.get(z.id);if(G&&G.project===z&&P(G.activeSessions,U)&&P(G.archivedSessions,ne)&&G.rootBranch===K&&G.isRepo===se&&G.buildGroupedSessions===c)return T+=1,M.set(z.id,G),G.section;O+=1;const R=li([...U,...ne]),A=c(R,z.normalizedPath,[],K,se),V={project:z,groups:A};return M.set(z.id,{project:z,activeSessions:U,archivedSessions:ne,rootBranch:K,isRepo:se,buildGroupedSessions:c,section:V}),V});return x.current=M,T>0&&Zt("ui.sidebar.project_section.reused",T),O>0&&Zt("ui.sidebar.project_section.rebuilt",O),B},[s,n,r,o,l,c,a]),g=i.useMemo(()=>v,[v]),j=i.useMemo(()=>{const I=new WeakMap;if(!d)return I;const M=T=>T.reduce((O,P)=>O+1+M(P.children),0);return g.forEach(T=>{T.groups.forEach(O=>{const P=y(O.sessions,u),B=M(P),z=m(O).includes(u),U=qe(O.directory??null),se=(U?w[U]??[]:[]).filter(K=>K.name.toLowerCase().includes(u)).length;I.set(O,{filteredNodes:P,matchedSessionCount:B,folderNameMatchCount:se,groupMatches:z,hasMatch:z||B>0||se>0})})}),I},[d,g,y,u,m,w]),C=i.useMemo(()=>d?g.map(I=>({...I,groups:I.groups.filter(M=>j.get(M)?.hasMatch===!0)})).filter(I=>I.groups.length>0):g,[d,g,j]),N=d?C:g,b=i.useRef(new WeakMap),h=i.useMemo(()=>{const I=b.current;return N.map(M=>{const T=I.get(M);if(T&&T.query===u)return T.section;const O=M.groups.filter(K=>!K.isArchivedBucket),P=M.groups.filter(K=>K.isArchivedBucket),B=O.flatMap(K=>d?j.get(K)?.filteredNodes??[]:K.sessions),z=O.map(K=>({scopeKey:K.folderScopeKey??qe(K.directory??null),directory:K.directory??null})).filter(K=>!!K.scopeKey),U=O.find(K=>K.isMain)??null,ne={id:"flat",label:U?.label??"",branch:U?.branch??null,description:U?.description??null,isMain:!0,isArchivedBucket:!1,directory:U?.directory??M.project.normalizedPath,folderScopeKey:U?.folderScopeKey??M.project.normalizedPath,folderScopes:z,sessions:B};if(d){const K=O.map(G=>j.get(G)).filter(G=>!!G);j.set(ne,{filteredNodes:B,matchedSessionCount:K.reduce((G,R)=>G+R.matchedSessionCount,0),folderNameMatchCount:K.reduce((G,R)=>G+R.folderNameMatchCount,0),groupMatches:K.some(G=>G.groupMatches),hasMatch:K.some(G=>G.hasMatch)})}const se={project:M.project,groups:[ne,...P]};return I.set(M,{query:u,section:se}),se})},[j,d,u,N]),f=i.useMemo(()=>d?N.reduce((I,M)=>I+M.groups.reduce((T,O)=>{const P=j.get(O);if(!P)return T;const B=P.folderNameMatchCount+(P.groupMatches?1:0);return T+P.matchedSessionCount+B},0),0):0,[d,N,j]);return{projectSections:v,visibleProjectSections:g,groupSearchDataByGroup:j,searchableProjectSections:C,sectionsForRender:N,flatSectionsForRender:h,searchMatchCount:f}},hf=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:y,setSessionSwitcherOpen:m}=e,w=i.useMemo(()=>{const v=new Map,g=new Map,j=(C,N,b,h)=>{v.has(C)||v.set(C,new Map);const f=v.get(C);h.forEach(I=>{const M=qe(I.session.directory??b??N);f.set(I.session.id,{directory:M}),g.has(C)||g.set(C,{id:I.session.id,directory:M}),I.children.length>0&&j(C,N,M,I.children)})};return s.forEach(C=>{C.groups.forEach(N=>{j(C.project.id,C.project.normalizedPath,N.directory,N.sessions)})}),{metaByProject:v,firstSessionByProject:g}},[s]),x=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){x.current=n;return}if(x.current===n)return;const v=s.find(I=>I.project.id===n);if(!v)return;x.current=n;const g=w.metaByProject.get(n);if(a&&g&&g.has(a)){o(I=>{if(I.get(n)===a)return I;const M=new Map(I);return M.set(n,a),M});return}const j=a?Array.from(w.metaByProject.entries()).some(([I,M])=>I!==n&&M.has(a)):!1;if(a&&g&&!j)return;if(!g||g.size===0){y("chat"),d&&m(!1),u({selectedProjectId:v.project.id,directoryOverride:v.project.normalizedPath});return}const C=r.get(n),N=C&&g.has(C)?C:null,b=w.firstSessionByProject.get(n)?.id??null,h=N??b;if(!h||h===a)return;const f=g.get(h)?.directory??null;l(h,f,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,w,y,m,o]),i.useEffect(()=>{if(!n||!a)return;const v=w.metaByProject.get(n);!v||!v.has(a)||o(g=>{if(g.get(n)===a)return g;const j=new Map(g);return j.set(n,a),j})},[n,a,w,o])},mf=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Me(c=>c.currentSessionId),o=Me(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return hf({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},dn=e=>!!e.time?.archived,pf=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=qe(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${l}`.toLowerCase()},[]),r=i.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):a,[n]),o=i.useCallback((a,l,c,d,u)=>{const y=qe(l??null),m=li(a).sort((b,h)=>jn(b,h,e.pinnedSessionIds,e.sessionOrderRanks)),w=new Map(m.map(b=>[b.id,b])),x=new Map;m.forEach(b=>{const h=b.parentID;if(!h)return;const f=w.get(h);if(!f||dn(f)!==dn(b))return;const I=x.get(h)??[];I.push(b),x.set(h,I)}),x.forEach(b=>b.sort((h,f)=>jn(h,f,e.pinnedSessionIds,e.sessionOrderRanks)));const v=b=>{const h=x.get(b.id)??[];return{session:b,children:h.map(f=>v(f)),worktree:null}},g=m.filter(b=>{const h=b.parentID;if(!h)return!0;const f=w.get(h);return f?dn(f)!==dn(b):!0}),j=[],C=[];g.forEach(b=>{const h=v(b);b.time?.archived?C.push(h):j.push(h)});const N=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:y?Hl(y,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:y,folderScopeKey:y,sessions:j}];return C.length>0&&N.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:y?ai(y):null,sessions:C}),N},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},gf=({enabled:e=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{i.useEffect(()=>{if(!e||!s||typeof window>"u")return;const a=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(a)},[e,s,r]),i.useEffect(()=>{if(!e||!s||typeof document>"u")return;const a=l=>{o.current&&(o.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e,s,n,o])},xf=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((b,h,f)=>{ar("navigation.session_select"),ue.getState().closeMainSurfaces();const I=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},M=f?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),b===Me.getState().currentSessionId){e.allowReselect&&M&&e.onSessionSelected?.(b),I();return}ar("navigation.session_state_set"),e.setCurrentSession(b,h??null),M&&e.onSessionSelected?.(b),I()},[e]),a=i.useCallback((b,h)=>{e.setEditingId(b),e.setEditTitle(h)},[e]),l=i.useCallback(async b=>{if(!e.editingId)return;const h=(b??e.editTitle).trim();h&&await e.updateSessionTitle(e.editingId,h),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=i.useCallback(async(b,h)=>{try{return(await nr(b)).ok?(n(h),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=i.useCallback(async b=>{const h=await e.shareSession(b.id);if(!h?.share?.url){oe.error("Unable to share session");return}const f=await d(h.share.url,b.id);oe[f?"success":"warning"]("Session shared",{description:f?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),y=i.useCallback((b,h)=>{d(b,h).then(f=>{f||oe.error("Failed to copy URL")})},[d]),m=i.useCallback(b=>{nr(b).then(h=>{if(h.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),w=i.useCallback(async b=>{await e.unshareSession(b)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),x=i.useCallback(b=>{const h=[],f=I=>{(e.childrenMap.get(I)??[]).forEach(T=>{h.push(T),f(T.id)})};return f(b),h},[e.childrenMap]),v=i.useCallback((b,h)=>h?b:b.filter(f=>!f.time?.archived),[]),g=i.useCallback(async(b,h,f)=>{const I=h?.archivedBucket===!0||h?.hardDelete===!0,M=f?.descendantIds??v(x(b.id),I).map(B=>B.id);if(M.length===0){(I?await e.deleteSession(b.id):await e.archiveSession(b.id))?oe.success(I?"Session deleted":"Session archived"):oe.error(I?"Failed to delete session":"Failed to archive session");return}const T=[b.id,...M];if(I){const{deletedIds:B,failedIds:z}=await e.deleteSessions(T);if(z.length===0){const U=B.length;oe.success(U===1?`Deleted ${U} session`:`Deleted ${U} sessions`)}else oe.error("Failed to delete session");return}const{archivedIds:O,failedIds:P}=await e.archiveSessions(T);O.length>0&&oe.success(O.length===1?`Archived ${O.length} session`:`Archived ${O.length} sessions`),P.length>0&&oe.error(P.length===1?`Failed to archive ${P.length} session`:`Failed to archive ${P.length} sessions`)},[e,x,v]),j=i.useCallback((b,h)=>{const f=h?.archivedBucket===!0||h?.hardDelete===!0,I=v(x(b.id),f).map(M=>M.id);if(!e.showDeletionDialog||h?.skipConfirm===!0){g(b,h,{descendantIds:I});return}e.setDeleteSessionConfirm({session:b,descendantCount:I.length,descendantIds:I,archivedBucket:f})},[e,x,g,v]),C=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:b,archivedBucket:h,descendantIds:f}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await g(b,{archivedBucket:h},{descendantIds:f})},[e,g]),N=i.useCallback(async b=>{await e.unarchiveSession(b.id)?oe.success("Session restored"):oe.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:y,handleCopySessionId:m,handleUnshareSession:w,handleDeleteSession:j,handleRestoreSession:N,confirmDeleteSession:C}},bf=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:a,setCollapsedProjects:l}=e,c=i.useRef(null),d=i.useRef(null),u=i.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:w}=Pt.getState(),x=w.map(v=>({...v,sidebarCollapsed:m.has(v.id)}));gi({projects:x}).catch(()=>{})},[]),y=i.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return i.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),i.useEffect(()=>{try{const m=s.getItem(n.sessionExpanded);if(m){const x=JSON.parse(m);Array.isArray(x)&&a(new Set(x.filter(v=>typeof v=="string")))}const w=s.getItem(n.projectCollapse);if(w){const x=JSON.parse(w);Array.isArray(x)&&l(new Set(x.filter(v=>typeof v=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const m=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(m))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:y}},yf=5*6e4,vf=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=ci(),c=Wl(m=>m.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(m=>{Td(()=>c(m.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const m=new Map;s.forEach(w=>{m.set(w.id,r.get(w.normalizedPath)?.isGitRepo??null)}),o(m)},[n,s,r,o]);const d=i.useMemo(()=>s.map(m=>{const w=r.get(m.normalizedPath)?.branch??"";return`${m.id}:${w}`}).join("|"),[s,r]),u=i.useRef(new Map),y=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let m=!1;const w=setTimeout(()=>{(async()=>{const v=new Set(s.map(b=>b.id));for(const b of u.current.keys())v.has(b)||(u.current.delete(b),y.current.delete(b));const g=Date.now();if(s.filter(b=>{const h=r.get(b.normalizedPath);if(h?.isGitRepo===!1)return u.current.delete(b.id),y.current.delete(b.id),!1;if(h?.isGitRepo!==!0||h.branch===null)return!1;const f=h.branch.trim(),I=`${b.normalizedPath}\0${f}`,M=u.current.get(b.id);if(M===I){const T=y.current.get(b.id);return T&&(T.at=g),!1}return!(M!==void 0&&g-(y.current.get(b.id)?.at??0)<yf)}).length===0)return;const C=[];if(s.forEach(b=>{const h=r.get(b.normalizedPath)?.branch?.trim()??"",f=`${b.normalizedPath}\0${h}`;h&&C.push({id:b.id,inputKey:f,branch:h})}),m||C.length===0)return;const N=Date.now();a(b=>{const h=new Map(b);return C.forEach(({id:f,branch:I})=>{I&&h.set(f,I)}),h}),C.forEach(({id:b,inputKey:h,branch:f})=>{u.current.set(b,h),f&&y.current.set(b,{branch:f,at:N})})})()},150);return()=>{m=!0,clearTimeout(w)}},[n,s,d,r,a])},wf=e=>{const{ownership:s}=e,n=i.useCallback(o=>s.sessionsByProject.get(o)??[],[s]),r=i.useCallback(o=>s.archivedSessionsByProject.get(o)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Sf=e=>{if(e.runtimeKey!==Dn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=Zc(e.sessionId,e.directory,e.runtimeKey);s&&Xc.getState().clearQueue(s),ql.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),Ot.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),di.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),ir.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Ql(e.runtimeKey,e.directory,e.sessionId);n&&Vl(n,!0)},jf=e=>{const s=new Map;for(const n of e){const r=As(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},kf=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},Cf=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Dn(),l=jf(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const d of kf(c,l))Sf({runtimeKey:a,...d});o.current={runtimeKey:a,identities:l}},[s,n,r])},Nf=(e,s)=>e?s.kind!==e.kind?s.kind==="project":s.projectRoot.length!==e.projectRoot.length?s.projectRoot.length>e.projectRoot.length:s.projectId.localeCompare(e.projectId)<0:!0,To=(e,s,n)=>{Nf(e.get(s),n)&&e.set(s,n)},If=e=>{const s=e;return qe(s.directory)??qe(s.project?.worktree)},Df=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const s=e.lastIndexOf("/");return s<0?null:s===0?"/":s===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,s)},Pf=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const x of s){const v=qe(x.normalizedPath);if(!v)continue;const g=a.get(v);(!g||x.id.localeCompare(g.id)<0)&&a.set(v,x),To(o,v,{projectId:x.id,projectRoot:v,scopeDirectory:v,kind:"project"})}if(n)for(const[x,v]of n){const g=qe(x),j=g?a.get(g):void 0;if(!(!j||!g))for(const C of v||[]){const N=qe(C?.path);N&&To(o,N,{projectId:j.id,projectRoot:g,scopeDirectory:N,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,y=new Map,m=x=>{if(!x)return null;if(l.has(x))return l.get(x)??null;const v=[];let g=x,j=null;for(;g;){if(l.has(g)){j=l.get(g)??null;break}if(v.push(g),j=o.get(g)??null,j)break;g=Df(g)}for(const C of v)l.set(C,j);return j},w=(x,v,g)=>{for(const j of x){const C=m(If(j));if(!C)continue;c.set(j.id,C);const N=v.get(C.projectId);if(N?N.push(j):v.set(C.projectId,[j]),!g)continue;const b=g.get(C.scopeDirectory);b?b.add(j.id):g.set(C.scopeDirectory,new Set([j.id]))}};return w(e,d,y),w(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:y,directoryResolutions:l.size}},Tf=e=>{const{enabled:s=!0,isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:o}=e,[a,l]=i.useState(new Set);return i.useEffect(()=>{if(!s||!n){l(y=>y.size===0?y:new Set);return}const d=Array.from(o.current.values()).find(y=>y!==null)?.closest(".oc-sidebar-scroller")??null;if(!d)return;const u=new IntersectionObserver(y=>{l(m=>{const w=new Set(m);let x=!1;for(const v of y){const g=v.target.dataset.projectId;if(!g)continue;const j=v.rootBounds?.top??d.getBoundingClientRect().top,C=!v.isIntersecting&&v.boundingClientRect.top<j;w.has(g)!==C&&(x=!0,C?w.add(g):w.delete(g))}return x?w:m})},{root:d,threshold:0});return o.current.forEach(y=>{y&&u.observe(y)}),()=>u.disconnect()},[s,n,o,r]),a},Ef=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(os,{open:e,onOpenChange:s,children:t.jsx(is,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(ps,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:t.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&n?t.jsx(Tu,{project:n,onIdentitySave:r}):null})})})});function Ki({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:F("inline-flex items-center",r),"aria-label":n??s,title:n??s,children:t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):t.jsx("span",{className:F("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Mf=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:y,groupDirectory:m,projectId:w,mobileVariant:x=!1,alwaysShowActions:v=x,isRenaming:g=!1,renameDraft:j="",onRenameDraftChange:C,onRenameSave:N,onRenameCancel:b,droppableRef:h,isDropTarget:f=!1,onNewSession:I,depth:M=0,hideActions:T=!1,archivedBucket:O=!1})=>{const[P,B]=i.useState(!1),[z,U]=i.useState(""),ne=i.useRef(null),se=g||P,K=g?j:z,G=i.useCallback(()=>{U(e.name),B(!0)},[e.name]),R=i.useCallback(()=>{const $=K.trim();$&&$!==e.name&&c($),g&&N&&N(),B(!1),U("")},[K,e.name,g,c,N]),A=i.useCallback(()=>{g&&b&&b(),B(!1),U("")},[g,b]),V=i.useCallback($=>{g&&C?C($):U($)},[g,C]);i.useEffect(()=>{if(!g)return;const $=()=>{const _e=ne.current;_e&&(_e.focus(),_e.select())},ke=requestAnimationFrame($),Ie=window.setTimeout($,0);return()=>{cancelAnimationFrame(ke),window.clearTimeout(Ie)}},[g]);const le=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:h,className:F("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",f&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:se?void 0:$=>{$.currentTarget.blur(),l()},role:se?void 0:"button",tabIndex:se?void 0:0,onKeyDown:se?void 0:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:F("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",O?v?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":v?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(k,{name:le,className:F(gn,f?"text-primary":"text-muted-foreground")}),se?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onSubmit:$=>{$.preventDefault(),R()},children:[t.jsx("input",{ref:ne,value:K,onChange:$=>V($.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:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onKeyDown:$=>{if($.key==="Escape"){$.stopPropagation(),A();return}($.key===" "||$.key==="Enter")&&$.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),children:t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),A()},onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("span",{className:F(ui,f?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(st,{side:"right",sideOffset:8,className:"max-w-xs",children:s??e.name})]}),t.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),a?t.jsx(Ki,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(k,{name:"arrow-right-s",className:F(gn,"text-muted-foreground")}):t.jsx(k,{name:"arrow-down-s",className:F(gn,"text-muted-foreground")})]})]}),!se&&(!T||O)?t.jsx("div",{className:F("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",v?"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:t.jsxs("div",{className:"flex items-center gap-0.5",children:[!O&&I?t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),I()},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:t.jsx(k,{name:"add",className:"size-4"})}):null,O?null:t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),G()},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:t.jsx(k,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":O?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(k,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map($=>t.jsx(i.Fragment,{children:u($,0,m??null,w??null,O,void 0,"project",y?.($))},$.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Af=i.memo(Mf),Rf=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=yd({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),d=i.useCallback(u=>{u.stopPropagation(),a?.onPointerDown&&a.onPointerDown(u)},[a]);return t.jsx("div",{ref:l,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Ff=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=vd({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},Lf=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=Pn(qs(kr,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,d]=i.useState("Session"),[u,y]=i.useState(null),[m,w]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const x=v=>{l(null),y(null),w(null);const{active:g,over:j}=v;if(!j)return;const C=g.data.current,N=j.data.current;C?.type==="session"&&C.sessionId&&N?.type==="folder"&&N.folderId&&n(C.sessionId,N.folderId)};return t.jsxs(Tn,{sensors:o,collisionDetection:En,onDragStart:v=>{const g=v.active.data.current;if(g?.type==="session"&&g.sessionId){l(g.sessionId),d(g.sessionTitle??"Session");const j=v.active.rect.current.initial?.width,C=v.active.rect.current.initial?.height;y(typeof j=="number"?j:null),w(typeof C=="number"?C:null)}},onDragCancel:()=>{l(null),y(null),w(null)},onDragEnd:x,children:[r,t.jsx(ji,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:m?`${m}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[t.jsx(k,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),t.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},vn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),o=r.length;if(o===0)return e;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(e.slice(l,c));const d=e.slice(c,c+o);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e},gs=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:F(o?Yl:Jl,r),children:[t.jsx(k,{name:e,className:F(Hs(o),"text-muted-foreground")}),t.jsx("span",{className:F(Ws(o),"flex-1 text-muted-foreground"),children:s})]}),Eo=(e,s,n)=>{if(!s)return;const r=o=>{let a=o.session.id===s;for(const l of o.children)a=r(l)||a;return a&&n.add(o.session.id),a};for(const o of e)r(o)},ns=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(ns(n,s))return!0;return!1},Of=(e,s,n)=>{const r=new Map,o=a=>{const l=As(a.session)??n;if(l){const c=r.get(l)??[];c.push(a.session.id),r.set(l,c)}if(!(a===e&&s))for(const c of a.children)o(c)};return o(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},Bf=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let a=r.session.parentID??null;for(;a&&!o.has(a);){if(n.has(a)&&s.has(a))return!1;o.add(a),a=s.get(a)?.session?.parentID??null}return!0})},Mo=new WeakMap;let Ao=1;const _f=e=>{const s=Mo.get(e);if(s!==void 0)return s;const n=Ao;return Ao+=1,Mo.set(e,n),n},mr=e=>e.children.length===0?"":e.children.map(n=>{const r=_f(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${mr(n)}`}).join("|"),Gi=(e,s,n,r,o,a)=>{const l=Dn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const y=d.session.directory??o,m=u.session.directory??a,w=so(l,y??"",d.session.id),x=so(l,m??"",u.session.id);return(w?n.has(w):!1)!==(x?r.has(x):!1)?!0:d.children.some((v,g)=>c(v,u.children[g]))};return c(e,s)},Nn=(e,s,n,r)=>{if(!s)return null;const o=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${o}:${c.session.id}`===s)return a=c.session.id,!0;for(const u of c.children)if(l(u))return!0;return!1};return e.forEach(c=>l(c)),a},Hi=(e,s)=>"",Np=ws(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),$f=e=>null,Pr=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Wi=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let o=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(o="unread");for(const l of e.children)if(o=Pr(o,Wi(l,s,n,r)),o==="active")return o;return o},Ro=(e,s,n,r)=>{let o=null;for(const a of e)if(o=Pr(o,Wi(a,s,n,r)),o==="active")return o;return o},zf=50,Uf=28,un=(e,s)=>s?e.sessions.some(n=>ns(n,s)):!1,Kf=(e,s,n)=>e.sessions.some(r=>Gi(r,r,s,n,e.directory,e.directory)),Gf=(e,s,n)=>{const r=o=>{const a=o.session.id;return s.get(a)!==n.get(a)?!0:o.children.some(r)};return e.sessions.some(r)},Fo=(e,s,n)=>{const r=o=>s.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Hf=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},Wf=(e,s,n)=>{const r=e.isArchivedBucket?"archived":"active",o=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(o)};return e.sessions.some(o)},qf=(e,s)=>{if(e.group!==s.group||e.groupKey!==s.groupKey||e.projectId!==s.projectId||e.hideGroupLabel!==s.hideGroupLabel||e.compactBodyPadding!==s.compactBodyPadding||e.groupSearchDataByGroup!==s.groupSearchDataByGroup||e.visibleSessionCount!==s.visibleSessionCount||e.collapsedGroups!==s.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==s.collapsedGroups.has(s.groupKey)||e.pinnedSessionIds!==s.pinnedSessionIds&&Kf(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&Wf(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&Gf(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(un(e.group,e.editingId)||un(s.group,s.editingId))||e.editTitle!==s.editTitle&&(un(e.group,e.editingId)||un(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Nn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Nn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Fo(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Fo(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&Hf(s.group,s.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===s.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===s.normalizedSessionSearchQuery&&e.hideDirectoryControls===s.hideDirectoryControls&&e.collapsedFolderIds===s.collapsedFolderIds&&e.toggleFolderCollapse===s.toggleFolderCollapse&&e.renameFolder===s.renameFolder&&e.deleteFolder===s.deleteFolder&&e.showDeletionDialog===s.showDeletionDialog&&e.setDeleteFolderConfirm===s.setDeleteFolderConfirm&&e.renderSessionNode===s.renderSessionNode&&e.showMoreGroupSessions===s.showMoreGroupSessions&&e.resetGroupSessionLimit===s.resetGroupSessionLimit&&e.mobileVariant===s.mobileVariant&&e.alwaysShowActions===s.alwaysShowActions&&e.activeProjectId===s.activeProjectId&&e.setActiveProjectIdOnly===s.setActiveProjectIdOnly&&e.setActiveMainTab===s.setActiveMainTab&&e.setSessionSwitcherOpen===s.setSessionSwitcherOpen&&e.openNewSessionDraft===s.openNewSessionDraft&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.renamingFolderId===s.renamingFolderId&&e.renameFolderDraft===s.renameFolderDraft&&e.setRenameFolderDraft===s.setRenameFolderDraft&&e.setRenamingFolderId===s.setRenamingFolderId&&e.onToggleCollapsedGroup===s.onToggleCollapsedGroup&&e.dragHandleProps===s.dragHandleProps&&e.scrollContainerRef===s.scrollContainerRef};function Qf(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:y,collapsedFolderIds:m,toggleFolderCollapse:w,renameFolder:x,deleteFolder:v,showDeletionDialog:g,setDeleteFolderConfirm:j,renderSessionNode:C,showMoreGroupSessions:N,resetGroupSessionLimit:b,mobileVariant:h,alwaysShowActions:f,activeProjectId:I,setActiveProjectIdOnly:M,setActiveMainTab:T,setSessionSwitcherOpen:O,openNewSessionDraft:P,addSessionToFolder:B,createFolderAndStartRename:z,renamingFolderId:U,renameFolderDraft:ne,setRenameFolderDraft:se,setRenamingFolderId:K,pinnedSessionIds:G,expandedParents:R,sessionOrderIndex:A,editingId:V,openSidebarMenuKey:le,activeActivitySessionIds:$,unreadActivitySessionIds:ke,notifyOnSubtasks:Ie,onToggleCollapsedGroup:_e,dragHandleProps:Ge,compactBodyPadding:Fe=!1,scrollContainerRef:ve}=e,Pe=i.useCallback((L,q)=>{const ee=A.get(L.session.id),te=A.get(q.session.id);if(ee!==void 0||te!==void 0){if(ee===void 0)return 1;if(te===void 0)return-1;if(ee!==te)return ee-te}return jn(L.session,q.session,G,fi)},[G,A]),me=a?c.get(s):null,He=Ot(L=>L.foldersMap),we=a?!1:u.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const L=qe(s.directory??null),q=s.branch?.trim();return L&&q?Hi():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const xe=hi(),Ce=i.useMemo(()=>{const L=s.folderScopes?.map(q=>qe(q.directory))??[qe(s.directory??null)];return[...new Set(L.filter(q=>!!q))]},[s.directory,s.folderScopes]);i.useSyncExternalStore(i.useCallback(L=>Ce.length>0?xe.subscribeBootstrap(L):()=>{},[Ce.length,xe]),i.useCallback(()=>Ce.map(L=>`${L}\0${xe.getBootstrapState(L)??""}\0${xe.getBootstrapFailure(L)??""}`).join(""),[Ce,xe]),i.useCallback(()=>"",[]));const Qe=Ce.some(L=>{const q=xe.getBootstrapState(L);return q==="queued"||q==="running"}),Be=Ce.find(L=>xe.getBootstrapState(L)==="failed")??null,W=Be?xe.getBootstrapFailure(Be):void 0,H=W==="os-permission"&&wr(),[ie,pe]=i.useState(!1),Se=i.useCallback(()=>{Be&&xe.requestBootstrap({directory:Be,priority:we?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[xe,Be,s.isMain,we]),Y=i.useCallback(async()=>{if(!(!Be||!H||ie)){pe(!0);try{(await Sr(Be)).success&&Se()}finally{pe(!1)}}},[H,Be,ie,Se]),be=y?10:5,de=Math.max(be,d??be),Ve=a?me?.groupMatches===!0:!1,at=a,ze=i.useMemo(()=>[...at?me?.filteredNodes??[]:s.sessions].sort(Pe),[Pe,s.sessions,me?.filteredNodes,at]),je=s.folderScopeKey??qe(s.directory??null),Ae=i.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:je?[{scopeKey:je,directory:s.directory??null}]:[],[je,s.directory,s.folderScopes]),ot=i.useMemo(()=>Ae.flatMap(({scopeKey:L,directory:q})=>(He[L]??[]).map(ee=>({folder:ee,scopeKey:L,scopeDirectory:q}))),[Ae,He]),ht=i.useMemo(()=>{const L=new Map,q=ee=>{ee.forEach(te=>{L.set(te.session.id,te),te.children.length>0&&q(te.children)})};return q(ze),L},[ze]),pt=i.useMemo(()=>ot.map(({folder:L,scopeKey:q,scopeDirectory:ee})=>{const te=Bf(L.sessionIds,ht).sort(Pe);return{folder:L,scopeKey:q,scopeDirectory:ee,nodes:te}}),[ot,ht,Pe]),ge=i.useMemo(()=>{const L=new Map(pt.map(re=>[re.folder.id,re])),q=new Map;for(const{folder:re}of pt){if(!re.parentId)continue;const rt=q.get(re.parentId);rt?rt.push(re.id):q.set(re.parentId,[re.id])}const ee=new Map,te=re=>{const rt=ee.get(re);if(rt!==void 0)return rt;const wt=L.get(re);if(!wt)return ee.set(re,!1),!1;const St=q.get(re)??[];if(s.isArchivedBucket&&wt.nodes.length===0){const jt=St.some(cs=>te(cs));return ee.set(re,jt),jt}if(!a||wt.folder.name.toLowerCase().includes(l)||wt.nodes.length>0)return ee.set(re,!0),!0;const es=St.some(jt=>te(jt));return ee.set(re,es),es};return pt.filter(({folder:re})=>te(re.id))},[pt,s.isArchivedBucket,a,l]),Ye=i.useMemo(()=>new Set(ge.flatMap(L=>L.folder.sessionIds)),[ge]),Tt=i.useMemo(()=>ze.filter(L=>!Ye.has(L.session.id)),[ze,Ye]),S=i.useMemo(()=>ge.filter(({folder:L})=>!L.parentId),[ge]),Z=i.useMemo(()=>{const L=new Map;return ge.forEach(q=>{if(!q.folder.parentId)return;const ee=L.get(q.folder.parentId)??[];ee.push(q),L.set(q.folder.parentId,ee)}),L},[ge]),ae=i.useMemo(()=>{const L=new Map(ge.map(te=>[te.folder.id,te])),q=new Map,ee=(te,re)=>{const rt=q.get(te);if(rt!==void 0)return rt;if(re.has(te))return null;re.add(te);const wt=L.get(te);let St=wt?Ro(wt.nodes,$,ke,Ie):null;for(const Ut of Z.get(te)??[])if(St=Pr(St,ee(Ut.folder.id,re)),St==="active")break;return q.set(te,St),St};return ge.forEach(({folder:te})=>ee(te.id,new Set)),q},[$,ge,Z,Ie,ke]),ye="project",Re=i.useMemo(()=>{const L=new Set;return Eo(ze,V,L),ge.forEach(({nodes:q})=>{Eo(q,V,L)}),L},[ze,ge,V]),Ke=i.useMemo(()=>{if(!le)return null;const L=Nn(ze,le,ye,!!s.isArchivedBucket);if(L)return L;for(const{nodes:q}of ge){const ee=Nn(q,le,ye,!!s.isArchivedBucket);if(ee)return ee}return null},[le,ze,ge,s.isArchivedBucket]),nt=i.useCallback(L=>{const q=new WeakMap,ee=te=>{q.set(te,mr(te));for(const re of te.children)ee(re)};return L.forEach(ee),q},[]),ct=i.useMemo(()=>nt(ze),[nt,ze]),Gt=i.useMemo(()=>{const L=new WeakMap;return ge.forEach(({nodes:q})=>{q.forEach(ee=>L.set(ee,mr(ee)))}),L},[ge]),it=i.useCallback(L=>ct.get(L)??Gt.get(L)??"",[ct,Gt]),gt=i.useCallback(L=>({subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(L)}),[Re,Ke,it]),yt=Tt.length,Je=s.isArchivedBucket||a?Tt:Tt.slice(0,de),Bt=yt-Je.length,_t=!s.isArchivedBucket&&!a&&yt>be&&Bt===0,Et=s.isArchivedBucket===!0&&!a&&Je.length>=zf,xt=s.isArchivedBucket?"archived":"active",Mt=Et&&Je.some(L=>{if(L.children.length===0)return!1;const q=`project:${xt}:${L.session.id}`;return R.has(q)}),D=i.useRef(null),[fe,Ne]=i.useState(null),[Le,We]=i.useState(0),[,kt]=i.useState(0);i.useEffect(()=>{if(!Et)return;const L=D.current;if(!L||typeof ResizeObserver>"u")return;const q=new ResizeObserver(()=>kt(ee=>ee+1));return q.observe(L),()=>q.disconnect()},[Et]),i.useLayoutEffect(()=>{if(!Et){fe!==null&&Ne(null),Le!==0&&We(0);return}const L=D.current;if(!L)return;let q=fe;const ee=ve?.current??null;if(ee&&ee.contains(L)){if(q=ee,q!==fe){Ne(q);return}}else if(!q||!q.contains(L)){let re=L.parentElement;for(;re;){const rt=window.getComputedStyle(re);if(rt.overflowY==="auto"||rt.overflowY==="scroll"){q=re;break}re=re.parentElement}if(q!==fe){Ne(q);return}}if(!q)return;const te=L.getBoundingClientRect().top-q.getBoundingClientRect().top+q.scrollTop;We(re=>Math.abs(re-te)<1?re:te)});const E=Et&&fe!==null,X=bd({count:Je.length,enabled:E,getScrollElement:()=>fe,initialOffset:()=>fe?.scrollTop??0,estimateSize:()=>Uf,overscan:Mt?20:8,scrollMargin:Le,getItemKey:L=>Je[L]?.session.id??L}),ce=i.useCallback(L=>{const q=[],ee=te=>{te.forEach(re=>{q.push(re.session),re.children.length>0&&ee(re.children)})};return ee(L),q},[]),$e=i.useMemo(()=>ce(ze),[ce,ze]),he=i.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const L=new Map,q=new Map;for(const{folder:te}of ge){if(!te.parentId)continue;const re=q.get(te.parentId)??[];re.push(te.id),q.set(te.parentId,re)}const ee=(te,re)=>{if(re.has(te))return[];re.add(te);const rt=ge.find(({folder:Ut})=>Ut.id===te),wt=rt?ce(rt.nodes):[],St=q.get(te)??[];for(const Ut of St)wt.push(...ee(Ut,re));return wt};for(const{folder:te}of ge)L.set(te.id,ee(te.id,new Set));return L},[ge,ce,s.isArchivedBucket]);if(a&&!Ve&&S.length===0&&Tt.length===0)return null;const Te=!s.isMain&&!!s.branch,lt=s.branch&&Zl(s.branch,s.label)?{label:s.branch}:null,vt=we?Ro(ze,$,ke,Ie):null,$t=vt?t.jsx(Ki,{state:vt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Ft=(L,q)=>{const{folder:ee,scopeKey:te,scopeDirectory:re,nodes:rt}=L,wt=he.get(ee.id)??[],St=a?!1:m.has(ee.id);return t.jsx(Ff,{folderId:ee.id,children:(Ut,es)=>t.jsx(Af,{folder:ee,displayName:q,sessions:rt,isCollapsed:St,collapsedActivityState:St?ae.get(ee.id)??null:null,onToggle:()=>w(ee.id),onRename:jt=>{x(te,ee.id,jt)},onDelete:()=>{if(s.isArchivedBucket){bs.requestDelete({sessions:wt,mode:"session"});return}if(!g){v(te,ee.id);return}const jt=ge.filter(({folder:Ss})=>Ss.parentId===ee.id).length,cs=rt.length;j({scopeKey:te,folderId:ee.id,folderName:ee.name,subFolderCount:jt,sessionCount:cs})},renderSessionNode:C,getRenderExtras:it?jt=>({subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(jt),childRenderExtrasFor:gt}):void 0,groupDirectory:re??s.directory,projectId:r,mobileVariant:h,alwaysShowActions:f,isRenaming:U===ee.id,renameDraft:U===ee.id?ne:void 0,onRenameDraftChange:jt=>se(jt),onRenameSave:()=>{const jt=ne.trim();jt&&x(te,ee.id,jt),K(null),se("")},onRenameCancel:()=>{K(null),se("")},droppableRef:Ut,isDropTarget:es,depth:0,onNewSession:()=>{r&&r!==I&&M(r),T("chat"),h&&O(!1),P({selectedProjectId:r,directoryOverride:re??s.directory,targetFolderId:ee.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},ee.id)},Ht=()=>{const L=new Map;for(const te of ge){const re=te.folder.parentId;if(!re)continue;const rt=L.get(re);rt?rt.push(te):L.set(re,[te])}const q=[],ee=(te,re)=>{const rt=re?`${re} / ${te.folder.name}`:te.folder.name;q.push(Ft(te,rt)),!(!a&&m.has(te.folder.id))&&(L.get(te.folder.id)??[]).forEach(St=>ee(St,rt))};return S.forEach(te=>ee(te,"")),q},zt=f?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",mt=Be?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[W==="os-permission"?"Folder access is required.":"Could not refresh sessions.",H?t.jsx(Ee,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:ie,onClick:()=>{Y()},children:"Grant access"}):null,t.jsx(Ee,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:Se,children:"Try again"})]}):null,Lt=t.jsxs(Lf,{scopeKey:Ae[0]?.scopeKey??je,hasFolders:ge.length>0,onSessionDroppedOnFolder:(L,q)=>{const ee=ge.find(({folder:re})=>re.id===q);if(!ee)return;const te=Ot.getState();for(const{scopeKey:re}of Ae)re!==ee.scopeKey&&te.getSessionFolderId(re,L)&&te.removeSessionFromFolder(re,L);B(ee.scopeKey,q,L)},children:[Ht(),Et?t.jsx("div",{ref:D,children:E?t.jsx("div",{style:{height:X.getTotalSize(),position:"relative"},children:X.getVirtualItems().map(L=>{const q=Je[L.index];return q?t.jsx("div",{"data-index":L.index,ref:X.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${L.start-Le}px)`},children:C(q,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(q),childRenderExtrasFor:gt})},q.session.id):null})}):Je.map(L=>t.jsx(i.Fragment,{children:C(L,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(L),childRenderExtrasFor:gt})},L.session.id))}):Je.map(L=>t.jsx(i.Fragment,{children:C(L,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Re,menuOpenSessionId:Ke,nodeStructureKey:it(L),childRenderExtrasFor:gt})},L.session.id)),yt===0&&ge.length===0?s.isArchivedBucket?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):Qe?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:t.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[t.jsx(k,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):mt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:mt}):t.jsx(gs,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,yt>0&&mt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:mt}):null,Bt>0?t.jsx(gs,{icon:"arrow-down-s",onClick:()=>N(n,Je.length),children:Bt===1?"Show 1 more session":`Show ${Bt} more sessions`}):null,_t?t.jsx(gs,{icon:"arrow-up-s",onClick:()=>b(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:Lt})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:F("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>_e(n),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),_e(n))},"aria-label":we?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!we,children:[t.jsx("div",{ref:Ge?.setActivatorNodeRef,className:F("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",zt),...Ge?.listeners??{},children:t.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[t.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:s.isArchivedBucket?t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(k,{name:"archive",className:F("size-4 shrink-0 text-muted-foreground",f?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:F("text-muted-foreground size-4 items-center justify-center",f?"inline-flex":"hidden group-hover/gh:inline-flex"),children:we?t.jsx(k,{name:"arrow-right-s",className:"size-4"}):t.jsx(k,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:vn(s.label,l)}),$t]}):!s.isMain||s.worktree?t.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(k,{name:"git-branch",className:F("size-4 shrink-0","text-muted-foreground",f?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:F("text-muted-foreground size-4 items-center justify-center",f?"inline-flex":"hidden group-hover/gh:inline-flex"),children:we?t.jsx(k,{name:"arrow-right-s",className:"size-4"}):t.jsx(k,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:vn(s.label,l)}),$t,null]}):t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"min-w-0 truncate",children:vn(s.label,l)}),$t]})}),Te&<?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[s.isArchivedBucket?t.jsx(k,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(k,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),t.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:lt.label})]}):null]})}),s.isArchivedBucket&&$e.length>0?t.jsx("div",{className:F("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",f?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),bs.requestDelete({sessions:$e,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${s.label}`,children:t.jsx(k,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,s.directory?t.jsx("div",{className:F("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",f?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),r&&r!==I&&M(r),T("chat"),h&&O(!1),P({selectedProjectId:r,directoryOverride:s.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 ${s.label}`,children:t.jsx(k,{name:"add",className:"h-4 w-4"})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]}),we?null:t.jsx("div",{className:"oc-group-body",children:Lt})]})}const Vf=i.memo(Qf,qf);function Yf(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:y,setIsSessionSearchOpen:m,sessionSearchInputRef:w,sessionSearchQuery:x,setSessionSearchQuery:v,hasSessionSearchQuery:g,searchMatchCount:j,selectionModeEnabled:C,onToggleSelectionMode:N,mobileVariant:b=!1}=e;if(s)return null;const h=F(u,"text-muted-foreground hover:text-foreground",!b&&"hover:bg-transparent");return t.jsx("div",{className:F("select-none flex-shrink-0",b?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:F("flex flex-col",b?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:F("flex items-center justify-between",b?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:F("flex min-w-0 items-center",b?"gap-0.5 overflow-x-auto":"gap-1.5"),children:[o?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:h,"aria-label":"Settings",children:t.jsx(k,{name:"settings-3",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,a?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:h,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(k,{name:"server",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:h,"aria-label":"Update",children:t.jsx(k,{name:"download",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:h,"aria-label":"Add project",children:t.jsx(k,{name:"folder-add",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:h,"aria-label":"Archive",children:t.jsx(k,{name:"archive",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:F("flex shrink-0 items-center",b?"gap-0.5":"gap-1.5"),children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>m(f=>!f),className:h,"aria-label":"Search sessions","aria-expanded":y,children:t.jsx(k,{name:"search",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:N,className:F(h,C&&"bg-interactive-hover text-primary"),"aria-label":C?"Exit selection":"Select sessions","aria-pressed":C,children:t.jsx(k,{name:"checkbox-multiple",className:d})})}),t.jsx(st,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:C?"Exit selection":"Select sessions"})})]})]})]}),y?t.jsxs("div",{className:F(b?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:g?t.jsx("span",{children:j===1?`${j} match`:`${j} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(k,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{ref:w,value:x,onChange:f=>v(f.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:f=>{f.key==="Escape"&&(f.stopPropagation(),g?v(""):m(!1))}}),x.length>0?t.jsx("button",{type:"button",onClick:()=>v(""),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:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function Jf(e){const s=ue(o=>o.toggleSidebar),n=ue(o=>o.shortcutOverrides),r=Xl(ec("toggle_sidebar",n));return t.jsx("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",style:{paddingLeft:`max(${no}, var(--oc-titlebar-left-inset, ${no}), var(--oc-titlebar-overlay-width, 0px))`},children:t.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsxs("button",{type:"button",onClick:e.onNewSession,className:F("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] 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"),children:[t.jsx(k,{name:"chat-new",className:F(gn,"text-current")}),t.jsx("span",{className:ui,children:"New session"})]}),e.showSidebarToggle?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,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:t.jsx(k,{name:"layout-left",className:"size-4"})})}),t.jsx(st,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})})}const Zf=500,Xf=({project:e,label:s,isSelected:n,hasActive:r,canDrag:o,onSelect:a,onOpenProjectEditDialog:l,onRemoveProject:c,mobileVariant:d=!1})=>{const{attributes:u,listeners:y,setNodeRef:m,transform:w,transition:x,isDragging:v}=Mn({id:e.id,disabled:!o}),[g,j]=i.useState(!1),C=i.useRef(null),N=i.useCallback(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null)},[]);i.useEffect(()=>()=>N(),[N]);const b=i.useCallback(()=>{N(),C.current=window.setTimeout(()=>{C.current=null,j(!0)},Zf)},[N]);return t.jsx("div",{ref:m,style:{transform:An.Translate.toString(w),transition:x},className:F(v&&"opacity-60"),children:t.jsxs(Eu,{open:g,onOpenChange:j,children:[t.jsxs(Mu,{render:t.jsx("button",{type:"button",onClick:()=>{g||a()},onTouchStart:b,onTouchMove:N,onTouchEnd:N,onTouchCancel:N,className:F("relative flex w-full items-center justify-between rounded-xl px-3 py-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",n?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:F("inline-flex shrink-0 items-center justify-center",o&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":o?`Reorder ${s}`:void 0,...o?{...u,...y}:{},children:t.jsx(k,{name:"folder",className:F(Hs(d),"text-muted-foreground")})}),t.jsx("span",{className:Ws(d),children:s})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsxs(Au,{className:"min-w-[160px]",children:[t.jsxs(Co,{onClick:()=>l(e.id),children:[t.jsx(k,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(Ru,{}),t.jsxs(Co,{onClick:()=>c(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(k,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},eh=({projects:e,selectedProjectId:s,onSelectProject:n,onOpenDirectoryDialog:r,onOpenProjectEditDialog:o,onRemoveProject:a,hasActiveSessionByProject:l,homeDirectory:c,className:d,mobileVariant:u=!1})=>{const y=s===null,m=Pt(g=>g.reorderProjects),w=e.length>1,x=Pn(qs(Sd,{activationConstraint:{distance:8}}),qs(wd,{activationConstraint:{delay:200,tolerance:6}})),v=i.useCallback(g=>{const{active:j,over:C}=g;if(!C||j.id===C.id)return;const N=Pt.getState().projects,b=N.findIndex(f=>f.id===j.id),h=N.findIndex(f=>f.id===C.id);b<0||h<0||m(b,h)},[m]);return t.jsxs("div",{className:F("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",d),children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:F("group relative flex w-full items-center justify-between rounded-xl px-3 py-2 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",y?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),"aria-pressed":y,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(k,{name:"folder",className:Hs(u)}),t.jsx("span",{className:Ws(u),children:"All Folders"})]})}),t.jsx(Tn,{sensors:x,collisionDetection:En,onDragEnd:v,children:t.jsx(Cr,{items:e.map(g=>g.id),strategy:ki,children:e.map(g=>{const j=s===g.id,C=In(g.label?.trim()||xs(g.normalizedPath,c)||g.normalizedPath);return t.jsx(Xf,{project:g,label:C,isSelected:j,hasActive:l?.(g.id),canDrag:w,onSelect:()=>n(j?null:g.id),onOpenProjectEditDialog:o,onRemoveProject:a,mobileVariant:u},g.id)})})}),t.jsxs("button",{type:"button",onClick:r,className:F("flex w-full items-center gap-1.5 rounded-xl px-3 py-2 typography-ui-label text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"),children:[t.jsx(k,{name:"add",className:Hs(u)}),t.jsx("span",{className:Ws(u),children:"Add folder"})]})]})},Wn="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 th({onOpenSettings:e,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:a=!0}){return!o&&!a?null:t.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?t.jsxs(t.Fragment,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:Wn,"aria-label":"Settings",children:t.jsx(k,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:Wn,"aria-label":"Shortcuts",children:t.jsx(k,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:Wn,"aria-label":"About PiChamber",children:t.jsx(k,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Ee,{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 sh=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},Lo=ws()(jr(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(s=>({stickyZoneHeaders:!s.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:s=>e({showRecentSection:s}),setShowArchivedSessions:s=>e({showArchivedSessions:s}),toggleRecentSection:()=>e(s=>({showRecentSection:!s.showRecentSection})),toggleArchivedSessions:()=>e(s=>({showArchivedSessions:!s.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:sh})),nh=({projectLabel:e,isCollapsed:s,alwaysShowActions:n=!1,mobileVariant:r=!1})=>{const o=s!==void 0,a=o?n?"hidden":"group-hover/project:hidden group-focus-within/project:hidden":void 0,l=Hs(r),c=Ws(r);return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:F("inline-flex shrink-0 items-center justify-center",l),children:[o?t.jsx("span",{className:F("items-center justify-center text-muted-foreground",l,n?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:t.jsx(k,{name:s?"arrow-right-s":"arrow-down-s",className:l})}):null,t.jsx(k,{name:"folder",className:F(l,"text-muted-foreground/80",a)})]}),t.jsx("span",{className:F(c,"text-foreground"),children:e})]})},rh=({id:e,disabled:s=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=Mn({id:e,disabled:s}),u=i.useMemo(()=>({listeners:r,setActivatorNodeRef:a}),[r,a]);return t.jsx("div",{ref:o,style:{transform:An.Transform.toString(l),transition:c},className:F("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};i.memo(rh);const oh=48,ih=32,ah=24,Oo=(e,s)=>In(e.label?.trim()||xs(e.normalizedPath,s)||e.normalizedPath);function lh(e){Zt("ui.sidebar_projects_list.render");const s=e.isDesktopShellRuntime&&e.stickyZoneHeaders,n=i.useRef(new Map),r=i.useRef(e.getOrderedGroups);r.current!==e.getOrderedGroups&&(r.current=e.getOrderedGroups,n.current.clear());const o=(N,b)=>{const h=n.current,f=h.get(N);if(f&&f.groups===b)return f.ordered;const I=e.getOrderedGroups(N,b);if(h.set(N,{groups:b,ordered:I}),h.size>256){const M=h.keys().next().value;M!==void 0&&h.delete(M)}return I},a=i.useRef(null),l=i.useRef(0),c=i.useCallback(N=>{const h=N.scrollTop>1?Math.min(ih+N.scrollTop,oh):0;l.current=h,N.style.setProperty("--scroll-shadow-top-size",`${h}px`),N.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(h-8,0),ah)}px`)},[]),d=i.useCallback(N=>{N.target.closest("[data-overlay-scrollbar-thumb], [data-sidebar-sticky-header]")||N.clientY-N.currentTarget.getBoundingClientRect().top>=l.current||(N.preventDefault(),N.stopPropagation())},[]),u=e.projectSections.length>0&&e.sectionsForRender.length>0;i.useLayoutEffect(()=>{s&&u&&a.current&&c(a.current)},[s,u,c]);let y=null;for(const N of e.projectSections)e.stuckProjectHeaders.has(N.project.id)&&(y=N.project);const m=y??(e.hasSharedSessions?null:e.sectionsForRender[0]?.project??null),w=m?Oo(m,e.homeDirectory):null,x=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const N=[];for(const b of e.sectionsForRender){const h=Oo(b.project,e.homeDirectory);for(const f of b.groups)if(!f.isArchivedBucket)for(const I of f.sessions){const M=!!e.pinnedSessionIds?.has(I.session.id),T=I.session.time?.updated||I.session.time?.created||0;N.push({node:I,project:b.project,projectLabel:h,isPinned:M,timestamp:T})}}return N.sort((b,h)=>b.isPinned!==h.isPinned?b.isPinned?-1:1:h.timestamp-b.timestamp),N},[e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[v,g]=i.useState(30);i.useEffect(()=>{g(30)},[e.hasSessionSearchQuery]);const j=x.slice(0,v),C=x.length-j.length;return e.sharedSessionsOnly?t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})}):e.projectSections.length===0?t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0?t.jsx(ps,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):t.jsxs("div",{className:"oc-sticky-fade-root relative flex min-h-0 flex-1",onPointerDownCapture:s?d:void 0,onClickCapture:s?d:void 0,onContextMenuCapture:s?d:void 0,children:[t.jsx(ps,{ref:a,useScrollShadow:!0,hideTopScrollShadow:!s,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:F("oc-sidebar-scroller oc-sticky-fade-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-20"),style:s?{"--scroll-shadow-top-size":"0px"}:void 0,onScroll:s?N=>c(N.currentTarget):void 0,children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.showOnlyMainWorkspace?t.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const N=e.sectionsForRender.find(I=>I.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!N)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=N.groups.find(I=>I.isMain&&I.sessions.length>0)??N.groups.find(I=>I.sessions.length>0)??N.groups.find(I=>I.isMain)??N.groups[0];if(!b)return t.jsx(gs,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:N.project.id,directoryOverride:N.project.normalizedPath}),children:"New session"});const h=N.groups.find(I=>I.isArchivedBucket);return[b,...h&&h.id!==b.id?[h]:[]].map(I=>{const M=`${N.project.id}:${I.id}`,T=I.id===b.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(I,M,N.project.id,T,null,!0,a)},M)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:x.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[j.map(({node:N,project:b,projectLabel:h})=>{const f=N.session.directory??b.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(N,0,f,b.id,!1,{projectLabel:h,showFolderLabel:!0},"project")},N.session.id)}),C>0?t.jsx(gs,{icon:"arrow-down-s",onClick:()=>g(N=>N+30),children:C===1?"Show 1 more session":`Show ${C} more sessions`}):null,v>30&&x.length>30?t.jsx(gs,{icon:"arrow-up-s",onClick:()=>g(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(N=>{const b=N.project.id,h=o(b,N.groups),f=h.find(M=>M.isMain)??null,I=f?h.filter(M=>M.id!==f.id):h;return t.jsxs("div",{children:[f?e.renderGroupSessions(f,`${b}:${f.id}`,b,!0,null,void 0,a):null,I.map(M=>{const T=`${b}:${M.id}`;return t.jsx(i.Fragment,{children:e.renderGroupSessions(M,T,b,!1,null,void 0,a)},M.id)})]},b)})})]})}),s&&m&&w?t.jsx("div",{className:"oc-sticky-fade-overlay pointer-events-none absolute inset-x-0 top-0 z-30 flex items-center gap-1.5 py-1 px-3","aria-hidden":"true",children:t.jsx(nh,{id:m.id,projectLabel:w,mobileVariant:e.mobileVariant})}):null]})}const ch=i.memo(lh);function dh(e){if(typeof e!="number"||!Number.isFinite(e))return"";const s=new Date(e);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleString("en-US",{month:"short"}),r=s.getDate(),o=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${a}:${l}`}function uh(e){if(e.info.role==="user")return"";const s=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return s&&n?`${s}/${n}`:n||s}function fh(e){const s=e.info.role==="user"?"User":"Assistant",n=dh(e.info.time?.created),r=uh(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
|
|
4
|
-
|
|
5
|
-
*${o}*`:`**${s}**`}function hh(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function qi(e){const s=fh(e),n=hh(e.parts).trim();return n?`${s}
|
|
6
|
-
|
|
7
|
-
${n}`:""}function Qi(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
8
|
-
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
`,a=e.records.map(qi).filter(Boolean).join(`
|
|
12
|
-
|
|
13
|
-
---
|
|
14
|
-
|
|
15
|
-
`),l=[o+a];for(const c of e.children)l.push(Qi(c,s+1));return l.join(`
|
|
16
|
-
|
|
17
|
-
---
|
|
18
|
-
|
|
19
|
-
`)}function mh(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
20
|
-
|
|
21
|
-
*Exported on ${o}*
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
`,l=e.map(qi).filter(Boolean).join(`
|
|
26
|
-
|
|
27
|
-
---
|
|
28
|
-
|
|
29
|
-
`);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Qi(u,1)).join(`
|
|
30
|
-
|
|
31
|
-
---
|
|
32
|
-
|
|
33
|
-
`);c+=`
|
|
34
|
-
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
`+d}return c}function ph(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function gh(e,s){const n=await ed(s,e);return n||null}async function xh(e){const s=xi()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await td(e)?!0:sd(e)}function bh(){return tc()}function yh(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 vh=(e,s)=>{if(!s)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const a=s.get(o);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},At=ws()((e,s)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{s().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{s().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,o)=>{const a=s(),l=new Set(a.selectedIds);let c=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(l.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const y=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const w of y)l.delete(w);d===n&&(d=null)}else{for(const w of y)l.add(w);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,o,a,l)=>{const c=s();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),y=o.indexOf(r);if(u<0||y<0)return;const[m,w]=u<=y?[u,y]:[y,u],x=o.slice(m,w+1),v=vh(x,l),j=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const C of v)j.add(C);e({selectedIds:j,scopeKey:a??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}}));let pr=!1;const gr=new Set;let Bo=!1;function wh(){for(const e of gr)e()}function Tr(e){pr!==e&&(pr=e,wh())}function Sh(e){e.key==="Shift"&&Tr(!0)}function jh(e){e.key==="Shift"&&Tr(!1)}function kh(){Tr(!1)}function Ch(){Bo||typeof window>"u"||(Bo=!0,window.addEventListener("keydown",Sh),window.addEventListener("keyup",jh),window.addEventListener("blur",kh))}function Nh(e){return Ch(),gr.add(e),()=>{gr.delete(e)}}function Ih(){return pr}function Dh(){return!1}function Ph(){return Ue.useSyncExternalStore(Nh,Ih,Dh)}const qn=new WeakMap,Th=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;qn.get(n)?.();const r=s.getBoundingClientRect().top;let o=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,qn.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(a||!s.isConnected||!n.isConnected){c();return}const u=s.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Zt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),qn.set(n,c),l=window.requestAnimationFrame(d)},Eh=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Ph(),y=u?n:s,m=w=>{if(u||w.shiftKey){d(w);return}c(w)};return t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",className:F("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":y,onPointerDown:a,onMouseDown:l,onClick:m,onKeyDown:w=>w.stopPropagation(),children:t.jsx(k,{name:u?"delete-bin":"archive",className:o})})}),t.jsx(st,{side:"left",sideOffset:8,children:y})]})});function Mh(e){Zt("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:y,editingId:m,setEditingId:w,editTitle:x,setEditTitle:v,handleSaveEdit:g,handleCancelEdit:j,toggleParent:C,handleSessionSelect:N,handleSessionDoubleClick:b,togglePinnedSession:h,handleShareSession:f,copiedSessionId:I,handleCopyShareUrl:M,handleCopySessionId:T,handleUnshareSession:O,openSidebarMenuKey:P,setOpenSidebarMenuKey:B,renamingFolderId:z,getFoldersForScope:U,getSessionFolderId:ne,removeSessionFromFolder:se,addSessionToFolder:K,createFolderAndStartRename:G,openContextPanelTab:R,handleDeleteSession:A,handleRestoreSession:V,mobileVariant:le,alwaysShowActions:$,renderSessionNode:ke,secondaryMeta:Ie,renderContext:_e="project",subtreeContainsEditing:Ge,menuOpenSessionId:Fe,childRenderExtrasFor:ve}=e,Pe=i.useMemo(()=>nd(),[]),me=!a&&!le,He=i.useRef(!1),[we,xe]=i.useState(!1),Ce=i.useRef(m);Ce.current=m;const Qe=i.useRef(null),Be=i.useRef(g);Be.current=g;const[W,H]=i.useState(x),ie=i.useRef(W);ie.current=W;const pe=i.useRef(null),Se=i.useRef(null),Y=s.session,be=Y,de=qe(Y.directory??null)??qe(r??null),Ve=Me(_=>_.currentSessionId===Y.id),at=sc(de),ze=nc(de),je=Pt(i.useCallback(_=>{if(Ie?.projectLabel||!o)return null;const De=_.projects.find(Ze=>Ze.id===o);return De?De.label?.trim()||xs(qe(De.path)??De.path,null)||De.path:null},[o,Ie?.projectLabel])),Ae=Ie?.projectLabel??(je?In(je):null),ot=Ie?.branchLabel??s.worktree?.branch??(at&&at!=="HEAD"?at:null),ht=ot,pt=ze===!0||!!(ot||s.worktree),ge=s.children.length,Ye=be.agent;i.useMemo(()=>{const _=s.worktree?.branch?.trim()||ot?.trim(),De=qe(s.worktree?.path??de);return _&&De?Hi():null},[s.worktree,ot,de]);const Tt=$f();i.useMemo(()=>null,[Tt]);const S=o??de??null,Z=uc(),ae=mi(),ye=At(_=>_.enabled),Re=At(i.useCallback(_=>_.selectedIds.has(Y.id),[Y.id])),Ke=At(_=>_.toggleSelected),nt=At(_=>_.setRange),ct=i.useCallback(_=>{const De=[],Ze=dt=>{dt.children.forEach(Ct=>{De.push(Ct.session.id),Ze(Ct)})};return Ze(_),De},[]);i.useCallback(_=>{const De=[],Ze=dt=>{dt.children.forEach(Ct=>{De.push(Ct.session),Ze(Ct)})};return Ze(_),De},[]);const[Gt,it]=i.useState(!1),[gt,yt]=i.useState(!0),Je=`${_e}:${a?"archived":"active"}:${Y.id}`,Bt=rc(i.useCallback(_=>!!_.sessionMemoryState.get(oc(Y.id))?.isZombie,[Y.id])),Et=ic(Y.id)?.type??"idle",xt=Et==="busy"||Et==="retry",Mt=ac(Y.id,xt),D=lc(Y.id),fe=be.title||"Untitled Session",Ne=s.children.length>0,Le=cc(l,de,Y.id),We=Je,kt=d?!0:c.has(We);i.useMemo(()=>Of(s,kt,de),[kt,s,de]);const E=hc(),X=!!be.parentID,$e=dc(Y.id)>0&&(!X||y),he=be.time?.updated||be.time?.created||Date.now(),Te=oi(he),lt=mc(he),[vt,$t]=i.useState(!1),Ft=i.useMemo(()=>ct(s).length,[ct,s]),Ht=i.useCallback(async _=>{const De=[];let Ze=0;for(const dt of _)try{if(!de)throw new Error("Session directory is required for export");await ae.loadCompleteHistory?.(dt.session.id,de);const Ct=ro(Z.getState(),dt.session.id).list,ut=dt.session.title||"Untitled Sub-agent",Yt=dt.session.agent,Kt=await Ht(dt.children);Ze+=Kt.skipped,De.push({title:ut,agent:Yt,records:Ct,children:Kt.children})}catch{Ze+=ct(dt).length+1}return{children:De,skipped:Ze}},[ct,Z,de,ae]),zt=i.useCallback(_=>{_<=0||oe.warning(_===1?`Exported session, but skipped ${_} sub-agent task that could not be loaded.`:`Exported session, but skipped ${_} sub-agent tasks that could not be loaded.`)},[]),mt=i.useCallback(async _=>{if(!de){oe.error("Nothing to export");return}try{await ae.loadCompleteHistory?.(Y.id,de)}catch{oe.error("Failed to load the complete session history");return}const De=ro(Z.getState(),Y.id).list;if(De.length===0){oe.error("Nothing to export");return}let Ze,dt=0;if(_&&s.children.length>0){const Kt=await Ht(s.children);Ze=Kt.children,dt=Kt.skipped}const Ct=mh(De,be.title??null,Ze),ut=yh(be.title??null),Yt=await gh(Ct,ut);if(Yt){oe.success("Session exported",{action:{label:bh(),onClick:()=>{xh(Yt).then(Kt=>{Kt||oe.error("Failed to reveal path")})}}}),zt(dt);return}ph(Ct,ut),oe.success("Session exported"),zt(dt)},[Ht,Z,s.children,be.title,Y.id,de,zt,ae]),Lt=i.useCallback(async()=>{if(s.children.length>0){yt(!0),it(!0);return}await mt(!1)},[mt,s.children.length]),L=i.useCallback(()=>{de&&rd("desktop_open_session_mini_chat_window",{sessionId:Y.id,directory:de,apiBaseUrl:id(),clientToken:od()}).catch(_=>{console.warn("[session-sidebar] failed to open mini chat window",_)})},[Y.id,de]);i.useEffect(()=>{if(m!==Y.id)return;const _=De=>{const dt=De.target?.closest?.(`[data-session-rename-form="${CSS.escape(Y.id)}"]`);Se.current&&!dt&&Be.current(ie.current)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[m,Y.id]),i.useLayoutEffect(()=>{if(m!==Y.id){pe.current===Y.id&&(pe.current=null);return}pe.current!==Y.id&&(pe.current=Y.id,H(x))},[m,x,Y.id]);const q=D.length,ee=!xt&&$e&&!Ve,te=xt&&Mt,re=Le,rt=t.jsx(k,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),wt=re?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:rt}):null,St=Ne?t.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),C(We)},onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),_.stopPropagation(),C(We))},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":kt?"Collapse subsessions":"Expand subsessions",children:kt?t.jsx(k,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(k,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Ut=Bt?t.jsx(k,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,es=_=>{if(!_&&Qe.current){const{id:De,title:Ze}=Qe.current;Qe.current=null,w(De),v(Ze)}},jt=_=>{$t(_)},cs=_=>{_.preventDefault(),_.stopPropagation()},Ss=_=>{_.preventDefault(),_.stopPropagation()},js=_=>{_.preventDefault(),_.stopPropagation(),B(null),A(Y,{archivedBucket:a})},Rn=_=>{_.preventDefault(),_.stopPropagation(),B(null),A(Y,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Zs=_=>{if(He.current){He.current=!1;return}if(ye){if(_?.preventDefault(),_?.stopPropagation(),_?.shiftKey){const Ze=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(ut=>ut.getAttribute("data-session-row")).filter(ut=>typeof ut=="string"&&ut.length>0),dt=At.getState().anchorId,Ct=new Map;Ct.set(Y.id,ct(s)),nt(dt,Y.id,Ze,S,Ct);return}Ke(Y.id,S,ct(s));return}_?.currentTarget&&Th(_.currentTarget),N(Y.id,de)},Fn=_=>{_.defaultPrevented||_.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Zs(_)},Xs=_=>{(_.button===2||_.button===0&&_.ctrlKey&&!ye)&&(He.current=!0)},ts=_=>{le&&_.pointerType==="touch"&&xe(!0)},ks=_=>{le&&_.pointerType==="touch"&&xe(!1)},$s=({Item:_,Separator:De,Sub:Ze,SubTrigger:dt,SubContent:Ct})=>t.jsxs(t.Fragment,{children:[t.jsxs(_,{onClick:()=>{Qe.current={id:Y.id,title:fe}},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(_,{onClick:()=>T(Y.id),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(_,{onClick:()=>de&&h({directory:de,sessionId:Y.id}),className:"[&>svg]:mr-1",children:[Le?t.jsx(k,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(k,{name:"pushpin",className:"mr-1 h-4 w-4"}),Le?"Unpin session":"Pin session"]}),be.share?t.jsxs(t.Fragment,{children:[t.jsx(_,{onClick:()=>{be.share?.url&&M(be.share.url,Y.id)},className:"[&>svg]:mr-1",children:I===Y.id?t.jsxs(t.Fragment,{children:[t.jsx(k,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):t.jsxs(t.Fragment,{children:[t.jsx(k,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy link"]})}),t.jsxs(_,{onClick:()=>O(Y.id),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),"Unshare"]})]}):t.jsxs(_,{onClick:()=>f(be),className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"share-2",className:"mr-1 h-4 w-4"}),"Share"]}),t.jsxs(_,{onClick:()=>{Lt()},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),de&&!a?(()=>{const ut=[],Yt=Nt=>{const It=qe(Nt??null);It&&!ut.includes(It)&&ut.push(It)};if(o){const Nt=Pt.getState().projects.find(Ns=>Ns.id===o),It=qe(Nt?.path??null);Yt(It)}Yt(de);const Kt=ut.flatMap(Nt=>U(Nt).map(It=>({scope:Nt,folder:It}))),qt=Kt.find(({scope:Nt,folder:It})=>ne(Nt,Y.id)===It.id)??null,Cs=ut[0]??de;return t.jsxs(t.Fragment,{children:[t.jsx(De,{}),t.jsxs(Ze,{children:[t.jsxs(dt,{className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"folder",className:"h-4 w-4"}),"Move to folder"]}),t.jsxs(Ct,{className:"min-w-[180px]",children:[Kt.length===0?t.jsx(_,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):Kt.map(({scope:Nt,folder:It})=>{const Ns=qt?.folder.id===It.id;return t.jsxs(_,{onClick:()=>{if(Ns){se(Nt,Y.id);return}qt&&qt.scope!==Nt&&se(qt.scope,Y.id),K(Nt,It.id,Y.id)},children:[t.jsx("span",{className:"flex-1 truncate",children:It.name}),Ns?t.jsx(k,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},It.id)}),t.jsx(De,{}),t.jsxs(_,{onClick:()=>{const Nt=G(Cs);Nt&&(qt&&qt.scope!==Cs&&se(qt.scope,Y.id),K(Cs,Nt.id,Y.id))},children:[t.jsx(k,{name:"add",className:"mr-1 h-4 w-4"}),"New folder..."]}),qt?t.jsxs(_,{onClick:()=>{se(qt.scope,Y.id)},className:"text-destructive focus:text-destructive",children:[t.jsx(k,{name:"close",className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]})]})})():null,t.jsxs(_,{disabled:!de,onClick:()=>{de&&R(de,{mode:"chat",dedupeKey:`session:${Y.id}`,label:fe,sessionTitleFallback:fe})},className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"chat-4",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Side Panel"}),t.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:"beta"})]}),Pe?t.jsxs(_,{disabled:!de,onClick:L,className:"[&>svg]:mr-1",children:[t.jsx(k,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(De,{}),a?null:t.jsxs(_,{className:"[&>svg]:mr-1",onClick:()=>A(Y,{archivedBucket:a}),children:[t.jsx(k,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs(_,{className:"[&>svg]:mr-1",onClick:()=>V(Y),children:[t.jsx(k,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(_,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>A(Y,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(k,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]});Xt,$s({Item:Rt,Separator:pi,Sub:pc,SubTrigger:gc,SubContent:xc});const en=t.jsx(lr,{children:t.jsx(cr,{className:"app-region-no-drag z-50",children:t.jsx(dr,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(z||Ce.current),style:{color:"var(--surface-elevated-foreground)"},className:F(rr,"min-w-[180px]"),children:$s({Item:({className:_,...De})=>t.jsx(vi,{className:F(ni,_),...De}),Separator:({className:_,...De})=>t.jsx(wi,{className:F(ri,_),...De}),Sub:pd,SubTrigger:({className:_,children:De,...Ze})=>t.jsxs(gd,{className:F(fc,_),...Ze,children:[De,t.jsx(k,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:_,children:De,...Ze})=>t.jsx(lr,{children:t.jsx(cr,{className:"app-region-no-drag z-50",children:t.jsx(dr,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:F(rr,_),...Ze,children:De})})})})})})});return t.jsxs(i.Fragment,{children:[t.jsx(Rf,{sessionId:Y.id,sessionDirectory:de??null,sessionTitle:fe,children:t.jsxs(bi,{open:vt,onOpenChange:jt,onOpenChangeComplete:es,children:[t.jsxs(yi,{render:t.jsx("div",{"data-session-row":Y.id,"data-session-scope":S??"","data-session-archived":a?"1":"0",onClick:Fn,style:n>0?{marginLeft:`${n*14}px`}:void 0,className:F("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",n>0?"bg-secondary/30 hover:bg-interactive-hover":"hover:bg-interactive-hover",Ve&&!Re&&"bg-interactive-selection",Re&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[St,wt,m===Y.id?t.jsxs("form",{ref:Se,"data-session-rename-form":Y.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:_=>_.stopPropagation(),onMouseDown:_=>_.stopPropagation(),onSubmit:_=>{_.preventDefault(),g(W)},children:[t.jsx("input",{value:W,onChange:_=>H(_.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:_=>{_.stopPropagation(),_.key==="Escape"&&j()}}),t.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:t.jsx(k,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:j,"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:t.jsx(k,{name:"close",className:"size-4"})})]}):t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsxs("button",{type:"button",onPointerDown:ts,onPointerUp:ks,onPointerCancel:ks,onMouseDown:Xs,onClick:_=>Zs(_),onDoubleClick:_=>{_.stopPropagation(),b(Y.id,fe)},className:F("flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",we&&"bg-interactive-hover/70"),children:[t.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:t.jsx("div",{className:F("block min-w-0 flex-1 truncate font-normal typography-ui-label",$e?"text-foreground":"text-foreground/90"),children:vn(fe,u)})}),Ie?.showFolderLabel&&Ae||ht||pt||Tt||ge>0||Ye&&Ye!=="default"||te||q>0||E>0?t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[Ie?.showFolderLabel&&Ae?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",title:`Folder: ${Ae}`,children:Ae}):null,ht?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",title:`Branch: ${ht}`,children:[t.jsx(k,{name:"git-branch",className:F("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:ht})]}):pt?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",title:"Git repository",children:[t.jsx(k,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,ge>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",title:`${ge} ${ge===1?"subtask":"subtasks"}`,children:[t.jsx(k,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:ge})]}):null,Ye&&Ye!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",title:`Agent: ${Ye}`,children:Ye}):null,te?t.jsx(zn,{sessionId:Y.id,running:xt,className:"text-muted-foreground/70"}):null,q>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0",title:"Permission required","aria-label":"Permission required",children:[t.jsx(k,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:q})]}):null,null]}):null]})}),t.jsx(st,{side:"right",sideOffset:56,className:"max-w-xs text-left",children:t.jsxs("div",{className:"flex min-w-44 flex-col gap-1.5 text-left text-xs",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"min-w-0 truncate font-normal text-foreground",children:fe}),xt?t.jsx(zn,{sessionId:Y.id,running:!0,className:"flex-shrink-0 text-primary font-medium"}):ee?t.jsx(oo,{label:"Session complete"}):t.jsx("span",{className:"flex-shrink-0 text-muted-foreground",title:Te,children:lt})]}),xt?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-primary",children:[t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"h-3 w-3 shrink-0"}),t.jsxs("span",{className:"min-w-0 truncate font-medium",children:["Running for ",t.jsx(zn,{sessionId:Y.id,running:!0})]})]}):null,Ae?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"folder",className:"h-3 w-3 flex-shrink-0"}),t.jsx("span",{className:"min-w-0 truncate",children:Ae})]}):null,ht?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"git-branch",className:"h-3 w-3 flex-shrink-0",style:void 0}),t.jsx("span",{className:"min-w-0 truncate",children:ht})]}):pt?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"git-repository",className:"h-3 w-3 flex-shrink-0"}),t.jsx("span",{className:"min-w-0 truncate",children:"Git Repository"})]}):null,null,ge>0?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"node-tree",className:"h-3 w-3 flex-shrink-0"}),t.jsxs("span",{className:"min-w-0 truncate text-[11px]",children:[ge," ",ge===1?"subtask":"subtasks"]})]}):null,Ye&&Ye!=="default"?t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-muted-foreground",children:[t.jsx(k,{name:"terminal",className:"h-3 w-3 flex-shrink-0"}),t.jsxs("span",{className:"min-w-0 truncate text-[11px]",children:["Agent: ",Ye]})]}):null]})})]})]}),Le?t.jsx(k,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,t.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[t.jsx("div",{className:F("flex items-center justify-end",me&&($||vt)?"opacity-0":me?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:xt?t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):ee?t.jsx(oo,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",title:Te,children:lt})}),me?t.jsx("div",{className:F("absolute inset-0 flex items-center justify-end",$||vt?"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:t.jsx(Eh,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:cs,onMouseDown:Ss,onArchive:js,onDelete:Rn})}):null]}),Ut&&!le?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:Ut}):null]}),en]})}),Ne&&kt?s.children.map(_=>{const De=ve?ve(_):{subtreeContainsEditing:Ge,menuOpenSessionId:Fe,nodeStructureKey:""};return t.jsx(i.Fragment,{children:ke(_,n+1,de??r,o,a,void 0,_e,De)},_.session.id)}):null,t.jsx(os,{open:Gt,onOpenChange:it,children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(us,{children:"Export Markdown"}),t.jsx(Bs,{children:Ft===1?`This session has ${Ft} sub-agent task. Include it in the export?`:`This session has ${Ft} sub-agent tasks. Include them in the export?`})]}),t.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:gt,onChange:_=>yt(_.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(_s,{children:[t.jsx(Ee,{type:"button",onClick:()=>it(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Ee,{type:"button",onClick:()=>{it(!1),mt(gt)},size:"sm",children:"Export"})]})]})})]},Y.id)}const _o=e=>qe(e.session.directory??null),Ah=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),Rh=e=>{if(!e.openSidebarMenuKey)return null;const s=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${s}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},fn=e=>e.menuOpenSessionId??Rh(e),hn=(e,s,n)=>s?n.has(e.node.session.id)?!0:ns(e.node,s):!1,xr=(e,s,n,r,o)=>{if(e.session.id!==s.session.id)return!0;const a=o(e);if(n.has(a)!==r.has(a)||e.children.length!==s.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(xr(e.children[l],s.children[l],n,r,o))return!0;return!1},Fh=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return xr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||xr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},Lh=(e,s)=>{if(e.node.session.id!==s.node.session.id||e.node.session!==s.node.session||e.depth!==s.depth||e.groupDirectory!==s.groupDirectory||e.projectId!==s.projectId||e.archivedBucket!==s.archivedBucket||(e.renderContext??"project")!==(s.renderContext??"project")||e.mobileVariant!==s.mobileVariant||e.alwaysShowActions!==s.alwaysShowActions||e.hasSessionSearchQuery!==s.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||e.notifyOnSubtasks!==s.notifyOnSubtasks||e.nodeStructureKey!==s.nodeStructureKey||_o(e.node)!==_o(s.node)||!Ah(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Gi(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&Fh(e,s)||e.editingId!==s.editingId&&(hn(e,e.editingId,e.subtreeContainsEditing)||hn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(hn(e,e.editingId,e.subtreeContainsEditing)||hn(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(ns(e.node,e.copiedSessionId)||ns(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=fn(e),r=fn(s);if(ns(e.node,n)||ns(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=fn(e),r=fn(s);if(ns(e.node,n)||ns(s.node,r))return!1}return e.setEditingId===s.setEditingId&&e.setEditTitle===s.setEditTitle&&e.handleSaveEdit===s.handleSaveEdit&&e.handleCancelEdit===s.handleCancelEdit&&e.toggleParent===s.toggleParent&&e.handleSessionSelect===s.handleSessionSelect&&e.handleSessionDoubleClick===s.handleSessionDoubleClick&&e.togglePinnedSession===s.togglePinnedSession&&e.handleShareSession===s.handleShareSession&&e.handleCopyShareUrl===s.handleCopyShareUrl&&e.handleCopySessionId===s.handleCopySessionId&&e.handleUnshareSession===s.handleUnshareSession&&e.setOpenSidebarMenuKey===s.setOpenSidebarMenuKey&&e.getFoldersForScope===s.getFoldersForScope&&e.getSessionFolderId===s.getSessionFolderId&&e.removeSessionFromFolder===s.removeSessionFromFolder&&e.addSessionToFolder===s.addSessionToFolder&&e.createFolderAndStartRename===s.createFolderAndStartRename&&e.openContextPanelTab===s.openContextPanelTab&&e.handleDeleteSession===s.handleDeleteSession&&e.handleRestoreSession===s.handleRestoreSession&&e.renderSessionNode===s.renderSessionNode},Oh=i.memo(Mh,Lh),$o={selected:0,"active-project":1,expanded:2,visible:3,background:4};function Bh(e){const s=new Map,n=(r,o,a)=>{const l=qe(r??null);if(!l)return;const c=s.get(l);c&&$o[c.priority]<=$o[o]||s.set(l,{directory:l,priority:o,reason:a})};for(const r of e.projectSections){const o=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":o&&(a="expanded"),n(r.project.normalizedPath,a,o?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=o&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":o&&(d="visible"),n(l.directory,d,c?"worktree-expanded":"known-worktree")}}return n(e.currentDirectory,"selected","current-directory"),n(e.currentSessionDirectory,"selected","selected-session"),[...s.values()]}function _h(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l="Untitled Session";return t.jsx(os,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(us,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(Bs,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be permanently deleted.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be archived.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`\\"${s?.session.title||l}\\" will be permanently deleted.`:`\\"${s?.session.title||l}\\" will be archived.`})]}),t.jsxs(_s,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>o(!r),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":!r,children:[r?t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>n(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"}),t.jsx("button",{type:"button",onClick:()=>{a()},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:s?.archivedBucket?"Delete":"Archive"})]})]})]})})}function $h(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=s?.archivedBucket===!0,c=s?.sessionCount??0,d=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=l?c===1?`${c} session will be permanently deleted.`:`${c} sessions will be permanently deleted.`:c===1?`${c} session will be archived.`:`${c} sessions will be archived.`;return t.jsx(os,{open:!!s,onOpenChange:y=>{y||n(null)},children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(us,{children:d}),t.jsx(Bs,{children:u})]}),t.jsxs(_s,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>o(!r),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":!r,children:[r?t.jsx(k,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(k,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>n(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"}),t.jsx("button",{type:"button",onClick:()=>{a()},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:l?"Delete":"Archive"})]})]})]})})}function zh(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(os,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(is,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(us,{children:"Delete folder?"}),t.jsx(Bs,{children:s&&(s.subFolderCount>0||s.sessionCount>0)?s.subFolderCount>0?s.subFolderCount===1?`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted. Sessions inside will not be deleted.`:`\\"${s?.folderName??""}\\" will be permanently deleted.`})]}),t.jsxs(_s,{children:[t.jsx("button",{type:"button",onClick:()=>n(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"}),t.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 Uh=({selectedCount:e,scopeKey:s,scopeFolders:n,archivedBucket:r,onMoveToFolder:o,onCreateFolderAndMove:a,onRemoveFromFolder:l,canRemoveFromFolder:c,onRestore:d,onDelete:u,onDone:y})=>{const m=!!s&&!r,w=r?"Delete":"Archive",x="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 t.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-3 py-1.5",children:[t.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),t.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[m?t.jsxs(as,{children:[t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx(ls,{asChild:!0,children:t.jsx("button",{type:"button",className:x,"aria-label":"Move to folder",children:t.jsx(k,{name:"folder",className:"h-4 w-4"})})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Move to folder"})})]}),t.jsxs(Xt,{align:"end",className:"min-w-[180px]",children:[n.length===0?t.jsx(Rt,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):n.map(g=>t.jsx(Rt,{onClick:()=>o(g.id),children:t.jsx("span",{className:"flex-1 truncate",children:g.name})},g.id)),t.jsx(pi,{}),t.jsxs(Rt,{onClick:a,children:[t.jsx(k,{name:"add",className:"mr-1 h-4 w-4"}),"New folder..."]}),c?t.jsxs(Rt,{onClick:l,className:"text-destructive focus:text-destructive",children:[t.jsx(k,{name:"close",className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]}):null,r?t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:d,className:x,"aria-label":"Restore",children:t.jsx(k,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:u,className:F("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"),"aria-label":w,children:t.jsx(k,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:w})})]}),t.jsxs(et,{children:[t.jsx(tt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:y,className:x,"aria-label":"Exit selection",children:t.jsx(k,{name:"close",className:"h-4 w-4"})})}),t.jsx(st,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},Kh=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:y,setBulkDeleteConfirm:m}=e,w=At(G=>G.enabled),x=At(G=>G.selectedIds.size),v=x>0,g=At(G=>G.selectedIds),j=At(G=>G.scopeKey),C=i.useCallback(()=>{At.getState().toggleMode()},[]),N=i.useCallback(()=>{At.getState().disable()},[]),b=i.useMemo(()=>{if(!v||typeof document>"u")return!1;let G=!1,R=!1;for(const A of g){const V=document.querySelectorAll(`[data-session-row="${CSS.escape(A)}"]`);for(const le of V)le.getAttribute("data-session-archived")==="1"?R=!0:G=!0}return R&&!G},[v,g]),h=i.useMemo(()=>{if(j)return j;if(!v||typeof document>"u")return null;for(const G of g){const A=document.querySelector(`[data-session-row="${CSS.escape(G)}"]`)?.getAttribute("data-session-scope");if(A&&A.length>0)return A}return null},[v,g,j]),f=i.useMemo(()=>{if(!h)return[];const G=o.get(h);return G&&G.length>0?G.map(R=>R.scopeKey):[h]},[h,o]),I=i.useMemo(()=>f.flatMap(G=>r[G]??[]),[r,f]),M=i.useCallback(G=>{for(const R of f)if((r[R]??[]).some(A=>A.id===G))return R;return null},[r,f]),T=i.useMemo(()=>{if(!v)return!1;for(const G of f)for(const R of r[G]??[])for(const A of R.sessionIds)if(g.has(A))return!0;return!1},[r,f,v,g]),O=i.useCallback((G,R)=>{const A=Array.from(g);for(const V of f)V!==G&&l(V,A);a(G,R,A)},[a,l,g,f]),P=i.useCallback(G=>{if(!v)return;const R=M(G);R&&O(R,G)},[v,O,M]),B=i.useCallback(()=>{const G=f[0];if(!G||!v)return;const R=c(G);R&&O(G,R.id)},[c,v,O,f]),z=i.useCallback(()=>{if(!v)return;const G=Array.from(g);for(const R of f)l(R,G)},[l,g,f,v]),U=i.useCallback(async()=>{const G=Array.from(g);if(G.length!==0){if(b){const{deletedIds:R,failedIds:A}=await y(G);R.length>0&&oe.success(R.length===1?`Deleted ${R.length} session`:`Deleted ${R.length} sessions`),A.length>0&&oe.error(A.length===1?`Failed to delete ${A.length} session`:`Failed to delete ${A.length} sessions`)}else{const{archivedIds:R,failedIds:A}=await d(G);R.length>0&&oe.success(R.length===1?`Archived ${R.length} session`:`Archived ${R.length} sessions`),A.length>0&&oe.error(A.length===1?`Failed to archive ${A.length} session`:`Failed to archive ${A.length} sessions`)}At.getState().clear()}},[d,b,y,g]),ne=i.useCallback(()=>{if(!v)return;const G=g.size;if(!n){U();return}m({sessionCount:G,archivedBucket:b})},[b,U,g,n,m,v]),se=i.useCallback(async()=>{if(!v||!b)return;const G=Array.from(g),{restoredIds:R,failedIds:A}=await u(G);R.length>0&&oe.success(R.length===1?`Restored ${R.length} session`:`Restored ${R.length} sessions`),A.length>0&&oe.error(A.length===1?`Failed to restore ${A.length} session`:`Failed to restore ${A.length} sessions`),At.getState().clear()},[b,v,g,u]),K=i.useCallback(async()=>{m(null),await U()},[U]);return i.useEffect(()=>{if(!w)return;const G=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),R=A=>{if(s)return;const V=A.target;if(V&&(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.isContentEditable))return;const le=G?A.metaKey:A.ctrlKey;if(A.key==="Escape"){A.preventDefault(),At.getState().disable();return}if(le&&A.key==="Backspace"){A.preventDefault(),ne();return}if(le&&(A.key==="a"||A.key==="A")){const $=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if($.length===0)return;A.preventDefault();const Ie=At.getState().scopeKey??$[0]?.getAttribute("data-session-scope")??null,_e=Fe=>Ie?Fe.getAttribute("data-session-scope")===Ie:!0,Ge=$.filter(_e).map(Fe=>Fe.getAttribute("data-session-row")).filter(Fe=>typeof Fe=="string"&&Fe.length>0);if(Ge.length===0)return;At.getState().replaceAll(Ge,Ie||null)}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[ne,s,w]),{selectionModeEnabled:w,hasSelection:v,selectedIdsSize:x,bulkScopeIsArchived:b,derivedSelectionScope:h,bulkScopeFolders:I,bulkCanRemoveFromFolder:T,handleToggleSelectionMode:C,handleExitSelectionMode:N,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:B,handleBulkRemoveFromFolder:z,handleBulkDelete:ne,handleBulkRestore:se,confirmBulkDelete:K}},zo="oc.sessions.projectCollapse",Uo="oc.sessions.groupOrder",Ko="oc.sessions.groupCollapse",Go="oc.sessions.activeSessionByProject",Ho="oc.sessions.expandedParents.v3",Gh=(e,s,n)=>{if(e.time?.archived)return!0;const r=io(As(e));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const o of s)if(io(o)===r)return!0;return!1},Hh=new Set,Qn=[],Wt=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},Wh=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l})=>{const c=Me(d=>d.currentSessionDirectory);return i.useEffect(()=>{s.setBootstrapDemand(e,Bh({projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,o,l,c,e,n]),i.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},qh=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=qe(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return xn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=qe(o.directory)?.toLowerCase();if(a&&s.has(a))return!0}return!1},void 0,"catalog")?t.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:t.jsx(Gs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},Qh=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{ar("react.session_sidebar_render"),Zt("ui.session_sidebar.render"),Zt(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Zt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=i.useState(!1),[u,y]=i.useState(""),m=i.useRef(null),w=i.useRef(null),[x,v]=i.useState(null),[g,j]=i.useState(""),[C,N]=i.useState(null),[b,h]=i.useState(new Set),f=i.useMemo(()=>an(),[]),[I,M]=i.useState(new Set),[T,O]=i.useState(null),[P,B]=i.useState(new Map),[z,U]=i.useState(new Map),[ne,se]=i.useState(!1),[K,G]=i.useState(null),[R,A]=i.useState(null),[V,le]=i.useState(""),[$,ke]=i.useState(null),[Ie,_e]=i.useState(null),[Ge,Fe]=i.useState(null),ve=ir(p=>p.ids),Pe=bc(i.useCallback(p=>e?p.rankById:fi,[e])),me=xn(p=>e?yc(p.catalog):"",void 0,"catalog"),He=i.useMemo(()=>me?me.split("|"):Qn,[me]),we=i.useMemo(()=>new Set(He),[He]),xe=vc(ho(p=>e?Object.entries(p.index.session.unseenCount).filter(([,J])=>J>0).map(([J])=>J).sort():Qn)),Ce=i.useMemo(()=>new Set(xe),[xe]),Qe=ir(p=>p.toggle),[Be,W]=i.useState(()=>{try{const p=an().getItem(Ko);if(!p)return new Set;const J=JSON.parse(p);return new Set(Array.isArray(J)?J.filter(Q=>typeof Q=="string"):[])}catch{return new Set}}),[H,ie]=i.useState(()=>{try{const p=an().getItem(Uo);if(!p)return new Map;const J=JSON.parse(p),Q=new Map;return Object.entries(J).forEach(([Oe,ft])=>{Array.isArray(ft)&&Q.set(Oe,ft.filter(Jt=>typeof Jt=="string"))}),Q}catch{return new Map}}),pe=i.useMemo(()=>{try{const p=an().getItem(Go);if(!p)return new Map;const J=JSON.parse(p),Q=new Map;return Object.entries(J).forEach(([Oe,ft])=>{typeof ft=="string"&&ft.length>0&&Q.set(Oe,ft)}),Q}catch{return new Map}},[]),Se=i.useCallback(p=>{try{f.setItem(Go,JSON.stringify(Object.fromEntries(p.entries())))}catch{}},[f]),[Y,be]=i.useState(new Map),de=i.useRef(new Map),Ve=i.useRef(0),at=ys(p=>p.homeDirectory),ze=ys(p=>p.currentDirectory),je=Pt(p=>p.projects),Ae=Pt(p=>p.activeProjectId),ot=Pt(p=>p.removeProject),ht=Pt(p=>p.setActiveProjectIdOnly),pt=Pt(p=>p.updateProjectMeta),ge=Pt(p=>p.reorderProjects),Ye=ue(p=>p.setActiveMainTab),Tt=ue(p=>p.openContextPanelTab),S=ue(p=>p.setSettingsDialogOpen),Z=ue(p=>p.setSettingsPage),ae=ue(p=>p.toggleHelpDialog),ye=ue(p=>p.setSessionSwitcherOpen),Re=ue(p=>p.setArchivePageOpen),Ke=ue(p=>p.notifyOnSubtasks),nt=ue(p=>p.showDeletionDialog),ct=ue(p=>p.setShowDeletionDialog),Gt=wc(u,120),it=i.useMemo(()=>Gt.trim().toLowerCase(),[Gt]),gt=it.length>0,yt=Ot(p=>p.collapsedFolderIds),Je=Ot(p=>p.foldersMap),Bt=Ot(p=>p.getFoldersForScope),_t=Ot(p=>p.createFolder),Et=Ot(p=>p.renameFolder),xt=Ot(p=>p.deleteFolder),Mt=Ot(p=>p.addSessionToFolder),D=Ot(p=>p.addSessionsToFolder),fe=Ot(p=>p.removeSessionFromFolder),Ne=Ot(p=>p.removeSessionsFromFolders),Le=Ot(p=>p.toggleFolderCollapse),We=Ot(p=>p.getSessionFolderId);gf({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:w,sessionSearchContainerRef:m});const kt=Sc(e),E=mi(),X=hi(),ce=xn(p=>p.connection,void 0,"chrome"),$e=xn(p=>{for(const J of p.catalog.listStatusByDirectory.values())if(J==="ready")return!0;return!1},void 0,"catalog"),he=or({archived:!1}),Te=or({archived:!0}),lt=`session-sidebar:${i.useId()}`,vt=Me(p=>p.setCurrentSession),$t=Me(p=>p.updateSessionTitle),Ft=Me(p=>p.shareSession),Ht=Me(p=>p.unshareSession),zt=Me(p=>p.availableWorktreesByProject)??new Map,mt=Me(p=>p.openNewSessionDraft),Lt=i.useCallback(p=>{ue.getState().closeMainSurfaces(),mt(p),r?.()},[r,mt]),L=yn(ho(p=>({checkForUpdates:p.checkForUpdates,available:p.available,runtimeType:p.runtimeType,info:p.info,downloading:p.downloading,downloaded:p.downloaded,progress:p.progress,error:p.error,downloadUpdate:p.downloadUpdate,restartToUpdate:p.restartToUpdate}))),q=i.useMemo(()=>jc(je,zt,{includeWorktrees:!0}),[zt,je]),ee=i.useMemo(()=>he.filter(p=>Gh(p,q,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[he,q]),te=i.useMemo(()=>[...ee,...Te],[Te,ee]),re=Dn(),rt=i.useMemo(()=>`${re}|${je.map(p=>`${p.id}:${qe(p.path)??""}`).join("|")}`,[je,re]),[wt,St]=i.useState(null),Ut=wt!==rt,[es,jt]=i.useState(new Set),cs=i.useMemo(()=>vr(),[]),{isTablet:Ss}=Vs(),js=s||Ss,{buildGroupSearchText:Rn,filterSessionNodesForSearch:Zs,buildGroupedSessions:Fn}=pf({homeDirectory:at,pinnedSessionIds:ve,sessionOrderRanks:Pe}),{scheduleCollapsedProjectsPersist:Xs}=bf({safeStorage:f,keys:{sessionExpanded:Ho,projectCollapse:zo,groupOrder:Uo,groupCollapse:Ko},groupOrderByProject:H,collapsedGroups:Be,setExpandedParents:h,setCollapsedProjects:M}),ts=i.useMemo(()=>kc(ee,ve,Pe),[ve,Pe,ee]),ks=i.useMemo(()=>ts.map(p=>p.id).join("|"),[ts]),$s=i.useRef(null),en=i.useMemo(()=>{const p=$s.current;if(p&&p.signature===ks)return p.map;const J=new Map(ts.map((Q,Oe)=>[Q.id,Oe]));return $s.current={signature:ks,map:J},J},[ts,ks]),_=i.useMemo(()=>{const p=new Map;return ts.forEach(J=>{const Q=J.parentID;if(!Q)return;const Oe=p.get(Q)??[];Oe.push(J),p.set(Q,Oe)}),p.forEach(J=>J.sort((Q,Oe)=>jn(Q,Oe,ve,Pe))),p},[ts,ve,Pe]),De=i.useMemo(()=>t.jsx(gs,{icon:"chat-new",mobileVariant:s,onClick:()=>Lt(),children:"New session"}),[s,Lt]),Ze=i.useMemo(()=>je.find(p=>p.id===C)??null,[je,C]),dt=i.useCallback(p=>{C&&pt(C,{label:p.label,defaultModel:p.defaultModel??null})},[C,pt]),Ct=i.useCallback(()=>{const p=yn.getState();if(p.available&&p.info){se(!0);return}L.checkForUpdates().then(()=>{const{available:J,error:Q}=yn.getState();if(Q){oe.error("Failed to check for updates",{description:Q});return}if(!J){oe.success("You are on the latest version");return}se(!0)})},[L]),ut=Cc(),Yt=i.useCallback(()=>{if(s&&ye(!1),r?.(),ut?.openSettings){ut.openSettings();return}S(!0)},[ut,s,r,ye,S]),Kt=L.available&&(L.runtimeType==="desktop"||L.runtimeType==="web"),qt=Me(p=>p.deleteSession),Cs=Me(p=>p.deleteSessions),Nt=Me(p=>p.archiveSession),It=Me(p=>p.archiveSessions),Ns=Me(p=>p.unarchiveSession),Zi=Me(p=>p.unarchiveSessions),{copiedSessionId:Xi,handleSessionSelect:ea,handleSessionDoubleClick:ta,handleSaveEdit:sa,handleCancelEdit:na,handleShareSession:ra,handleCopyShareUrl:oa,handleCopySessionId:ia,handleUnshareSession:aa,handleDeleteSession:la,handleRestoreSession:ca,confirmDeleteSession:da}=xf({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:y,setIsSessionSearchOpen:d,setActiveMainTab:Ye,setSessionSwitcherOpen:ye,setCurrentSession:vt,updateSessionTitle:$t,shareSession:Ft,unshareSession:Ht,deleteSession:qt,deleteSessions:Cs,archiveSession:Nt,archiveSessions:It,unarchiveSession:Ns,childrenMap:_,showDeletionDialog:nt,setDeleteSessionConfirm:ke,deleteSessionConfirm:$,setEditingId:v,setEditTitle:j,editingId:x,editTitle:g}),ua=i.useCallback(()=>{if(!Ie)return;const{scopeKey:p,folderId:J}=Ie;_e(null),xt(p,J)},[Ie,xt]),Er=i.useCallback(()=>{bs.requestDirectoryDialog()},[]),fa=i.useCallback(p=>{h(J=>{const Q=Nc(J,p);try{f.setItem(Ho,JSON.stringify(Array.from(Q)))}catch{}return Q})},[f]),Mr=i.useCallback((p,J)=>{if(!p)return null;J&&yt.has(J)&&Le(J);const Q=_t(p,"New folder",J);return A(Q.id),le(Q.name),Q},[yt,Le,_t]),Ar=Wt(ea),ha=Wt(ta),ma=Wt(sa),pa=Wt(na),ga=Wt(ra),xa=Wt(oa),ba=Wt(ia),ya=Wt(aa),va=Wt(la),wa=Wt(ca),Ln=Wt(Mr),Rr=i.useCallback((p,J)=>{U(Q=>{const Oe=new Map(Q);return Oe.set(p,J+7),Oe})},[]),tn=i.useCallback(p=>{U(J=>{if(!J.has(p))return J;const Q=new Map(J);return Q.delete(p),Q})},[]),Fr=i.useCallback(p=>{U(J=>{let Q=!1;const Oe=new Map(J),ft=`${p}:`;for(const Jt of Oe.keys())Jt.startsWith(ft)&&(Oe.delete(Jt),Q=!0);return Q?Oe:J})},[]),Sa=i.useCallback(p=>{Ve.current=Date.now()+150,Fr(p),M(J=>{const Q=new Set(J);Q.has(p)?Q.delete(p):Q.add(p);try{f.setItem(zo,JSON.stringify(Array.from(Q)))}catch{}return Xs(Q),Q})},[Fr,f,Xs]),ds=i.useMemo(()=>je.map(p=>({...p,normalizedPath:qe(p.path)})).filter(p=>!!p.normalizedPath),[je]),ja=i.useMemo(()=>ds.map(p=>p.normalizedPath),[ds]),Lr=Ic(e?ja:Qn);vf({enabled:e,normalizedProjects:ds,gitRepoStatus:Lr,setProjectRepoStatus:B,setProjectRootBranches:be});const ka=Me(p=>p.isLoading),Or=i.useMemo(()=>Pf(ee,ds,zt,Te),[Te,zt,ds,ee]);Cf({enabled:e,hasAuthoritativeGlobalSessions:$e,sessions:te});const{getSessionsForProject:Ca,getArchivedSessionsForProject:Na}=wf({ownership:Or});df({enabled:e,normalizedProjects:ds,ownership:Or,isSessionsLoading:ka,hasAuthoritativeGlobalSessions:$e,isWorktreeTopologyLoading:Ut,unresolvedWorktreeProjectPaths:es,foldersMap:Je,createFolder:_t,addSessionToFolder:Mt});const Br=i.useRef(!1);Ae&&P.has(Ae)&&(Br.current=!!P.get(Ae));const Ia=Lo(p=>p.showArchivedSessions),_r=Lo(p=>p.stickyZoneHeaders),On=Pt(p=>p.manualProjectOrder),$r=i.useRef(new Set),sn=Dc($r.current,b,"project");$r.current=sn;const Bn={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:Ss,catalogSessions:he,archivedSessions:Te,projects:je,activeProjectId:Ae,manualProjectOrder:On,currentDirectory:ze,availableWorktreesByProject:zt,pinnedSessionIds:ve,sessionOrderRanks:Pe,foldersMap:Je,collapsedFolderIds:yt,gitBranches:kt,gitRepoStatus:Lr,updateStore:L,showArchivedSessions:Ia,projectRepoStatus:P,projectRootBranches:Y,resolvedWorktreeTopologyKey:wt,unresolvedWorktreeProjectPaths:es,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:x,editTitle:g,editingProjectDialogId:C,expandedParents:b,collapsedProjects:I,visibleSessionCountByGroup:z,updateDialogOpen:ne,openSidebarMenuKey:K,renamingFolderId:R,renameFolderDraft:V,deleteSessionConfirm:$,deleteFolderConfirm:Ie,bulkDeleteConfirm:Ge,collapsedGroups:Be},zr=i.useRef(null),Ur=zr.current;if(Ur){let p=!1;for(const J of Object.keys(Bn))Object.is(Ur[J],Bn[J])||(Zt(`ui.session_sidebar.source.${J}`),p=!0);p||Zt("ui.session_sidebar.source.parent_or_context")}zr.current=Bn;const Da=i.useMemo(()=>{const p=new Map(On.map((J,Q)=>[J,Q]));return[...ds].sort((J,Q)=>(p.get(J.id)??1/0)-(p.get(Q.id)??1/0))},[On,ds]),{projectSections:bt,groupSearchDataByGroup:Kr,flatSectionsForRender:nn,searchMatchCount:Pa}=ff({normalizedProjects:Da,getSessionsForProject:Ca,getArchivedSessionsForProject:Na,projectRepoStatus:P,projectRootBranches:Y,lastRepoStatus:Br.current,buildGroupedSessions:Fn,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,filterSessionNodesForSearch:Zs,buildGroupSearchText:Rn,foldersMap:Je}),Ta=i.useMemo(()=>t.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[t.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),t.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Ea}=uf(H),Gr=i.useRef(!1);i.useEffect(()=>{if(Gr.current||bt.length===0)return;const p=bt.flatMap(J=>J.groups.filter(Q=>Q.isArchivedBucket).map(Q=>`${J.project.id}:${Q.id}`));p.length>0&&W(J=>new Set([...J,...p])),Gr.current=!0},[bt]),i.useMemo(()=>{const p=new Map,J=new Map;return bt.forEach(Q=>{const Oe=In(Q.project.label?.trim()||xs(Q.project.normalizedPath,at)||Q.project.normalizedPath);Q.groups.forEach(ft=>{const Jt=ft.branch&&ft.branch!=="HEAD"&&ft.branch!==Oe?ft.branch:null,zs={projectLabel:Oe,branchLabel:Jt},fs=rl=>{rl.forEach(Is=>{const Qr=Q.project.normalizedPath.length,ol=J.get(Is.session.id)??-1;Qr<ol||(p.set(Is.session.id,{node:Is,projectId:Q.project.id,groupDirectory:ft.directory,secondaryMeta:zs}),J.set(Is.session.id,Qr),Is.children.length>0&&fs(Is.children))})};fs(ft.sessions)})}),p},[bt,at]);const _n=i.useMemo(()=>nn.map(p=>p.groups.some(J=>J.isArchivedBucket)?{...p,groups:p.groups.filter(J=>!J.isArchivedBucket)}:p),[nn]),Ma=i.useMemo(()=>T?_n.filter(p=>p.project.id===T):_n,[_n,T]),Aa=i.useMemo(()=>{let p=0;for(const J of bt)for(const Q of J.groups)Q.isArchivedBucket||(p+=Q.sessions.length);return p},[bt]),Ra=i.useMemo(()=>{const p=new Map;for(const J of bt){let Q=0;for(const Oe of J.groups)Oe.isArchivedBucket||(Q+=Oe.sessions.length);p.set(J.project.id,Q)}return p},[bt]),Fa=i.useCallback(p=>{const J=bt.find(Q=>Q.project.id===p);return J?J.groups.some(Q=>Q.isArchivedBucket?!1:Q.sessions.some(Oe=>we.has(Oe.session.id))):!1},[we,bt]),La=i.useCallback(p=>{const J=bt.find(Q=>Q.project.id===p);return J?J.groups.some(Q=>Q.isArchivedBucket?!1:Q.sessions.some(Oe=>Ce.has(Oe.session.id))):!1},[bt,Ce]),Oa=s?"flex size-9 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",Ba=s?"size-4":"h-4.5 w-4.5",_a=Tf({enabled:e&&_r,isDesktopShellRuntime:cs,projectSections:bt,projectHeaderSentinelRefs:de}),rn=Wt((p,J=0,Q,Oe,ft=!1,Jt,zs="project",fs)=>t.jsx(Oh,{node:p,depth:J,groupDirectory:Q,projectId:Oe,archivedBucket:ft,pinnedSessionIds:ve,expandedParents:sn,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,notifyOnSubtasks:Ke,editingId:x,setEditingId:v,editTitle:g,setEditTitle:j,handleSaveEdit:ma,handleCancelEdit:pa,toggleParent:fa,handleSessionSelect:Ar,handleSessionDoubleClick:ha,togglePinnedSession:Qe,handleShareSession:ga,copiedSessionId:Xi,handleCopyShareUrl:xa,handleCopySessionId:ba,handleUnshareSession:ya,openSidebarMenuKey:K,setOpenSidebarMenuKey:G,renamingFolderId:R,getFoldersForScope:Bt,getSessionFolderId:We,removeSessionFromFolder:fe,addSessionToFolder:Mt,createFolderAndStartRename:Ln,openContextPanelTab:Tt,handleDeleteSession:va,handleRestoreSession:wa,mobileVariant:s,alwaysShowActions:js,renderSessionNode:rn,secondaryMeta:Jt,renderContext:zs,subtreeContainsEditing:fs?.subtreeContainsEditing??Hh,menuOpenSessionId:fs?.menuOpenSessionId??null,nodeStructureKey:fs?.nodeStructureKey??"",childRenderExtrasFor:fs?.childRenderExtrasFor})),$a=i.useMemo(()=>{const p=new Map;return nn.forEach(J=>{const Q=J.groups.find(Oe=>!Oe.isArchivedBucket);Q?.folderScopes&&Q.folderScopes.length>0&&p.set(J.project.id,Q.folderScopes)}),p},[nn]),za=i.useCallback((p,J)=>{const Q=[];return J.forEach(Oe=>{Oe.isArchivedBucket||(Q.push(Oe.directory),Oe.folderScopes?.forEach(ft=>Q.push(ft.directory)))}),t.jsx(qh,{directories:Q})},[]),Hr=i.useCallback(p=>{tn(p),W(J=>{const Q=new Set(J);return Q.has(p)?Q.delete(p):Q.add(p),Q})},[tn]),Ua=i.useCallback((p,J,Q,Oe,ft,Jt,zs)=>t.jsx(Vf,{group:p,groupKey:J,projectId:Q,hideGroupLabel:Oe,dragHandleProps:ft,compactBodyPadding:Jt,hasSessionSearchQuery:gt,normalizedSessionSearchQuery:it,groupSearchDataByGroup:Kr,visibleSessionCount:z.get(J),collapsedGroups:Be,hideDirectoryControls:a,collapsedFolderIds:yt,toggleFolderCollapse:Le,renameFolder:Et,deleteFolder:xt,showDeletionDialog:nt,setDeleteFolderConfirm:_e,renderSessionNode:rn,showMoreGroupSessions:Rr,resetGroupSessionLimit:tn,mobileVariant:s,alwaysShowActions:js,activeProjectId:Ae,setActiveProjectIdOnly:ht,setActiveMainTab:Ye,setSessionSwitcherOpen:ye,openNewSessionDraft:Lt,addSessionToFolder:Mt,createFolderAndStartRename:Ln,renamingFolderId:R,renameFolderDraft:V,setRenameFolderDraft:le,setRenamingFolderId:A,pinnedSessionIds:ve,expandedParents:sn,sessionOrderIndex:en,editingId:x,editTitle:g,openSidebarMenuKey:K,activeActivitySessionIds:we,unreadActivitySessionIds:Ce,notifyOnSubtasks:Ke,onToggleCollapsedGroup:Hr,scrollContainerRef:zs}),[gt,it,Kr,z,Be,a,yt,Le,Et,xt,nt,rn,Rr,tn,s,js,Ae,ht,Ye,ye,Lt,Mt,Ln,R,V,ve,sn,en,x,g,K,we,Ce,Ke,Hr]),Wr=!!(R||x||C),{selectionModeEnabled:qr,hasSelection:Ka,selectedIdsSize:Ga,bulkScopeIsArchived:Ha,derivedSelectionScope:Wa,bulkScopeFolders:qa,bulkCanRemoveFromFolder:Qa,handleToggleSelectionMode:Va,handleExitSelectionMode:Ya,handleBulkMoveToFolder:Ja,handleBulkCreateFolderAndMove:Za,handleBulkRemoveFromFolder:Xa,handleBulkDelete:el,handleBulkRestore:tl,confirmBulkDelete:sl}=Kh({isInlineEditing:Wr,showDeletionDialog:nt,foldersMap:Je,folderScopesByProject:$a,addSessionsToFolder:D,removeSessionsFromFolders:Ne,createFolderAndStartRename:Mr,archiveSessions:It,unarchiveSessions:Zi,deleteSessions:Cs,setBulkDeleteConfirm:Fe}),nl=i.useCallback(()=>{ue.getState().closeMainSurfaces(),Ye("chat"),s&&ye(!1),mt(),r?.()},[s,r,mt,Ye,ye]);return t.jsx(Pc,{delay:0,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:m,className:F("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(Wh,{owner:lt,childStores:X,projectSections:bt,activeProjectId:Ae,collapsedProjects:I,collapsedGroups:Be,currentDirectory:ze}),t.jsx(mf,{projectSections:bt,activeProjectId:Ae,initialActiveSessionByProject:pe,persistActiveSessionByProject:Se,handleSessionSelect:Ar,mobileVariant:s,openNewSessionDraft:mt,setActiveMainTab:Ye,setSessionSwitcherOpen:ye}),t.jsx(cf,{enabled:e,sortedSessions:ts,prefetchSession:async p=>{await E.syncSession(p)}}),!a&&!s?t.jsx(Jf,{onNewSession:nl,showSidebarToggle:!0}):null,t.jsx(Yf,{hideDirectoryControls:a,handleOpenDirectoryDialog:Er,onOpenArchive:()=>{s&&ye(!1),Re(!0)},onOpenSettings:s?Yt:void 0,onOpenInstances:s?ut?.openInstances:void 0,instanceLabel:s?ut?.instanceLabel:void 0,onOpenUpdate:s?ut?.openUpdate:void 0,headerActionIconClass:Ba,headerActionButtonClass:Oa,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:w,sessionSearchQuery:u,setSessionSearchQuery:y,hasSessionSearchQuery:gt,searchMatchCount:Pa,selectionModeEnabled:qr,onToggleSelectionMode:Va,mobileVariant:s}),ce==="error"||ce==="unavailable"?t.jsx("div",{role:"alert",className:"mx-3 mb-2 rounded bg-[var(--status-error-background)] p-2 text-xs text-[var(--status-error-foreground)]",children:"Unable to reach server"}):null,!a&&bt.length>0?t.jsx(eh,{projects:bt.map(p=>p.project),selectedProjectId:T,onSelectProject:p=>{O(p),p&&ht(p)},onOpenDirectoryDialog:Er,onOpenProjectEditDialog:N,onRemoveProject:ot,totalSessionCount:Aa,getSessionCountForProject:p=>Ra.get(p)??0,hasActiveSessionByProject:Fa,hasUnseenByProject:La,homeDirectory:at,mobileVariant:s}):null,e||s?t.jsx(ch,{sectionsForRender:Ma,projectSections:bt,activeProjectId:Ae,showOnlyMainWorkspace:l,hasSessionSearchQuery:gt,emptyState:De,searchEmptyState:Ta,isAllFoldersView:T===null,pinnedSessionIds:ve,renderSessionNode:rn,renderGroupSessions:Ua,homeDirectory:at,collapsedProjects:I,hideDirectoryControls:a,projectRepoStatus:P,isDesktopShellRuntime:cs,stickyZoneHeaders:_r,stuckProjectHeaders:_a,mobileVariant:s,alwaysShowActions:js,toggleProject:Sa,setActiveProjectIdOnly:ht,setActiveMainTab:Ye,setSessionSwitcherOpen:ye,openNewSessionDraft:Lt,openProjectEditDialog:N,removeProject:ot,projectHeaderSentinelRefs:de,reorderProjects:ge,getOrderedGroups:Ea,setGroupOrderByProject:ie,renderProjectStatusIndicator:za,openSidebarMenuKey:K,setOpenSidebarMenuKey:G,isInlineEditing:Wr}):null,qr&&Ka?t.jsx(Uh,{selectedCount:Ga,scopeKey:Wa,scopeFolders:qa,archivedBucket:Ha,onMoveToFolder:Ja,onCreateFolderAndMove:Za,onRemoveFromFolder:Xa,canRemoveFromFolder:Qa,onRestore:tl,onDelete:el,onDone:Ya}):null,s?null:t.jsx(th,{onOpenSettings:Yt,onOpenShortcuts:ae,onOpenAbout:()=>{Z("about"),S(!0)},onOpenUpdate:Ct,showRuntimeButtons:!0,showUpdateButton:Kt}),t.jsx(Zd,{open:ne,onOpenChange:se,info:L.info,downloading:L.downloading,downloaded:L.downloaded,progress:L.progress,error:L.error,onDownload:L.downloadUpdate,onRestart:L.restartToUpdate,runtimeType:L.runtimeType}),t.jsx(Ef,{open:!!Ze,onOpenChange:p=>{p||N(null)},project:Ze,onSave:dt}),t.jsx(_h,{value:$,setValue:ke,showDeletionDialog:nt,setShowDeletionDialog:ct,onConfirm:da}),t.jsx(zh,{value:Ie,setValue:_e,onConfirm:ua}),t.jsx($h,{value:Ge,setValue:Fe,showDeletionDialog:nt,setShowDeletionDialog:ct,onConfirm:sl})]})})},Ip=i.memo(Qh),Vh=({value:e,options:s,disabled:n,onChange:r})=>{const o=e||"Default",a=t.jsxs("div",{className:F("flex h-6 w-fit items-center gap-1.5 rounded-lg border border-border/20 bg-interactive-selection/20 px-2",n?"cursor-not-allowed opacity-60":"cursor-pointer hover:bg-interactive-hover/30"),children:[t.jsx("span",{className:"typography-micro whitespace-nowrap font-medium capitalize",children:o}),t.jsx(k,{name:"arrow-down-s",className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]});return n?a:t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:a}),t.jsxs(Xt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(Rt,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:F("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(Rt,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:F("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Wo=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function Yh(e){const{open:s,onOpenChange:n,projectDirectory:r,submitting:o=!1,onConfirm:a}=e,l=Vt(h=>h.loadProviders),c=Vt(h=>h.loadAgents),d=Vt(h=>h.providers),u=Vt(h=>h.currentProviderId),y=Vt(h=>h.currentModelId),m=Vt(h=>h.currentVariant||""),w=Vt(h=>h.currentAgentName||""),[x,v]=i.useState(()=>Wo({providerID:u,modelID:y,variant:m,agent:w}));i.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),i.useEffect(()=>{s&&v(Wo({providerID:u,modelID:y,variant:m,agent:w}))},[s,u,y,m,w]),i.useEffect(()=>{if(!s||d.length===0)return;const h=d.find(T=>T.id===x.providerID)??d[0],f=Array.isArray(h?.models)?h.models:[],I=f.some(T=>T.id===x.modelID),M=f[0]?.id??"";h?.id===x.providerID&&I||v(T=>({...T,providerID:typeof h?.id=="string"?h.id:"",modelID:typeof M=="string"?I?T.modelID:M:"",variant:""}))},[s,d,x.providerID,x.modelID]),i.useCallback(h=>Tc(h.mode),[]);const g=i.useMemo(()=>{const f=d.find(I=>I.id===x.providerID)?.models?.find(I=>I.id===x.modelID);return f?.variants?Object.keys(f.variants):[]},[d,x.providerID,x.modelID]),j=g.length>0;i.useEffect(()=>{j||!x.variant||v(h=>({...h,variant:""}))},[j,x.variant]);const C=x.providerID.trim().length>0&&x.modelID.trim().length>0,N=i.useCallback(()=>{!C||o||a(x)},[C,o,a,x]);return i.useEffect(()=>{if(!s)return;const h=f=>{(f.metaKey||f.ctrlKey)&&f.key==="Enter"&&(f.preventDefault(),N())};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[s,N]),t.jsx(os,{open:s,onOpenChange:h=>{o||n(h)},children:t.jsxs(is,{className:"max-w-md overflow-visible",children:[t.jsx(vs,{children:t.jsx(us,{children:"Send to new session"})}),t.jsx("div",{className:"flex flex-col gap-4",children:t.jsxs("div",{className:"flex flex-col gap-1.5",children:[t.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Thinking level"}),t.jsx(Vh,{value:x.variant,options:g,disabled:!j,onChange:h=>v(f=>({...f,variant:h}))})]})}),t.jsx("div",{className:"flex items-center justify-end gap-3",children:t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>n(!1),disabled:o,children:"Cancel"}),t.jsx(Ee,{size:"sm",onClick:N,disabled:!C||o,children:o?"Sending":"Send"})]})})]})})}const br=5,Vi=15,mn=new Map,wn=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},Jh=(e,s)=>{const n=wn(s);return Math.max(n*br,Math.min(n*Vi,n*e))},Zh=async(e,s)=>{const n=await Lc(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},Xh=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,qo=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],Qo=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},em=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:o,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=Mn({id:e});return t.jsx("li",{ref:o,style:{transform:An.Transform.toString(l),transition:c},className:F(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},tm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[o,a]=i.useState(!1),[l,c]=i.useState(""),[d,u]=i.useState([]),[y,m]=i.useState(""),[w,x]=i.useState(null),[v,g]=i.useState(()=>new Set),[j,C]=i.useState([]),[N,b]=i.useState(null),[h,f]=i.useState(!1),[I,M]=i.useState(0),T=i.useRef(!1),O=i.useRef(""),P=i.useRef(null),B=ue(S=>S.todoPanelHeight),z=ue(S=>S.setTodoPanelHeight),U=ue(S=>S.notesPanelHeight),ne=ue(S=>S.setNotesPanelHeight),[se,K]=i.useState(!1),G=i.useRef(0),R=i.useRef(B),A=Me(S=>S.currentSessionId),V=Me(S=>S.createSession),le=Me(S=>S.initializeNewPiChamberSession),$=Me(S=>S.sendMessage),ke=Me(S=>S.setCurrentSession),Ie=Ec(S=>S.setPendingInputText),_e=ys(S=>S.currentDirectory),Ge=ue(S=>S.openContextPanelTab),Fe=ue(S=>S.setActiveMainTab),ve=ue(S=>S.setSessionSwitcherOpen),Pe=ue(S=>S.padding),me=i.useCallback(async(S,Z)=>{if(!e)return!1;const ae=e.id,Re=(mn.get(ae)??Promise.resolve()).catch(()=>{}).then(()=>Mc(e,{notes:S,todos:Z}));mn.set(ae,Re);try{const Ke=await Re;return Ke||oe.error("Failed to save project notes"),Ke}finally{mn.get(ae)===Re&&mn.delete(ae)}},[e]);i.useEffect(()=>{if(!e){c(""),u([]),C([]),m(""),g(new Set);return}let S=!1;return a(!0),(async()=>{try{const Z=await Ac(e),ae=await Promise.all(Z.plans.map(ye=>Zh(ye,"Plan")));if(S)return;c(Z.notes),u(qo(Z.todos)),C(ae),O.current=Z.notes,T.current=!0,m(""),g(new Set)}catch{S||(oe.error("Failed to load project notes"),c(""),u([]),C([]),O.current="",T.current=!0)}finally{S||a(!1)}})(),()=>{S=!0}},[I,e]),i.useEffect(()=>{if(!e)return;const S=Z=>{const ae=Z.detail;ae?.projectId&&ae.projectId!==e.id||M(ye=>ye+1)};return window.addEventListener("pichamber:project-plan-saved",S),window.addEventListener("pichamber:project-notes-updated",S),()=>{window.removeEventListener("pichamber:project-plan-saved",S),window.removeEventListener("pichamber:project-notes-updated",S)}},[e]),i.useEffect(()=>{if(d.length<7)return;const S=Jh(d.length,Pe),Z=wn(Pe)*br;B!==S&&(B<Z||B>S)&&z(S)},[d.length,Pe,B,z]),i.useEffect(()=>{if(!se)return;const S=ae=>{const ye=ae.clientY-G.current,Re=Math.min(wn(Pe)*Vi,Math.max(wn(Pe)*br,R.current+ye));z(Re)},Z=()=>{K(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",Z,{once:!0}),window.addEventListener("pointercancel",Z,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",Z),window.removeEventListener("pointercancel",Z)}},[se,Pe,z]);const He=i.useCallback(S=>{K(!0),G.current=S.clientY,R.current=B,S.preventDefault()},[B]),we=i.useCallback(()=>{P.current!==null&&(window.clearTimeout(P.current),P.current=null)},[]),xe=i.useCallback(()=>{we(),O.current=l,me(l,d)},[we,l,me,d]);i.useEffect(()=>{if(!(!e||!T.current)&&l!==O.current)return P.current=window.setTimeout(()=>{P.current=null,O.current=l,me(l,d)},400),()=>{we()}},[we,l,me,e,d]),i.useEffect(()=>()=>we(),[we]);const Ce=i.useCallback(()=>{const S=y.trim();if(!S)return;const Z=Qo(d,{id:Xh(),text:S.slice(0,on),completed:!1,createdAt:Date.now()});u(Z),m(""),me(l,Z)},[y,l,me,d]),Qe=i.useCallback(S=>{g(Z=>{const ae=new Set(Z);return ae.has(S)?ae.delete(S):ae.add(S),ae})},[]),Be=i.useCallback((S,Z)=>{const ae=d.find(nt=>nt.id===S);if(!ae||ae.completed===Z)return;const ye=d.filter(nt=>nt.id!==S),Re={...ae,completed:Z},Ke=Z?[...ye,Re]:Qo(ye,Re);u(Ke),me(l,Ke)},[l,me,d]),W=i.useCallback(S=>{const Z=d.filter(ae=>ae.id!==S);u(Z),me(l,Z)},[l,me,d]),H=i.useCallback(()=>{const S=d.filter(Z=>!Z.completed);S.length!==d.length&&(u(S),me(l,S))},[l,me,d]),ie=i.useCallback(S=>{const{active:Z,over:ae}=S;if(!ae||Z.id===ae.id)return;const ye=d.findIndex(nt=>nt.id===Z.id),Re=d.findIndex(nt=>nt.id===ae.id);if(ye===-1||Re===-1)return;const Ke=qo(jd(d,ye,Re));u(Ke),me(l,Ke)},[l,me,d]),pe=Pn(qs(kr,{activationConstraint:{distance:8}})),Se=y.slice(0,on),Y=d.reduce((S,Z)=>S+(Z.completed?1:0),0),be=i.useCallback(()=>{Fe("chat"),ve(!1)},[Fe,ve]),de=i.useCallback((S,Z)=>{!e||w!==null||b({todoId:S,todoText:Z})},[e,w]),Ve=i.useCallback(S=>{if(!A){oe.error("No active session selected");return}be();const Z=`\`\`\`md
|
|
38
|
-
${S}
|
|
39
|
-
\`\`\``;Ie(Z,"append"),oe.success("Todo sent to current session"),n?.()},[A,n,be,Ie]),at=i.useCallback(async S=>{if(!e||!N)return;const Z=await ao("plan.todo.visible",{todo_text:N.todoText}),ye=[{synthetic:!0,text:await ao("plan.todo.instructions",{todo_text:N.todoText})}];f(!0),x(N.todoId);try{be();const Re=await V(void 0,e.path,null);if(!Re?.id){oe.error("Failed to create session");return}const Ke=Re.id,nt=Re.directory??e.path;le(Re.id,Vt.getState().agents??[]);const ct=Rc.getState();ct.saveSessionModelSelection(Ke,S.providerID,S.modelID),S.agent.trim()&&(ct.saveSessionAgentSelection(Ke,S.agent),ct.saveAgentModelForSession(Ke,S.agent,S.providerID,S.modelID),ct.saveAgentModelVariantForSession(Ke,S.agent,S.providerID,S.modelID,S.variant||void 0)),ke(Ke,nt),await $(Z,S.providerID,S.modelID,S.agent.trim()||void 0,void 0,void 0,ye,S.variant||void 0),oe.success("Todo sent to new session"),b(null),n?.()}catch{oe.error("Failed to send note")}finally{f(!1),x(null)}},[V,le,n,N,e,be,$,ke]),ze=i.useRef(null),[je,Ae]=i.useState(!1),[ot,ht]=i.useState(null),pt=i.useCallback(async S=>{if(!(!e||ot)){ht(S);try{if(!await Fc(e,S)){oe.error("Failed to delete plan");return}C(ae=>ae.filter(ye=>ye.id!==S)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{ht(null)}}},[ot,e]),ge=i.useCallback(async()=>{if(!e||je)return;const S=await ad({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(S.success&&S.path){Ae(!0);try{const Z=new URLSearchParams({path:S.path,allowOutsideWorkspace:"true"});S.outsideFileGrant&&Z.set("outsideFileGrant",S.outsideFileGrant);const ae=await rs(`/api/fs/read?${Z.toString()}`,{cache:"no-store"});if(!ae.ok){oe.error("Failed to read plan file");return}const ye=await ae.text();if(!ye.trim()){oe.error("Plan file is empty");return}const Re=S.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await lo(e,ye,Re)){oe.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),oe.success("Plan imported")}catch(Z){const ae=Z instanceof Error?Z.message:void 0;oe.error("Failed to read plan file",ae?{description:ae}:void 0)}finally{Ae(!1)}}else S.error==="Native file picker not available"&&ze.current?.click()},[je,e]),Ye=i.useCallback(async S=>{if(!(!e||!S)){Ae(!0);try{const Z=await S.text();if(!Z.trim()){oe.error("Plan file is empty");return}const ae=S.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await lo(e,Z,ae)){oe.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),oe.success("Plan imported")}catch(Z){const ae=Z instanceof Error?Z.message:void 0;oe.error("Failed to read plan file",ae?{description:ae}:void 0)}finally{Ae(!1)}}},[e]),Tt=i.useCallback(S=>{const Z=e?.path?.trim(),ae=_e?.trim()||Z;ae&&Ge(ae,{mode:"file",targetPath:S.path,dedupeKey:S.path,label:S.title})},[_e,Ge,e]);return e?t.jsxs("div",{className:F("w-full min-w-0 space-y-3 p-3",r),children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:e.path,children:`Quick notes - ${s?.trim()||e.path.split("/").filter(Boolean).pop()||e.path}`}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length,"/",co]})]}),t.jsx(Ir,{value:l,onChange:S=>c(S.target.value.slice(0,co)),onBlur:xe,placeholder:"Capture context, reminders, or links",resizedHeight:U,onResizeHeightChange:ne,useScrollShadow:!0,scrollShadowSize:56,disabled:o})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Todo"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:d.length===1?`${d.length} item`:`${d.length} items`}),t.jsx("button",{type:"button",onClick:H,disabled:o||Y===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:"Clear completed"})]}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:[Se.length,"/",on]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ls,{value:Se,onChange:S=>m(S.target.value.slice(0,on)),onKeyDown:S=>{S.key==="Enter"&&(S.preventDefault(),Ce())},placeholder:"Add a todo",disabled:o,className:"h-8"}),t.jsx("button",{type:"button",onClick:Ce,disabled:o||Se.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Add todo",title:"Add todo",children:t.jsx(k,{name:"add",className:"h-4 w-4"})})]}),t.jsx("div",{className:F("overflow-y-auto rounded-lg border border-border/60 bg-background/40",se&&"transition-none"),style:d.length<7?void 0:{height:`${B}px`,maxHeight:`${B}px`},children:d.length===0?t.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No todos yet. Add a small checklist for this project."}):t.jsx(Tn,{sensors:pe,collisionDetection:En,onDragEnd:ie,children:t.jsx(Cr,{items:d.map(S=>S.id),strategy:ki,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(S=>{const Z=v.has(S.id);return t.jsx(em,{id:S.id,children:ae=>t.jsxs("div",{className:F("flex gap-1.5 px-2.5 py-1.5",Z?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:ae.setActivatorNodeRef,...ae.attributes,...ae.listeners,onClick:ye=>{ye.preventDefault(),ye.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":`Reorder \\"${S.text}\\"`,title:`Reorder \\"${S.text}\\"`,children:t.jsx(k,{name:"draggable",className:"h-3.5 w-3.5"})}),t.jsx("div",{className:"flex h-6 items-center",children:t.jsx(si,{checked:S.completed,onChange:ye=>Be(S.id,ye),ariaLabel:`Mark \\"${S.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>Qe(S.id),className:F("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",Z?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",S.completed&&"text-muted-foreground line-through"),title:Z?void 0:S.text,"aria-label":Z?`Collapse todo \\"${S.text}\\"`:`Expand todo \\"${S.text}\\"`,children:S.text}),t.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:()=>W(S.id),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":`Delete \\"${S.text}\\"`,title:`Delete \\"${S.text}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})}),t.jsxs(as,{children:[t.jsx(ls,{asChild:!0,children:t.jsx("button",{type:"button",disabled:w===S.id,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 disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Send \\"${S.text}\\"`,title:`Send \\"${S.text}\\"`,children:t.jsx(k,{name:"send-plane",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-56",children:[t.jsx(Rt,{onClick:()=>Ve(S.text),children:"Send to current session"}),t.jsx(Rt,{onClick:()=>de(S.id,S.text),children:"Send to new session"})]})]})]})]})},S.id)})})})})}),d.length>=7&&t.jsx("div",{className:F("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",se&&"bg-[var(--interactive-border)]"),onPointerDown:He,role:"separator","aria-orientation":"horizontal","aria-label":"Resize todo list"})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Plans"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:j.length===1?`${j.length} file`:`${j.length} files`})]}),t.jsx("input",{ref:ze,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:S=>{const Z=S.target.files?.[0]??null;Ye(Z),S.currentTarget.value=""}}),t.jsx("button",{type:"button",onClick:ge,disabled:!e||je,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Import plan from file",title:"Import plan from file",children:t.jsx(k,{name:"add",className:"h-3.5 w-3.5"})})]}),t.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:j.length===0?t.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No saved plans yet."}):t.jsx("ul",{className:"divide-y divide-border/50",children:j.map(S=>t.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[t.jsxs("button",{type:"button",onClick:()=>Tt(S),className:"flex min-w-0 flex-1 items-center justify-between gap-3 rounded-md px-1.5 py-1 text-left hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[t.jsx("span",{className:"min-w-0 truncate typography-ui-label text-foreground",children:S.title}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(S.createdAt).toLocaleDateString("en-US")})]}),t.jsx("button",{type:"button",onClick:()=>{pt(S.id)},disabled:ot===S.id,className:"inline-flex h-6 w-6 flex-shrink-0 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 disabled:cursor-not-allowed disabled:opacity-50",title:"Delete plan","aria-label":`Delete plan \\"${S.title}\\"`,children:t.jsx(k,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},S.id))})})]}),t.jsx(Yh,{open:N!==null,onOpenChange:S=>{!S&&!h&&b(null)},projectDirectory:e?.path??null,submitting:h,onConfirm:at})]}):t.jsx("div",{className:F("w-full min-w-0 p-3",r),children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to add notes and todos."})})},Dp=({onActionComplete:e})=>{const s=Pt(c=>c.activeProjectId),n=Pt(c=>c.projects),r=ys(c=>c.homeDirectory),o=i.useMemo(()=>s?n.find(c=>c.id===s)??n[0]??null:n[0]??null,[s,n]),a=i.useMemo(()=>o?{id:o.id,path:o.path}:null,[o]),l=i.useMemo(()=>o?o.label?.trim()||xs(o.path,r)||o.path:null,[o,r]);return t.jsx("div",{className:"h-full min-h-0 overflow-auto bg-transparent",children:t.jsx(tm,{projectRef:a,projectLabel:l,onActionComplete:e})})},Sn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),yr=512*1024,sm=new TextEncoder,nm=new TextDecoder,Vn=e=>{const s=sm.encode(e);if(s.byteLength<=yr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-yr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:nm.decode(r),byteLength:r.byteLength}},Ps=(e,s)=>`${e}\0${s}`,Yn=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},rm="terminal-store";let Vo=!1,Yo=0;const pn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Yo+=1,`tab-${Date.now().toString(36)}-${Yo.toString(36)}`),Jn=e=>typeof e=="object"&&e!==null,om=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function Dt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const im=/^Terminal(?: (\d+))?$/,am=e=>{let s=0;for(const n of e){const r=im.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(s=Math.max(s,o))}return s===0?"Terminal":`Terminal ${s+1}`},Zn=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Xn=e=>({tabs:[e],activeTabId:e.id}),Qt=(e,s)=>e.tabs.findIndex(n=>n.id===s);let er=null,tr=null;const lm=e=>{if(tr&&er?.sessions===e.sessions&&er.nextTabId===e.nextTabId)return tr;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return er={sessions:e.sessions,nextTabId:e.nextTabId},tr=s,s},cm=()=>{const e=xd(()=>ld());if(!e)return;let s=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==s)return s=r.state,e.setItem(n,r)},removeItem:n=>(s=null,e.removeItem(n))}},Xe=ws()(Si(jr((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Dt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=pn(),c=Zn(l,"Terminal");return a.set(r,Xn(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=Dt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=Dt(n),o=s().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(l=>l.id===a)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>s().buffers.get(Ps(Dt(n),r))??Sn,createTab:n=>{const r=Dt(n);if(!r)return"tab-invalid";const o=pn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=am(c?.tabs??[]),y=Zn(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,y]}):l.set(r,Xn(y)),{sessions:l,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=Dt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Qt(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=Dt(n),l=o.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const y=Qt(u,r);if(y<0||u.tabs[y]?.label===l)return c;const m=[...u.tabs];return m[y]={...m[y],label:l},d.set(a,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const a=Dt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Qt(d,r);if(u<0)return l;const y=o?.trim()||null;if(d.tabs[u]?.iconKey===y)return l;const m=[...d.tabs];return m[u]={...m[u],iconKey:y},c.set(a,{...d,tabs:m}),{sessions:c}})},closeTab:(n,r)=>{const o=Dt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Qt(c,r);if(d<0)return a;const u=c.tabs.filter(g=>g.id!==r),y=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,g])=>!(g.directory===o&&g.tabId===r))),m=Object.keys(y).length!==Object.keys(a.projectActionRuns).length,w=Ps(o,r),x=a.buffers.has(w)?Yn(a.buffers,g=>g===w):null;if(u.length===0){const g=pn(),j=Zn(g,"Terminal");return l.set(o,Xn(j)),{sessions:l,nextTabId:a.nextTabId+1,...x?{buffers:x}:{},...m?{projectActionRuns:y}:{}}}let v=c.activeTabId;return c.activeTabId===r&&(v=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:v}),{sessions:l,...x?{buffers:x}:{},...m?{projectActionRuns:y}:{}}})},setTabSessionId:(n,r,o)=>{const a=Dt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Qt(d,r);if(u<0)return l;const y=d.tabs[u],m=o!==null&&y.terminalSessionId!==o,w=o?"running":y.terminalSessionId?"exited":y.lifecycle,x={...y,terminalSessionId:o,lifecycle:w,isConnecting:!1},v=Ps(a,r),g=m&&l.buffers.has(v)?Yn(l.buffers,C=>C===v):null,j=[...d.tabs];return j[u]=x,c.set(a,{...d,tabs:j}),{sessions:c,...g?{buffers:g}:{}}})},setTabLifecycle:(n,r,o)=>{const a=Dt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Qt(d,r);if(u<0)return l;const y=[...d.tabs];return y[u]={...y[u],lifecycle:o,isConnecting:!1},c.set(a,{...d,tabs:y}),{sessions:c}})},setConnecting:(n,r,o)=>{const a=Dt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=Qt(d,r);if(u<0)return l;const y=[...d.tabs];return y[u]={...y[u],isConnecting:o},c.set(a,{...d,tabs:y}),{sessions:c}})},replaceBuffer:(n,r,o,a)=>{const l=Dt(n);e(c=>{const d=c.sessions.get(l);if(!d||Qt(d,r)<0)return c;const u=Ps(l,r),y=c.buffers.get(u)??Sn;if(y.lastSequence>a)return c;const m=Vn(o);if(y.lastSequence===a&&y.byteLength===m.byteLength&&y.chunks.map(v=>v.data).join("")===m.text)return c;const w=c.nextChunkId,x=new Map(c.buffers);return x.set(u,{chunks:m.text?[{id:w,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:a}),{buffers:x,nextChunkId:m.text?w+1:w}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=Dt(n);e(d=>{const u=d.sessions.get(c);if(!u||Qt(u,r)<0)return d;const y=Ps(c,r),m=d.buffers.get(y)??Sn;if(a!==void 0&&a<=m.lastSequence)return d;const w=d.nextChunkId,x=Vn(o),v=l!==void 0&&l!==o?Vn(l).text:void 0,g={id:w,data:x.text,...v!==void 0?{replayData:v}:{},byteLength:x.byteLength},j=[...m.chunks,g];let C=m.byteLength+g.byteLength;for(;C>yr&&j.length>1;){const b=j.shift();if(!b)break;C-=b.byteLength}const N=new Map(d.buffers);return N.set(y,{chunks:j,byteLength:C,lastSequence:a??m.lastSequence}),{buffers:N,nextChunkId:w+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=Dt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const y=Qt(u,r);if(y<0)return c;const m=u.tabs[y],w=a.autoOpened??m.previewAutoOpened,x=a.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===w&&m.previewUrlLocked===x)return c;const v=[...u.tabs];return v[y]={...m,previewUrl:o,previewAutoOpened:w,previewUrlLocked:x},d.set(l,{...u,tabs:v}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=Dt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const d=Qt(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const y=[...c.tabs];return y[d]={...u,previewAutoOpened:!0},l.set(o,{...c,tabs:y}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=Dt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Ps(r,""),c=Yn(o.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:rm,storage:cm(),partialize:lm,merge:(e,s)=>{if(!Jn(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!Jn(u))continue;const y=Array.isArray(u.tabs)?u.tabs:[],m=[],w=new Map;for(const j of y){if(!Jn(j))continue;const C=typeof j.id=="string"?j.id:null;if(!C)continue;const N=om(C);N!==null&&(o=Math.max(o,N));const b=N===null?C:pn();w.set(C,b),m.push({id:b,label:typeof j.label=="string"?j.label:"Terminal",iconKey:typeof j.iconKey=="string"?j.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof j.createdAt=="number"?j.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const x=typeof u.activeTabId=="string"?u.activeTabId:null,v=x?w.get(x)??x:null,g=v?m.some(j=>j.id===v):!1;r.set(d,{tabs:m,activeTabId:g?v:m[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,o+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!Vo){Vo=!0;const e=Xe.persist,s=()=>{Xe.getState().hasHydrated||Xe.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function dm(e){const{colors:s}=e,n=s.syntax.base;return{background:s.surface.background,foreground:n.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:s.surface.elevatedForeground}}function um(e,s,n,r,o=!1){const l=`${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",fontSize:s,fontFamily:l,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:o}}const sr=["\x1B[0m","\x1B[m"],fm=e=>{const s=e.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(s)?.[1];if(n){const a=n.length<=4?n.slice(0,3).split("").map(l=>l+l).join(""):n.slice(0,6);return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16)]}const r=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(s);if(!r)return null;const o=r.slice(1,4).map(Number);return o.some(a=>a<0||a>255)?null:o},Jo=e=>{const s=fm(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},hm=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let o=0;const a=Math.max(...sr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);sr.some(y=>y.length>u.length&&y.startsWith(u))&&(o=d)}const l=o>0?r.slice(-o):"";let c=o>0?r.slice(0,-o):r;for(const d of sr)c=c.replaceAll(d,n);return{data:c,carry:l}},mm=(e,s,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(o-1,l))}},pm=(e,s)=>{const n=Math.max(0,Math.min(e.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,a=n;for(;o>0&&r(e[o-1]);)o-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:o,endColumn:a}};let gm=null;const xm=()=>gm??=Ms(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,8])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),bm=2e3,ym=()=>{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(s=>setTimeout(s,bm))]).then(()=>{})},vm=(e,s,n)=>{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=`${n}px ${s}`;const o=r.measureText("M"),a=Math.ceil(o.width),l=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(a<1||l<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/a)),rows:Math.max(1,Math.floor((e.clientHeight-u)/l))}},Yi=i.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:y=!0},m)=>{const w=i.useRef(null),x=i.useRef(null),v=i.useRef(null),g=i.useRef(n),j=i.useRef(r),C=i.useRef(null),N=i.useRef(null),b=i.useRef(null),h=i.useRef(""),f=i.useRef(""),I=i.useRef(Jo(o.background)),M=i.useRef(!1),T=i.useRef(0),O=i.useRef(y),P=i.useRef(!1),[B,z]=i.useState(0),[U,ne]=i.useState(0);g.current=n,j.current=r,O.current=y,I.current=Jo(o.background),i.useLayoutEffect(()=>{const R=w.current;if(!R)return;const A=vm(R,a,l);N.current=A,A&&j.current(A.cols,A.rows)},[a,l]);const se=i.useCallback(()=>{const R=w.current,A=x.current;if(!R||!A||!v.current||!O.current)return;const V=R.getBoundingClientRect();if(!(V.width<24||V.height<24))try{v.current.fit();const le={cols:A.cols,rows:A.rows};(!C.current||C.current.cols!==le.cols||C.current.rows!==le.rows)&&(C.current=le,j.current(le.cols,le.rows)),P.current||(P.current=!0,z($=>$+1))}catch{}},[]),K=i.useCallback(()=>{if(M.current||!h.current||!x.current)return;const R=x.current,A=h.current;h.current="";const V=hm(A,f.current,I.current);if(f.current=V.carry,!V.data){h.current&&K();return}M.current=!0;const le=T.current;R.write(V.data,()=>{x.current!==R||T.current!==le||(M.current=!1,h.current&&K())})},[]),G=i.useCallback(()=>{b.current=null,h.current="",f.current="",M.current=!1,T.current+=1;const R=x.current;if(!R){ne(A=>A+1);return}try{R.reset();const A=I.current;A&&R.write(`${A}\x1B[2J\x1B[H`)}catch{ne(A=>A+1)}},[]);return i.useEffect(()=>{const R=w.current;if(!R)return;let A=!1,V=null,le=null,$=null,ke=null,Ie=[];const _e=()=>{V&&O.current&&(V.options.cursorBlink=!0)},Ge=Pe=>{Pe.relatedTarget instanceof Node&&R.contains(Pe.relatedTarget)||V&&(V.options.cursorBlink=!1)},Fe=()=>{V&&O.current&&R.contains(document.activeElement)&&(V.options.cursorBlink=!0)},ve=()=>{V&&(V.options.cursorBlink=!1)};return R.addEventListener("focusin",_e),R.addEventListener("focusout",Ge),window.addEventListener("focus",Fe),window.addEventListener("blur",ve),Promise.all([xm(),ym()]).then(([{module:Pe,ghostty:me}])=>{if(A)return;V=new Pe.Terminal({...um(a,l,o,me,!1),...N.current??{}});const He=new Pe.FitAddon;V.loadAddon(He),V.open(R),x.current=V,v.current=He,Ie=[V.onData(xe=>g.current(xe))],le=new ResizeObserver(()=>{$&&clearTimeout($),$=setTimeout(se,80)}),le.observe(R),se();const we=I.current;we&&V.write(`${we}\x1B[2J\x1B[H`),ke=requestAnimationFrame(se)}),()=>{A=!0;const Pe=document.activeElement;Pe instanceof HTMLElement&&R.contains(Pe)&&(Pe.blur(),window.Capacitor?.getPlatform?.()==="android"&&Ms(async()=>{const{Keyboard:He}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:He}},__vite__mapDeps([113,114])).then(({Keyboard:He})=>He.hide()).catch(()=>{})),le?.disconnect(),$&&clearTimeout($),ke!==null&&cancelAnimationFrame(ke),R.removeEventListener("focusin",_e),R.removeEventListener("focusout",Ge),window.removeEventListener("focus",Fe),window.removeEventListener("blur",ve),Ie.forEach(me=>me.dispose()),V?.dispose(),x.current=null,v.current=null,C.current=null,b.current=null,h.current="",f.current="",M.current=!1,T.current+=1,P.current=!1}},[se,a,l,U,o]),i.useEffect(()=>{const R=x.current,A=w.current;!R||!A||(R.options.cursorBlink=y&&document.hasFocus()&&A.contains(document.activeElement))},[y,B]),i.useEffect(()=>{if(!x.current)return;if(s.length===0){b.current!==null&&G();return}const A=b.current;let V=-1;if(A!==null){for(let ke=s.length-1;ke>=0;ke-=1){const Ie=s[ke].id;if(Ie===A){V=ke;break}if(Ie<A)break}if(V<0){G();return}}const le=V<0,$=V>=0?s.slice(V+1):s;h.current+=$.map(ke=>le?ke.replayData??ke.data:ke.data).join(""),b.current=s.at(-1)?.id??null,K()},[s,K,B,G]),i.useEffect(()=>{if(!u||!y)return;const R=requestAnimationFrame(()=>x.current?.focus());return()=>cancelAnimationFrame(R)},[u,y,B,e]),i.useEffect(()=>{const R=w.current;if(!d||!R)return;const A=V=>{const le=V;if(!le.isComposing)switch(le.inputType){case"insertText":le.data&&g.current(le.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return R.addEventListener("beforeinput",A),()=>R.removeEventListener("beforeinput",A)},[d,B]),i.useEffect(()=>{const R=w.current,A=x.current;if(!d||!R||!A)return;let V=null,le=null,$="idle",ke=0,Ie=0,_e=0,Ge=0,Fe=null;const ve=Math.max(12,l+2),Pe=()=>{window.Capacitor?.getPlatform?.()==="android"&&Ms(async()=>{const{Keyboard:ie}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ie}},__vite__mapDeps([113,114])).then(({Keyboard:ie})=>ie.show()).catch(()=>{})},me=()=>{le&&(clearTimeout(le),le=null)},He=(H,ie)=>{const pe=R.querySelector("canvas");return pe?mm(H,ie,pe.getBoundingClientRect(),A.cols,A.rows):null},we=(H,ie)=>{const pe=R.querySelector("canvas");if(!pe)return;const Se=pe.getBoundingClientRect(),Y=Se.left+(ie.column+.5)/A.cols*Se.width,be=Se.top+(ie.row+.5)/A.rows*Se.height;pe.dispatchEvent(new MouseEvent(H,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:Y,clientY:be}))},xe=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},Ce=H=>{H.pointerType!=="touch"||V!==null||(V=H.pointerId,$="pending",ke=H.clientX,Ie=H.clientY,_e=H.clientY,Ge=0,Fe=null,R.setPointerCapture(H.pointerId),le=setTimeout(()=>{if(le=null,V!==H.pointerId||$!=="pending")return;const ie=He(ke,Ie);if(!ie)return;const pe=A.buffer.active,Se=Math.max(0,pe.length-A.rows-pe.viewportY+ie.row),Y=pe.getLine(Se),be=Array.from({length:A.cols},(at,ze)=>Y?.getCell(ze)?.getChars()??""),de=pm(be,ie.column),Ve={column:de.startColumn,row:ie.row};Fe={column:de.endColumn,row:ie.row},$="selecting",we("mousedown",Ve),we("mousemove",Fe)},350))},Qe=H=>{if(V!==H.pointerId)return;if($==="selecting"){const Se=He(H.clientX,H.clientY);Se&&(!Fe||Se.column!==Fe.column||Se.row!==Fe.row)&&(Fe=Se,we("mousemove",Se)),H.cancelable&&H.preventDefault();return}if($==="pending"){if(Math.hypot(H.clientX-ke,H.clientY-Ie)<8)return;me(),$="scrolling"}if($!=="scrolling")return;const ie=_e-H.clientY;_e=H.clientY,Ge+=ie;const pe=Math.trunc(Ge/ve);pe&&(A.scrollLines(pe),Ge-=pe*ve),H.cancelable&&H.preventDefault()},Be=H=>{if(V!==H.pointerId)return;const ie=$==="pending",pe=$==="selecting";me(),R.hasPointerCapture(H.pointerId)&&R.releasePointerCapture(H.pointerId),V=null,$="idle",pe&&xe(),ie&&(A.focus(),Pe())},W=H=>{if(V!==H.pointerId)return;const ie=$==="selecting";me(),R.hasPointerCapture(H.pointerId)&&R.releasePointerCapture(H.pointerId),V=null,$="idle",ie&&xe()};return R.addEventListener("pointerdown",Ce),R.addEventListener("pointermove",Qe,{passive:!1}),R.addEventListener("pointerup",Be),R.addEventListener("pointercancel",W),()=>{me(),R.removeEventListener("pointerdown",Ce),R.removeEventListener("pointermove",Qe),R.removeEventListener("pointerup",Be),R.removeEventListener("pointercancel",W)}},[d,l,B]),i.useImperativeHandle(m,()=>({focus:()=>x.current?.focus(),fit:se,getSelection:()=>{const R=x.current,A=R?.getSelectionPosition(),V=R?.getSelection()??"";return!A||!V.trim()?null:{text:V,startLine:A.start.y+1,endLine:A.end.y+1}}}),[se]),t.jsx("div",{ref:w,"data-terminal-owner":"main",className:F("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});Yi.displayName="TerminalViewport";const wm=280,Zo=4,Sm=({transform:e})=>({...e,y:0}),jm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:o,setNodeRef:a,transform:l,transition:c,isDragging:d}=Mn({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:An.Transform.toString(l),transition:c},className:F("h-full rounded-md",n,d&&"opacity-50"),...r,...o,children:s})},km=({id:e,children:s,className:n})=>t.jsx("div",{className:F("h-full",n),"data-sortable-tab-id":e,children:s}),Cm=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:o,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:y,activePillLowercase:m=!0,nonCompositedIndicator:w=!1,className:x})=>{const v=ue(W=>W.isMobile),{isTablet:g}=Vs(),j=v||g,C=i.useRef(null),[N,b]=i.useState({left:!1,right:!1}),h=i.useMemo(()=>e.map(W=>W.id),[e]),f=a==="scrollable",I=l==="default",M=l==="active-pill",O=M||l==="animated",P=I,B=O||P,z=M&&f,U=O,ne=y??O,se=typeof o=="function",K=se?jm:km,G=i.useRef(new Map),[R,A]=i.useState(null),[V,le]=i.useState(!1),[$,ke]=i.useState(null),Ie=i.useRef(!1),_e=i.useRef(0),Ge=i.useRef(s),Fe=i.useRef(null),ve=i.useMemo(()=>{if(!B||!$||!s||$===s)return 0;const W=e.findIndex(ie=>ie.id===$),H=e.findIndex(ie=>ie.id===s);return W<0||H<0?0:W>H?Zo:-Zo},[s,e,$,B]),Pe=Pn(qs(kr,{activationConstraint:{distance:8}})),me=i.useCallback((W,H)=>!W||!H?W===H:Math.abs(W.left-H.left)<.5&&Math.abs(W.top-H.top)<.5&&Math.abs(W.width-H.width)<.5&&Math.abs(W.height-H.height)<.5,[]),He=i.useCallback((W,H)=>{if(H){G.current.set(W,H);return}G.current.delete(W)},[]),we=i.useCallback(()=>{if(!B||!s){A(be=>be===null?be:null);return}const W=C.current,H=G.current.get(s);if(!W||!H){A(be=>be===null?be:null);return}let ie=0,pe=0,Se=H;for(;Se&&Se!==W;)ie+=Se.offsetLeft,pe+=Se.offsetTop,Se=Se.offsetParent;const Y={left:ie,top:pe,width:H.offsetWidth,height:H.offsetHeight};A(be=>me(be,Y)?be:Y)},[s,me,B]),xe=i.useCallback(()=>{if(!f){b({left:!1,right:!1});return}const W=C.current;if(!W){b({left:!1,right:!1});return}b({left:W.scrollLeft>2,right:W.scrollLeft+W.clientWidth<W.scrollWidth-2})},[f]);i.useEffect(()=>{if(!f){b({left:!1,right:!1});return}const W=C.current;if(!W)return;xe(),W.addEventListener("scroll",xe,{passive:!0});const H=new ResizeObserver(xe);return H.observe(W),()=>{W.removeEventListener("scroll",xe),H.disconnect()}},[f,e.length,xe]),i.useEffect(()=>{if(!B){A(null);return}we();const W=C.current;if(!W)return;const H=new ResizeObserver(()=>{performance.now()-_e.current>wm&&le(!1),we()});if(H.observe(W),s){const ie=G.current.get(s);ie&&H.observe(ie)}return()=>{H.disconnect()}},[s,e.length,we,B]),i.useLayoutEffect(()=>{we()});const Ce=h.join("\0");i.useLayoutEffect(()=>{if(!B){Ie.current=!1,le(!1);return}const W=Fe.current!==Ce;if(Fe.current=Ce,!Ie.current){Ie.current=!0,Ge.current=s;return}const H=Ge.current!==s;if(Ge.current=s,!H||W){le(!1);return}_e.current=performance.now(),le(!0)},[s,Ce,B]),i.useEffect(()=>{if(!f||!s)return;const W=C.current;if(!W)return;const H=window.requestAnimationFrame(()=>{const ie=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),pe=W.querySelector(`[data-sortable-tab-id="${ie}"]`);pe&&(pe.scrollIntoView({block:"nearest",inline:"nearest"}),xe())});return()=>{window.cancelAnimationFrame(H)}},[s,f,e.length,xe]);const Qe=i.useCallback(W=>{if(!o)return;const{active:H,over:ie}=W;!ie||H.id===ie.id||o(String(H.id),String(ie.id))},[o]),Be=t.jsxs("div",{className:F("relative flex h-full min-w-0 flex-1",x),children:[f&&N.left?t.jsx("div",{className:F("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",O?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,f&&N.right?t.jsx("div",{className:F("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",O?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:C,className:F("relative flex h-full min-w-0 flex-1",O?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",O&&"@container/pill-tabs",O&&"pill-tabs__track",O&&(c??"gap-0.5 py-0.5"),P&&"items-center overflow-y-hidden",U&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",f?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:f?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[O&&R?t.jsx("div",{className:F("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",ne&&V&&(w?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:w?{left:`${R.left+ve}px`,top:`${R.top}px`,width:`${R.width}px`,height:`${R.height}px`}:{transform:`translate3d(${R.left+ve}px, ${R.top}px, 0)`,width:`${R.width}px`,height:`${R.height}px`}}):null,P&&R?t.jsx("div",{className:F("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",V&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${R.left+ve}px, 0, 0)`,width:`${R.width}px`},"aria-hidden":!0}):null,e.map(W=>{const H=W.id===s,ie=u&&O&&!H&&!!W.icon,pe=!ie,Se=!!W.icon,Y=u&&O&&H&&!f&&!z,be=W.closable!==!1&&!!r,de=be&&!!W.icon,Ve=f||z?void 0:O?Y?"flex-none basis-auto":v?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",at=be?je=>{je.button===1&&(je.preventDefault(),je.stopPropagation(),r?.(W.id))}:void 0,ze=be?je=>{je.button===1&&je.preventDefault()}:void 0;return t.jsx(K,{id:W.id,className:Ve,children:t.jsxs("div",{ref:je=>He(W.id,je),onAuxClick:at,onMouseDown:ze,className:F("group flex h-full min-w-0 flex-nowrap items-center",f||z?"shrink-0":O?"w-full":"w-full min-w-0",O?"relative z-10 bg-transparent":H?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":H,"aria-label":ie?W.title??W.label:void 0,onClick:()=>n(W.id),onPointerDown:B?()=>{le(!0),ke(W.id)}:void 0,onPointerUp:B?()=>ke(null):void 0,onPointerLeave:B?()=>ke(null):void 0,onPointerCancel:B?()=>ke(null):void 0,className:F(O?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",O&&m?"lowercase":null,O&&(ie?"gap-0":"gap-1.5"),O?z?"shrink-0 whitespace-nowrap px-3 text-center":f?"max-w-56 shrink-0 px-3 text-center":ie?"px-2 !min-w-0 text-center":Y?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":f?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",O?d??(M?v?"h-[38px]":"h-[31px]":"h-7"):null,O?H?"text-foreground":"text-muted-foreground hover:text-foreground":null,O?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:W.title??W.label,children:O?t.jsxs(t.Fragment,{children:[Se?t.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[t.jsx("span",{className:F("flex items-center justify-center transition-opacity",de&&(j?"opacity-0":"group-hover:opacity-0")),children:W.icon}),de?t.jsx("span",{role:"button",tabIndex:-1,className:F("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:je=>{je.stopPropagation()},onClick:je=>{je.stopPropagation(),r?.(W.id)},"aria-label":W.closeLabel??`Close ${W.label} tab`,title:W.closeLabel??`Close ${W.label} tab`,children:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,pe?t.jsx("span",{className:"animated-tabs__label truncate",children:W.label}):null]}):t.jsxs("span",{className:F("flex min-w-0 flex-nowrap items-center gap-1.5",!f&&"justify-center"),children:[Se?t.jsxs("span",{className:F("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",H?"text-[var(--primary-base)]":"text-muted-foreground"),children:[t.jsx("span",{className:F("flex items-center justify-center transition-opacity",de&&(j?"opacity-0":"group-hover:opacity-0")),children:W.icon}),de?t.jsx("span",{role:"button",tabIndex:-1,className:F("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:je=>{je.stopPropagation()},onClick:je=>{je.stopPropagation(),r?.(W.id)},"aria-label":W.closeLabel??`Close ${W.label} tab`,title:W.closeLabel??`Close ${W.label} tab`,children:t.jsx(k,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,t.jsx("span",{className:"truncate leading-[1.2]",children:W.label})]})}),be&&!de?t.jsx("button",{type:"button",onPointerDown:je=>{je.stopPropagation()},onClick:je=>{je.stopPropagation(),r?.(W.id)},className:F("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",O?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",O?H?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":H?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":W.closeLabel??`Close ${W.label} tab`,title:W.closeLabel??`Close ${W.label} tab`,children:t.jsx(k,{name:"close",className:"h-3 w-3"})}):null]})},W.id)})]})]});return se?t.jsxs(Tn,{sensors:Pe,collisionDetection:En,onDragEnd:Qe,modifiers:[Sm],children:[t.jsx(Cr,{items:h,strategy:kd,children:Be}),t.jsx(ji,{dropAnimation:null})]}):Be},Nm="\x1B",Im=new RegExp(`${Nm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Dm=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Pm=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Tm=/Serving HTTP on .*? port (\d{2,5})/i,Em=new Set([".",",",";",":","!","?"]),Mm=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=s.slice(0,-1),a=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=o;continue}if(Em.has(n)){s=s.slice(0,-1);continue}break}return s},Xo=e=>{let s=Mm(e);return s=s.replace("0.0.0.0","127.0.0.1"),s=s.replace("[::1]","127.0.0.1"),s=s.replace("[::]","127.0.0.1"),s},Am=e=>{if(!e)return null;const s=e.replace(Im,""),n=s.match(Tm);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=s.split(`
|
|
40
|
-
`);for(const o of r){if(!Pm.test(o))continue;const a=Array.from(o.matchAll(Dm));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Xo(c[1])).port}catch{return!1}});return Xo((l??a[0])[1])}return null},Rm=async(e,s=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,a=window.setTimeout(()=>o.abort(),s);try{const l=await rs("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},Fm={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Lm=(e,s)=>{if(s&&e.startsWith("arrow-")){const n=s==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return Fm[e]},Ji=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},Om=(e,s)=>e&&(s==="ctrl"?Ji(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),ei={cols:80,rows:24},Pp=({visible:e})=>{const{terminal:s,runtime:n}=ci(),{currentTheme:r}=Oc(),o=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});o.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=Bc(),l=ue(E=>E.terminalFontSize),c=ue(E=>E.terminalShell),d=ue(E=>E.terminalLoginShells.includes(E.terminalShell)),{isMobile:u,isTablet:y,hasTouchOnlyPointer:m}=Vs(),w=u||y,x=(w||m)&&n.platform==="web",v=!0,g=ue(E=>E.showTerminalQuickKeysOnDesktop),j=w||g,C=Me(E=>E.currentSessionId),N=Me(E=>E.newSessionDraft),b=C!==null||N?.open===!0,h=_c()??null,f=Xe(E=>h?E.sessions.get(h):void 0),I=Xe(E=>E.hasHydrated),M=Xe(E=>E.ensureDirectory),T=Xe(E=>E.createTab),O=Xe(E=>E.setActiveTab),P=Xe(E=>E.closeTab),B=Xe(E=>E.setTabSessionId),z=Xe(E=>E.setTabLifecycle),U=Xe(E=>E.setConnecting),ne=Xe(E=>E.appendToBuffer),se=Xe(E=>E.replaceBuffer),K=Xe(E=>E.setTabPreviewUrl),G=di(E=>E.addDraft),R=ue(E=>E.openContextPreview),A=i.useMemo(()=>f?f.activeTabId??f.tabs[0]?.id??null:null,[f,v]),V=i.useMemo(()=>{if(f)return A?f.tabs.find(E=>E.id===A)??f.tabs[0]:f.tabs[0]},[f,A]),le=i.useMemo(()=>(f?.tabs??[]).map(E=>({icon:(()=>{const X=E.iconKey?Ai[E.iconKey]??"terminal":"terminal";return t.jsx(k,{name:X,className:"h-4 w-4"})})(),id:E.id,label:E.label,title:E.label,closeLabel:"Close tab"})),[f?.tabs]),$=V?.terminalSessionId??null,ke=V?.lifecycle??"idle",Ie=Xe(E=>h&&A?E.getBuffer(h,A).chunks:Sn.chunks),_e=V?.isConnecting??!1,Ge=V?.previewUrl??null,[Fe,ve]=i.useState(null),[Pe,me]=i.useState(!1),[He,we]=i.useState(!1),[xe,Ce]=i.useState(null),[Qe,Be]=i.useState(!1),W=i.useRef(null),H=i.useRef(null),ie=i.useRef(A),pe=i.useRef($),Se=i.useRef(h),Y=i.useRef(null),be=i.useRef(null),de=i.useRef(new Set),Ve=i.useRef(""),at=i.useRef(new Set),ze=i.useRef(0),je=i.useCallback(()=>{Ve.current="",at.current.clear(),ze.current+=1},[]),Ae=i.useCallback(()=>{x||typeof document<"u"&&!document.hasFocus()||Y.current?.focus()},[x]),ot=i.useCallback(()=>{x||Y.current?.focus()},[x]),pt=ue(E=>E.activeMainTab)==="terminal",ge=e??pt,[Ye,Tt]=i.useState(ge);i.useEffect(()=>{ge&&Tt(!0)},[ge]),i.useEffect(()=>{pe.current=$},[$]),i.useEffect(()=>{!$||!s.updateAppearance||s.updateAppearance($,o.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,$]),i.useEffect(()=>{ie.current=A,je()},[A,je]),i.useEffect(()=>{Se.current=h},[h]),i.useEffect(()=>{!j&&xe!==null&&Ce(null)},[j,xe,Ce]),i.useEffect(()=>{!$&&xe!==null&&Ce(null)},[$,xe,Ce]);const S=i.useCallback(()=>{W.current?.(),W.current=null,H.current=null,we(!1)},[]);i.useEffect(()=>()=>{S(),pe.current=null},[S]);const Z=i.useCallback((E,X,ce)=>{if(!ce)return;const $e=`${Ve.current}${ce}`.replace(/\r\n|\r/g,`
|
|
41
|
-
`),he=$e.split(`
|
|
42
|
-
`),Te=$e.endsWith(`
|
|
43
|
-
`)?he.join(`
|
|
44
|
-
`):he.slice(0,-1).join(`
|
|
45
|
-
`);if(Ve.current=$e.endsWith(`
|
|
46
|
-
`)?"":(he[he.length-1]??"").slice(-1024),!Te)return;const lt=Am(Te);if(!lt||at.current.has(lt))return;const vt=ze.current;at.current.add(lt),Rm(lt).then($t=>{if(at.current.delete(lt),!$t||ze.current!==vt)return;const Ft=Xe.getState().getDirectoryState(E)?.tabs.find(Ht=>Ht.id===X);!Ft||Ft.previewUrlLocked||Ft.previewUrl===lt||K(E,X,lt,{locked:!1,autoOpened:!1})})},[K]),ae=i.useCallback((E,X,ce)=>{if(H.current===ce)return;S(),H.current=ce;const $e=s.connect(ce,{onEvent:he=>{if(H.current===ce)switch(he.type){case"snapshot":{U(E,X,!1),ve(null),me(!1),we(!1),Ae(),se(E,X,he.data??"",he.sequence??0),Z(E,X,he.data??""),he.status==="exited"&&z(E,X,"exited");break}case"reconnecting":{ve(null),me(!1),we(!0);break}case"data":{he.data&&(ne(E,X,he.data,he.sequence,he.replayData),Z(E,X,he.data));break}case"exit":{const Te=typeof he.exitCode=="number"?he.exitCode:null,lt=typeof he.signal=="number"?he.signal:null,$t=!!Xe.getState().getDirectoryState(E)?.tabs.find(Ft=>Ft.id===X)?.label?.startsWith("Action:");ne(E,X,`\\r\\n[Process exited${Te!==null?` with code ${Te}`:""}${lt!==null?` (signal ${lt})`:""}]\\r\\n`),z(E,X,"exited"),U(E,X,!1),ve($t?null:"Terminal session ended"),me(!1),we(!1),S();break}}},onError:(he,Te)=>{if(H.current===ce){if(!Te){ve(null),me(!1);return}if(we(!1),he.code==="SESSION_NOT_FOUND"&&!Xe.getState().getDirectoryState(E)?.tabs.find(vt=>vt.id===X)?.label?.startsWith("Action:")){ve(null),me(!1),U(E,X,!1),B(E,X,null),z(E,X,"idle"),S();return}ve(`Connection failed: ${he.message}`),me(!0),U(E,X,!1),z(E,X,"exited"),B(E,X,null),S()}}});W.current=()=>{$e.close(),H.current=null}},[ne,se,S,Ae,Z,U,z,B,s]);i.useEffect(()=>{let E=!1;if(!I||!Ye)return;if(!h){ve(b?"No working directory available for terminal.":"Select a session to open the terminal."),S();return}return(async()=>{const ce=h;if(!Se.current||Se.current!==ce)return;if(!Xe.getState().getDirectoryState(ce)){M(ce);return}const he=Xe.getState().getDirectoryState(ce);if(!he||he.tabs.length===0)return;const Te=he.activeTabId??he.tabs[0]?.id??null;if(!Te)return;const lt=he.tabs.find(mt=>mt.id===Te)??he.tabs[0],vt=lt?.terminalSessionId??null,$t=lt?.lifecycle??"idle",Ft=!!lt?.label?.startsWith("Action:"),Ht=Xe.getState().getBuffer(ce,Te),zt=Ht.byteLength>0||Ht.chunks.length>0;if(!vt){if($t==="exited"){U(ce,Te,!1);return}if(Ft&&zt){U(ce,Te,!1);return}const mt=`${ce}\0${Te}`;if(de.current.has(mt))return;const Lt=be.current??ei;de.current.add(mt),ve(null),me(!1),we(!1),U(ce,Te,!0);try{const L=await s.createSession({cwd:ce,sessionId:Te,cols:Lt.cols,rows:Lt.rows,shell:c,loginShell:d,...o.current}),q=!E&&Se.current===ce&&ie.current===Te;if(!Xe.getState().getDirectoryState(ce)?.tabs.find(re=>re.id===Te)){try{await s.close(L.sessionId)}catch{}return}if(B(ce,Te,L.sessionId),!q)return;const te=be.current;te&&(te.cols!==Lt.cols||te.rows!==Lt.rows)&&s.resize({sessionId:L.sessionId,...te}).catch(()=>{});return}catch(L){const q=Xe.getState().getDirectoryState(ce)?.tabs.find(ee=>ee.id===Te);if(!q||q.terminalSessionId||(U(ce,Te,!1),Se.current!==ce||ie.current!==Te))return;ve(L instanceof Error?L.message:"Failed to start terminal session"),me(!0),we(!1);return}finally{de.current.delete(mt)}}!vt||E||(pe.current=vt,ae(ce,Te,vt))})(),()=>{E=!0,pe.current=null,S()}},[b,h,$,ke,A,Ye,v,I,M,U,z,B,ae,S,s,d,c]),i.useEffect(()=>{if(!ge||x)return;if(typeof window>"u"){Ae();return}const E=window.requestAnimationFrame(()=>{Ae()});return()=>{window.cancelAnimationFrame(E)}},[A,Ae,ge,x]);const ye=i.useCallback(async()=>{if(!h||Qe)return;const E=Xe.getState().getDirectoryState(h),X=A??E?.activeTabId??E?.tabs[0]?.id??null;if(!X)return;const ce=E?.tabs.find($e=>$e.id===X)?.terminalSessionId??null;if(!(!ce||!s.restartSession)){Be(!0),ve(null),me(!1),we(!1),S(),je();try{const $e=be.current??ei,he=await s.restartSession(ce,{cwd:h,shell:c,loginShell:d,...$e,...o.current});if(Xe.getState().getDirectoryState(h)?.tabs.find(lt=>lt.id===X)?.terminalSessionId!==ce||(B(h,X,he.sessionId),z(h,X,"running"),Se.current!==h||ie.current!==X))return;pe.current=he.sessionId,ae(h,X,he.sessionId)}catch($e){if(Xe.getState().getDirectoryState(h)?.tabs.find(Te=>Te.id===X)?.terminalSessionId!==ce||Se.current!==h||ie.current!==X)return;ve($e instanceof Error?$e.message:"Failed to restart terminal"),me(!1),we(!1),pe.current=ce,ae(h,X,ce)}finally{Be(!1)}}},[A,S,h,v,Qe,je,z,B,ae,s,d,c]),Re=i.useCallback(async()=>{await ye()},[ye]),Ke=i.useCallback(()=>{if(!h)return;const E=T(h);O(h,E),ve(null),me(!1),we(!1),S()},[T,S,h,O]),nt=i.useCallback(()=>{const E=Y.current?.getSelection(),X=C??(N?.open?"draft":null);!E||!X||!V||!h||G({directory:h,sessionKey:X},{source:"terminal",fileLabel:V.label,startLine:E.startLine,endLine:E.endLine,code:E.text,language:V.terminalSessionId??V.id,text:""})},[V,G,C,h,N?.open]),ct=i.useCallback(E=>{h&&(O(h,E),ve(null),me(!1),we(!1),S())},[S,h,O]),Gt=i.useCallback(E=>{if(!h)return;E===A&&S(),ve(null),me(!1),we(!1);const X=Xe.getState().getDirectoryState(h)?.tabs.find(ce=>ce.id===E)?.terminalSessionId;(async()=>{X&&await s.close(X),P(h,E)})().catch(ce=>ve(ce instanceof Error?ce.message:"Terminal session ended"))},[A,P,S,h,s]),it=i.useCallback(E=>{if(!E||He)return;let X=E,ce=!1;xe&&E.length>0&&(X=Om(E,xe),ce=!0);const $e=pe.current;$e&&(s.sendInput($e,X).catch(he=>{He||ve(he instanceof Error?he.message:"Failed to send input")}),ce&&(Ce(null),ot()))},[xe,ot,He,Ce,s]),gt=i.useCallback((E,X)=>{const ce=be.current;if((!ce||ce.cols!==E||ce.rows!==X)&&(be.current={cols:E,rows:X}),!ge)return;const $e=pe.current;$e&&s.resize({sessionId:$e,cols:E,rows:X}).catch(()=>{})},[ge,s]),yt=i.useCallback(E=>{Ce(X=>X===E?null:E),ot()},[ot,Ce]),Je=i.useCallback(E=>{const X=Lm(E,xe);X&&(it(X),Ce(null),ot())},[xe,ot,it,Ce]),Bt=i.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),_t=i.useCallback(E=>{if(E.repeat)return;const X=E.key;if(!X||X==="Control"||X==="Meta"||X==="Alt"||X==="Shift")return;const ce=X.length===1?X.toLowerCase():X;if(ce in Bt){E.preventDefault(),E.stopPropagation(),Je(Bt[ce]);return}if(xe!=="ctrl")return;const $e=E.code??"",he=X.length===1&&/[a-zA-Z]/.test(X)?X.toUpperCase():$e.startsWith("Key")&&$e.length===4?$e.slice(3).toUpperCase():null;if(he&&he.length===1&&he>="A"&&he<="Z"){const Te=Ji(he);if(!Te)return;E.preventDefault(),E.stopPropagation(),it(Te),Ce(null),ot()}},[xe,ot,Je,it,Bt,Ce]);i.useEffect(()=>{if(!(!j||!xe||!$))return window.addEventListener("keydown",_t),()=>window.removeEventListener("keydown",_t)},[xe,_t,j,$]);const Et=i.useMemo(()=>{const E=Ks[Un].stack;if(typeof window>"u")return(Ks[a]??Ks[Un]).stack;const ce=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ce&&ce.trim().length>0?ce.trim():(Ks[a]??Ks[Un]).stack??E},[a]),xt=i.useMemo(()=>dm(r),[r]),Mt=`${h??"no-dir"}::${A??"no-tab"}`;if(i.useEffect(()=>{if(!ge||x)return;const E=Y.current;if(!E)return;const X=()=>{E.fit()};if(typeof window<"u"){const ce=window.requestAnimationFrame(()=>{X(),Ae()}),$e=[220,400].map(he=>window.setTimeout(X,he));return()=>{window.cancelAnimationFrame(ce),$e.forEach(he=>window.clearTimeout(he))}}X()},[Ae,ge,x,Mt,$]),i.useEffect(()=>{if(!ge||!x)return;let E=null;const X=()=>{E!==null&&window.cancelAnimationFrame(E),E=window.requestAnimationFrame(()=>{E=null,Y.current?.fit()})};return window.addEventListener("oc:keyboard-settled",X),()=>{window.removeEventListener("oc:keyboard-settled",X),E!==null&&window.cancelAnimationFrame(E)}},[ge,Mt,x]),!b)return t.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(!h)return t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{children:"No working directory available for this session."}),t.jsx("button",{onClick:ye,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const D=!$||_e||Qe||He,fe=Ye,Ne=w?"lg":"xs",Le=w?"w-10 p-0":"w-9 p-0",We=E=>{w&&E.preventDefault()},kt=t.jsxs(t.Fragment,{children:[t.jsx(Ee,{type:"button",size:Ne,variant:"outline",onPointerDown:We,onClick:()=>Je("esc"),disabled:D,children:"Esc"}),t.jsxs(Ee,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Je("tab"),disabled:D,children:[t.jsx(k,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"chip","aria-pressed":xe==="ctrl",className:w?"px-3":"px-2",onPointerDown:We,onClick:()=>yt("ctrl"),disabled:D,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"chip","aria-pressed":xe==="alt",className:w?"px-3":"px-2",onPointerDown:We,onClick:()=>yt("alt"),disabled:D,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Je("arrow-up"),disabled:D,children:[t.jsx(k,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Je("arrow-left"),disabled:D,children:[t.jsx(k,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Je("arrow-down"),disabled:D,children:[t.jsx(k,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Je("arrow-right"),disabled:D,children:[t.jsx(k,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Ee,{type:"button",size:Ne,variant:"outline",className:Le,onPointerDown:We,onClick:()=>Je("enter"),disabled:D,children:[t.jsx(k,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:F("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",w?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[f?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:F("min-w-0 flex-1",w?"h-8":"h-7"),children:t.jsx(Cm,{items:le,activeId:A,onSelect:ct,onClose:Gt,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Ee,{type:"button",size:"xs",variant:"ghost",className:F("shrink-0",w?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ke,title:"New tab",children:t.jsx(k,{name:"add",className:`${w?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Ee,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ye()},disabled:Qe,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(k,{name:"restart",className:"h-4 w-4"})}),t.jsx(Ee,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:nt,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(k,{name:"attachment-2",className:"h-4 w-4"})}),Ge?t.jsxs(Ee,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{h&&R(h,Ge)},title:"Open preview pane",children:[t.jsx(k,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!w&&j&&v&&f?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:kt}):null,!w&&j&&!f?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:kt}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:xt.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:fe?t.jsx(Yi,{ref:E=>{Y.current=E},sessionKey:Mt,chunks:Ie,onInput:it,onResize:gt,theme:xt,fontFamily:Et,fontSize:l,enableTouchScroll:x,autoFocus:ge,isVisible:ge},Mt):null}),!He&&Fe&&t.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[t.jsx("span",{children:Fe}),Pe&&w&&t.jsx(Ee,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Re,disabled:Qe,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),w&&j?t.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",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:kt})}):null]})};export{cp as $,yp as A,iu as B,pp as C,Jm as D,Nr as E,kp as F,rp as G,ou as H,Ir as I,op as J,Tu as K,au as L,Ys as M,eu as N,Ti as O,Dp as P,Js as Q,Xd as R,Ip as S,Pp as T,Zd as U,Es as V,su as W,ep as X,dp as Y,tu as Z,nu as _,Gu as a,hp as a0,fp as a1,lu as a2,ms as a3,lp as a4,up as a5,mp as a6,Xm as a7,tp as a8,sp as a9,np as aa,Cu as ab,ip as ac,Ou as ad,Bu as ae,ru as af,Zm as ag,Cp as ah,vp as ai,Xe as b,Np as c,jp as d,Sp as e,wp as f,jo as g,fu as h,Ai as i,mh as j,yh as k,ph as l,Eu as m,hu as n,Mu as o,Au as p,Co as q,xp as r,gh as s,gp as t,yn as u,Ru as v,Cm as w,Fu as x,bp as y,ap as z};
|