@pi-chamber/web 0.5.2 → 0.7.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/dist/assets/{CommitSection-BMoPmxW5.js → CommitSection-BL61C8nr.js} +1 -1
- package/dist/assets/{DiagramEditor-DmDE7OFs.js → DiagramEditor-CH_gE8Ho.js} +1 -1
- package/dist/assets/{DiagramView-DQqjMY2l.js → DiagramView-D5PsfvzH.js} +1 -1
- package/dist/assets/{DiffView-CA4gogOk.js → DiffView-CP49mbz0.js} +1 -1
- package/dist/assets/{FilesView-B6u279g1.js → FilesView-DQ0jIXPf.js} +1 -1
- package/dist/assets/{GitView-BZVWI9Uo.js → GitView-BvIVUn8p.js} +3 -3
- package/dist/assets/{JsonTreeView-Lcl4hDE0.js → JsonTreeView-4xkZ1oUB.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Uz4H4e3u.js → MarkdownRendererImpl-BYiITelR.js} +1 -1
- package/dist/assets/PatchDiff-cYVpwvLs.js +1 -0
- package/dist/assets/{PierreDiffViewer-CODKwHC9.js → PierreDiffViewer-CxTRnaw4.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-Cp2Zm5gn.js → SessionSwitcherContent-C_kE1AkY.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-BdQTFOMs.js → SessionSwitcherDropdown-CCXNg-hd.js} +2 -2
- package/dist/assets/{SessionUnreadDot-CyaUql-t.js → SessionUnreadDot-DcLebnEm.js} +1 -1
- package/dist/assets/{SettingsView-BtYR1m1l.js → SettingsView-CfpCOseW.js} +3 -3
- package/dist/assets/{SettingsWindow-BWemjgov.js → SettingsWindow-BCfEIGLV.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BmSMXqFj.js → ToolOutputDialog-CG3Djpaw.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-qaLAaq5N.js → ToolPartDiffPreview-Bno_Kf_v.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-B-r2zJ_k.js → VirtualizedFileDiff-CtTCV9aT.js} +3 -3
- package/dist/assets/{WindowsWindowControls-NzKm1MYj.js → WindowsWindowControls-C1cyCACC.js} +107 -107
- package/dist/assets/{collapsible-IV1T6v7c.js → collapsible-Y0lXAGWU.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DOtVuPAu.js → computeVirtualFileMetrics-Ygq8IDgM.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-CR2p7-61.js → contextFileOpenGuard-CdZD2lzt.js} +1 -1
- package/dist/assets/index-CiQblNLS.js +8 -0
- package/dist/assets/{index-Z6Hwnczz.js → index-Cl-EsRzi.js} +1 -1
- package/dist/assets/{isDiffPlainText-DKfgU8d8.js → isDiffPlainText-BOtu3iWK.js} +1 -1
- package/dist/assets/{isFilePlainText-2ndX4gYw.js → isFilePlainText-DZkgwQ85.js} +1 -1
- package/dist/assets/{main-CsU2nR8Q.js → main-BlGDTFM8.js} +9 -9
- package/dist/assets/{main-BfG1ShoJ.js → main-hi9Mn-Bi.js} +2 -2
- package/dist/assets/{markdownCore-BaZ2plrB.js → markdownCore-BnziCWjq.js} +2 -2
- package/dist/assets/{miniChat-BpFgzk2I.js → miniChat-jlNYy4Yo.js} +2 -2
- package/dist/assets/{mobile-Dh_Vvtjt.js → mobile-B2J6RZei.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-DNmqLSsJ.js → renderElectronMiniChatApp-D2j7dJjx.js} +2 -2
- package/dist/assets/{renderMobileApp-BZbx_IU1.js → renderMobileApp-DRMRL_Rc.js} +4 -4
- package/dist/assets/{runtimeSurface-D3p7a-uO.js → runtimeSurface-DRCRpZ4U.js} +1 -1
- package/dist/assets/{useInlineCommentController-TZXHonVr.js → useInlineCommentController-BafZc9gs.js} +2 -2
- package/dist/assets/usePanelSlide-C4DKnekW.js +56 -0
- package/dist/assets/{usePushVisibilityBeacon-9FqcXiL9.js → usePushVisibilityBeacon-C6yhoKax.js} +2 -2
- package/dist/assets/{useSwitcherItems-DZW2vj37.js → useSwitcherItems-D4fvD6XH.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-DXJ_-7WI.js → vendor-codemirror-language-data-DOlAvLSI.js} +2 -2
- package/dist/assets/{web-components-RWdkgqgC.js → web-components-CDndDwR4.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +2 -2
- package/dist/mobile.html +2 -2
- package/package.json +1 -1
- package/server/lib/inherited-env.js +1 -1
- package/server/lib/pi/routes.js +9 -1
- package/server/lib/pi/routes.test.js +24 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -4
- package/server/lib/pi/session-daemon/session-daemon.js +42 -22
- package/server/lib/pi/session-daemon/session-daemon.test.js +116 -8
- package/server/lib/pi/session-daemon/session-jsonl.js +27 -7
- package/server/lib/pi/session-daemon/session-jsonl.test.js +31 -0
- package/dist/assets/PatchDiff-DpAN_LfK.js +0 -1
- package/dist/assets/index--5Zr-fSk.js +0 -8
- package/dist/assets/usePanelSlide-SCy9Q8Wl.js +0 -56
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Z6Hwnczz.js","assets/WindowsWindowControls-NzKm1MYj.js","assets/index--5Zr-fSk.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index--zDkVFU6.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.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-D3p7a-uO.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-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.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-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-DXJ_-7WI.js","assets/vendor-codemirror-lang-python-_2bIYTiJ.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-RrgJ8H_6.js","assets/vendor-class-variance-authority-5VPnzWs2.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-CW8w438f.js","assets/computeVirtualFileMetrics-DOtVuPAu.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-2ndX4gYw.js","assets/isDiffPlainText-DKfgU8d8.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","assets/SessionSwitcherDropdown-BdQTFOMs.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as Ds}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as qe,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{a_ as Us,a$ as jc,ai as Cc,o as Xi,D as cs,n as ds,q as ms,I as N,ar as As,b0 as zo,B as Qe,ap as fn,T as rt,l as ot,m as it,b1 as Zi,b2 as kc,b3 as Nc,b4 as Ac,b5 as Ic,g as _e,b6 as Dc,b7 as $o,b8 as Pc,b9 as Ec,ba as Uo,bb as Tc,bc as Rc,bd as Mc,be as Fc,bf as Ir,bg as Oc,t as le,am as Qt,an as Jt,ao as Xt,R as Ws,bh as Lc,bi as Bc,bj as _c,bk as zc,bl as Go,W as Ot,bm as $c,bn as Uc,bo as Gc,bp as Kc,bq as Hc,br as Wc,bs as Dr,bt as ea,bu as ta,bv as Yc,bw as Vc,bx as qc,by as Qc,bz as Jc,bA as Xc,aO as Pr,r as Ps,aQ as Ts,aT as Zc,aU as ed,aV as td,aW as sd,aX as ar,aY as Xs,bB as Ko,as as St,b as zt,aJ as Fs,bC as sa,p as Ss,s as Os,v as Ls,bD as nd,a2 as Zs,bE as lr,bF as Ho,bG as Wo,bH as rn,av as rd,aK as na,aA as Yo,ay as od,ax as id,aN as ra,f as eo,bI as ad,e as to,w as Qn,C as oa,bJ as ld,bK as Kt,aF as ia,c as Er,bL as cd,bM as dd,bN as aa,bO as Jn,bP as Vo,aP as la,bQ as ca,bR as da,z as ud,bS as so,bT as fd,bU as hd,h as ua,j as pd,bV as md,bW as gd,i as xd,bX as Tr,bY as fa,bZ as bd,b_ as yd,d as vd,b$ as wd,a as Sd,aq as jd,aS as Cd,c0 as ha,c1 as kd,c2 as Nd,aR as Ad,c3 as Id,c4 as Dd,a8 as Pd,c5 as qo,c6 as Ed,aG as Td,c7 as Rd,c8 as Md,c9 as Cn,ca as Qo,cb as Fd,cc as Jo,cd as Xo,ce as Od,aE as pa,U as Ld,x as Bd,cf as ma,u as _d,cg as zd,ch as $d,at as Ys,k as Ud,ci as Gd,cj as ga,ck as Kd,cl as Hd,cm as Wd,cn as Yd,co as Vd,cp as xa,cq as qd,cr as Qd}from"./WindowsWindowControls-NzKm1MYj.js";import{V as Zo,W as Jd,X as ei,Y as Xd,i as Zd,Z as eu,P as tu,r as es,_ as hn,b as su,m as B,O as ws,u as ue,$ as nu,a0 as fs,a1 as no,t as ro,n as Rs,a2 as Ze,a3 as Ms,a4 as oo,a5 as io,a6 as ru,a7 as ou,F as iu,a8 as au,a9 as lu,aa as cu,ab as du,ac as as,ad as ti,ae as Rr,a as Xn,af as uu,ag as fu,Q as ao,R as on,ah as hu,ai as pu,aj as ba,A as mu,N as ya,G as an,ak as Mr,e as Fr,d as kn,al as gu,am as xu,an as en,ao as cr,ap as va,E as bu,q as yu,aq as Or,ar as Is,as as si,at as Lr,au as wa,av as Br,aw as vu,ax as wu,ay as Su,x as ju,az as Cu,aA as ku,aB as ni}from"./index--5Zr-fSk.js";import{d as Nu,g as Sa,r as Au,e as ja,h as On,i as Ca,b as ln,c as cn,s as Iu,j as Du,k as Pu,l as ri,m as Zn,a as Eu,S as Tu,f as Ru,t as Mu,n as Fu}from"./SessionUnreadDot-CyaUql-t.js";import{C as ka,a as Na,M as _r,b as zr,c as $r,d as Aa,S as Ia,D as Ou,e as Lu,f as Bu,g as _u,h as zu,i as $u,j as Uu,k as Gu,l as Ku}from"./vendor-base-ui-DL8r2fgQ.js";import{c as gs,d as Da,p as lo,u as Ur,a as Hu}from"./vendor-zustand-CnsBKjP5.js";import{u as Wu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as er,d as pn,P as co,D as tr,e as sr,f as Pa,b as Yu,a as Vu,T as qu,M as Qu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as uo,v as Ea,u as fo,a as Ju,h as Xu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as ho}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as Zu}from"./permissionStore-BRcQ9Jgt.js";const ef="chat";function Ta(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Us.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Us.SETTINGS,n),s}return e.tab!==ef&&s.set(Us.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Us.FILE,e.diffFile),s}function tf(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,i=e.toString();return i?`${r}?${i}`:r}function sf(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Ta(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has(Us.SESSION)&&s.set(Us.SESSION,i);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 Gr(e,s={}){if(!(typeof window>"u")&&!(!s.force&&sf(e)))try{const n=Ta(e),r=tf(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const nf=["typescript","javascript","tsx","jsx","json","markdown"],Ra={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let oi=null;const Ma=()=>(oi??=Promise.all([Ds(()=>import("./index-Z6Hwnczz.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])),Ds(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ds(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,11,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})),oi),mn={},ii=new Set,Kr=new Set;let Ln={light:"pierre-light",dark:"pierre-dark"};const rf=()=>{for(const e of Kr)e()},Fa=(e,s)=>{s.setRenderOptions({theme:Ln,lineDiffType:Ra[e].lineDiffType})},Hr=e=>{typeof window>"u"||ii.has(e)||(ii.add(e),Ma().then(s=>{if(mn[e])return;const n=Ra[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:nf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),mn[e]=r,Fa(e,r),rf()}))},of=e=>(Kr.add(e),()=>Kr.delete(e)),af=e=>{if(!(Ln.light===e.light&&Ln.dark===e.dark)){Ln=e;for(const s of Object.keys(mn)){const n=mn[s];n&&Fa(s,n)}}},nx=({children:e})=>{const s=jc(),n=Zo(!1),r=Zo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return qe.useEffect(()=>{let d=!1;return Ma().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),af({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),qe.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Hr("unified"),Hr("split")};if(typeof window.requestIdleCallback=="function"){const p=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(p)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},rx=(e="unified")=>{const s=qe.useSyncExternalStore(of,()=>mn[e],()=>{});return qe.useEffect(()=>{Hr(e)},[e]),s};function lf(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=Cc();return e}catch{return"unknown"}}function cf(){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 df(){const e=su();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 uf(e){const s=new URLSearchParams;return s.set("deviceClass",lf()),s.set("arch",cf()),s.set("platform",df()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",hn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function dr(e,s){try{const n=uf(e);s&&n.set("currentVersion",s);const r=await es(`/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 i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function ff(){return Zd()?"mobile":eu()?"desktop":tu()?"web":null}const ai={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Bn=gs()((e,s)=>({...ai,checkForUpdates:async()=>{const n=ff();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.5.2",[l,c]=await Promise.allSettled([ei(),dr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await dr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await dr("mobile","0.5.2"),i=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:i}),i}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 i=await ei();if(!i?.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,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await Xd(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(i){e({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Jd())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ai)}})),li="https://github.com/RyderAsKing/PiChamber/releases";function hf(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 pf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function ci(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function mf(e,s){const n=e.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function gf(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((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const di=2e3,xf=600*1e3;async function bf(){try{const e=await es("/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 yf(){try{return(await es("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function vf(e,s=Math.ceil(xf/di),n=di){for(let r=0;r<s;r++){try{const i=await es("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await yf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Oa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[p,m]=qe.useState(!1),[x,h]=qe.useState("idle"),[f,g]=qe.useState(null),S=n?.version?n.releaseUrl||`${li}/tag/v${n.version}`:li,k=n?.downloadUrl||S,O=a?.total?Math.round(a.downloaded/a.total*100):0,j=u==="web",v=u==="mobile",y=n?.updateCommand||"pichamber update";qe.useEffect(()=>{e||(h("idle"),g(null))},[e]);const L=async()=>{(await fn(y)).ok&&(m(!0),setTimeout(()=>m(!1),2e3))},A=qe.useCallback(async W=>{await Xi(W)},[]),C=qe.useCallback(async()=>{h("updating"),g(null);const W=await bf();if(!W.success){h("error"),g(W.error||"Update failed");return}W.autoRestart&&(h("restarting"),await new Promise(Z=>setTimeout(Z,2e3))),h("reconnecting"),await vf(n?.currentVersion)?window.location.reload():(h("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),I=qe.useCallback(()=>{A(k)},[A,k]),P=x!=="idle"&&x!=="error",D=qe.useMemo(()=>{if(!n?.body)return null;const W=n.body.trim();if(!W)return null;const ee=gf(W);return ee.length===0?{kind:"raw",title:"What's new",content:ci(W)}:{kind:"sections",title:"What's new",sections:[...ee].sort((ie,z)=>mf(ie.version,z.version)).map(ie=>({version:ie.version,dateLabel:hf(ie.date),content:ci(pf(ie.raw)||W)}))}},[n?.body]);return t.jsx(cs,{open:e,onOpenChange:P?void 0:s,children:t.jsxs(ds,{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(ms,{className:"flex items-center gap-2.5",children:[t.jsx(N,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="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:[j&&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(N,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="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."})]}),D&&!P&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(As,{className:"max-h-[400px] p-0",fillContainer:!1,children:D.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:W=>{const Z=W.target.closest("a");Z&&Z.href&&(W.preventDefault(),W.stopPropagation(),A(Z.href))},children:t.jsx(zo,{content:D.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:D.sections.map(W=>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",W.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:W.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:ee=>{const ie=ee.target.closest("a");ie&&ie.href&&(ee.preventDefault(),ee.stopPropagation(),A(ie.href))},children:t.jsx(zo,{content:W.content,disableLinkSafety:!0,enableFileReferences:!1})})]},W.version))})})}),j&&x==="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(N,{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:y}),t.jsx("button",{onClick:L,className:B("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",p&&"text-[var(--status-success)]"),title:p?"Copied!":"Copy command",children:p?t.jsx(N,{name:"check",className:"h-4 w-4"}):t.jsx(N,{name:"clipboard",className:"h-4 w-4"})})]})]}),!j&&!v&&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:[O,"%"]})]}),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:`${O}%`}})})]}),(l||f)&&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||f})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:S,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(N,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!v&&!i&&!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(N,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!j&&!v&&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(N,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!v&&i&&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(N,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),v&&t.jsxs(Qe,{onClick:I,size:"default",children:[t.jsx(N,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!P&&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(N,{name:"download",className:"h-4 w-4"}),"Update Now"]}),j&&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(N,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},wf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.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":i,className:B("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:B("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),gn=({children:e,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(rt,{open:r,onOpenChange:i,children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:B("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(N,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(it,{sideOffset:8,className:B("max-w-sm",n),children:e})]})},ox="w-full min-w-40 max-w-48",Sf="settings",jf="w-full min-w-40 max-w-48",ix="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Cf="w-full max-w-[24rem]",ax="min-w-0 flex-1",lx="flex w-full min-w-0 items-center gap-2",cx="typography-meta shrink-0 text-muted-foreground tabular-nums",La="space-y-3.5",kf="space-y-1.5",dx="typography-settings-page-title text-muted-foreground",Nf="typography-settings-section-title text-foreground",ux="typography-settings-section-title text-foreground",Ba="typography-settings-group-title text-foreground",po="typography-settings-field-label text-foreground",Af="typography-settings-description text-muted-foreground",xn="typography-meta text-muted-foreground",fx="typography-meta font-medium text-foreground",hx="typography-settings-section-title text-foreground",If=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const p=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:B("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[p?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:Nf,children:e}):e,n,r!=null?t.jsx(gn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Af,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:B(d),children:a})]})},px=({children:e,className:s})=>t.jsx("div",{className:B("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Df=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:B(Ba,s),children:e}),mx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:B("space-y-2",i),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(Df,{children:e}),n!=null?t.jsx(gn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:xn,children:s}):null]}):null,t.jsx("div",{className:B(a),children:r})]}),Gs=({label:e,description:s,info:n,descriptionPlacement:r="before",children:i,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:xn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:B("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:po,children:e}),n!=null?t.jsx(gn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:B("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},gx=({label:e,description:s,info:n,children:r,settingsItem:i,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":i,className:B("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:po,children:e}),n!=null?t.jsx(gn,{children:n}):null]}),s!=null?t.jsx("p",{className:B(xn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:B("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),xx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:B("pt-4",s),children:e}),Pf=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const p=()=>{i||s(!e)},m=r!=null;return t.jsxs("div",{"data-settings-item":l,className:B("group flex cursor-pointer gap-2 py-0.5",m?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:p,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),p())},children:[t.jsx(Zi,{checked:e,onChange:s,disabled:i,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:po,children:n}),d,u!=null?t.jsx(gn,{children:u}):null]}),m?t.jsx("span",{className:xn,children:r}):null]})]})},bx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:B("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(wf,{checked:e,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:B("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:xn,children:r}):null]})]}),yx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:B(kf,n),children:s});function vx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:B("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Qe,{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 Ef extends o.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(kc,{className:"w-full max-w-md",children:[t.jsx(Nc,{className:"text-center",children:t.jsxs(Ac,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(N,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Ic,{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(Qe,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(N,{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 Tf(e){return t.jsx(Ef,{...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 wx=({active:e=!0})=>{const s=_e(n=>n.currentSessionId);return t.jsx(Tf,{sessionId:s||void 0,children:t.jsx(Dc,{active:e},s??"no-session")})};function Rf({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 mo=qe.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:p,endSlot:m,...x},h)=>{const f=qe.useRef(null),g=qe.useRef(null),[S,k]=qe.useState(null),O=c??S,j=qe.useCallback(y=>{const L=f.current;if(!L)return;g.current={startY:y.clientY,startHeight:L.getBoundingClientRect().height};const A=y.currentTarget;A.setPointerCapture(y.pointerId);const C=P=>{const D=g.current;if(!D)return;const W=D.startHeight+(P.clientY-D.startY),ee=Math.max(82,W);d?d(ee):k(ee)},I=()=>{g.current=null,A.removeEventListener("pointermove",C),A.removeEventListener("pointerup",I),A.removeEventListener("pointercancel",I)};A.addEventListener("pointermove",C),A.addEventListener("pointerup",I),A.addEventListener("pointercancel",I),y.preventDefault()},[d]),v=qe.useCallback(y=>{if(y.target.closest('textarea, button, [role="separator"]'))return;const A=f.current?.querySelector("textarea");A&&document.activeElement!==A&&(y.preventDefault(),A.focus())},[]);return p?t.jsx(As,{as:"textarea",ref:h,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:B("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:f,onPointerDown:v,style:O!==null?{height:`${O}px`}:void 0,className:B("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:h,className:B("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,t.jsx(Rf,{onResizeStart:j,ariaLabel:"Resize textarea"})]})]})})});mo.displayName="Textarea";const ui=(e,s)=>s.updatedAtMs-e.updatedAtMs,Kn=gs((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([Rc(),Uo()]),i={};for(const a of r.sort(ui))i[a.id]=a;s().listenerReady||await Mc(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:i,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 Tc();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Uo(),r={};for(const i of n.sort(ui))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Ec({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,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=Fc(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await $o(n).catch(()=>{});const r=s().instances.filter(i=>i.id!==n);await s().setInstances(r),e(i=>{const a={...i.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await Pc(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 $o(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})})),_a=[{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"}],dn=Object.fromEntries(_a.map(e=>[e.key,e.Icon])),Wr="pichamber:project-actions-updated",za=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},hs=(e,s)=>`${za(e)}::${s}`,Mf=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},fi=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Ff=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=fi(s.localPort),r=fi(s.remotePort);if(!n||!r)return null;const i=Mf(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} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},$a=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Ff(n,r);i&&s.push(i)}return s},Of=(e,s)=>{const n=(e||"").trim();return n&&$a(s).find(a=>a.id===n)?.url||null},Lf=Cf,Ua=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(If,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Yr=e=>e.name.trim().length>0&&e.command.trim().length>0,Bf=e=>e.name.trim().length===0&&e.command.trim().length===0,_f=e=>!Yr(e)&&!Bf(e),zf=(e,s)=>e.some(r=>s.has(r.id)&&!Yr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Yr)},$f=450,Uf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Gf=()=>({id:Uf(),name:"",command:"",icon:"play"}),Kf=({projectRef:e})=>{const s=o.useMemo(()=>ws(),[]),n=Kn(y=>y.instances),r=Kn(y=>y.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[p,m]=o.useState(new Set),x=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let y=!1;return c(!0),(async()=>{try{const L=await Ir(e);if(y)return;a(L.actions),u(JSON.stringify({actions:L.actions})),m(new Set(L.actions.map(A=>A.id)))}catch{if(y)return;a([]),u(JSON.stringify({actions:[]})),m(new Set)}finally{y||c(!1)}})(),()=>{y=!0}},[e]);const h=o.useMemo(()=>s?$a(n):[],[n,s]),f=o.useMemo(()=>zf(i,p),[i,p]),g=o.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),S=d!==null&&f.canPersist&&g!==d,k=o.useCallback(async y=>await Oc(e,{actions:y,primaryActionId:null})?(u(JSON.stringify({actions:y})),m(new Set(y.map(A=>A.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Wr,{detail:{projectId:e.id}})),!0):(le.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!S||l||x.current)return;const y=window.setTimeout(()=>{x.current||(x.current=!0,(async()=>{try{await k(f.actions)}finally{x.current=!1}})())},$f);return()=>{window.clearTimeout(y)}},[S,l,k,f.actions]);const O=o.useCallback(()=>{const y=Gf();a(L=>[...L,y])},[]),j=o.useCallback(y=>{a(L=>L.filter(A=>A.id!==y))},[]),v=o.useCallback((y,L)=>{a(A=>A.map(C=>C.id===y?L(C):C))},[]);return t.jsx(Ua,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Qe,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:O,children:[t.jsx(N,{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..."}):i.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:B("space-y-6",Lf),children:i.map((y,L)=>{const A=y.icon||"play",C=dn[A]||"play",I=y.name.trim()||`Action ${L+1}`,P=_f(y);return t.jsxs("div",{className:La,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Ba,children:I}),t.jsx(Qe,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>j(y.id),"aria-label":`Delete ${I}`,children:t.jsx(N,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Gs,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Qt,{children:[t.jsx(Jt,{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(N,{name:C,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:_a.map(D=>{const W=D.Icon,ee=(y.icon||"play")===D.key;return t.jsx("button",{type:"button",onClick:()=>v(y.id,Z=>({...Z,icon:D.key})),className:B("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",ee&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${D.label}`,children:t.jsx(N,{name:W,className:"h-4 w-4"})},D.key)})})})]}),t.jsx(Ws,{value:y.name,onChange:D=>v(y.id,W=>({...W,name:D.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Gs,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(mo,{value:y.command,onChange:D=>v(y.id,W=>({...W,command:D.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(Pf,{checked:y.autoOpenUrl===!0,onChange:D=>v(y.id,W=>({...W,...D?{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 ${I}`}),y.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Gs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Ws,{value:y.openUrl||"",onChange:D=>v(y.id,W=>({...W,openUrl:D.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Gs,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:h.length>0?t.jsxs(Lc,{value:y.desktopOpenSshForward&&h.some(D=>D.id===y.desktopOpenSshForward)?y.desktopOpenSshForward:"__none__",onValueChange:D=>{v(y.id,W=>({...W,...D==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:D}}))},children:[t.jsx(Bc,{size:Sf,className:"w-full",children:t.jsx(_c,{placeholder:"Use output/manual URL"})}),t.jsxs(zc,{children:[t.jsx(Go,{value:"__none__",children:"Use output/manual URL"}),h.map(D=>t.jsx(Go,{value:D.id,children:D.label},D.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},y.id)})})})},Hf={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)"},Wf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=Ot(P=>P.providers),d=Ot(P=>P.modelsMetadata),u=ue(P=>P.hiddenModels),p=ue(P=>P.providerOrder),m=ue(P=>P.setProviderOrder),x=ue(P=>P.isFavoriteModel),h=ue(P=>P.toggleFavoriteModel),f=ue(P=>P.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:S}=$c(),[k,O]=o.useState(!1),[j,v]=o.useState("");o.useEffect(()=>{k||v("")},[k]);const y=e?c.find(P=>P.id===e.providerId):void 0,L=e&&y?(Array.isArray(y.models)?y.models:[]).find(P=>P.id===e.modelId):void 0,A=e?Uc(L,e.modelId):s,C=o.useMemo(()=>e?u.filter(P=>!(P.providerID===e.providerId&&P.modelID===e.modelId)):u,[u,e]),I=o.useCallback(P=>{l({providerId:P.providerID,modelId:P.modelID}),O(!1)},[l]);return t.jsxs(Qt,{modal:!1,open:k,onOpenChange:P=>{r||O(P)},children:[t.jsx(Jt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:B(Kc({size:"default"}),jf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Gc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:B("truncate",e?"text-foreground":"text-muted-foreground"),children:A})]}),t.jsx(N,{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(Hc,{providers:c,favoriteModels:g,recentModels:S,modelsMetadata:d,searchQuery:j,onSearchQueryChange:v,onSelect:I,labels:{...Hf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),O(!1)},disabled:r,autoFocus:!0,onEscape:()=>O(!1),isFavorite:P=>x(P.providerID,P.modelID),onToggleFavorite:P=>h(P.providerID,P.modelID),onReorderFavorite:(P,D)=>f(P.providerID,P.modelID,D.providerID,D.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:p,onReorderProvider:m,reorderProviderTitle:"Drag to reorder provider"})})]})},ur="w-full max-w-none",Yf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=Ot(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(Ua,{title:"Project",divider:!1,children:t.jsxs("div",{className:La,children:[t.jsx(Gs,{label:"Name",settingsItem:"projects.name",controlClassName:ur,children:t.jsx(Ws,{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(Gs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ur,children:t.jsx(Wf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ur,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},Vf=e=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!e){n(""),i(void 0);return}n(e.label??""),i(e.defaultModel)},[e]);const a=o.useMemo(()=>Wc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,p)=>{i(u&&p?`${u}/${p}`:void 0)},[]),d=o.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}},qf=450,Qf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.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{le.error("Failed to save project settings")}}finally{l.current=!1}})())},qf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Jf=({project:e,onIdentitySave:s})=>{const n=Vf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Qf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Yf,{form:n}),t.jsx(Kf,{projectRef:r})]})};function Xf({...e}){return t.jsx(ka,{...e})}function Zf({...e}){return t.jsx(Na,{...e})}function eh({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(_r,{children:t.jsx(zr,{className:B("app-region-no-drag z-50",s),children:t.jsx($r,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:B(Dr,e),...i,children:n})})})}function hi({className:e,...s}){return t.jsx(Aa,{className:B(ea,e),...s})}function th({className:e,...s}){return t.jsx(Ia,{className:B(ta,e),...s})}const Ns=gs()(Da(lo((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 Xc();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 Jc();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 Qc();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 i=r.trim();return i.length>0?i:null};try{let r=null;if(r===null){const i=ro()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await es("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.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():"",i=r.length>0?r:"";return await no({defaultGitIdentityId:i}),e({defaultGitIdentityId:i.length>0?i: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 fs("saving"),await qc(r),fs("saved"),await s().loadProfiles(),!0}catch(r){return fs("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return fs("saving"),await Vc(n,a),fs("saved"),await s().loadProfiles(),!0}catch(i){return fs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return fs("saving"),await Yc(n),fs("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return fs("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:nu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Ns);const sh=[{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:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","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:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"PiChamber Utility Prompts",group:"agent",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request","utility"],isAvailable:()=>!1},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",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"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],nh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function rh(e){const s=e.trim().toLowerCase();return sh.find(n=>n.slug===s)??null}function oh(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=nh[s];if(n)return n;const r=rh(s);return r?r.slug:"home"}function Sx(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"dictation":return"mic";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 Nn=100;function jx(){const e=ue(C=>C.isArchivePageOpen),s=ue(C=>C.setArchivePageOpen),n=ue(C=>C.setActiveMainTab),r=_e(C=>C.setCurrentSession),i=_e(C=>C.unarchiveSession),a=Rs(C=>C.homeDirectory),l=Pr({archived:!0}),[c,d]=o.useState(""),[u,p]=o.useState(null),[m,x]=o.useState(Nn),h=c.trim().toLowerCase(),f=o.useMemo(()=>e?[...l].sort((C,I)=>(I.time?.archived??0)-(C.time?.archived??0)):[],[l,e]),g=o.useMemo(()=>{const C=new Map;for(const I of f){const P=Ze(Ps(I))??"",D=C.get(P);if(D){D.sessions.push(I);continue}C.set(P,{directory:P,label:P?Ms(P,a)||P:"other projects",sessions:[I]})}return[...C.values()].sort((I,P)=>P.sessions.length-I.sessions.length)},[a,f]),S=o.useMemo(()=>h?f.filter(C=>(C.title??"").toLowerCase().includes(h)):u===null?f:g.find(C=>C.directory===u)?.sessions??[],[g,h,u,f]),k=S.slice(0,m),O=S.length-k.length,j=l.length,v=o.useCallback(C=>{p(C),x(Nn)},[]),y=o.useCallback(C=>{const I=Ze(Ps(C));r(C.id,I??void 0),n("chat"),s(!1)},[n,r,s]),L=o.useCallback(C=>{i(C.id).then(I=>{I?le.success("Session restored"):le.error("Failed to restore session")})},[i]);if(!e)return null;const A=(C,I,P,D,W,ee,Z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:W,title:ee,className:B("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",Z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",D?"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:I}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:P})]}),Z?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Ts.requestDelete({sessions:Z,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 ${I}`,children:t.jsx(N,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},C);return t.jsx(Ou,{open:e,onOpenChange:s,children:t.jsxs(Lu,{children:[t.jsx(Bu,{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(_u,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(zu,{className:"sr-only",children:"Archived sessions"}),t.jsx($u,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Uu,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(N,{name:"close",className:"size-4"})}),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:[A("__all__","All directories",j,u===null,()=>v(null)),g.map(C=>A(C.directory||"__none__",C.label,C.sessions.length,u===C.directory,()=>v(C.directory),C.directory||void 0,C.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 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(N,{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:C=>{d(C.target.value),x(Nn)},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:S.length===1?`${S.length} archived session`:`${S.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:[k.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:h?"No matching archived sessions":"No archived sessions"})}):k.map(C=>{const I=Ze(Ps(C))??"",P=I?Ms(I,a)||I: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:()=>y(C),role:"button",tabIndex:0,onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),y(C))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:C.title||"Untitled Session"}),h&&P?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:I,children:P}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Nu(C.time?.archived??C.time?.updated??C.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:D=>{D.stopPropagation(),L(C)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${C.title||"Untitled Session"}`,children:t.jsx(N,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:D=>{D.stopPropagation(),Ts.requestDelete({sessions:[C],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${C.title||"Untitled Session"}`,children:t.jsx(N,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},C.id)}),O>0?t.jsx("button",{type:"button",onClick:()=>x(C=>C+Nn),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 ih=()=>{const[e,s]=qe.useState(!1),[n,r]=qe.useState(!1);qe.useEffect(()=>{s(ws()),r(oo())},[]);const i=qe.useCallback(async c=>e?await io(c):{success:!0,path:c},[e]),a=qe.useCallback(async c=>e?await ru():{success:!0},[e]),l=qe.useCallback(async c=>e?await ou():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},ah=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),lh=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[p,m]=o.useState(""),[x,h]=o.useState(!1),[f,g]=o.useState(!1),[S,k]=o.useState(""),[O,j]=o.useState(!1),v=o.useRef(null),y=o.useCallback(z=>{z.stopPropagation()},[]),L=l.length>1,A=o.useMemo(()=>ah(S),[S]),C=o.useMemo(()=>{const z=p.toLowerCase();return z?s.filter(U=>U.toLowerCase().includes(z)):s},[p,s]),I=o.useMemo(()=>{const z=p.toLowerCase();return z?n.filter(U=>U.toLowerCase().includes(z)):n},[p,n]),P=z=>{if(z===e){u(!1);return}i(z),u(!1),m("")},D=()=>{h(!0),setTimeout(()=>v.current?.focus(),50)},W=async()=>{if(!(!A||O)){if(L){g(!0);return}j(!0);try{await a(A,l[0]),k(""),h(!1),u(!1)}finally{j(!1)}}},ee=async z=>{if(!(!A||O)){j(!0);try{await a(A,z),k(""),h(!1),g(!1),u(!1)}finally{j(!1)}}},Z=()=>{g(!1)},ie=()=>{k(""),h(!1),g(!1)};return o.useEffect(()=>{d||(m(""),h(!1),g(!1),k(""))},[d]),t.jsxs(Qt,{open:d,onOpenChange:u,children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Qe,{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(N,{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(N,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(it,{sideOffset:8,children:"Current branch"})]}),t.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(Zc,{className:"h-full min-h-0",children:[t.jsx(ed,{placeholder:"Search branches...",value:p,onValueChange:m,onKeyDown:y}),t.jsxs(td,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(sd,{children:"No branches found."}),t.jsx(ar,{children:f?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:Z,disabled:O,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(N,{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:A})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(z=>t.jsxs("button",{type:"button",onClick:()=>ee(z),disabled:O,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:[O?t.jsx(N,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,z.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:z.pushUrl})]},z.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:v,placeholder:"New branch name",value:S,onChange:z=>k(z.target.value),onClick:z=>z.stopPropagation(),onKeyDown:z=>{y(z),z.key==="Enter"?(z.preventDefault(),W()):z.key==="Escape"&&(z.preventDefault(),ie())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:W,disabled:!A||O,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:O?t.jsx(N,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(N,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:ie,disabled:O,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(N,{name:"close",className:"size-4"})})]}):t.jsxs(Xs,{onSelect:D,children:[t.jsx(N,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ko,{}),t.jsxs(ar,{heading:"Local branches",children:[C.map(z=>t.jsxs(Xs,{onSelect:()=>P(z),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:z}),(r?.[z]?.ahead||r?.[z]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[z].ahead||0," ahead ·"," ",r[z].behind||0," behind"]})]}),e===z&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${z}`)),C.length===0&&t.jsx(Xs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ko,{}),t.jsxs(ar,{heading:"Remote branches",children:[I.map(z=>t.jsx(Xs,{onSelect:()=>P(z),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:z})},`remote-${z}`)),I.length===0&&t.jsx(Xs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},ch=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),dh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),p=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},m=async()=>{if(!e||!s||!a.trim())return;const f=ch(a);if(f===e){i(!1);return}d(!0);try{await s(e,f),i(!1),l("")}finally{d(!1)}},x=()=>{i(!1),l("")},h=f=>{f.key==="Enter"?(f.preventDefault(),m()):f.key==="Escape"&&(f.preventDefault(),x())};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:f=>{f.preventDefault(),m()},children:[t.jsx(N,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:f=>l(f.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:h,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(N,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(N,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,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(N,{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(N,{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(Qe,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:p,title:"Rename branch",children:t.jsx(N,{name:"edit",className:"size-4"})})]})]})},uh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:p=!1})=>{const m=o.useRef(!1),x=!!l,h=s.find(y=>y.name===u)??s[0],f=d>0&&p,g=a||e!==null||x||!h||f,S=a||e!==null||x||s.length===0,k=c>0||d>0,O=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),j=f?"Commit or stash your changes before syncing":h?k?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",v=()=>{h&&r(h)};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(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:f?0:void 0,children:t.jsxs("button",{type:"button",onClick:v,disabled:g,className:B("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(N,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(N,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:O})]})})}),t.jsx(it,{sideOffset:8,children:j})]}),t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("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:S,"aria-label":"More sync actions",children:t.jsx(N,{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(y=>t.jsx(St,{onSelect:L=>{if(m.current){L.preventDefault(),m.current=!1;return}n(y)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(N,{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 ${y.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:y.fetchUrl})]})}),i&&y.name!==u?t.jsx(Qe,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:L=>{m.current=!0,L.preventDefault(),L.stopPropagation()},onClick:L=>{m.current=!0,L.preventDefault(),L.stopPropagation(),i(y)},"aria-label":`Remove remote ${y.name}`,title:`Remove remote ${y.name}`,children:l===y.name?t.jsx(N,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(N,{name:"close",className:"size-3.5"})}):null]})},y.name))})]})]})},fh={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},hh={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 Ga(e){return e&&hh[e]||"var(--primary)"}const pi=({icon:e,className:s,colorToken:n})=>{const r=fh[e??"branch"]??"user-3";return t.jsx(N,{name:r,className:s,style:{color:Ga(n)}})},Ka=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Qt,{children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Qe,{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:Ga(e?.color)},disabled:a,children:[r?t.jsx(N,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(pi,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(N,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(it,{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(St,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(pi,{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(N,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},ph=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,i=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(rt,{delayDuration:n,children:[t.jsx(ot,{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(N,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?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(it,{sideOffset:8,children:a})]})},Cx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:p,onCreateBranch:m,onRenameBranch:x,activeIdentityProfile:h,availableIdentities:f,onSelectIdentity:g,isApplyingIdentity:S,isWorktreeMode:k,onOpenHistory:O,onOpenGraph:j,onOpenStashes:v,onOpenUpdateBranch:y,onOpenReintegrateCommits:L,pullRequest:A,prChecks:C,onOpenPullRequest:I})=>{if(!e)return null;const P=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:O||j||v||y?t.jsxs(Qt,{children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsx(Qe,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(N,{name:"more-fill",className:"size-4"})})})}),t.jsx(it,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Xt,{align:"end",children:[O?t.jsxs(St,{onSelect:O,children:[t.jsx(N,{name:"history",className:"size-4"}),"History"]}):null,j?t.jsxs(St,{onSelect:j,children:[t.jsx(N,{name:"git-branch",className:"size-4"}),"Graph"]}):null,v?t.jsxs(St,{onSelect:v,children:[t.jsx(N,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,y?t.jsxs(St,{onSelect:y,children:[t.jsx(N,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,L?t.jsxs(St,{onSelect:L,children:[t.jsx(N,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),D=C?C.state==="success"?"var(--status-success)":C.state==="failure"?"var(--status-error)":"var(--status-warning)":null,W=A?A.state==="merged"?"merged":A.state==="closed"?"closed":A.draft?"draft":C?.state==="failure"||A.mergeable===!1||A.mergeableState==="blocked"||A.mergeableState==="dirty"?"blocked":"open":null,ee=A&&I?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsxs(Qe,{variant:"ghost",size:"sm",onClick:I,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(N,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${W})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${A.number}`}),D?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:D}}):null]})}),t.jsx(it,{sideOffset:8,children:"Open pull request"})]}):null,Z=t.jsx(uh,{syncAction:i,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}),ie=e.upstreamComparison?t.jsx(ph,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,z=t.jsx(Ka,{activeProfile:h,identities:f,onSelect:g,isApplying:S,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:k?t.jsx(dh,{currentBranch:e.current,onRename:x}):t.jsx(lh,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:p,onCreate:m,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:z})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[ee?t.jsx("div",{className:"shrink-0",children:ee}):null,t.jsx("div",{className:"min-w-0 flex-1"}),ie?t.jsx("div",{className:"min-w-0 shrink",children:ie}):null,P,t.jsx("div",{className:"shrink-0",children:Z})]})]})},mh=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Vs=e=>{if(!e||mh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Hs=e=>e.endsWith("/"),Hn=e=>{const s=e.trim();return!s||Hs(s)?s:`${s}/`},go=e=>e.lastIndexOf("/"),Ha=e=>{if(Hs(e))return e;const s=go(e);return s<0?e:e.slice(0,s+1)},Wa=e=>{const s=go(e);return e.slice(s+1)},Ya=e=>{const s=Vs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=go(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Va=e=>Hs(e)&&Ya(e)!==null,gh=e=>{if(!Va(e))return null;const s=Vs(e.trim());return Wa(s)||s},xh=(e,s)=>`${Ha(e)}${s}/`,Cs=e=>{if(!e)return null;const s=Vs(Ks(e.trim()));return s?s.toLowerCase():null},mi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},bh=(e,s)=>{const n=Vs(Ks(e.trim())),r=Vs(Ks(s.trim()));if(!n)return"";if(!r)return Hn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Hn(n)},yh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,fr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},vh=async()=>cu(),wh=({open:e,onOpenChange:s})=>{const n=Rs(M=>M.homeDirectory),r=zt(M=>M.projects),i=zt(M=>M.addProject),a=ue(M=>M.setActiveMainTab),l=ue(M=>M.setSessionSwitcherOpen),c=_e(M=>M.openNewSessionDraft),d=Ns(M=>M.profiles),u=Ns(M=>M.globalIdentity),p=Ns(M=>M.defaultGitIdentityId),m=Ns(M=>M.loadProfiles),x=Ns(M=>M.loadGlobalIdentity),h=Ns(M=>M.loadDefaultGitIdentityId),{canRequestAccess:f,startAccessing:g}=ih(),{isMobile:S,isTablet:k}=Fs(),O=S||k,j=o.useRef(null),v=o.useRef(new Map),[y,L]=o.useState(""),[A,C]=o.useState("~/"),[I,P]=o.useState([]),[D,W]=o.useState(!1),[ee,Z]=o.useState(!1),[ie,z]=o.useState(null),[U,T]=o.useState(0),[R,V]=o.useState(0),[oe,$]=o.useState(!1),[Me,Te]=o.useState(!1),[Ye,Ue]=o.useState(!1),[Ge,Le]=o.useState(""),[re,pe]=o.useState(null),[Ke,ke]=o.useState(!1),[Ce,He]=o.useState("right"),tt=o.useRef("~/"),ze=y||n,J=o.useMemo(()=>new Set(r.map(M=>Cs(M.path)).filter(M=>!!M)),[r]);o.useEffect(()=>{if(!e)return;C("~/"),P([]),V(0),$(!1),Te(!1),Ue(!1),Le(""),pe(null),ke(!1),tt.current="~/",He("right"),O||requestAnimationFrame(()=>fr(j.current));let M=!1;return(async()=>{const Be=await vh();M||(L(Be||n||""),O||requestAnimationFrame(()=>fr(j.current)))})(),()=>{M=!0}},[n,e,O]),o.useEffect(()=>{e&&(m(),x(),h())},[h,m,x,e]);const q=o.useMemo(()=>{const M=new Map;u&&M.set(u.id,u);for(const je of d)M.set(je.id,je);return Array.from(M.values())},[d,u]);o.useEffect(()=>{if(!e||!Ye||re!==null)return;const M=typeof p=="string"?p.trim():"";if(M&&q.some(Be=>Be.id===M)){pe(M);return}const je=q.find(Be=>Be.authType==="ssh"||Be.sshKey);je&&pe(je.id)},[q,p,Ye,e,re]);const ge=o.useMemo(()=>q.find(M=>M.id===re)??null,[q,re]),X=o.useMemo(()=>Ha(A),[A]),we=o.useMemo(()=>Hs(A)?"":Wa(A),[A]),xe=o.useMemo(()=>ze?mi(X,ze):"",[X,ze]);o.useEffect(()=>{const M=tt.current;M!==X&&(He(X.length>=M.length?"right":"left"),tt.current=X)},[X]),o.useEffect(()=>{if(!e||!xe){P([]),z(null);return}let M=!1;return W(!0),Z(!1),z(null),iu(xe).then(je=>{if(M)return;Z(!1),z(null);const Be=je.filter(dt=>dt.isDirectory).map(dt=>({name:dt.name,path:Ks(dt.path)})).sort((dt,F)=>dt.name.localeCompare(F.name));P(Be)}).catch(je=>{if(!M){P([]);const Be=au(je)?je.reason:"unknown";z(Be),Z(Be==="not-found")}}).finally(()=>{M||W(!1)}),()=>{M=!0}},[xe,U,e]);const Ne=o.useMemo(()=>{const M=we.toLowerCase(),je=Ke||we.startsWith(".");return I.filter(Be=>Be.name.toLowerCase().startsWith(M)&&(je||!Be.name.startsWith(".")))},[we,I,Ke]),pt=o.useMemo(()=>gh(A),[A]),gt=o.useMemo(()=>Ya(A),[A]),et=o.useMemo(()=>{const M=[],je=Cs(xe);Va(A)&&pt&>&&M.push({type:"parent",value:"browse:up",name:pt,path:gt,alreadyAdded:!!(je&&J.has(je))});for(const Be of Ne){const dt=Cs(Be.path);M.push({type:"directory",value:`browse:${Be.path}`,name:Be.name,path:Be.path,alreadyAdded:!!(dt&&J.has(dt))})}return M},[J,xe,pt,Ne,gt,A]);o.useEffect(()=>{V(0)},[A,et.length]);const De=o.useMemo(()=>ze?Vs(mi(A,ze)):"",[ze,A]),Fe=Cs(De),Ae=!!(Fe&&J.has(Fe)),at=o.useMemo(()=>we?Ne.find(M=>M.name===we)??null:null,[we,Ne]),jt=!!(De&&!Ae&&(ie===null||ie==="not-found")&&(Hs(A)&&ee||!Hs(A)&&we.trim().length>0&&at===null)),st=!oe&&!Me&&!Ae&&ie!=="os-permission"&&ie!=="invalid-response"&&ie!=="unknown"&&!!De,_=st&&Ge.trim().length>0,ye=et[R]??null,be=!!ye,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Y=Ae?"Already added":Ye?oe?"Cloning...":"Clone & add":oe?"Adding...":jt?"Create & add":"Add folder",se=Ye?_:st;o.useLayoutEffect(()=>{const M=j.current;M&&(M.scrollLeft=M.scrollWidth)},[A]),o.useLayoutEffect(()=>{!e||O||fr(j.current)},[e,O]),o.useLayoutEffect(()=>{const M=et[R];M&&v.current.get(M.value)?.scrollIntoView({block:"nearest"})},[R,et]);const de=o.useCallback(()=>{s(!1)},[s]),Se=o.useCallback((M,je)=>{a("chat"),S&&l(!1),c({selectedProjectId:M,directoryOverride:je}),de()},[de,S,c,a,l]),Pe=o.useCallback(async M=>{if(!M||oe)return;const je=Cs(M);if(je&&J.has(je))return;let Be=M;$(!0);try{const dt=!Ye&&jt&&Cs(M)===Cs(De);if(Ye){const ae=Ge.trim();if(!ae){le.error("Enter a repository URL before cloning.");return}const me=await es("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ae,destinationPath:M,gitIdentityId:ge?.id??null})});if(!me.ok)throw new Error("Failed to clone git repository");Be=(await me.json()).path||M}else if(dt&&!(await es("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:xe?{directory:xe}:void 0,body:JSON.stringify({path:M})})).ok)throw new Error("Failed to select directory");const F=i(Be);if(!F){le.error("Failed to add folder",{description:"Please select a valid directory path."});return}Se(F.id,F.path)}catch(dt){le.error("Failed to select directory",{description:dt instanceof Error?dt.message:"Unknown error occurred."})}finally{$(!1)}},[i,J,xe,Ge,Ye,oe,Se,ge?.id,jt,De]),$e=o.useCallback(M=>{C(Hn(M))},[]),mt=o.useCallback(M=>{C(xh(A,M.name))},[A]),Ct=o.useCallback(M=>{if(M){if(M.type==="parent"){$e(M.path);return}mt(M)}},[$e,mt]),Xe=o.useCallback(async M=>{const je=await g(M);if(!je.success)return le.error("Failed to open directory",{description:je.error||"Desktop could not grant file access."}),!1;const Be=ze?bh(M,ze):Hn(Ks(M));return $e(Be),!0},[$e,ze,g]),ct=o.useCallback(async()=>{if(!Me){Te(!0);try{if(oo()){const je=await io(De);if(!je.success||!je.path){je.error&&je.error!=="Directory selection cancelled"&&le.error("Failed to select directory",{description:je.error});return}await Xe(je.path);return}const M=await lu(De);if(M.status==="cancelled")return;if(M.status!=="picked"){le.error("Couldn't open a folder picker",{description:M.error});return}await Xe(M.path)}catch(M){le.error("Failed to select directory",{description:M instanceof Error?M.message:"Unknown error occurred."})}finally{Te(!1)}}},[Xe,Me,De]),xt=o.useCallback(M=>{if(M.key==="ArrowDown"){M.preventDefault(),V(je=>Math.min(et.length-1,je+1));return}if(M.key==="ArrowUp"){M.preventDefault(),V(je=>Math.max(0,je-1));return}if(M.key==="Enter"){if(M.preventDefault(),yh(M)){Pe(De);return}be&&Ct(ye);return}M.key==="Backspace"&&A===""&&(M.preventDefault(),de())},[Ct,Pe,de,be,ye,A,et.length,De]),Oe=t.jsxs("button",{type:"button",onClick:()=>ke(M=>!M),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:[Ke?t.jsx(N,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(N,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),We=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(N,{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(Ws,{ref:j,value:A,onChange:M=>C(Ks(M.target.value)),onKeyDown:xt,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(Qe,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:oe||Me,onMouseDown:M=>M.preventDefault(),onClick:()=>{ct()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(N,{name:"folder-open",className:"h-3.5 w-3.5"}),Me?"Opening...":"Browse"]})]})}),bt=et.some(M=>M.type==="parent"),Mt=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(Qe,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ye,disabled:oe||Me,onClick:()=>Ue(M=>!M),children:[t.jsx(N,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ye?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(Ws,{value:Ge,onChange:M=>Le(M.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(Ka,{activeProfile:ge,identities:q,onSelect:M=>pe(M.id),isApplying:oe,iconOnly:!0})]})]}):null,Ae?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:B("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",Ce==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:D?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):ie&&ie!=="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:ie==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[ie==="os-permission"&&f?t.jsx(Qe,{size:"xs",onClick:()=>{ct()},disabled:Me,children:"Grant access"}):null,t.jsx(Qe,{variant:"outline",size:"xs",onClick:()=>T(M=>M+1),children:"Try again"})]})]}):et.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:et.map((M,je)=>{const Be=je===R,dt=M.type==="directory"&&bt;return t.jsxs("button",{ref:F=>{F?v.current.set(M.value,F):v.current.delete(M.value)},type:"button","aria-label":M.type==="parent"?M.alreadyAdded?`Go back from ${M.name}, already added`:`Go back from ${M.name}`:M.alreadyAdded?`Open ${M.name}, already added`:`Open ${M.name}`,onMouseEnter:()=>V(je),onMouseDown:F=>F.preventDefault(),onClick:()=>Ct(M),className:B("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",Be&&"bg-interactive-selection text-interactive-selection-foreground",!Be&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:B("flex min-w-0 flex-1 items-center gap-2",dt&&"pl-4"),children:[M.type==="parent"?t.jsx(N,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(N,{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:M.name})]}),M.alreadyAdded?t.jsx("span",{className:B("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Be?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,M.type==="parent"?t.jsx(N,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(N,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},M.value)})})},X)]})}),$t=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[We,Mt]}),Nt=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(N,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(N,{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(N,{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:w}),t.jsx(N,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),At=t.jsx(Qe,{size:S?"xs":"default",onClick:()=>{Pe(De)},disabled:!se,className:B(S&&"w-full flex-1"),children:Y}),It=()=>t.jsxs(t.Fragment,{children:[S?null:Nt,t.jsx("div",{className:B("flex w-full flex-row justify-end gap-2 sm:w-auto",S&&"justify-stretch"),children:At})]});return S?t.jsx(sa,{open:e,onClose:de,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:It()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Oe}),$t]})}):t.jsx(cs,{open:e,onOpenChange:s,children:t.jsxs(ds,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(Ss,{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(ms,{children:"Add folder"}),t.jsx(Os,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Oe]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:$t}),t.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:It()})]})})},An=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,kx=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=nd,c=_e(L=>L.deleteSessions),d=ue(L=>L.showDeletionDialog),u=ue(L=>L.setShowDeletionDialog),{isMobile:p,isTablet:m,hasTouchInput:x}=Fs(),h=p||m||x;o.useEffect(()=>du(()=>{s(!1)}),[]);const f=o.useCallback(L=>{r({sessions:L.sessions,dateLabel:L.dateLabel})},[]),g=o.useCallback(()=>{r(null),a(!1)},[]),S=o.useCallback(async L=>{if(L.sessions.length===0)return;if(L.sessions.length===1){const P=L.sessions[0];await l(P.id)?le.success("Session deleted"):le.error("Failed to delete session");return}const A=L.sessions.map(P=>P.id),{deletedIds:C,failedIds:I}=await c(A);if(C.length>0){const P=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:L.dateLabel?`Removed all sessions from ${L.dateLabel}.`:void 0;le.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:An(P)})}I.length>0&&le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:An("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Ts.onDeleteRequest(L=>{if(!d){S(L);return}f(L)}),[f,d,S]),o.useEffect(()=>Ts.onDirectoryRequest(()=>{s(!0)}),[]);const k=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const L=n.sessions[0];if(!await l(L.id)){le.error("Failed to delete session"),a(!1);return}le.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const L=n.sessions.map(P=>P.id),A=await c(L),C=A.deletedIds,I=A.failedIds;if(C.length>0){const P=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;le.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:An(P),action:{label:"OK",onClick:()=>{}}})}if(I.length>0&&(le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:An("Please try again in a moment.")}),C.length===0)){a(!1);return}}g()}finally{a(!1)}}},[n,l,c,g]),O=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",j=n?t.jsxs("div",{className:"space-y-2",children:[n.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:[n.sessions.slice(0,5).map(L=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:L.title||"Untitled Session"})},L.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.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,v=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(N,{name:"checkbox-blank",className:"size-4"}):t.jsx(N,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Qe,{variant:"ghost",onClick:g,disabled:i,children:"Cancel"}),t.jsx(Qe,{variant:"destructive",onClick:k,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),y=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[h?t.jsx(sa,{open:!!n,onClose:()=>{i||g()},title:y,footer:t.jsx("div",{className:"flex justify-end gap-2",children:v}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[O&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:O}),j]})}):t.jsx(cs,{open:!!n,onOpenChange:L=>{if(!L){if(i)return;g()}},children:t.jsxs(ds,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(Ss,{children:[t.jsx(ms,{children:y}),O&&t.jsx(Os,{children:O})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:j}),t.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:v})]})}),t.jsx(wh,{open:e,onOpenChange:s})]})};function Nx(){const e=o.useRef(!1),s=o.useRef(!1),n=_e(p=>p.setCurrentSession),r=ue(p=>p.setActiveMainTab),i=ue(p=>p.setSettingsDialogOpen),a=ue(p=>p.setSettingsPage),l=ue(p=>p.navigateToDiff),c=o.useCallback(async p=>{if(!s.current){s.current=!0;try{if(p.sessionId){const m=_e.getState().currentSessionId,x=Zs().getState().selectedSessionId;if(p.sessionId!==m||p.sessionId!==x){const h=_e.getState().getDirectoryForSession(p.sessionId);n(p.sessionId,h)}}if(p.settingsPath){a(oh(p.settingsPath)),i(!0);return}ue.getState().isSettingsDialogOpen&&i(!1),p.tab&&r(p.tab),p.diffFile&&(p.tab==="diff"||!p.tab)&&l(p.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const p=_e.getState(),m=Zs().getState(),x=ue.getState();return{sessionId:lr({currentSessionId:p.currentSessionId,piSelectedSessionId:m.selectedSessionId,draft:p.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=o.useCallback((p={})=>{if(s.current)return;const m=d();Gr(m,p)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Ho()))return;const p=Wo();(async()=>(await c(p),Gr({...d(),sessionId:p.sessionId??lr({currentSessionId:_e.getState().currentSessionId,piSelectedSessionId:Zs().getState().selectedSessionId,draft:_e.getState().newSessionDraft}),tab:p.tab??ue.getState().activeMainTab,settingsPath:p.settingsPath??ue.getState().settingsPage,diffFile:p.diffFile??ue.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const p=()=>{const S=_e.getState(),k=Zs().getState();return lr({currentSessionId:S.currentSessionId,piSelectedSessionId:k.selectedSessionId,draft:S.newSessionDraft})};let m=p(),x=_e.getState().newSessionDraft?.open===!0;const h=()=>{const S=_e.getState(),k=p(),O=S.newSessionDraft?.open===!0;k===m&&O===x||s.current||(m=k,x=O,u({replace:!0}))},f=_e.subscribe(()=>{h()}),g=Zs().subscribe(()=>{h()});return()=>{f(),g()}},[u]),o.useEffect(()=>{let p=ue.getState().activeMainTab,m=ue.getState().isSettingsDialogOpen,x=ue.getState().settingsPage,h=ue.getState().pendingDiffFile;return ue.subscribe(g=>{if(s.current)return;const S=g.activeMainTab!==p,k=g.isSettingsDialogOpen!==m,O=g.settingsPage!==x,j=g.pendingDiffFile!==h&&g.activeMainTab==="diff";p=g.activeMainTab,m=g.isSettingsDialogOpen,x=g.settingsPage,h=g.pendingDiffFile,(S||k||O||j)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const p=()=>{const m=Wo();if(Ho())c(m);else{const x=ue.getState();x.isSettingsDialogOpen&&i(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",p),()=>{window.removeEventListener("popstate",p)}},[c,r,i])}function Sh(e=!0){const s=Bn(r=>r.checkForUpdates),n=o.useRef(s);o.useEffect(()=>{n.current=s},[s]),o.useEffect(()=>{if(!e)return;const r=3e3,i=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=m=>{const x=Math.round(m*1e3);return Math.max(a,Math.min(l,x))},p=m=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),h=typeof x=="number"&&Number.isFinite(x)?u(x):i;p(h)},m))};return p(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Ax(){const e=rn(s=>s.connection==="ready",void 0,"chrome");return Sh(e),null}const gi=12,jh=[{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"}],Ch=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=jh,onComplete:a})=>{const l=qe.useRef(!1);qe.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=qe.useMemo(()=>Array.from({length:gi},(d,u)=>{const p=Math.PI*2*u/gi;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return e?t.jsx("div",{className:B("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.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((p,m)=>{const x=p.x*d.radius,h=p.y*d.radius,f={"--translate-x":`${x}px`,"--translate-y":`${h}px`,"--particle-delay":`${p.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:f},`${d.id}-${m}-${s}`)})},`${d.id}-${s}`)})}):null},kh=({durationMs:e=3400}={})=>{const[s,n]=qe.useState({isActive:!1,cycle:0}),r=qe.useRef(null),i=qe.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=qe.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=qe.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[i,e]);return qe.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},qa=o.createContext(void 0),Ix=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=kh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(qa.Provider,{value:a,children:[e,t.jsx(Ch,{isActive:s,burstKey:n})]})},Nh={triggerFireworks:()=>{},dismissFireworks:()=>{}},Dx=()=>o.useContext(qa)??Nh,xi=380,bi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Wn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),In=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(N,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Ah=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const i=o.useRef(null),[a,l]=o.useState(e),[c,d]=o.useState(!1),{enabled:u}=eo(),p=o.useRef(null),[m,x]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const f=()=>{const k=n.current?.getBoundingClientRect(),O=p.current?.getBoundingClientRect();if(!k||!O){x(null);return}const j=k.left-O.left,v=Math.min(Math.max(j,8),Math.max(8,O.width-xi-8));x(v)};f();const g=p.current;if(typeof ResizeObserver>"u"||!g)return;const S=new ResizeObserver(f);return S.observe(g),()=>S.disconnect()},[n,u,e,a]);const h=u&&m!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const f=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(f)},[e,a]),o.useEffect(()=>{if(!e)return;const f=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s,e]),o.useEffect(()=>{if(!e)return;const f=g=>{const S=g.target;if(!(S instanceof Node)){s();return}i.current?.contains(S)||n.current?.contains(S)||s()};return document.addEventListener("pointerdown",f,!0),document.addEventListener("wheel",f,!0),()=>{document.removeEventListener("pointerdown",f,!0),document.removeEventListener("wheel",f,!0)}},[n,s,e]),a?t.jsxs("div",{ref:p,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:i,role:"tooltip","aria-label":"Context usage for current conversation",className:B("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",h?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...h?{top:8,left:m??8,width:`min(${xi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(In,{iconNode:t.jsx(ra,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:B("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(In,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Wn(r.cacheRead)})}),t.jsx(In,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Wn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(In,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
|
|
3
|
-
@keyframes session-metadata-in {
|
|
4
|
-
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
|
-
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
6
|
-
}
|
|
7
|
-
@keyframes session-metadata-out {
|
|
8
|
-
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
9
|
-
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
10
|
-
}
|
|
11
|
-
`})]}):null},Ih=o.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:i,isNewSessionDraftOpen:a}){const l=o.useRef(null),c=rd(r??""),d=Ot(z=>z.providers),u=Ot(z=>z.currentProviderId),p=Ot(z=>z.currentModelId),m=Ot(z=>z.getCurrentModel()),x=Ot(z=>z.getModelMetadata);Ot(z=>z.modelsMetadata.size);const h=na(o.useCallback(z=>r?z.sessionModelSelections.get(r)??null:null,[r])),f=o.useMemo(()=>{for(let z=c.length-1;z>=0;z-=1){const U=c[z]?.info;if(U.role!=="user")continue;const T=U.model,R=T?.providerID??T?.providerId,V=T?.modelID??T?.modelId,oe=typeof R=="string"&&R.trim().length>0?R:void 0,$=typeof V=="string"&&V.trim().length>0?V:void 0;if(oe&&$)return{providerID:oe,modelID:$}}return null},[c]),g=o.useMemo(()=>{for(let z=c.length-1;z>=0;z-=1){const U=c[z];if(U?.info.role==="assistant"&&Yo(U).total>0)return U}return null},[c]),S=f??(()=>{const z=g?.info.model,U=z?.providerID??z?.providerId,T=z?.modelID??z?.modelId;return U&&T?{providerID:U,modelID:T}:null})()??(h?{providerID:h.providerId,modelID:h.modelId}:null)??(u&&p?{providerID:u,modelID:p}:null),O=(S?d.find(z=>z.id===S.providerID):void 0)?.models.find(z=>z.id===S?.modelID),j=S?x(S.providerID,S.modelID):void 0,v=bi(O?.limit,"context")??j?.limit?.context??bi(m?.limit,"context")??0,y=g?Yo(g):null,L=g?.info?.usage,A=L?od(L):y?.total??0,C=!a&&A>0&&v>0?Math.min(A/v*100,999):null,I=C!==null?`${Wn(A)}/${Wn(v)}`:null,P=C===null?"":C>=90?"text-[var(--status-error)]":C>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",D=y?.cacheRead??null,W=y?.cacheWrite??null,ee=y?id({input:y.input,cache:{read:y.cacheRead,write:y.cacheWrite}}):{percent:0,hasInput:!1},Z=ee.hasInput?ee.percent:null,ie=C!==null&&I?{percentage:C,tokens:I,colorClass:P,cacheRead:D,cacheWrite:W,cacheHitPercent:Z}:null;return t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:l,type:"button",className:"flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Show context usage for current conversation",title:"Context usage","aria-expanded":s,onClick:()=>n(z=>!z),style:{touchAction:"manipulation"},children:t.jsx(ra,{percentage:ie?.percentage??0})}),t.jsx(Ah,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:ie})]})}),yi=600,Dh=1,Ph=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},Eh=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:i})=>{const a=o.useRef(new Map),l=o.useRef([]),c=o.useRef(new Set),d=o.useRef(0),u=!1,p=o.useCallback(f=>`${f.directory}
|
|
12
|
-
${f.sessionId}`,[]),m=o.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(f=>window.clearTimeout(f)),a.current.clear()},[]),x=o.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<Dh&&l.current.length>0;){const f=l.current.shift();if(!f)break;f.generation!==d.current||_e.getState().currentSessionId===f.sessionId||ad(f.sessionId,f.directory).renderable}},[e,u,i,p]),h=o.useCallback(f=>{const g=f?.id,S=Ph(f);if(!e||u||!g||!S||g===s||typeof window>"u")return;const k={sessionId:g,directory:S,generation:d.current};p(k)},[s,e,u,x,p]);o.useEffect(()=>{m()},[m,s,e,u]),o.useEffect(()=>{if(!e||u||!s||n.length===0)return;const f=window.setTimeout(()=>{const g=n.findIndex(S=>S.id===s);g<0||(h(n[g-1]),h(n[g+1]))},yi);return()=>window.clearTimeout(f)},[s,e,u,h,n]),o.useEffect(()=>{if(!e||u||!s||r.length===0)return;const f=window.setTimeout(()=>{const g=r.findIndex(S=>S.id===s);g<0||(h(r[g-1]),h(r[g+1]))},yi);return()=>window.clearTimeout(f)},[s,e,u,r,h]),o.useEffect(()=>m,[m])},Th=e=>{const s=_e(n=>n.currentSessionId);return Eh({...e,currentSessionId:s}),null},Rh=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:i,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:p}=e;o.useEffect(()=>{!n||i||!a||l||s.forEach(m=>{if(c.has(m.normalizedPath))return;const x=Sa(m.normalizedPath),h=r.archivedSessionsByProject.get(m.id)??[],f=d[x]??[],g=new Map(f.map(S=>[S.name.toLowerCase(),S]));h.forEach(S=>{const k=Au(S,m.normalizedPath),O=k.toLowerCase();let j=g.get(O);j||(j=u(x,k),g.set(O,j)),j.sessionIds.includes(S.id)||p(x,j.id,S.id)})})},[s,n,r,i,a,l,c,d,u,p])},Mh=e=>({getOrderedGroups:o.useCallback((n,r)=>{const i=e.get(n);if(!i||i.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];i.forEach(u=>{const p=a.get(u);p&&(l.push(p),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])}),Fh=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:i,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:p,filterSessionNodesForSearch:m,buildGroupSearchText:x,foldersMap:h}=e,f=o.useRef(new Map),g=o.useMemo(()=>{const A=f.current,C=new Map;let I=0,P=0;const D=(ee,Z)=>ee.length===Z.length&&ee.every((ie,z)=>ie===Z[z]),W=s.map(ee=>{const Z=n(ee.id),ie=r(ee.id),z=a.has(ee.id)?!!a.get(ee.id):c,U=l.get(ee.id)??null,T=i.get(ee.normalizedPath)??[],R=A.get(ee.id);if(R&&R.project===ee&&D(R.activeSessions,Z)&&D(R.archivedSessions,ie)&&R.rootBranch===U&&R.isRepo===z&&R.worktrees===T&&R.buildGroupedSessions===d)return I+=1,C.set(ee.id,R),R.section;P+=1;const V=ja([...Z,...ie]),oe=d(V,ee.normalizedPath,T,U,z),$={project:ee,groups:oe};return C.set(ee.id,{project:ee,activeSessions:Z,archivedSessions:ie,rootBranch:U,isRepo:z,worktrees:T,buildGroupedSessions:d,section:$}),$});return f.current=C,I>0&&as("ui.sidebar.project_section.reused",I),P>0&&as("ui.sidebar.project_section.rebuilt",P),W},[s,n,r,i,a,c,d,l]),S=o.useMemo(()=>g,[g]),k=o.useMemo(()=>{const A=new WeakMap;if(!u)return A;const C=I=>I.reduce((P,D)=>P+1+C(D.children),0);return S.forEach(I=>{I.groups.forEach(P=>{const D=m(P.sessions,p),W=C(D),ee=x(P).includes(p),Z=Ze(P.directory??null),z=(Z?h[Z]??[]:[]).filter(U=>U.name.toLowerCase().includes(p)).length;A.set(P,{filteredNodes:D,matchedSessionCount:W,folderNameMatchCount:z,groupMatches:ee,hasMatch:ee||W>0||z>0})})}),A},[u,S,m,p,x,h]),O=o.useMemo(()=>u?S.map(A=>({...A,groups:A.groups.filter(C=>k.get(C)?.hasMatch===!0)})).filter(A=>A.groups.length>0):S,[u,S,k]),j=u?O:S,v=o.useRef(new WeakMap),y=o.useMemo(()=>{const A=v.current;return j.map(C=>{const I=A.get(C);if(I&&I.query===p)return I.section;const P=C.groups.filter(U=>!U.isArchivedBucket),D=C.groups.filter(U=>U.isArchivedBucket),W=P.flatMap(U=>u?k.get(U)?.filteredNodes??[]:U.sessions),ee=P.map(U=>({scopeKey:U.folderScopeKey??Ze(U.directory??null),directory:U.directory??null})).filter(U=>!!U.scopeKey),Z=P.find(U=>U.isMain)??null,ie={id:"flat",label:Z?.label??"",branch:Z?.branch??null,description:Z?.description??null,isMain:!0,isArchivedBucket:!1,directory:Z?.directory??C.project.normalizedPath,folderScopeKey:Z?.folderScopeKey??C.project.normalizedPath,folderScopes:ee,sessions:W};if(u){const U=P.map(T=>k.get(T)).filter(T=>!!T);k.set(ie,{filteredNodes:W,matchedSessionCount:U.reduce((T,R)=>T+R.matchedSessionCount,0),folderNameMatchCount:U.reduce((T,R)=>T+R.folderNameMatchCount,0),groupMatches:U.some(T=>T.groupMatches),hasMatch:U.some(T=>T.hasMatch)})}const z={project:C.project,groups:[ie,...D]};return A.set(C,{query:p,section:z}),z})},[k,u,p,j]),L=o.useMemo(()=>u?j.reduce((A,C)=>A+C.groups.reduce((I,P)=>{const D=k.get(P);if(!D)return I;const W=D.folderNameMatchCount+(D.groupMatches?1:0);return I+D.matchedSessionCount+W},0),0):0,[u,j,k]);return{projectSections:g,visibleProjectSections:S,groupSearchDataByGroup:k,searchableProjectSections:O,sectionsForRender:j,flatSectionsForRender:y,searchMatchCount:L}},Oh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:i,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:p,setSessionSwitcherOpen:m}=e,x=o.useMemo(()=>{const f=new Map,g=new Map,S=(k,O,j,v)=>{f.has(k)||f.set(k,new Map);const y=f.get(k);v.forEach(L=>{const A=Ze(L.session.directory??j??O);y.set(L.session.id,{directory:A}),g.has(k)||g.set(k,{id:L.session.id,directory:A}),L.children.length>0&&S(k,O,A,L.children)})};return s.forEach(k=>{k.groups.forEach(O=>{S(k.project.id,k.project.normalizedPath,O.directory,O.sessions)})}),{metaByProject:f,firstSessionByProject:g}},[s]),h=o.useRef(null);o.useLayoutEffect(()=>{if(!n)return;if(c){h.current=n;return}if(h.current===n)return;const f=s.find(L=>L.project.id===n);if(!f)return;h.current=n;const g=x.metaByProject.get(n);if(a&&g&&g.has(a)){i(L=>{if(L.get(n)===a)return L;const A=new Map(L);return A.set(n,a),A});return}const S=a?Array.from(x.metaByProject.entries()).some(([L,A])=>L!==n&&A.has(a)):!1;if(a&&g&&!S)return;if(!g||g.size===0){p("chat"),d&&m(!1),u({selectedProjectId:f.project.id,directoryOverride:f.project.normalizedPath});return}const k=r.get(n),O=k&&g.has(k)?k:null,j=x.firstSessionByProject.get(n)?.id??null,v=O??j;if(!v||v===a)return;const y=g.get(v)?.directory??null;l(v,y,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,x,p,m,i]),o.useEffect(()=>{if(!n||!a)return;const f=x.metaByProject.get(n);!f||!f.has(a)||i(g=>{if(g.get(n)===a)return g;const S=new Map(g);return S.set(n,a),S})},[n,a,x,i])},Lh=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=_e(c=>c.currentSessionId),i=_e(c=>!!c.newSessionDraft?.open),[a,l]=o.useState(()=>new Map(e));return Oh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:i}),o.useEffect(()=>{s(a)},[a,s]),null},vi=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Bh=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},_h=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,Qa=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=Bh(e.trim())%vi.length;return vi[s]},zh=(e,s)=>{const n=Qa(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},wi=e=>!!e.time?.archived,$h=e=>{const s=o.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=o.useCallback(a=>{const l=Ze(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${l}`.toLowerCase()},[]),r=o.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]),i=o.useCallback((a,l,c=[],d,u)=>{const p=Ze(l??null),m=ja(a).sort((A,C)=>to(A,C,e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(m.map(A=>[A.id,A])),h=new Map,f=new Map;m.forEach(A=>{const C=A.parentID??null,I=C?x.get(C):null,P=I&&wi(I)===wi(A)?C:null;h.set(A.id,P),P&&f.set(P,(f.get(P)??0)+1)});const g=c.map(A=>({worktree:A,directory:Ze(A.path)})).filter(A=>!!A.directory&&!A.worktree.isPrimary).sort((A,C)=>C.directory.length-A.directory.length),S=(A,C)=>C===A||C.startsWith(`${A}/`),k=A=>{const C=Ze(A.directory??null);return C?g.find(I=>S(I.directory,C))?.worktree??null:null},O=(A,C)=>{const I=_h(A.id,h,f);return{session:A,children:[],worktree:C,forkColorId:I}},j=[],v=new Map,y=[];for(const A of g)v.set(A.directory,[]);m.forEach(A=>{const C=k(A),I=O(A,C);A.time?.archived?y.push(I):C?v.get(Ze(C.path)??"")?.push(I):j.push(I)});const L=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:p?ti(p,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:p,folderScopeKey:p,sessions:j}];for(const{worktree:A,directory:C}of g)L.push({id:`worktree:${C}`,label:A.branch||(A.detached?"Detached HEAD":A.name),branch:A.branch,description:ti(C,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:A,directory:C,folderScopeKey:C,sessions:v.get(C)??[]});return y.length>0&&L.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:p?Sa(p):null,sessions:y}),L},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:i}},Uh=({mobileVariant:e,isTablet:s})=>!e&&!s,Gh=({enabled:e=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:i})=>{o.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]),o.useEffect(()=>{if(!e||!s||typeof document>"u")return;const a=l=>{i.current&&(i.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e,s,n,i])},Kh=e=>{const[s,n]=o.useState(null),r=o.useRef(null);o.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const i=o.useCallback((j,v,y)=>{Rr("navigation.session_select"),ue.getState().closeMainSurfaces();const L=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},A=y?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),j===_e.getState().currentSessionId){e.allowReselect&&A&&e.onSessionSelected?.(j),L();return}Rr("navigation.session_state_set"),e.setCurrentSession(j,v??null),A&&e.onSessionSelected?.(j),L()},[e]),a=o.useCallback((j,v)=>{e.setEditingId(j),e.setEditTitle(v)},[e]),l=o.useCallback(async j=>{if(!e.editingId)return;const v=(j??e.editTitle).trim();v&&await e.updateSessionTitle(e.editingId,v),e.setEditingId(null),e.setEditTitle("")},[e]),c=o.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=o.useCallback(async(j,v)=>{try{return(await fn(j)).ok?(n(v),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=o.useCallback(async j=>{const v=await e.shareSession(j.id);if(!v?.share?.url){le.error("Unable to share session");return}const y=await d(v.share.url,j.id);le[y?"success":"warning"]("Session shared",{description:y?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),p=o.useCallback((j,v)=>{d(j,v).then(y=>{y||le.error("Failed to copy URL")})},[d]),m=o.useCallback(j=>{fn(j).then(v=>{if(v.ok){le.success("Session ID copied");return}le.error("Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[]),x=o.useCallback(async j=>{await e.unshareSession(j)?le.success("Session unshared"):le.error("Unable to unshare session")},[e]),h=o.useCallback(j=>{const v=[],y=L=>{(e.childrenMap.get(L)??[]).forEach(C=>{v.push(C),y(C.id)})};return y(j),v},[e.childrenMap]),f=o.useCallback((j,v)=>v?j:j.filter(y=>!y.time?.archived),[]),g=o.useCallback(async(j,v,y)=>{const L=v?.archivedBucket===!0||v?.hardDelete===!0,A=y?.descendantIds??f(h(j.id),L).map(D=>D.id);if(A.length===0){(L?await e.deleteSession(j.id):await e.archiveSession(j.id))?le.success(L?"Session deleted":"Session archived"):le.error(L?"Failed to delete session":"Failed to archive session");return}const C=[j.id,...A];if(L){const{deletedIds:D,failedIds:W}=await e.deleteSessions(C);if(W.length===0){const ee=D.length;le.success(ee===1?`Deleted ${ee} session`:`Deleted ${ee} sessions`)}else le.error("Failed to delete session");return}const{archivedIds:I,failedIds:P}=await e.archiveSessions(C);I.length>0&&le.success(I.length===1?`Archived ${I.length} session`:`Archived ${I.length} sessions`),P.length>0&&le.error(P.length===1?`Failed to archive ${P.length} session`:`Failed to archive ${P.length} sessions`)},[e,h,f]),S=o.useCallback((j,v)=>{const y=v?.archivedBucket===!0||v?.hardDelete===!0,L=f(h(j.id),y).map(A=>A.id);if(!e.showDeletionDialog||v?.skipConfirm===!0){g(j,v,{descendantIds:L});return}e.setDeleteSessionConfirm({session:j,descendantCount:L.length,descendantIds:L,archivedBucket:y})},[e,h,g,f]),k=o.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:j,archivedBucket:v,descendantIds:y}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await g(j,{archivedBucket:v},{descendantIds:y})},[e,g]),O=o.useCallback(async j=>{await e.unarchiveSession(j.id)?le.success("Session restored"):le.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:i,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:p,handleCopySessionId:m,handleUnshareSession:x,handleDeleteSession:S,handleRestoreSession:O,confirmDeleteSession:k}},Hh=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:i,setExpandedParents:a,setCollapsedProjects:l}=e,c=o.useRef(null),d=o.useRef(null),u=o.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:x}=zt.getState(),h=x.map(f=>({...f,sidebarCollapsed:m.has(f.id)}));no({projects:h}).catch(()=>{})},[]),p=o.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return o.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),o.useEffect(()=>{try{const m=s.getItem(n.sessionExpanded);if(m){const h=JSON.parse(m);Array.isArray(h)&&a(new Set(h.filter(f=>typeof f=="string")))}const x=s.getItem(n.projectCollapse);if(x){const h=JSON.parse(x);Array.isArray(h)&&l(new Set(h.filter(f=>typeof f=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),o.useEffect(()=>{try{const m=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(m))}catch{}},[r,n.groupOrder,s]),o.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(i)))}catch{}},[i,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:p}},Wh=3;let Yn=0;const Ja=[],Yh=()=>Yn<Wh?(Yn+=1,Promise.resolve()):new Promise(e=>{Ja.push(e)}),Vh=()=>{const e=Ja.shift();if(e){e();return}Yn=Math.max(0,Yn-1)},qh=async e=>{await Yh();try{return await e()}finally{Vh()}},Qh=5*6e4,Jh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:i,setProjectRootBranches:a}=e,{git:l}=Qn(),c=oa(m=>m.ensureStatus);o.useEffect(()=>{if(!n||!l||s.length===0){i(new Map);return}s.forEach(m=>{qh(()=>c(m.normalizedPath,l))})},[n,s,l,c,i]),o.useEffect(()=>{if(!n)return;const m=new Map;s.forEach(x=>{m.set(x.id,r.get(x.normalizedPath)?.isGitRepo??null)}),i(m)},[n,s,r,i]);const d=o.useMemo(()=>s.map(m=>{const x=r.get(m.normalizedPath)?.branch??"";return`${m.id}:${x}`}).join("|"),[s,r]),u=o.useRef(new Map),p=o.useRef(new Map);o.useEffect(()=>{if(!n)return;let m=!1;const x=setTimeout(()=>{(async()=>{const f=new Set(s.map(j=>j.id));for(const j of u.current.keys())f.has(j)||(u.current.delete(j),p.current.delete(j));const g=Date.now();if(s.filter(j=>{const v=r.get(j.normalizedPath);if(v?.isGitRepo===!1)return u.current.delete(j.id),p.current.delete(j.id),!1;if(v?.isGitRepo!==!0||v.branch===null)return!1;const y=v.branch.trim(),L=`${j.normalizedPath}\0${y}`,A=u.current.get(j.id);if(A===L){const C=p.current.get(j.id);return C&&(C.at=g),!1}return!(A!==void 0&&g-(p.current.get(j.id)?.at??0)<Qh)}).length===0)return;const k=[];if(s.forEach(j=>{const v=r.get(j.normalizedPath)?.branch?.trim()??"",y=`${j.normalizedPath}\0${v}`;v&&k.push({id:j.id,inputKey:y,branch:v})}),m||k.length===0)return;const O=Date.now();a(j=>{const v=new Map(j);return k.forEach(({id:y,branch:L})=>{L&&v.set(y,L)}),v}),k.forEach(({id:j,inputKey:v,branch:y})=>{u.current.set(j,v),y&&p.current.set(j,{branch:y,at:O})})})()},150);return()=>{m=!0,clearTimeout(x)}},[n,s,d,r,a])},Xh=e=>{const{ownership:s}=e,n=o.useCallback(i=>s.sessionsByProject.get(i)??[],[s]),r=o.useCallback(i=>s.archivedSessionsByProject.get(i)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Zh=e=>{if(e.runtimeKey!==Xn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=uu(e.sessionId,e.directory,e.runtimeKey);s&&fu.getState().clearQueue(s),ld.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),Kt.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),ia.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),Er.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=cd(e.runtimeKey,e.directory,e.sessionId);n&&dd(n,!0)},ep=e=>{const s=new Map;for(const n of e){const r=Ps(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},tp=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,i)=>{s.has(i)||n.push(r)}),n},sp=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,i=o.useRef(null);o.useEffect(()=>{if(!s||!n)return;const a=Xn(),l=ep(r),c=i.current?.runtimeKey===a?i.current.identities:null;for(const d of tp(c,l))Zh({runtimeKey:a,...d});i.current={runtimeKey:a,identities:l}},[s,n,r])},np=(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,Si=(e,s,n)=>{np(e.get(s),n)&&e.set(s,n)},rp=e=>{const s=e;return Ze(s.directory)??Ze(s.project?.worktree)},op=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)},ip=(e,s,n,r=[])=>{const i=new Map,a=new Map;for(const h of s){const f=Ze(h.normalizedPath);if(!f)continue;const g=a.get(f);(!g||h.id.localeCompare(g.id)<0)&&a.set(f,h),Si(i,f,{projectId:h.id,projectRoot:f,scopeDirectory:f,kind:"project"})}if(n)for(const[h,f]of n){const g=Ze(h),S=g?a.get(g):void 0;if(!(!S||!g))for(const k of f||[]){const O=Ze(k?.path);O&&Si(i,O,{projectId:S.id,projectRoot:g,scopeDirectory:O,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,p=new Map,m=h=>{if(!h)return null;if(l.has(h))return l.get(h)??null;const f=[];let g=h,S=null;for(;g;){if(l.has(g)){S=l.get(g)??null;break}if(f.push(g),S=i.get(g)??null,S)break;g=op(g)}for(const k of f)l.set(k,S);return S},x=(h,f,g)=>{for(const S of h){const k=rp(S);if(aa(k))continue;const O=m(k);if(!O)continue;c.set(S.id,O);const j=f.get(O.projectId);if(j?j.push(S):f.set(O.projectId,[S]),!g)continue;const v=g.get(O.scopeDirectory);v?v.add(S.id):g.set(O.scopeDirectory,new Set([S.id]))}};return x(e,d,p),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:p,directoryResolutions:l.size}},ap=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(cs,{open:e,onOpenChange:s,children:t.jsx(ds,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(As,{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(Jf,{project:n,onIdentitySave:r}):null})})})});function Xa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:B("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:B("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(Jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const lp=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:i,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:p,groupDirectory:m,projectId:x,mobileVariant:h=!1,alwaysShowActions:f=h,isRenaming:g=!1,renameDraft:S="",onRenameDraftChange:k,onRenameSave:O,onRenameCancel:j,droppableRef:v,isDropTarget:y=!1,onNewSession:L,depth:A=0,hideActions:C=!1,archivedBucket:I=!1})=>{const[P,D]=o.useState(!1),[W,ee]=o.useState(""),Z=o.useRef(null),ie=g||P,z=g?S:W,U=o.useCallback(()=>{ee(e.name),D(!0)},[e.name]),T=o.useCallback(()=>{const $=z.trim();$&&$!==e.name&&c($),g&&O&&O(),D(!1),ee("")},[z,e.name,g,c,O]),R=o.useCallback(()=>{g&&j&&j(),D(!1),ee("")},[g,j]),V=o.useCallback($=>{g&&k?k($):ee($)},[g,k]);o.useEffect(()=>{if(!g)return;const $=()=>{const Ye=Z.current;Ye&&(Ye.focus(),Ye.select())},Me=requestAnimationFrame($),Te=window.setTimeout($,0);return()=>{cancelAnimationFrame(Me),window.clearTimeout(Te)}},[g]);const oe=i?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:v,className:B("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",y&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:ie?void 0:$=>{$.currentTarget.blur(),l()},role:ie?void 0:"button",tabIndex:ie?void 0:0,onKeyDown:ie?void 0:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),l())},"aria-label":i?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:B("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",I?f?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":f?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(N,{name:oe,className:B(On,y?"text-primary":"text-muted-foreground")}),ie?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onSubmit:$=>{$.preventDefault(),T()},children:[t.jsx("input",{ref:Z,value:z,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(),R();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(N,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),R()},onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(N,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("span",{className:B(Ca,y?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(it,{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(Xa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,i?t.jsx(N,{name:"arrow-right-s",className:B(On,"text-muted-foreground")}):t.jsx(N,{name:"arrow-down-s",className:B(On,"text-muted-foreground")})]})]}),!ie&&(!C||I)?t.jsx("div",{className:B("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",f?"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:[!I&&L?t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),L()},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(N,{name:"add",className:"size-4"})}):null,I?null:t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),U()},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(N,{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":I?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(N,{name:"delete-bin",className:"size-4"})})]})}):null]}),i?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map($=>t.jsx(o.Fragment,{children:u($,0,m??null,x??null,I,void 0,"project",p?.($))},$.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},cp=o.memo(lp),dp=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:i,listeners:a,setNodeRef:l,isDragging:c}=Yu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),d=o.useCallback(u=>{u.stopPropagation(),a?.onPointerDown&&a.onPointerDown(u)},[a]);return t.jsx("div",{ref:l,...i,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},up=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Vu({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},fp=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const i=er(pn(co,{activationConstraint:{distance:8}})),[a,l]=o.useState(null),[c,d]=o.useState("Session"),[u,p]=o.useState(null),[m,x]=o.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const h=f=>{l(null),p(null),x(null);const{active:g,over:S}=f;if(!S)return;const k=g.data.current,O=S.data.current;k?.type==="session"&&k.sessionId&&O?.type==="folder"&&O.folderId&&n(k.sessionId,O.folderId)};return t.jsxs(tr,{sensors:i,collisionDetection:sr,onDragStart:f=>{const g=f.active.data.current;if(g?.type==="session"&&g.sessionId){l(g.sessionId),d(g.sessionTitle??"Session");const S=f.active.rect.current.initial?.width,k=f.active.rect.current.initial?.height;p(typeof S=="number"?S:null),x(typeof k=="number"?k:null)}},onDragCancel:()=>{l(null),p(null),x(null)},onDragEnd:h,children:[r,t.jsx(Pa,{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(N,{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})]})},_n=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),i=r.length;if(i===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+i);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+i,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e},Es=({icon:e,children:s,onClick:n,className:r,mobileVariant:i=!1})=>t.jsxs("button",{type:"button",onClick:n,className:B(i?Iu:Du,r),children:[t.jsx(N,{name:e,className:B(ln(i),"text-muted-foreground")}),t.jsx("span",{className:B(cn(i),"flex-1 text-muted-foreground"),children:s})]}),ji=(e,s,n)=>{if(!s)return;const r=i=>{let a=i.session.id===s;for(const l of i.children)a=r(l)||a;return a&&n.add(i.session.id),a};for(const i of e)r(i)},ps=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(ps(n,s))return!0;return!1},hp=(e,s,n)=>{const r=new Map,i=a=>{const l=Ps(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)i(c)};return i(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},pp=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const i=new Set;let a=r.session.parentID??null;for(;a&&!i.has(a);){if(n.has(a)&&s.has(a))return!1;i.add(a),a=s.get(a)?.session?.parentID??null}return!0})},Ci=new WeakMap;let ki=1;const mp=e=>{const s=Ci.get(e);if(s!==void 0)return s;const n=ki;return ki+=1,Ci.set(e,n),n},Vr=e=>e.children.length===0?"":e.children.map(n=>{const r=mp(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Vr(n)}`}).join("|"),Za=(e,s,n,r,i,a)=>{const l=Xn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const p=d.session.directory??i,m=u.session.directory??a,x=Vo(l,p??"",d.session.id),h=Vo(l,m??"",u.session.id);return(x?n.has(x):!1)!==(h?r.has(h):!1)?!0:d.children.some((f,g)=>c(f,u.children[g]))};return c(e,s)},Vn=(e,s,n,r)=>{if(!s)return null;const i=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${i}:${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},el=(e,s)=>"",gp=gs(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),xp=e=>null,xo=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,tl=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let i=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(i="unread");for(const l of e.children)if(i=xo(i,tl(l,s,n,r)),i==="active")return i;return i},Ni=(e,s,n,r)=>{let i=null;for(const a of e)if(i=xo(i,tl(a,s,n,r)),i==="active")return i;return i},bp=50,yp=28,Dn=(e,s)=>s?e.sessions.some(n=>ps(n,s)):!1,vp=(e,s,n)=>e.sessions.some(r=>Za(r,r,s,n,e.directory,e.directory)),wp=(e,s,n)=>{const r=i=>{const a=i.session.id;return s.get(a)!==n.get(a)?!0:i.children.some(r)};return e.sessions.some(r)},Ai=(e,s,n)=>{const r=i=>s.has(i.session.id)!==n.has(i.session.id)?!0:i.children.some(r);return e.sessions.some(r)},Sp=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},jp=(e,s,n)=>{const r=e.isArchivedBucket?"archived":"active",i=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(i)};return e.sessions.some(i)},Cp=(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&&vp(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&jp(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&wp(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(Dn(e.group,e.editingId)||Dn(s.group,s.editingId))||e.editTitle!==s.editTitle&&(Dn(e.group,e.editingId)||Dn(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Vn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Vn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Ai(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Ai(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&Sp(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 kp(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:i,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:p,collapsedFolderIds:m,toggleFolderCollapse:x,renameFolder:h,deleteFolder:f,showDeletionDialog:g,setDeleteFolderConfirm:S,renderSessionNode:k,showMoreGroupSessions:O,resetGroupSessionLimit:j,mobileVariant:v,alwaysShowActions:y,activeProjectId:L,setActiveProjectIdOnly:A,setActiveMainTab:C,setSessionSwitcherOpen:I,openNewSessionDraft:P,addSessionToFolder:D,createFolderAndStartRename:W,renamingFolderId:ee,renameFolderDraft:Z,setRenameFolderDraft:ie,setRenamingFolderId:z,pinnedSessionIds:U,expandedParents:T,sessionOrderIndex:R,editingId:V,openSidebarMenuKey:oe,activeActivitySessionIds:$,unreadActivitySessionIds:Me,notifyOnSubtasks:Te,onToggleCollapsedGroup:Ye,dragHandleProps:Ue,compactBodyPadding:Ge=!1,scrollContainerRef:Le}=e,re=o.useCallback((G,te)=>{const ne=R.get(G.session.id),ce=R.get(te.session.id);if(ne!==void 0||ce!==void 0){if(ne===void 0)return 1;if(ce===void 0)return-1;if(ne!==ce)return ne-ce}return to(G.session,te.session,U,la)},[U,R]),pe=a?c.get(s):null,Ke=Kt(G=>G.foldersMap),ke=a?!1:u.has(n);o.useMemo(()=>{if(s.isMain||s.isArchivedBucket||i)return null;const G=Ze(s.directory??null),te=s.branch?.trim();return G&&te?el():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,i]);const Ce=ca(),He=o.useMemo(()=>{const G=s.folderScopes?.map(te=>Ze(te.directory))??[Ze(s.directory??null)];return[...new Set(G.filter(te=>!!te))]},[s.directory,s.folderScopes]);o.useSyncExternalStore(o.useCallback(G=>He.length>0?Ce.subscribeBootstrap(G):()=>{},[He.length,Ce]),o.useCallback(()=>He.map(G=>`${G}\0${Ce.getBootstrapState(G)??""}\0${Ce.getBootstrapFailure(G)??""}`).join(""),[He,Ce]),o.useCallback(()=>"",[]));const tt=He.some(G=>{const te=Ce.getBootstrapState(G);return te==="queued"||te==="running"}),ze=He.find(G=>Ce.getBootstrapState(G)==="failed")??null,J=ze?Ce.getBootstrapFailure(ze):void 0,q=J==="os-permission"&&oo(),[ge,X]=o.useState(!1),we=o.useCallback(()=>{ze&&Ce.requestBootstrap({directory:ze,priority:ke?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[Ce,ze,s.isMain,ke]),xe=o.useCallback(async()=>{if(!(!ze||!q||ge)){X(!0);try{(await io(ze)).success&&we()}finally{X(!1)}}},[q,ze,ge,we]),Ne=p?10:5,pt=Math.max(Ne,d??Ne),gt=a?pe?.groupMatches===!0:!1,et=a,De=o.useMemo(()=>[...et?pe?.filteredNodes??[]:s.sessions].sort(re),[re,s.sessions,pe?.filteredNodes,et]),Fe=s.folderScopeKey??Ze(s.directory??null),Ae=o.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:Fe?[{scopeKey:Fe,directory:s.directory??null}]:[],[Fe,s.directory,s.folderScopes]),at=o.useMemo(()=>Ae.flatMap(({scopeKey:G,directory:te})=>(Ke[G]??[]).map(ne=>({folder:ne,scopeKey:G,scopeDirectory:te}))),[Ae,Ke]),jt=o.useMemo(()=>{const G=new Map,te=ne=>{ne.forEach(ce=>{G.set(ce.session.id,ce),ce.children.length>0&&te(ce.children)})};return te(De),G},[De]),st=o.useMemo(()=>at.map(({folder:G,scopeKey:te,scopeDirectory:ne})=>{const ce=pp(G.sessionIds,jt).sort(re);return{folder:G,scopeKey:te,scopeDirectory:ne,nodes:ce}}),[at,jt,re]),_=o.useMemo(()=>{const G=new Map(st.map(fe=>[fe.folder.id,fe])),te=new Map;for(const{folder:fe}of st){if(!fe.parentId)continue;const ft=te.get(fe.parentId);ft?ft.push(fe.id):te.set(fe.parentId,[fe.id])}const ne=new Map,ce=fe=>{const ft=ne.get(fe);if(ft!==void 0)return ft;const Et=G.get(fe);if(!Et)return ne.set(fe,!1),!1;const wt=te.get(fe)??[];if(s.isArchivedBucket&&Et.nodes.length===0){const Dt=wt.some(ls=>ce(ls));return ne.set(fe,Dt),Dt}if(!a||Et.folder.name.toLowerCase().includes(l)||Et.nodes.length>0)return ne.set(fe,!0),!0;const ts=wt.some(Dt=>ce(Dt));return ne.set(fe,ts),ts};return st.filter(({folder:fe})=>ce(fe.id))},[st,s.isArchivedBucket,a,l]),ye=o.useMemo(()=>new Set(_.flatMap(G=>G.folder.sessionIds)),[_]),be=o.useMemo(()=>De.filter(G=>!ye.has(G.session.id)),[De,ye]),w=o.useMemo(()=>_.filter(({folder:G})=>!G.parentId),[_]),Y=o.useMemo(()=>{const G=new Map;return _.forEach(te=>{if(!te.folder.parentId)return;const ne=G.get(te.folder.parentId)??[];ne.push(te),G.set(te.folder.parentId,ne)}),G},[_]),se=o.useMemo(()=>{const G=new Map(_.map(ce=>[ce.folder.id,ce])),te=new Map,ne=(ce,fe)=>{const ft=te.get(ce);if(ft!==void 0)return ft;if(fe.has(ce))return null;fe.add(ce);const Et=G.get(ce);let wt=Et?Ni(Et.nodes,$,Me,Te):null;for(const Gt of Y.get(ce)??[])if(wt=xo(wt,ne(Gt.folder.id,fe)),wt==="active")break;return te.set(ce,wt),wt};return _.forEach(({folder:ce})=>ne(ce.id,new Set)),te},[$,_,Y,Te,Me]),de="project",Se=o.useMemo(()=>{const G=new Set;return ji(De,V,G),_.forEach(({nodes:te})=>{ji(te,V,G)}),G},[De,_,V]),Pe=o.useMemo(()=>{if(!oe)return null;const G=Vn(De,oe,de,!!s.isArchivedBucket);if(G)return G;for(const{nodes:te}of _){const ne=Vn(te,oe,de,!!s.isArchivedBucket);if(ne)return ne}return null},[oe,De,_,s.isArchivedBucket]),$e=o.useCallback(G=>{const te=new WeakMap,ne=ce=>{te.set(ce,Vr(ce));for(const fe of ce.children)ne(fe)};return G.forEach(ne),te},[]),mt=o.useMemo(()=>$e(De),[$e,De]),Ct=o.useMemo(()=>{const G=new WeakMap;return _.forEach(({nodes:te})=>{te.forEach(ne=>G.set(ne,Vr(ne)))}),G},[_]),Xe=o.useCallback(G=>mt.get(G)??Ct.get(G)??"",[mt,Ct]),ct=o.useCallback(G=>({subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:Xe(G)}),[Se,Pe,Xe]),xt=be.length,Oe=s.isArchivedBucket||a?be:be.slice(0,pt),We=xt-Oe.length,bt=!s.isArchivedBucket&&!a&&xt>Ne&&We===0,Mt=s.isArchivedBucket===!0&&!a&&Oe.length>=bp,$t=s.isArchivedBucket?"archived":"active",Nt=Mt&&Oe.some(G=>{if(G.children.length===0)return!1;const te=`project:${$t}:${G.session.id}`;return T.has(te)}),At=o.useRef(null),[It,M]=o.useState(null),[je,Be]=o.useState(0),[,dt]=o.useState(0);o.useEffect(()=>{if(!Mt)return;const G=At.current;if(!G||typeof ResizeObserver>"u")return;const te=new ResizeObserver(()=>dt(ne=>ne+1));return te.observe(G),()=>te.disconnect()},[Mt]),o.useLayoutEffect(()=>{if(!Mt){It!==null&&M(null),je!==0&&Be(0);return}const G=At.current;if(!G)return;let te=It;const ne=Le?.current??null;if(ne&&ne.contains(G)){if(te=ne,te!==It){M(te);return}}else if(!te||!te.contains(G)){let fe=G.parentElement;for(;fe;){const ft=window.getComputedStyle(fe);if(ft.overflowY==="auto"||ft.overflowY==="scroll"){te=fe;break}fe=fe.parentElement}if(te!==It){M(te);return}}if(!te)return;const ce=G.getBoundingClientRect().top-te.getBoundingClientRect().top+te.scrollTop;Be(fe=>Math.abs(fe-ce)<1?fe:ce)});const F=Mt&&It!==null,ae=Wu({count:Oe.length,enabled:F,getScrollElement:()=>It,initialOffset:()=>It?.scrollTop??0,estimateSize:()=>yp,overscan:Nt?20:8,scrollMargin:je,getItemKey:G=>Oe[G]?.session.id??G}),me=o.useCallback(G=>{const te=[],ne=ce=>{ce.forEach(fe=>{te.push(fe.session),fe.children.length>0&&ne(fe.children)})};return ne(G),te},[]),nt=o.useMemo(()=>me(De),[me,De]),ve=o.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const G=new Map,te=new Map;for(const{folder:ce}of _){if(!ce.parentId)continue;const fe=te.get(ce.parentId)??[];fe.push(ce.id),te.set(ce.parentId,fe)}const ne=(ce,fe)=>{if(fe.has(ce))return[];fe.add(ce);const ft=_.find(({folder:Gt})=>Gt.id===ce),Et=ft?me(ft.nodes):[],wt=te.get(ce)??[];for(const Gt of wt)Et.push(...ne(Gt,fe));return Et};for(const{folder:ce}of _)G.set(ce.id,ne(ce.id,new Set));return G},[_,me,s.isArchivedBucket]);if(a&&!gt&&w.length===0&&be.length===0)return null;const Je=!s.isMain&&!!s.branch,yt=s.branch&&Pu(s.branch,s.label)?{label:s.branch}:null,Ft=ke?Ni(De,$,Me,Te):null,Lt=Ft?t.jsx(Xa,{state:Ft,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,kt=(G,te)=>{const{folder:ne,scopeKey:ce,scopeDirectory:fe,nodes:ft}=G,Et=ve.get(ne.id)??[],wt=a?!1:m.has(ne.id);return t.jsx(up,{folderId:ne.id,children:(Gt,ts)=>t.jsx(cp,{folder:ne,displayName:te,sessions:ft,isCollapsed:wt,collapsedActivityState:wt?se.get(ne.id)??null:null,onToggle:()=>x(ne.id),onRename:Dt=>{h(ce,ne.id,Dt)},onDelete:()=>{if(s.isArchivedBucket){Ts.requestDelete({sessions:Et,mode:"session"});return}if(!g){f(ce,ne.id);return}const Dt=_.filter(({folder:us})=>us.parentId===ne.id).length,ls=ft.length;S({scopeKey:ce,folderId:ne.id,folderName:ne.name,subFolderCount:Dt,sessionCount:ls})},renderSessionNode:k,getRenderExtras:Xe?Dt=>({subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:Xe(Dt),childRenderExtrasFor:ct}):void 0,groupDirectory:fe??s.directory,projectId:r,mobileVariant:v,alwaysShowActions:y,isRenaming:ee===ne.id,renameDraft:ee===ne.id?Z:void 0,onRenameDraftChange:Dt=>ie(Dt),onRenameSave:()=>{const Dt=Z.trim();Dt&&h(ce,ne.id,Dt),z(null),ie("")},onRenameCancel:()=>{z(null),ie("")},droppableRef:Gt,isDropTarget:ts,depth:0,onNewSession:()=>{r&&r!==L&&A(r),C("chat"),v&&I(!1),P({selectedProjectId:r,directoryOverride:fe??s.directory,targetFolderId:ne.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},ne.id)},Ut=()=>{const G=new Map;for(const ce of _){const fe=ce.folder.parentId;if(!fe)continue;const ft=G.get(fe);ft?ft.push(ce):G.set(fe,[ce])}const te=[],ne=(ce,fe)=>{const ft=fe?`${fe} / ${ce.folder.name}`:ce.folder.name;te.push(kt(ce,ft)),!(!a&&m.has(ce.folder.id))&&(G.get(ce.folder.id)??[]).forEach(wt=>ne(wt,ft))};return w.forEach(ce=>ne(ce,"")),te},Rt=y?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",vt=ze?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[J==="os-permission"?"Folder access is required.":"Could not refresh sessions.",q?t.jsx(Qe,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:ge,onClick:()=>{xe()},children:"Grant access"}):null,t.jsx(Qe,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:we,children:"Try again"})]}):null,Wt=t.jsxs(fp,{scopeKey:Ae[0]?.scopeKey??Fe,hasFolders:_.length>0,onSessionDroppedOnFolder:(G,te)=>{const ne=_.find(({folder:fe})=>fe.id===te);if(!ne)return;const ce=Kt.getState();for(const{scopeKey:fe}of Ae)fe!==ne.scopeKey&&ce.getSessionFolderId(fe,G)&&ce.removeSessionFromFolder(fe,G);D(ne.scopeKey,te,G)},children:[Ut(),Mt?t.jsx("div",{ref:At,children:F?t.jsx("div",{style:{height:ae.getTotalSize(),position:"relative"},children:ae.getVirtualItems().map(G=>{const te=Oe[G.index];return te?t.jsx("div",{"data-index":G.index,ref:ae.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${G.start-je}px)`},children:k(te,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:Xe(te),childRenderExtrasFor:ct})},te.session.id):null})}):Oe.map(G=>t.jsx(o.Fragment,{children:k(G,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:Xe(G),childRenderExtrasFor:ct})},G.session.id))}):Oe.map(G=>t.jsx(o.Fragment,{children:k(G,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:Xe(G),childRenderExtrasFor:ct})},G.session.id)),xt===0&&_.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."}):tt?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(N,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):vt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:vt}):t.jsx(Es,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,xt>0&&vt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:vt}):null,We>0?t.jsx(Es,{icon:"arrow-down-s",onClick:()=>O(n,Oe.length),children:We===1?"Show 1 more session":`Show ${We} more sessions`}):null,bt?t.jsx(Es,{icon:"arrow-up-s",onClick:()=>j(n),children:"Show fewer sessions"}):null]});return i?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:Wt})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:B("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>Ye(n),role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),Ye(n))},"aria-label":ke?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!ke,children:[t.jsx("div",{ref:Ue?.setActivatorNodeRef,className:B("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",Rt),...Ue?.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(N,{name:"archive",className:B("size-4 shrink-0 text-muted-foreground",y?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:B("text-muted-foreground size-4 items-center justify-center",y?"inline-flex":"hidden group-hover/gh:inline-flex"),children:ke?t.jsx(N,{name:"arrow-right-s",className:"size-4"}):t.jsx(N,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:_n(s.label,l)}),Lt]}):!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(N,{name:"git-branch",className:B("size-4 shrink-0","text-muted-foreground",y?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:B("text-muted-foreground size-4 items-center justify-center",y?"inline-flex":"hidden group-hover/gh:inline-flex"),children:ke?t.jsx(N,{name:"arrow-right-s",className:"size-4"}):t.jsx(N,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:_n(s.label,l)}),Lt,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:_n(s.label,l)}),Lt]})}),Je&&yt?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[s.isArchivedBucket?t.jsx(N,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(N,{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:yt.label})]}):null]})}),s.isArchivedBucket&&nt.length>0?t.jsx("div",{className:B("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",y?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),Ts.requestDelete({sessions:nt,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(N,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,s.directory?t.jsx("div",{className:B("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",y?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),r&&r!==L&&A(r),C("chat"),v&&I(!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(N,{name:"add",className:"h-4 w-4"})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]}),ke?null:t.jsx("div",{className:"oc-group-body",children:Wt})]})}const Np=o.memo(kp,Cp);function Ap(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:i,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:p,setIsSessionSearchOpen:m,sessionSearchInputRef:x,sessionSearchQuery:h,setSessionSearchQuery:f,hasSessionSearchQuery:g,searchMatchCount:S,selectionModeEnabled:k,onToggleSelectionMode:O,mobileVariant:j=!1}=e;if(s)return null;const v=B(u,"text-muted-foreground hover:text-foreground",!j&&"hover:bg-transparent");return t.jsx("div",{className:B("select-none flex-shrink-0",j?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:B("flex flex-col",j?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:B("flex items-center justify-between",j?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:B("flex min-w-0 items-center",j?"gap-0.5 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":j?"true":void 0,children:[i?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:v,"aria-label":"Settings",children:t.jsx(N,{name:"settings-3",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!j&&a?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:v,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(N,{name:"server",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:v,"aria-label":"Update",children:t.jsx(N,{name:"download",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,j?null:t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:v,"aria-label":"Add project",children:t.jsx(N,{name:"folder-add",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),j?null:t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:v,"aria-label":"Archive",children:t.jsx(N,{name:"archive",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:B("flex shrink-0 items-center",j?"gap-0.5":"gap-1.5"),children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>m(y=>!y),className:v,"aria-label":"Search sessions","aria-expanded":p,children:t.jsx(N,{name:"search",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:O,className:B(v,k&&"bg-interactive-hover text-primary"),"aria-label":k?"Exit selection":"Select sessions","aria-pressed":k,children:t.jsx(N,{name:"checkbox-multiple",className:d})})}),t.jsx(it,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:k?"Exit selection":"Select sessions"})})]})]})]}),p?t.jsxs("div",{className:B(j?"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:S===1?`${S} match`:`${S} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(N,{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:x,value:h,onChange:y=>f(y.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:y=>{y.key==="Escape"&&(y.stopPropagation(),g?f(""):m(!1))}}),h.length>0?t.jsx("button",{type:"button",onClick:()=>f(""),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(N,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function Ip(e){const s=ue(i=>i.toggleSidebar),n=ue(i=>i.shortcutOverrides),r=ao(on("toggle_sidebar",n));return t.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${ri})`}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${ri})))`}}),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:B("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(N,{name:"chat-new",className:B(On,"text-current")}),t.jsx("span",{className:Ca,children:"New session"})]}),e.showSidebarToggle?t.jsxs(rt,{children:[t.jsx(ot,{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(N,{name:"layout-left",className:"size-4"})})}),t.jsx(it,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Dp=500,zn=(e,s)=>B("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),Pp=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:i,worktreeError:a,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:p,mobileVariant:m=!1})=>{const{listeners:x,setNodeRef:h,transform:f,transition:g,isDragging:S}=fo({id:e.id,disabled:!c}),[k,O]=o.useState(!1),j=o.useRef(null),v=o.useCallback(()=>{j.current!==null&&(window.clearTimeout(j.current),j.current=null)},[]);o.useEffect(()=>()=>v(),[v]);const y=o.useCallback(()=>{v(),j.current=window.setTimeout(()=>{j.current=null,O(!0)},Dp)},[v]);return t.jsx("div",{ref:h,style:{transform:ho.Translate.toString(f),transition:g},className:B(S&&"opacity-60"),children:t.jsxs(Xf,{open:k,onOpenChange:O,children:[t.jsxs(Zf,{render:t.jsx("button",{type:"button",onClick:()=>{k||d()},onTouchStart:y,onTouchMove:v,onTouchEnd:v,onTouchCancel:v,style:{touchAction:"manipulation"},className:zn(m,n),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:B("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${s}`:void 0,...c?x:{},children:t.jsx(N,{name:"folder",className:B(ln(m),"text-muted-foreground")})}),t.jsx("span",{className:cn(m),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(Jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,a?t.jsx("span",{title:a,"aria-label":"Worktree discovery failed",children:t.jsx(N,{name:"error-warning",className:"size-4 text-[var(--status-warning-foreground)]"})}):null,i?t.jsx(N,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(eh,{className:"min-w-[160px]",children:[t.jsxs(hi,{onClick:()=>u(e.id),children:[t.jsx(N,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(th,{}),t.jsxs(hi,{onClick:()=>p(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(N,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},Ep=({projects:e,selectedProjectId:s,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:i=new Map,onSelectProject:a,onSelectWorktree:l,onOpenDirectoryDialog:c,onOpenProjectEditDialog:d,onRemoveProject:u,hasActiveSessionByProject:p,homeDirectory:m,className:x,mobileVariant:h=!1})=>{const f=s===null,g=zt(j=>j.reorderProjects),S=e.length>1,k=er(pn(Qu,{activationConstraint:{distance:8}}),pn(qu,{activationConstraint:{delay:200,tolerance:6}})),O=o.useCallback(j=>{const{active:v,over:y}=j;if(!y||v.id===y.id)return;const L=zt.getState().projects,A=L.findIndex(I=>I.id===v.id),C=L.findIndex(I=>I.id===y.id);A<0||C<0||g(A,C)},[g]);return t.jsxs("div",{className:B("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",x),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:zn(h,f),"aria-pressed":f,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(N,{name:"folder",className:ln(h)}),t.jsx("span",{className:cn(h),children:"All Folders"})]})}),t.jsx(tr,{sensors:k,collisionDetection:sr,onDragEnd:O,children:t.jsx(uo,{items:e.map(j=>j.id),strategy:Ea,children:e.map(j=>{const v=s===j.id,y=v&&!n,L=r.get(j.normalizedPath)??[],A=Zn(j.label?.trim()||Ms(j.normalizedPath,m)||j.normalizedPath);return t.jsxs(o.Fragment,{children:[t.jsx(Pp,{project:j,label:A,isSelected:y,hasActive:p?.(j.id),hasWorktrees:L.length>0,worktreeError:i.get(j.normalizedPath),isExpanded:v,canDrag:S,onSelect:()=>a(j.id),onOpenProjectEditDialog:d,onRemoveProject:u,mobileVariant:h}),v?L.map(C=>{const I=n===C.path;return t.jsxs("button",{type:"button",onClick:()=>l?.(j.id,C.path),className:B(zn(h,I)),"aria-pressed":I,title:C.path,children:[t.jsx(N,{name:"git-branch",className:B(ln(h),"text-muted-foreground")}),t.jsx("span",{className:cn(h),children:C.branch||(C.detached?"Detached HEAD":C.name)})]},C.path)}):null]},j.id)})})}),t.jsxs("button",{type:"button",onClick:c,className:zn(h,!1),children:[t.jsx(N,{name:"add",className:ln(h)}),t.jsx("span",{className:cn(h),children:"Add folder"})]})]})},hr="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 Tp({onOpenSettings:e,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:i=!0,showUpdateButton:a=!0}){return!i&&!a?null:t.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[i?t.jsxs(t.Fragment,{children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:hr,"aria-label":"Settings",children:t.jsx(N,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(it,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:hr,"aria-label":"Shortcuts",children:t.jsx(N,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(it,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:hr,"aria-label":"About PiChamber",children:t.jsx(N,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(it,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Qe,{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 Rp=(e,s)=>Zn(e.label?.trim()||Ms(e.normalizedPath,s)||e.normalizedPath);function Mp(e){as("ui.sidebar_projects_list.render");const s=o.useRef(new Map),n=o.useRef(e.getOrderedGroups);n.current!==e.getOrderedGroups&&(n.current=e.getOrderedGroups,s.current.clear());const r=(m,x)=>{const h=s.current,f=h.get(m);if(f&&f.groups===x)return f.ordered;const g=e.getOrderedGroups(m,x);if(h.set(m,{groups:x,ordered:g}),h.size>256){const S=h.keys().next().value;S!==void 0&&h.delete(S)}return g},i=o.useRef(null),a=o.useMemo(()=>{if(!e.isAllFoldersView)return[];const m=[],x=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const h of x){const f=Rp(h.project,e.homeDirectory);for(const g of h.groups)if(!g.isArchivedBucket)for(const S of g.sessions){const k=!!e.pinnedSessionIds?.has(S.session.id),O=S.session.time?.updated||S.session.time?.created||0;m.push({node:S,project:h.project,projectLabel:f,isPinned:k,timestamp:O,globalSession:h===e.allFoldersOnlySection})}}return m.sort((h,f)=>h.isPinned!==f.isPinned?h.isPinned?-1:1:f.timestamp-h.timestamp),m},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=o.useState(30);o.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const d=a.slice(0,l),u=a.length-d.length;if(e.sharedSessionsOnly)return t.jsx(As,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:B("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]})});const p=e.isAllFoldersView&&!!e.allFoldersOnlySection;return e.projectSections.length===0&&!p?t.jsx(As,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:B("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&&!p?t.jsx(As,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:B("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsx("div",{className:"space-y-1 px-3",children:e.searchEmptyState})}):t.jsx("div",{className:"relative flex min-h-0 flex-1",children:t.jsx(As,{ref:i,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:B("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-20"),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 m=e.sectionsForRender.find(g=>g.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!m)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const x=m.groups.find(g=>g.isMain&&g.sessions.length>0)??m.groups.find(g=>g.sessions.length>0)??m.groups.find(g=>g.isMain)??m.groups[0];if(!x)return t.jsx(Es,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:m.project.id,directoryOverride:m.project.normalizedPath}),children:"New session"});const h=m.groups.find(g=>g.isArchivedBucket);return[x,...h&&h.id!==x.id?[h]:[]].map(g=>{const S=`${m.project.id}:${g.id}`,k=g.id===x.id;return t.jsx(o.Fragment,{children:e.renderGroupSessions(g,S,m.project.id,k,null,!0,i)},S)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[d.map(({node:m,project:x,projectLabel:h,globalSession:f})=>{const g=m.session.directory??x.normalizedPath;return t.jsx(o.Fragment,{children:e.renderSessionNode(m,0,g,x.id,!1,{projectLabel:h,showFolderLabel:!0,globalSession:f},"project")},m.session.id)}),u>0?t.jsx(Es,{icon:"arrow-down-s",onClick:()=>c(m=>m+30),children:u===1?"Show 1 more session":`Show ${u} more sessions`}):null,l>30&&a.length>30?t.jsx(Es,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(m=>{const x=m.project.id,h=r(x,m.groups),f=h.find(S=>S.isMain)??null,g=f?h.filter(S=>S.id!==f.id):h;return t.jsxs("div",{children:[f?e.renderGroupSessions(f,`${x}:${f.id}`,x,!0,null,void 0,i):null,g.map(S=>{const k=`${x}:${S.id}`,O=h.length===1;return t.jsx(o.Fragment,{children:e.renderGroupSessions(S,k,x,O,null,void 0,i)},S.id)})]},x)})})]})})})}const Fp=o.memo(Mp);function Op(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(),i=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${i}, ${a}:${l}`}function Lp(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 Bp(e){const s=e.info.role==="user"?"User":"Assistant",n=Op(e.info.time?.created),r=Lp(e),i=n&&r?`${n} (${r})`:n||r;return i?`**${s}**
|
|
13
|
-
|
|
14
|
-
*${i}*`:`**${s}**`}function _p(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function sl(e){const s=Bp(e),n=_p(e.parts).trim();return n?`${s}
|
|
15
|
-
|
|
16
|
-
${n}`:""}function nl(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",i=`${n} Sub-agent: ${e.title}${r}
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
`,a=e.records.map(sl).filter(Boolean).join(`
|
|
21
|
-
|
|
22
|
-
---
|
|
23
|
-
|
|
24
|
-
`),l=[i+a];for(const c of e.children)l.push(nl(c,s+1));return l.join(`
|
|
25
|
-
|
|
26
|
-
---
|
|
27
|
-
|
|
28
|
-
`)}function rl(e,s,n){const r=s?.trim()||"Session",i=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
29
|
-
|
|
30
|
-
*Exported on ${i}*
|
|
31
|
-
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
`,l=e.map(sl).filter(Boolean).join(`
|
|
35
|
-
|
|
36
|
-
---
|
|
37
|
-
|
|
38
|
-
`);let c=a+l;if(n&&n.length>0){const d=n.map(u=>nl(u,1)).join(`
|
|
39
|
-
|
|
40
|
-
---
|
|
41
|
-
|
|
42
|
-
`);c+=`
|
|
43
|
-
|
|
44
|
-
---
|
|
45
|
-
|
|
46
|
-
`+d}return c}function ol(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=s,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}async function il(e,s){const n=await hu(s,e);return n||null}async function zp(e){const s=ro()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await pu(e)?!0:ba(e)}function $p(){return mu()}function al(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",i=new Date().toISOString().split("T")[0];return`${r}-${i}.md`}const Up=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},Gp=gs()(lo(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:Up})),Kp=(e,s)=>{if(!s)return Array.from(e);const n=[],r=new Set;for(const i of e){r.has(i)||(r.add(i),n.push(i));const a=s.get(i);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},Ht=gs()((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,i)=>{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 p=i&&i.length>0?[n,...i]:[n];if(l.has(n)){for(const x of p)l.delete(x);d===n&&(d=null)}else{for(const x of p)l.add(x);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,i,a,l)=>{const c=s();if(i.length===0)return;const d=n&&i.includes(n)?n:i[0],u=i.indexOf(d),p=i.indexOf(r);if(u<0||p<0)return;const[m,x]=u<=p?[u,p]:[p,u],h=i.slice(m,x+1),f=Kp(h,l),S=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const k of f)S.add(k);e({selectedIds:S,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 i=new Set(r.selectedIds);for(const a of n)i.delete(a);i.size!==r.selectedIds.size&&(i.size===0?e({selectedIds:i,scopeKey:null,anchorId:null}):e({selectedIds:i}))}}));let qr=!1;const Qr=new Set;let Ii=!1;function Hp(){for(const e of Qr)e()}function bo(e){qr!==e&&(qr=e,Hp())}function Wp(e){e.key==="Shift"&&bo(!0)}function Yp(e){e.key==="Shift"&&bo(!1)}function Vp(){bo(!1)}function qp(){Ii||typeof window>"u"||(Ii=!0,window.addEventListener("keydown",Wp),window.addEventListener("keyup",Yp),window.addEventListener("blur",Vp))}function Qp(e){return qp(),Qr.add(e),()=>{Qr.delete(e)}}function Jp(){return qr}function Xp(){return!1}function Zp(){return qe.useSyncExternalStore(Qp,Jp,Xp)}const pr=new WeakMap,em=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;pr.get(n)?.();const r=s.getBoundingClientRect().top;let i=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,pr.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,as("ui.sidebar.selection_scroll_anchor_adjustment")),i-=1,i<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),pr.set(n,c),l=window.requestAnimationFrame(d)},tm=o.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:i,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Zp(),p=u?n:s,m=x=>{if(u||x.shiftKey){d(x);return}c(x)};return t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",className:B("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":p,onPointerDown:a,onMouseDown:l,onClick:m,onKeyDown:x=>x.stopPropagation(),children:t.jsx(N,{name:u?"delete-bin":"archive",className:i})})}),t.jsx(it,{side:"left",sideOffset:8,children:p})]})});function sm(e){as("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:i,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:p,editingId:m,setEditingId:x,editTitle:h,setEditTitle:f,handleSaveEdit:g,handleCancelEdit:S,toggleParent:k,handleSessionSelect:O,handleSessionDoubleClick:j,togglePinnedSession:v,handleShareSession:y,copiedSessionId:L,handleCopyShareUrl:A,handleCopySessionId:C,handleUnshareSession:I,openSidebarMenuKey:P,setOpenSidebarMenuKey:D,renamingFolderId:W,getFoldersForScope:ee,getSessionFolderId:Z,removeSessionFromFolder:ie,addSessionToFolder:z,createFolderAndStartRename:U,handleDeleteSession:T,handleRestoreSession:R,mobileVariant:V,alwaysShowActions:oe,allowQuickArchiveAction:$,renderSessionNode:Me,secondaryMeta:Te,renderContext:Ye="project",subtreeContainsEditing:Ue,menuOpenSessionId:Ge,childRenderExtrasFor:Le}=e,re=o.useMemo(()=>ya(),[]),pe=!a&&$,Ke=o.useRef(!1),ke=o.useRef(m);ke.current=m;const Ce=o.useRef(null),He=o.useRef(g);He.current=g;const[tt,ze]=o.useState(h),J=o.useRef(tt);J.current=tt;const q=o.useRef(null),ge=o.useRef(null),X=s.session,we=X,xe=Ze(X.directory??null)??Ze(r??null),Ne=_e(K=>K.currentSessionId===X.id),pt=da(xe),gt=ud(xe),et=zt(o.useCallback(K=>{if(Te?.projectLabel||!i)return null;const Ve=K.projects.find(ut=>ut.id===i);return Ve?Ve.label?.trim()||Ms(Ze(Ve.path)??Ve.path,null)||Ve.path:null},[i,Te?.projectLabel])),De=Te?.projectLabel??(et?Zn(et):null),Fe=Te?.branchLabel??s.worktree?.branch??(pt&&pt!=="HEAD"?pt:null),Ae=Fe,at=gt===!0||!!(Fe||s.worktree),jt=s.children.length,st=we.agent;o.useMemo(()=>{const K=s.worktree?.branch?.trim()||Fe?.trim(),Ve=Ze(s.worktree?.path??xe);return K&&Ve?el():null},[s.worktree,Fe,xe]);const _=xp();o.useMemo(()=>null,[_]);const ye=i??xe??null,be=fa(),w=so(),Y=Ht(K=>K.enabled),se=Ht(o.useCallback(K=>K.selectedIds.has(X.id),[X.id])),de=Ht(K=>K.toggleSelected),Se=Ht(K=>K.setRange),Pe=o.useCallback(K=>{const Ve=[],ut=Pt=>{Pt.children.forEach(Bt=>{Ve.push(Bt.session.id),ut(Bt)})};return ut(K),Ve},[]);o.useCallback(K=>{const Ve=[],ut=Pt=>{Pt.children.forEach(Bt=>{Ve.push(Bt.session),ut(Bt)})};return ut(K),Ve},[]);const[$e,mt]=o.useState(!1),[Ct,Xe]=o.useState(!0),ct=`${Ye}:${a?"archived":"active"}:${X.id}`,xt=fd(o.useCallback(K=>!!K.sessionMemoryState.get(hd(X.id))?.isZombie,[X.id])),We=ua(X.id)?.type??"idle",bt=We==="busy"||We==="retry",Mt=pd(X.id,bt),$t=md(X.id),Nt=we.title||"Untitled Session",At=s.children.length>0,It=gd(l,xe,X.id),M=ct,je=d?!0:c.has(M);o.useMemo(()=>hp(s,je,xe),[je,s,xe]);const Be=yd(),dt=!!we.parentID,ae=xd(X.id)>0&&(!dt||p),me=we.time?.updated||we.time?.created||Date.now(),nt=Ru(me),[ve,Je]=o.useState(!1),yt=o.useMemo(()=>Qa(s.forkColorId),[s.forkColorId]),Ft=o.useMemo(()=>zh(s.forkColorId,{active:Ne||se}),[s.forkColorId,Ne,se]),Lt=Te?.globalSession&&!Ne&&!se?"var(--surface-elevated)":null,kt=Ft??Lt,Ut=o.useMemo(()=>Pe(s).length,[Pe,s]),Rt=o.useCallback(async K=>{const Ve=[];let ut=0;for(const Pt of K)try{if(!xe)throw new Error("Session directory is required for export");await w.loadCompleteHistory?.(Pt.session.id,xe);const Bt=Tr(be.getState(),Pt.session.id).list,os=Pt.session.title||"Untitled Sub-agent",Bs=Pt.session.agent,Yt=await Rt(Pt.children);ut+=Yt.skipped,Ve.push({title:os,agent:Bs,records:Bt,children:Yt.children})}catch{ut+=Pe(Pt).length+1}return{children:Ve,skipped:ut}},[Pe,be,xe,w]),vt=o.useCallback(K=>{K<=0||le.warning(K===1?`Exported session, but skipped ${K} sub-agent task that could not be loaded.`:`Exported session, but skipped ${K} sub-agent tasks that could not be loaded.`)},[]),Wt=o.useCallback(async K=>{if(!xe){le.error("Nothing to export");return}try{await w.loadCompleteHistory?.(X.id,xe)}catch{le.error("Failed to load the complete session history");return}const Ve=Tr(be.getState(),X.id).list;if(Ve.length===0){le.error("Nothing to export");return}let ut,Pt=0;if(K&&s.children.length>0){const Yt=await Rt(s.children);ut=Yt.children,Pt=Yt.skipped}const Bt=rl(Ve,we.title??null,ut),os=al(we.title??null),Bs=await il(Bt,os);if(Bs){le.success("Session exported",{action:{label:$p(),onClick:()=>{zp(Bs).then(Yt=>{Yt||le.error("Failed to reveal path")})}}}),vt(Pt);return}ol(Bt,os),le.success("Session exported"),vt(Pt)},[Rt,be,s.children,we.title,X.id,xe,vt,w]),G=o.useCallback(async()=>{if(s.children.length>0){Xe(!0),mt(!0);return}await Wt(!1)},[Wt,s.children.length]),te=o.useCallback(()=>{xe&&an("desktop_open_session_mini_chat_window",{sessionId:X.id,directory:xe,apiBaseUrl:Fr(),clientToken:Mr()}).catch(K=>{console.warn("[session-sidebar] failed to open mini chat window",K)})},[X.id,xe]);o.useEffect(()=>{if(m!==X.id)return;const K=Ve=>{const Pt=Ve.target?.closest?.(`[data-session-rename-form="${CSS.escape(X.id)}"]`);ge.current&&!Pt&&He.current(J.current)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[m,X.id]),o.useLayoutEffect(()=>{if(m!==X.id){q.current===X.id&&(q.current=null);return}q.current!==X.id&&(q.current=X.id,ze(h))},[m,h,X.id]);const ne=$t.length,ce=!bt&&ae&&!Ne,fe=bt&&Mt,ft=It,Et=t.jsx(N,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),wt=ft?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:Et}):null,Gt=At?t.jsx("button",{type:"button",onClick:K=>{K.stopPropagation(),k(M)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),k(M))},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":je?"Collapse subsessions":"Expand subsessions",children:je?t.jsx(N,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(N,{name:"arrow-right-s",className:"h-3 w-3"})}):null,ts=xt?t.jsx(N,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Dt=K=>{if(!K&&Ce.current){const{id:Ve,title:ut}=Ce.current;Ce.current=null,x(Ve),f(ut)}},ls=K=>{Je(K)},us=K=>{K.preventDefault(),K.stopPropagation()},xs=K=>{K.preventDefault(),K.stopPropagation()},qs=K=>{K.preventDefault(),K.stopPropagation(),D(null),T(X,{archivedBucket:a})},Qs=K=>{K.preventDefault(),K.stopPropagation(),D(null),T(X,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},E=K=>{if(Ke.current){Ke.current=!1;return}if(Y){if(K?.preventDefault(),K?.stopPropagation(),K?.shiftKey){const ut=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(os=>os.getAttribute("data-session-row")).filter(os=>typeof os=="string"&&os.length>0),Pt=Ht.getState().anchorId,Bt=new Map;Bt.set(X.id,Pe(s)),Se(Pt,X.id,ut,ye,Bt);return}de(X.id,ye,Pe(s));return}K?.currentTarget&&em(K.currentTarget),O(X.id,xe)},he=K=>{K.defaultPrevented||K.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||E(K)},Ie=K=>{(K.button===2||K.button===0&&K.ctrlKey&&!Y)&&(Ke.current=!0)},lt=({Item:K,Separator:Ve,Sub:ut,SubTrigger:Pt,SubContent:Bt})=>t.jsxs(t.Fragment,{children:[t.jsxs(K,{onClick:()=>{Ce.current={id:X.id,title:Nt}},className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(K,{onClick:()=>C(X.id),className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(K,{onClick:()=>xe&&v({directory:xe,sessionId:X.id}),className:"[&>svg]:mr-1",children:[It?t.jsx(N,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(N,{name:"pushpin",className:"mr-1 h-4 w-4"}),It?"Unpin session":"Pin session"]}),t.jsxs(K,{onClick:()=>{G()},className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),re?t.jsxs(K,{disabled:!xe,onClick:te,className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(Ve,{}),a?null:t.jsxs(K,{className:"[&>svg]:mr-1",onClick:()=>T(X,{archivedBucket:a}),children:[t.jsx(N,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs(K,{className:"[&>svg]:mr-1",onClick:()=>R(X),children:[t.jsx(N,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(K,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>T(X,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(N,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]}),ss=t.jsx(_r,{children:t.jsx(zr,{className:"app-region-no-drag z-50",children:t.jsx($r,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(W||ke.current),style:{color:"var(--surface-elevated-foreground)"},className:B(Dr,"min-w-[180px]"),children:lt({Item:({className:K,...Ve})=>t.jsx(Aa,{className:B(ea,K),...Ve}),Separator:({className:K,...Ve})=>t.jsx(Ia,{className:B(ta,K),...Ve}),Sub:Gu,SubTrigger:({className:K,children:Ve,...ut})=>t.jsxs(Ku,{className:B(bd,K),...ut,children:[Ve,t.jsx(N,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:K,children:Ve,...ut})=>t.jsx(_r,{children:t.jsx(zr,{className:"app-region-no-drag z-50",children:t.jsx($r,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:B(Dr,K),...ut,children:Ve})})})})})})});return t.jsxs(o.Fragment,{children:[t.jsx(dp,{sessionId:X.id,sessionDirectory:xe??null,sessionTitle:Nt,children:t.jsxs(ka,{open:ve,onOpenChange:ls,onOpenChangeComplete:Dt,children:[t.jsxs(Na,{render:t.jsx("div",{"data-session-row":X.id,"data-session-scope":ye??"","data-session-archived":a?"1":"0","data-fork-color":yt?s.forkColorId:void 0,"data-global-session":Te?.globalSession?"1":void 0,onClick:he,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...kt?{backgroundColor:kt}:void 0},className:B("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!kt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":kt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!kt&&Ne&&!se&&"bg-interactive-selection",!kt&&se&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[Gt,wt,m===X.id?t.jsxs("form",{ref:ge,"data-session-rename-form":X.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onSubmit:K=>{K.preventDefault(),g(tt)},children:[t.jsx("input",{value:tt,onChange:K=>ze(K.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:K=>{K.stopPropagation(),K.key==="Escape"&&S()}}),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(N,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:S,"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(N,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:Ie,onClick:K=>E(K),onDoubleClick:K=>{K.stopPropagation(),j(X.id,Nt)},className:"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",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:B("block min-w-0 flex-1 truncate font-normal typography-ui-label",ae?"text-foreground":"text-foreground/90"),children:_n(Nt,u)})}),Te?.showFolderLabel&&De||Ae||at||_||jt>0||st&&st!=="default"||fe||ne>0||Be>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:[Te?.showFolderLabel&&De?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:De}):null,Ae?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(N,{name:"git-branch",className:B("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Ae})]}):at?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(N,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,jt>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(N,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:jt})]}):null,st&&st!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:st}):null,fe?t.jsx(Eu,{sessionId:X.id,running:bt,className:"text-muted-foreground/70"}):null,ne>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[t.jsx(N,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:ne})]}):null,null]}):null]})]}),It?t.jsx(N,{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:B("flex items-center justify-end",pe&&(oe||ve)?"opacity-0":pe?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:bt?t.jsx(Jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):ce?t.jsx(Tu,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:nt})}),pe?t.jsx("div",{className:B("absolute inset-0 flex items-center justify-end",oe||ve?"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(tm,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:us,onMouseDown:xs,onArchive:qs,onDelete:Qs})}):null]}),ts&&!V?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:ts}):null]}),ss]})}),At&&je?s.children.map(K=>{const Ve=Le?Le(K):{subtreeContainsEditing:Ue,menuOpenSessionId:Ge,nodeStructureKey:""};return t.jsx(o.Fragment,{children:Me(K,n+1,xe??r,i,a,Te?.globalSession?{globalSession:!0}:void 0,Ye,Ve)},K.session.id)}):null,t.jsx(cs,{open:$e,onOpenChange:mt,children:t.jsxs(ds,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(ms,{children:"Export Markdown"}),t.jsx(Os,{children:Ut===1?`This session has ${Ut} sub-agent task. Include it in the export?`:`This session has ${Ut} 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:Ct,onChange:K=>Xe(K.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Ls,{children:[t.jsx(Qe,{type:"button",onClick:()=>mt(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Qe,{type:"button",onClick:()=>{mt(!1),Wt(Ct)},size:"sm",children:"Export"})]})]})})]},X.id)}const Di=e=>Ze(e.session.directory??null),nm=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),rm=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},Pn=e=>e.menuOpenSessionId??rm(e),En=(e,s,n)=>s?n.has(e.node.session.id)?!0:ps(e.node,s):!1,Jr=(e,s,n,r,i)=>{if(e.session.id!==s.session.id)return!0;const a=i(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(Jr(e.children[l],s.children[l],n,r,i))return!0;return!1},om=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Jr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${e.renderContext??"project"}:${n}:${i.session.id}`)||Jr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${s.renderContext??"project"}:${r}:${i.session.id}`)},im=(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.allowQuickArchiveAction!==s.allowQuickArchiveAction||e.hasSessionSearchQuery!==s.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||e.notifyOnSubtasks!==s.notifyOnSubtasks||e.nodeStructureKey!==s.nodeStructureKey||Di(e.node)!==Di(s.node)||!nm(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Za(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&om(e,s)||e.editingId!==s.editingId&&(En(e,e.editingId,e.subtreeContainsEditing)||En(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(En(e,e.editingId,e.subtreeContainsEditing)||En(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(ps(e.node,e.copiedSessionId)||ps(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Pn(e),r=Pn(s);if(ps(e.node,n)||ps(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=Pn(e),r=Pn(s);if(ps(e.node,n)||ps(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.handleDeleteSession===s.handleDeleteSession&&e.handleRestoreSession===s.handleRestoreSession&&e.renderSessionNode===s.renderSessionNode},am=o.memo(sm,im),Pi={selected:0,"active-project":1,expanded:2,visible:3,background:4};function lm(e){const s=new Map,n=(r,i,a)=>{const l=Ze(r??null);if(!l)return;const c=s.get(l);c&&Pi[c.priority]<=Pi[i]||s.set(l,{directory:l,priority:i,reason:a})};for(const r of e.projectSections){const i=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":i&&(a="expanded"),n(r.project.normalizedPath,a,i?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=i&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":i&&(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 cm(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=e,l="Untitled Session";return t.jsx(cs,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(ds,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(ms,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(Os,{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(Ls,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>i(!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(N,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(N,{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 dm(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,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(cs,{open:!!s,onOpenChange:p=>{p||n(null)},children:t.jsxs(ds,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(ms,{children:d}),t.jsx(Os,{children:u})]}),t.jsxs(Ls,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>i(!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(N,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(N,{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 um(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(cs,{open:!!s,onOpenChange:i=>{i||n(null)},children:t.jsxs(ds,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(ms,{children:"Delete folder?"}),t.jsx(Os,{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(Ls,{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 fm=({selectedCount:e,archivedBucket:s,onRestore:n,onDelete:r,onDone:i})=>{const a=s?"Delete":"Archive",l="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:[s?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(N,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(it,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:B("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":a,children:t.jsx(N,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(it,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:l,"aria-label":"Exit selection",children:t.jsx(N,{name:"close",className:"h-4 w-4"})})}),t.jsx(it,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},hm=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:i,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:p,setBulkDeleteConfirm:m}=e,x=Ht(U=>U.enabled),h=Ht(U=>U.selectedIds.size),f=h>0,g=Ht(U=>U.selectedIds),S=Ht(U=>U.scopeKey),k=o.useCallback(()=>{Ht.getState().toggleMode()},[]),O=o.useCallback(()=>{Ht.getState().disable()},[]),j=o.useMemo(()=>{if(!f||typeof document>"u")return!1;let U=!1,T=!1;for(const R of g){const V=document.querySelectorAll(`[data-session-row="${CSS.escape(R)}"]`);for(const oe of V)oe.getAttribute("data-session-archived")==="1"?T=!0:U=!0}return T&&!U},[f,g]),v=o.useMemo(()=>{if(S)return S;if(!f||typeof document>"u")return null;for(const U of g){const R=document.querySelector(`[data-session-row="${CSS.escape(U)}"]`)?.getAttribute("data-session-scope");if(R&&R.length>0)return R}return null},[f,g,S]),y=o.useMemo(()=>{if(!v)return[];const U=i.get(v);return U&&U.length>0?U.map(T=>T.scopeKey):[v]},[v,i]),L=o.useMemo(()=>y.flatMap(U=>r[U]??[]),[r,y]),A=o.useCallback(U=>{for(const T of y)if((r[T]??[]).some(R=>R.id===U))return T;return null},[r,y]),C=o.useMemo(()=>{if(!f)return!1;for(const U of y)for(const T of r[U]??[])for(const R of T.sessionIds)if(g.has(R))return!0;return!1},[r,y,f,g]),I=o.useCallback((U,T)=>{const R=Array.from(g);for(const V of y)V!==U&&l(V,R);a(U,T,R)},[a,l,g,y]),P=o.useCallback(U=>{if(!f)return;const T=A(U);T&&I(T,U)},[f,I,A]),D=o.useCallback(()=>{const U=y[0];if(!U||!f)return;const T=c(U);T&&I(U,T.id)},[c,f,I,y]),W=o.useCallback(()=>{if(!f)return;const U=Array.from(g);for(const T of y)l(T,U)},[l,g,y,f]),ee=o.useCallback(async()=>{const U=Array.from(g);if(U.length!==0){if(j){const{deletedIds:T,failedIds:R}=await p(U);T.length>0&&le.success(T.length===1?`Deleted ${T.length} session`:`Deleted ${T.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to delete ${R.length} session`:`Failed to delete ${R.length} sessions`)}else{const{archivedIds:T,failedIds:R}=await d(U);T.length>0&&le.success(T.length===1?`Archived ${T.length} session`:`Archived ${T.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to archive ${R.length} session`:`Failed to archive ${R.length} sessions`)}Ht.getState().clear()}},[d,j,p,g]),Z=o.useCallback(()=>{if(!f)return;const U=g.size;if(!n){ee();return}m({sessionCount:U,archivedBucket:j})},[j,ee,g,n,m,f]),ie=o.useCallback(async()=>{if(!f||!j)return;const U=Array.from(g),{restoredIds:T,failedIds:R}=await u(U);T.length>0&&le.success(T.length===1?`Restored ${T.length} session`:`Restored ${T.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to restore ${R.length} session`:`Failed to restore ${R.length} sessions`),Ht.getState().clear()},[j,f,g,u]),z=o.useCallback(async()=>{m(null),await ee()},[ee]);return o.useEffect(()=>{if(!x)return;const U=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),T=R=>{if(s)return;const V=R.target;if(V&&(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.isContentEditable))return;const oe=U?R.metaKey:R.ctrlKey;if(R.key==="Escape"){R.preventDefault(),Ht.getState().disable();return}if(oe&&R.key==="Backspace"){R.preventDefault(),Z();return}if(oe&&(R.key==="a"||R.key==="A")){const $=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if($.length===0)return;R.preventDefault();const Te=Ht.getState().scopeKey??$[0]?.getAttribute("data-session-scope")??null,Ye=Ge=>Te?Ge.getAttribute("data-session-scope")===Te:!0,Ue=$.filter(Ye).map(Ge=>Ge.getAttribute("data-session-row")).filter(Ge=>typeof Ge=="string"&&Ge.length>0);if(Ue.length===0)return;Ht.getState().replaceAll(Ue,Te||null)}};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[Z,s,x]),{selectionModeEnabled:x,hasSelection:f,selectedIdsSize:h,bulkScopeIsArchived:j,derivedSelectionScope:v,bulkScopeFolders:L,bulkCanRemoveFromFolder:C,handleToggleSelectionMode:k,handleExitSelectionMode:O,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:D,handleBulkRemoveFromFolder:W,handleBulkDelete:Z,handleBulkRestore:ie,confirmBulkDelete:z}},Ei="oc.sessions.projectCollapse",Ti="oc.sessions.groupOrder",Ri="oc.sessions.groupCollapse",Mi="oc.sessions.activeSessionByProject",Fi="oc.sessions.expandedParents.v3",pm=(e,s,n)=>{if(e.time?.archived)return!0;const r=qo(Ps(e));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const i of s)if(qo(i)===r)return!0;return!1},mm=new Set,mr=[],ns=e=>{const s=o.useRef(e);return s.current=e,o.useCallback((...n)=>s.current(...n),[])},gm=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l})=>{const c=_e(d=>d.currentSessionDirectory);return o.useEffect(()=>{s.setBootstrapDemand(e,lm({projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,i,l,c,e,n]),o.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},xm=({directories:e})=>{const s=o.useMemo(()=>{const r=new Set;return e.forEach(i=>{const a=Ze(i)?.toLowerCase();a&&r.add(a)}),r},[e]);return rn(r=>{for(const i of r.catalog.byId.values()){if(i.lifecycle!=="busy"&&i.lifecycle!=="retry")continue;const a=Ze(i.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(Jn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},bm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:i=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Rr("react.session_sidebar_render"),as("ui.session_sidebar.render"),as(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),as(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=o.useState(!1),[u,p]=o.useState(""),m=o.useRef(null),x=o.useRef(null),[h,f]=o.useState(null),[g,S]=o.useState(""),[k,O]=o.useState(null),[j,v]=o.useState(new Set),y=o.useMemo(()=>kn(),[]),[L,A]=o.useState(new Set),[C,I]=o.useState(null),[P,D]=o.useState(null),[W,ee]=o.useState(new Map),[Z,ie]=o.useState(new Map),[z,U]=o.useState(!1),[T,R]=o.useState(null),[V,oe]=o.useState(null),[$,Me]=o.useState(""),[Te,Ye]=o.useState(null),[Ue,Ge]=o.useState(null),[Le,re]=o.useState(null),pe=Er(b=>b.ids),Ke=vd(o.useCallback(b=>e?b.rankById:la,[e])),ke=rn(b=>e?wd(b.catalog):"",void 0,"catalog"),Ce=o.useMemo(()=>ke?ke.split("|"):mr,[ke]),He=o.useMemo(()=>new Set(Ce),[Ce]),tt=Sd(Ur(b=>e?Object.entries(b.index.session.unseenCount).filter(([,Q])=>Q>0).map(([Q])=>Q).sort():mr)),ze=o.useMemo(()=>new Set(tt),[tt]),J=Er(b=>b.toggle),[q,ge]=o.useState(()=>{try{const b=kn().getItem(Ri);if(!b)return new Set;const Q=JSON.parse(b);return new Set(Array.isArray(Q)?Q.filter(H=>typeof H=="string"):[])}catch{return new Set}}),[X,we]=o.useState(()=>{try{const b=kn().getItem(Ti);if(!b)return new Map;const Q=JSON.parse(b),H=new Map;return Object.entries(Q).forEach(([Re,ht])=>{Array.isArray(ht)&&H.set(Re,ht.filter(Vt=>typeof Vt=="string"))}),H}catch{return new Map}}),xe=o.useMemo(()=>{try{const b=kn().getItem(Mi);if(!b)return new Map;const Q=JSON.parse(b),H=new Map;return Object.entries(Q).forEach(([Re,ht])=>{typeof ht=="string"&&ht.length>0&&H.set(Re,ht)}),H}catch{return new Map}},[]),Ne=o.useCallback(b=>{try{y.setItem(Mi,JSON.stringify(Object.fromEntries(b.entries())))}catch{}},[y]),[pt,gt]=o.useState(new Map),et=o.useRef(0),De=Rs(b=>b.homeDirectory),Fe=Rs(b=>b.currentDirectory),Ae=zt(b=>b.projects),at=zt(b=>b.activeProjectId),jt=zt(b=>b.removeProject),st=zt(b=>b.setActiveProjectIdOnly),_=zt(b=>b.updateProjectMeta),ye=zt(b=>b.reorderProjects),be=ue(b=>b.setActiveMainTab),w=ue(b=>b.setSettingsDialogOpen),Y=ue(b=>b.setSettingsPage),se=ue(b=>b.toggleHelpDialog),de=ue(b=>b.setSessionSwitcherOpen),Se=ue(b=>b.setArchivePageOpen),Pe=ue(b=>b.notifyOnSubtasks),$e=ue(b=>b.showDeletionDialog),mt=ue(b=>b.setShowDeletionDialog),Ct=jd(u,120),Xe=o.useMemo(()=>Ct.trim().toLowerCase(),[Ct]),ct=Xe.length>0,xt=Kt(b=>b.collapsedFolderIds),Oe=Kt(b=>b.foldersMap),We=Kt(b=>b.getFoldersForScope),bt=Kt(b=>b.createFolder),Mt=Kt(b=>b.renameFolder),$t=Kt(b=>b.deleteFolder),Nt=Kt(b=>b.addSessionToFolder),At=Kt(b=>b.addSessionsToFolder),It=Kt(b=>b.removeSessionFromFolder),M=Kt(b=>b.removeSessionsFromFolders),je=Kt(b=>b.toggleFolderCollapse),Be=Kt(b=>b.getSessionFolderId);Gh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:m});const dt=Cd(e),F=so(),ae=ca(),me=rn(b=>b.connection,void 0,"chrome"),nt=rn(b=>{for(const Q of b.catalog.listStatusByDirectory.values())if(Q==="ready")return!0;return!1},void 0,"catalog"),ve=Pr({archived:!1}),Je=Pr({archived:!0}),yt=`session-sidebar:${o.useId()}`,Ft=_e(b=>b.setCurrentSession),Lt=_e(b=>b.updateSessionTitle),kt=_e(b=>b.shareSession),Ut=_e(b=>b.unshareSession),Rt=ha(b=>b.projects),vt=o.useMemo(()=>kd(Ae,{projects:Rt}),[Ae,Rt]),Wt=o.useMemo(()=>{const b=new Map;for(const Q of Ae){const H=Ze(Q.path);if(!H)continue;const Re=Rt.get(H)?.error;Re&&b.set(H,Re)}return b},[Ae,Rt]);o.useEffect(()=>{if(!C)return;const b=Ae.find(H=>H.id===C);if(!b){I(null),D(null);return}if(!P)return;(vt.get(Ze(b.path)??b.path)??[]).some(H=>Ze(H.path)===Ze(P))||(D(null),le.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[vt,Ae,C,P]);const G=_e(b=>b.openNewSessionDraft),te=o.useCallback(b=>{ue.getState().closeMainSurfaces(),G(b),r?.()},[r,G]),ne=Bn(Ur(b=>({checkForUpdates:b.checkForUpdates,available:b.available,runtimeType:b.runtimeType,info:b.info,downloading:b.downloading,downloaded:b.downloaded,progress:b.progress,error:b.error,downloadUpdate:b.downloadUpdate,restartToUpdate:b.restartToUpdate}))),ce=o.useMemo(()=>Nd(Ae,vt,{includeWorktrees:!0}),[vt,Ae]),fe=o.useMemo(()=>ve.filter(b=>pm(b,ce,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[ve,ce]),ft=o.useMemo(()=>[...fe,...Je],[Je,fe]),Et=Xn(),wt=o.useMemo(()=>`${Et}|${Ae.map(b=>`${b.id}:${Ze(b.path)??""}`).join("|")}`,[Ae,Et]),Gt=o.useMemo(()=>{const b=new Set;let Q=!0;for(const H of Ae){const Re=Ze(H.path);if(!Re)continue;const ht=Rt.get(Re)?.status??"idle";ht==="failed"&&b.add(Re),(ht==="idle"||ht==="loading")&&(Q=!1)}return{complete:Q,unresolved:b}},[Ae,Rt]),ts=Gt.complete?wt:null,Dt=!Gt.complete,ls=Gt.unresolved,{isTablet:us}=Fs(),xs=s||us,qs=Uh({mobileVariant:s,isTablet:us}),{buildGroupSearchText:Qs,filterSessionNodesForSearch:E,buildGroupedSessions:he}=$h({homeDirectory:De,pinnedSessionIds:pe,sessionOrderRanks:Ke}),{scheduleCollapsedProjectsPersist:Ie}=Hh({safeStorage:y,keys:{sessionExpanded:Fi,projectCollapse:Ei,groupOrder:Ti,groupCollapse:Ri},groupOrderByProject:X,collapsedGroups:q,setExpandedParents:v,setCollapsedProjects:A}),lt=o.useMemo(()=>Ad(fe,pe,Ke),[pe,Ke,fe]),ss=o.useMemo(()=>lt.map(b=>b.id).join("|"),[lt]),K=o.useRef(null),Ve=o.useMemo(()=>{const b=K.current;if(b&&b.signature===ss)return b.map;const Q=new Map(lt.map((H,Re)=>[H.id,Re]));return K.current={signature:ss,map:Q},Q},[lt,ss]),ut=o.useMemo(()=>{const b=new Map;return lt.forEach(Q=>{const H=Q.parentID;if(!H)return;const Re=b.get(H)??[];Re.push(Q),b.set(H,Re)}),b.forEach(Q=>Q.sort((H,Re)=>to(H,Re,pe,Ke))),b},[lt,pe,Ke]),Pt=o.useMemo(()=>t.jsx(Es,{icon:"chat-new",mobileVariant:s,onClick:()=>te(),children:"New session"}),[s,te]),Bt=o.useMemo(()=>Ae.find(b=>b.id===k)??null,[Ae,k]),os=o.useCallback(b=>{k&&_(k,{label:b.label,defaultModel:b.defaultModel??null})},[k,_]),Bs=o.useCallback(()=>{const b=Bn.getState();if(b.available&&b.info){U(!0);return}ne.checkForUpdates().then(()=>{const{available:Q,error:H}=Bn.getState();if(H){le.error("Failed to check for updates",{description:H});return}if(!Q){le.success("You are on the latest version");return}U(!0)})},[ne]),Yt=Id(),yo=o.useCallback(()=>{if(s&&de(!1),r?.(),Yt?.openSettings){Yt.openSettings();return}w(!0)},[Yt,s,r,de,w]),ul=ne.available&&(ne.runtimeType==="desktop"||ne.runtimeType==="web"),fl=_e(b=>b.deleteSession),vo=_e(b=>b.deleteSessions),hl=_e(b=>b.archiveSession),wo=_e(b=>b.archiveSessions),pl=_e(b=>b.unarchiveSession),ml=_e(b=>b.unarchiveSessions),{copiedSessionId:gl,handleSessionSelect:xl,handleSessionDoubleClick:bl,handleSaveEdit:yl,handleCancelEdit:vl,handleShareSession:wl,handleCopyShareUrl:Sl,handleCopySessionId:jl,handleUnshareSession:Cl,handleDeleteSession:kl,handleRestoreSession:Nl,confirmDeleteSession:Al}=Kh({mobileVariant:s,allowReselect:i,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:p,setIsSessionSearchOpen:d,setActiveMainTab:be,setSessionSwitcherOpen:de,setCurrentSession:Ft,updateSessionTitle:Lt,shareSession:kt,unshareSession:Ut,deleteSession:fl,deleteSessions:vo,archiveSession:hl,archiveSessions:wo,unarchiveSession:pl,childrenMap:ut,showDeletionDialog:$e,setDeleteSessionConfirm:Ye,deleteSessionConfirm:Te,setEditingId:f,setEditTitle:S,editingId:h,editTitle:g}),Il=o.useCallback(()=>{if(!Ue)return;const{scopeKey:b,folderId:Q}=Ue;Ge(null),$t(b,Q)},[Ue,$t]),So=o.useCallback(()=>{Ts.requestDirectoryDialog()},[]),Dl=o.useCallback(b=>{v(Q=>{const H=Mu(Q,b);try{y.setItem(Fi,JSON.stringify(Array.from(H)))}catch{}return H})},[y]),jo=o.useCallback((b,Q)=>{if(!b)return null;Q&&xt.has(Q)&&je(Q);const H=bt(b,"New folder",Q);return oe(H.id),Me(H.name),H},[xt,je,bt]),bn=ns(xl),Pl=ns(bl),El=ns(yl),Tl=ns(vl),Rl=ns(wl),Ml=ns(Sl),Fl=ns(jl),Ol=ns(Cl),Ll=ns(kl),Bl=ns(Nl),rr=ns(jo),Co=o.useCallback((b,Q)=>{ie(H=>{const Re=new Map(H);return Re.set(b,Q+7),Re})},[]),yn=o.useCallback(b=>{ie(Q=>{if(!Q.has(b))return Q;const H=new Map(Q);return H.delete(b),H})},[]),ko=o.useCallback(b=>{ie(Q=>{let H=!1;const Re=new Map(Q),ht=`${b}:`;for(const Vt of Re.keys())Vt.startsWith(ht)&&(Re.delete(Vt),H=!0);return H?Re:Q})},[]),_l=o.useCallback(b=>{et.current=Date.now()+150,ko(b),A(Q=>{const H=new Set(Q);H.has(b)?H.delete(b):H.add(b);try{y.setItem(Ei,JSON.stringify(Array.from(H)))}catch{}return Ie(H),H})},[ko,y,Ie]),bs=o.useMemo(()=>Ae.map(b=>({...b,normalizedPath:Ze(b.path)})).filter(b=>!!b.normalizedPath),[Ae]),zl=o.useMemo(()=>bs.map(b=>b.normalizedPath),[bs]),No=Dd(e?zl:mr);Jh({enabled:e,normalizedProjects:bs,gitRepoStatus:No,setProjectRepoStatus:ee,setProjectRootBranches:gt});const $l=_e(b=>b.isLoading),Ao=o.useMemo(()=>ip(fe,bs,vt,Je),[Je,vt,bs,fe]);sp({enabled:e,hasAuthoritativeGlobalSessions:nt,sessions:ft});const{getSessionsForProject:Ul,getArchivedSessionsForProject:Gl}=Xh({ownership:Ao});Rh({enabled:e,normalizedProjects:bs,ownership:Ao,isSessionsLoading:$l,hasAuthoritativeGlobalSessions:nt,isWorktreeTopologyLoading:Dt,unresolvedWorktreeProjectPaths:ls,foldersMap:Oe,createFolder:bt,addSessionToFolder:Nt});const Io=o.useRef(!1);at&&W.has(at)&&(Io.current=!!W.get(at));const Kl=Gp(b=>b.showArchivedSessions),or=zt(b=>b.manualProjectOrder),Do=o.useRef(new Set),vn=Fu(Do.current,j,"project");Do.current=vn;const ir={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:i,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:us,catalogSessions:ve,archivedSessions:Je,projects:Ae,activeProjectId:at,manualProjectOrder:or,currentDirectory:Fe,availableWorktreesByProject:vt,pinnedSessionIds:pe,sessionOrderRanks:Ke,foldersMap:Oe,collapsedFolderIds:xt,gitBranches:dt,gitRepoStatus:No,updateStore:ne,showArchivedSessions:Kl,projectRepoStatus:W,projectRootBranches:pt,resolvedWorktreeTopologyKey:ts,unresolvedWorktreeProjectPaths:ls,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:h,editTitle:g,editingProjectDialogId:k,expandedParents:j,collapsedProjects:L,visibleSessionCountByGroup:Z,updateDialogOpen:z,openSidebarMenuKey:T,renamingFolderId:V,renameFolderDraft:$,deleteSessionConfirm:Te,deleteFolderConfirm:Ue,bulkDeleteConfirm:Le,collapsedGroups:q},Po=o.useRef(null),Eo=Po.current;if(Eo){let b=!1;for(const Q of Object.keys(ir))Object.is(Eo[Q],ir[Q])||(as(`ui.session_sidebar.source.${Q}`),b=!0);b||as("ui.session_sidebar.source.parent_or_context")}Po.current=ir;const Hl=o.useMemo(()=>{const b=new Map(or.map((Q,H)=>[Q,H]));return[...bs].sort((Q,H)=>(b.get(Q.id)??1/0)-(b.get(H.id)??1/0))},[or,bs]),{projectSections:Tt,groupSearchDataByGroup:To,sectionsForRender:Ro,flatSectionsForRender:wn,searchMatchCount:Wl}=Fh({normalizedProjects:Hl,getSessionsForProject:Ul,getArchivedSessionsForProject:Gl,availableWorktreesByProject:vt,projectRepoStatus:W,projectRootBranches:pt,lastRepoStatus:Io.current,buildGroupedSessions:he,hasSessionSearchQuery:ct,normalizedSessionSearchQuery:Xe,filterSessionNodesForSearch:E,buildGroupSearchText:Qs,foldersMap:Oe}),Sn=o.useMemo(()=>{const b=fe.filter(H=>aa(Ps(H),De));if(b.length===0)return null;const Q=he(b,"~",[],null,!1).map(H=>ct?{...H,sessions:E(H.sessions,Xe)}:H).filter(H=>H.sessions.length>0&&!H.isArchivedBucket);return Q.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Q}},[he,E,ct,De,Xe,fe]),Yl=o.useMemo(()=>{if(!ct||!Sn)return 0;const b=Q=>Q.reduce((H,Re)=>H+1+b(Re.children),0);return Sn.groups.reduce((Q,H)=>Q+b(H.sessions),0)},[Sn,ct]),Vl=o.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:ql}=Mh(X),Mo=o.useRef(!1);o.useEffect(()=>{if(Mo.current||Tt.length===0)return;const b=Tt.flatMap(Q=>Q.groups.filter(H=>H.isArchivedBucket).map(H=>`${Q.project.id}:${H.id}`));b.length>0&&ge(Q=>new Set([...Q,...b])),Mo.current=!0},[Tt]),o.useMemo(()=>{const b=new Map,Q=new Map;return Tt.forEach(H=>{const Re=Zn(H.project.label?.trim()||Ms(H.project.normalizedPath,De)||H.project.normalizedPath);H.groups.forEach(ht=>{const Vt=ht.branch&&ht.branch!=="HEAD"&&ht.branch!==Re?ht.branch:null,Js={projectLabel:Re,branchLabel:Vt},js=wc=>{wc.forEach(_s=>{const _o=H.project.normalizedPath.length,Sc=Q.get(_s.session.id)??-1;_o<Sc||(b.set(_s.session.id,{node:_s,projectId:H.project.id,groupDirectory:ht.directory,secondaryMeta:Js}),Q.set(_s.session.id,_o),_s.children.length>0&&js(_s.children))})};js(ht.sessions)})}),b},[Tt,De]);const Fo=o.useMemo(()=>wn.map(b=>b.groups.some(Q=>Q.isArchivedBucket)?{...b,groups:b.groups.filter(Q=>!Q.isArchivedBucket)}:b),[wn]),Ql=o.useMemo(()=>{if(!C)return Fo;const b=Ro.find(Re=>Re.project.id===C);if(!b)return[];const Q=Ze(P??b.project.normalizedPath),H=b.groups.find(Re=>!Re.isArchivedBucket&&Ze(Re.directory)===Q);return H?[{...b,groups:[H]}]:[]},[Ro,Fo,C,P]),Jl=o.useMemo(()=>{let b=0;for(const Q of Tt)for(const H of Q.groups)H.isArchivedBucket||(b+=H.sessions.length);return b},[Tt]),Xl=o.useMemo(()=>{const b=new Map;for(const Q of Tt){let H=0;for(const Re of Q.groups)Re.isArchivedBucket||(H+=Re.sessions.length);b.set(Q.project.id,H)}return b},[Tt]),Zl=o.useCallback(b=>{const Q=Tt.find(H=>H.project.id===b);return Q?Q.groups.some(H=>H.isArchivedBucket?!1:H.sessions.some(Re=>He.has(Re.session.id))):!1},[He,Tt]),ec=o.useCallback(b=>{const Q=Tt.find(H=>H.project.id===b);return Q?Q.groups.some(H=>H.isArchivedBucket?!1:H.sessions.some(Re=>ze.has(Re.session.id))):!1},[Tt,ze]),tc=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",sc=s?"size-4":"h-4.5 w-4.5",jn=ns((b,Q=0,H,Re,ht=!1,Vt,Js="project",js)=>t.jsx(am,{node:b,depth:Q,groupDirectory:H,projectId:Re,archivedBucket:ht,pinnedSessionIds:pe,expandedParents:vn,hasSessionSearchQuery:ct,normalizedSessionSearchQuery:Xe,notifyOnSubtasks:Pe,editingId:h,setEditingId:f,editTitle:g,setEditTitle:S,handleSaveEdit:El,handleCancelEdit:Tl,toggleParent:Dl,handleSessionSelect:bn,handleSessionDoubleClick:Pl,togglePinnedSession:J,handleShareSession:Rl,copiedSessionId:gl,handleCopyShareUrl:Ml,handleCopySessionId:Fl,handleUnshareSession:Ol,openSidebarMenuKey:T,setOpenSidebarMenuKey:R,renamingFolderId:V,getFoldersForScope:We,getSessionFolderId:Be,removeSessionFromFolder:It,addSessionToFolder:Nt,createFolderAndStartRename:rr,handleDeleteSession:Ll,handleRestoreSession:Bl,mobileVariant:s,alwaysShowActions:xs,allowQuickArchiveAction:qs,renderSessionNode:jn,secondaryMeta:Vt,renderContext:Js,subtreeContainsEditing:js?.subtreeContainsEditing??mm,menuOpenSessionId:js?.menuOpenSessionId??null,nodeStructureKey:js?.nodeStructureKey??"",childRenderExtrasFor:js?.childRenderExtrasFor})),nc=o.useMemo(()=>{const b=new Map;return wn.forEach(Q=>{const H=Q.groups.find(Re=>!Re.isArchivedBucket);H?.folderScopes&&H.folderScopes.length>0&&b.set(Q.project.id,H.folderScopes)}),b},[wn]),rc=o.useCallback((b,Q)=>{const H=[];return Q.forEach(Re=>{Re.isArchivedBucket||(H.push(Re.directory),Re.folderScopes?.forEach(ht=>H.push(ht.directory)))}),t.jsx(xm,{directories:H})},[]),Oo=o.useCallback(b=>{yn(b),ge(Q=>{const H=new Set(Q);return H.has(b)?H.delete(b):H.add(b),H})},[yn]),oc=o.useCallback((b,Q,H,Re,ht,Vt,Js)=>t.jsx(Np,{group:b,groupKey:Q,projectId:H,hideGroupLabel:Re,dragHandleProps:ht,compactBodyPadding:Vt,hasSessionSearchQuery:ct,normalizedSessionSearchQuery:Xe,groupSearchDataByGroup:To,visibleSessionCount:Z.get(Q),collapsedGroups:q,hideDirectoryControls:a,collapsedFolderIds:xt,toggleFolderCollapse:je,renameFolder:Mt,deleteFolder:$t,showDeletionDialog:$e,setDeleteFolderConfirm:Ge,renderSessionNode:jn,showMoreGroupSessions:Co,resetGroupSessionLimit:yn,mobileVariant:s,alwaysShowActions:xs,activeProjectId:at,setActiveProjectIdOnly:st,setActiveMainTab:be,setSessionSwitcherOpen:de,openNewSessionDraft:te,addSessionToFolder:Nt,createFolderAndStartRename:rr,renamingFolderId:V,renameFolderDraft:$,setRenameFolderDraft:Me,setRenamingFolderId:oe,pinnedSessionIds:pe,expandedParents:vn,sessionOrderIndex:Ve,editingId:h,editTitle:g,openSidebarMenuKey:T,activeActivitySessionIds:He,unreadActivitySessionIds:ze,notifyOnSubtasks:Pe,onToggleCollapsedGroup:Oo,scrollContainerRef:Js}),[ct,Xe,To,Z,q,a,xt,je,Mt,$t,$e,jn,Co,yn,s,xs,at,st,be,de,te,Nt,rr,V,$,pe,vn,Ve,h,g,T,He,ze,Pe,Oo]),Lo=!!(V||h||k),{selectionModeEnabled:Bo,hasSelection:ic,selectedIdsSize:ac,bulkScopeIsArchived:lc,derivedSelectionScope:cc,bulkScopeFolders:dc,bulkCanRemoveFromFolder:uc,handleToggleSelectionMode:fc,handleExitSelectionMode:hc,handleBulkMoveToFolder:pc,handleBulkCreateFolderAndMove:mc,handleBulkRemoveFromFolder:gc,handleBulkDelete:xc,handleBulkRestore:bc,confirmBulkDelete:yc}=hm({isInlineEditing:Lo,showDeletionDialog:$e,foldersMap:Oe,folderScopesByProject:nc,addSessionsToFolder:At,removeSessionsFromFolders:M,createFolderAndStartRename:jo,archiveSessions:wo,unarchiveSessions:ml,deleteSessions:vo,setBulkDeleteConfirm:re}),vc=o.useCallback(()=>{ue.getState().closeMainSurfaces(),be("chat"),s&&de(!1),G(),r?.()},[s,r,G,be,de]);return t.jsx(Pd,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:m,className:B("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(gm,{owner:yt,childStores:ae,projectSections:Tt,activeProjectId:at,collapsedProjects:L,collapsedGroups:q,currentDirectory:Fe}),t.jsx(Lh,{projectSections:Tt,activeProjectId:at,initialActiveSessionByProject:xe,persistActiveSessionByProject:Ne,handleSessionSelect:bn,mobileVariant:s,openNewSessionDraft:G,setActiveMainTab:be,setSessionSwitcherOpen:de}),t.jsx(Th,{enabled:e,sortedSessions:lt,prefetchSession:async b=>{await F.syncSession(b)}}),!a&&!s?t.jsx(Ip,{onNewSession:vc,showSidebarToggle:!0}):null,t.jsx(Ap,{hideDirectoryControls:a,handleOpenDirectoryDialog:So,onOpenArchive:()=>{s&&de(!1),Se(!0)},onOpenSettings:s?yo:void 0,onOpenInstances:s?Yt?.openInstances:void 0,instanceLabel:s?Yt?.instanceLabel:void 0,onOpenUpdate:s?Yt?.openUpdate:void 0,headerActionIconClass:sc,headerActionButtonClass:tc,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:p,hasSessionSearchQuery:ct,searchMatchCount:Wl+(C===null?Yl:0),selectionModeEnabled:Bo,onToggleSelectionMode:fc,mobileVariant:s}),me==="error"||me==="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&&Tt.length>0?t.jsx(Ep,{projects:Tt.map(b=>b.project),selectedProjectId:C,selectedWorktreePath:P,worktreesByProject:vt,worktreeErrorsByProject:Wt,onSelectProject:b=>{if(I(b),D(null),!b)return;st(b);const Q=Tt.find(ht=>ht.project.id===b),H=Q?.groups.find(ht=>ht.isMain),Re=H?.sessions[0]?.session;Re?bn(Re.id,H?.directory??Q?.project.normalizedPath??null,{keepPanelOpen:!0}):Q&&te({selectedProjectId:b,directoryOverride:Q.project.normalizedPath})},onSelectWorktree:(b,Q)=>{I(b),D(Q),st(b);const ht=Tt.find(Vt=>Vt.project.id===b)?.groups.find(Vt=>Ze(Vt.directory)===Ze(Q))?.sessions[0]?.session;ht?bn(ht.id,Q,{keepPanelOpen:!0}):te({selectedProjectId:b,directoryOverride:Q})},onOpenDirectoryDialog:So,onOpenProjectEditDialog:O,onRemoveProject:jt,totalSessionCount:Jl,getSessionCountForProject:b=>Xl.get(b)??0,hasActiveSessionByProject:Zl,hasUnseenByProject:ec,homeDirectory:De,mobileVariant:s}):null,t.jsx(Fp,{sectionsForRender:Ql,allFoldersOnlySection:C===null?Sn:null,projectSections:Tt,activeProjectId:at,showOnlyMainWorkspace:l,hasSessionSearchQuery:ct,emptyState:Pt,searchEmptyState:Vl,isAllFoldersView:C===null,pinnedSessionIds:pe,renderSessionNode:jn,renderGroupSessions:oc,homeDirectory:De,collapsedProjects:L,hideDirectoryControls:a,projectRepoStatus:W,mobileVariant:s,alwaysShowActions:xs,toggleProject:_l,setActiveProjectIdOnly:st,setActiveMainTab:be,setSessionSwitcherOpen:de,openNewSessionDraft:te,openProjectEditDialog:O,removeProject:jt,reorderProjects:ye,getOrderedGroups:ql,setGroupOrderByProject:we,renderProjectStatusIndicator:rc,openSidebarMenuKey:T,setOpenSidebarMenuKey:R,isInlineEditing:Lo}),Bo&&ic?t.jsx(fm,{selectedCount:ac,scopeKey:cc,scopeFolders:dc,archivedBucket:lc,onMoveToFolder:pc,onCreateFolderAndMove:mc,onRemoveFromFolder:gc,canRemoveFromFolder:uc,onRestore:bc,onDelete:xc,onDone:hc}):null,s?null:t.jsx(Tp,{onOpenSettings:yo,onOpenShortcuts:se,onOpenAbout:()=>{Y("about"),w(!0)},onOpenUpdate:Bs,showRuntimeButtons:!0,showUpdateButton:ul}),t.jsx(Oa,{open:z,onOpenChange:U,info:ne.info,downloading:ne.downloading,downloaded:ne.downloaded,progress:ne.progress,error:ne.error,onDownload:ne.downloadUpdate,onRestart:ne.restartToUpdate,runtimeType:ne.runtimeType}),t.jsx(ap,{open:!!Bt,onOpenChange:b=>{b||O(null)},project:Bt,onSave:os}),t.jsx(cm,{value:Te,setValue:Ye,showDeletionDialog:$e,setShowDeletionDialog:mt,onConfirm:Al}),t.jsx(um,{value:Ue,setValue:Ge,onConfirm:Il}),t.jsx(dm,{value:Le,setValue:re,showDeletionDialog:$e,setShowDeletionDialog:mt,onConfirm:yc})]})})},Px=o.memo(bm),Oi=6,rs=.18,sn=1.2,nn=.38,$n=48,ym=(e,s)=>e==="left"?s<0:s>0,Ex=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Tx=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,Li=(e,s,n,r)=>e==="left"?s?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):s?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),Rx=e=>{const{side:s,dx:n,dy:r,dt:i,progress:a,isDragging:l}=e,c=n/Math.max(1,i);if(l){const d=s==="left"?c<-rs:c>rs,u=s==="left"?c>rs:c<-rs;return d||!u&&a<nn}return Math.abs(n)>=$n&&Math.abs(r)<=Math.abs(n)*sn&&ym(s,n)},vm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:i,progress:a}=e,l=r/Math.max(1,i);return s==="left"?n?l<-rs?!1:l>rs?!0:a>nn:l>rs?!0:l<-rs?!1:a>nn:n?l>rs?!1:l<-rs?!0:a>nn:l<-rs?!0:l>rs?!1:a>nn},wm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Sm=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(wm);if(a&&s.contains(a))return!0}else{const a=e.closest("[data-no-drawer-swipe]");if(a&&s.contains(a))return!0}let i=e;for(;i&&i!==s;){if(i instanceof HTMLElement&&i.scrollWidth>i.clientWidth){const a=getComputedStyle(i).overflowX;if(a==="auto"||a==="scroll")return!0}i=i.parentElement}return!1},jm=({value:e,options:s,disabled:n,onChange:r})=>{const i=e||"Default",a=t.jsxs("div",{className:B("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:i}),t.jsx(N,{name:"arrow-down-s",className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]});return n?a:t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:a}),t.jsxs(Xt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(St,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:B("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(St,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:B("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Bi=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function Cm(e){const{open:s,onOpenChange:n,projectDirectory:r,submitting:i=!1,onConfirm:a}=e,l=Ot(v=>v.loadProviders),c=Ot(v=>v.loadAgents),d=Ot(v=>v.providers),u=Ot(v=>v.currentProviderId),p=Ot(v=>v.currentModelId),m=Ot(v=>v.currentVariant||""),x=Ot(v=>v.currentAgentName||""),[h,f]=o.useState(()=>Bi({providerID:u,modelID:p,variant:m,agent:x}));o.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),o.useEffect(()=>{s&&f(Bi({providerID:u,modelID:p,variant:m,agent:x}))},[s,u,p,m,x]),o.useEffect(()=>{if(!s||d.length===0)return;const v=d.find(C=>C.id===h.providerID)??d[0],y=Array.isArray(v?.models)?v.models:[],L=y.some(C=>C.id===h.modelID),A=y[0]?.id??"";v?.id===h.providerID&&L||f(C=>({...C,providerID:typeof v?.id=="string"?v.id:"",modelID:typeof A=="string"?L?C.modelID:A:"",variant:""}))},[s,d,h.providerID,h.modelID]),o.useCallback(v=>Ed(v.mode),[]);const g=o.useMemo(()=>{const y=d.find(L=>L.id===h.providerID)?.models?.find(L=>L.id===h.modelID);return y?.variants?Object.keys(y.variants):[]},[d,h.providerID,h.modelID]),S=g.length>0;o.useEffect(()=>{S||!h.variant||f(v=>({...v,variant:""}))},[S,h.variant]);const k=h.providerID.trim().length>0&&h.modelID.trim().length>0,O=o.useCallback(()=>{!k||i||a(h)},[k,i,a,h]);return o.useEffect(()=>{if(!s)return;const v=y=>{(y.metaKey||y.ctrlKey)&&y.key==="Enter"&&(y.preventDefault(),O())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[s,O]),t.jsx(cs,{open:s,onOpenChange:v=>{i||n(v)},children:t.jsxs(ds,{className:"max-w-md overflow-visible",children:[t.jsx(Ss,{children:t.jsx(ms,{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(jm,{value:h.variant,options:g,disabled:!S,onChange:v=>f(y=>({...y,variant:v}))})]})}),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(Qe,{variant:"ghost",size:"sm",onClick:()=>n(!1),disabled:i,children:"Cancel"}),t.jsx(Qe,{size:"sm",onClick:O,disabled:!k||i,children:i?"Sending":"Send"})]})})]})})}const Xr=5,ll=15,Tn=new Map,Un=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},km=(e,s)=>{const n=Un(s);return Math.max(n*Xr,Math.min(n*ll,n*e))},Nm=async(e,s)=>{const n=await Od(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},Am=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_i=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],zi=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},Im=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=fo({id:e});return t.jsx("li",{ref:i,style:{transform:ho.Transform.toString(l),transition:c},className:B(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},Dm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[i,a]=o.useState(!1),[l,c]=o.useState(""),[d,u]=o.useState([]),[p,m]=o.useState(""),[x,h]=o.useState(null),[f,g]=o.useState(()=>new Set),[S,k]=o.useState([]),[O,j]=o.useState(null),[v,y]=o.useState(!1),[L,A]=o.useState(0),C=o.useRef(!1),I=o.useRef(""),P=o.useRef(null),D=ue(w=>w.todoPanelHeight),W=ue(w=>w.setTodoPanelHeight),ee=ue(w=>w.notesPanelHeight),Z=ue(w=>w.setNotesPanelHeight),[ie,z]=o.useState(!1),U=o.useRef(0),T=o.useRef(D),R=_e(w=>w.currentSessionId),V=_e(w=>w.createSession),oe=_e(w=>w.initializeNewPiChamberSession),$=_e(w=>w.sendMessage),Me=_e(w=>w.setCurrentSession),Te=Td(w=>w.setPendingInputText),Ye=Rs(w=>w.currentDirectory),Ue=ue(w=>w.openContextPanelTab),Ge=ue(w=>w.setActiveMainTab),Le=ue(w=>w.setSessionSwitcherOpen),re=ue(w=>w.padding),pe=o.useCallback(async(w,Y)=>{if(!e)return!1;const se=e.id,Se=(Tn.get(se)??Promise.resolve()).catch(()=>{}).then(()=>Rd(e,{notes:w,todos:Y}));Tn.set(se,Se);try{const Pe=await Se;return Pe||le.error("Failed to save project notes"),Pe}finally{Tn.get(se)===Se&&Tn.delete(se)}},[e]);o.useEffect(()=>{if(!e){c(""),u([]),k([]),m(""),g(new Set);return}let w=!1;return a(!0),(async()=>{try{const Y=await Md(e),se=await Promise.all(Y.plans.map(de=>Nm(de,"Plan")));if(w)return;c(Y.notes),u(_i(Y.todos)),k(se),I.current=Y.notes,C.current=!0,m(""),g(new Set)}catch{w||(le.error("Failed to load project notes"),c(""),u([]),k([]),I.current="",C.current=!0)}finally{w||a(!1)}})(),()=>{w=!0}},[L,e]),o.useEffect(()=>{if(!e)return;const w=Y=>{const se=Y.detail;se?.projectId&&se.projectId!==e.id||A(de=>de+1)};return window.addEventListener("pichamber:project-plan-saved",w),window.addEventListener("pichamber:project-notes-updated",w),()=>{window.removeEventListener("pichamber:project-plan-saved",w),window.removeEventListener("pichamber:project-notes-updated",w)}},[e]),o.useEffect(()=>{if(d.length<7)return;const w=km(d.length,re),Y=Un(re)*Xr;D!==w&&(D<Y||D>w)&&W(w)},[d.length,re,D,W]),o.useEffect(()=>{if(!ie)return;const w=se=>{const de=se.clientY-U.current,Se=Math.min(Un(re)*ll,Math.max(Un(re)*Xr,T.current+de));W(Se)},Y=()=>{z(!1)};return window.addEventListener("pointermove",w),window.addEventListener("pointerup",Y,{once:!0}),window.addEventListener("pointercancel",Y,{once:!0}),()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",Y),window.removeEventListener("pointercancel",Y)}},[ie,re,W]);const Ke=o.useCallback(w=>{z(!0),U.current=w.clientY,T.current=D,w.preventDefault()},[D]),ke=o.useCallback(()=>{P.current!==null&&(window.clearTimeout(P.current),P.current=null)},[]),Ce=o.useCallback(()=>{ke(),I.current=l,pe(l,d)},[ke,l,pe,d]);o.useEffect(()=>{if(!(!e||!C.current)&&l!==I.current)return P.current=window.setTimeout(()=>{P.current=null,I.current=l,pe(l,d)},400),()=>{ke()}},[ke,l,pe,e,d]),o.useEffect(()=>()=>ke(),[ke]);const He=o.useCallback(()=>{const w=p.trim();if(!w)return;const Y=zi(d,{id:Am(),text:w.slice(0,Cn),completed:!1,createdAt:Date.now()});u(Y),m(""),pe(l,Y)},[p,l,pe,d]),tt=o.useCallback(w=>{g(Y=>{const se=new Set(Y);return se.has(w)?se.delete(w):se.add(w),se})},[]),ze=o.useCallback((w,Y)=>{const se=d.find($e=>$e.id===w);if(!se||se.completed===Y)return;const de=d.filter($e=>$e.id!==w),Se={...se,completed:Y},Pe=Y?[...de,Se]:zi(de,Se);u(Pe),pe(l,Pe)},[l,pe,d]),J=o.useCallback(w=>{const Y=d.filter(se=>se.id!==w);u(Y),pe(l,Y)},[l,pe,d]),q=o.useCallback(()=>{const w=d.filter(Y=>!Y.completed);w.length!==d.length&&(u(w),pe(l,w))},[l,pe,d]),ge=o.useCallback(w=>{const{active:Y,over:se}=w;if(!se||Y.id===se.id)return;const de=d.findIndex($e=>$e.id===Y.id),Se=d.findIndex($e=>$e.id===se.id);if(de===-1||Se===-1)return;const Pe=_i(Ju(d,de,Se));u(Pe),pe(l,Pe)},[l,pe,d]),X=er(pn(co,{activationConstraint:{distance:8}})),we=p.slice(0,Cn),xe=d.reduce((w,Y)=>w+(Y.completed?1:0),0),Ne=o.useCallback(()=>{Ge("chat"),Le(!1)},[Ge,Le]),pt=o.useCallback((w,Y)=>{!e||x!==null||j({todoId:w,todoText:Y})},[e,x]),gt=o.useCallback(w=>{if(!R){le.error("No active session selected");return}Ne();const Y=`\`\`\`md
|
|
47
|
-
${w}
|
|
48
|
-
\`\`\``;Te(Y,"append"),le.success("Todo sent to current session"),n?.()},[R,n,Ne,Te]),et=o.useCallback(async w=>{if(!e||!O)return;const Y=await Qo("plan.todo.visible",{todo_text:O.todoText}),de=[{synthetic:!0,text:await Qo("plan.todo.instructions",{todo_text:O.todoText})}];y(!0),h(O.todoId);try{Ne();const Se=await V(void 0,e.path,null);if(!Se?.id){le.error("Failed to create session");return}const Pe=Se.id,$e=Se.directory??e.path;oe(Se.id,Ot.getState().agents??[]);const mt=na.getState();mt.saveSessionModelSelection(Pe,w.providerID,w.modelID),w.agent.trim()&&(mt.saveSessionAgentSelection(Pe,w.agent),mt.saveAgentModelForSession(Pe,w.agent,w.providerID,w.modelID),mt.saveAgentModelVariantForSession(Pe,w.agent,w.providerID,w.modelID,w.variant||void 0)),Me(Pe,$e),await $(Y,w.providerID,w.modelID,w.agent.trim()||void 0,void 0,void 0,de,w.variant||void 0),le.success("Todo sent to new session"),j(null),n?.()}catch{le.error("Failed to send note")}finally{y(!1),h(null)}},[V,oe,n,O,e,Ne,$,Me]),De=o.useRef(null),[Fe,Ae]=o.useState(!1),[at,jt]=o.useState(null),st=o.useCallback(async w=>{if(!(!e||at)){jt(w);try{if(!await Fd(e,w)){le.error("Failed to delete plan");return}k(se=>se.filter(de=>de.id!==w)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{jt(null)}}},[at,e]),_=o.useCallback(async()=>{if(!e||Fe)return;const w=await gu({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(w.success&&w.path){Ae(!0);try{const Y=new URLSearchParams({path:w.path,allowOutsideWorkspace:"true"});w.outsideFileGrant&&Y.set("outsideFileGrant",w.outsideFileGrant);const se=await es(`/api/fs/read?${Y.toString()}`,{cache:"no-store"});if(!se.ok){le.error("Failed to read plan file");return}const de=await se.text();if(!de.trim()){le.error("Plan file is empty");return}const Se=w.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Jo(e,de,Se)){le.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),le.success("Plan imported")}catch(Y){const se=Y instanceof Error?Y.message:void 0;le.error("Failed to read plan file",se?{description:se}:void 0)}finally{Ae(!1)}}else w.error==="Native file picker not available"&&De.current?.click()},[Fe,e]),ye=o.useCallback(async w=>{if(!(!e||!w)){Ae(!0);try{const Y=await w.text();if(!Y.trim()){le.error("Plan file is empty");return}const se=w.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Jo(e,Y,se)){le.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),le.success("Plan imported")}catch(Y){const se=Y instanceof Error?Y.message:void 0;le.error("Failed to read plan file",se?{description:se}:void 0)}finally{Ae(!1)}}},[e]),be=o.useCallback(w=>{const Y=e?.path?.trim(),se=Ye?.trim()||Y;se&&Ue(se,{mode:"file",targetPath:w.path,dedupeKey:w.path,label:w.title})},[Ye,Ue,e]);return e?t.jsxs("div",{className:B("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,"/",Xo]})]}),t.jsx(mo,{value:l,onChange:w=>c(w.target.value.slice(0,Xo)),onBlur:Ce,placeholder:"Capture context, reminders, or links",resizedHeight:ee,onResizeHeightChange:Z,useScrollShadow:!0,scrollShadowSize:56,disabled:i})]}),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:q,disabled:i||xe===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:[we.length,"/",Cn]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{value:we,onChange:w=>m(w.target.value.slice(0,Cn)),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),He())},placeholder:"Add a todo",disabled:i,className:"h-8"}),t.jsx("button",{type:"button",onClick:He,disabled:i||we.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(N,{name:"add",className:"h-4 w-4"})})]}),t.jsx("div",{className:B("overflow-y-auto rounded-lg border border-border/60 bg-background/40",ie&&"transition-none"),style:d.length<7?void 0:{height:`${D}px`,maxHeight:`${D}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(tr,{sensors:X,collisionDetection:sr,onDragEnd:ge,children:t.jsx(uo,{items:d.map(w=>w.id),strategy:Ea,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(w=>{const Y=f.has(w.id);return t.jsx(Im,{id:w.id,children:se=>t.jsxs("div",{className:B("flex gap-1.5 px-2.5 py-1.5",Y?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:se.setActivatorNodeRef,...se.attributes,...se.listeners,onClick:de=>{de.preventDefault(),de.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 \\"${w.text}\\"`,title:`Reorder \\"${w.text}\\"`,children:t.jsx(N,{name:"draggable",className:"h-3.5 w-3.5"})}),t.jsx("div",{className:"flex h-6 items-center",children:t.jsx(Zi,{checked:w.completed,onChange:de=>ze(w.id,de),ariaLabel:`Mark \\"${w.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>tt(w.id),className:B("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",Y?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",w.completed&&"text-muted-foreground line-through"),title:Y?void 0:w.text,"aria-label":Y?`Collapse todo \\"${w.text}\\"`:`Expand todo \\"${w.text}\\"`,children:w.text}),t.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:()=>J(w.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 \\"${w.text}\\"`,title:`Delete \\"${w.text}\\"`,children:t.jsx(N,{name:"delete-bin",className:"h-3.5 w-3.5"})}),t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:x===w.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 \\"${w.text}\\"`,title:`Send \\"${w.text}\\"`,children:t.jsx(N,{name:"send-plane",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-56",children:[t.jsx(St,{onClick:()=>gt(w.text),children:"Send to current session"}),t.jsx(St,{onClick:()=>pt(w.id,w.text),children:"Send to new session"})]})]})]})]})},w.id)})})})})}),d.length>=7&&t.jsx("div",{className:B("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",ie&&"bg-[var(--interactive-border)]"),onPointerDown:Ke,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:S.length===1?`${S.length} file`:`${S.length} files`})]}),t.jsx("input",{ref:De,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:w=>{const Y=w.target.files?.[0]??null;ye(Y),w.currentTarget.value=""}}),t.jsx("button",{type:"button",onClick:_,disabled:!e||Fe,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(N,{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:S.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:S.map(w=>t.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[t.jsxs("button",{type:"button",onClick:()=>be(w),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:w.title}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(w.createdAt).toLocaleDateString("en-US")})]}),t.jsx("button",{type:"button",onClick:()=>{st(w.id)},disabled:at===w.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 \\"${w.title}\\"`,children:t.jsx(N,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id))})})]}),t.jsx(Cm,{open:O!==null,onOpenChange:w=>{!w&&!v&&j(null)},projectDirectory:e?.path??null,submitting:v,onConfirm:et})]}):t.jsx("div",{className:B("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."})})},Mx=({onActionComplete:e})=>{const s=zt(c=>c.activeProjectId),n=zt(c=>c.projects),r=Rs(c=>c.homeDirectory),i=o.useMemo(()=>s?n.find(c=>c.id===s)??n[0]??null:n[0]??null,[s,n]),a=o.useMemo(()=>i?{id:i.id,path:i.path}:null,[i]),l=o.useMemo(()=>i?i.label?.trim()||Ms(i.path,r)||i.path:null,[i,r]);return t.jsx("div",{className:"h-full min-h-0 overflow-auto bg-transparent",children:t.jsx(Dm,{projectRef:a,projectLabel:l,onActionComplete:e})})},Gn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Zr=512*1024,Pm=new TextEncoder,Em=new TextDecoder,gr=e=>{const s=Pm.encode(e);if(s.byteLength<=Zr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-Zr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:Em.decode(r),byteLength:r.byteLength}},zs=(e,s)=>`${e}\0${s}`,xr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},Tm="terminal-store";let $i=!1,Ui=0;const Rn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Ui+=1,`tab-${Date.now().toString(36)}-${Ui.toString(36)}`),br=e=>typeof e=="object"&&e!==null,Rm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function _t(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const Mm=/^Terminal(?: (\d+))?$/,Fm=e=>{let s=0;for(const n of e){const r=Mm.exec(n.label);if(!r)continue;const i=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(i)&&(s=Math.max(s,i))}return s===0?"Terminal":`Terminal ${s+1}`},yr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),vr=e=>({tabs:[e],activeTabId:e.id}),is=(e,s)=>e.tabs.findIndex(n=>n.id===s);let wr=null,Sr=null;const Om=e=>{if(Sr&&wr?.sessions===e.sessions&&wr.nextTabId===e.nextTabId)return Sr;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(i=>({id:i.id,label:i.label,iconKey:i.iconKey,createdAt:i.createdAt}))}]),nextTabId:e.nextTabId};return wr={sessions:e.sessions,nextTabId:e.nextTabId},Sr=s,s},Lm=()=>{const e=Hu(()=>xu());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))}},Ee=gs()(Da(lo((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=_t(n);r&&e(i=>{if(i.sessions.has(r))return i;const a=new Map(i.sessions),l=Rn(),c=yr(l,"Terminal");return a.set(r,vr(c)),{sessions:a,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const r=_t(n);return s().sessions.get(r)},getActiveTab:n=>{const r=_t(n),i=s().sessions.get(r);if(!i)return;const a=i.activeTabId;return a?i.tabs.find(l=>l.id===a)??i.tabs[0]:i.tabs[0]},getBuffer:(n,r)=>s().buffers.get(zs(_t(n),r))??Gn,createTab:n=>{const r=_t(n);if(!r)return"tab-invalid";const i=Rn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Fm(c?.tabs??[]),p=yr(i,u);return c?l.set(r,{...c,tabs:[...c.tabs,p]}):l.set(r,vr(p)),{sessions:l,nextTabId:d}}),i},setActiveTab:(n,r)=>{const i=_t(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);return!c||c.activeTabId===r||is(c,r)<0?a:(l.set(i,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,i)=>{const a=_t(n),l=i.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const p=is(u,r);if(p<0||u.tabs[p]?.label===l)return c;const m=[...u.tabs];return m[p]={...m[p],label:l},d.set(a,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(n,r,i)=>{const a=_t(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const p=i?.trim()||null;if(d.tabs[u]?.iconKey===p)return l;const m=[...d.tabs];return m[u]={...m[u],iconKey:p},c.set(a,{...d,tabs:m}),{sessions:c}})},closeTab:(n,r)=>{const i=_t(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=is(c,r);if(d<0)return a;const u=c.tabs.filter(g=>g.id!==r),p=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,g])=>!(g.directory===i&&g.tabId===r))),m=Object.keys(p).length!==Object.keys(a.projectActionRuns).length,x=zs(i,r),h=a.buffers.has(x)?xr(a.buffers,g=>g===x):null;if(u.length===0){const g=Rn(),S=yr(g,"Terminal");return l.set(i,vr(S)),{sessions:l,nextTabId:a.nextTabId+1,...h?{buffers:h}:{},...m?{projectActionRuns:p}:{}}}let f=c.activeTabId;return c.activeTabId===r&&(f=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(i,{...c,tabs:u,activeTabId:f}),{sessions:l,...h?{buffers:h}:{},...m?{projectActionRuns:p}:{}}})},setTabSessionId:(n,r,i)=>{const a=_t(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const p=d.tabs[u],m=i!==null&&p.terminalSessionId!==i,x=i?"running":p.terminalSessionId?"exited":p.lifecycle,h={...p,terminalSessionId:i,lifecycle:x,isConnecting:!1},f=zs(a,r),g=m&&l.buffers.has(f)?xr(l.buffers,k=>k===f):null,S=[...d.tabs];return S[u]=h,c.set(a,{...d,tabs:S}),{sessions:c,...g?{buffers:g}:{}}})},setTabLifecycle:(n,r,i)=>{const a=_t(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const p=[...d.tabs];return p[u]={...p[u],lifecycle:i,isConnecting:!1},c.set(a,{...d,tabs:p}),{sessions:c}})},setConnecting:(n,r,i)=>{const a=_t(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=is(d,r);if(u<0)return l;const p=[...d.tabs];return p[u]={...p[u],isConnecting:i},c.set(a,{...d,tabs:p}),{sessions:c}})},replaceBuffer:(n,r,i,a)=>{const l=_t(n);e(c=>{const d=c.sessions.get(l);if(!d||is(d,r)<0)return c;const u=zs(l,r),p=c.buffers.get(u)??Gn;if(p.lastSequence>a)return c;const m=gr(i);if(p.lastSequence===a&&p.byteLength===m.byteLength&&p.chunks.map(f=>f.data).join("")===m.text)return c;const x=c.nextChunkId,h=new Map(c.buffers);return h.set(u,{chunks:m.text?[{id:x,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:a}),{buffers:h,nextChunkId:m.text?x+1:x}})},appendToBuffer:(n,r,i,a,l)=>{if(!i)return;const c=_t(n);e(d=>{const u=d.sessions.get(c);if(!u||is(u,r)<0)return d;const p=zs(c,r),m=d.buffers.get(p)??Gn;if(a!==void 0&&a<=m.lastSequence)return d;const x=d.nextChunkId,h=gr(i),f=l!==void 0&&l!==i?gr(l).text:void 0,g={id:x,data:h.text,...f!==void 0?{replayData:f}:{},byteLength:h.byteLength},S=[...m.chunks,g];let k=m.byteLength+g.byteLength;for(;k>Zr&&S.length>1;){const j=S.shift();if(!j)break;k-=j.byteLength}const O=new Map(d.buffers);return O.set(p,{chunks:S,byteLength:k,lastSequence:a??m.lastSequence}),{buffers:O,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,i,a={})=>{const l=_t(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const p=is(u,r);if(p<0)return c;const m=u.tabs[p],x=a.autoOpened??m.previewAutoOpened,h=a.locked??m.previewUrlLocked;if(m.previewUrl===i&&m.previewAutoOpened===x&&m.previewUrlLocked===h)return c;const f=[...u.tabs];return f[p]={...m,previewUrl:i,previewAutoOpened:x,previewUrlLocked:h},d.set(l,{...u,tabs:f}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const i=_t(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=is(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const p=[...c.tabs];return p[d]={...u,previewAutoOpened:!0},l.set(i,{...c,tabs:p}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const i=r.projectActionRuns[n.key];return i&&i.directory===n.directory&&i.actionId===n.actionId&&i.tabId===n.tabId&&i.sessionId===n.sessionId&&i.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(i=>{const a=i.projectActionRuns[n];return!a||a.status===r?i:{projectActionRuns:{...i.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const i={...r.projectActionRuns};return delete i[n],{projectActionRuns:i}})},removeDirectory:n=>{const r=_t(n);e(i=>{const a=new Map(i.sessions);a.delete(r);const l=zs(r,""),c=xr(i.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(i.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:Tm,storage:Lm(),partialize:Om,merge:(e,s)=>{if(!br(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let i=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!br(u))continue;const p=Array.isArray(u.tabs)?u.tabs:[],m=[],x=new Map;for(const S of p){if(!br(S))continue;const k=typeof S.id=="string"?S.id:null;if(!k)continue;const O=Rm(k);O!==null&&(i=Math.max(i,O));const j=O===null?k:Rn();x.set(k,j),m.push({id:j,label:typeof S.label=="string"?S.label:"Terminal",iconKey:typeof S.iconKey=="string"?S.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof S.createdAt=="number"?S.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const h=typeof u.activeTabId=="string"?u.activeTabId:null,f=h?x.get(h)??h:null,g=f?m.some(S=>S.id===f):!1;r.set(d,{tabs:m,activeTabId:g?f:m[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,i+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!$i){$i=!0;const e=Ee.persist,s=()=>{Ee.getState().hasHydrated||Ee.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Bm(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 _m(e,s,n,r,i=!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:i}}const jr=["\x1B[0m","\x1B[m"],zm=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 i=r.slice(1,4).map(Number);return i.some(a=>a<0||a>255)?null:i},Gi=e=>{const s=zm(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},$m=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let i=0;const a=Math.max(...jr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);jr.some(p=>p.length>u.length&&p.startsWith(u))&&(i=d)}const l=i>0?r.slice(-i):"";let c=i>0?r.slice(0,-i):r;for(const d of jr)c=c.replaceAll(d,n);return{data:c,carry:l}},Um=(e,s,n,r,i)=>{if(n.width<=0||n.height<=0||r<=0||i<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*i);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(i-1,l))}},Gm=(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 i=n,a=n;for(;i>0&&r(e[i-1]);)i-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:i,endColumn:a}};let Km=null;const Hm=()=>Km??=Ds(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,11])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Wm=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,Wm))]).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 i=r.measureText("M"),a=Math.ceil(i.width),l=Math.ceil((i.actualBoundingBoxAscent||n*.8)+(i.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))}},cl=o.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:i,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:p=!0},m)=>{const x=o.useRef(null),h=o.useRef(null),f=o.useRef(null),g=o.useRef(n),S=o.useRef(r),k=o.useRef(null),O=o.useRef(null),j=o.useRef(null),v=o.useRef(""),y=o.useRef(""),L=o.useRef(Gi(i.background)),A=o.useRef(!1),C=o.useRef(0),I=o.useRef(p),P=o.useRef(!1),[D,W]=o.useState(0),[ee,Z]=o.useState(0);g.current=n,S.current=r,I.current=p,L.current=Gi(i.background),o.useLayoutEffect(()=>{const T=x.current;if(!T)return;const R=Vm(T,a,l);O.current=R,R&&S.current(R.cols,R.rows)},[a,l]);const ie=o.useCallback(()=>{const T=x.current,R=h.current;if(!T||!R||!f.current||!I.current)return;const V=T.getBoundingClientRect();if(!(V.width<24||V.height<24))try{f.current.fit();const oe={cols:R.cols,rows:R.rows};(!k.current||k.current.cols!==oe.cols||k.current.rows!==oe.rows)&&(k.current=oe,S.current(oe.cols,oe.rows)),P.current||(P.current=!0,W($=>$+1))}catch{}},[]),z=o.useCallback(()=>{if(A.current||!v.current||!h.current)return;const T=h.current,R=v.current;v.current="";const V=$m(R,y.current,L.current);if(y.current=V.carry,!V.data){v.current&&z();return}A.current=!0;const oe=C.current;T.write(V.data,()=>{h.current!==T||C.current!==oe||(A.current=!1,v.current&&z())})},[]),U=o.useCallback(()=>{j.current=null,v.current="",y.current="",A.current=!1,C.current+=1;const T=h.current;if(!T){Z(R=>R+1);return}try{T.reset();const R=L.current;R&&T.write(`${R}\x1B[2J\x1B[H`)}catch{Z(R=>R+1)}},[]);return o.useEffect(()=>{const T=x.current;if(!T)return;let R=!1,V=null,oe=null,$=null,Me=null,Te=[];const Ye=()=>{V&&I.current&&(V.options.cursorBlink=!0)},Ue=re=>{re.relatedTarget instanceof Node&&T.contains(re.relatedTarget)||V&&(V.options.cursorBlink=!1)},Ge=()=>{V&&I.current&&T.contains(document.activeElement)&&(V.options.cursorBlink=!0)},Le=()=>{V&&(V.options.cursorBlink=!1)};return T.addEventListener("focusin",Ye),T.addEventListener("focusout",Ue),window.addEventListener("focus",Ge),window.addEventListener("blur",Le),Promise.all([Hm(),Ym()]).then(([{module:re,ghostty:pe}])=>{if(R)return;V=new re.Terminal({..._m(a,l,i,pe,!1),...O.current??{}});const Ke=new re.FitAddon;V.loadAddon(Ke),V.open(T),h.current=V,f.current=Ke,Te=[V.onData(Ce=>g.current(Ce))],oe=new ResizeObserver(()=>{$&&clearTimeout($),$=setTimeout(ie,80)}),oe.observe(T),ie();const ke=L.current;ke&&V.write(`${ke}\x1B[2J\x1B[H`),Me=requestAnimationFrame(ie)}),()=>{R=!0;const re=document.activeElement;re instanceof HTMLElement&&T.contains(re)&&(re.blur(),window.Capacitor?.getPlatform?.()==="android"&&Ds(async()=>{const{Keyboard:Ke}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:Ke}},__vite__mapDeps([113,114])).then(({Keyboard:Ke})=>Ke.hide()).catch(()=>{})),oe?.disconnect(),$&&clearTimeout($),Me!==null&&cancelAnimationFrame(Me),T.removeEventListener("focusin",Ye),T.removeEventListener("focusout",Ue),window.removeEventListener("focus",Ge),window.removeEventListener("blur",Le),Te.forEach(pe=>pe.dispose()),V?.dispose(),h.current=null,f.current=null,k.current=null,j.current=null,v.current="",y.current="",A.current=!1,C.current+=1,P.current=!1}},[ie,a,l,ee,i]),o.useEffect(()=>{const T=h.current,R=x.current;!T||!R||(T.options.cursorBlink=p&&document.hasFocus()&&R.contains(document.activeElement))},[p,D]),o.useEffect(()=>{if(!h.current)return;if(s.length===0){j.current!==null&&U();return}const R=j.current;let V=-1;if(R!==null){for(let Me=s.length-1;Me>=0;Me-=1){const Te=s[Me].id;if(Te===R){V=Me;break}if(Te<R)break}if(V<0){U();return}}const oe=V<0,$=V>=0?s.slice(V+1):s;v.current+=$.map(Me=>oe?Me.replayData??Me.data:Me.data).join(""),j.current=s.at(-1)?.id??null,z()},[s,z,D,U]),o.useEffect(()=>{if(!u||!p)return;const T=requestAnimationFrame(()=>h.current?.focus());return()=>cancelAnimationFrame(T)},[u,p,D,e]),o.useEffect(()=>{const T=x.current;if(!d||!T)return;const R=V=>{const oe=V;if(!oe.isComposing)switch(oe.inputType){case"insertText":oe.data&&g.current(oe.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return T.addEventListener("beforeinput",R),()=>T.removeEventListener("beforeinput",R)},[d,D]),o.useEffect(()=>{const T=x.current,R=h.current;if(!d||!T||!R)return;let V=null,oe=null,$="idle",Me=0,Te=0,Ye=0,Ue=0,Ge=null;const Le=Math.max(12,l+2),re=()=>{window.Capacitor?.getPlatform?.()==="android"&&Ds(async()=>{const{Keyboard:ge}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ge}},__vite__mapDeps([113,114])).then(({Keyboard:ge})=>ge.show()).catch(()=>{})},pe=()=>{oe&&(clearTimeout(oe),oe=null)},Ke=(q,ge)=>{const X=T.querySelector("canvas");return X?Um(q,ge,X.getBoundingClientRect(),R.cols,R.rows):null},ke=(q,ge)=>{const X=T.querySelector("canvas");if(!X)return;const we=X.getBoundingClientRect(),xe=we.left+(ge.column+.5)/R.cols*we.width,Ne=we.top+(ge.row+.5)/R.rows*we.height;X.dispatchEvent(new MouseEvent(q,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:xe,clientY:Ne}))},Ce=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},He=q=>{q.pointerType!=="touch"||V!==null||(V=q.pointerId,$="pending",Me=q.clientX,Te=q.clientY,Ye=q.clientY,Ue=0,Ge=null,T.setPointerCapture(q.pointerId),oe=setTimeout(()=>{if(oe=null,V!==q.pointerId||$!=="pending")return;const ge=Ke(Me,Te);if(!ge)return;const X=R.buffer.active,we=Math.max(0,X.length-R.rows-X.viewportY+ge.row),xe=X.getLine(we),Ne=Array.from({length:R.cols},(et,De)=>xe?.getCell(De)?.getChars()??""),pt=Gm(Ne,ge.column),gt={column:pt.startColumn,row:ge.row};Ge={column:pt.endColumn,row:ge.row},$="selecting",ke("mousedown",gt),ke("mousemove",Ge)},350))},tt=q=>{if(V!==q.pointerId)return;if($==="selecting"){const we=Ke(q.clientX,q.clientY);we&&(!Ge||we.column!==Ge.column||we.row!==Ge.row)&&(Ge=we,ke("mousemove",we)),q.cancelable&&q.preventDefault();return}if($==="pending"){if(Math.hypot(q.clientX-Me,q.clientY-Te)<8)return;pe(),$="scrolling"}if($!=="scrolling")return;const ge=Ye-q.clientY;Ye=q.clientY,Ue+=ge;const X=Math.trunc(Ue/Le);X&&(R.scrollLines(X),Ue-=X*Le),q.cancelable&&q.preventDefault()},ze=q=>{if(V!==q.pointerId)return;const ge=$==="pending",X=$==="selecting";pe(),T.hasPointerCapture(q.pointerId)&&T.releasePointerCapture(q.pointerId),V=null,$="idle",X&&Ce(),ge&&(R.focus(),re())},J=q=>{if(V!==q.pointerId)return;const ge=$==="selecting";pe(),T.hasPointerCapture(q.pointerId)&&T.releasePointerCapture(q.pointerId),V=null,$="idle",ge&&Ce()};return T.addEventListener("pointerdown",He),T.addEventListener("pointermove",tt,{passive:!1}),T.addEventListener("pointerup",ze),T.addEventListener("pointercancel",J),()=>{pe(),T.removeEventListener("pointerdown",He),T.removeEventListener("pointermove",tt),T.removeEventListener("pointerup",ze),T.removeEventListener("pointercancel",J)}},[d,l,D]),o.useImperativeHandle(m,()=>({focus:()=>h.current?.focus(),fit:ie,getSelection:()=>{const T=h.current,R=T?.getSelectionPosition(),V=T?.getSelection()??"";return!R||!V.trim()?null:{text:V,startLine:R.start.y+1,endLine:R.end.y+1}}}),[ie]),t.jsx("div",{ref:x,"data-terminal-owner":"main",className:B("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});cl.displayName="TerminalViewport";const qm=280,Ki=4,Qm=({transform:e})=>({...e,y:0}),Jm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:d}=fo({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:ho.Transform.toString(l),transition:c},className:B("h-full rounded-md",n,d&&"opacity-50"),...r,...i,children:s})},Xm=({id:e,children:s,className:n})=>t.jsx("div",{className:B("h-full",n),"data-sortable-tab-id":e,children:s}),Zm=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:i,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:p,activePillLowercase:m=!0,nonCompositedIndicator:x=!1,className:h})=>{const f=ue(J=>J.isMobile),{isTablet:g}=Fs(),S=f||g,k=o.useRef(null),[O,j]=o.useState({left:!1,right:!1}),v=o.useMemo(()=>e.map(J=>J.id),[e]),y=a==="scrollable",L=l==="default",A=l==="active-pill",I=A||l==="animated",P=L,D=I||P,W=A&&y,ee=I,Z=p??I,ie=typeof i=="function",z=ie?Jm:Xm,U=o.useRef(new Map),[T,R]=o.useState(null),[V,oe]=o.useState(!1),[$,Me]=o.useState(null),Te=o.useRef(!1),Ye=o.useRef(0),Ue=o.useRef(s),Ge=o.useRef(null),Le=o.useMemo(()=>{if(!D||!$||!s||$===s)return 0;const J=e.findIndex(ge=>ge.id===$),q=e.findIndex(ge=>ge.id===s);return J<0||q<0?0:J>q?Ki:-Ki},[s,e,$,D]),re=er(pn(co,{activationConstraint:{distance:8}})),pe=o.useCallback((J,q)=>!J||!q?J===q:Math.abs(J.left-q.left)<.5&&Math.abs(J.top-q.top)<.5&&Math.abs(J.width-q.width)<.5&&Math.abs(J.height-q.height)<.5,[]),Ke=o.useCallback((J,q)=>{if(q){U.current.set(J,q);return}U.current.delete(J)},[]),ke=o.useCallback(()=>{if(!D||!s){R(Ne=>Ne===null?Ne:null);return}const J=k.current,q=U.current.get(s);if(!J||!q){R(Ne=>Ne===null?Ne:null);return}let ge=0,X=0,we=q;for(;we&&we!==J;)ge+=we.offsetLeft,X+=we.offsetTop,we=we.offsetParent;const xe={left:ge,top:X,width:q.offsetWidth,height:q.offsetHeight};R(Ne=>pe(Ne,xe)?Ne:xe)},[s,pe,D]),Ce=o.useCallback(()=>{if(!y){j({left:!1,right:!1});return}const J=k.current;if(!J){j({left:!1,right:!1});return}j({left:J.scrollLeft>2,right:J.scrollLeft+J.clientWidth<J.scrollWidth-2})},[y]);o.useEffect(()=>{if(!y){j({left:!1,right:!1});return}const J=k.current;if(!J)return;Ce(),J.addEventListener("scroll",Ce,{passive:!0});const q=new ResizeObserver(Ce);return q.observe(J),()=>{J.removeEventListener("scroll",Ce),q.disconnect()}},[y,e.length,Ce]),o.useEffect(()=>{if(!D){R(null);return}ke();const J=k.current;if(!J)return;const q=new ResizeObserver(()=>{performance.now()-Ye.current>qm&&oe(!1),ke()});if(q.observe(J),s){const ge=U.current.get(s);ge&&q.observe(ge)}return()=>{q.disconnect()}},[s,e.length,ke,D]),o.useLayoutEffect(()=>{ke()});const He=v.join("\0");o.useLayoutEffect(()=>{if(!D){Te.current=!1,oe(!1);return}const J=Ge.current!==He;if(Ge.current=He,!Te.current){Te.current=!0,Ue.current=s;return}const q=Ue.current!==s;if(Ue.current=s,!q||J){oe(!1);return}Ye.current=performance.now(),oe(!0)},[s,He,D]),o.useEffect(()=>{if(!y||!s)return;const J=k.current;if(!J)return;const q=window.requestAnimationFrame(()=>{const ge=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),X=J.querySelector(`[data-sortable-tab-id="${ge}"]`);X&&(X.scrollIntoView({block:"nearest",inline:"nearest"}),Ce())});return()=>{window.cancelAnimationFrame(q)}},[s,y,e.length,Ce]);const tt=o.useCallback(J=>{if(!i)return;const{active:q,over:ge}=J;!ge||q.id===ge.id||i(String(q.id),String(ge.id))},[i]),ze=t.jsxs("div",{className:B("relative flex h-full min-w-0 flex-1",h),children:[y&&O.left?t.jsx("div",{className:B("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",I?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,y&&O.right?t.jsx("div",{className:B("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",I?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,t.jsxs("div",{ref:k,className:B("relative flex h-full min-w-0 flex-1",I?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",I&&"@container/pill-tabs",I&&"pill-tabs__track",I&&(c??"gap-0.5 py-0.5"),P&&"items-center overflow-y-hidden",ee&&"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",y?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:y?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[I&&T?t.jsx("div",{className:B("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)]",Z&&V&&(x?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:x?{left:`${T.left+Le}px`,top:`${T.top}px`,width:`${T.width}px`,height:`${T.height}px`}:{transform:`translate3d(${T.left+Le}px, ${T.top}px, 0)`,width:`${T.width}px`,height:`${T.height}px`}}):null,P&&T?t.jsx("div",{className:B("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(${T.left+Le}px, 0, 0)`,width:`${T.width}px`},"aria-hidden":!0}):null,e.map(J=>{const q=J.id===s,ge=u&&I&&!q&&!!J.icon,X=!ge,we=!!J.icon,xe=u&&I&&q&&!y&&!W,Ne=J.closable!==!1&&!!r,pt=Ne&&!!J.icon,gt=y||W?void 0:I?xe?"flex-none basis-auto":f?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",et=Ne?Fe=>{Fe.button===1&&(Fe.preventDefault(),Fe.stopPropagation(),r?.(J.id))}:void 0,De=Ne?Fe=>{Fe.button===1&&Fe.preventDefault()}:void 0;return t.jsx(z,{id:J.id,className:gt,children:t.jsxs("div",{ref:Fe=>Ke(J.id,Fe),onAuxClick:et,onMouseDown:De,className:B("group flex h-full min-w-0 flex-nowrap items-center",y||W?"shrink-0":I?"w-full":"w-full min-w-0",I?"relative z-10 bg-transparent":q?"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":q,"aria-label":ge?J.title??J.label:void 0,onClick:()=>n(J.id),onPointerDown:D?()=>{oe(!0),Me(J.id)}:void 0,onPointerUp:D?()=>Me(null):void 0,onPointerLeave:D?()=>Me(null):void 0,onPointerCancel:D?()=>Me(null):void 0,className:B(I?"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",I&&m?"lowercase":null,I&&(ge?"gap-0":"gap-1.5"),I?W?"shrink-0 whitespace-nowrap px-3 text-center":y?"max-w-56 shrink-0 px-3 text-center":ge?"px-2 !min-w-0 text-center":xe?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":y?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",I?d??(A?f?"h-[38px]":"h-[31px]":"h-7"):null,I?q?"text-foreground":"text-muted-foreground hover:text-foreground":null,I?"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:J.title??J.label,children:I?t.jsxs(t.Fragment,{children:[we?t.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[t.jsx("span",{className:B("flex items-center justify-center transition-opacity",pt&&(S?"opacity-0":"group-hover:opacity-0")),children:J.icon}),pt?t.jsx("span",{role:"button",tabIndex:-1,className:B("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",S?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Fe=>{Fe.stopPropagation()},onClick:Fe=>{Fe.stopPropagation(),r?.(J.id)},"aria-label":J.closeLabel??`Close ${J.label} tab`,title:J.closeLabel??`Close ${J.label} tab`,children:t.jsx(N,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,X?t.jsx("span",{className:"animated-tabs__label truncate",children:J.label}):null]}):t.jsxs("span",{className:B("flex min-w-0 flex-nowrap items-center gap-1.5",!y&&"justify-center"),children:[we?t.jsxs("span",{className:B("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",q?"text-[var(--primary-base)]":"text-muted-foreground"),children:[t.jsx("span",{className:B("flex items-center justify-center transition-opacity",pt&&(S?"opacity-0":"group-hover:opacity-0")),children:J.icon}),pt?t.jsx("span",{role:"button",tabIndex:-1,className:B("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",S?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Fe=>{Fe.stopPropagation()},onClick:Fe=>{Fe.stopPropagation(),r?.(J.id)},"aria-label":J.closeLabel??`Close ${J.label} tab`,title:J.closeLabel??`Close ${J.label} tab`,children:t.jsx(N,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,t.jsx("span",{className:"truncate leading-[1.2]",children:J.label})]})}),Ne&&!pt?t.jsx("button",{type:"button",onPointerDown:Fe=>{Fe.stopPropagation()},onClick:Fe=>{Fe.stopPropagation(),r?.(J.id)},className:B("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",I?"-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",I?q?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":q?"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":J.closeLabel??`Close ${J.label} tab`,title:J.closeLabel??`Close ${J.label} tab`,children:t.jsx(N,{name:"close",className:"h-3 w-3"})}):null]})},J.id)})]})]});return ie?t.jsxs(tr,{sensors:re,collisionDetection:sr,onDragEnd:tt,modifiers:[Qm],children:[t.jsx(uo,{items:v,strategy:Xu,children:ze}),t.jsx(Pa,{dropAnimation:null})]}):ze},eg="\x1B",tg=new RegExp(`${eg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),sg=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,ng=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,rg=/Serving HTTP on .*? port (\d{2,5})/i,og=new Set([".",",",";",":","!","?"]),ig=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",i=s.slice(0,-1),a=(i.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(i.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=i;continue}if(og.has(n)){s=s.slice(0,-1);continue}break}return s},Hi=e=>{let s=ig(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},ag=e=>{if(!e)return null;const s=e.replace(tg,""),n=s.match(rg);if(n?.[1]){const i=Number.parseInt(n[1],10);if(Number.isFinite(i)&&i>0&&i<=65535)return`http://127.0.0.1:${i}/`}const r=s.split(`
|
|
49
|
-
`);for(const i of r){if(!ng.test(i))continue;const a=Array.from(i.matchAll(sg));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Hi(c[1])).port}catch{return!1}});return Hi((l??a[0])[1])}return null},lg=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 i=new AbortController,a=window.setTimeout(()=>i.abort(),s);try{const l=await es("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:i.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},cg={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},dg=(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 cg[e]},dl=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},ug=(e,s)=>e&&(s==="ctrl"?dl(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Wi={cols:80,rows:24},Fx=({visible:e})=>{const{terminal:s,runtime:n}=Qn(),{currentTheme:r}=pa(),i=o.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});i.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=Ld(),l=ue(F=>F.terminalFontSize),c=ue(F=>F.terminalShell),d=ue(F=>F.terminalLoginShells.includes(F.terminalShell)),{isMobile:u,isTablet:p,hasTouchOnlyPointer:m}=Fs(),x=u||p,h=(x||m)&&n.platform==="web",f=!0,g=ue(F=>F.showTerminalQuickKeysOnDesktop),S=x||g,k=_e(F=>F.currentSessionId),O=_e(F=>F.newSessionDraft),j=k!==null||O?.open===!0,v=Bd()??null,y=Ee(F=>v?F.sessions.get(v):void 0),L=Ee(F=>F.hasHydrated),A=Ee(F=>F.ensureDirectory),C=Ee(F=>F.createTab),I=Ee(F=>F.setActiveTab),P=Ee(F=>F.closeTab),D=Ee(F=>F.setTabSessionId),W=Ee(F=>F.setTabLifecycle),ee=Ee(F=>F.setConnecting),Z=Ee(F=>F.appendToBuffer),ie=Ee(F=>F.replaceBuffer),z=Ee(F=>F.setTabPreviewUrl),U=ia(F=>F.addDraft),T=ue(F=>F.openContextPreview),R=o.useMemo(()=>y?y.activeTabId??y.tabs[0]?.id??null:null,[y,f]),V=o.useMemo(()=>{if(y)return R?y.tabs.find(F=>F.id===R)??y.tabs[0]:y.tabs[0]},[y,R]),oe=o.useMemo(()=>(y?.tabs??[]).map(F=>({icon:(()=>{const ae=F.iconKey?dn[F.iconKey]??"terminal":"terminal";return t.jsx(N,{name:ae,className:"h-4 w-4"})})(),id:F.id,label:F.label,title:F.label,closeLabel:"Close tab"})),[y?.tabs]),$=V?.terminalSessionId??null,Me=V?.lifecycle??"idle",Te=Ee(F=>v&&R?F.getBuffer(v,R).chunks:Gn.chunks),Ye=V?.isConnecting??!1,Ue=V?.previewUrl??null,[Ge,Le]=o.useState(null),[re,pe]=o.useState(!1),[Ke,ke]=o.useState(!1),[Ce,He]=o.useState(null),[tt,ze]=o.useState(!1),J=o.useRef(null),q=o.useRef(null),ge=o.useRef(R),X=o.useRef($),we=o.useRef(v),xe=o.useRef(null),Ne=o.useRef(null),pt=o.useRef(new Set),gt=o.useRef(""),et=o.useRef(new Set),De=o.useRef(0),Fe=o.useCallback(()=>{gt.current="",et.current.clear(),De.current+=1},[]),Ae=o.useCallback(()=>{h||typeof document<"u"&&!document.hasFocus()||xe.current?.focus()},[h]),at=o.useCallback(()=>{h||xe.current?.focus()},[h]),st=ue(F=>F.activeMainTab)==="terminal",_=e??st,[ye,be]=o.useState(_);o.useEffect(()=>{_&&be(!0)},[_]),o.useEffect(()=>{X.current=$},[$]),o.useEffect(()=>{!$||!s.updateAppearance||s.updateAppearance($,i.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,$]),o.useEffect(()=>{ge.current=R,Fe()},[R,Fe]),o.useEffect(()=>{we.current=v},[v]),o.useEffect(()=>{!S&&Ce!==null&&He(null)},[S,Ce,He]),o.useEffect(()=>{!$&&Ce!==null&&He(null)},[$,Ce,He]);const w=o.useCallback(()=>{J.current?.(),J.current=null,q.current=null,ke(!1)},[]);o.useEffect(()=>()=>{w(),X.current=null},[w]);const Y=o.useCallback((F,ae,me)=>{if(!me)return;const nt=`${gt.current}${me}`.replace(/\r\n|\r/g,`
|
|
50
|
-
`),ve=nt.split(`
|
|
51
|
-
`),Je=nt.endsWith(`
|
|
52
|
-
`)?ve.join(`
|
|
53
|
-
`):ve.slice(0,-1).join(`
|
|
54
|
-
`);if(gt.current=nt.endsWith(`
|
|
55
|
-
`)?"":(ve[ve.length-1]??"").slice(-1024),!Je)return;const yt=ag(Je);if(!yt||et.current.has(yt))return;const Ft=De.current;et.current.add(yt),lg(yt).then(Lt=>{if(et.current.delete(yt),!Lt||De.current!==Ft)return;const kt=Ee.getState().getDirectoryState(F)?.tabs.find(Ut=>Ut.id===ae);!kt||kt.previewUrlLocked||kt.previewUrl===yt||z(F,ae,yt,{locked:!1,autoOpened:!1})})},[z]),se=o.useCallback((F,ae,me)=>{if(q.current===me)return;w(),q.current=me;const nt=s.connect(me,{onEvent:ve=>{if(q.current===me)switch(ve.type){case"snapshot":{ee(F,ae,!1),Le(null),pe(!1),ke(!1),Ae(),ie(F,ae,ve.data??"",ve.sequence??0),Y(F,ae,ve.data??""),ve.status==="exited"&&W(F,ae,"exited");break}case"reconnecting":{Le(null),pe(!1),ke(!0);break}case"data":{ve.data&&(Z(F,ae,ve.data,ve.sequence,ve.replayData),Y(F,ae,ve.data));break}case"exit":{const Je=typeof ve.exitCode=="number"?ve.exitCode:null,yt=typeof ve.signal=="number"?ve.signal:null,Lt=!!Ee.getState().getDirectoryState(F)?.tabs.find(kt=>kt.id===ae)?.label?.startsWith("Action:");Z(F,ae,`\\r\\n[Process exited${Je!==null?` with code ${Je}`:""}${yt!==null?` (signal ${yt})`:""}]\\r\\n`),W(F,ae,"exited"),ee(F,ae,!1),Le(Lt?null:"Terminal session ended"),pe(!1),ke(!1),w();break}}},onError:(ve,Je)=>{if(q.current===me){if(!Je){Le(null),pe(!1);return}if(ke(!1),ve.code==="SESSION_NOT_FOUND"&&!Ee.getState().getDirectoryState(F)?.tabs.find(Ft=>Ft.id===ae)?.label?.startsWith("Action:")){Le(null),pe(!1),ee(F,ae,!1),D(F,ae,null),W(F,ae,"idle"),w();return}Le(`Connection failed: ${ve.message}`),pe(!0),ee(F,ae,!1),W(F,ae,"exited"),D(F,ae,null),w()}}});J.current=()=>{nt.close(),q.current=null}},[Z,ie,w,Ae,Y,ee,W,D,s]);o.useEffect(()=>{let F=!1;if(!L||!ye)return;if(!v){Le(j?"No working directory available for terminal.":"Select a session to open the terminal."),w();return}return(async()=>{const me=v;if(!we.current||we.current!==me)return;if(!Ee.getState().getDirectoryState(me)){A(me);return}const ve=Ee.getState().getDirectoryState(me);if(!ve||ve.tabs.length===0)return;const Je=ve.activeTabId??ve.tabs[0]?.id??null;if(!Je)return;const yt=ve.tabs.find(vt=>vt.id===Je)??ve.tabs[0],Ft=yt?.terminalSessionId??null,Lt=yt?.lifecycle??"idle",kt=!!yt?.label?.startsWith("Action:"),Ut=Ee.getState().getBuffer(me,Je),Rt=Ut.byteLength>0||Ut.chunks.length>0;if(!Ft){if(Lt==="exited"){ee(me,Je,!1);return}if(kt&&Rt){ee(me,Je,!1);return}const vt=`${me}\0${Je}`;if(pt.current.has(vt))return;const Wt=Ne.current??Wi;pt.current.add(vt),Le(null),pe(!1),ke(!1),ee(me,Je,!0);try{const G=await s.createSession({cwd:me,sessionId:Je,cols:Wt.cols,rows:Wt.rows,shell:c,loginShell:d,...i.current}),te=!F&&we.current===me&&ge.current===Je;if(!Ee.getState().getDirectoryState(me)?.tabs.find(fe=>fe.id===Je)){try{await s.close(G.sessionId)}catch{}return}if(D(me,Je,G.sessionId),!te)return;const ce=Ne.current;ce&&(ce.cols!==Wt.cols||ce.rows!==Wt.rows)&&s.resize({sessionId:G.sessionId,...ce}).catch(()=>{});return}catch(G){const te=Ee.getState().getDirectoryState(me)?.tabs.find(ne=>ne.id===Je);if(!te||te.terminalSessionId||(ee(me,Je,!1),we.current!==me||ge.current!==Je))return;Le(G instanceof Error?G.message:"Failed to start terminal session"),pe(!0),ke(!1);return}finally{pt.current.delete(vt)}}!Ft||F||(X.current=Ft,se(me,Je,Ft))})(),()=>{F=!0,X.current=null,w()}},[j,v,$,Me,R,ye,f,L,A,ee,W,D,se,w,s,d,c]),o.useEffect(()=>{if(!_||h)return;if(typeof window>"u"){Ae();return}const F=window.requestAnimationFrame(()=>{Ae()});return()=>{window.cancelAnimationFrame(F)}},[R,Ae,_,h]);const de=o.useCallback(async()=>{if(!v||tt)return;const F=Ee.getState().getDirectoryState(v),ae=R??F?.activeTabId??F?.tabs[0]?.id??null;if(!ae)return;const me=F?.tabs.find(nt=>nt.id===ae)?.terminalSessionId??null;if(!(!me||!s.restartSession)){ze(!0),Le(null),pe(!1),ke(!1),w(),Fe();try{const nt=Ne.current??Wi,ve=await s.restartSession(me,{cwd:v,shell:c,loginShell:d,...nt,...i.current});if(Ee.getState().getDirectoryState(v)?.tabs.find(yt=>yt.id===ae)?.terminalSessionId!==me||(D(v,ae,ve.sessionId),W(v,ae,"running"),we.current!==v||ge.current!==ae))return;X.current=ve.sessionId,se(v,ae,ve.sessionId)}catch(nt){if(Ee.getState().getDirectoryState(v)?.tabs.find(Je=>Je.id===ae)?.terminalSessionId!==me||we.current!==v||ge.current!==ae)return;Le(nt instanceof Error?nt.message:"Failed to restart terminal"),pe(!1),ke(!1),X.current=me,se(v,ae,me)}finally{ze(!1)}}},[R,w,v,f,tt,Fe,W,D,se,s,d,c]),Se=o.useCallback(async()=>{await de()},[de]),Pe=o.useCallback(()=>{if(!v)return;const F=C(v);I(v,F),Le(null),pe(!1),ke(!1),w()},[C,w,v,I]),$e=o.useCallback(()=>{const F=xe.current?.getSelection(),ae=k??(O?.open?"draft":null);!F||!ae||!V||!v||U({directory:v,sessionKey:ae},{source:"terminal",fileLabel:V.label,startLine:F.startLine,endLine:F.endLine,code:F.text,language:V.terminalSessionId??V.id,text:""})},[V,U,k,v,O?.open]),mt=o.useCallback(F=>{v&&(I(v,F),Le(null),pe(!1),ke(!1),w())},[w,v,I]),Ct=o.useCallback(F=>{if(!v)return;F===R&&w(),Le(null),pe(!1),ke(!1);const ae=Ee.getState().getDirectoryState(v)?.tabs.find(me=>me.id===F)?.terminalSessionId;(async()=>{ae&&await s.close(ae),P(v,F)})().catch(me=>Le(me instanceof Error?me.message:"Terminal session ended"))},[R,P,w,v,s]),Xe=o.useCallback(F=>{if(!F||Ke)return;let ae=F,me=!1;Ce&&F.length>0&&(ae=ug(F,Ce),me=!0);const nt=X.current;nt&&(s.sendInput(nt,ae).catch(ve=>{Ke||Le(ve instanceof Error?ve.message:"Failed to send input")}),me&&(He(null),at()))},[Ce,at,Ke,He,s]),ct=o.useCallback((F,ae)=>{const me=Ne.current;if((!me||me.cols!==F||me.rows!==ae)&&(Ne.current={cols:F,rows:ae}),!_)return;const nt=X.current;nt&&s.resize({sessionId:nt,cols:F,rows:ae}).catch(()=>{})},[_,s]),xt=o.useCallback(F=>{He(ae=>ae===F?null:F),at()},[at,He]),Oe=o.useCallback(F=>{const ae=dg(F,Ce);ae&&(Xe(ae),He(null),at())},[Ce,at,Xe,He]),We=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),bt=o.useCallback(F=>{if(F.repeat)return;const ae=F.key;if(!ae||ae==="Control"||ae==="Meta"||ae==="Alt"||ae==="Shift")return;const me=ae.length===1?ae.toLowerCase():ae;if(me in We){F.preventDefault(),F.stopPropagation(),Oe(We[me]);return}if(Ce!=="ctrl")return;const nt=F.code??"",ve=ae.length===1&&/[a-zA-Z]/.test(ae)?ae.toUpperCase():nt.startsWith("Key")&&nt.length===4?nt.slice(3).toUpperCase():null;if(ve&&ve.length===1&&ve>="A"&&ve<="Z"){const Je=dl(ve);if(!Je)return;F.preventDefault(),F.stopPropagation(),Xe(Je),He(null),at()}},[Ce,at,Oe,Xe,We,He]);o.useEffect(()=>{if(!(!S||!Ce||!$))return window.addEventListener("keydown",bt),()=>window.removeEventListener("keydown",bt)},[Ce,bt,S,$]);const Mt=o.useMemo(()=>{const F=en[cr].stack;if(typeof window>"u")return(en[a]??en[cr]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(en[a]??en[cr]).stack??F},[a]),$t=o.useMemo(()=>Bm(r),[r]),Nt=`${v??"no-dir"}::${R??"no-tab"}`;if(o.useEffect(()=>{if(!_||h)return;const F=xe.current;if(!F)return;const ae=()=>{F.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{ae(),Ae()}),nt=[220,400].map(ve=>window.setTimeout(ae,ve));return()=>{window.cancelAnimationFrame(me),nt.forEach(ve=>window.clearTimeout(ve))}}ae()},[Ae,_,h,Nt,$]),o.useEffect(()=>{if(!_||!h)return;let F=null;const ae=()=>{F!==null&&window.cancelAnimationFrame(F),F=window.requestAnimationFrame(()=>{F=null,xe.current?.fit()})};return window.addEventListener("oc:keyboard-settled",ae),()=>{window.removeEventListener("oc:keyboard-settled",ae),F!==null&&window.cancelAnimationFrame(F)}},[_,Nt,h]),!j)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(!v)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:de,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const At=!$||Ye||tt||Ke,It=ye,M=x?"lg":"xs",je=x?"w-10 p-0":"w-9 p-0",Be=F=>{x&&F.preventDefault()},dt=t.jsxs(t.Fragment,{children:[t.jsx(Qe,{type:"button",size:M,variant:"outline",onPointerDown:Be,onClick:()=>Oe("esc"),disabled:At,children:"Esc"}),t.jsxs(Qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Oe("tab"),disabled:At,children:[t.jsx(N,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"chip","aria-pressed":Ce==="ctrl",className:x?"px-3":"px-2",onPointerDown:Be,onClick:()=>xt("ctrl"),disabled:At,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"chip","aria-pressed":Ce==="alt",className:x?"px-3":"px-2",onPointerDown:Be,onClick:()=>xt("alt"),disabled:At,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Oe("arrow-up"),disabled:At,children:[t.jsx(N,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Oe("arrow-left"),disabled:At,children:[t.jsx(N,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Oe("arrow-down"),disabled:At,children:[t.jsx(N,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Oe("arrow-right"),disabled:At,children:[t.jsx(N,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Oe("enter"),disabled:At,children:[t.jsx(N,{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:B("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[y?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:B("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(Zm,{items:oe,activeId:R,onSelect:mt,onClose:Ct,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Qe,{type:"button",size:"xs",variant:"ghost",className:B("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Pe,title:"New tab",children:t.jsx(N,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Qe,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{de()},disabled:tt,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(N,{name:"restart",className:"h-4 w-4"})}),t.jsx(Qe,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:$e,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(N,{name:"attachment-2",className:"h-4 w-4"})}),Ue?t.jsxs(Qe,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{v&&T(v,Ue)},title:"Open preview pane",children:[t.jsx(N,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&S&&f&&y?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:dt}):null,!x&&S&&!y?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:dt}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:$t.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:It?t.jsx(cl,{ref:F=>{xe.current=F},sessionKey:Nt,chunks:Te,onInput:Xe,onResize:ct,theme:$t,fontFamily:Mt,fontSize:l,enableTouchScroll:h,autoFocus:_,isVisible:_},Nt):null}),!Ke&&Ge&&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:Ge}),re&&x&&t.jsx(Qe,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Se,disabled:tt,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&S?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","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:dt})}):null]})},fg=gs(()=>({statusById:new Map})),Ox=()=>{va(),ma()},Lx=e=>{_e.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ue.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),va(),Ee.getState().clearAll(),Rs.getState().resetForRuntimeSwitch(),Ot.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),zt.getState().resetForRuntimeSwitch(),_d.getState().resetForRuntimeSwitch(),fg.setState({statusById:new Map}),zd(),$d(),Zu.getState().reset(),bu.getState().resetForRuntimeSwitch(),oa.getState().resetForRuntimeSwitch(e.runtimeKey),ha.getState().resetForRuntimeSwitch(e.runtimeKey),gp.getState().resetForRuntimeSwitch(),Kt.getState().resetForRuntimeSwitch(e.runtimeKey),yu.getState().resetForRuntimeSwitch(e.runtimeKey),_e.getState().restoreForRuntimeSwitch(e.runtimeKey),ue.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=ue.getState();Gr({sessionId:_e.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),ma()},hg=48,pg=96,qt=(e,...s)=>{try{e?.(...s)}catch{}},Cr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Bx=(e,s)=>{const n=o.useRef(s);n.current=s;const r=s.enabled;o.useEffect(()=>{const i=e.current;if(!i||r===!1)return;const a=i.style.touchAction;i.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?pg:hg;let d=!1,u=!1,p=!1,m=null,x=!1,h=0,f=0,g=0,S=0;const k=()=>{d=!1,u=!1,p=!1,m=null},O=()=>{const I=n.current,P=m,D=x;u&&P&&(qt(P==="left"?I.onLeftProgress:I.onRightProgress,D?1:0),qt(I.onDragEnd,P,D)),k()},j=()=>{O(),u||k()},v=I=>{const P=n.current;if(P.enabled===!1){u&&m?O():k();return}if(I.touches.length!==1){u&&m?O():k();return}const D=I.touches[0],W=i.getBoundingClientRect(),ee=i.clientWidth,Z=!!P.leftOpen,ie=!!P.rightOpen,z=U=>Sm(U,i);if(Z||ie){if(z(I.target)){k();return}if(Z&&ie){const U=D.clientX<=W.left+c;D.clientX>=W.right-c?(m="right",x=!0):U?(m="left",x=!0):(m=Z?"left":"right",x=!0)}else Z?(m="left",x=!0):(m="right",x=!0);S=Cr(m==="left"?P.leftWidth:P.rightWidth,ee),S<10&&(S=ee||window.innerWidth||320),S<10&&(S=320),d=!0}else{if(z(I.target)){k();return}m=null,x=!1,S=0,d=!0}h=D.clientX,f=D.clientY,g=Date.now(),u=!1,p=!1},y=I=>{if(!d)return;if(I.touches.length!==1){j();return}const P=I.touches[0],D=P.clientX-h,W=P.clientY-f;if(!p){if(Math.abs(D)<Oi&&Math.abs(W)<Oi)return;if(Math.abs(W)>Math.abs(D)*sn){k();return}if(!m){const ie=n.current;m=D>0?"left":"right",S=Cr(m==="left"?ie.leftWidth:ie.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(m==="left"){if(!x&&D<=0){k();return}if(x&&D>=0){k();return}}else{if(!x&&D>=0){k();return}if(x&&D<=0){k();return}}p=!0,u=!0,qt(n.current.onDragStart,m)}if(!u)return;I.cancelable&&I.preventDefault();const ee=n.current,Z=Li(m,x,D,S);qt(m==="left"?ee.onLeftProgress:ee.onRightProgress,Z)},L=(I,P)=>{if(!d){k();return}const D=I-h,W=P-f;if(!m&&!x&&Math.abs(D)>=$n&&Math.abs(W)<=Math.abs(D)*sn){const T=n.current;m=D>0?"left":"right",S=Cr(m==="left"?T.leftWidth:T.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(!m){k();return}const ee=Math.max(1,Date.now()-g),Z=n.current;if(!u){const T=Math.abs(D),R=Math.abs(W);T>=$n&&R<=T*sn?m==="left"&&!x&&D>0?(qt(Z.onLeftProgress,1),qt(Z.onLeftOpen)):m==="right"&&!x&&D<0?(qt(Z.onRightProgress,1),qt(Z.onRightOpen)):qt(m==="left"?Z.onLeftProgress:Z.onRightProgress,x?1:0):qt(m==="left"?Z.onLeftProgress:Z.onRightProgress,x?1:0);const V=m;k(),qt(Z.onDragEnd,V);return}const ie=Li(m,x,D,S),z=vm({side:m,isOpenAtStart:x,dx:D,dt:ee,progress:ie}),U=m;qt(U==="left"?z?Z.onLeftOpen:Z.onLeftClose:z?Z.onRightOpen:Z.onRightClose),k(),qt(Z.onDragEnd,U,z)},A=I=>{const P=I.changedTouches[0];if(!P){k();return}const D=P.clientX-h,W=P.clientY-f;d&&(u||Math.abs(D)>=$n&&Math.abs(W)<=Math.abs(D)*sn)&&I.cancelable&&I.preventDefault(),L(P.clientX,P.clientY)},C=()=>{j()};return i.addEventListener("touchstart",v,{passive:!0}),i.addEventListener("touchmove",y,{passive:!1}),i.addEventListener("touchend",A,{passive:!1}),i.addEventListener("touchcancel",C,{passive:!0}),()=>{try{u&&m&&O()}catch{}i.style.touchAction=a,i.removeEventListener("touchstart",v),i.removeEventListener("touchmove",y),i.removeEventListener("touchend",A),i.removeEventListener("touchcancel",C)}},[e,r])};function _x({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(N,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Yi({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const kr=()=>Is.filter(e=>Lr.has(e.id)).map(e=>({...wa(e)})),mg=()=>{if(typeof window>"u")return Br;const e=window.localStorage.getItem("openInAppId");return e&&Or(e)?e:Br};let Nr=!1,$s=!1,ys=!1,vs=0,un=null;const Vi=()=>{un&&(clearTimeout(un),un=null)},ks=gs()((e,s)=>({selectedAppId:mg(),availableApps:kr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Nr||typeof window>"u")return;Nr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:kr(),hasLoadedApps:u});return}const p=new Set(d.map(f=>f.name)),m=new Map(d.map(f=>[f.name,f.iconDataUrl??void 0])),h=Is.filter(f=>p.has(f.appName)||Lr.has(f.id)).map(f=>({...wa(f),iconDataUrl:m.get(f.appName)}));e({availableApps:h,hasLoadedApps:!0})},r=async d=>{if(!ws()||!hn()||$s||s().hasLoadedApps&&!d)return;const p=Is.map(m=>m.appName);Vi(),$s=!0,ys=!1,e({isScanning:!0});try{const{apps:m,success:x,hasCache:h,isCacheStale:f}=await si(p,d),g=x&&!h&&m.length===0&&vs<3;if(e({isCacheStale:h?f:!1}),n(m,x?!g:!1),x){if(g){const k=[800,1600,3200][vs]??3200;vs+=1,ys=!0,un=setTimeout(()=>{r()},k);return}vs=0,ys=!1;return}if(vs<3){const k=[1e3,3e3,7e3][vs]??7e3;vs+=1,ys=!0,un=setTimeout(()=>{r()},k)}}finally{$s=!1,ys||e({isScanning:!1})}};r();const i=d=>{const u=d.detail,p=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Or(u.openInAppId)?u.openInAppId:null;p&&(window.localStorage.setItem("openInAppId",p),e({selectedAppId:p}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(vs=3,ys=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",i),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Nr||s().initialize(),!ws()||!hn()||$s||s().hasLoadedApps&&!n)return;const i=Is.map(a=>a.appName);Vi(),n&&e({hasLoadedApps:!1}),$s=!0,ys=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await si(i,n),d=new Set(a.map(x=>x.name)),u=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),m=Is.filter(x=>d.has(x.appName)||Lr.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:m.length>0?m:kr(),hasLoadedApps:m.length>0,isCacheStale:l?c:!1})}finally{$s=!1,ys||e({isScanning:!1})}},selectApp:async n=>{Or(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await no({openInAppId:n}))}})),gg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",xg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",Ar=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?gg:e.id==="terminal"?xg:void 0}),qi=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,i]=o.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>i(!0)}):t.jsx("span",{className:B("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},bg=({directory:e,className:s})=>{const n=ks(f=>f.selectedAppId),r=ks(f=>f.availableApps),i=ks(f=>f.isCacheStale),a=ks(f=>f.isScanning),l=ks(f=>f.initialize),c=ks(f=>f.loadInstalledApps),d=ks(f=>f.selectApp);o.useEffect(()=>{l()},[l]);const u=ws()&&hn(),p=o.useMemo(()=>{const f=r.find(g=>g.id===n)??r.find(g=>g.id===Br)??r[0]??Is[0];return Ar(f||Is[0])},[r,n]);if(!u||!e||r.length===0)return null;const m=async f=>{await vu(e,f.id,f.appName)||await ba(e,f.appName)},x=async f=>{await d(f.id),await m(f)},h=async()=>{(await fn(e)).ok&&le.success("Path copied to clipboard")};return t.jsxs("div",{className:B("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{m(p)},className:B("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${p.label}`,children:t.jsx(qi,{label:p.label,iconDataUrl:p.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl})}),t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(N,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(St,{className:"flex items-center gap-2",onClick:()=>{h()},children:[t.jsx(N,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Ys,{}),r.map(f=>{const g=Ar(f);return t.jsxs(St,{className:"flex items-center gap-2",onClick:()=>{x(f)},children:[t.jsx(qi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:g.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:f.label}),p.id===f.id?t.jsx(N,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},f.id)}),i?t.jsxs(St,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(N,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},yg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],vg=["dev","start","preview","serve"];async function wg(e,s,n){if(!e)return null;const r=Cg(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=kg(n);if(i){const a=await Ng(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${i}`,label:`Start (${i})`}}}if(await Sg(e)){const i=await jg(),a=typeof i=="number"&&Number.isFinite(i)&&i>0?i:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function Sg(e){const s=`${e}/index.html`,n=await qn(s,e);return typeof n=="string"&&n.trim().length>0}async function jg(){try{const e=await es("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Cg(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(vg.some(i=>n.includes(i)))return s}return null}function kg(e){for(const{pattern:s}of yg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Ng(e){const s=await qn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),i=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(i.startsWith("bun@"))return"bun";if(i.startsWith("pnpm@"))return"pnpm";if(i.startsWith("yarn@"))return"yarn";if(i.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,i]of n){const a=await qn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function qn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),i=await es(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=ro()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await es(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Ag(e){try{const s=await qn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Ig=(e,s,n)=>new Promise(r=>{let i=!1,a=null,l=null;const c=d=>{i||(i=!0,l&&clearTimeout(l),a?.close(),r(d))};a=e.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),i?a.close():l=setTimeout(()=>c(!1),n)}),Dg="\x1B",Pg=new RegExp(`${Dg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Eg=/https?:\/\/[^\s<>'"`]+/gi,Zt="__pichamber_auto_discover_preview__",Tg=15e3,Rg=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},Mg=e=>{const s=(e||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Fg=e=>{const n=e.replace(Pg,"").match(Eg);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const i=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&i.push({raw:a,parsed:l})}catch{}if(i.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",p=c.pathname||"/",m=p.split("/").filter(Boolean).length,x=p==="/"||p==="",h=!!(c.search||c.hash);let f=0;return u&&(f+=50),x&&(f+=30),f-=Math.min(m*5,20),h&&(f-=10),f};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},Qi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=pa(),{terminal:l}=Qn(),{isMobile:c}=Fs(),d=o.useMemo(()=>ws(),[]),u=Kn(_=>_.instances),p=Kn(_=>_.load),m=ue(_=>_.terminalShell),x=ue(_=>_.terminalLoginShells.includes(_.terminalShell)),h=ue(_=>_.setSettingsPage),f=ue(_=>_.setSettingsDialogOpen),g=ue(_=>_.setSettingsProjectsSelectedId),S=ue(_=>_.openContextPreview),k=Ee(_=>_.ensureDirectory),O=Ee(_=>_.setTabLabel),j=Ee(_=>_.setTabIconKey),v=Ee(_=>_.setActiveTab),y=Ee(_=>_.setConnecting),L=Ee(_=>_.setTabSessionId),A=Ee(_=>_.setTabPreviewUrl),C=Ee(_=>_.projectActionRuns),I=Ee(_=>_.setProjectActionRun),P=Ee(_=>_.updateProjectActionRunStatus),D=Ee(_=>_.removeProjectActionRun),[W,ee]=o.useState([]),[Z,ie]=o.useState(null),[z,U]=o.useState(!1),T=o.useRef({}),R=o.useRef({}),V=o.useRef({}),oe=o.useRef({}),$=o.useRef(new Set),Me=o.useRef(0),Te=e?.id??null,Ye=e?.path??"",Ue=o.useMemo(()=>Te?{id:Te,path:Ye}:null,[Te,Ye]);o.useEffect(()=>{d&&p().catch(()=>{})},[d,p]);const Ge=o.useCallback(async _=>{await Xi(_)},[]),Le=o.useCallback(async()=>{if(!Ue)return;const _=Me.current+1;Me.current=_,U(!0);try{const ye=await Ir(Ue);if(Me.current!==_)return;const be=ye.actions;ee(be),ie(w=>w===Zt||w&&be.some(Y=>Y.id===w)?w:null)}catch{if(Me.current!==_)return}finally{Me.current===_&&U(!1)}},[Ue]),re=o.useMemo(()=>za(s||Ue?.path||""),[s,Ue?.path]),pe=o.useMemo(()=>Z?W.find(_=>_.id===Z)??null:null,[W,Z]),Ke=o.useMemo(()=>({id:Zt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),ke=!c,Ce=o.useMemo(()=>ke?[Ke,...W]:W,[W,Ke,ke]);o.useEffect(()=>{Le()},[Le]),o.useEffect(()=>{if(typeof window>"u")return;const _=ye=>{const be=ye.detail;Te&&(be?.projectId&&be.projectId!==Te||Le())};return window.addEventListener(Wr,_),()=>{window.removeEventListener(Wr,_)}},[Le,Te]),o.useEffect(()=>{Z&&(Z===Zt&&ke||W.some(_=>_.id===Z)||ie(null))},[W,ke,Z]),o.useEffect(()=>{const _=()=>{const ye=Ee.getState(),be=ye.sessions,w=ye.projectActionRuns;for(const[Y,se]of Object.entries(w)){const Se=be.get(se.directory)?.tabs.find(We=>We.id===se.tabId);if(!Se||Se.terminalSessionId!==se.sessionId){D(Y);continue}const Pe=R.current[Y]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};R.current[Y]=Pe;const $e=Ce.find(We=>We.id===se.actionId),mt=ye.getBuffer(se.directory,se.tabId).chunks;if(!$e||mt.length===0)continue;const Ct=mt.filter(We=>Pe.lastSeenChunkId===null||We.id>Pe.lastSeenChunkId);if(Ct.length===0)continue;const Xe=Ct.map(We=>We.data).join(""),ct=`${Pe.tail}${Xe}`,xt=!Pe.openedUrl&&$e.autoOpenUrl===!0?Fg(ct):null,Oe=Ct[Ct.length-1]?.id??Pe.lastSeenChunkId;if(Pe.lastSeenChunkId=Oe,Pe.tail=ct.slice(-512),xt)if(Pe.openedUrl=!0,Pe.openInPreview){const We=w[Y];We&&(A(We.directory,We.tabId,xt,{locked:!1,autoOpened:!1}),We.status==="waiting-for-preview"&&P(Y,"running"),window.clearTimeout(oe.current[Y]),delete oe.current[Y],S(We.directory,xt))}else Ge(xt),le.success("Opened URL from action output");R.current[Y]=Pe}for(const Y of Object.keys(R.current))w[Y]||(delete R.current[Y],window.clearTimeout(oe.current[Y]),delete oe.current[Y])};return _(),Ee.subscribe((ye,be)=>{(ye.sessions!==be.sessions||ye.buffers!==be.buffers)&&_()})},[Ce,S,Ge,C,D,A,P]);const He=o.useCallback(async(_,ye={})=>{if(!re)throw new Error("No active directory");const be=hs(re,_.id);k(re);const w=Ee.getState(),Y=w.getDirectoryState(re);let se=T.current[be]||null;const de=se?!!Y?.tabs.some($e=>$e.id===se):!1;(!se||!de)&&(se=w.createTab(re),T.current[be]=se),O(re,se,`Action: ${_.name}`),j(re,se,_.icon||"play"),v(re,se),ye.revealTerminal!==!1&&ue.getState().openContextPanelTab(re,{mode:"terminal"});const Pe=Ee.getState().getDirectoryState(re)?.tabs.find($e=>$e.id===se);return{key:be,tabId:se,sessionId:Pe?.terminalSessionId??null}},[k,re,v,j,O]),tt=o.useCallback(async _=>{if(!i&&c)return;if(!re){le.error("No active directory for action");return}const ye=hs(re,_.id),be=C[ye];if(!(be&&be.status==="running")&&!$.current.has(ye)){$.current.add(ye);try{const w=_.id===Zt?await(async()=>{const[Oe,We]=await Promise.all([Ir({id:Ue?.id??"",path:re}),Ag(re)]),bt=await wg(re,Oe.actions,We);if(!bt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Zt,name:"Auto-discover",command:bt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:bt.previewUrlHint||""}})():_,Y=w.autoOpenUrl===!0&&(w.openUrl||"").trim().length>0,se=!Y&&_.id!==Zt,{key:de,tabId:Se,sessionId:Pe}=await He(w,{revealTerminal:se});let $e=Pe;if(!$e){y(re,Se,!0);try{$e=(await l.createSession({cwd:re,sessionId:Se,shell:m,loginShell:x,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,L(re,Se,$e)}finally{y(re,Se,!1)}}if(!$e)throw new Error("Failed to create terminal session");V.current[de]?.(),y(re,Se,!0);const mt=l.connect($e,{onEvent:Oe=>{Oe.type==="snapshot"&&(Ee.getState().replaceBuffer(re,Se,Oe.data??"",Oe.sequence??0),Ee.getState().setConnecting(re,Se,!1)),Oe.type==="data"&&typeof Oe.data=="string"&&Oe.data.length>0&&Ee.getState().appendToBuffer(re,Se,Oe.data,Oe.sequence,Oe.replayData),Oe.type==="exit"&&(Ee.getState().setTabLifecycle(re,Se,"exited"),Ee.getState().setConnecting(re,Se,!1),Ee.getState().removeProjectActionRun(de),delete R.current[de],V.current[de]?.(),delete V.current[de],window.clearTimeout(oe.current[de]),delete oe.current[de])},onError:(Oe,We)=>{Ee.getState().setConnecting(re,Se,!1),We&&(Ee.getState().setTabLifecycle(re,Se,"exited"),Ee.getState().setTabSessionId(re,Se,null),Ee.getState().removeProjectActionRun(de))}});V.current[de]=mt.close;const Ct=w.autoOpenUrl===!0&&d&&(w.desktopOpenSshForward||"").trim().length>0,Xe=w.autoOpenUrl?Mg(w.openUrl):null,ct=w.autoOpenUrl&&d?Of(w.desktopOpenSshForward,u):null;I({key:de,directory:re,actionId:w.id,tabId:Se,sessionId:$e,status:w.id===Zt&&!Xe?"waiting-for-preview":"running"}),window.clearTimeout(oe.current[de]),delete oe.current[de],w.id===Zt&&!Xe&&(oe.current[de]=window.setTimeout(()=>{const Oe=Ee.getState(),We=Oe.projectActionRuns[de];Oe.updateProjectActionRunStatus(de,"running"),We&&(Oe.setActiveTab(We.directory,We.tabId),ue.getState().openContextPanelTab(We.directory,{mode:"terminal"})),delete oe.current[de]},Tg)),R.current[de]={lastSeenChunkId:null,openedUrl:!!ct||!!Xe||Y,tail:"",openInPreview:w.id===Zt};const xt=Rg(w.command.trim().replace(/\r\n|\r/g,`
|
|
56
|
-
`));await l.sendInput($e,`${xt}\r`),ct?(A(re,Se,null,{locked:!0}),Ge(ct),le.success("Opened forwarded URL")):Xe?(A(re,Se,Xe,{locked:!0,autoOpened:!0}),S(re,Xe),le.success("Opened action URL")):Y?(A(re,Se,null,{locked:!0}),le.error("Invalid custom URL format")):Ct?(A(re,Se,null,{locked:!0}),le.error("Selected desktop SSH forward is unavailable")):A(re,Se,null,{locked:!1,autoOpened:!1})}catch(w){D(ye),delete R.current[ye],V.current[ye]?.(),delete V.current[ye],window.clearTimeout(oe.current[ye]),delete oe.current[ye],le.error(w instanceof Error?w.message:"Failed to run action")}finally{$.current.delete(ye)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,He,i,c,d,re,x,m,Ge,S,C,D,y,I,A,L,Ue?.id,l]),ze=o.useCallback(async _=>{const ye=hs(re,_.id),be=C[ye];if(!be)return;P(ye,"stopping");const w=Ig(l,be.sessionId,1e3);try{await l.sendInput(be.sessionId,"")}catch{}const Y=await w;if(Ee.getState().getDirectoryState(be.directory)?.tabs.find(Se=>Se.id===be.tabId)?.terminalSessionId===be.sessionId&&!Y){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:be.sessionId})}catch{}else try{await l.close(be.sessionId)}catch{}L(be.directory,be.tabId,null)}D(ye),delete R.current[ye],V.current[ye]?.(),delete V.current[ye],window.clearTimeout(oe.current[ye]),delete oe.current[ye]},[re,C,D,L,l,P]),J=o.useCallback(()=>{const _=pe??Ce[0];if(!_)return;const ye=hs(re,_.id),be=C[ye];if(be?.status!=="stopping"){if(be){ze(_);return}tt(_)}},[Ce,re,tt,C,pe,ze]),q=o.useCallback((_,ye=!1)=>{if(ie(_.id),!ye){tt(_);return}const be=hs(re,_.id),w=C[be];if(w?.status!=="stopping"){if(w){ze(_);return}tt(_)}},[re,tt,C,ze]),ge=o.useCallback(()=>{Ue?.id&&(g(Ue.id),h("projects"),f(!0))},[f,h,g,Ue?.id]),X=pe??Ce[0]??null,we=X?C[hs(re,X.id)]:null,xe=Ee(_=>we?_.sessions.get(we.directory)?.tabs.find(ye=>ye.id===we.tabId)?.previewUrl??null:null);if(!i&&c||!Ue||!re)return null;const Ne=pe??Ce[0]??null;if(!Ne)return null;const pt=Ne.icon||"play",gt=Ne.id===Zt?"scan-2":dn[pt]||"play",et=hs(re,Ne.id),De=C[et],Fe=De?.status==="stopping",Ae=De?.status==="waiting-for-preview",at=!!(De&&xe),jt=()=>{!De||!xe||S(De.directory,xe)},st=Ne.id===Zt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",disabled:z||Fe,className:B("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:J,"aria-label":De?`Stop ${Ne.name}`:`Run ${Ne.name}`,children:Fe||Ae?t.jsx(N,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):De?t.jsx(N,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(N,{name:gt,className:"h-5 w-5"})})}),st?t.jsx(it,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),at?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:jt,children:t.jsx(N,{name:"global",className:"h-4 w-4"})})}),t.jsx(it,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(N,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(St,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(N,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ys,{}),Ce.map(_=>{const ye=_.icon||"play",be=_.id===Zt?"scan-2":dn[ye]||"play",w=hs(re,_.id),Y=C[w],se=!!Y,de=Y?.status==="stopping";return t.jsxs(St,{className:"flex items-center gap-2",onClick:()=>{q(_,!0)},children:[t.jsx(N,{name:be,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.name}),de||Y?.status==="waiting-for-preview"?t.jsx(N,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(N,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]}):t.jsxs("div",{className:B("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:J,disabled:z||Fe,className:B("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":De?`Stop ${Ne.name}`:`Run ${Ne.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:Fe||Ae?t.jsx(N,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):De?t.jsx(N,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(N,{name:gt,className:"h-4 w-4"})})})}),st?t.jsx(it,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),at?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:jt,className:B(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(N,{name:"global",className:"h-4 w-4"})})}),t.jsx(it,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(N,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(St,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(N,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ys,{}),Ce.map(_=>{const ye=_.icon||"play",be=_.id===Zt?"scan-2":dn[ye]||"play",w=hs(re,_.id),Y=C[w],se=!!Y,de=Y?.status==="stopping";return t.jsxs(St,{className:"flex items-center gap-2",onClick:()=>{q(_,!0)},children:[t.jsx(N,{name:be,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:_.name}),de||Y?.status==="waiting-for-preview"?t.jsx(N,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(N,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]})},Og=o.lazy(()=>Ds(()=>import("./SessionSwitcherDropdown-BdQTFOMs.js"),__vite__mapDeps([115,11,4,5,1,2,3,6,7,8,9,10,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])).then(e=>({default:e.SessionSwitcherDropdown}))),nr="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Lg="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Bg=o.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:i,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:B(a??nr,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(N,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(it,{children:t.jsx("p",{children:n})})]}):null}),_g=o.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:i,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B(nr,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(N,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Xt,{align:"end",className:"w-64",children:[t.jsx(Qd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ys,{}),r.map(d=>{const u=d.user,p=!!d.current,m=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(St,{className:"gap-2",disabled:l,onSelect:()=>{p||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(N,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:m})]}):null]}),p?t.jsx(N,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(N,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),zg=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:p,remoteUpdateError:m,onOpenRemoteUpdate:x}){return t.jsxs(Qt,{open:a,onOpenChange:h=>{l(h),h&&c()},children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:B(nr,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(N,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(it,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Xt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[i?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:p?"Looking for updates...":m||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(qd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),$g=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],i=n[1].slice(0,3),a=`${r} ${i}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},tn=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},zx=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{as("ui.header.render");const l=ue(E=>E.setSessionSwitcherOpen),c=ue(E=>E.toggleSidebar),d=ue(E=>E.isSidebarOpen),u=ue(E=>E.activeMainTab),p=ue(E=>E.setActiveMainTab),m=ue(E=>E.shortcutOverrides);ue(E=>E.timeFormatPreference),Qn();const x=_e(E=>!!E.newSessionDraft?.open),h=_e(E=>E.currentSessionId),f=ua(h??""),g=Ud(h),S=o.useMemo(()=>{if(!g)return null;const E=g;return{title:g.title??null,directory:E.directory??null,created:g.time?.created??null,slug:E.slug??null,shareUrl:g.share?.url??null,parentId:g.parentID??null}},[g]),k=zt(Ur(E=>{if(!E.activeProjectId)return null;const he=E.projects.find(Ie=>Ie.id===E.activeProjectId);return he?{id:he.id,path:he.path,label:he.label}:null})),O=o.useMemo(()=>{if(!k)return null;const E=k.label?.trim();if(E)return E;const he=k.path.split(/[\\/]/).filter(Boolean);return he[he.length-1]??null},[k]),{isMobile:j}=Fs(),{enabled:v}=eo(),y=!!(v&&a&&i!==void 0),L=o.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"notes",label:"Notes",icon:"sticky-note"}],[]),[A,C]=o.useState(!1),I=null,P=o.useRef(null),[D,W]=o.useState(()=>typeof window>"u"?!1:ws()),ee=o.useMemo(()=>ya(),[]),Z=Gd(),[ie,z]=o.useState(!1),U=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:T,side:R}=ga(),V=o.useMemo(()=>{if(typeof window>"u")return null;const E=window.__PICHAMBER_MACOS_MAJOR__;if(typeof E=="number"&&Number.isFinite(E)&&E>0)return E;if(typeof navigator>"u")return null;const he=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!he)return null;const Ie=Number.parseInt(he[1],10),lt=Number.parseInt(he[2],10);return Number.isNaN(Ie)?null:Ie===10?lt:Ie},[]);qe.useEffect(()=>{typeof window>"u"||W(ws())},[]);const oe=ue(E=>E.isSessionSwitcherOpen),$=null,Me=null,Te=[],[Ye,Ue]=o.useState(!1),[Ge,Le]=o.useState(!1),[re,pe]=o.useState("Local"),[Ke,ke]=o.useState(!0),[Ce,He]=o.useState(!1),[tt,ze]=o.useState(null),[J,q]=o.useState(!1),[ge,X]=o.useState(null),we=o.useMemo(()=>$g(re),[re]),xe=o.useCallback(async()=>{if(!(typeof window>"u"||!D))try{if(hn()){pe("Local"),ke(!0);return}ke(!1);const E=await wu(),he=Kd(),Ie=Hd([Wd(he),...E.hosts]);if(Ie.id===Yd){pe("Local"),ke(!0);return}pe(Su(Ie.label.trim()||"Instance"))}catch{pe("Local"),ke(!0)}},[D]);qe.useEffect(()=>(xe(),ju(()=>{xe()})),[xe]);const Ne=o.useCallback(async()=>{if(Ke){ze(null),X(null);return}q(!0),X(null);try{const E=new URLSearchParams({appType:"web",instanceMode:"remote"}),he=await es(`/api/pi/update-check?${E.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!he.ok)throw new Error(`Server responded with ${he.status}`);const Ie=await he.json();ze({available:Ie.available??!1,version:Ie.version,currentVersion:Ie.currentVersion??"unknown",body:Ie.body,nextSuggestedCheckInSec:typeof Ie.nextSuggestedCheckInSec=="number"?Ie.nextSuggestedCheckInSec:void 0,packageManager:Ie.packageManager,updateCommand:Ie.updateCommand})}catch(E){ze(null),X(E instanceof Error?E.message:"Failed to check remote instance updates")}finally{q(!1)}},[Ke]);o.useEffect(()=>{ze(null),X(null),He(!1)},[Ke,re]),o.useEffect(()=>{if(!D||Ke)return;const E=3e3,he=3600*1e3;let Ie=!1,lt=null;const ss=K=>{lt=window.setTimeout(()=>{if(Ie||typeof document<"u"&&document.visibilityState!=="visible"){ss(he);return}Ne().finally(()=>{Ie||ss(he)})},K)};return ss(E),()=>{Ie=!0,lt!==null&&window.clearTimeout(lt)}},[Ne,Ke,re,D]);const pt=o.useCallback(()=>{if(tt?.available){He(!0);return}Ne()},[Ne,tt?.available]),gt=h?S??null:null,et=o.useRef(null),[De,Fe]=o.useState(0);o.useEffect(()=>{if(!h){et.current&&(et.current=null,Fe(lt=>lt+1));return}if(gt){et.current={sessionId:h,session:gt,expiresAt:Date.now()+2e3};return}const E=et.current;if(!E||E.sessionId!==h)return;const he=E.expiresAt-Date.now();if(he<=0){et.current=null,Fe(lt=>lt+1);return}const Ie=window.setTimeout(()=>{et.current?.sessionId===h&&(et.current=null),Fe(lt=>lt+1)},he);return()=>{window.clearTimeout(Ie)}},[h,gt]);const Ae=(()=>{if(gt)return gt;if(!h)return null;const E=et.current;return E&&E.sessionId===h&&E.expiresAt>Date.now()?E.session:null})(),at=o.useMemo(()=>{const E=typeof Ae?.directory=="string"?Ae.directory:"";return tn(E||"")},[Ae?.directory]),jt=_e(E=>E.newSessionDraft?.open?tn(E.newSessionDraft.directoryOverride??""):""),st=o.useMemo(()=>at||jt,[jt,at]),ye=da(st||null),be=!!(O||ye),w=o.useMemo(()=>{if(!h)return O??"PiChamber";const E=Ae?.title?.trim();return E&&E.length>0?E:"Untitled Session"},[O,Ae?.title,h]),Y=fa(),se=so(),de=_e(E=>E.updateSessionTitle),Se=_e(E=>E.archiveSessions),Pe=_e(E=>E.deleteSessions),[$e,mt]=o.useState(!1),[Ct,Xe]=o.useState(!1),ct=o.useRef(!1),[xt,Oe]=o.useState(""),[We,bt]=o.useState(null),Mt=o.useRef(null);o.useEffect(()=>{ct.current=!1,Xe(!1),mt(!1),Oe(""),bt(null)},[h]);const $t=o.useCallback(()=>{h&&(Oe(Ae?.title?.trim()||w),mt(!0))},[Ae?.title,h,w]),Nt=o.useCallback(async()=>{if(!h)return;const E=xt.trim();E&&E!==Ae?.title?.trim()&&await de(h,E),mt(!1)},[Ae?.title,h,xt,de]);o.useEffect(()=>{if(!$e)return;const E=he=>{const Ie=he.target;(!Ie||!Mt.current?.contains(Ie))&&Nt()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[$e,Nt]);const At=o.useCallback(()=>{h&&fn(h).then(E=>{le[E.ok?"success":"error"](E.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[h]),It=o.useCallback(async()=>{if(!h||!st){le.error("Nothing to export");return}try{await se.syncSession(h)}catch{le.error("Failed to load the complete session history");return}const E=Tr(Y.getState()).list;if(E.length===0){le.error("Nothing to export");return}const he=rl(E,Ae?.title??null),Ie=al(Ae?.title??null);await il(he,Ie)||ol(he,Ie),le.success("Session exported")},[Ae?.title,h,Y,st,se]);f?.type==="busy"||f?.type;const M=o.useCallback(async()=>{if(!h||!We)return;const E=Vd(),he=[h];for(let K=0;K<he.length;K+=1){const Ve=he[K];for(const ut of E)ut.parentID===Ve&&!he.includes(ut.id)&&he.push(ut.id)}const Ie=We;if(bt(null),(Ie==="archive"?await Se(he):await Pe(he)).failedIds.length>0){le.error(Ie==="archive"?"Failed to archive session":"Failed to delete session");return}le.success(Ie==="archive"?"Session archived":"Session deleted")},[Se,h,Pe,We]),je=ue(E=>E.isArchivePageOpen),Be=o.useMemo(()=>je?{title:"Archive",subtitle:null}:null,[je]),dt=o.useMemo(()=>tn(st||k?.path||""),[k?.path,st]),F=o.useMemo(()=>k?{id:k.id,path:k.path}:null,[k]),ae=o.useRef(null);o.useEffect(()=>{!F||!dt||(ae.current={projectRef:F,directory:dt})},[dt,F]);const me=o.useMemo(()=>F&&dt?{projectRef:F,directory:dt}:ae.current,[dt,F]),nt=o.useCallback(async E=>{},[]),ve=o.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const he=E.tagName;(he==="INPUT"||he==="TEXTAREA"||he==="SELECT"||E.isContentEditable)&&E.blur()},[]),Je=o.useCallback(()=>{if(j){ve(),l(!oe);return}c()},[ve,j,oe,l,c]),yt=o.useCallback(()=>{an("desktop_open_draft_mini_chat_window",{directory:tn(st||k?.path||""),projectId:k?.id??null,apiBaseUrl:Fr(),clientToken:Mr()}).catch(E=>{console.warn("[header] failed to open draft mini chat window",E)})},[k?.id,k?.path,st]),Ft=o.useCallback(()=>{if(x){yt();return}h&&an("desktop_open_session_mini_chat_window",{sessionId:h,directory:tn(st||k?.path||""),apiBaseUrl:Fr(),clientToken:Mr()}).catch(E=>{console.warn("[header] failed to open session mini chat window",E)})},[k?.path,h,yt,x,st]),Lt=nr,kt=Lg,Ut=o.useMemo(()=>n?"sessions":y?r&&i?i:null:r?"git":u,[u,y,n,r,i]),Rt=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&oe&&l(!1)},[oe,n,e,s,r,l]),vt=o.useCallback(()=>{e?.()},[e]),Wt=o.useCallback(()=>{s?.()},[s]),G=o.useMemo(()=>D&&U&&!ie?"5.5rem":Z?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!D||T?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[D,ie,U,Z,T]);qe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",G)},[G]);const te=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",ne=d?"0px":D&&T?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":v?"2.75rem":"2.5rem";qe.useEffect(()=>{if(!D||!U){z(!1);return}let E=!1;const he=async()=>{try{const lt=await an("desktop_is_window_fullscreen");E||z(lt===!0)}catch{E||z(!1)}},Ie=()=>{he()};return he(),window.addEventListener("pichamber:window-resized",Ie),()=>{E=!0,window.removeEventListener("pichamber:window-resized",Ie)}},[D,U]);const ce=o.useMemo(()=>!D||!U||V===null?"":V>=26?"h-12":V<=15?"h-14":"",[D,U,V]),fe=o.useMemo(()=>{if(!(D&&!T))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[D,T]),ft=o.useCallback(()=>{if(typeof document>"u")return;const E=P.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);qe.useEffect(()=>{if(typeof window>"u")return;ft();const E=P.current;if(!E||typeof ResizeObserver>"u")return()=>{};let he=0;const Ie=()=>{he||(he=requestAnimationFrame(()=>{he=0,ft()}))},lt=new ResizeObserver(Ie);return lt.observe(E),window.addEventListener("resize",Ie),window.addEventListener("orientationchange",Ie),()=>{he&&cancelAnimationFrame(he),lt.disconnect(),window.removeEventListener("resize",Ie),window.removeEventListener("orientationchange",Ie)}},[ft]),qe.useEffect(()=>{ft()},[ft,j,ce]);const Et=o.useCallback(async E=>{const he=E.target;he.closest(".app-region-no-drag")||he.closest("button, a, input, select, textarea")||E.button===0&&D&&await Cu()},[D]),wt=o.useMemo(()=>j?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[j]),Gt=o.useCallback(E=>ao(on(E,m)),[m]);qe.useEffect(()=>{!j&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&p("chat")},[u,j,p]);const ts=o.useMemo(()=>{const E=[];return D&&E.push({value:"instance",label:"Instance",icon:t.jsx(N,{name:"server",className:"h-3.5 w-3.5"})}),E},[D]);qe.useEffect(()=>{const E=he=>{if(ku(he)&&!he.shiftKey&&!he.altKey){const Ie=parseInt(he.key,10);Ie>=1&&Ie<=wt.length&&(he.preventDefault(),j&&(ve(),Rt()),p(wt[Ie-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[ve,Rt,j,p,wt]),qe.useEffect(()=>{const E=he=>{const Ie=on("toggle_services_menu",m);if(ni(he,Ie)){he.preventDefault(),Ge?Le(!1):(Le(!0),xe());return}const lt=on("cycle_services_tab",m);if(ni(he,lt)){if(he.preventDefault(),ts.length===0)return;Le(!0),xe();return}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[m,Ge,ts,xe]);const Dt=E=>{const he=u===E.id,Ie=E.icon==="diff",lt=Ie?null:E.icon,ss=E.id==="chat",K=ut=>Ie?t.jsx(Yi,{size:ut}):lt?t.jsx(N,{name:lt,className:`h-${ut/4} w-${ut/4}`}):null,Ve=t.jsxs("button",{type:"button",onClick:()=>p(E.id),className:B("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",he?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",ss&&!j&&"min-w-[100px] justify-center"),"aria-label":E.label,"aria-selected":he,role:"tab",children:[j?K(20):t.jsxs(t.Fragment,{children:[K(16),t.jsx("span",{className:"header-tab-label",children:E.label})]}),E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:E.badge})]});return t.jsx(o.Fragment,{children:Ve},E.id)},ls=t.jsxs(t.Fragment,{children:[t.jsx(bg,{directory:dt,className:"mr-1"}),D?t.jsx(zg,{isDesktopApp:D,currentInstanceLabel:re,compactCurrentInstanceLabel:we,currentInstanceIsLocal:Ke,isDesktopServicesOpen:Ge,setIsDesktopServicesOpen:Le,refreshCurrentInstanceLabel:xe,shortcutLabel:Gt,remoteUpdateInfo:tt,remoteUpdateChecking:J,remoteUpdateError:ge,onOpenRemoteUpdate:pt}):null,t.jsx(_g,{isMobile:j,githubAuthStatus:I,githubAccounts:Te,githubAvatarUrl:$,githubLogin:Me,isSwitchingGitHubAccount:Ye,handleGitHubAccountSwitch:nt})]}),us=ee&&(x||!!h),xs=()=>t.jsxs("div",{onMouseDown:Et,className:B("app-region-drag relative flex h-12 select-none items-center pr-3",ce),style:fe,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:te}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:ne}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Be?t.jsxs("div",{className:"mr-3 flex min-w-0 flex-col items-start px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Be.title}),Be.subtitle?t.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:Be.subtitle}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(o.Suspense,{fallback:t.jsx("button",{type:"button",className:Lt,"aria-label":"Open session switcher",children:t.jsx(N,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Og,{align:"start",children:t.jsx("button",{type:"button",className:Lt,"aria-label":"Open session switcher",children:t.jsx(N,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[$e?t.jsxs("form",{ref:Mt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:E=>{E.preventDefault(),Nt()},children:[t.jsx("input",{value:xt,onChange:E=>Oe(E.target.value),autoFocus:!0,onKeyDown:E=>{E.stopPropagation(),E.key==="Escape"&&mt(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(N,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>mt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(N,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:x?"New session":w}),be?t.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[O?t.jsx("span",{className:"truncate",children:O}):null,ye?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(N,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:ye})]}):null]}):null]}),t.jsx("div",{className:B("flex h-[18px] shrink-0 items-center justify-center",be?"self-start":"self-center"),children:h&&!x&&!$e?t.jsxs(Qt,{open:Ct,onOpenChange:Xe,onOpenChangeComplete:E=>{!E&&ct.current&&(ct.current=!1,$t())},children:[t.jsx(Jt,{asChild:!0,children:t.jsx(Qe,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(N,{name:"more",className:"size-4"})})}),t.jsxs(Xt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(St,{onClick:()=>{ct.current=!0},children:[t.jsx(N,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(St,{onClick:At,children:[t.jsx(N,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Ys,{}),t.jsxs(St,{onClick:()=>{It()},children:[t.jsx(N,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ys,{}),t.jsxs(St,{onClick:()=>bt("archive"),children:[t.jsx(N,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(St,{className:"text-destructive focus:text-destructive",onClick:()=>bt("delete"),children:[t.jsx(N,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),wt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:wt.map(E=>Dt(E))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[me?t.jsx(Qi,{projectRef:me.projectRef,directory:me.directory,className:"mr-1"}):null,t.jsx(Bg,{visible:us,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Ft,className:B(Lt,"mr-1"),Icon:"picture-in-picture-2"}),ls,t.jsx(xa,{visible:T&&R==="right",position:"right"})]})]})]}),qs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[v&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:te}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:ne}})]}),!v&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:vt,className:B(kt,Ut==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(N,{name:"layout-left",className:"h-5 w-5"})}):oe?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(N,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Je,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(N,{name:"play-list-add",className:"h-5 w-5"})}),!e&&oe&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!oe||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!y&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:wt.map(E=>{const he=u===E.id,Ie=E.icon==="diff",lt=Ie?null:E.icon;return t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{j&&(ve(),Rt()),p(E.id)},"aria-label":E.label,"aria-selected":he,role:"tab",className:B(kt,"relative rounded-lg",Ut===E.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[Ie?t.jsx(Yi,{className:"h-5 w-5"}):lt?t.jsx(N,{name:lt,className:"h-5 w-5"}):null,E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:E.badge}),E.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(it,{children:t.jsx("p",{children:E.label})})]},E.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[y&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:L.map(E=>{const he=r&&i===E.id;return t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{j&&(ve(),Rt()),C(!1),a?.(E.id)},"aria-label":E.label,"aria-selected":he,role:"tab",className:B(kt,"relative rounded-lg",he&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(N,{name:E.icon,className:"h-5 w-5"})})}),t.jsx(it,{children:t.jsx("p",{children:E.label})})]},E.id)})}),t.jsx(Ih,{open:A,onOpenChange:C,currentSessionId:h,effectiveDirectory:st||null,isNewSessionDraftOpen:x})]}),me&&t.jsx(Qi,{projectRef:me.projectRef,directory:me.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!y?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Wt,className:B(kt,"relative",Ut==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(N,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(it,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Qs=B("header-safe-area relative z-10 bg-background",j&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:Qs,style:{"--padding-scale":"1"},children:j?qs():xs()}),t.jsx(cs,{open:We!==null,onOpenChange:E=>{E||bt(null)},children:t.jsxs(ds,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(ms,{children:We==="delete"?"Delete session?":"Archive session?"}),t.jsx(Os,{children:We==="delete"?`\\"${w}\\" will be permanently deleted.`:`\\"${w}\\" will be archived.`})]}),t.jsxs(Ls,{children:[t.jsx(Qe,{variant:"outline",size:"sm",onClick:()=>bt(null),children:"Cancel"}),t.jsx(Qe,{variant:"destructive",size:"sm",onClick:()=>{M()},children:We==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Oa,{open:Ce,onOpenChange:He,info:tt,downloading:!1,downloaded:!1,progress:null,error:ge,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ji="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",Ug="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",$x=()=>{const e=ue(g=>g.isSidebarOpen),s=ue(g=>g.toggleSidebar),n=ue(g=>g.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=ao(on("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=ga(),{enabled:d}=eo(),u=!e,p=l&&c==="left",m=l,x=u||p||m,h=p||m,f=o.useCallback(()=>{an("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const g=y=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(y)}px`)},S=y=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(y)}px`)};if(!h)return;const k=i.current,O=r.current;if(!k||!O){g(0),S(0);return}const j=()=>{const y=Math.max(k.getBoundingClientRect().width,k.scrollWidth);g(y),S(O.getBoundingClientRect().width)};if(j(),typeof ResizeObserver>"u")return;const v=new ResizeObserver(j);return v.observe(k),v.observe(O),()=>{v.disconnect()}},[h]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 top-0 z-40 flex select-none items-center pr-2",style:{height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:i,className:"flex items-center gap-2",children:[p?t.jsx(xa,{visible:!0,position:"left"}):null,m?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:f,"aria-label":"Open PiChamber menu",className:B(Ji,"shrink-0"),children:t.jsx(N,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(it,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:B(d?Ug:Ji,"shrink-0"),children:t.jsx(N,{name:"layout-left",className:d?"h-5 w-5":"h-[18px] w-[18px]"})})}),t.jsx(it,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Mn=200,Fn="cubic-bezier(0.22, 1, 0.36, 1)",Ux=e=>{const s=o.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=o.useState(e);return o.useLayoutEffect(()=>{if(s){r(e);return}if(e){r(!1);let i=0;const a=window.requestAnimationFrame(()=>{i=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(a),window.cancelAnimationFrame(i)}}r(!1)},[e,s]),{slidIn:n,prefersReducedMotion:s,transition:s?"none":`transform ${Mn}ms ${Fn}, width ${Mn}ms ${Fn}, min-width ${Mn}ms ${Fn}, max-width ${Mn}ms ${Fn}`}};export{Gs as $,jx as A,Sx as B,wx as C,Oi as D,ks as E,Ix as F,hx as G,zx as H,If as I,po as J,dx as K,Af as L,Ih as M,mo as N,ux as O,Mx as P,Jf as Q,Kn as R,Px as S,Fx as T,Oa as U,Df as V,gn as W,wf as X,Sf as Y,La as Z,xn as _,sn as a,Cf as a0,ix as a1,gx as a2,jf as a3,kf as a4,mx as a5,yx as a6,bx as a7,Pf as a8,Ns as a9,px as aa,xx as ab,vx as ac,ox as ad,ax as ae,lx as af,cx as ag,Wf as ah,fx as ai,rh as aj,oh as ak,Nf as al,rx as am,Dx as an,Cx as ao,ym as b,Ex as c,$n as d,uh as e,Lx as f,Tx as g,Nx as h,Sm as i,Ax as j,kx as k,Ux as l,Bx as m,$x as n,nx as o,Xf as p,Zf as q,Ox as r,Rx as s,eh as t,Bn as u,hi as v,th as w,Zm as x,_x as y,sh as z};
|