@pi-chamber/web 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/assets/{CommitSection-Cz-ACBaD.js → CommitSection-BMoPmxW5.js} +1 -1
  2. package/dist/assets/{DiagramEditor-BNUOrd9m.js → DiagramEditor-DmDE7OFs.js} +1 -1
  3. package/dist/assets/{DiagramView-D4YR9YRt.js → DiagramView-DQqjMY2l.js} +1 -1
  4. package/dist/assets/{DiffView-DPW8dcg_.js → DiffView-CA4gogOk.js} +3 -3
  5. package/dist/assets/{FilesView-BFGIdY6b.js → FilesView-B6u279g1.js} +5 -5
  6. package/dist/assets/{GitView-CKtiKOfJ.js → GitView-BZVWI9Uo.js} +4 -4
  7. package/dist/assets/{JsonTreeView-c-UJUw3D.js → JsonTreeView-Lcl4hDE0.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-CvC9eXoa.js → MarkdownRendererImpl-Uz4H4e3u.js} +1 -1
  9. package/dist/assets/PatchDiff-DpAN_LfK.js +1 -0
  10. package/dist/assets/{PierreDiffViewer-CoXa-JJK.js → PierreDiffViewer-CODKwHC9.js} +2 -2
  11. package/dist/assets/{SessionSwitcherContent-B7eep3dO.js → SessionSwitcherContent-Cp2Zm5gn.js} +1 -1
  12. package/dist/assets/{SessionSwitcherDropdown-CZOFeJHH.js → SessionSwitcherDropdown-BdQTFOMs.js} +2 -2
  13. package/dist/assets/{SessionUnreadDot-ClpeYFPz.js → SessionUnreadDot-CyaUql-t.js} +1 -1
  14. package/dist/assets/{SettingsView-CPmHHDbQ.js → SettingsView-BtYR1m1l.js} +3 -3
  15. package/dist/assets/{SettingsWindow-2CBpoJ8H.js → SettingsWindow-BWemjgov.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-HMW-Kh19.js → ToolOutputDialog-BmSMXqFj.js} +6 -6
  17. package/dist/assets/{ToolPartDiffPreview-C3nbNbxk.js → ToolPartDiffPreview-qaLAaq5N.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-DEX83nQ0.js → VirtualizedFileDiff-B-r2zJ_k.js} +3 -3
  19. package/dist/assets/{WindowsWindowControls-PPk5H89-.js → WindowsWindowControls-NzKm1MYj.js} +105 -105
  20. package/dist/assets/{collapsible-Dux-9hAC.js → collapsible-IV1T6v7c.js} +1 -1
  21. package/dist/assets/{computeVirtualFileMetrics-Cy0nxMJB.js → computeVirtualFileMetrics-DOtVuPAu.js} +1 -1
  22. package/dist/assets/{contextFileOpenGuard-Dn_38hd9.js → contextFileOpenGuard-CR2p7-61.js} +1 -1
  23. package/dist/assets/{index-DU2OBBy5.js → index--5Zr-fSk.js} +6 -6
  24. package/dist/assets/{index-EN7MioVf.js → index-Z6Hwnczz.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-DSWRVq-W.js → isDiffPlainText-DKfgU8d8.js} +1 -1
  26. package/dist/assets/{isFilePlainText-7RAjjrQ5.js → isFilePlainText-2ndX4gYw.js} +1 -1
  27. package/dist/assets/{main-DGHrBx_u.js → main-BfG1ShoJ.js} +2 -2
  28. package/dist/assets/{main-BGKjg-qW.js → main-CsU2nR8Q.js} +4 -4
  29. package/dist/assets/{markdownCore-BYPqQtbE.js → markdownCore-BaZ2plrB.js} +2 -2
  30. package/dist/assets/{miniChat-DW2PVX49.js → miniChat-BpFgzk2I.js} +2 -2
  31. package/dist/assets/{mobile-0Gxc02iO.js → mobile-Dh_Vvtjt.js} +2 -2
  32. package/dist/assets/{renderElectronMiniChatApp-C-qpqp1i.js → renderElectronMiniChatApp-DNmqLSsJ.js} +2 -2
  33. package/dist/assets/renderMobileApp-BZbx_IU1.js +14 -0
  34. package/dist/assets/{runtimeSurface-DefD-2Iv.js → runtimeSurface-D3p7a-uO.js} +1 -1
  35. package/dist/assets/{useInlineCommentController-B8p2XwXA.js → useInlineCommentController-TZXHonVr.js} +2 -2
  36. package/dist/assets/usePanelSlide-SCy9Q8Wl.js +56 -0
  37. package/dist/assets/{usePushVisibilityBeacon-CvjN-47R.js → usePushVisibilityBeacon-9FqcXiL9.js} +2 -2
  38. package/dist/assets/{useSwitcherItems-B6_F-J-z.js → useSwitcherItems-DZW2vj37.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-BhBdEPsJ.js → vendor-codemirror-language-data-DXJ_-7WI.js} +2 -2
  40. package/dist/assets/{web-components-C9yVPsWN.js → web-components-RWdkgqgC.js} +1 -1
  41. package/dist/index.html +3 -3
  42. package/dist/mini-chat.html +2 -2
  43. package/dist/mobile.html +2 -2
  44. package/package.json +1 -1
  45. package/server/lib/pi/small-model-generation.js +14 -1
  46. package/server/lib/pi/small-model-generation.test.js +20 -5
  47. package/dist/assets/PatchDiff-YGHsZUIR.js +0 -1
  48. package/dist/assets/renderMobileApp-UB9bhC1x.js +0 -14
  49. package/dist/assets/usePanelSlide-CbqVf-y8.js +0 -56
@@ -1,56 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-EN7MioVf.js","assets/WindowsWindowControls-PPk5H89-.js","assets/index-DU2OBBy5.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-DefD-2Iv.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-BhBdEPsJ.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-Cy0nxMJB.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-7RAjjrQ5.js","assets/isDiffPlainText-DSWRVq-W.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-CZOFeJHH.js"])))=>i.map(i=>d[i]);
2
- import{_ as Is}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Qe,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{aZ as $s,a_ as vc,ah as wc,o as qi,D as is,n as as,q as hs,I as N,aq as Ns,a$ as Bo,B as qe,ao as un,T as rt,l as ot,m as it,b0 as Ji,b1 as Sc,b2 as jc,b3 as Cc,b4 as kc,g as _e,b5 as Nc,b6 as _o,b7 as Ac,b8 as Ic,b9 as zo,ba as Dc,bb as Pc,bc as Ec,bd as Tc,be as Nr,bf as Rc,t as le,al as Yt,am as Vt,an as Qt,R as Ws,bg as Mc,bh as Fc,bi as Lc,bj as Oc,bk as $o,Z as Ot,bl as Bc,bm as _c,bn as zc,bo as $c,bp as Uc,bq as Gc,br as Ar,bs as Xi,bt as Zi,bu as Kc,bv as Hc,bw as Wc,bx as Yc,by as Vc,bz as Qc,aN as Ir,r as Gs,aP as Ps,aS as qc,aT as Jc,aU as Xc,aV as Zc,aW as or,aX as Js,bA as Uo,ar as jt,b as _t,aI as Rs,bB as ea,p as vs,s as Ms,v as Fs,bC as ed,a2 as Xs,bD as ir,bE as Go,bF as Ko,bG as nn,au as td,aJ as ta,az as Ho,ax as sd,aw as nd,aM as sa,f as Xr,bH as rd,e as Zr,w as Vn,C as na,bI as od,bJ as Gt,aE as ra,c as Dr,bK as id,bL as ad,bM as Qn,bN as Wo,aO as oa,bO as ia,bP as aa,z as ld,bQ as eo,bR as cd,bS as dd,h as la,j as ud,bT as fd,bU as hd,i as pd,bV as Pr,bW as ca,bX as md,bY as gd,d as xd,bZ as bd,a as yd,ap as vd,aR as wd,b_ as da,b$ as Sd,c0 as jd,aQ as Cd,c1 as kd,c2 as Nd,a8 as Ad,c3 as Yo,c4 as Id,aF as Dd,c5 as Pd,c6 as Ed,c7 as Sn,c8 as Vo,c9 as Td,ca as Qo,cb as qo,cc as Rd,aD as ua,X as Md,x as Fd,cd as fa,u as Ld,ce as Od,cf as Bd,as as Ys,k as _d,cg as zd,ch as ha,ci as $d,cj as Ud,ck as Gd,cl as Kd,cm as Hd,cn as pa,co as Wd,cp as Yd}from"./WindowsWindowControls-PPk5H89-.js";import{V as Jo,W as Vd,X as Xo,Y as Qd,i as qd,Z as Jd,P as Xd,r as Xt,_ as fn,b as Zd,m as O,O as ys,u as ue,$ as eu,a0 as ds,a1 as to,t as so,n as Es,a2 as Xe,a3 as Ts,a4 as no,a5 as ro,a6 as tu,a7 as su,F as nu,a8 as ru,a9 as ou,aa as iu,ab as au,ac as rs,ad as Zo,ae as Er,a as qn,af as lu,ag as cu,Q as oo,R as rn,ah as du,ai as uu,aj as ma,A as fu,N as ga,G as on,ak as Tr,e as Rr,d as jn,al as hu,am as pu,an as Zs,ao as ar,ap as xa,E as mu,q as gu,aq as Mr,ar as As,as as ei,at as Fr,au as ba,av as Lr,aw as xu,ax as bu,ay as yu,x as vu,az as wu,aA as Su,aB as ti}from"./index-DU2OBBy5.js";import{d as ju,g as ya,r as Cu,e as va,h as Mn,i as wa,b as an,c as ln,s as ku,j as Nu,k as Au,l as si,m as Jn,a as Iu,S as Du,f as Pu,t as Eu,n as Tu}from"./SessionUnreadDot-ClpeYFPz.js";import{C as Sa,a as ja,M as Or,b as Br,c as _r,d as Ca,S as ka,D as Ru,e as Mu,f as Fu,g as Lu,h as Ou,i as Bu,j as _u,k as zu,l as $u}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as Na,p as io,u as zr,a as Uu}from"./vendor-zustand-CnsBKjP5.js";import{u as Gu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as Xn,d as hn,P as ao,D as Zn,e as er,f as Aa,b as Ku,a as Hu,T as Wu,M as Yu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as lo,v as Ia,u as co,a as Vu,h as Qu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as uo}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as qu}from"./permissionStore-BRcQ9Jgt.js";const Ju="chat";function Da(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set($s.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set($s.SETTINGS,n),s}return e.tab!==Ju&&s.set($s.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set($s.FILE,e.diffFile),s}function Xu(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 Zu(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Da(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has($s.SESSION)&&s.set($s.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 $r(e,s={}){if(!(typeof window>"u")&&!(!s.force&&Zu(e)))try{const n=Da(e),r=Xu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const ef=["typescript","javascript","tsx","jsx","json","markdown"],Pa={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ni=null;const Ea=()=>(ni??=Promise.all([Is(()=>import("./index-EN7MioVf.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])),Is(()=>import("./workerFactory-tw7cIdmV.js"),[]),Is(()=>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})),ni),pn={},ri=new Set,Ur=new Set;let Fn={light:"pierre-light",dark:"pierre-dark"};const tf=()=>{for(const e of Ur)e()},Ta=(e,s)=>{s.setRenderOptions({theme:Fn,lineDiffType:Pa[e].lineDiffType})},Gr=e=>{typeof window>"u"||ri.has(e)||(ri.add(e),Ea().then(s=>{if(pn[e])return;const n=Pa[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:ef,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),pn[e]=r,Ta(e,r),tf()}))},sf=e=>(Ur.add(e),()=>Ur.delete(e)),nf=e=>{if(!(Fn.light===e.light&&Fn.dark===e.dark)){Fn=e;for(const s of Object.keys(pn)){const n=pn[s];n&&Ta(s,n)}}},ex=({children:e})=>{const s=vc(),n=Jo(!1),r=Jo(!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 Ea().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),nf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Qe.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Gr("unified"),Gr("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},tx=(e="unified")=>{const s=Qe.useSyncExternalStore(sf,()=>pn[e],()=>{});return Qe.useEffect(()=>{Gr(e)},[e]),s};function rf(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=wc();return e}catch{return"unknown"}}function of(){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 af(){const e=Zd();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 lf(e){const s=new URLSearchParams;return s.set("deviceClass",rf()),s.set("arch",of()),s.set("platform",af()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",fn()?"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 lr(e,s){try{const n=lf(e);s&&n.set("currentVersion",s);const r=await Xt(`/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 cf(){return qd()?"mobile":Jd()?"desktop":Xd()?"web":null}const oi={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Ln=ps()((e,s)=>({...oi,checkForUpdates:async()=>{const n=cf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.5.0",[l,c]=await Promise.allSettled([Xo(),lr("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 lr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await lr("mobile","0.5.0"),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 Xo();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 Qd(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 Vd())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(oi)}})),ii="https://github.com/RyderAsKing/PiChamber/releases";function df(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 uf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function ai(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function ff(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 hf(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 li=2e3,pf=600*1e3;async function mf(){try{const e=await Xt("/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 gf(){try{return(await Xt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function xf(e,s=Math.ceil(pf/li),n=li){for(let r=0;r<s;r++){try{const i=await Xt("/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 gf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Ra=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Qe.useState(!1),[g,m]=Qe.useState("idle"),[h,x]=Qe.useState(null),j=n?.version?n.releaseUrl||`${ii}/tag/v${n.version}`:ii,k=n?.downloadUrl||j,B=a?.total?Math.round(a.downloaded/a.total*100):0,S=u==="web",v=u==="mobile",b=n?.updateCommand||"pichamber update";Qe.useEffect(()=>{e||(m("idle"),x(null))},[e]);const L=async()=>{(await un(b)).ok&&(p(!0),setTimeout(()=>p(!1),2e3))},A=Qe.useCallback(async H=>{await qi(H)},[]),C=Qe.useCallback(async()=>{m("updating"),x(null);const H=await mf();if(!H.success){m("error"),x(H.error||"Update failed");return}H.autoRestart&&(m("restarting"),await new Promise(Z=>setTimeout(Z,2e3))),m("reconnecting"),await xf(n?.currentVersion)?window.location.reload():(m("error"),x("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=g!=="idle"&&g!=="error",D=Qe.useMemo(()=>{if(!n?.body)return null;const H=n.body.trim();if(!H)return null;const ee=hf(H);return ee.length===0?{kind:"raw",title:"What's new",content:ai(H)}:{kind:"sections",title:"What's new",sections:[...ee].sort((ie,$)=>ff(ie.version,$.version)).map(ie=>({version:ie.version,dateLabel:df(ie.date),content:ai(uf(ie.raw)||H)}))}},[n?.body]);return t.jsx(is,{open:e,onOpenChange:P?void 0:s,children:t.jsxs(as,{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(hs,{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:g==="restarting"||g==="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:[S&&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:[g==="updating"&&"Installing update...",g==="restarting"&&"Server restarting...",g==="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(Ns,{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:H=>{const Z=H.target.closest("a");Z&&Z.href&&(H.preventDefault(),H.stopPropagation(),A(Z.href))},children:t.jsx(Bo,{content:D.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:D.sections.map(H=>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",H.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:H.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(Bo,{content:H.content,disableLinkSafety:!0,enableFileReferences:!1})})]},H.version))})})}),S&&g==="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:b}),t.jsx("button",{onClick:L,className:O("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(N,{name:"check",className:"h-4 w-4"}):t.jsx(N,{name:"clipboard",className:"h-4 w-4"})})]})]}),!S&&!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:[B,"%"]})]}),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:`${B}%`}})})]}),(l||h)&&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||h})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(N,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!S&&!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"]}),!S&&!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..."]}),!S&&!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"]}),S&&!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"]}),S&&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..."]})]})]})]})})},bf=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:O("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:O("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),mn=({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:O("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:O("max-w-sm",n),children:e})]})},sx="w-full min-w-40 max-w-48",yf="settings",vf="w-full min-w-40 max-w-48",nx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",wf="w-full max-w-[24rem]",rx="min-w-0 flex-1",ox="flex w-full min-w-0 items-center gap-2",ix="typography-meta shrink-0 text-muted-foreground tabular-nums",Ma="space-y-3.5",Sf="space-y-1.5",ax="typography-settings-page-title text-muted-foreground",jf="typography-settings-section-title text-foreground",lx="typography-settings-section-title text-foreground",Fa="typography-settings-group-title text-foreground",fo="typography-settings-field-label text-foreground",Cf="typography-settings-description text-muted-foreground",gn="typography-meta text-muted-foreground",cx="typography-meta font-medium text-foreground",dx="typography-settings-section-title text-foreground",kf=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:O("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?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:jf,children:e}):e,n,r!=null?t.jsx(mn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Cf,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:O(d),children:a})]})},ux=({children:e,className:s})=>t.jsx("div",{className:O("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Nf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:O(Fa,s),children:e}),fx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:O("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(Nf,{children:e}),n!=null?t.jsx(mn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:gn,children:s}):null]}):null,t.jsx("div",{className:O(a),children:r})]}),Us=({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:gn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:O("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:fo,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:O("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},hx=({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:O("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:fo,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),s!=null?t.jsx("p",{className:O(gn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:O("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),px=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:O("pt-4",s),children:e}),Af=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{i||s(!e)},p=r!=null;return t.jsxs("div",{"data-settings-item":l,className:O("group flex cursor-pointer gap-2 py-0.5",p?"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:f,onKeyDown:g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),f())},children:[t.jsx(Ji,{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:fo,children:n}),d,u!=null?t.jsx(mn,{children:u}):null]}),p?t.jsx("span",{className:gn,children:r}):null]})]})},mx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:O("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(bf,{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:O("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:gn,children:r}):null]})]}),gx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:O(Sf,n),children:s});function xx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:O("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 If 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(Sc,{className:"w-full max-w-md",children:[t.jsx(jc,{className:"text-center",children:t.jsxs(Cc,{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(kc,{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 Df(e){return t.jsx(If,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const bx=({active:e=!0})=>{const s=_e(n=>n.currentSessionId);return t.jsx(Df,{sessionId:s||void 0,children:t.jsx(Nc,{active:e},s??"no-session")})};function Pf({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 ho=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:f,endSlot:p,...g},m)=>{const h=Qe.useRef(null),x=Qe.useRef(null),[j,k]=Qe.useState(null),B=c??j,S=Qe.useCallback(b=>{const L=h.current;if(!L)return;x.current={startY:b.clientY,startHeight:L.getBoundingClientRect().height};const A=b.currentTarget;A.setPointerCapture(b.pointerId);const C=P=>{const D=x.current;if(!D)return;const H=D.startHeight+(P.clientY-D.startY),ee=Math.max(82,H);d?d(ee):k(ee)},I=()=>{x.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),b.preventDefault()},[d]),v=Qe.useCallback(b=>{if(b.target.closest('textarea, button, [role="separator"]'))return;const A=h.current?.querySelector("textarea");A&&document.activeElement!==A&&(b.preventDefault(),A.focus())},[]);return f?t.jsx(Ns,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:O("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,...g}):t.jsx("div",{ref:h,onPointerDown:v,style:B!==null?{height:`${B}px`}:void 0,className:O("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:m,className:O("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,...g}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,t.jsx(Pf,{onResizeStart:S,ariaLabel:"Resize textarea"})]})]})})});ho.displayName="Textarea";const ci=(e,s)=>s.updatedAtMs-e.updatedAtMs,Un=ps((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([Pc(),zo()]),i={};for(const a of r.sort(ci))i[a.id]=a;s().listenerReady||await Ec(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 Dc();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await zo(),r={};for(const i of n.sort(ci))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 Ic({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=Tc(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 Ac(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})})),La=[{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"}],cn=Object.fromEntries(La.map(e=>[e.key,e.Icon])),Kr="pichamber:project-actions-updated",Oa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},us=(e,s)=>`${Oa(e)}::${s}`,Ef=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},di=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Tf=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=di(s.localPort),r=di(s.remotePort);if(!n||!r)return null;const i=Ef(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}`}},Ba=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Tf(n,r);i&&s.push(i)}return s},Rf=(e,s)=>{const n=(e||"").trim();return n&&Ba(s).find(a=>a.id===n)?.url||null},Mf=wf,_a=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(kf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Hr=e=>e.name.trim().length>0&&e.command.trim().length>0,Ff=e=>e.name.trim().length===0&&e.command.trim().length===0,Lf=e=>!Hr(e)&&!Ff(e),Of=(e,s)=>e.some(r=>s.has(r.id)&&!Hr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Hr)},Bf=450,_f=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,zf=()=>({id:_f(),name:"",command:"",icon:"play"}),$f=({projectRef:e})=>{const s=o.useMemo(()=>ys(),[]),n=Un(b=>b.instances),r=Un(b=>b.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[f,p]=o.useState(new Set),g=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let b=!1;return c(!0),(async()=>{try{const L=await Nr(e);if(b)return;a(L.actions),u(JSON.stringify({actions:L.actions})),p(new Set(L.actions.map(A=>A.id)))}catch{if(b)return;a([]),u(JSON.stringify({actions:[]})),p(new Set)}finally{b||c(!1)}})(),()=>{b=!0}},[e]);const m=o.useMemo(()=>s?Ba(n):[],[n,s]),h=o.useMemo(()=>Of(i,f),[i,f]),x=o.useMemo(()=>JSON.stringify({actions:h.actions}),[h.actions]),j=d!==null&&h.canPersist&&x!==d,k=o.useCallback(async b=>await Rc(e,{actions:b,primaryActionId:null})?(u(JSON.stringify({actions:b})),p(new Set(b.map(A=>A.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Kr,{detail:{projectId:e.id}})),!0):(le.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!j||l||g.current)return;const b=window.setTimeout(()=>{g.current||(g.current=!0,(async()=>{try{await k(h.actions)}finally{g.current=!1}})())},Bf);return()=>{window.clearTimeout(b)}},[j,l,k,h.actions]);const B=o.useCallback(()=>{const b=zf();a(L=>[...L,b])},[]),S=o.useCallback(b=>{a(L=>L.filter(A=>A.id!==b))},[]),v=o.useCallback((b,L)=>{a(A=>A.map(C=>C.id===b?L(C):C))},[]);return t.jsx(_a,{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:B,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:O("space-y-6",Mf),children:i.map((b,L)=>{const A=b.icon||"play",C=cn[A]||"play",I=b.name.trim()||`Action ${L+1}`,P=Lf(b);return t.jsxs("div",{className:Ma,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Fa,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:()=>S(b.id),"aria-label":`Delete ${I}`,children:t.jsx(N,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Us,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Yt,{children:[t.jsx(Vt,{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(Qt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:La.map(D=>{const H=D.Icon,ee=(b.icon||"play")===D.key;return t.jsx("button",{type:"button",onClick:()=>v(b.id,Z=>({...Z,icon:D.key})),className:O("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:H,className:"h-4 w-4"})},D.key)})})})]}),t.jsx(Ws,{value:b.name,onChange:D=>v(b.id,H=>({...H,name:D.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Us,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(ho,{value:b.command,onChange:D=>v(b.id,H=>({...H,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(Af,{checked:b.autoOpenUrl===!0,onChange:D=>v(b.id,H=>({...H,...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}`}),b.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Us,{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:b.openUrl||"",onChange:D=>v(b.id,H=>({...H,openUrl:D.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Us,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:m.length>0?t.jsxs(Mc,{value:b.desktopOpenSshForward&&m.some(D=>D.id===b.desktopOpenSshForward)?b.desktopOpenSshForward:"__none__",onValueChange:D=>{v(b.id,H=>({...H,...D==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:D}}))},children:[t.jsx(Fc,{size:yf,className:"w-full",children:t.jsx(Lc,{placeholder:"Use output/manual URL"})}),t.jsxs(Oc,{children:[t.jsx($o,{value:"__none__",children:"Use output/manual URL"}),m.map(D=>t.jsx($o,{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]},b.id)})})})},Uf={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)"},Gf=({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),f=ue(P=>P.providerOrder),p=ue(P=>P.setProviderOrder),g=ue(P=>P.isFavoriteModel),m=ue(P=>P.toggleFavoriteModel),h=ue(P=>P.reorderFavoriteModel),{favoriteModelsList:x,recentModelsList:j}=Bc(),[k,B]=o.useState(!1),[S,v]=o.useState("");o.useEffect(()=>{k||v("")},[k]);const b=e?c.find(P=>P.id===e.providerId):void 0,L=e&&b?(Array.isArray(b.models)?b.models:[]).find(P=>P.id===e.modelId):void 0,A=e?_c(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}),B(!1)},[l]);return t.jsxs(Yt,{modal:!1,open:k,onOpenChange:P=>{r||B(P)},children:[t.jsx(Vt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:O($c({size:"default"}),vf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(zc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:O("truncate",e?"text-foreground":"text-muted-foreground"),children:A})]}),t.jsx(N,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Uc,{providers:c,favoriteModels:x,recentModels:j,modelsMetadata:d,searchQuery:S,onSearchQueryChange:v,onSelect:I,labels:{...Uf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),B(!1)},disabled:r,autoFocus:!0,onEscape:()=>B(!1),isFavorite:P=>g(P.providerID,P.modelID),onToggleFavorite:P=>m(P.providerID,P.modelID),onReorderFavorite:(P,D)=>h(P.providerID,P.modelID,D.providerID,D.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:f,onReorderProvider:p,reorderProviderTitle:"Drag to reorder provider"})})]})},cr="w-full max-w-none",Kf=({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(_a,{title:"Project",divider:!1,children:t.jsxs("div",{className:Ma,children:[t.jsx(Us,{label:"Name",settingsItem:"projects.name",controlClassName:cr,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(Us,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:cr,children:t.jsx(Gf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:cr,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},Hf=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(()=>Gc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,f)=>{i(u&&f?`${u}/${f}`: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}},Wf=450,Yf=(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}})())},Wf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Vf=({project:e,onIdentitySave:s})=>{const n=Hf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Yf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Kf,{form:n}),t.jsx($f,{projectRef:r})]})};function Qf({...e}){return t.jsx(Sa,{...e})}function qf({...e}){return t.jsx(ja,{...e})}function Jf({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(Or,{children:t.jsx(Br,{className:O("app-region-no-drag z-50",s),children:t.jsx(_r,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:O(Ar,e),...i,children:n})})})}function ui({className:e,...s}){return t.jsx(Ca,{className:O(Xi,e),...s})}function Xf({className:e,...s}){return t.jsx(ka,{className:O(Zi,e),...s})}const ks=ps()(Na(io((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 Qc();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 Vc();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 Yc();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=so()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await Xt("/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 to({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 ds("saving"),await Wc(r),ds("saved"),await s().loadProfiles(),!0}catch(r){return ds("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 ds("saving"),await Hc(n,a),ds("saved"),await s().loadProfiles(),!0}catch(i){return ds("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return ds("saving"),await Kc(n),ds("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ds("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:eu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ks);const Zf=[{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"]}],eh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function th(e){const s=e.trim().toLowerCase();return Zf.find(n=>n.slug===s)??null}function sh(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=eh[s];if(n)return n;const r=th(s);return r?r.slug:"home"}function yx(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 Cn=100;function vx(){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=Es(C=>C.homeDirectory),l=Ir({archived:!0}),[c,d]=o.useState(""),[u,f]=o.useState(null),[p,g]=o.useState(Cn),m=c.trim().toLowerCase(),h=o.useMemo(()=>e?[...l].sort((C,I)=>(I.time?.archived??0)-(C.time?.archived??0)):[],[l,e]),x=o.useMemo(()=>{const C=new Map;for(const I of h){const P=Xe(Gs(I))??"",D=C.get(P);if(D){D.sessions.push(I);continue}C.set(P,{directory:P,label:P?Ts(P,a)||P:"other projects",sessions:[I]})}return[...C.values()].sort((I,P)=>P.sessions.length-I.sessions.length)},[a,h]),j=o.useMemo(()=>m?h.filter(C=>(C.title??"").toLowerCase().includes(m)):u===null?h:x.find(C=>C.directory===u)?.sessions??[],[x,m,u,h]),k=j.slice(0,p),B=j.length-k.length,S=l.length,v=o.useCallback(C=>{f(C),g(Cn)},[]),b=o.useCallback(C=>{const I=Xe(Gs(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,H,ee,Z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:H,title:ee,className:O("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:()=>Ps.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(Ru,{open:e,onOpenChange:s,children:t.jsxs(Mu,{children:[t.jsx(Fu,{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(Lu,{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(Ou,{className:"sr-only",children:"Archived sessions"}),t.jsx(Bu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(_u,{"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",S,u===null,()=>v(null)),x.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),g(Cn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:j.length===1?`${j.length} archived session`:`${j.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[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:m?"No matching archived sessions":"No archived sessions"})}):k.map(C=>{const I=Xe(Gs(C))??"",P=I?Ts(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:()=>b(C),role:"button",tabIndex:0,onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),b(C))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:C.title||"Untitled Session"}),m&&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:ju(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(),Ps.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)}),B>0?t.jsx("button",{type:"button",onClick:()=>g(C=>C+Cn),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 nh=()=>{const[e,s]=Qe.useState(!1),[n,r]=Qe.useState(!1);Qe.useEffect(()=>{s(ys()),r(no())},[]);const i=Qe.useCallback(async c=>e?await ro(c):{success:!0,path:c},[e]),a=Qe.useCallback(async c=>e?await tu():{success:!0},[e]),l=Qe.useCallback(async c=>e?await su():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},rh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),oh=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[f,p]=o.useState(""),[g,m]=o.useState(!1),[h,x]=o.useState(!1),[j,k]=o.useState(""),[B,S]=o.useState(!1),v=o.useRef(null),b=o.useCallback($=>{$.stopPropagation()},[]),L=l.length>1,A=o.useMemo(()=>rh(j),[j]),C=o.useMemo(()=>{const $=f.toLowerCase();return $?s.filter(K=>K.toLowerCase().includes($)):s},[f,s]),I=o.useMemo(()=>{const $=f.toLowerCase();return $?n.filter(K=>K.toLowerCase().includes($)):n},[f,n]),P=$=>{if($===e){u(!1);return}i($),u(!1),p("")},D=()=>{m(!0),setTimeout(()=>v.current?.focus(),50)},H=async()=>{if(!(!A||B)){if(L){x(!0);return}S(!0);try{await a(A,l[0]),k(""),m(!1),u(!1)}finally{S(!1)}}},ee=async $=>{if(!(!A||B)){S(!0);try{await a(A,$),k(""),m(!1),x(!1),u(!1)}finally{S(!1)}}},Z=()=>{x(!1)},ie=()=>{k(""),m(!1),x(!1)};return o.useEffect(()=>{d||(p(""),m(!1),x(!1),k(""))},[d]),t.jsxs(Yt,{open:d,onOpenChange:u,children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Vt,{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(Qt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(qc,{className:"h-full min-h-0",children:[t.jsx(Jc,{placeholder:"Search branches...",value:f,onValueChange:p,onKeyDown:b}),t.jsxs(Xc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(Zc,{children:"No branches found."}),t.jsx(or,{children:h?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:B,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($=>t.jsxs("button",{type:"button",onClick:()=>ee($),disabled:B,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:[B?t.jsx(N,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,$.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:$.pushUrl})]},$.name))})]}):g?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:j,onChange:$=>k($.target.value),onClick:$=>$.stopPropagation(),onKeyDown:$=>{b($),$.key==="Enter"?($.preventDefault(),H()):$.key==="Escape"&&($.preventDefault(),ie())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:H,disabled:!A||B,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:B?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:B,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(N,{name:"close",className:"size-4"})})]}):t.jsxs(Js,{onSelect:D,children:[t.jsx(N,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Uo,{}),t.jsxs(or,{heading:"Local branches",children:[C.map($=>t.jsxs(Js,{onSelect:()=>P($),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:$}),(r?.[$]?.ahead||r?.[$]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[$].ahead||0," ahead ·"," ",r[$].behind||0," behind"]})]}),e===$&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${$}`)),C.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Uo,{}),t.jsxs(or,{heading:"Remote branches",children:[I.map($=>t.jsx(Js,{onSelect:()=>P($),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:$})},`remote-${$}`)),I.length===0&&t.jsx(Js,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},ih=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ah=({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),f=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},p=async()=>{if(!e||!s||!a.trim())return;const h=ih(a);if(h===e){i(!1);return}d(!0);try{await s(e,h),i(!1),l("")}finally{d(!1)}},g=()=>{i(!1),l("")},m=h=>{h.key==="Enter"?(h.preventDefault(),p()):h.key==="Escape"&&(h.preventDefault(),g())};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:h=>{h.preventDefault(),p()},children:[t.jsx(N,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:h=>l(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:m,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:g,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:f,title:"Rename branch",children:t.jsx(N,{name:"edit",className:"size-4"})})]})]})},lh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:f=!1})=>{const p=o.useRef(!1),g=!!l,m=s.find(b=>b.name===u)??s[0],h=d>0&&f,x=a||e!==null||g||!m||h,j=a||e!==null||g||s.length===0,k=c>0||d>0,B=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),S=h?"Commit or stash your changes before syncing":m?k?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",v=()=>{m&&r(m)};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:h?0:void 0,children:t.jsxs("button",{type:"button",onClick:v,disabled:x,className:O("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:B})]})})}),t.jsx(it,{sideOffset:8,children:S})]}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:j,"aria-label":"More sync actions",children:t.jsx(N,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Qt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(b=>t.jsx(jt,{onSelect:L=>{if(p.current){L.preventDefault(),p.current=!1;return}n(b)},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 ${b.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:b.fetchUrl})]})}),i&&b.name!==u?t.jsx(qe,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||g,onPointerDown:L=>{p.current=!0,L.preventDefault(),L.stopPropagation()},onClick:L=>{p.current=!0,L.preventDefault(),L.stopPropagation(),i(b)},"aria-label":`Remove remote ${b.name}`,title:`Remove remote ${b.name}`,children:l===b.name?t.jsx(N,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(N,{name:"close",className:"size-3.5"})}):null]})},b.name))})]})]})},ch={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},dh={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 za(e){return e&&dh[e]||"var(--primary)"}const fi=({icon:e,className:s,colorToken:n})=>{const r=ch[e??"branch"]??"user-3";return t.jsx(N,{name:r,className:s,style:{color:za(n)}})},$a=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Yt,{children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Vt,{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:za(e?.color)},disabled:a,children:[r?t.jsx(N,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(fi,{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(Qt,{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(jt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(fi,{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)})})]})},uh=({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})]})},wx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:f,onCreateBranch:p,onRenameBranch:g,activeIdentityProfile:m,availableIdentities:h,onSelectIdentity:x,isApplyingIdentity:j,isWorktreeMode:k,onOpenHistory:B,onOpenGraph:S,onOpenStashes:v,onOpenUpdateBranch:b,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:B||S||v||b?t.jsxs(Yt,{children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Vt,{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(Qt,{align:"end",children:[B?t.jsxs(jt,{onSelect:B,children:[t.jsx(N,{name:"history",className:"size-4"}),"History"]}):null,S?t.jsxs(jt,{onSelect:S,children:[t.jsx(N,{name:"git-branch",className:"size-4"}),"Graph"]}):null,v?t.jsxs(jt,{onSelect:v,children:[t.jsx(N,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,b?t.jsxs(jt,{onSelect:b,children:[t.jsx(N,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,L?t.jsxs(jt,{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,H=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-${H})`}}),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(lh,{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(uh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,$=t.jsx($a,{activeProfile:m,identities:h,onSelect:x,isApplying:j,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:k?t.jsx(ah,{currentBranch:e.current,onRename:g}):t.jsx(oh,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:f,onCreate:p,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:$})]}),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})]})]})},fh=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Vs=e=>{if(!e||fh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Hs=e=>e.endsWith("/"),Gn=e=>{const s=e.trim();return!s||Hs(s)?s:`${s}/`},po=e=>e.lastIndexOf("/"),Ua=e=>{if(Hs(e))return e;const s=po(e);return s<0?e:e.slice(0,s+1)},Ga=e=>{const s=po(e);return e.slice(s+1)},Ka=e=>{const s=Vs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=po(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Ha=e=>Hs(e)&&Ka(e)!==null,hh=e=>{if(!Ha(e))return null;const s=Vs(e.trim());return Ga(s)||s},ph=(e,s)=>`${Ua(e)}${s}/`,js=e=>{if(!e)return null;const s=Vs(Ks(e.trim()));return s?s.toLowerCase():null},hi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},mh=(e,s)=>{const n=Vs(Ks(e.trim())),r=Vs(Ks(s.trim()));if(!n)return"";if(!r)return Gn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Gn(n)},gh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,dr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},xh=async()=>iu(),bh=({open:e,onOpenChange:s})=>{const n=Es(M=>M.homeDirectory),r=_t(M=>M.projects),i=_t(M=>M.addProject),a=ue(M=>M.setActiveMainTab),l=ue(M=>M.setSessionSwitcherOpen),c=_e(M=>M.openNewSessionDraft),d=ks(M=>M.profiles),u=ks(M=>M.globalIdentity),f=ks(M=>M.defaultGitIdentityId),p=ks(M=>M.loadProfiles),g=ks(M=>M.loadGlobalIdentity),m=ks(M=>M.loadDefaultGitIdentityId),{canRequestAccess:h,startAccessing:x}=nh(),{isMobile:j,isTablet:k}=Rs(),B=j||k,S=o.useRef(null),v=o.useRef(new Map),[b,L]=o.useState(""),[A,C]=o.useState("~/"),[I,P]=o.useState([]),[D,H]=o.useState(!1),[ee,Z]=o.useState(!1),[ie,$]=o.useState(null),[K,E]=o.useState(0),[R,Y]=o.useState(0),[oe,U]=o.useState(!1),[Te,Le]=o.useState(!1),[Ve,Ge]=o.useState(!1),[Ke,Oe]=o.useState(""),[se,fe]=o.useState(null),[He,ke]=o.useState(!1),[Ce,We]=o.useState("right"),tt=o.useRef("~/"),ze=b||n,q=o.useMemo(()=>new Set(r.map(M=>js(M.path)).filter(M=>!!M)),[r]);o.useEffect(()=>{if(!e)return;C("~/"),P([]),Y(0),U(!1),Le(!1),Ge(!1),Oe(""),fe(null),ke(!1),tt.current="~/",We("right"),B||requestAnimationFrame(()=>dr(S.current));let M=!1;return(async()=>{const Be=await xh();M||(L(Be||n||""),B||requestAnimationFrame(()=>dr(S.current)))})(),()=>{M=!0}},[n,e,B]),o.useEffect(()=>{e&&(p(),g(),m())},[m,p,g,e]);const V=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||!Ve||se!==null)return;const M=typeof f=="string"?f.trim():"";if(M&&V.some(Be=>Be.id===M)){fe(M);return}const je=V.find(Be=>Be.authType==="ssh"||Be.sshKey);je&&fe(je.id)},[V,f,Ve,e,se]);const ge=o.useMemo(()=>V.find(M=>M.id===se)??null,[V,se]),J=o.useMemo(()=>Ua(A),[A]),we=o.useMemo(()=>Hs(A)?"":Ga(A),[A]),xe=o.useMemo(()=>ze?hi(J,ze):"",[J,ze]);o.useEffect(()=>{const M=tt.current;M!==J&&(We(J.length>=M.length?"right":"left"),tt.current=J)},[J]),o.useEffect(()=>{if(!e||!xe){P([]),$(null);return}let M=!1;return H(!0),Z(!1),$(null),nu(xe).then(je=>{if(M)return;Z(!1),$(null);const Be=je.filter(ct=>ct.isDirectory).map(ct=>({name:ct.name,path:Ks(ct.path)})).sort((ct,F)=>ct.name.localeCompare(F.name));P(Be)}).catch(je=>{if(!M){P([]);const Be=ru(je)?je.reason:"unknown";$(Be),Z(Be==="not-found")}}).finally(()=>{M||H(!1)}),()=>{M=!0}},[xe,K,e]);const Ie=o.useMemo(()=>{const M=we.toLowerCase(),je=He||we.startsWith(".");return I.filter(Be=>Be.name.toLowerCase().startsWith(M)&&(je||!Be.name.startsWith(".")))},[we,I,He]),ft=o.useMemo(()=>hh(A),[A]),mt=o.useMemo(()=>Ka(A),[A]),Ze=o.useMemo(()=>{const M=[],je=js(xe);Ha(A)&&ft&&mt&&M.push({type:"parent",value:"browse:up",name:ft,path:mt,alreadyAdded:!!(je&&q.has(je))});for(const Be of Ie){const ct=js(Be.path);M.push({type:"directory",value:`browse:${Be.path}`,name:Be.name,path:Be.path,alreadyAdded:!!(ct&&q.has(ct))})}return M},[q,xe,ft,Ie,mt,A]);o.useEffect(()=>{Y(0)},[A,Ze.length]);const Pe=o.useMemo(()=>ze?Vs(hi(A,ze)):"",[ze,A]),Re=js(Pe),Ne=!!(Re&&q.has(Re)),at=o.useMemo(()=>we?Ie.find(M=>M.name===we)??null:null,[we,Ie]),Ct=!!(Pe&&!Ne&&(ie===null||ie==="not-found")&&(Hs(A)&&ee||!Hs(A)&&we.trim().length>0&&at===null)),st=!oe&&!Te&&!Ne&&ie!=="os-permission"&&ie!=="invalid-response"&&ie!=="unknown"&&!!Pe,_=st&&Ke.trim().length>0,ye=Ze[R]??null,be=!!ye,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",W=Ne?"Already added":Ve?oe?"Cloning...":"Clone & add":oe?"Adding...":Ct?"Create & add":"Add folder",ne=Ve?_:st;o.useLayoutEffect(()=>{const M=S.current;M&&(M.scrollLeft=M.scrollWidth)},[A]),o.useLayoutEffect(()=>{!e||B||dr(S.current)},[e,B]),o.useLayoutEffect(()=>{const M=Ze[R];M&&v.current.get(M.value)?.scrollIntoView({block:"nearest"})},[R,Ze]);const de=o.useCallback(()=>{s(!1)},[s]),Se=o.useCallback((M,je)=>{a("chat"),j&&l(!1),c({selectedProjectId:M,directoryOverride:je}),de()},[de,j,c,a,l]),De=o.useCallback(async M=>{if(!M||oe)return;const je=js(M);if(je&&q.has(je))return;let Be=M;U(!0);try{const ct=!Ve&&Ct&&js(M)===js(Pe);if(Ve){const ae=Ke.trim();if(!ae){le.error("Enter a repository URL before cloning.");return}const he=await Xt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:ae,destinationPath:M,gitIdentityId:ge?.id??null})});if(!he.ok)throw new Error("Failed to clone git repository");Be=(await he.json()).path||M}else if(ct&&!(await Xt("/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(ct){le.error("Failed to select directory",{description:ct instanceof Error?ct.message:"Unknown error occurred."})}finally{U(!1)}},[i,q,xe,Ke,Ve,oe,Se,ge?.id,Ct,Pe]),$e=o.useCallback(M=>{C(Gn(M))},[]),ht=o.useCallback(M=>{C(ph(A,M.name))},[A]),kt=o.useCallback(M=>{if(M){if(M.type==="parent"){$e(M.path);return}ht(M)}},[$e,ht]),et=o.useCallback(async M=>{const je=await x(M);if(!je.success)return le.error("Failed to open directory",{description:je.error||"Desktop could not grant file access."}),!1;const Be=ze?mh(M,ze):Gn(Ks(M));return $e(Be),!0},[$e,ze,x]),pt=o.useCallback(async()=>{if(!Te){Le(!0);try{if(no()){const je=await ro(Pe);if(!je.success||!je.path){je.error&&je.error!=="Directory selection cancelled"&&le.error("Failed to select directory",{description:je.error});return}await et(je.path);return}const M=await ou(Pe);if(M.status==="cancelled")return;if(M.status!=="picked"){le.error("Couldn't open a folder picker",{description:M.error});return}await et(M.path)}catch(M){le.error("Failed to select directory",{description:M instanceof Error?M.message:"Unknown error occurred."})}finally{Le(!1)}}},[et,Te,Pe]),gt=o.useCallback(M=>{if(M.key==="ArrowDown"){M.preventDefault(),Y(je=>Math.min(Ze.length-1,je+1));return}if(M.key==="ArrowUp"){M.preventDefault(),Y(je=>Math.max(0,je-1));return}if(M.key==="Enter"){if(M.preventDefault(),gh(M)){De(Pe);return}be&&kt(ye);return}M.key==="Backspace"&&A===""&&(M.preventDefault(),de())},[kt,De,de,be,ye,A,Ze.length,Pe]),Me=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:[He?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"]}),Ye=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:S,value:A,onChange:M=>C(Ks(M.target.value)),onKeyDown:gt,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||Te,onMouseDown:M=>M.preventDefault(),onClick:()=>{pt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(N,{name:"folder-open",className:"h-3.5 w-3.5"}),Te?"Opening...":"Browse"]})]})}),xt=Ze.some(M=>M.type==="parent"),Lt=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":Ve,disabled:oe||Te,onClick:()=>Ge(M=>!M),children:[t.jsx(N,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ve?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:Ke,onChange:M=>Oe(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($a,{activeProfile:ge,identities:V,onSelect:M=>fe(M.id),isApplying:oe,iconOnly:!0})]})]}):null,Ne?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:O("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"&&h?t.jsx(qe,{size:"xs",onClick:()=>{pt()},disabled:Te,children:"Grant access"}):null,t.jsx(qe,{variant:"outline",size:"xs",onClick:()=>E(M=>M+1),children:"Try again"})]})]}):Ze.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:Ze.map((M,je)=>{const Be=je===R,ct=M.type==="directory"&&xt;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:()=>Y(je),onMouseDown:F=>F.preventDefault(),onClick:()=>kt(M),className:O("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:O("flex min-w-0 flex-1 items-center gap-2",ct&&"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:O("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)})})},J)]})}),zt=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Ye,Lt]}),At=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"]})]}),It=t.jsx(qe,{size:j?"xs":"default",onClick:()=>{De(Pe)},disabled:!ne,className:O(j&&"w-full flex-1"),children:W}),Dt=()=>t.jsxs(t.Fragment,{children:[j?null:At,t.jsx("div",{className:O("flex w-full flex-row justify-end gap-2 sm:w-auto",j&&"justify-stretch"),children:It})]});return j?t.jsx(ea,{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:Dt()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Me}),zt]})}):t.jsx(is,{open:e,onOpenChange:s,children:t.jsxs(as,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(vs,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Ms,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Me]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:zt}),t.jsx(Fs,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:Dt()})]})})},kn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Sx=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=ed,c=_e(L=>L.deleteSessions),d=ue(L=>L.showDeletionDialog),u=ue(L=>L.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:g}=Rs(),m=f||p||g;o.useEffect(()=>au(()=>{s(!1)}),[]);const h=o.useCallback(L=>{r({sessions:L.sessions,dateLabel:L.dateLabel})},[]),x=o.useCallback(()=>{r(null),a(!1)},[]),j=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:kn(P)})}I.length>0&&le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:kn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Ps.onDeleteRequest(L=>{if(!d){j(L);return}h(L)}),[h,d,j]),o.useEffect(()=>Ps.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:kn(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:kn("Please try again in a moment.")}),C.length===0)){a(!1);return}}x()}finally{a(!1)}}},[n,l,c,x]),B=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.`:"",S=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:x,disabled:i,children:"Cancel"}),t.jsx(qe,{variant:"destructive",onClick:k,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),b=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(ea,{open:!!n,onClose:()=>{i||x()},title:b,footer:t.jsx("div",{className:"flex justify-end gap-2",children:v}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[B&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:B}),S]})}):t.jsx(is,{open:!!n,onOpenChange:L=>{if(!L){if(i)return;x()}},children:t.jsxs(as,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(vs,{children:[t.jsx(hs,{children:b}),B&&t.jsx(Ms,{children:B})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:S}),t.jsx(Fs,{className:"mt-2 gap-2 pt-1 pb-1",children:v})]})}),t.jsx(bh,{open:e,onOpenChange:s})]})};function jx(){const e=o.useRef(!1),s=o.useRef(!1),n=_e(f=>f.setCurrentSession),r=ue(f=>f.setActiveMainTab),i=ue(f=>f.setSettingsDialogOpen),a=ue(f=>f.setSettingsPage),l=ue(f=>f.navigateToDiff),c=o.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=_e.getState().currentSessionId,g=Xs().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==g){const m=_e.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,m)}}if(f.settingsPath){a(sh(f.settingsPath)),i(!0);return}ue.getState().isSettingsDialogOpen&&i(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const f=_e.getState(),p=Xs().getState(),g=ue.getState();return{sessionId:ir({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:g.activeMainTab,isSettingsOpen:g.isSettingsDialogOpen,settingsPath:g.settingsPage,diffFile:g.pendingDiffFile}},[]),u=o.useCallback((f={})=>{if(s.current)return;const p=d();$r(p,f)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Go()))return;const f=Ko();(async()=>(await c(f),$r({...d(),sessionId:f.sessionId??ir({currentSessionId:_e.getState().currentSessionId,piSelectedSessionId:Xs().getState().selectedSessionId,draft:_e.getState().newSessionDraft}),tab:f.tab??ue.getState().activeMainTab,settingsPath:f.settingsPath??ue.getState().settingsPage,diffFile:f.diffFile??ue.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const f=()=>{const j=_e.getState(),k=Xs().getState();return ir({currentSessionId:j.currentSessionId,piSelectedSessionId:k.selectedSessionId,draft:j.newSessionDraft})};let p=f(),g=_e.getState().newSessionDraft?.open===!0;const m=()=>{const j=_e.getState(),k=f(),B=j.newSessionDraft?.open===!0;k===p&&B===g||s.current||(p=k,g=B,u({replace:!0}))},h=_e.subscribe(()=>{m()}),x=Xs().subscribe(()=>{m()});return()=>{h(),x()}},[u]),o.useEffect(()=>{let f=ue.getState().activeMainTab,p=ue.getState().isSettingsDialogOpen,g=ue.getState().settingsPage,m=ue.getState().pendingDiffFile;return ue.subscribe(x=>{if(s.current)return;const j=x.activeMainTab!==f,k=x.isSettingsDialogOpen!==p,B=x.settingsPage!==g,S=x.pendingDiffFile!==m&&x.activeMainTab==="diff";f=x.activeMainTab,p=x.isSettingsDialogOpen,g=x.settingsPage,m=x.pendingDiffFile,(j||k||B||S)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Ko();if(Go())c(p);else{const g=ue.getState();g.isSettingsDialogOpen&&i(!1),g.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,i])}function yh(e=!0){const s=Ln(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=p=>{const g=Math.round(p*1e3);return Math.max(a,Math.min(l,g))},f=p=>{c||(d=window.setTimeout(async()=>{const g=await n.current(),m=typeof g=="number"&&Number.isFinite(g)?u(g):i;f(m)},p))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Cx(){const e=nn(s=>s.connection==="ready",void 0,"chrome");return yh(e),null}const pi=12,vh=[{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"}],wh=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=vh,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:pi},(d,u)=>{const f=Math.PI*2*u/pi;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?t.jsx("div",{className:O("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((f,p)=>{const g=f.x*d.radius,m=f.y*d.radius,h={"--translate-x":`${g}px`,"--translate-y":`${m}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:h},`${d.id}-${p}-${s}`)})},`${d.id}-${s}`)})}):null},Sh=({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}},Wa=o.createContext(void 0),kx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Sh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Wa.Provider,{value:a,children:[e,t.jsx(wh,{isActive:s,burstKey:n})]})},jh={triggerFireworks:()=>{},dismissFireworks:()=>{}},Nx=()=>o.useContext(Wa)??jh,mi=380,gi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Kn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Nn=({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})]}),Ch=({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}=Xr(),f=o.useRef(null),[p,g]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const h=()=>{const k=n.current?.getBoundingClientRect(),B=f.current?.getBoundingClientRect();if(!k||!B){g(null);return}const S=k.left-B.left,v=Math.min(Math.max(S,8),Math.max(8,B.width-mi-8));g(v)};h();const x=f.current;if(typeof ResizeObserver>"u"||!x)return;const j=new ResizeObserver(h);return j.observe(x),()=>j.disconnect()},[n,u,e,a]);const m=u&&p!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const h=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(h)},[e,a]),o.useEffect(()=>{if(!e)return;const h=x=>{x.key==="Escape"&&s()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[s,e]),o.useEffect(()=>{if(!e)return;const h=x=>{const j=x.target;if(!(j instanceof Node)){s();return}i.current?.contains(j)||n.current?.contains(j)||s()};return document.addEventListener("pointerdown",h,!0),document.addEventListener("wheel",h,!0),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("wheel",h,!0)}},[n,s,e]),a?t.jsxs("div",{ref:f,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:O("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",m?"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))",...m?{top:8,left:p??8,width:`min(${mi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Nn,{iconNode:t.jsx(sa,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:O("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(Nn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Kn(r.cacheRead)})}),t.jsx(Nn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Kn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Nn,{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},kh=o.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:i,isNewSessionDraftOpen:a}){const l=o.useRef(null),c=td(r??""),d=Ot($=>$.providers),u=Ot($=>$.currentProviderId),f=Ot($=>$.currentModelId),p=Ot($=>$.getCurrentModel()),g=Ot($=>$.getModelMetadata);Ot($=>$.modelsMetadata.size);const m=ta(o.useCallback($=>r?$.sessionModelSelections.get(r)??null:null,[r])),h=o.useMemo(()=>{for(let $=c.length-1;$>=0;$-=1){const K=c[$]?.info;if(K.role!=="user")continue;const E=K.model,R=E?.providerID??E?.providerId,Y=E?.modelID??E?.modelId,oe=typeof R=="string"&&R.trim().length>0?R:void 0,U=typeof Y=="string"&&Y.trim().length>0?Y:void 0;if(oe&&U)return{providerID:oe,modelID:U}}return null},[c]),x=o.useMemo(()=>{for(let $=c.length-1;$>=0;$-=1){const K=c[$];if(K?.info.role==="assistant"&&Ho(K).total>0)return K}return null},[c]),j=h??(()=>{const $=x?.info.model,K=$?.providerID??$?.providerId,E=$?.modelID??$?.modelId;return K&&E?{providerID:K,modelID:E}:null})()??(m?{providerID:m.providerId,modelID:m.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),B=(j?d.find($=>$.id===j.providerID):void 0)?.models.find($=>$.id===j?.modelID),S=j?g(j.providerID,j.modelID):void 0,v=gi(B?.limit,"context")??S?.limit?.context??gi(p?.limit,"context")??0,b=x?Ho(x):null,L=x?.info?.usage,A=L?sd(L):b?.total??0,C=!a&&A>0&&v>0?Math.min(A/v*100,999):null,I=C!==null?`${Kn(A)}/${Kn(v)}`:null,P=C===null?"":C>=90?"text-[var(--status-error)]":C>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",D=b?.cacheRead??null,H=b?.cacheWrite??null,ee=b?nd({input:b.input,cache:{read:b.cacheRead,write:b.cacheWrite}}):{percent:0,hasInput:!1},Z=ee.hasInput?ee.percent:null,ie=C!==null&&I?{percentage:C,tokens:I,colorClass:P,cacheRead:D,cacheWrite:H,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($=>!$),style:{touchAction:"manipulation"},children:t.jsx(sa,{percentage:ie?.percentage??0})}),t.jsx(Ch,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:ie})]})}),xi=600,Nh=1,Ah=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},Ih=({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,f=o.useCallback(h=>`${h.directory}
12
- ${h.sessionId}`,[]),p=o.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(h=>window.clearTimeout(h)),a.current.clear()},[]),g=o.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<Nh&&l.current.length>0;){const h=l.current.shift();if(!h)break;h.generation!==d.current||_e.getState().currentSessionId===h.sessionId||rd(h.sessionId,h.directory).renderable}},[e,u,i,f]),m=o.useCallback(h=>{const x=h?.id,j=Ah(h);if(!e||u||!x||!j||x===s||typeof window>"u")return;const k={sessionId:x,directory:j,generation:d.current};f(k)},[s,e,u,g,f]);o.useEffect(()=>{p()},[p,s,e,u]),o.useEffect(()=>{if(!e||u||!s||n.length===0)return;const h=window.setTimeout(()=>{const x=n.findIndex(j=>j.id===s);x<0||(m(n[x-1]),m(n[x+1]))},xi);return()=>window.clearTimeout(h)},[s,e,u,m,n]),o.useEffect(()=>{if(!e||u||!s||r.length===0)return;const h=window.setTimeout(()=>{const x=r.findIndex(j=>j.id===s);x<0||(m(r[x-1]),m(r[x+1]))},xi);return()=>window.clearTimeout(h)},[s,e,u,r,m]),o.useEffect(()=>p,[p])},Dh=e=>{const s=_e(n=>n.currentSessionId);return Ih({...e,currentSessionId:s}),null},Ph=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:i,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:f}=e;o.useEffect(()=>{!n||i||!a||l||s.forEach(p=>{if(c.has(p.normalizedPath))return;const g=ya(p.normalizedPath),m=r.archivedSessionsByProject.get(p.id)??[],h=d[g]??[],x=new Map(h.map(j=>[j.name.toLowerCase(),j]));m.forEach(j=>{const k=Cu(j,p.normalizedPath),B=k.toLowerCase();let S=x.get(B);S||(S=u(g,k),x.set(B,S)),S.sessionIds.includes(j.id)||f(g,S.id,j.id)})})},[s,n,r,i,a,l,c,d,u,f])},Eh=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 f=a.get(u);f&&(l.push(f),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])}),Th=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:i,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:g,foldersMap:m}=e,h=o.useRef(new Map),x=o.useMemo(()=>{const A=h.current,C=new Map;let I=0,P=0;const D=(ee,Z)=>ee.length===Z.length&&ee.every((ie,$)=>ie===Z[$]),H=s.map(ee=>{const Z=n(ee.id),ie=r(ee.id),$=a.has(ee.id)?!!a.get(ee.id):c,K=l.get(ee.id)??null,E=i.get(ee.normalizedPath)??[],R=A.get(ee.id);if(R&&R.project===ee&&D(R.activeSessions,Z)&&D(R.archivedSessions,ie)&&R.rootBranch===K&&R.isRepo===$&&R.worktrees===E&&R.buildGroupedSessions===d)return I+=1,C.set(ee.id,R),R.section;P+=1;const Y=va([...Z,...ie]),oe=d(Y,ee.normalizedPath,E,K,$),U={project:ee,groups:oe};return C.set(ee.id,{project:ee,activeSessions:Z,archivedSessions:ie,rootBranch:K,isRepo:$,worktrees:E,buildGroupedSessions:d,section:U}),U});return h.current=C,I>0&&rs("ui.sidebar.project_section.reused",I),P>0&&rs("ui.sidebar.project_section.rebuilt",P),H},[s,n,r,i,a,c,d,l]),j=o.useMemo(()=>x,[x]),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 j.forEach(I=>{I.groups.forEach(P=>{const D=p(P.sessions,f),H=C(D),ee=g(P).includes(f),Z=Xe(P.directory??null),$=(Z?m[Z]??[]:[]).filter(K=>K.name.toLowerCase().includes(f)).length;A.set(P,{filteredNodes:D,matchedSessionCount:H,folderNameMatchCount:$,groupMatches:ee,hasMatch:ee||H>0||$>0})})}),A},[u,j,p,f,g,m]),B=o.useMemo(()=>u?j.map(A=>({...A,groups:A.groups.filter(C=>k.get(C)?.hasMatch===!0)})).filter(A=>A.groups.length>0):j,[u,j,k]),S=u?B:j,v=o.useRef(new WeakMap),b=o.useMemo(()=>{const A=v.current;return S.map(C=>{const I=A.get(C);if(I&&I.query===f)return I.section;const P=C.groups.filter(K=>!K.isArchivedBucket),D=C.groups.filter(K=>K.isArchivedBucket),H=P.flatMap(K=>u?k.get(K)?.filteredNodes??[]:K.sessions),ee=P.map(K=>({scopeKey:K.folderScopeKey??Xe(K.directory??null),directory:K.directory??null})).filter(K=>!!K.scopeKey),Z=P.find(K=>K.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:H};if(u){const K=P.map(E=>k.get(E)).filter(E=>!!E);k.set(ie,{filteredNodes:H,matchedSessionCount:K.reduce((E,R)=>E+R.matchedSessionCount,0),folderNameMatchCount:K.reduce((E,R)=>E+R.folderNameMatchCount,0),groupMatches:K.some(E=>E.groupMatches),hasMatch:K.some(E=>E.hasMatch)})}const $={project:C.project,groups:[ie,...D]};return A.set(C,{query:f,section:$}),$})},[k,u,f,S]),L=o.useMemo(()=>u?S.reduce((A,C)=>A+C.groups.reduce((I,P)=>{const D=k.get(P);if(!D)return I;const H=D.folderNameMatchCount+(D.groupMatches?1:0);return I+D.matchedSessionCount+H},0),0):0,[u,S,k]);return{projectSections:x,visibleProjectSections:j,groupSearchDataByGroup:k,searchableProjectSections:B,sectionsForRender:S,flatSectionsForRender:b,searchMatchCount:L}},Rh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:i,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,g=o.useMemo(()=>{const h=new Map,x=new Map,j=(k,B,S,v)=>{h.has(k)||h.set(k,new Map);const b=h.get(k);v.forEach(L=>{const A=Xe(L.session.directory??S??B);b.set(L.session.id,{directory:A}),x.has(k)||x.set(k,{id:L.session.id,directory:A}),L.children.length>0&&j(k,B,A,L.children)})};return s.forEach(k=>{k.groups.forEach(B=>{j(k.project.id,k.project.normalizedPath,B.directory,B.sessions)})}),{metaByProject:h,firstSessionByProject:x}},[s]),m=o.useRef(null);o.useLayoutEffect(()=>{if(!n)return;if(c){m.current=n;return}if(m.current===n)return;const h=s.find(L=>L.project.id===n);if(!h)return;m.current=n;const x=g.metaByProject.get(n);if(a&&x&&x.has(a)){i(L=>{if(L.get(n)===a)return L;const A=new Map(L);return A.set(n,a),A});return}const j=a?Array.from(g.metaByProject.entries()).some(([L,A])=>L!==n&&A.has(a)):!1;if(a&&x&&!j)return;if(!x||x.size===0){f("chat"),d&&p(!1),u({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath});return}const k=r.get(n),B=k&&x.has(k)?k:null,S=g.firstSessionByProject.get(n)?.id??null,v=B??S;if(!v||v===a)return;const b=x.get(v)?.directory??null;l(v,b,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,g,f,p,i]),o.useEffect(()=>{if(!n||!a)return;const h=g.metaByProject.get(n);!h||!h.has(a)||i(x=>{if(x.get(n)===a)return x;const j=new Map(x);return j.set(n,a),j})},[n,a,g,i])},Mh=({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 Rh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:i}),o.useEffect(()=>{s(a)},[a,s]),null},bi=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Fh=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},Lh=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,Ya=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=Fh(e.trim())%bi.length;return bi[s]},Oh=(e,s)=>{const n=Ya(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},yi=e=>!!e.time?.archived,Bh=e=>{const s=o.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=o.useCallback(a=>{const l=Xe(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 f=Xe(l??null),p=va(a).sort((A,C)=>Zr(A,C,e.pinnedSessionIds,e.sessionOrderRanks)),g=new Map(p.map(A=>[A.id,A])),m=new Map,h=new Map;p.forEach(A=>{const C=A.parentID??null,I=C?g.get(C):null,P=I&&yi(I)===yi(A)?C:null;m.set(A.id,P),P&&h.set(P,(h.get(P)??0)+1)});const x=c.map(A=>({worktree:A,directory:Xe(A.path)})).filter(A=>!!A.directory&&!A.worktree.isPrimary).sort((A,C)=>C.directory.length-A.directory.length),j=(A,C)=>C===A||C.startsWith(`${A}/`),k=A=>{const C=Xe(A.directory??null);return C?x.find(I=>j(I.directory,C))?.worktree??null:null},B=(A,C)=>{const I=Lh(A.id,m,h);return{session:A,children:[],worktree:C,forkColorId:I}},S=[],v=new Map,b=[];for(const A of x)v.set(A.directory,[]);p.forEach(A=>{const C=k(A),I=B(A,C);A.time?.archived?b.push(I):C?v.get(Xe(C.path)??"")?.push(I):S.push(I)});const L=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?Zo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:S}];for(const{worktree:A,directory:C}of x)L.push({id:`worktree:${C}`,label:A.branch||(A.detached?"Detached HEAD":A.name),branch:A.branch,description:Zo(C,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:A,directory:C,folderScopeKey:C,sessions:v.get(C)??[]});return b.length>0&&L.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?ya(f):null,sessions:b}),L},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:i}},_h=({mobileVariant:e,isTablet:s})=>!e&&!s,zh=({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])},$h=e=>{const[s,n]=o.useState(null),r=o.useRef(null);o.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const i=o.useCallback((S,v,b)=>{Er("navigation.session_select"),ue.getState().closeMainSurfaces();const L=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},A=b?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),S===_e.getState().currentSessionId){e.allowReselect&&A&&e.onSessionSelected?.(S),L();return}Er("navigation.session_state_set"),e.setCurrentSession(S,v??null),A&&e.onSessionSelected?.(S),L()},[e]),a=o.useCallback((S,v)=>{e.setEditingId(S),e.setEditTitle(v)},[e]),l=o.useCallback(async S=>{if(!e.editingId)return;const v=(S??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(S,v)=>{try{return(await un(S)).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 S=>{const v=await e.shareSession(S.id);if(!v?.share?.url){le.error("Unable to share session");return}const b=await d(v.share.url,S.id);le[b?"success":"warning"]("Session shared",{description:b?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=o.useCallback((S,v)=>{d(S,v).then(b=>{b||le.error("Failed to copy URL")})},[d]),p=o.useCallback(S=>{un(S).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"))},[]),g=o.useCallback(async S=>{await e.unshareSession(S)?le.success("Session unshared"):le.error("Unable to unshare session")},[e]),m=o.useCallback(S=>{const v=[],b=L=>{(e.childrenMap.get(L)??[]).forEach(C=>{v.push(C),b(C.id)})};return b(S),v},[e.childrenMap]),h=o.useCallback((S,v)=>v?S:S.filter(b=>!b.time?.archived),[]),x=o.useCallback(async(S,v,b)=>{const L=v?.archivedBucket===!0||v?.hardDelete===!0,A=b?.descendantIds??h(m(S.id),L).map(D=>D.id);if(A.length===0){(L?await e.deleteSession(S.id):await e.archiveSession(S.id))?le.success(L?"Session deleted":"Session archived"):le.error(L?"Failed to delete session":"Failed to archive session");return}const C=[S.id,...A];if(L){const{deletedIds:D,failedIds:H}=await e.deleteSessions(C);if(H.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,m,h]),j=o.useCallback((S,v)=>{const b=v?.archivedBucket===!0||v?.hardDelete===!0,L=h(m(S.id),b).map(A=>A.id);if(!e.showDeletionDialog||v?.skipConfirm===!0){x(S,v,{descendantIds:L});return}e.setDeleteSessionConfirm({session:S,descendantCount:L.length,descendantIds:L,archivedBucket:b})},[e,m,x,h]),k=o.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:S,archivedBucket:v,descendantIds:b}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await x(S,{archivedBucket:v},{descendantIds:b})},[e,x]),B=o.useCallback(async S=>{await e.unarchiveSession(S.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:f,handleCopySessionId:p,handleUnshareSession:g,handleDeleteSession:j,handleRestoreSession:B,confirmDeleteSession:k}},Uh=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 p=d.current;if(d.current=null,c.current=null,!p)return;const{projects:g}=_t.getState(),m=g.map(h=>({...h,sidebarCollapsed:p.has(h.id)}));to({projects:m}).catch(()=>{})},[]),f=o.useCallback(p=>{typeof window>"u"||(d.current=p,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 p=s.getItem(n.sessionExpanded);if(p){const m=JSON.parse(p);Array.isArray(m)&&a(new Set(m.filter(h=>typeof h=="string")))}const g=s.getItem(n.projectCollapse);if(g){const m=JSON.parse(g);Array.isArray(m)&&l(new Set(m.filter(h=>typeof h=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),o.useEffect(()=>{try{const p=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(p))}catch{}},[r,n.groupOrder,s]),o.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(i)))}catch{}},[i,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:f}},Gh=3;let Hn=0;const Va=[],Kh=()=>Hn<Gh?(Hn+=1,Promise.resolve()):new Promise(e=>{Va.push(e)}),Hh=()=>{const e=Va.shift();if(e){e();return}Hn=Math.max(0,Hn-1)},Wh=async e=>{await Kh();try{return await e()}finally{Hh()}},Yh=5*6e4,Vh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:i,setProjectRootBranches:a}=e,{git:l}=Vn(),c=na(p=>p.ensureStatus);o.useEffect(()=>{if(!n||!l||s.length===0){i(new Map);return}s.forEach(p=>{Wh(()=>c(p.normalizedPath,l))})},[n,s,l,c,i]),o.useEffect(()=>{if(!n)return;const p=new Map;s.forEach(g=>{p.set(g.id,r.get(g.normalizedPath)?.isGitRepo??null)}),i(p)},[n,s,r,i]);const d=o.useMemo(()=>s.map(p=>{const g=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${g}`}).join("|"),[s,r]),u=o.useRef(new Map),f=o.useRef(new Map);o.useEffect(()=>{if(!n)return;let p=!1;const g=setTimeout(()=>{(async()=>{const h=new Set(s.map(S=>S.id));for(const S of u.current.keys())h.has(S)||(u.current.delete(S),f.current.delete(S));const x=Date.now();if(s.filter(S=>{const v=r.get(S.normalizedPath);if(v?.isGitRepo===!1)return u.current.delete(S.id),f.current.delete(S.id),!1;if(v?.isGitRepo!==!0||v.branch===null)return!1;const b=v.branch.trim(),L=`${S.normalizedPath}\0${b}`,A=u.current.get(S.id);if(A===L){const C=f.current.get(S.id);return C&&(C.at=x),!1}return!(A!==void 0&&x-(f.current.get(S.id)?.at??0)<Yh)}).length===0)return;const k=[];if(s.forEach(S=>{const v=r.get(S.normalizedPath)?.branch?.trim()??"",b=`${S.normalizedPath}\0${v}`;v&&k.push({id:S.id,inputKey:b,branch:v})}),p||k.length===0)return;const B=Date.now();a(S=>{const v=new Map(S);return k.forEach(({id:b,branch:L})=>{L&&v.set(b,L)}),v}),k.forEach(({id:S,inputKey:v,branch:b})=>{u.current.set(S,v),b&&f.current.set(S,{branch:b,at:B})})})()},150);return()=>{p=!0,clearTimeout(g)}},[n,s,d,r,a])},Qh=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}},qh=e=>{if(e.runtimeKey!==qn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=lu(e.sessionId,e.directory,e.runtimeKey);s&&cu.getState().clearQueue(s),od.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),Gt.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),ra.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),Dr.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=id(e.runtimeKey,e.directory,e.sessionId);n&&ad(n,!0)},Jh=e=>{const s=new Map;for(const n of e){const r=Gs(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Xh=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,i)=>{s.has(i)||n.push(r)}),n},Zh=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,i=o.useRef(null);o.useEffect(()=>{if(!s||!n)return;const a=qn(),l=Jh(r),c=i.current?.runtimeKey===a?i.current.identities:null;for(const d of Xh(c,l))qh({runtimeKey:a,...d});i.current={runtimeKey:a,identities:l}},[s,n,r])},ep=(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,vi=(e,s,n)=>{ep(e.get(s),n)&&e.set(s,n)},tp=e=>{const s=e;return Xe(s.directory)??Xe(s.project?.worktree)},sp=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)},np=(e,s,n,r=[])=>{const i=new Map,a=new Map;for(const m of s){const h=Xe(m.normalizedPath);if(!h)continue;const x=a.get(h);(!x||m.id.localeCompare(x.id)<0)&&a.set(h,m),vi(i,h,{projectId:m.id,projectRoot:h,scopeDirectory:h,kind:"project"})}if(n)for(const[m,h]of n){const x=Xe(m),j=x?a.get(x):void 0;if(!(!j||!x))for(const k of h||[]){const B=Xe(k?.path);B&&vi(i,B,{projectId:j.id,projectRoot:x,scopeDirectory:B,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,f=new Map,p=m=>{if(!m)return null;if(l.has(m))return l.get(m)??null;const h=[];let x=m,j=null;for(;x;){if(l.has(x)){j=l.get(x)??null;break}if(h.push(x),j=i.get(x)??null,j)break;x=sp(x)}for(const k of h)l.set(k,j);return j},g=(m,h,x)=>{for(const j of m){const k=p(tp(j));if(!k)continue;c.set(j.id,k);const B=h.get(k.projectId);if(B?B.push(j):h.set(k.projectId,[j]),!x)continue;const S=x.get(k.scopeDirectory);S?S.add(j.id):x.set(k.scopeDirectory,new Set([j.id]))}};return g(e,d,f),g(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:l.size}},rp=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(is,{open:e,onOpenChange:s,children:t.jsx(as,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(Ns,{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(Vf,{project:n,onIdentitySave:r}):null})})})});function Qa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:O("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:O("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(Qn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const op=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:i,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:p,projectId:g,mobileVariant:m=!1,alwaysShowActions:h=m,isRenaming:x=!1,renameDraft:j="",onRenameDraftChange:k,onRenameSave:B,onRenameCancel:S,droppableRef:v,isDropTarget:b=!1,onNewSession:L,depth:A=0,hideActions:C=!1,archivedBucket:I=!1})=>{const[P,D]=o.useState(!1),[H,ee]=o.useState(""),Z=o.useRef(null),ie=x||P,$=x?j:H,K=o.useCallback(()=>{ee(e.name),D(!0)},[e.name]),E=o.useCallback(()=>{const U=$.trim();U&&U!==e.name&&c(U),x&&B&&B(),D(!1),ee("")},[$,e.name,x,c,B]),R=o.useCallback(()=>{x&&S&&S(),D(!1),ee("")},[x,S]),Y=o.useCallback(U=>{x&&k?k(U):ee(U)},[x,k]);o.useEffect(()=>{if(!x)return;const U=()=>{const Ve=Z.current;Ve&&(Ve.focus(),Ve.select())},Te=requestAnimationFrame(U),Le=window.setTimeout(U,0);return()=>{cancelAnimationFrame(Te),window.clearTimeout(Le)}},[x]);const oe=i?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:v,className:O("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",b&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:ie?void 0:U=>{U.currentTarget.blur(),l()},role:ie?void 0:"button",tabIndex:ie?void 0:0,onKeyDown:ie?void 0:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),l())},"aria-label":i?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:O("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",I?h?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":h?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(N,{name:oe,className:O(Mn,b?"text-primary":"text-muted-foreground")}),ie?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),onSubmit:U=>{U.preventDefault(),E()},children:[t.jsx("input",{ref:Z,value:$,onChange:U=>Y(U.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:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),onKeyDown:U=>{if(U.key==="Escape"){U.stopPropagation(),R();return}(U.key===" "||U.key==="Enter")&&U.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.stopPropagation(),children:t.jsx(N,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),R()},onPointerDown:U=>U.stopPropagation(),onMouseDown:U=>U.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:O(wa,b?"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(Qa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,i?t.jsx(N,{name:"arrow-right-s",className:O(Mn,"text-muted-foreground")}):t.jsx(N,{name:"arrow-down-s",className:O(Mn,"text-muted-foreground")})]})]}),!ie&&(!C||I)?t.jsx("div",{className:O("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",h?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:t.jsxs("div",{className:"flex items-center gap-0.5",children:[!I&&L?t.jsx("button",{type:"button",onClick:U=>{U.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:U=>{U.stopPropagation(),K()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:t.jsx(N,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:U=>{U.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(U=>t.jsx(o.Fragment,{children:u(U,0,p??null,g??null,I,void 0,"project",f?.(U))},U.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},ip=o.memo(op),ap=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:i,listeners:a,setNodeRef:l,isDragging:c}=Ku({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})},lp=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=Hu({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},cp=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const i=Xn(hn(ao,{activationConstraint:{distance:8}})),[a,l]=o.useState(null),[c,d]=o.useState("Session"),[u,f]=o.useState(null),[p,g]=o.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const m=h=>{l(null),f(null),g(null);const{active:x,over:j}=h;if(!j)return;const k=x.data.current,B=j.data.current;k?.type==="session"&&k.sessionId&&B?.type==="folder"&&B.folderId&&n(k.sessionId,B.folderId)};return t.jsxs(Zn,{sensors:i,collisionDetection:er,onDragStart:h=>{const x=h.active.data.current;if(x?.type==="session"&&x.sessionId){l(x.sessionId),d(x.sessionTitle??"Session");const j=h.active.rect.current.initial?.width,k=h.active.rect.current.initial?.height;f(typeof j=="number"?j:null),g(typeof k=="number"?k:null)}},onDragCancel:()=>{l(null),f(null),g(null)},onDragEnd:m,children:[r,t.jsx(Aa,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:p?`${p}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})]})},On=(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},Ds=({icon:e,children:s,onClick:n,className:r,mobileVariant:i=!1})=>t.jsxs("button",{type:"button",onClick:n,className:O(i?ku:Nu,r),children:[t.jsx(N,{name:e,className:O(an(i),"text-muted-foreground")}),t.jsx("span",{className:O(ln(i),"flex-1 text-muted-foreground"),children:s})]}),wi=(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)},fs=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(fs(n,s))return!0;return!1},dp=(e,s,n)=>{const r=new Map,i=a=>{const l=Gs(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}))},up=(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})},Si=new WeakMap;let ji=1;const fp=e=>{const s=Si.get(e);if(s!==void 0)return s;const n=ji;return ji+=1,Si.set(e,n),n},Wr=e=>e.children.length===0?"":e.children.map(n=>{const r=fp(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Wr(n)}`}).join("|"),qa=(e,s,n,r,i,a)=>{const l=qn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??i,p=u.session.directory??a,g=Wo(l,f??"",d.session.id),m=Wo(l,p??"",u.session.id);return(g?n.has(g):!1)!==(m?r.has(m):!1)?!0:d.children.some((h,x)=>c(h,u.children[x]))};return c(e,s)},Wn=(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},Ja=(e,s)=>"",hp=ps(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),pp=e=>null,mo=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Xa=(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=mo(i,Xa(l,s,n,r)),i==="active")return i;return i},Ci=(e,s,n,r)=>{let i=null;for(const a of e)if(i=mo(i,Xa(a,s,n,r)),i==="active")return i;return i},mp=50,gp=28,An=(e,s)=>s?e.sessions.some(n=>fs(n,s)):!1,xp=(e,s,n)=>e.sessions.some(r=>qa(r,r,s,n,e.directory,e.directory)),bp=(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)},ki=(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)},yp=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},vp=(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)},wp=(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&&xp(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&vp(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&bp(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(An(e.group,e.editingId)||An(s.group,s.editingId))||e.editTitle!==s.editTitle&&(An(e.group,e.editingId)||An(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Wn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Wn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&ki(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&ki(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&yp(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 Sp(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:i,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:g,renameFolder:m,deleteFolder:h,showDeletionDialog:x,setDeleteFolderConfirm:j,renderSessionNode:k,showMoreGroupSessions:B,resetGroupSessionLimit:S,mobileVariant:v,alwaysShowActions:b,activeProjectId:L,setActiveProjectIdOnly:A,setActiveMainTab:C,setSessionSwitcherOpen:I,openNewSessionDraft:P,addSessionToFolder:D,createFolderAndStartRename:H,renamingFolderId:ee,renameFolderDraft:Z,setRenameFolderDraft:ie,setRenamingFolderId:$,pinnedSessionIds:K,expandedParents:E,sessionOrderIndex:R,editingId:Y,openSidebarMenuKey:oe,activeActivitySessionIds:U,unreadActivitySessionIds:Te,notifyOnSubtasks:Le,onToggleCollapsedGroup:Ve,dragHandleProps:Ge,compactBodyPadding:Ke=!1,scrollContainerRef:Oe}=e,se=o.useCallback((G,te)=>{const re=R.get(G.session.id),ce=R.get(te.session.id);if(re!==void 0||ce!==void 0){if(re===void 0)return 1;if(ce===void 0)return-1;if(re!==ce)return re-ce}return Zr(G.session,te.session,K,oa)},[K,R]),fe=a?c.get(s):null,He=Gt(G=>G.foldersMap),ke=a?!1:u.has(n);o.useMemo(()=>{if(s.isMain||s.isArchivedBucket||i)return null;const G=Xe(s.directory??null),te=s.branch?.trim();return G&&te?Ja():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,i]);const Ce=ia(),We=o.useMemo(()=>{const G=s.folderScopes?.map(te=>Xe(te.directory))??[Xe(s.directory??null)];return[...new Set(G.filter(te=>!!te))]},[s.directory,s.folderScopes]);o.useSyncExternalStore(o.useCallback(G=>We.length>0?Ce.subscribeBootstrap(G):()=>{},[We.length,Ce]),o.useCallback(()=>We.map(G=>`${G}\0${Ce.getBootstrapState(G)??""}\0${Ce.getBootstrapFailure(G)??""}`).join(""),[We,Ce]),o.useCallback(()=>"",[]));const tt=We.some(G=>{const te=Ce.getBootstrapState(G);return te==="queued"||te==="running"}),ze=We.find(G=>Ce.getBootstrapState(G)==="failed")??null,q=ze?Ce.getBootstrapFailure(ze):void 0,V=q==="os-permission"&&no(),[ge,J]=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||!V||ge)){J(!0);try{(await ro(ze)).success&&we()}finally{J(!1)}}},[V,ze,ge,we]),Ie=f?10:5,ft=Math.max(Ie,d??Ie),mt=a?fe?.groupMatches===!0:!1,Ze=a,Pe=o.useMemo(()=>[...Ze?fe?.filteredNodes??[]:s.sessions].sort(se),[se,s.sessions,fe?.filteredNodes,Ze]),Re=s.folderScopeKey??Xe(s.directory??null),Ne=o.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:Re?[{scopeKey:Re,directory:s.directory??null}]:[],[Re,s.directory,s.folderScopes]),at=o.useMemo(()=>Ne.flatMap(({scopeKey:G,directory:te})=>(He[G]??[]).map(re=>({folder:re,scopeKey:G,scopeDirectory:te}))),[Ne,He]),Ct=o.useMemo(()=>{const G=new Map,te=re=>{re.forEach(ce=>{G.set(ce.session.id,ce),ce.children.length>0&&te(ce.children)})};return te(Pe),G},[Pe]),st=o.useMemo(()=>at.map(({folder:G,scopeKey:te,scopeDirectory:re})=>{const ce=up(G.sessionIds,Ct).sort(se);return{folder:G,scopeKey:te,scopeDirectory:re,nodes:ce}}),[at,Ct,se]),_=o.useMemo(()=>{const G=new Map(st.map(pe=>[pe.folder.id,pe])),te=new Map;for(const{folder:pe}of st){if(!pe.parentId)continue;const dt=te.get(pe.parentId);dt?dt.push(pe.id):te.set(pe.parentId,[pe.id])}const re=new Map,ce=pe=>{const dt=re.get(pe);if(dt!==void 0)return dt;const Tt=G.get(pe);if(!Tt)return re.set(pe,!1),!1;const yt=te.get(pe)??[];if(s.isArchivedBucket&&Tt.nodes.length===0){const Pt=yt.some(os=>ce(os));return re.set(pe,Pt),Pt}if(!a||Tt.folder.name.toLowerCase().includes(l)||Tt.nodes.length>0)return re.set(pe,!0),!0;const ts=yt.some(Pt=>ce(Pt));return re.set(pe,ts),ts};return st.filter(({folder:pe})=>ce(pe.id))},[st,s.isArchivedBucket,a,l]),ye=o.useMemo(()=>new Set(_.flatMap(G=>G.folder.sessionIds)),[_]),be=o.useMemo(()=>Pe.filter(G=>!ye.has(G.session.id)),[Pe,ye]),w=o.useMemo(()=>_.filter(({folder:G})=>!G.parentId),[_]),W=o.useMemo(()=>{const G=new Map;return _.forEach(te=>{if(!te.folder.parentId)return;const re=G.get(te.folder.parentId)??[];re.push(te),G.set(te.folder.parentId,re)}),G},[_]),ne=o.useMemo(()=>{const G=new Map(_.map(ce=>[ce.folder.id,ce])),te=new Map,re=(ce,pe)=>{const dt=te.get(ce);if(dt!==void 0)return dt;if(pe.has(ce))return null;pe.add(ce);const Tt=G.get(ce);let yt=Tt?Ci(Tt.nodes,U,Te,Le):null;for(const Ut of W.get(ce)??[])if(yt=mo(yt,re(Ut.folder.id,pe)),yt==="active")break;return te.set(ce,yt),yt};return _.forEach(({folder:ce})=>re(ce.id,new Set)),te},[U,_,W,Le,Te]),de="project",Se=o.useMemo(()=>{const G=new Set;return wi(Pe,Y,G),_.forEach(({nodes:te})=>{wi(te,Y,G)}),G},[Pe,_,Y]),De=o.useMemo(()=>{if(!oe)return null;const G=Wn(Pe,oe,de,!!s.isArchivedBucket);if(G)return G;for(const{nodes:te}of _){const re=Wn(te,oe,de,!!s.isArchivedBucket);if(re)return re}return null},[oe,Pe,_,s.isArchivedBucket]),$e=o.useCallback(G=>{const te=new WeakMap,re=ce=>{te.set(ce,Wr(ce));for(const pe of ce.children)re(pe)};return G.forEach(re),te},[]),ht=o.useMemo(()=>$e(Pe),[$e,Pe]),kt=o.useMemo(()=>{const G=new WeakMap;return _.forEach(({nodes:te})=>{te.forEach(re=>G.set(re,Wr(re)))}),G},[_]),et=o.useCallback(G=>ht.get(G)??kt.get(G)??"",[ht,kt]),pt=o.useCallback(G=>({subtreeContainsEditing:Se,menuOpenSessionId:De,nodeStructureKey:et(G)}),[Se,De,et]),gt=be.length,Me=s.isArchivedBucket||a?be:be.slice(0,ft),Ye=gt-Me.length,xt=!s.isArchivedBucket&&!a&&gt>Ie&&Ye===0,Lt=s.isArchivedBucket===!0&&!a&&Me.length>=mp,zt=s.isArchivedBucket?"archived":"active",At=Lt&&Me.some(G=>{if(G.children.length===0)return!1;const te=`project:${zt}:${G.session.id}`;return E.has(te)}),It=o.useRef(null),[Dt,M]=o.useState(null),[je,Be]=o.useState(0),[,ct]=o.useState(0);o.useEffect(()=>{if(!Lt)return;const G=It.current;if(!G||typeof ResizeObserver>"u")return;const te=new ResizeObserver(()=>ct(re=>re+1));return te.observe(G),()=>te.disconnect()},[Lt]),o.useLayoutEffect(()=>{if(!Lt){Dt!==null&&M(null),je!==0&&Be(0);return}const G=It.current;if(!G)return;let te=Dt;const re=Oe?.current??null;if(re&&re.contains(G)){if(te=re,te!==Dt){M(te);return}}else if(!te||!te.contains(G)){let pe=G.parentElement;for(;pe;){const dt=window.getComputedStyle(pe);if(dt.overflowY==="auto"||dt.overflowY==="scroll"){te=pe;break}pe=pe.parentElement}if(te!==Dt){M(te);return}}if(!te)return;const ce=G.getBoundingClientRect().top-te.getBoundingClientRect().top+te.scrollTop;Be(pe=>Math.abs(pe-ce)<1?pe:ce)});const F=Lt&&Dt!==null,ae=Gu({count:Me.length,enabled:F,getScrollElement:()=>Dt,initialOffset:()=>Dt?.scrollTop??0,estimateSize:()=>gp,overscan:At?20:8,scrollMargin:je,getItemKey:G=>Me[G]?.session.id??G}),he=o.useCallback(G=>{const te=[],re=ce=>{ce.forEach(pe=>{te.push(pe.session),pe.children.length>0&&re(pe.children)})};return re(G),te},[]),nt=o.useMemo(()=>he(Pe),[he,Pe]),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 pe=te.get(ce.parentId)??[];pe.push(ce.id),te.set(ce.parentId,pe)}const re=(ce,pe)=>{if(pe.has(ce))return[];pe.add(ce);const dt=_.find(({folder:Ut})=>Ut.id===ce),Tt=dt?he(dt.nodes):[],yt=te.get(ce)??[];for(const Ut of yt)Tt.push(...re(Ut,pe));return Tt};for(const{folder:ce}of _)G.set(ce.id,re(ce.id,new Set));return G},[_,he,s.isArchivedBucket]);if(a&&!mt&&w.length===0&&be.length===0)return null;const Je=!s.isMain&&!!s.branch,bt=s.branch&&Au(s.branch,s.label)?{label:s.branch}:null,Nt=ke?Ci(Pe,U,Te,Le):null,Mt=Nt?t.jsx(Qa,{state:Nt,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Et=(G,te)=>{const{folder:re,scopeKey:ce,scopeDirectory:pe,nodes:dt}=G,Tt=ve.get(re.id)??[],yt=a?!1:p.has(re.id);return t.jsx(lp,{folderId:re.id,children:(Ut,ts)=>t.jsx(ip,{folder:re,displayName:te,sessions:dt,isCollapsed:yt,collapsedActivityState:yt?ne.get(re.id)??null:null,onToggle:()=>g(re.id),onRename:Pt=>{m(ce,re.id,Pt)},onDelete:()=>{if(s.isArchivedBucket){Ps.requestDelete({sessions:Tt,mode:"session"});return}if(!x){h(ce,re.id);return}const Pt=_.filter(({folder:ls})=>ls.parentId===re.id).length,os=dt.length;j({scopeKey:ce,folderId:re.id,folderName:re.name,subFolderCount:Pt,sessionCount:os})},renderSessionNode:k,getRenderExtras:et?Pt=>({subtreeContainsEditing:Se,menuOpenSessionId:De,nodeStructureKey:et(Pt),childRenderExtrasFor:pt}):void 0,groupDirectory:pe??s.directory,projectId:r,mobileVariant:v,alwaysShowActions:b,isRenaming:ee===re.id,renameDraft:ee===re.id?Z:void 0,onRenameDraftChange:Pt=>ie(Pt),onRenameSave:()=>{const Pt=Z.trim();Pt&&m(ce,re.id,Pt),$(null),ie("")},onRenameCancel:()=>{$(null),ie("")},droppableRef:Ut,isDropTarget:ts,depth:0,onNewSession:()=>{r&&r!==L&&A(r),C("chat"),v&&I(!1),P({selectedProjectId:r,directoryOverride:pe??s.directory,targetFolderId:re.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},re.id)},$t=()=>{const G=new Map;for(const ce of _){const pe=ce.folder.parentId;if(!pe)continue;const dt=G.get(pe);dt?dt.push(ce):G.set(pe,[ce])}const te=[],re=(ce,pe)=>{const dt=pe?`${pe} / ${ce.folder.name}`:ce.folder.name;te.push(Et(ce,dt)),!(!a&&p.has(ce.folder.id))&&(G.get(ce.folder.id)??[]).forEach(yt=>re(yt,dt))};return w.forEach(ce=>re(ce,"")),te},Ft=b?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",wt=ze?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[q==="os-permission"?"Folder access is required.":"Could not refresh sessions.",V?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,qt=t.jsxs(cp,{scopeKey:Ne[0]?.scopeKey??Re,hasFolders:_.length>0,onSessionDroppedOnFolder:(G,te)=>{const re=_.find(({folder:pe})=>pe.id===te);if(!re)return;const ce=Gt.getState();for(const{scopeKey:pe}of Ne)pe!==re.scopeKey&&ce.getSessionFolderId(pe,G)&&ce.removeSessionFromFolder(pe,G);D(re.scopeKey,te,G)},children:[$t(),Lt?t.jsx("div",{ref:It,children:F?t.jsx("div",{style:{height:ae.getTotalSize(),position:"relative"},children:ae.getVirtualItems().map(G=>{const te=Me[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:De,nodeStructureKey:et(te),childRenderExtrasFor:pt})},te.session.id):null})}):Me.map(G=>t.jsx(o.Fragment,{children:k(G,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:De,nodeStructureKey:et(G),childRenderExtrasFor:pt})},G.session.id))}):Me.map(G=>t.jsx(o.Fragment,{children:k(G,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:De,nodeStructureKey:et(G),childRenderExtrasFor:pt})},G.session.id)),gt===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…"]})}):wt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:wt}):t.jsx(Ds,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,gt>0&&wt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:wt}):null,Ye>0?t.jsx(Ds,{icon:"arrow-down-s",onClick:()=>B(n,Me.length),children:Ye===1?"Show 1 more session":`Show ${Ye} more sessions`}):null,xt?t.jsx(Ds,{icon:"arrow-up-s",onClick:()=>S(n),children:"Show fewer sessions"}):null]});return i?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:qt})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:O("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>Ve(n),role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),Ve(n))},"aria-label":ke?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!ke,children:[t.jsx("div",{ref:Ge?.setActivatorNodeRef,className:O("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",Ft),...Ge?.listeners??{},children:t.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[t.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:s.isArchivedBucket?t.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[t.jsx(N,{name:"archive",className:O("size-4 shrink-0 text-muted-foreground",b?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:O("text-muted-foreground size-4 items-center justify-center",b?"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:On(s.label,l)}),Mt]}):!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:O("size-4 shrink-0","text-muted-foreground",b?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:O("text-muted-foreground size-4 items-center justify-center",b?"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:On(s.label,l)}),Mt,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:On(s.label,l)}),Mt]})}),Je&&bt?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:bt.label})]}):null]})}),s.isArchivedBucket&&nt.length>0?t.jsx("div",{className:O("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",b?"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(),Ps.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:O("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",b?"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:qt})]})}const jp=o.memo(Sp,wp);function Cp(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:i,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:g,sessionSearchQuery:m,setSessionSearchQuery:h,hasSessionSearchQuery:x,searchMatchCount:j,selectionModeEnabled:k,onToggleSelectionMode:B,mobileVariant:S=!1}=e;if(s)return null;const v=O(u,"text-muted-foreground hover:text-foreground",!S&&"hover:bg-transparent");return t.jsx("div",{className:O("select-none flex-shrink-0",S?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:O("flex flex-col",S?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:O("flex items-center justify-between",S?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:O("flex min-w-0 items-center",S?"gap-0.5 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":S?"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,!S&&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,S?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"})})]}),S?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:O("flex shrink-0 items-center",S?"gap-0.5":"gap-1.5"),children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>p(b=>!b),className:v,"aria-label":"Search sessions","aria-expanded":f,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:B,className:O(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"})})]})]})]}),f?t.jsxs("div",{className:O(S?"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:x?t.jsx("span",{children:j===1?`${j} match`:`${j} 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:g,value:m,onChange:b=>h(b.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:b=>{b.key==="Escape"&&(b.stopPropagation(),x?h(""):p(!1))}}),m.length>0?t.jsx("button",{type:"button",onClick:()=>h(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:t.jsx(N,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function kp(e){const s=ue(i=>i.toggleSidebar),n=ue(i=>i.shortcutOverrides),r=oo(rn("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, ${si})`}}),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, ${si})))`}}),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:O("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:O(Mn,"text-current")}),t.jsx("span",{className:wa,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 Np=500,Bn=(e,s)=>O("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"),Ap=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:i,worktreeError:a,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:g,setNodeRef:m,transform:h,transition:x,isDragging:j}=co({id:e.id,disabled:!c}),[k,B]=o.useState(!1),S=o.useRef(null),v=o.useCallback(()=>{S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]);o.useEffect(()=>()=>v(),[v]);const b=o.useCallback(()=>{v(),S.current=window.setTimeout(()=>{S.current=null,B(!0)},Np)},[v]);return t.jsx("div",{ref:m,style:{transform:uo.Translate.toString(h),transition:x},className:O(j&&"opacity-60"),children:t.jsxs(Qf,{open:k,onOpenChange:B,children:[t.jsxs(qf,{render:t.jsx("button",{type:"button",onClick:()=>{k||d()},onTouchStart:b,onTouchMove:v,onTouchEnd:v,onTouchCancel:v,style:{touchAction:"manipulation"},className:Bn(p,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:O("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?g:{},children:t.jsx(N,{name:"folder",className:O(an(p),"text-muted-foreground")})}),t.jsx("span",{className:ln(p),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(Qn,{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(Jf,{className:"min-w-[160px]",children:[t.jsxs(ui,{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(Xf,{}),t.jsxs(ui,{onClick:()=>f(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"})]})]})]})})},Ip=({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:f,homeDirectory:p,className:g,mobileVariant:m=!1})=>{const h=s===null,x=_t(S=>S.reorderProjects),j=e.length>1,k=Xn(hn(Yu,{activationConstraint:{distance:8}}),hn(Wu,{activationConstraint:{delay:200,tolerance:6}})),B=o.useCallback(S=>{const{active:v,over:b}=S;if(!b||v.id===b.id)return;const L=_t.getState().projects,A=L.findIndex(I=>I.id===v.id),C=L.findIndex(I=>I.id===b.id);A<0||C<0||x(A,C)},[x]);return t.jsxs("div",{className:O("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",g),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:Bn(m,h),"aria-pressed":h,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(N,{name:"folder",className:an(m)}),t.jsx("span",{className:ln(m),children:"All Folders"})]})}),t.jsx(Zn,{sensors:k,collisionDetection:er,onDragEnd:B,children:t.jsx(lo,{items:e.map(S=>S.id),strategy:Ia,children:e.map(S=>{const v=s===S.id,b=v&&!n,L=r.get(S.normalizedPath)??[],A=Jn(S.label?.trim()||Ts(S.normalizedPath,p)||S.normalizedPath);return t.jsxs(o.Fragment,{children:[t.jsx(Ap,{project:S,label:A,isSelected:b,hasActive:f?.(S.id),hasWorktrees:L.length>0,worktreeError:i.get(S.normalizedPath),isExpanded:v,canDrag:j,onSelect:()=>a(S.id),onOpenProjectEditDialog:d,onRemoveProject:u,mobileVariant:m}),v?L.map(C=>{const I=n===C.path;return t.jsxs("button",{type:"button",onClick:()=>l?.(S.id,C.path),className:O(Bn(m,I)),"aria-pressed":I,title:C.path,children:[t.jsx(N,{name:"git-branch",className:O(an(m),"text-muted-foreground")}),t.jsx("span",{className:ln(m),children:C.branch||(C.detached?"Detached HEAD":C.name)})]},C.path)}):null]},S.id)})})}),t.jsxs("button",{type:"button",onClick:c,className:Bn(m,!1),children:[t.jsx(N,{name:"add",className:an(m)}),t.jsx("span",{className:ln(m),children:"Add folder"})]})]})},ur="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 Dp({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:ur,"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:ur,"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:ur,"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 Pp=(e,s)=>Jn(e.label?.trim()||Ts(e.normalizedPath,s)||e.normalizedPath);function Ep(e){rs("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=(f,p)=>{const g=s.current,m=g.get(f);if(m&&m.groups===p)return m.ordered;const h=e.getOrderedGroups(f,p);if(g.set(f,{groups:p,ordered:h}),g.size>256){const x=g.keys().next().value;x!==void 0&&g.delete(x)}return h},i=o.useRef(null),a=o.useMemo(()=>{if(!e.isAllFoldersView)return[];const f=[];for(const p of e.sectionsForRender){const g=Pp(p.project,e.homeDirectory);for(const m of p.groups)if(!m.isArchivedBucket)for(const h of m.sessions){const x=!!e.pinnedSessionIds?.has(h.session.id),j=h.session.time?.updated||h.session.time?.created||0;f.push({node:h,project:p.project,projectLabel:g,isPinned:x,timestamp:j})}}return f.sort((p,g)=>p.isPinned!==g.isPinned?p.isPinned?-1:1:g.timestamp-p.timestamp),f},[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;return e.sharedSessionsOnly?t.jsx(Ns,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})}):e.projectSections.length===0?t.jsx(Ns,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0?t.jsx(Ns,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("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(Ns,{ref:i,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:O("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 f=e.sectionsForRender.find(h=>h.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!f)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const p=f.groups.find(h=>h.isMain&&h.sessions.length>0)??f.groups.find(h=>h.sessions.length>0)??f.groups.find(h=>h.isMain)??f.groups[0];if(!p)return t.jsx(Ds,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:f.project.id,directoryOverride:f.project.normalizedPath}),children:"New session"});const g=f.groups.find(h=>h.isArchivedBucket);return[p,...g&&g.id!==p.id?[g]:[]].map(h=>{const x=`${f.project.id}:${h.id}`,j=h.id===p.id;return t.jsx(o.Fragment,{children:e.renderGroupSessions(h,x,f.project.id,j,null,!0,i)},x)})})()}):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:f,project:p,projectLabel:g})=>{const m=f.session.directory??p.normalizedPath;return t.jsx(o.Fragment,{children:e.renderSessionNode(f,0,m,p.id,!1,{projectLabel:g,showFolderLabel:!0},"project")},f.session.id)}),u>0?t.jsx(Ds,{icon:"arrow-down-s",onClick:()=>c(f=>f+30),children:u===1?"Show 1 more session":`Show ${u} more sessions`}):null,l>30&&a.length>30?t.jsx(Ds,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(f=>{const p=f.project.id,g=r(p,f.groups),m=g.find(x=>x.isMain)??null,h=m?g.filter(x=>x.id!==m.id):g;return t.jsxs("div",{children:[m?e.renderGroupSessions(m,`${p}:${m.id}`,p,!0,null,void 0,i):null,h.map(x=>{const j=`${p}:${x.id}`,k=g.length===1;return t.jsx(o.Fragment,{children:e.renderGroupSessions(x,j,p,k,null,void 0,i)},x.id)})]},p)})})]})})})}const Tp=o.memo(Ep);function Rp(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 Mp(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 Fp(e){const s=e.info.role==="user"?"User":"Assistant",n=Rp(e.info.time?.created),r=Mp(e),i=n&&r?`${n} (${r})`:n||r;return i?`**${s}**
13
-
14
- *${i}*`:`**${s}**`}function Lp(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Za(e){const s=Fp(e),n=Lp(e.parts).trim();return n?`${s}
15
-
16
- ${n}`:""}function el(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(Za).filter(Boolean).join(`
21
-
22
- ---
23
-
24
- `),l=[i+a];for(const c of e.children)l.push(el(c,s+1));return l.join(`
25
-
26
- ---
27
-
28
- `)}function tl(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(Za).filter(Boolean).join(`
35
-
36
- ---
37
-
38
- `);let c=a+l;if(n&&n.length>0){const d=n.map(u=>el(u,1)).join(`
39
-
40
- ---
41
-
42
- `);c+=`
43
-
44
- ---
45
-
46
- `+d}return c}function sl(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 nl(e,s){const n=await du(s,e);return n||null}async function Op(e){const s=so()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await uu(e)?!0:ma(e)}function Bp(){return fu()}function rl(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 _p=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},zp=ps()(io(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:_p})),$p=(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},Kt=ps()((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 f=i&&i.length>0?[n,...i]:[n];if(l.has(n)){for(const g of f)l.delete(g);d===n&&(d=null)}else{for(const g of f)l.add(g);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),f=i.indexOf(r);if(u<0||f<0)return;const[p,g]=u<=f?[u,f]:[f,u],m=i.slice(p,g+1),h=$p(m,l),j=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const k of h)j.add(k);e({selectedIds:j,scopeKey:a??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const 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 Yr=!1;const Vr=new Set;let Ni=!1;function Up(){for(const e of Vr)e()}function go(e){Yr!==e&&(Yr=e,Up())}function Gp(e){e.key==="Shift"&&go(!0)}function Kp(e){e.key==="Shift"&&go(!1)}function Hp(){go(!1)}function Wp(){Ni||typeof window>"u"||(Ni=!0,window.addEventListener("keydown",Gp),window.addEventListener("keyup",Kp),window.addEventListener("blur",Hp))}function Yp(e){return Wp(),Vr.add(e),()=>{Vr.delete(e)}}function Vp(){return Yr}function Qp(){return!1}function qp(){return Qe.useSyncExternalStore(Yp,Vp,Qp)}const fr=new WeakMap,Jp=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;fr.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,fr.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,rs("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}),fr.set(n,c),l=window.requestAnimationFrame(d)},Xp=o.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:i,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=qp(),f=u?n:s,p=g=>{if(u||g.shiftKey){d(g);return}c(g)};return t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",className:O("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:a,onMouseDown:l,onClick:p,onKeyDown:g=>g.stopPropagation(),children:t.jsx(N,{name:u?"delete-bin":"archive",className:i})})}),t.jsx(it,{side:"left",sideOffset:8,children:f})]})});function Zp(e){rs("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:f,editingId:p,setEditingId:g,editTitle:m,setEditTitle:h,handleSaveEdit:x,handleCancelEdit:j,toggleParent:k,handleSessionSelect:B,handleSessionDoubleClick:S,togglePinnedSession:v,handleShareSession:b,copiedSessionId:L,handleCopyShareUrl:A,handleCopySessionId:C,handleUnshareSession:I,openSidebarMenuKey:P,setOpenSidebarMenuKey:D,renamingFolderId:H,getFoldersForScope:ee,getSessionFolderId:Z,removeSessionFromFolder:ie,addSessionToFolder:$,createFolderAndStartRename:K,handleDeleteSession:E,handleRestoreSession:R,mobileVariant:Y,alwaysShowActions:oe,allowQuickArchiveAction:U,renderSessionNode:Te,secondaryMeta:Le,renderContext:Ve="project",subtreeContainsEditing:Ge,menuOpenSessionId:Ke,childRenderExtrasFor:Oe}=e,se=o.useMemo(()=>ga(),[]),fe=!a&&U,He=o.useRef(!1),ke=o.useRef(p);ke.current=p;const Ce=o.useRef(null),We=o.useRef(x);We.current=x;const[tt,ze]=o.useState(m),q=o.useRef(tt);q.current=tt;const V=o.useRef(null),ge=o.useRef(null),J=s.session,we=J,xe=Xe(J.directory??null)??Xe(r??null),Ie=_e(z=>z.currentSessionId===J.id),ft=aa(xe),mt=ld(xe),Ze=_t(o.useCallback(z=>{if(Le?.projectLabel||!i)return null;const Ue=z.projects.find(lt=>lt.id===i);return Ue?Ue.label?.trim()||Ts(Xe(Ue.path)??Ue.path,null)||Ue.path:null},[i,Le?.projectLabel])),Pe=Le?.projectLabel??(Ze?Jn(Ze):null),Re=Le?.branchLabel??s.worktree?.branch??(ft&&ft!=="HEAD"?ft:null),Ne=Re,at=mt===!0||!!(Re||s.worktree),Ct=s.children.length,st=we.agent;o.useMemo(()=>{const z=s.worktree?.branch?.trim()||Re?.trim(),Ue=Xe(s.worktree?.path??xe);return z&&Ue?Ja():null},[s.worktree,Re,xe]);const _=pp();o.useMemo(()=>null,[_]);const ye=i??xe??null,be=ca(),w=eo(),W=Kt(z=>z.enabled),ne=Kt(o.useCallback(z=>z.selectedIds.has(J.id),[J.id])),de=Kt(z=>z.toggleSelected),Se=Kt(z=>z.setRange),De=o.useCallback(z=>{const Ue=[],lt=vt=>{vt.children.forEach(St=>{Ue.push(St.session.id),lt(St)})};return lt(z),Ue},[]);o.useCallback(z=>{const Ue=[],lt=vt=>{vt.children.forEach(St=>{Ue.push(St.session),lt(St)})};return lt(z),Ue},[]);const[$e,ht]=o.useState(!1),[kt,et]=o.useState(!0),pt=`${Ve}:${a?"archived":"active"}:${J.id}`,gt=cd(o.useCallback(z=>!!z.sessionMemoryState.get(dd(J.id))?.isZombie,[J.id])),Ye=la(J.id)?.type??"idle",xt=Ye==="busy"||Ye==="retry",Lt=ud(J.id,xt),zt=fd(J.id),At=we.title||"Untitled Session",It=s.children.length>0,Dt=hd(l,xe,J.id),M=pt,je=d?!0:c.has(M);o.useMemo(()=>dp(s,je,xe),[je,s,xe]);const Be=gd(),ct=!!we.parentID,ae=pd(J.id)>0&&(!ct||f),he=we.time?.updated||we.time?.created||Date.now(),nt=Pu(he),[ve,Je]=o.useState(!1),bt=o.useMemo(()=>Ya(s.forkColorId),[s.forkColorId]),Nt=o.useMemo(()=>Oh(s.forkColorId,{active:Ie||ne}),[s.forkColorId,Ie,ne]),Mt=o.useMemo(()=>De(s).length,[De,s]),Et=o.useCallback(async z=>{const Ue=[];let lt=0;for(const vt of z)try{if(!xe)throw new Error("Session directory is required for export");await w.loadCompleteHistory?.(vt.session.id,xe);const St=Pr(be.getState(),vt.session.id).list,ss=vt.session.title||"Untitled Sub-agent",ws=vt.session.agent,cs=await Et(vt.children);lt+=cs.skipped,Ue.push({title:ss,agent:ws,records:St,children:cs.children})}catch{lt+=De(vt).length+1}return{children:Ue,skipped:lt}},[De,be,xe,w]),$t=o.useCallback(z=>{z<=0||le.warning(z===1?`Exported session, but skipped ${z} sub-agent task that could not be loaded.`:`Exported session, but skipped ${z} sub-agent tasks that could not be loaded.`)},[]),Ft=o.useCallback(async z=>{if(!xe){le.error("Nothing to export");return}try{await w.loadCompleteHistory?.(J.id,xe)}catch{le.error("Failed to load the complete session history");return}const Ue=Pr(be.getState(),J.id).list;if(Ue.length===0){le.error("Nothing to export");return}let lt,vt=0;if(z&&s.children.length>0){const cs=await Et(s.children);lt=cs.children,vt=cs.skipped}const St=tl(Ue,we.title??null,lt),ss=rl(we.title??null),ws=await nl(St,ss);if(ws){le.success("Session exported",{action:{label:Bp(),onClick:()=>{Op(ws).then(cs=>{cs||le.error("Failed to reveal path")})}}}),$t(vt);return}sl(St,ss),le.success("Session exported"),$t(vt)},[Et,be,s.children,we.title,J.id,xe,$t,w]),wt=o.useCallback(async()=>{if(s.children.length>0){et(!0),ht(!0);return}await Ft(!1)},[Ft,s.children.length]),qt=o.useCallback(()=>{xe&&on("desktop_open_session_mini_chat_window",{sessionId:J.id,directory:xe,apiBaseUrl:Rr(),clientToken:Tr()}).catch(z=>{console.warn("[session-sidebar] failed to open mini chat window",z)})},[J.id,xe]);o.useEffect(()=>{if(p!==J.id)return;const z=Ue=>{const vt=Ue.target?.closest?.(`[data-session-rename-form="${CSS.escape(J.id)}"]`);ge.current&&!vt&&We.current(q.current)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[p,J.id]),o.useLayoutEffect(()=>{if(p!==J.id){V.current===J.id&&(V.current=null);return}V.current!==J.id&&(V.current=J.id,ze(m))},[p,m,J.id]);const G=zt.length,te=!xt&&ae&&!Ie,re=xt&&Lt,ce=Dt,pe=t.jsx(N,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),dt=ce?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:pe}):null,Tt=It?t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),k(M)},onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),z.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,yt=gt?t.jsx(N,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Ut=z=>{if(!z&&Ce.current){const{id:Ue,title:lt}=Ce.current;Ce.current=null,g(Ue),h(lt)}},ts=z=>{Je(z)},Pt=z=>{z.preventDefault(),z.stopPropagation()},os=z=>{z.preventDefault(),z.stopPropagation()},ls=z=>{z.preventDefault(),z.stopPropagation(),D(null),E(J,{archivedBucket:a})},ms=z=>{z.preventDefault(),z.stopPropagation(),D(null),E(J,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Ls=z=>{if(He.current){He.current=!1;return}if(W){if(z?.preventDefault(),z?.stopPropagation(),z?.shiftKey){const lt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(ss=>ss.getAttribute("data-session-row")).filter(ss=>typeof ss=="string"&&ss.length>0),vt=Kt.getState().anchorId,St=new Map;St.set(J.id,De(s)),Se(vt,J.id,lt,ye,St);return}de(J.id,ye,De(s));return}z?.currentTarget&&Jp(z.currentTarget),B(J.id,xe)},Qs=z=>{z.defaultPrevented||z.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Ls(z)},T=z=>{(z.button===2||z.button===0&&z.ctrlKey&&!W)&&(He.current=!0)},me=({Item:z,Separator:Ue,Sub:lt,SubTrigger:vt,SubContent:St})=>t.jsxs(t.Fragment,{children:[t.jsxs(z,{onClick:()=>{Ce.current={id:J.id,title:At}},className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(z,{onClick:()=>C(J.id),className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(z,{onClick:()=>xe&&v({directory:xe,sessionId:J.id}),className:"[&>svg]:mr-1",children:[Dt?t.jsx(N,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(N,{name:"pushpin",className:"mr-1 h-4 w-4"}),Dt?"Unpin session":"Pin session"]}),t.jsxs(z,{onClick:()=>{wt()},className:"[&>svg]:mr-1",children:[t.jsx(N,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),se?t.jsxs(z,{disabled:!xe,onClick:qt,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(Ue,{}),a?null:t.jsxs(z,{className:"[&>svg]:mr-1",onClick:()=>E(J,{archivedBucket:a}),children:[t.jsx(N,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs(z,{className:"[&>svg]:mr-1",onClick:()=>R(J),children:[t.jsx(N,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(z,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>E(J,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(N,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]}),Ae=t.jsx(Or,{children:t.jsx(Br,{className:"app-region-no-drag z-50",children:t.jsx(_r,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(H||ke.current),style:{color:"var(--surface-elevated-foreground)"},className:O(Ar,"min-w-[180px]"),children:me({Item:({className:z,...Ue})=>t.jsx(Ca,{className:O(Xi,z),...Ue}),Separator:({className:z,...Ue})=>t.jsx(ka,{className:O(Zi,z),...Ue}),Sub:zu,SubTrigger:({className:z,children:Ue,...lt})=>t.jsxs($u,{className:O(md,z),...lt,children:[Ue,t.jsx(N,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:z,children:Ue,...lt})=>t.jsx(Or,{children:t.jsx(Br,{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:O(Ar,z),...lt,children:Ue})})})})})})});return t.jsxs(o.Fragment,{children:[t.jsx(ap,{sessionId:J.id,sessionDirectory:xe??null,sessionTitle:At,children:t.jsxs(Sa,{open:ve,onOpenChange:ts,onOpenChangeComplete:Ut,children:[t.jsxs(ja,{render:t.jsx("div",{"data-session-row":J.id,"data-session-scope":ye??"","data-session-archived":a?"1":"0","data-fork-color":bt?s.forkColorId:void 0,onClick:Qs,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...Nt?{backgroundColor:Nt}:void 0},className:O("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!Nt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":Nt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!Nt&&Ie&&!ne&&"bg-interactive-selection",!Nt&&ne&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[Tt,dt,p===J.id?t.jsxs("form",{ref:ge,"data-session-rename-form":J.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),onSubmit:z=>{z.preventDefault(),x(tt)},children:[t.jsx("input",{value:tt,onChange:z=>ze(z.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:z=>{z.stopPropagation(),z.key==="Escape"&&j()}}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(N,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:j,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(N,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:T,onClick:z=>Ls(z),onDoubleClick:z=>{z.stopPropagation(),S(J.id,At)},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:O("block min-w-0 flex-1 truncate font-normal typography-ui-label",ae?"text-foreground":"text-foreground/90"),children:On(At,u)})}),Le?.showFolderLabel&&Pe||Ne||at||_||Ct>0||st&&st!=="default"||re||G>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:[Le?.showFolderLabel&&Pe?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Pe}):null,Ne?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:O("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Ne})]}):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,Ct>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:Ct})]}):null,st&&st!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:st}):null,re?t.jsx(Iu,{sessionId:J.id,running:xt,className:"text-muted-foreground/70"}):null,G>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:G})]}):null,null]}):null]})]}),Dt?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:O("flex items-center justify-end",fe&&(oe||ve)?"opacity-0":fe?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:xt?t.jsx(Qn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):te?t.jsx(Du,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:nt})}),fe?t.jsx("div",{className:O("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(Xp,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Pt,onMouseDown:os,onArchive:ls,onDelete:ms})}):null]}),yt&&!Y?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:yt}):null]}),Ae]})}),It&&je?s.children.map(z=>{const Ue=Oe?Oe(z):{subtreeContainsEditing:Ge,menuOpenSessionId:Ke,nodeStructureKey:""};return t.jsx(o.Fragment,{children:Te(z,n+1,xe??r,i,a,void 0,Ve,Ue)},z.session.id)}):null,t.jsx(is,{open:$e,onOpenChange:ht,children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(hs,{children:"Export Markdown"}),t.jsx(Ms,{children:Mt===1?`This session has ${Mt} sub-agent task. Include it in the export?`:`This session has ${Mt} 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:kt,onChange:z=>et(z.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Fs,{children:[t.jsx(qe,{type:"button",onClick:()=>ht(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(qe,{type:"button",onClick:()=>{ht(!1),Ft(kt)},size:"sm",children:"Export"})]})]})})]},J.id)}const Ai=e=>Xe(e.session.directory??null),em=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),tm=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},In=e=>e.menuOpenSessionId??tm(e),Dn=(e,s,n)=>s?n.has(e.node.session.id)?!0:fs(e.node,s):!1,Qr=(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(Qr(e.children[l],s.children[l],n,r,i))return!0;return!1},sm=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Qr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${e.renderContext??"project"}:${n}:${i.session.id}`)||Qr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${s.renderContext??"project"}:${r}:${i.session.id}`)},nm=(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||Ai(e.node)!==Ai(s.node)||!em(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&qa(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&sm(e,s)||e.editingId!==s.editingId&&(Dn(e,e.editingId,e.subtreeContainsEditing)||Dn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(Dn(e,e.editingId,e.subtreeContainsEditing)||Dn(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(fs(e.node,e.copiedSessionId)||fs(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=In(e),r=In(s);if(fs(e.node,n)||fs(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=In(e),r=In(s);if(fs(e.node,n)||fs(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},rm=o.memo(Zp,nm),Ii={selected:0,"active-project":1,expanded:2,visible:3,background:4};function om(e){const s=new Map,n=(r,i,a)=>{const l=Xe(r??null);if(!l)return;const c=s.get(l);c&&Ii[c.priority]<=Ii[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 im(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=e,l="Untitled Session";return t.jsx(is,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(hs,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(Ms,{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(Fs,{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 am(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(is,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(hs,{children:d}),t.jsx(Ms,{children:u})]}),t.jsxs(Fs,{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 lm(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(is,{open:!!s,onOpenChange:i=>{i||n(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(hs,{children:"Delete folder?"}),t.jsx(Ms,{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(Fs,{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 cm=({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:O("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"})})]})]})]})},dm=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:i,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:p}=e,g=Kt(K=>K.enabled),m=Kt(K=>K.selectedIds.size),h=m>0,x=Kt(K=>K.selectedIds),j=Kt(K=>K.scopeKey),k=o.useCallback(()=>{Kt.getState().toggleMode()},[]),B=o.useCallback(()=>{Kt.getState().disable()},[]),S=o.useMemo(()=>{if(!h||typeof document>"u")return!1;let K=!1,E=!1;for(const R of x){const Y=document.querySelectorAll(`[data-session-row="${CSS.escape(R)}"]`);for(const oe of Y)oe.getAttribute("data-session-archived")==="1"?E=!0:K=!0}return E&&!K},[h,x]),v=o.useMemo(()=>{if(j)return j;if(!h||typeof document>"u")return null;for(const K of x){const R=document.querySelector(`[data-session-row="${CSS.escape(K)}"]`)?.getAttribute("data-session-scope");if(R&&R.length>0)return R}return null},[h,x,j]),b=o.useMemo(()=>{if(!v)return[];const K=i.get(v);return K&&K.length>0?K.map(E=>E.scopeKey):[v]},[v,i]),L=o.useMemo(()=>b.flatMap(K=>r[K]??[]),[r,b]),A=o.useCallback(K=>{for(const E of b)if((r[E]??[]).some(R=>R.id===K))return E;return null},[r,b]),C=o.useMemo(()=>{if(!h)return!1;for(const K of b)for(const E of r[K]??[])for(const R of E.sessionIds)if(x.has(R))return!0;return!1},[r,b,h,x]),I=o.useCallback((K,E)=>{const R=Array.from(x);for(const Y of b)Y!==K&&l(Y,R);a(K,E,R)},[a,l,x,b]),P=o.useCallback(K=>{if(!h)return;const E=A(K);E&&I(E,K)},[h,I,A]),D=o.useCallback(()=>{const K=b[0];if(!K||!h)return;const E=c(K);E&&I(K,E.id)},[c,h,I,b]),H=o.useCallback(()=>{if(!h)return;const K=Array.from(x);for(const E of b)l(E,K)},[l,x,b,h]),ee=o.useCallback(async()=>{const K=Array.from(x);if(K.length!==0){if(S){const{deletedIds:E,failedIds:R}=await f(K);E.length>0&&le.success(E.length===1?`Deleted ${E.length} session`:`Deleted ${E.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:E,failedIds:R}=await d(K);E.length>0&&le.success(E.length===1?`Archived ${E.length} session`:`Archived ${E.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to archive ${R.length} session`:`Failed to archive ${R.length} sessions`)}Kt.getState().clear()}},[d,S,f,x]),Z=o.useCallback(()=>{if(!h)return;const K=x.size;if(!n){ee();return}p({sessionCount:K,archivedBucket:S})},[S,ee,x,n,p,h]),ie=o.useCallback(async()=>{if(!h||!S)return;const K=Array.from(x),{restoredIds:E,failedIds:R}=await u(K);E.length>0&&le.success(E.length===1?`Restored ${E.length} session`:`Restored ${E.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to restore ${R.length} session`:`Failed to restore ${R.length} sessions`),Kt.getState().clear()},[S,h,x,u]),$=o.useCallback(async()=>{p(null),await ee()},[ee]);return o.useEffect(()=>{if(!g)return;const K=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=R=>{if(s)return;const Y=R.target;if(Y&&(Y.tagName==="INPUT"||Y.tagName==="TEXTAREA"||Y.isContentEditable))return;const oe=K?R.metaKey:R.ctrlKey;if(R.key==="Escape"){R.preventDefault(),Kt.getState().disable();return}if(oe&&R.key==="Backspace"){R.preventDefault(),Z();return}if(oe&&(R.key==="a"||R.key==="A")){const U=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(U.length===0)return;R.preventDefault();const Le=Kt.getState().scopeKey??U[0]?.getAttribute("data-session-scope")??null,Ve=Ke=>Le?Ke.getAttribute("data-session-scope")===Le:!0,Ge=U.filter(Ve).map(Ke=>Ke.getAttribute("data-session-row")).filter(Ke=>typeof Ke=="string"&&Ke.length>0);if(Ge.length===0)return;Kt.getState().replaceAll(Ge,Le||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[Z,s,g]),{selectionModeEnabled:g,hasSelection:h,selectedIdsSize:m,bulkScopeIsArchived:S,derivedSelectionScope:v,bulkScopeFolders:L,bulkCanRemoveFromFolder:C,handleToggleSelectionMode:k,handleExitSelectionMode:B,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:D,handleBulkRemoveFromFolder:H,handleBulkDelete:Z,handleBulkRestore:ie,confirmBulkDelete:$}},Di="oc.sessions.projectCollapse",Pi="oc.sessions.groupOrder",Ei="oc.sessions.groupCollapse",Ti="oc.sessions.activeSessionByProject",Ri="oc.sessions.expandedParents.v3",um=(e,s,n)=>{if(e.time?.archived)return!0;const r=Yo(Gs(e));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const i of s)if(Yo(i)===r)return!0;return!1},fm=new Set,hr=[],Zt=e=>{const s=o.useRef(e);return s.current=e,o.useCallback((...n)=>s.current(...n),[])},hm=({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,om({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},pm=({directories:e})=>{const s=o.useMemo(()=>{const r=new Set;return e.forEach(i=>{const a=Xe(i)?.toLowerCase();a&&r.add(a)}),r},[e]);return nn(r=>{for(const i of r.catalog.byId.values()){if(i.lifecycle!=="busy"&&i.lifecycle!=="retry")continue;const a=Xe(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(Qn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},mm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:i=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Er("react.session_sidebar_render"),rs("ui.session_sidebar.render"),rs(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),rs(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=o.useState(!1),[u,f]=o.useState(""),p=o.useRef(null),g=o.useRef(null),[m,h]=o.useState(null),[x,j]=o.useState(""),[k,B]=o.useState(null),[S,v]=o.useState(new Set),b=o.useMemo(()=>jn(),[]),[L,A]=o.useState(new Set),[C,I]=o.useState(null),[P,D]=o.useState(null),[H,ee]=o.useState(new Map),[Z,ie]=o.useState(new Map),[$,K]=o.useState(!1),[E,R]=o.useState(null),[Y,oe]=o.useState(null),[U,Te]=o.useState(""),[Le,Ve]=o.useState(null),[Ge,Ke]=o.useState(null),[Oe,se]=o.useState(null),fe=Dr(y=>y.ids),He=xd(o.useCallback(y=>e?y.rankById:oa,[e])),ke=nn(y=>e?bd(y.catalog):"",void 0,"catalog"),Ce=o.useMemo(()=>ke?ke.split("|"):hr,[ke]),We=o.useMemo(()=>new Set(Ce),[Ce]),tt=yd(zr(y=>e?Object.entries(y.index.session.unseenCount).filter(([,X])=>X>0).map(([X])=>X).sort():hr)),ze=o.useMemo(()=>new Set(tt),[tt]),q=Dr(y=>y.toggle),[V,ge]=o.useState(()=>{try{const y=jn().getItem(Ei);if(!y)return new Set;const X=JSON.parse(y);return new Set(Array.isArray(X)?X.filter(Q=>typeof Q=="string"):[])}catch{return new Set}}),[J,we]=o.useState(()=>{try{const y=jn().getItem(Pi);if(!y)return new Map;const X=JSON.parse(y),Q=new Map;return Object.entries(X).forEach(([Fe,ut])=>{Array.isArray(ut)&&Q.set(Fe,ut.filter(Ht=>typeof Ht=="string"))}),Q}catch{return new Map}}),xe=o.useMemo(()=>{try{const y=jn().getItem(Ti);if(!y)return new Map;const X=JSON.parse(y),Q=new Map;return Object.entries(X).forEach(([Fe,ut])=>{typeof ut=="string"&&ut.length>0&&Q.set(Fe,ut)}),Q}catch{return new Map}},[]),Ie=o.useCallback(y=>{try{b.setItem(Ti,JSON.stringify(Object.fromEntries(y.entries())))}catch{}},[b]),[ft,mt]=o.useState(new Map),Ze=o.useRef(0),Pe=Es(y=>y.homeDirectory),Re=Es(y=>y.currentDirectory),Ne=_t(y=>y.projects),at=_t(y=>y.activeProjectId),Ct=_t(y=>y.removeProject),st=_t(y=>y.setActiveProjectIdOnly),_=_t(y=>y.updateProjectMeta),ye=_t(y=>y.reorderProjects),be=ue(y=>y.setActiveMainTab),w=ue(y=>y.setSettingsDialogOpen),W=ue(y=>y.setSettingsPage),ne=ue(y=>y.toggleHelpDialog),de=ue(y=>y.setSessionSwitcherOpen),Se=ue(y=>y.setArchivePageOpen),De=ue(y=>y.notifyOnSubtasks),$e=ue(y=>y.showDeletionDialog),ht=ue(y=>y.setShowDeletionDialog),kt=vd(u,120),et=o.useMemo(()=>kt.trim().toLowerCase(),[kt]),pt=et.length>0,gt=Gt(y=>y.collapsedFolderIds),Me=Gt(y=>y.foldersMap),Ye=Gt(y=>y.getFoldersForScope),xt=Gt(y=>y.createFolder),Lt=Gt(y=>y.renameFolder),zt=Gt(y=>y.deleteFolder),At=Gt(y=>y.addSessionToFolder),It=Gt(y=>y.addSessionsToFolder),Dt=Gt(y=>y.removeSessionFromFolder),M=Gt(y=>y.removeSessionsFromFolders),je=Gt(y=>y.toggleFolderCollapse),Be=Gt(y=>y.getSessionFolderId);zh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:g,sessionSearchContainerRef:p});const ct=wd(e),F=eo(),ae=ia(),he=nn(y=>y.connection,void 0,"chrome"),nt=nn(y=>{for(const X of y.catalog.listStatusByDirectory.values())if(X==="ready")return!0;return!1},void 0,"catalog"),ve=Ir({archived:!1}),Je=Ir({archived:!0}),bt=`session-sidebar:${o.useId()}`,Nt=_e(y=>y.setCurrentSession),Mt=_e(y=>y.updateSessionTitle),Et=_e(y=>y.shareSession),$t=_e(y=>y.unshareSession),Ft=da(y=>y.projects),wt=o.useMemo(()=>Sd(Ne,{projects:Ft}),[Ne,Ft]),qt=o.useMemo(()=>{const y=new Map;for(const X of Ne){const Q=Xe(X.path);if(!Q)continue;const Fe=Ft.get(Q)?.error;Fe&&y.set(Q,Fe)}return y},[Ne,Ft]);o.useEffect(()=>{if(!C)return;const y=Ne.find(Q=>Q.id===C);if(!y){I(null),D(null);return}if(!P)return;(wt.get(Xe(y.path)??y.path)??[]).some(Q=>Xe(Q.path)===Xe(P))||(D(null),le.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[wt,Ne,C,P]);const G=_e(y=>y.openNewSessionDraft),te=o.useCallback(y=>{ue.getState().closeMainSurfaces(),G(y),r?.()},[r,G]),re=Ln(zr(y=>({checkForUpdates:y.checkForUpdates,available:y.available,runtimeType:y.runtimeType,info:y.info,downloading:y.downloading,downloaded:y.downloaded,progress:y.progress,error:y.error,downloadUpdate:y.downloadUpdate,restartToUpdate:y.restartToUpdate}))),ce=o.useMemo(()=>jd(Ne,wt,{includeWorktrees:!0}),[wt,Ne]),pe=o.useMemo(()=>ve.filter(y=>um(y,ce,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[ve,ce]),dt=o.useMemo(()=>[...pe,...Je],[Je,pe]),Tt=qn(),yt=o.useMemo(()=>`${Tt}|${Ne.map(y=>`${y.id}:${Xe(y.path)??""}`).join("|")}`,[Ne,Tt]),Ut=o.useMemo(()=>{const y=new Set;let X=!0;for(const Q of Ne){const Fe=Xe(Q.path);if(!Fe)continue;const ut=Ft.get(Fe)?.status??"idle";ut==="failed"&&y.add(Fe),(ut==="idle"||ut==="loading")&&(X=!1)}return{complete:X,unresolved:y}},[Ne,Ft]),ts=Ut.complete?yt:null,Pt=!Ut.complete,os=Ut.unresolved,{isTablet:ls}=Rs(),ms=s||ls,Ls=_h({mobileVariant:s,isTablet:ls}),{buildGroupSearchText:Qs,filterSessionNodesForSearch:T,buildGroupedSessions:me}=Bh({homeDirectory:Pe,pinnedSessionIds:fe,sessionOrderRanks:He}),{scheduleCollapsedProjectsPersist:Ae}=Uh({safeStorage:b,keys:{sessionExpanded:Ri,projectCollapse:Di,groupOrder:Pi,groupCollapse:Ei},groupOrderByProject:J,collapsedGroups:V,setExpandedParents:v,setCollapsedProjects:A}),z=o.useMemo(()=>Cd(pe,fe,He),[fe,He,pe]),Ue=o.useMemo(()=>z.map(y=>y.id).join("|"),[z]),lt=o.useRef(null),vt=o.useMemo(()=>{const y=lt.current;if(y&&y.signature===Ue)return y.map;const X=new Map(z.map((Q,Fe)=>[Q.id,Fe]));return lt.current={signature:Ue,map:X},X},[z,Ue]),St=o.useMemo(()=>{const y=new Map;return z.forEach(X=>{const Q=X.parentID;if(!Q)return;const Fe=y.get(Q)??[];Fe.push(X),y.set(Q,Fe)}),y.forEach(X=>X.sort((Q,Fe)=>Zr(Q,Fe,fe,He))),y},[z,fe,He]),ss=o.useMemo(()=>t.jsx(Ds,{icon:"chat-new",mobileVariant:s,onClick:()=>te(),children:"New session"}),[s,te]),ws=o.useMemo(()=>Ne.find(y=>y.id===k)??null,[Ne,k]),cs=o.useCallback(y=>{k&&_(k,{label:y.label,defaultModel:y.defaultModel??null})},[k,_]),ll=o.useCallback(()=>{const y=Ln.getState();if(y.available&&y.info){K(!0);return}re.checkForUpdates().then(()=>{const{available:X,error:Q}=Ln.getState();if(Q){le.error("Failed to check for updates",{description:Q});return}if(!X){le.success("You are on the latest version");return}K(!0)})},[re]),Os=kd(),xo=o.useCallback(()=>{if(s&&de(!1),r?.(),Os?.openSettings){Os.openSettings();return}w(!0)},[Os,s,r,de,w]),cl=re.available&&(re.runtimeType==="desktop"||re.runtimeType==="web"),dl=_e(y=>y.deleteSession),bo=_e(y=>y.deleteSessions),ul=_e(y=>y.archiveSession),yo=_e(y=>y.archiveSessions),fl=_e(y=>y.unarchiveSession),hl=_e(y=>y.unarchiveSessions),{copiedSessionId:pl,handleSessionSelect:ml,handleSessionDoubleClick:gl,handleSaveEdit:xl,handleCancelEdit:bl,handleShareSession:yl,handleCopyShareUrl:vl,handleCopySessionId:wl,handleUnshareSession:Sl,handleDeleteSession:jl,handleRestoreSession:Cl,confirmDeleteSession:kl}=$h({mobileVariant:s,allowReselect:i,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:be,setSessionSwitcherOpen:de,setCurrentSession:Nt,updateSessionTitle:Mt,shareSession:Et,unshareSession:$t,deleteSession:dl,deleteSessions:bo,archiveSession:ul,archiveSessions:yo,unarchiveSession:fl,childrenMap:St,showDeletionDialog:$e,setDeleteSessionConfirm:Ve,deleteSessionConfirm:Le,setEditingId:h,setEditTitle:j,editingId:m,editTitle:x}),Nl=o.useCallback(()=>{if(!Ge)return;const{scopeKey:y,folderId:X}=Ge;Ke(null),zt(y,X)},[Ge,zt]),vo=o.useCallback(()=>{Ps.requestDirectoryDialog()},[]),Al=o.useCallback(y=>{v(X=>{const Q=Eu(X,y);try{b.setItem(Ri,JSON.stringify(Array.from(Q)))}catch{}return Q})},[b]),wo=o.useCallback((y,X)=>{if(!y)return null;X&&gt.has(X)&&je(X);const Q=xt(y,"New folder",X);return oe(Q.id),Te(Q.name),Q},[gt,je,xt]),xn=Zt(ml),Il=Zt(gl),Dl=Zt(xl),Pl=Zt(bl),El=Zt(yl),Tl=Zt(vl),Rl=Zt(wl),Ml=Zt(Sl),Fl=Zt(jl),Ll=Zt(Cl),sr=Zt(wo),So=o.useCallback((y,X)=>{ie(Q=>{const Fe=new Map(Q);return Fe.set(y,X+7),Fe})},[]),bn=o.useCallback(y=>{ie(X=>{if(!X.has(y))return X;const Q=new Map(X);return Q.delete(y),Q})},[]),jo=o.useCallback(y=>{ie(X=>{let Q=!1;const Fe=new Map(X),ut=`${y}:`;for(const Ht of Fe.keys())Ht.startsWith(ut)&&(Fe.delete(Ht),Q=!0);return Q?Fe:X})},[]),Ol=o.useCallback(y=>{Ze.current=Date.now()+150,jo(y),A(X=>{const Q=new Set(X);Q.has(y)?Q.delete(y):Q.add(y);try{b.setItem(Di,JSON.stringify(Array.from(Q)))}catch{}return Ae(Q),Q})},[jo,b,Ae]),gs=o.useMemo(()=>Ne.map(y=>({...y,normalizedPath:Xe(y.path)})).filter(y=>!!y.normalizedPath),[Ne]),Bl=o.useMemo(()=>gs.map(y=>y.normalizedPath),[gs]),Co=Nd(e?Bl:hr);Vh({enabled:e,normalizedProjects:gs,gitRepoStatus:Co,setProjectRepoStatus:ee,setProjectRootBranches:mt});const _l=_e(y=>y.isLoading),ko=o.useMemo(()=>np(pe,gs,wt,Je),[Je,wt,gs,pe]);Zh({enabled:e,hasAuthoritativeGlobalSessions:nt,sessions:dt});const{getSessionsForProject:zl,getArchivedSessionsForProject:$l}=Qh({ownership:ko});Ph({enabled:e,normalizedProjects:gs,ownership:ko,isSessionsLoading:_l,hasAuthoritativeGlobalSessions:nt,isWorktreeTopologyLoading:Pt,unresolvedWorktreeProjectPaths:os,foldersMap:Me,createFolder:xt,addSessionToFolder:At});const No=o.useRef(!1);at&&H.has(at)&&(No.current=!!H.get(at));const Ul=zp(y=>y.showArchivedSessions),nr=_t(y=>y.manualProjectOrder),Ao=o.useRef(new Set),yn=Tu(Ao.current,S,"project");Ao.current=yn;const rr={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:i,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:ls,catalogSessions:ve,archivedSessions:Je,projects:Ne,activeProjectId:at,manualProjectOrder:nr,currentDirectory:Re,availableWorktreesByProject:wt,pinnedSessionIds:fe,sessionOrderRanks:He,foldersMap:Me,collapsedFolderIds:gt,gitBranches:ct,gitRepoStatus:Co,updateStore:re,showArchivedSessions:Ul,projectRepoStatus:H,projectRootBranches:ft,resolvedWorktreeTopologyKey:ts,unresolvedWorktreeProjectPaths:os,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:m,editTitle:x,editingProjectDialogId:k,expandedParents:S,collapsedProjects:L,visibleSessionCountByGroup:Z,updateDialogOpen:$,openSidebarMenuKey:E,renamingFolderId:Y,renameFolderDraft:U,deleteSessionConfirm:Le,deleteFolderConfirm:Ge,bulkDeleteConfirm:Oe,collapsedGroups:V},Io=o.useRef(null),Do=Io.current;if(Do){let y=!1;for(const X of Object.keys(rr))Object.is(Do[X],rr[X])||(rs(`ui.session_sidebar.source.${X}`),y=!0);y||rs("ui.session_sidebar.source.parent_or_context")}Io.current=rr;const Gl=o.useMemo(()=>{const y=new Map(nr.map((X,Q)=>[X,Q]));return[...gs].sort((X,Q)=>(y.get(X.id)??1/0)-(y.get(Q.id)??1/0))},[nr,gs]),{projectSections:Rt,groupSearchDataByGroup:Po,sectionsForRender:Eo,flatSectionsForRender:vn,searchMatchCount:Kl}=Th({normalizedProjects:Gl,getSessionsForProject:zl,getArchivedSessionsForProject:$l,availableWorktreesByProject:wt,projectRepoStatus:H,projectRootBranches:ft,lastRepoStatus:No.current,buildGroupedSessions:me,hasSessionSearchQuery:pt,normalizedSessionSearchQuery:et,filterSessionNodesForSearch:T,buildGroupSearchText:Qs,foldersMap:Me}),Hl=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:Wl}=Eh(J),To=o.useRef(!1);o.useEffect(()=>{if(To.current||Rt.length===0)return;const y=Rt.flatMap(X=>X.groups.filter(Q=>Q.isArchivedBucket).map(Q=>`${X.project.id}:${Q.id}`));y.length>0&&ge(X=>new Set([...X,...y])),To.current=!0},[Rt]),o.useMemo(()=>{const y=new Map,X=new Map;return Rt.forEach(Q=>{const Fe=Jn(Q.project.label?.trim()||Ts(Q.project.normalizedPath,Pe)||Q.project.normalizedPath);Q.groups.forEach(ut=>{const Ht=ut.branch&&ut.branch!=="HEAD"&&ut.branch!==Fe?ut.branch:null,qs={projectLabel:Fe,branchLabel:Ht},Ss=bc=>{bc.forEach(Bs=>{const Oo=Q.project.normalizedPath.length,yc=X.get(Bs.session.id)??-1;Oo<yc||(y.set(Bs.session.id,{node:Bs,projectId:Q.project.id,groupDirectory:ut.directory,secondaryMeta:qs}),X.set(Bs.session.id,Oo),Bs.children.length>0&&Ss(Bs.children))})};Ss(ut.sessions)})}),y},[Rt,Pe]);const Ro=o.useMemo(()=>vn.map(y=>y.groups.some(X=>X.isArchivedBucket)?{...y,groups:y.groups.filter(X=>!X.isArchivedBucket)}:y),[vn]),Yl=o.useMemo(()=>{if(!C)return Ro;const y=Eo.find(Fe=>Fe.project.id===C);if(!y)return[];const X=Xe(P??y.project.normalizedPath),Q=y.groups.find(Fe=>!Fe.isArchivedBucket&&Xe(Fe.directory)===X);return Q?[{...y,groups:[Q]}]:[]},[Eo,Ro,C,P]),Vl=o.useMemo(()=>{let y=0;for(const X of Rt)for(const Q of X.groups)Q.isArchivedBucket||(y+=Q.sessions.length);return y},[Rt]),Ql=o.useMemo(()=>{const y=new Map;for(const X of Rt){let Q=0;for(const Fe of X.groups)Fe.isArchivedBucket||(Q+=Fe.sessions.length);y.set(X.project.id,Q)}return y},[Rt]),ql=o.useCallback(y=>{const X=Rt.find(Q=>Q.project.id===y);return X?X.groups.some(Q=>Q.isArchivedBucket?!1:Q.sessions.some(Fe=>We.has(Fe.session.id))):!1},[We,Rt]),Jl=o.useCallback(y=>{const X=Rt.find(Q=>Q.project.id===y);return X?X.groups.some(Q=>Q.isArchivedBucket?!1:Q.sessions.some(Fe=>ze.has(Fe.session.id))):!1},[Rt,ze]),Xl=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",Zl=s?"size-4":"h-4.5 w-4.5",wn=Zt((y,X=0,Q,Fe,ut=!1,Ht,qs="project",Ss)=>t.jsx(rm,{node:y,depth:X,groupDirectory:Q,projectId:Fe,archivedBucket:ut,pinnedSessionIds:fe,expandedParents:yn,hasSessionSearchQuery:pt,normalizedSessionSearchQuery:et,notifyOnSubtasks:De,editingId:m,setEditingId:h,editTitle:x,setEditTitle:j,handleSaveEdit:Dl,handleCancelEdit:Pl,toggleParent:Al,handleSessionSelect:xn,handleSessionDoubleClick:Il,togglePinnedSession:q,handleShareSession:El,copiedSessionId:pl,handleCopyShareUrl:Tl,handleCopySessionId:Rl,handleUnshareSession:Ml,openSidebarMenuKey:E,setOpenSidebarMenuKey:R,renamingFolderId:Y,getFoldersForScope:Ye,getSessionFolderId:Be,removeSessionFromFolder:Dt,addSessionToFolder:At,createFolderAndStartRename:sr,handleDeleteSession:Fl,handleRestoreSession:Ll,mobileVariant:s,alwaysShowActions:ms,allowQuickArchiveAction:Ls,renderSessionNode:wn,secondaryMeta:Ht,renderContext:qs,subtreeContainsEditing:Ss?.subtreeContainsEditing??fm,menuOpenSessionId:Ss?.menuOpenSessionId??null,nodeStructureKey:Ss?.nodeStructureKey??"",childRenderExtrasFor:Ss?.childRenderExtrasFor})),ec=o.useMemo(()=>{const y=new Map;return vn.forEach(X=>{const Q=X.groups.find(Fe=>!Fe.isArchivedBucket);Q?.folderScopes&&Q.folderScopes.length>0&&y.set(X.project.id,Q.folderScopes)}),y},[vn]),tc=o.useCallback((y,X)=>{const Q=[];return X.forEach(Fe=>{Fe.isArchivedBucket||(Q.push(Fe.directory),Fe.folderScopes?.forEach(ut=>Q.push(ut.directory)))}),t.jsx(pm,{directories:Q})},[]),Mo=o.useCallback(y=>{bn(y),ge(X=>{const Q=new Set(X);return Q.has(y)?Q.delete(y):Q.add(y),Q})},[bn]),sc=o.useCallback((y,X,Q,Fe,ut,Ht,qs)=>t.jsx(jp,{group:y,groupKey:X,projectId:Q,hideGroupLabel:Fe,dragHandleProps:ut,compactBodyPadding:Ht,hasSessionSearchQuery:pt,normalizedSessionSearchQuery:et,groupSearchDataByGroup:Po,visibleSessionCount:Z.get(X),collapsedGroups:V,hideDirectoryControls:a,collapsedFolderIds:gt,toggleFolderCollapse:je,renameFolder:Lt,deleteFolder:zt,showDeletionDialog:$e,setDeleteFolderConfirm:Ke,renderSessionNode:wn,showMoreGroupSessions:So,resetGroupSessionLimit:bn,mobileVariant:s,alwaysShowActions:ms,activeProjectId:at,setActiveProjectIdOnly:st,setActiveMainTab:be,setSessionSwitcherOpen:de,openNewSessionDraft:te,addSessionToFolder:At,createFolderAndStartRename:sr,renamingFolderId:Y,renameFolderDraft:U,setRenameFolderDraft:Te,setRenamingFolderId:oe,pinnedSessionIds:fe,expandedParents:yn,sessionOrderIndex:vt,editingId:m,editTitle:x,openSidebarMenuKey:E,activeActivitySessionIds:We,unreadActivitySessionIds:ze,notifyOnSubtasks:De,onToggleCollapsedGroup:Mo,scrollContainerRef:qs}),[pt,et,Po,Z,V,a,gt,je,Lt,zt,$e,wn,So,bn,s,ms,at,st,be,de,te,At,sr,Y,U,fe,yn,vt,m,x,E,We,ze,De,Mo]),Fo=!!(Y||m||k),{selectionModeEnabled:Lo,hasSelection:nc,selectedIdsSize:rc,bulkScopeIsArchived:oc,derivedSelectionScope:ic,bulkScopeFolders:ac,bulkCanRemoveFromFolder:lc,handleToggleSelectionMode:cc,handleExitSelectionMode:dc,handleBulkMoveToFolder:uc,handleBulkCreateFolderAndMove:fc,handleBulkRemoveFromFolder:hc,handleBulkDelete:pc,handleBulkRestore:mc,confirmBulkDelete:gc}=dm({isInlineEditing:Fo,showDeletionDialog:$e,foldersMap:Me,folderScopesByProject:ec,addSessionsToFolder:It,removeSessionsFromFolders:M,createFolderAndStartRename:wo,archiveSessions:yo,unarchiveSessions:hl,deleteSessions:bo,setBulkDeleteConfirm:se}),xc=o.useCallback(()=>{ue.getState().closeMainSurfaces(),be("chat"),s&&de(!1),G(),r?.()},[s,r,G,be,de]);return t.jsx(Ad,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:p,className:O("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(hm,{owner:bt,childStores:ae,projectSections:Rt,activeProjectId:at,collapsedProjects:L,collapsedGroups:V,currentDirectory:Re}),t.jsx(Mh,{projectSections:Rt,activeProjectId:at,initialActiveSessionByProject:xe,persistActiveSessionByProject:Ie,handleSessionSelect:xn,mobileVariant:s,openNewSessionDraft:G,setActiveMainTab:be,setSessionSwitcherOpen:de}),t.jsx(Dh,{enabled:e,sortedSessions:z,prefetchSession:async y=>{await F.syncSession(y)}}),!a&&!s?t.jsx(kp,{onNewSession:xc,showSidebarToggle:!0}):null,t.jsx(Cp,{hideDirectoryControls:a,handleOpenDirectoryDialog:vo,onOpenArchive:()=>{s&&de(!1),Se(!0)},onOpenSettings:s?xo:void 0,onOpenInstances:s?Os?.openInstances:void 0,instanceLabel:s?Os?.instanceLabel:void 0,onOpenUpdate:s?Os?.openUpdate:void 0,headerActionIconClass:Zl,headerActionButtonClass:Xl,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:g,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:pt,searchMatchCount:Kl,selectionModeEnabled:Lo,onToggleSelectionMode:cc,mobileVariant:s}),he==="error"||he==="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&&Rt.length>0?t.jsx(Ip,{projects:Rt.map(y=>y.project),selectedProjectId:C,selectedWorktreePath:P,worktreesByProject:wt,worktreeErrorsByProject:qt,onSelectProject:y=>{if(I(y),D(null),!y)return;st(y);const X=Rt.find(ut=>ut.project.id===y),Q=X?.groups.find(ut=>ut.isMain),Fe=Q?.sessions[0]?.session;Fe?xn(Fe.id,Q?.directory??X?.project.normalizedPath??null,{keepPanelOpen:!0}):X&&te({selectedProjectId:y,directoryOverride:X.project.normalizedPath})},onSelectWorktree:(y,X)=>{I(y),D(X),st(y);const ut=Rt.find(Ht=>Ht.project.id===y)?.groups.find(Ht=>Xe(Ht.directory)===Xe(X))?.sessions[0]?.session;ut?xn(ut.id,X,{keepPanelOpen:!0}):te({selectedProjectId:y,directoryOverride:X})},onOpenDirectoryDialog:vo,onOpenProjectEditDialog:B,onRemoveProject:Ct,totalSessionCount:Vl,getSessionCountForProject:y=>Ql.get(y)??0,hasActiveSessionByProject:ql,hasUnseenByProject:Jl,homeDirectory:Pe,mobileVariant:s}):null,t.jsx(Tp,{sectionsForRender:Yl,projectSections:Rt,activeProjectId:at,showOnlyMainWorkspace:l,hasSessionSearchQuery:pt,emptyState:ss,searchEmptyState:Hl,isAllFoldersView:C===null,pinnedSessionIds:fe,renderSessionNode:wn,renderGroupSessions:sc,homeDirectory:Pe,collapsedProjects:L,hideDirectoryControls:a,projectRepoStatus:H,mobileVariant:s,alwaysShowActions:ms,toggleProject:Ol,setActiveProjectIdOnly:st,setActiveMainTab:be,setSessionSwitcherOpen:de,openNewSessionDraft:te,openProjectEditDialog:B,removeProject:Ct,reorderProjects:ye,getOrderedGroups:Wl,setGroupOrderByProject:we,renderProjectStatusIndicator:tc,openSidebarMenuKey:E,setOpenSidebarMenuKey:R,isInlineEditing:Fo}),Lo&&nc?t.jsx(cm,{selectedCount:rc,scopeKey:ic,scopeFolders:ac,archivedBucket:oc,onMoveToFolder:uc,onCreateFolderAndMove:fc,onRemoveFromFolder:hc,canRemoveFromFolder:lc,onRestore:mc,onDelete:pc,onDone:dc}):null,s?null:t.jsx(Dp,{onOpenSettings:xo,onOpenShortcuts:ne,onOpenAbout:()=>{W("about"),w(!0)},onOpenUpdate:ll,showRuntimeButtons:!0,showUpdateButton:cl}),t.jsx(Ra,{open:$,onOpenChange:K,info:re.info,downloading:re.downloading,downloaded:re.downloaded,progress:re.progress,error:re.error,onDownload:re.downloadUpdate,onRestart:re.restartToUpdate,runtimeType:re.runtimeType}),t.jsx(rp,{open:!!ws,onOpenChange:y=>{y||B(null)},project:ws,onSave:cs}),t.jsx(im,{value:Le,setValue:Ve,showDeletionDialog:$e,setShowDeletionDialog:ht,onConfirm:kl}),t.jsx(lm,{value:Ge,setValue:Ke,onConfirm:Nl}),t.jsx(am,{value:Oe,setValue:se,showDeletionDialog:$e,setShowDeletionDialog:ht,onConfirm:gc})]})})},Ax=o.memo(mm),Mi=6,es=.18,tn=1.2,sn=.38,_n=48,gm=(e,s)=>e==="left"?s<0:s>0,Ix=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Dx=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,Fi=(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)),Px=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<-es:c>es,u=s==="left"?c>es:c<-es;return d||!u&&a<sn}return Math.abs(n)>=_n&&Math.abs(r)<=Math.abs(n)*tn&&gm(s,n)},xm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:i,progress:a}=e,l=r/Math.max(1,i);return s==="left"?n?l<-es?!1:l>es?!0:a>sn:l>es?!0:l<-es?!1:a>sn:n?l>es?!1:l<-es?!0:a>sn:l<-es?!0:l>es?!1:a>sn},bm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',ym=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(bm);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},vm=({value:e,options:s,disabled:n,onChange:r})=>{const i=e||"Default",a=t.jsxs("div",{className:O("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(Yt,{children:[t.jsx(Vt,{asChild:!0,children:a}),t.jsxs(Qt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(jt,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:O("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(jt,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:O("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Li=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function wm(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),f=Ot(v=>v.currentModelId),p=Ot(v=>v.currentVariant||""),g=Ot(v=>v.currentAgentName||""),[m,h]=o.useState(()=>Li({providerID:u,modelID:f,variant:p,agent:g}));o.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),o.useEffect(()=>{s&&h(Li({providerID:u,modelID:f,variant:p,agent:g}))},[s,u,f,p,g]),o.useEffect(()=>{if(!s||d.length===0)return;const v=d.find(C=>C.id===m.providerID)??d[0],b=Array.isArray(v?.models)?v.models:[],L=b.some(C=>C.id===m.modelID),A=b[0]?.id??"";v?.id===m.providerID&&L||h(C=>({...C,providerID:typeof v?.id=="string"?v.id:"",modelID:typeof A=="string"?L?C.modelID:A:"",variant:""}))},[s,d,m.providerID,m.modelID]),o.useCallback(v=>Id(v.mode),[]);const x=o.useMemo(()=>{const b=d.find(L=>L.id===m.providerID)?.models?.find(L=>L.id===m.modelID);return b?.variants?Object.keys(b.variants):[]},[d,m.providerID,m.modelID]),j=x.length>0;o.useEffect(()=>{j||!m.variant||h(v=>({...v,variant:""}))},[j,m.variant]);const k=m.providerID.trim().length>0&&m.modelID.trim().length>0,B=o.useCallback(()=>{!k||i||a(m)},[k,i,a,m]);return o.useEffect(()=>{if(!s)return;const v=b=>{(b.metaKey||b.ctrlKey)&&b.key==="Enter"&&(b.preventDefault(),B())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[s,B]),t.jsx(is,{open:s,onOpenChange:v=>{i||n(v)},children:t.jsxs(as,{className:"max-w-md overflow-visible",children:[t.jsx(vs,{children:t.jsx(hs,{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(vm,{value:m.variant,options:x,disabled:!j,onChange:v=>h(b=>({...b,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:B,disabled:!k||i,children:i?"Sending":"Send"})]})})]})})}const qr=5,ol=15,Pn=new Map,zn=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},Sm=(e,s)=>{const n=zn(s);return Math.max(n*qr,Math.min(n*ol,n*e))},jm=async(e,s)=>{const n=await Rd(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},Cm=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Oi=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],Bi=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},km=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=co({id:e});return t.jsx("li",{ref:i,style:{transform:uo.Transform.toString(l),transition:c},className:O(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},Nm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[i,a]=o.useState(!1),[l,c]=o.useState(""),[d,u]=o.useState([]),[f,p]=o.useState(""),[g,m]=o.useState(null),[h,x]=o.useState(()=>new Set),[j,k]=o.useState([]),[B,S]=o.useState(null),[v,b]=o.useState(!1),[L,A]=o.useState(0),C=o.useRef(!1),I=o.useRef(""),P=o.useRef(null),D=ue(w=>w.todoPanelHeight),H=ue(w=>w.setTodoPanelHeight),ee=ue(w=>w.notesPanelHeight),Z=ue(w=>w.setNotesPanelHeight),[ie,$]=o.useState(!1),K=o.useRef(0),E=o.useRef(D),R=_e(w=>w.currentSessionId),Y=_e(w=>w.createSession),oe=_e(w=>w.initializeNewPiChamberSession),U=_e(w=>w.sendMessage),Te=_e(w=>w.setCurrentSession),Le=Dd(w=>w.setPendingInputText),Ve=Es(w=>w.currentDirectory),Ge=ue(w=>w.openContextPanelTab),Ke=ue(w=>w.setActiveMainTab),Oe=ue(w=>w.setSessionSwitcherOpen),se=ue(w=>w.padding),fe=o.useCallback(async(w,W)=>{if(!e)return!1;const ne=e.id,Se=(Pn.get(ne)??Promise.resolve()).catch(()=>{}).then(()=>Pd(e,{notes:w,todos:W}));Pn.set(ne,Se);try{const De=await Se;return De||le.error("Failed to save project notes"),De}finally{Pn.get(ne)===Se&&Pn.delete(ne)}},[e]);o.useEffect(()=>{if(!e){c(""),u([]),k([]),p(""),x(new Set);return}let w=!1;return a(!0),(async()=>{try{const W=await Ed(e),ne=await Promise.all(W.plans.map(de=>jm(de,"Plan")));if(w)return;c(W.notes),u(Oi(W.todos)),k(ne),I.current=W.notes,C.current=!0,p(""),x(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=W=>{const ne=W.detail;ne?.projectId&&ne.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=Sm(d.length,se),W=zn(se)*qr;D!==w&&(D<W||D>w)&&H(w)},[d.length,se,D,H]),o.useEffect(()=>{if(!ie)return;const w=ne=>{const de=ne.clientY-K.current,Se=Math.min(zn(se)*ol,Math.max(zn(se)*qr,E.current+de));H(Se)},W=()=>{$(!1)};return window.addEventListener("pointermove",w),window.addEventListener("pointerup",W,{once:!0}),window.addEventListener("pointercancel",W,{once:!0}),()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",W),window.removeEventListener("pointercancel",W)}},[ie,se,H]);const He=o.useCallback(w=>{$(!0),K.current=w.clientY,E.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,fe(l,d)},[ke,l,fe,d]);o.useEffect(()=>{if(!(!e||!C.current)&&l!==I.current)return P.current=window.setTimeout(()=>{P.current=null,I.current=l,fe(l,d)},400),()=>{ke()}},[ke,l,fe,e,d]),o.useEffect(()=>()=>ke(),[ke]);const We=o.useCallback(()=>{const w=f.trim();if(!w)return;const W=Bi(d,{id:Cm(),text:w.slice(0,Sn),completed:!1,createdAt:Date.now()});u(W),p(""),fe(l,W)},[f,l,fe,d]),tt=o.useCallback(w=>{x(W=>{const ne=new Set(W);return ne.has(w)?ne.delete(w):ne.add(w),ne})},[]),ze=o.useCallback((w,W)=>{const ne=d.find($e=>$e.id===w);if(!ne||ne.completed===W)return;const de=d.filter($e=>$e.id!==w),Se={...ne,completed:W},De=W?[...de,Se]:Bi(de,Se);u(De),fe(l,De)},[l,fe,d]),q=o.useCallback(w=>{const W=d.filter(ne=>ne.id!==w);u(W),fe(l,W)},[l,fe,d]),V=o.useCallback(()=>{const w=d.filter(W=>!W.completed);w.length!==d.length&&(u(w),fe(l,w))},[l,fe,d]),ge=o.useCallback(w=>{const{active:W,over:ne}=w;if(!ne||W.id===ne.id)return;const de=d.findIndex($e=>$e.id===W.id),Se=d.findIndex($e=>$e.id===ne.id);if(de===-1||Se===-1)return;const De=Oi(Vu(d,de,Se));u(De),fe(l,De)},[l,fe,d]),J=Xn(hn(ao,{activationConstraint:{distance:8}})),we=f.slice(0,Sn),xe=d.reduce((w,W)=>w+(W.completed?1:0),0),Ie=o.useCallback(()=>{Ke("chat"),Oe(!1)},[Ke,Oe]),ft=o.useCallback((w,W)=>{!e||g!==null||S({todoId:w,todoText:W})},[e,g]),mt=o.useCallback(w=>{if(!R){le.error("No active session selected");return}Ie();const W=`\`\`\`md
47
- ${w}
48
- \`\`\``;Le(W,"append"),le.success("Todo sent to current session"),n?.()},[R,n,Ie,Le]),Ze=o.useCallback(async w=>{if(!e||!B)return;const W=await Vo("plan.todo.visible",{todo_text:B.todoText}),de=[{synthetic:!0,text:await Vo("plan.todo.instructions",{todo_text:B.todoText})}];b(!0),m(B.todoId);try{Ie();const Se=await Y(void 0,e.path,null);if(!Se?.id){le.error("Failed to create session");return}const De=Se.id,$e=Se.directory??e.path;oe(Se.id,Ot.getState().agents??[]);const ht=ta.getState();ht.saveSessionModelSelection(De,w.providerID,w.modelID),w.agent.trim()&&(ht.saveSessionAgentSelection(De,w.agent),ht.saveAgentModelForSession(De,w.agent,w.providerID,w.modelID),ht.saveAgentModelVariantForSession(De,w.agent,w.providerID,w.modelID,w.variant||void 0)),Te(De,$e),await U(W,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"),S(null),n?.()}catch{le.error("Failed to send note")}finally{b(!1),m(null)}},[Y,oe,n,B,e,Ie,U,Te]),Pe=o.useRef(null),[Re,Ne]=o.useState(!1),[at,Ct]=o.useState(null),st=o.useCallback(async w=>{if(!(!e||at)){Ct(w);try{if(!await Td(e,w)){le.error("Failed to delete plan");return}k(ne=>ne.filter(de=>de.id!==w)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{Ct(null)}}},[at,e]),_=o.useCallback(async()=>{if(!e||Re)return;const w=await hu({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(w.success&&w.path){Ne(!0);try{const W=new URLSearchParams({path:w.path,allowOutsideWorkspace:"true"});w.outsideFileGrant&&W.set("outsideFileGrant",w.outsideFileGrant);const ne=await Xt(`/api/fs/read?${W.toString()}`,{cache:"no-store"});if(!ne.ok){le.error("Failed to read plan file");return}const de=await ne.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 Qo(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(W){const ne=W instanceof Error?W.message:void 0;le.error("Failed to read plan file",ne?{description:ne}:void 0)}finally{Ne(!1)}}else w.error==="Native file picker not available"&&Pe.current?.click()},[Re,e]),ye=o.useCallback(async w=>{if(!(!e||!w)){Ne(!0);try{const W=await w.text();if(!W.trim()){le.error("Plan file is empty");return}const ne=w.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Qo(e,W,ne)){le.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),le.success("Plan imported")}catch(W){const ne=W instanceof Error?W.message:void 0;le.error("Failed to read plan file",ne?{description:ne}:void 0)}finally{Ne(!1)}}},[e]),be=o.useCallback(w=>{const W=e?.path?.trim(),ne=Ve?.trim()||W;ne&&Ge(ne,{mode:"file",targetPath:w.path,dedupeKey:w.path,label:w.title})},[Ve,Ge,e]);return e?t.jsxs("div",{className:O("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,"/",qo]})]}),t.jsx(ho,{value:l,onChange:w=>c(w.target.value.slice(0,qo)),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:V,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,"/",Sn]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{value:we,onChange:w=>p(w.target.value.slice(0,Sn)),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),We())},placeholder:"Add a todo",disabled:i,className:"h-8"}),t.jsx("button",{type:"button",onClick:We,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:O("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(Zn,{sensors:J,collisionDetection:er,onDragEnd:ge,children:t.jsx(lo,{items:d.map(w=>w.id),strategy:Ia,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(w=>{const W=h.has(w.id);return t.jsx(km,{id:w.id,children:ne=>t.jsxs("div",{className:O("flex gap-1.5 px-2.5 py-1.5",W?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:ne.setActivatorNodeRef,...ne.attributes,...ne.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(Ji,{checked:w.completed,onChange:de=>ze(w.id,de),ariaLabel:`Mark \\"${w.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>tt(w.id),className:O("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",W?"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:W?void 0:w.text,"aria-label":W?`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:()=>q(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(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:g===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(Qt,{align:"end",className:"w-56",children:[t.jsx(jt,{onClick:()=>mt(w.text),children:"Send to current session"}),t.jsx(jt,{onClick:()=>ft(w.id,w.text),children:"Send to new session"})]})]})]})]})},w.id)})})})})}),d.length>=7&&t.jsx("div",{className:O("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",ie&&"bg-[var(--interactive-border)]"),onPointerDown:He,role:"separator","aria-orientation":"horizontal","aria-label":"Resize todo list"})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Plans"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:j.length===1?`${j.length} file`:`${j.length} files`})]}),t.jsx("input",{ref:Pe,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:w=>{const W=w.target.files?.[0]??null;ye(W),w.currentTarget.value=""}}),t.jsx("button",{type:"button",onClick:_,disabled:!e||Re,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:j.length===0?t.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No saved plans yet."}):t.jsx("ul",{className:"divide-y divide-border/50",children:j.map(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(wm,{open:B!==null,onOpenChange:w=>{!w&&!v&&S(null)},projectDirectory:e?.path??null,submitting:v,onConfirm:Ze})]}):t.jsx("div",{className:O("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."})})},Ex=({onActionComplete:e})=>{const s=_t(c=>c.activeProjectId),n=_t(c=>c.projects),r=Es(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()||Ts(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(Nm,{projectRef:a,projectLabel:l,onActionComplete:e})})},$n=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Jr=512*1024,Am=new TextEncoder,Im=new TextDecoder,pr=e=>{const s=Am.encode(e);if(s.byteLength<=Jr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-Jr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:Im.decode(r),byteLength:r.byteLength}},_s=(e,s)=>`${e}\0${s}`,mr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},Dm="terminal-store";let _i=!1,zi=0;const En=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(zi+=1,`tab-${Date.now().toString(36)}-${zi.toString(36)}`),gr=e=>typeof e=="object"&&e!==null,Pm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function Bt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const Em=/^Terminal(?: (\d+))?$/,Tm=e=>{let s=0;for(const n of e){const r=Em.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}`},xr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),br=e=>({tabs:[e],activeTabId:e.id}),ns=(e,s)=>e.tabs.findIndex(n=>n.id===s);let yr=null,vr=null;const Rm=e=>{if(vr&&yr?.sessions===e.sessions&&yr.nextTabId===e.nextTabId)return vr;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 yr={sessions:e.sessions,nextTabId:e.nextTabId},vr=s,s},Mm=()=>{const e=Uu(()=>pu());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=ps()(Na(io((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=Bt(n);r&&e(i=>{if(i.sessions.has(r))return i;const a=new Map(i.sessions),l=En(),c=xr(l,"Terminal");return a.set(r,br(c)),{sessions:a,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const r=Bt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=Bt(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(_s(Bt(n),r))??$n,createTab:n=>{const r=Bt(n);if(!r)return"tab-invalid";const i=En();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Tm(c?.tabs??[]),f=xr(i,u);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,br(f)),{sessions:l,nextTabId:d}}),i},setActiveTab:(n,r)=>{const i=Bt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);return!c||c.activeTabId===r||ns(c,r)<0?a:(l.set(i,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,i)=>{const a=Bt(n),l=i.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=ns(u,r);if(f<0||u.tabs[f]?.label===l)return c;const p=[...u.tabs];return p[f]={...p[f],label:l},d.set(a,{...u,tabs:p}),{sessions:d}})},setTabIconKey:(n,r,i)=>{const a=Bt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ns(d,r);if(u<0)return l;const f=i?.trim()||null;if(d.tabs[u]?.iconKey===f)return l;const p=[...d.tabs];return p[u]={...p[u],iconKey:f},c.set(a,{...d,tabs:p}),{sessions:c}})},closeTab:(n,r)=>{const i=Bt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=ns(c,r);if(d<0)return a;const u=c.tabs.filter(x=>x.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,x])=>!(x.directory===i&&x.tabId===r))),p=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,g=_s(i,r),m=a.buffers.has(g)?mr(a.buffers,x=>x===g):null;if(u.length===0){const x=En(),j=xr(x,"Terminal");return l.set(i,br(j)),{sessions:l,nextTabId:a.nextTabId+1,...m?{buffers:m}:{},...p?{projectActionRuns:f}:{}}}let h=c.activeTabId;return c.activeTabId===r&&(h=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(i,{...c,tabs:u,activeTabId:h}),{sessions:l,...m?{buffers:m}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,i)=>{const a=Bt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ns(d,r);if(u<0)return l;const f=d.tabs[u],p=i!==null&&f.terminalSessionId!==i,g=i?"running":f.terminalSessionId?"exited":f.lifecycle,m={...f,terminalSessionId:i,lifecycle:g,isConnecting:!1},h=_s(a,r),x=p&&l.buffers.has(h)?mr(l.buffers,k=>k===h):null,j=[...d.tabs];return j[u]=m,c.set(a,{...d,tabs:j}),{sessions:c,...x?{buffers:x}:{}}})},setTabLifecycle:(n,r,i)=>{const a=Bt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ns(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],lifecycle:i,isConnecting:!1},c.set(a,{...d,tabs:f}),{sessions:c}})},setConnecting:(n,r,i)=>{const a=Bt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ns(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],isConnecting:i},c.set(a,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,i,a)=>{const l=Bt(n);e(c=>{const d=c.sessions.get(l);if(!d||ns(d,r)<0)return c;const u=_s(l,r),f=c.buffers.get(u)??$n;if(f.lastSequence>a)return c;const p=pr(i);if(f.lastSequence===a&&f.byteLength===p.byteLength&&f.chunks.map(h=>h.data).join("")===p.text)return c;const g=c.nextChunkId,m=new Map(c.buffers);return m.set(u,{chunks:p.text?[{id:g,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:a}),{buffers:m,nextChunkId:p.text?g+1:g}})},appendToBuffer:(n,r,i,a,l)=>{if(!i)return;const c=Bt(n);e(d=>{const u=d.sessions.get(c);if(!u||ns(u,r)<0)return d;const f=_s(c,r),p=d.buffers.get(f)??$n;if(a!==void 0&&a<=p.lastSequence)return d;const g=d.nextChunkId,m=pr(i),h=l!==void 0&&l!==i?pr(l).text:void 0,x={id:g,data:m.text,...h!==void 0?{replayData:h}:{},byteLength:m.byteLength},j=[...p.chunks,x];let k=p.byteLength+x.byteLength;for(;k>Jr&&j.length>1;){const S=j.shift();if(!S)break;k-=S.byteLength}const B=new Map(d.buffers);return B.set(f,{chunks:j,byteLength:k,lastSequence:a??p.lastSequence}),{buffers:B,nextChunkId:g+1}})},setTabPreviewUrl:(n,r,i,a={})=>{const l=Bt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const f=ns(u,r);if(f<0)return c;const p=u.tabs[f],g=a.autoOpened??p.previewAutoOpened,m=a.locked??p.previewUrlLocked;if(p.previewUrl===i&&p.previewAutoOpened===g&&p.previewUrlLocked===m)return c;const h=[...u.tabs];return h[f]={...p,previewUrl:i,previewAutoOpened:g,previewUrlLocked:m},d.set(l,{...u,tabs:h}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const i=Bt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=ns(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const f=[...c.tabs];return f[d]={...u,previewAutoOpened:!0},l.set(i,{...c,tabs:f}),{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=Bt(n);e(i=>{const a=new Map(i.sessions);a.delete(r);const l=_s(r,""),c=mr(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:Dm,storage:Mm(),partialize:Rm,merge:(e,s)=>{if(!gr(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"||!gr(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],p=[],g=new Map;for(const j of f){if(!gr(j))continue;const k=typeof j.id=="string"?j.id:null;if(!k)continue;const B=Pm(k);B!==null&&(i=Math.max(i,B));const S=B===null?k:En();g.set(k,S),p.push({id:S,label:typeof j.label=="string"?j.label:"Terminal",iconKey:typeof j.iconKey=="string"?j.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof j.createdAt=="number"?j.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const m=typeof u.activeTabId=="string"?u.activeTabId:null,h=m?g.get(m)??m:null,x=h?p.some(j=>j.id===h):!1;r.set(d,{tabs:p,activeTabId:x?h:p[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 Fm(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 Lm(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 wr=["\x1B[0m","\x1B[m"],Om=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},$i=e=>{const s=Om(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},Bm=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let i=0;const a=Math.max(...wr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);wr.some(f=>f.length>u.length&&f.startsWith(u))&&(i=d)}const l=i>0?r.slice(-i):"";let c=i>0?r.slice(0,-i):r;for(const d of wr)c=c.replaceAll(d,n);return{data:c,carry:l}},_m=(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))}},zm=(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 $m=null;const Um=()=>$m??=Is(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,11])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Gm=2e3,Km=()=>{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,Gm))]).then(()=>{})},Hm=(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))}},il=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:f=!0},p)=>{const g=o.useRef(null),m=o.useRef(null),h=o.useRef(null),x=o.useRef(n),j=o.useRef(r),k=o.useRef(null),B=o.useRef(null),S=o.useRef(null),v=o.useRef(""),b=o.useRef(""),L=o.useRef($i(i.background)),A=o.useRef(!1),C=o.useRef(0),I=o.useRef(f),P=o.useRef(!1),[D,H]=o.useState(0),[ee,Z]=o.useState(0);x.current=n,j.current=r,I.current=f,L.current=$i(i.background),o.useLayoutEffect(()=>{const E=g.current;if(!E)return;const R=Hm(E,a,l);B.current=R,R&&j.current(R.cols,R.rows)},[a,l]);const ie=o.useCallback(()=>{const E=g.current,R=m.current;if(!E||!R||!h.current||!I.current)return;const Y=E.getBoundingClientRect();if(!(Y.width<24||Y.height<24))try{h.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,j.current(oe.cols,oe.rows)),P.current||(P.current=!0,H(U=>U+1))}catch{}},[]),$=o.useCallback(()=>{if(A.current||!v.current||!m.current)return;const E=m.current,R=v.current;v.current="";const Y=Bm(R,b.current,L.current);if(b.current=Y.carry,!Y.data){v.current&&$();return}A.current=!0;const oe=C.current;E.write(Y.data,()=>{m.current!==E||C.current!==oe||(A.current=!1,v.current&&$())})},[]),K=o.useCallback(()=>{S.current=null,v.current="",b.current="",A.current=!1,C.current+=1;const E=m.current;if(!E){Z(R=>R+1);return}try{E.reset();const R=L.current;R&&E.write(`${R}\x1B[2J\x1B[H`)}catch{Z(R=>R+1)}},[]);return o.useEffect(()=>{const E=g.current;if(!E)return;let R=!1,Y=null,oe=null,U=null,Te=null,Le=[];const Ve=()=>{Y&&I.current&&(Y.options.cursorBlink=!0)},Ge=se=>{se.relatedTarget instanceof Node&&E.contains(se.relatedTarget)||Y&&(Y.options.cursorBlink=!1)},Ke=()=>{Y&&I.current&&E.contains(document.activeElement)&&(Y.options.cursorBlink=!0)},Oe=()=>{Y&&(Y.options.cursorBlink=!1)};return E.addEventListener("focusin",Ve),E.addEventListener("focusout",Ge),window.addEventListener("focus",Ke),window.addEventListener("blur",Oe),Promise.all([Um(),Km()]).then(([{module:se,ghostty:fe}])=>{if(R)return;Y=new se.Terminal({...Lm(a,l,i,fe,!1),...B.current??{}});const He=new se.FitAddon;Y.loadAddon(He),Y.open(E),m.current=Y,h.current=He,Le=[Y.onData(Ce=>x.current(Ce))],oe=new ResizeObserver(()=>{U&&clearTimeout(U),U=setTimeout(ie,80)}),oe.observe(E),ie();const ke=L.current;ke&&Y.write(`${ke}\x1B[2J\x1B[H`),Te=requestAnimationFrame(ie)}),()=>{R=!0;const se=document.activeElement;se instanceof HTMLElement&&E.contains(se)&&(se.blur(),window.Capacitor?.getPlatform?.()==="android"&&Is(async()=>{const{Keyboard:He}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:He}},__vite__mapDeps([113,114])).then(({Keyboard:He})=>He.hide()).catch(()=>{})),oe?.disconnect(),U&&clearTimeout(U),Te!==null&&cancelAnimationFrame(Te),E.removeEventListener("focusin",Ve),E.removeEventListener("focusout",Ge),window.removeEventListener("focus",Ke),window.removeEventListener("blur",Oe),Le.forEach(fe=>fe.dispose()),Y?.dispose(),m.current=null,h.current=null,k.current=null,S.current=null,v.current="",b.current="",A.current=!1,C.current+=1,P.current=!1}},[ie,a,l,ee,i]),o.useEffect(()=>{const E=m.current,R=g.current;!E||!R||(E.options.cursorBlink=f&&document.hasFocus()&&R.contains(document.activeElement))},[f,D]),o.useEffect(()=>{if(!m.current)return;if(s.length===0){S.current!==null&&K();return}const R=S.current;let Y=-1;if(R!==null){for(let Te=s.length-1;Te>=0;Te-=1){const Le=s[Te].id;if(Le===R){Y=Te;break}if(Le<R)break}if(Y<0){K();return}}const oe=Y<0,U=Y>=0?s.slice(Y+1):s;v.current+=U.map(Te=>oe?Te.replayData??Te.data:Te.data).join(""),S.current=s.at(-1)?.id??null,$()},[s,$,D,K]),o.useEffect(()=>{if(!u||!f)return;const E=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(E)},[u,f,D,e]),o.useEffect(()=>{const E=g.current;if(!d||!E)return;const R=Y=>{const oe=Y;if(!oe.isComposing)switch(oe.inputType){case"insertText":oe.data&&x.current(oe.data);break;case"insertLineBreak":case"insertParagraph":x.current("\r");break;case"deleteContentBackward":x.current("");break}};return E.addEventListener("beforeinput",R),()=>E.removeEventListener("beforeinput",R)},[d,D]),o.useEffect(()=>{const E=g.current,R=m.current;if(!d||!E||!R)return;let Y=null,oe=null,U="idle",Te=0,Le=0,Ve=0,Ge=0,Ke=null;const Oe=Math.max(12,l+2),se=()=>{window.Capacitor?.getPlatform?.()==="android"&&Is(async()=>{const{Keyboard:ge}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ge}},__vite__mapDeps([113,114])).then(({Keyboard:ge})=>ge.show()).catch(()=>{})},fe=()=>{oe&&(clearTimeout(oe),oe=null)},He=(V,ge)=>{const J=E.querySelector("canvas");return J?_m(V,ge,J.getBoundingClientRect(),R.cols,R.rows):null},ke=(V,ge)=>{const J=E.querySelector("canvas");if(!J)return;const we=J.getBoundingClientRect(),xe=we.left+(ge.column+.5)/R.cols*we.width,Ie=we.top+(ge.row+.5)/R.rows*we.height;J.dispatchEvent(new MouseEvent(V,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:xe,clientY:Ie}))},Ce=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},We=V=>{V.pointerType!=="touch"||Y!==null||(Y=V.pointerId,U="pending",Te=V.clientX,Le=V.clientY,Ve=V.clientY,Ge=0,Ke=null,E.setPointerCapture(V.pointerId),oe=setTimeout(()=>{if(oe=null,Y!==V.pointerId||U!=="pending")return;const ge=He(Te,Le);if(!ge)return;const J=R.buffer.active,we=Math.max(0,J.length-R.rows-J.viewportY+ge.row),xe=J.getLine(we),Ie=Array.from({length:R.cols},(Ze,Pe)=>xe?.getCell(Pe)?.getChars()??""),ft=zm(Ie,ge.column),mt={column:ft.startColumn,row:ge.row};Ke={column:ft.endColumn,row:ge.row},U="selecting",ke("mousedown",mt),ke("mousemove",Ke)},350))},tt=V=>{if(Y!==V.pointerId)return;if(U==="selecting"){const we=He(V.clientX,V.clientY);we&&(!Ke||we.column!==Ke.column||we.row!==Ke.row)&&(Ke=we,ke("mousemove",we)),V.cancelable&&V.preventDefault();return}if(U==="pending"){if(Math.hypot(V.clientX-Te,V.clientY-Le)<8)return;fe(),U="scrolling"}if(U!=="scrolling")return;const ge=Ve-V.clientY;Ve=V.clientY,Ge+=ge;const J=Math.trunc(Ge/Oe);J&&(R.scrollLines(J),Ge-=J*Oe),V.cancelable&&V.preventDefault()},ze=V=>{if(Y!==V.pointerId)return;const ge=U==="pending",J=U==="selecting";fe(),E.hasPointerCapture(V.pointerId)&&E.releasePointerCapture(V.pointerId),Y=null,U="idle",J&&Ce(),ge&&(R.focus(),se())},q=V=>{if(Y!==V.pointerId)return;const ge=U==="selecting";fe(),E.hasPointerCapture(V.pointerId)&&E.releasePointerCapture(V.pointerId),Y=null,U="idle",ge&&Ce()};return E.addEventListener("pointerdown",We),E.addEventListener("pointermove",tt,{passive:!1}),E.addEventListener("pointerup",ze),E.addEventListener("pointercancel",q),()=>{fe(),E.removeEventListener("pointerdown",We),E.removeEventListener("pointermove",tt),E.removeEventListener("pointerup",ze),E.removeEventListener("pointercancel",q)}},[d,l,D]),o.useImperativeHandle(p,()=>({focus:()=>m.current?.focus(),fit:ie,getSelection:()=>{const E=m.current,R=E?.getSelectionPosition(),Y=E?.getSelection()??"";return!R||!Y.trim()?null:{text:Y,startLine:R.start.y+1,endLine:R.end.y+1}}}),[ie]),t.jsx("div",{ref:g,"data-terminal-owner":"main",className:O("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});il.displayName="TerminalViewport";const Wm=280,Ui=4,Ym=({transform:e})=>({...e,y:0}),Vm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:d}=co({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:uo.Transform.toString(l),transition:c},className:O("h-full rounded-md",n,d&&"opacity-50"),...r,...i,children:s})},Qm=({id:e,children:s,className:n})=>t.jsx("div",{className:O("h-full",n),"data-sortable-tab-id":e,children:s}),qm=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:i,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:f,activePillLowercase:p=!0,nonCompositedIndicator:g=!1,className:m})=>{const h=ue(q=>q.isMobile),{isTablet:x}=Rs(),j=h||x,k=o.useRef(null),[B,S]=o.useState({left:!1,right:!1}),v=o.useMemo(()=>e.map(q=>q.id),[e]),b=a==="scrollable",L=l==="default",A=l==="active-pill",I=A||l==="animated",P=L,D=I||P,H=A&&b,ee=I,Z=f??I,ie=typeof i=="function",$=ie?Vm:Qm,K=o.useRef(new Map),[E,R]=o.useState(null),[Y,oe]=o.useState(!1),[U,Te]=o.useState(null),Le=o.useRef(!1),Ve=o.useRef(0),Ge=o.useRef(s),Ke=o.useRef(null),Oe=o.useMemo(()=>{if(!D||!U||!s||U===s)return 0;const q=e.findIndex(ge=>ge.id===U),V=e.findIndex(ge=>ge.id===s);return q<0||V<0?0:q>V?Ui:-Ui},[s,e,U,D]),se=Xn(hn(ao,{activationConstraint:{distance:8}})),fe=o.useCallback((q,V)=>!q||!V?q===V:Math.abs(q.left-V.left)<.5&&Math.abs(q.top-V.top)<.5&&Math.abs(q.width-V.width)<.5&&Math.abs(q.height-V.height)<.5,[]),He=o.useCallback((q,V)=>{if(V){K.current.set(q,V);return}K.current.delete(q)},[]),ke=o.useCallback(()=>{if(!D||!s){R(Ie=>Ie===null?Ie:null);return}const q=k.current,V=K.current.get(s);if(!q||!V){R(Ie=>Ie===null?Ie:null);return}let ge=0,J=0,we=V;for(;we&&we!==q;)ge+=we.offsetLeft,J+=we.offsetTop,we=we.offsetParent;const xe={left:ge,top:J,width:V.offsetWidth,height:V.offsetHeight};R(Ie=>fe(Ie,xe)?Ie:xe)},[s,fe,D]),Ce=o.useCallback(()=>{if(!b){S({left:!1,right:!1});return}const q=k.current;if(!q){S({left:!1,right:!1});return}S({left:q.scrollLeft>2,right:q.scrollLeft+q.clientWidth<q.scrollWidth-2})},[b]);o.useEffect(()=>{if(!b){S({left:!1,right:!1});return}const q=k.current;if(!q)return;Ce(),q.addEventListener("scroll",Ce,{passive:!0});const V=new ResizeObserver(Ce);return V.observe(q),()=>{q.removeEventListener("scroll",Ce),V.disconnect()}},[b,e.length,Ce]),o.useEffect(()=>{if(!D){R(null);return}ke();const q=k.current;if(!q)return;const V=new ResizeObserver(()=>{performance.now()-Ve.current>Wm&&oe(!1),ke()});if(V.observe(q),s){const ge=K.current.get(s);ge&&V.observe(ge)}return()=>{V.disconnect()}},[s,e.length,ke,D]),o.useLayoutEffect(()=>{ke()});const We=v.join("\0");o.useLayoutEffect(()=>{if(!D){Le.current=!1,oe(!1);return}const q=Ke.current!==We;if(Ke.current=We,!Le.current){Le.current=!0,Ge.current=s;return}const V=Ge.current!==s;if(Ge.current=s,!V||q){oe(!1);return}Ve.current=performance.now(),oe(!0)},[s,We,D]),o.useEffect(()=>{if(!b||!s)return;const q=k.current;if(!q)return;const V=window.requestAnimationFrame(()=>{const ge=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),J=q.querySelector(`[data-sortable-tab-id="${ge}"]`);J&&(J.scrollIntoView({block:"nearest",inline:"nearest"}),Ce())});return()=>{window.cancelAnimationFrame(V)}},[s,b,e.length,Ce]);const tt=o.useCallback(q=>{if(!i)return;const{active:V,over:ge}=q;!ge||V.id===ge.id||i(String(V.id),String(ge.id))},[i]),ze=t.jsxs("div",{className:O("relative flex h-full min-w-0 flex-1",m),children:[b&&B.left?t.jsx("div",{className:O("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,b&&B.right?t.jsx("div",{className:O("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:O("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",b?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:b?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[I&&E?t.jsx("div",{className:O("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&&Y&&(g?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:g?{left:`${E.left+Oe}px`,top:`${E.top}px`,width:`${E.width}px`,height:`${E.height}px`}:{transform:`translate3d(${E.left+Oe}px, ${E.top}px, 0)`,width:`${E.width}px`,height:`${E.height}px`}}):null,P&&E?t.jsx("div",{className:O("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",Y&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${E.left+Oe}px, 0, 0)`,width:`${E.width}px`},"aria-hidden":!0}):null,e.map(q=>{const V=q.id===s,ge=u&&I&&!V&&!!q.icon,J=!ge,we=!!q.icon,xe=u&&I&&V&&!b&&!H,Ie=q.closable!==!1&&!!r,ft=Ie&&!!q.icon,mt=b||H?void 0:I?xe?"flex-none basis-auto":h?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",Ze=Ie?Re=>{Re.button===1&&(Re.preventDefault(),Re.stopPropagation(),r?.(q.id))}:void 0,Pe=Ie?Re=>{Re.button===1&&Re.preventDefault()}:void 0;return t.jsx($,{id:q.id,className:mt,children:t.jsxs("div",{ref:Re=>He(q.id,Re),onAuxClick:Ze,onMouseDown:Pe,className:O("group flex h-full min-w-0 flex-nowrap items-center",b||H?"shrink-0":I?"w-full":"w-full min-w-0",I?"relative z-10 bg-transparent":V?"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":V,"aria-label":ge?q.title??q.label:void 0,onClick:()=>n(q.id),onPointerDown:D?()=>{oe(!0),Te(q.id)}:void 0,onPointerUp:D?()=>Te(null):void 0,onPointerLeave:D?()=>Te(null):void 0,onPointerCancel:D?()=>Te(null):void 0,className:O(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&&p?"lowercase":null,I&&(ge?"gap-0":"gap-1.5"),I?H?"shrink-0 whitespace-nowrap px-3 text-center":b?"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":b?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",I?d??(A?h?"h-[38px]":"h-[31px]":"h-7"):null,I?V?"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:q.title??q.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:O("flex items-center justify-center transition-opacity",ft&&(j?"opacity-0":"group-hover:opacity-0")),children:q.icon}),ft?t.jsx("span",{role:"button",tabIndex:-1,className:O("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Re=>{Re.stopPropagation()},onClick:Re=>{Re.stopPropagation(),r?.(q.id)},"aria-label":q.closeLabel??`Close ${q.label} tab`,title:q.closeLabel??`Close ${q.label} tab`,children:t.jsx(N,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,J?t.jsx("span",{className:"animated-tabs__label truncate",children:q.label}):null]}):t.jsxs("span",{className:O("flex min-w-0 flex-nowrap items-center gap-1.5",!b&&"justify-center"),children:[we?t.jsxs("span",{className:O("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",V?"text-[var(--primary-base)]":"text-muted-foreground"),children:[t.jsx("span",{className:O("flex items-center justify-center transition-opacity",ft&&(j?"opacity-0":"group-hover:opacity-0")),children:q.icon}),ft?t.jsx("span",{role:"button",tabIndex:-1,className:O("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",j?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Re=>{Re.stopPropagation()},onClick:Re=>{Re.stopPropagation(),r?.(q.id)},"aria-label":q.closeLabel??`Close ${q.label} tab`,title:q.closeLabel??`Close ${q.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:q.label})]})}),Ie&&!ft?t.jsx("button",{type:"button",onPointerDown:Re=>{Re.stopPropagation()},onClick:Re=>{Re.stopPropagation(),r?.(q.id)},className:O("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?V?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":V?"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":q.closeLabel??`Close ${q.label} tab`,title:q.closeLabel??`Close ${q.label} tab`,children:t.jsx(N,{name:"close",className:"h-3 w-3"})}):null]})},q.id)})]})]});return ie?t.jsxs(Zn,{sensors:se,collisionDetection:er,onDragEnd:tt,modifiers:[Ym],children:[t.jsx(lo,{items:v,strategy:Qu,children:ze}),t.jsx(Aa,{dropAnimation:null})]}):ze},Jm="\x1B",Xm=new RegExp(`${Jm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Zm=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,eg=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,tg=/Serving HTTP on .*? port (\d{2,5})/i,sg=new Set([".",",",";",":","!","?"]),ng=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(sg.has(n)){s=s.slice(0,-1);continue}break}return s},Gi=e=>{let s=ng(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},rg=e=>{if(!e)return null;const s=e.replace(Xm,""),n=s.match(tg);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(!eg.test(i))continue;const a=Array.from(i.matchAll(Zm));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Gi(c[1])).port}catch{return!1}});return Gi((l??a[0])[1])}return null},og=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 Xt("/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)}},ig={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ag=(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 ig[e]},al=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},lg=(e,s)=>e&&(s==="ctrl"?al(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Ki={cols:80,rows:24},Tx=({visible:e})=>{const{terminal:s,runtime:n}=Vn(),{currentTheme:r}=ua(),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}=Md(),l=ue(F=>F.terminalFontSize),c=ue(F=>F.terminalShell),d=ue(F=>F.terminalLoginShells.includes(F.terminalShell)),{isMobile:u,isTablet:f,hasTouchOnlyPointer:p}=Rs(),g=u||f,m=(g||p)&&n.platform==="web",h=!0,x=ue(F=>F.showTerminalQuickKeysOnDesktop),j=g||x,k=_e(F=>F.currentSessionId),B=_e(F=>F.newSessionDraft),S=k!==null||B?.open===!0,v=Fd()??null,b=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),H=Ee(F=>F.setTabLifecycle),ee=Ee(F=>F.setConnecting),Z=Ee(F=>F.appendToBuffer),ie=Ee(F=>F.replaceBuffer),$=Ee(F=>F.setTabPreviewUrl),K=ra(F=>F.addDraft),E=ue(F=>F.openContextPreview),R=o.useMemo(()=>b?b.activeTabId??b.tabs[0]?.id??null:null,[b,h]),Y=o.useMemo(()=>{if(b)return R?b.tabs.find(F=>F.id===R)??b.tabs[0]:b.tabs[0]},[b,R]),oe=o.useMemo(()=>(b?.tabs??[]).map(F=>({icon:(()=>{const ae=F.iconKey?cn[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"})),[b?.tabs]),U=Y?.terminalSessionId??null,Te=Y?.lifecycle??"idle",Le=Ee(F=>v&&R?F.getBuffer(v,R).chunks:$n.chunks),Ve=Y?.isConnecting??!1,Ge=Y?.previewUrl??null,[Ke,Oe]=o.useState(null),[se,fe]=o.useState(!1),[He,ke]=o.useState(!1),[Ce,We]=o.useState(null),[tt,ze]=o.useState(!1),q=o.useRef(null),V=o.useRef(null),ge=o.useRef(R),J=o.useRef(U),we=o.useRef(v),xe=o.useRef(null),Ie=o.useRef(null),ft=o.useRef(new Set),mt=o.useRef(""),Ze=o.useRef(new Set),Pe=o.useRef(0),Re=o.useCallback(()=>{mt.current="",Ze.current.clear(),Pe.current+=1},[]),Ne=o.useCallback(()=>{m||typeof document<"u"&&!document.hasFocus()||xe.current?.focus()},[m]),at=o.useCallback(()=>{m||xe.current?.focus()},[m]),st=ue(F=>F.activeMainTab)==="terminal",_=e??st,[ye,be]=o.useState(_);o.useEffect(()=>{_&&be(!0)},[_]),o.useEffect(()=>{J.current=U},[U]),o.useEffect(()=>{!U||!s.updateAppearance||s.updateAppearance(U,i.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,U]),o.useEffect(()=>{ge.current=R,Re()},[R,Re]),o.useEffect(()=>{we.current=v},[v]),o.useEffect(()=>{!j&&Ce!==null&&We(null)},[j,Ce,We]),o.useEffect(()=>{!U&&Ce!==null&&We(null)},[U,Ce,We]);const w=o.useCallback(()=>{q.current?.(),q.current=null,V.current=null,ke(!1)},[]);o.useEffect(()=>()=>{w(),J.current=null},[w]);const W=o.useCallback((F,ae,he)=>{if(!he)return;const nt=`${mt.current}${he}`.replace(/\r\n|\r/g,`
50
- `),ve=nt.split(`
51
- `),Je=nt.endsWith(`
52
- `)?ve.join(`
53
- `):ve.slice(0,-1).join(`
54
- `);if(mt.current=nt.endsWith(`
55
- `)?"":(ve[ve.length-1]??"").slice(-1024),!Je)return;const bt=rg(Je);if(!bt||Ze.current.has(bt))return;const Nt=Pe.current;Ze.current.add(bt),og(bt).then(Mt=>{if(Ze.current.delete(bt),!Mt||Pe.current!==Nt)return;const Et=Ee.getState().getDirectoryState(F)?.tabs.find($t=>$t.id===ae);!Et||Et.previewUrlLocked||Et.previewUrl===bt||$(F,ae,bt,{locked:!1,autoOpened:!1})})},[$]),ne=o.useCallback((F,ae,he)=>{if(V.current===he)return;w(),V.current=he;const nt=s.connect(he,{onEvent:ve=>{if(V.current===he)switch(ve.type){case"snapshot":{ee(F,ae,!1),Oe(null),fe(!1),ke(!1),Ne(),ie(F,ae,ve.data??"",ve.sequence??0),W(F,ae,ve.data??""),ve.status==="exited"&&H(F,ae,"exited");break}case"reconnecting":{Oe(null),fe(!1),ke(!0);break}case"data":{ve.data&&(Z(F,ae,ve.data,ve.sequence,ve.replayData),W(F,ae,ve.data));break}case"exit":{const Je=typeof ve.exitCode=="number"?ve.exitCode:null,bt=typeof ve.signal=="number"?ve.signal:null,Mt=!!Ee.getState().getDirectoryState(F)?.tabs.find(Et=>Et.id===ae)?.label?.startsWith("Action:");Z(F,ae,`\\r\\n[Process exited${Je!==null?` with code ${Je}`:""}${bt!==null?` (signal ${bt})`:""}]\\r\\n`),H(F,ae,"exited"),ee(F,ae,!1),Oe(Mt?null:"Terminal session ended"),fe(!1),ke(!1),w();break}}},onError:(ve,Je)=>{if(V.current===he){if(!Je){Oe(null),fe(!1);return}if(ke(!1),ve.code==="SESSION_NOT_FOUND"&&!Ee.getState().getDirectoryState(F)?.tabs.find(Nt=>Nt.id===ae)?.label?.startsWith("Action:")){Oe(null),fe(!1),ee(F,ae,!1),D(F,ae,null),H(F,ae,"idle"),w();return}Oe(`Connection failed: ${ve.message}`),fe(!0),ee(F,ae,!1),H(F,ae,"exited"),D(F,ae,null),w()}}});q.current=()=>{nt.close(),V.current=null}},[Z,ie,w,Ne,W,ee,H,D,s]);o.useEffect(()=>{let F=!1;if(!L||!ye)return;if(!v){Oe(S?"No working directory available for terminal.":"Select a session to open the terminal."),w();return}return(async()=>{const he=v;if(!we.current||we.current!==he)return;if(!Ee.getState().getDirectoryState(he)){A(he);return}const ve=Ee.getState().getDirectoryState(he);if(!ve||ve.tabs.length===0)return;const Je=ve.activeTabId??ve.tabs[0]?.id??null;if(!Je)return;const bt=ve.tabs.find(wt=>wt.id===Je)??ve.tabs[0],Nt=bt?.terminalSessionId??null,Mt=bt?.lifecycle??"idle",Et=!!bt?.label?.startsWith("Action:"),$t=Ee.getState().getBuffer(he,Je),Ft=$t.byteLength>0||$t.chunks.length>0;if(!Nt){if(Mt==="exited"){ee(he,Je,!1);return}if(Et&&Ft){ee(he,Je,!1);return}const wt=`${he}\0${Je}`;if(ft.current.has(wt))return;const qt=Ie.current??Ki;ft.current.add(wt),Oe(null),fe(!1),ke(!1),ee(he,Je,!0);try{const G=await s.createSession({cwd:he,sessionId:Je,cols:qt.cols,rows:qt.rows,shell:c,loginShell:d,...i.current}),te=!F&&we.current===he&&ge.current===Je;if(!Ee.getState().getDirectoryState(he)?.tabs.find(pe=>pe.id===Je)){try{await s.close(G.sessionId)}catch{}return}if(D(he,Je,G.sessionId),!te)return;const ce=Ie.current;ce&&(ce.cols!==qt.cols||ce.rows!==qt.rows)&&s.resize({sessionId:G.sessionId,...ce}).catch(()=>{});return}catch(G){const te=Ee.getState().getDirectoryState(he)?.tabs.find(re=>re.id===Je);if(!te||te.terminalSessionId||(ee(he,Je,!1),we.current!==he||ge.current!==Je))return;Oe(G instanceof Error?G.message:"Failed to start terminal session"),fe(!0),ke(!1);return}finally{ft.current.delete(wt)}}!Nt||F||(J.current=Nt,ne(he,Je,Nt))})(),()=>{F=!0,J.current=null,w()}},[S,v,U,Te,R,ye,h,L,A,ee,H,D,ne,w,s,d,c]),o.useEffect(()=>{if(!_||m)return;if(typeof window>"u"){Ne();return}const F=window.requestAnimationFrame(()=>{Ne()});return()=>{window.cancelAnimationFrame(F)}},[R,Ne,_,m]);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 he=F?.tabs.find(nt=>nt.id===ae)?.terminalSessionId??null;if(!(!he||!s.restartSession)){ze(!0),Oe(null),fe(!1),ke(!1),w(),Re();try{const nt=Ie.current??Ki,ve=await s.restartSession(he,{cwd:v,shell:c,loginShell:d,...nt,...i.current});if(Ee.getState().getDirectoryState(v)?.tabs.find(bt=>bt.id===ae)?.terminalSessionId!==he||(D(v,ae,ve.sessionId),H(v,ae,"running"),we.current!==v||ge.current!==ae))return;J.current=ve.sessionId,ne(v,ae,ve.sessionId)}catch(nt){if(Ee.getState().getDirectoryState(v)?.tabs.find(Je=>Je.id===ae)?.terminalSessionId!==he||we.current!==v||ge.current!==ae)return;Oe(nt instanceof Error?nt.message:"Failed to restart terminal"),fe(!1),ke(!1),J.current=he,ne(v,ae,he)}finally{ze(!1)}}},[R,w,v,h,tt,Re,H,D,ne,s,d,c]),Se=o.useCallback(async()=>{await de()},[de]),De=o.useCallback(()=>{if(!v)return;const F=C(v);I(v,F),Oe(null),fe(!1),ke(!1),w()},[C,w,v,I]),$e=o.useCallback(()=>{const F=xe.current?.getSelection(),ae=k??(B?.open?"draft":null);!F||!ae||!Y||!v||K({directory:v,sessionKey:ae},{source:"terminal",fileLabel:Y.label,startLine:F.startLine,endLine:F.endLine,code:F.text,language:Y.terminalSessionId??Y.id,text:""})},[Y,K,k,v,B?.open]),ht=o.useCallback(F=>{v&&(I(v,F),Oe(null),fe(!1),ke(!1),w())},[w,v,I]),kt=o.useCallback(F=>{if(!v)return;F===R&&w(),Oe(null),fe(!1),ke(!1);const ae=Ee.getState().getDirectoryState(v)?.tabs.find(he=>he.id===F)?.terminalSessionId;(async()=>{ae&&await s.close(ae),P(v,F)})().catch(he=>Oe(he instanceof Error?he.message:"Terminal session ended"))},[R,P,w,v,s]),et=o.useCallback(F=>{if(!F||He)return;let ae=F,he=!1;Ce&&F.length>0&&(ae=lg(F,Ce),he=!0);const nt=J.current;nt&&(s.sendInput(nt,ae).catch(ve=>{He||Oe(ve instanceof Error?ve.message:"Failed to send input")}),he&&(We(null),at()))},[Ce,at,He,We,s]),pt=o.useCallback((F,ae)=>{const he=Ie.current;if((!he||he.cols!==F||he.rows!==ae)&&(Ie.current={cols:F,rows:ae}),!_)return;const nt=J.current;nt&&s.resize({sessionId:nt,cols:F,rows:ae}).catch(()=>{})},[_,s]),gt=o.useCallback(F=>{We(ae=>ae===F?null:F),at()},[at,We]),Me=o.useCallback(F=>{const ae=ag(F,Ce);ae&&(et(ae),We(null),at())},[Ce,at,et,We]),Ye=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),xt=o.useCallback(F=>{if(F.repeat)return;const ae=F.key;if(!ae||ae==="Control"||ae==="Meta"||ae==="Alt"||ae==="Shift")return;const he=ae.length===1?ae.toLowerCase():ae;if(he in Ye){F.preventDefault(),F.stopPropagation(),Me(Ye[he]);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=al(ve);if(!Je)return;F.preventDefault(),F.stopPropagation(),et(Je),We(null),at()}},[Ce,at,Me,et,Ye,We]);o.useEffect(()=>{if(!(!j||!Ce||!U))return window.addEventListener("keydown",xt),()=>window.removeEventListener("keydown",xt)},[Ce,xt,j,U]);const Lt=o.useMemo(()=>{const F=Zs[ar].stack;if(typeof window>"u")return(Zs[a]??Zs[ar]).stack;const he=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return he&&he.trim().length>0?he.trim():(Zs[a]??Zs[ar]).stack??F},[a]),zt=o.useMemo(()=>Fm(r),[r]),At=`${v??"no-dir"}::${R??"no-tab"}`;if(o.useEffect(()=>{if(!_||m)return;const F=xe.current;if(!F)return;const ae=()=>{F.fit()};if(typeof window<"u"){const he=window.requestAnimationFrame(()=>{ae(),Ne()}),nt=[220,400].map(ve=>window.setTimeout(ae,ve));return()=>{window.cancelAnimationFrame(he),nt.forEach(ve=>window.clearTimeout(ve))}}ae()},[Ne,_,m,At,U]),o.useEffect(()=>{if(!_||!m)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)}},[_,At,m]),!S)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 It=!U||Ve||tt||He,Dt=ye,M=g?"lg":"xs",je=g?"w-10 p-0":"w-9 p-0",Be=F=>{g&&F.preventDefault()},ct=t.jsxs(t.Fragment,{children:[t.jsx(qe,{type:"button",size:M,variant:"outline",onPointerDown:Be,onClick:()=>Me("esc"),disabled:It,children:"Esc"}),t.jsxs(qe,{type:"button",size:M,variant:"outline",className:je,onPointerDown:Be,onClick:()=>Me("tab"),disabled:It,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:g?"px-3":"px-2",onPointerDown:Be,onClick:()=>gt("ctrl"),disabled:It,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:g?"px-3":"px-2",onPointerDown:Be,onClick:()=>gt("alt"),disabled:It,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:()=>Me("arrow-up"),disabled:It,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:()=>Me("arrow-left"),disabled:It,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:()=>Me("arrow-down"),disabled:It,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:()=>Me("arrow-right"),disabled:It,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:()=>Me("enter"),disabled:It,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:O("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",g?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[b?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:O("min-w-0 flex-1",g?"h-8":"h-7"),children:t.jsx(qm,{items:oe,activeId:R,onSelect:ht,onClose:kt,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(qe,{type:"button",size:"xs",variant:"ghost",className:O("shrink-0",g?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:De,title:"New tab",children:t.jsx(N,{name:"add",className:`${g?"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"})}),Ge?t.jsxs(qe,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{v&&E(v,Ge)},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,!g&&j&&h&&b?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:ct}):null,!g&&j&&!b?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:ct}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:zt.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Dt?t.jsx(il,{ref:F=>{xe.current=F},sessionKey:At,chunks:Le,onInput:et,onResize:pt,theme:zt,fontFamily:Lt,fontSize:l,enableTouchScroll:m,autoFocus:_,isVisible:_},At):null}),!He&&Ke&&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:Ke}),se&&g&&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"})]})]}),g&&j?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:ct})}):null]})},cg=ps(()=>({statusById:new Map})),Rx=()=>{xa(),fa()},Mx=e=>{_e.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ue.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),xa(),Ee.getState().clearAll(),Es.getState().resetForRuntimeSwitch(),Ot.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),_t.getState().resetForRuntimeSwitch(),Ld.getState().resetForRuntimeSwitch(),cg.setState({statusById:new Map}),Od(),Bd(),qu.getState().reset(),mu.getState().resetForRuntimeSwitch(),na.getState().resetForRuntimeSwitch(e.runtimeKey),da.getState().resetForRuntimeSwitch(e.runtimeKey),hp.getState().resetForRuntimeSwitch(),Gt.getState().resetForRuntimeSwitch(e.runtimeKey),gu.getState().resetForRuntimeSwitch(e.runtimeKey),_e.getState().restoreForRuntimeSwitch(e.runtimeKey),ue.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=ue.getState();$r({sessionId:_e.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),fa()},dg=48,ug=96,Wt=(e,...s)=>{try{e?.(...s)}catch{}},Sr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Fx=(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"?ug:dg;let d=!1,u=!1,f=!1,p=null,g=!1,m=0,h=0,x=0,j=0;const k=()=>{d=!1,u=!1,f=!1,p=null},B=()=>{const I=n.current,P=p,D=g;u&&P&&(Wt(P==="left"?I.onLeftProgress:I.onRightProgress,D?1:0),Wt(I.onDragEnd,P,D)),k()},S=()=>{B(),u||k()},v=I=>{const P=n.current;if(P.enabled===!1){u&&p?B():k();return}if(I.touches.length!==1){u&&p?B():k();return}const D=I.touches[0],H=i.getBoundingClientRect(),ee=i.clientWidth,Z=!!P.leftOpen,ie=!!P.rightOpen,$=K=>ym(K,i);if(Z||ie){if($(I.target)){k();return}if(Z&&ie){const K=D.clientX<=H.left+c;D.clientX>=H.right-c?(p="right",g=!0):K?(p="left",g=!0):(p=Z?"left":"right",g=!0)}else Z?(p="left",g=!0):(p="right",g=!0);j=Sr(p==="left"?P.leftWidth:P.rightWidth,ee),j<10&&(j=ee||window.innerWidth||320),j<10&&(j=320),d=!0}else{if($(I.target)){k();return}p=null,g=!1,j=0,d=!0}m=D.clientX,h=D.clientY,x=Date.now(),u=!1,f=!1},b=I=>{if(!d)return;if(I.touches.length!==1){S();return}const P=I.touches[0],D=P.clientX-m,H=P.clientY-h;if(!f){if(Math.abs(D)<Mi&&Math.abs(H)<Mi)return;if(Math.abs(H)>Math.abs(D)*tn){k();return}if(!p){const ie=n.current;p=D>0?"left":"right",j=Sr(p==="left"?ie.leftWidth:ie.rightWidth,i.clientWidth),j<10&&(j=window.innerWidth||320)}if(p==="left"){if(!g&&D<=0){k();return}if(g&&D>=0){k();return}}else{if(!g&&D>=0){k();return}if(g&&D<=0){k();return}}f=!0,u=!0,Wt(n.current.onDragStart,p)}if(!u)return;I.cancelable&&I.preventDefault();const ee=n.current,Z=Fi(p,g,D,j);Wt(p==="left"?ee.onLeftProgress:ee.onRightProgress,Z)},L=(I,P)=>{if(!d){k();return}const D=I-m,H=P-h;if(!p&&!g&&Math.abs(D)>=_n&&Math.abs(H)<=Math.abs(D)*tn){const E=n.current;p=D>0?"left":"right",j=Sr(p==="left"?E.leftWidth:E.rightWidth,i.clientWidth),j<10&&(j=window.innerWidth||320)}if(!p){k();return}const ee=Math.max(1,Date.now()-x),Z=n.current;if(!u){const E=Math.abs(D),R=Math.abs(H);E>=_n&&R<=E*tn?p==="left"&&!g&&D>0?(Wt(Z.onLeftProgress,1),Wt(Z.onLeftOpen)):p==="right"&&!g&&D<0?(Wt(Z.onRightProgress,1),Wt(Z.onRightOpen)):Wt(p==="left"?Z.onLeftProgress:Z.onRightProgress,g?1:0):Wt(p==="left"?Z.onLeftProgress:Z.onRightProgress,g?1:0);const Y=p;k(),Wt(Z.onDragEnd,Y);return}const ie=Fi(p,g,D,j),$=xm({side:p,isOpenAtStart:g,dx:D,dt:ee,progress:ie}),K=p;Wt(K==="left"?$?Z.onLeftOpen:Z.onLeftClose:$?Z.onRightOpen:Z.onRightClose),k(),Wt(Z.onDragEnd,K,$)},A=I=>{const P=I.changedTouches[0];if(!P){k();return}const D=P.clientX-m,H=P.clientY-h;d&&(u||Math.abs(D)>=_n&&Math.abs(H)<=Math.abs(D)*tn)&&I.cancelable&&I.preventDefault(),L(P.clientX,P.clientY)},C=()=>{S()};return i.addEventListener("touchstart",v,{passive:!0}),i.addEventListener("touchmove",b,{passive:!1}),i.addEventListener("touchend",A,{passive:!1}),i.addEventListener("touchcancel",C,{passive:!0}),()=>{try{u&&p&&B()}catch{}i.style.touchAction=a,i.removeEventListener("touchstart",v),i.removeEventListener("touchmove",b),i.removeEventListener("touchend",A),i.removeEventListener("touchcancel",C)}},[e,r])};function Lx({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 Hi({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 jr=()=>As.filter(e=>Fr.has(e.id)).map(e=>({...ba(e)})),fg=()=>{if(typeof window>"u")return Lr;const e=window.localStorage.getItem("openInAppId");return e&&Mr(e)?e:Lr};let Cr=!1,zs=!1,xs=!1,bs=0,dn=null;const Wi=()=>{dn&&(clearTimeout(dn),dn=null)},Cs=ps()((e,s)=>({selectedAppId:fg(),availableApps:jr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Cr||typeof window>"u")return;Cr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:jr(),hasLoadedApps:u});return}const f=new Set(d.map(h=>h.name)),p=new Map(d.map(h=>[h.name,h.iconDataUrl??void 0])),m=As.filter(h=>f.has(h.appName)||Fr.has(h.id)).map(h=>({...ba(h),iconDataUrl:p.get(h.appName)}));e({availableApps:m,hasLoadedApps:!0})},r=async d=>{if(!ys()||!fn()||zs||s().hasLoadedApps&&!d)return;const f=As.map(p=>p.appName);Wi(),zs=!0,xs=!1,e({isScanning:!0});try{const{apps:p,success:g,hasCache:m,isCacheStale:h}=await ei(f,d),x=g&&!m&&p.length===0&&bs<3;if(e({isCacheStale:m?h:!1}),n(p,g?!x:!1),g){if(x){const k=[800,1600,3200][bs]??3200;bs+=1,xs=!0,dn=setTimeout(()=>{r()},k);return}bs=0,xs=!1;return}if(bs<3){const k=[1e3,3e3,7e3][bs]??7e3;bs+=1,xs=!0,dn=setTimeout(()=>{r()},k)}}finally{zs=!1,xs||e({isScanning:!1})}};r();const i=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Mr(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(bs=3,xs=!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(Cr||s().initialize(),!ys()||!fn()||zs||s().hasLoadedApps&&!n)return;const i=As.map(a=>a.appName);Wi(),n&&e({hasLoadedApps:!1}),zs=!0,xs=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await ei(i,n),d=new Set(a.map(g=>g.name)),u=new Map(a.map(g=>[g.name,g.iconDataUrl??void 0])),p=As.filter(g=>d.has(g.appName)||Fr.has(g.id)).map(g=>({...g,iconDataUrl:u.get(g.appName)}));e({availableApps:p.length>0?p:jr(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{zs=!1,xs||e({isScanning:!1})}},selectApp:async n=>{Mr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await to({openInAppId:n}))}})),hg="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",pg="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",kr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?hg:e.id==="terminal"?pg:void 0}),Yi=({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:O("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},mg=({directory:e,className:s})=>{const n=Cs(h=>h.selectedAppId),r=Cs(h=>h.availableApps),i=Cs(h=>h.isCacheStale),a=Cs(h=>h.isScanning),l=Cs(h=>h.initialize),c=Cs(h=>h.loadInstalledApps),d=Cs(h=>h.selectApp);o.useEffect(()=>{l()},[l]);const u=ys()&&fn(),f=o.useMemo(()=>{const h=r.find(x=>x.id===n)??r.find(x=>x.id===Lr)??r[0]??As[0];return kr(h||As[0])},[r,n]);if(!u||!e||r.length===0)return null;const p=async h=>{await xu(e,h.id,h.appName)||await ma(e,h.appName)},g=async h=>{await d(h.id),await p(h)},m=async()=>{(await un(e)).ok&&le.success("Path copied to clipboard")};return t.jsxs("div",{className:O("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:()=>{p(f)},className:O("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 ${f.label}`,children:t.jsx(Yi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O("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(Qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(jt,{className:"flex items-center gap-2",onClick:()=>{m()},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(h=>{const x=kr(h);return t.jsxs(jt,{className:"flex items-center gap-2",onClick:()=>{g(h)},children:[t.jsx(Yi,{label:h.label,iconDataUrl:h.iconDataUrl,fallbackIconDataUrl:x.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:h.label}),f.id===h.id?t.jsx(N,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},h.id)}),i?t.jsxs(jt,{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]})]})]})},gg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],xg=["dev","start","preview","serve"];async function bg(e,s,n){if(!e)return null;const r=wg(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=Sg(n);if(i){const a=await jg(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 yg(e)){const i=await vg(),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 yg(e){const s=`${e}/index.html`,n=await Yn(s,e);return typeof n=="string"&&n.trim().length>0}async function vg(){try{const e=await Xt("/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 wg(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(xg.some(i=>n.includes(i)))return s}return null}function Sg(e){for(const{pattern:s}of gg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function jg(e){const s=await Yn(`${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 Yn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function Yn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),i=await Xt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=so()?.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 Xt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Cg(e){try{const s=await Yn(`${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 kg=(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)}),Ng="\x1B",Ag=new RegExp(`${Ng}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ig=/https?:\/\/[^\s<>'"`]+/gi,Jt="__pichamber_auto_discover_preview__",Dg=15e3,Pg=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},Eg=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}},Tg=e=>{const n=e.replace(Ag,"").match(Ig);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",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,g=f==="/"||f==="",m=!!(c.search||c.hash);let h=0;return u&&(h+=50),g&&(h+=30),h-=Math.min(p*5,20),m&&(h-=10),h};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},Vi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=ua(),{terminal:l}=Vn(),{isMobile:c}=Rs(),d=o.useMemo(()=>ys(),[]),u=Un(_=>_.instances),f=Un(_=>_.load),p=ue(_=>_.terminalShell),g=ue(_=>_.terminalLoginShells.includes(_.terminalShell)),m=ue(_=>_.setSettingsPage),h=ue(_=>_.setSettingsDialogOpen),x=ue(_=>_.setSettingsProjectsSelectedId),j=ue(_=>_.openContextPreview),k=Ee(_=>_.ensureDirectory),B=Ee(_=>_.setTabLabel),S=Ee(_=>_.setTabIconKey),v=Ee(_=>_.setActiveTab),b=Ee(_=>_.setConnecting),L=Ee(_=>_.setTabSessionId),A=Ee(_=>_.setTabPreviewUrl),C=Ee(_=>_.projectActionRuns),I=Ee(_=>_.setProjectActionRun),P=Ee(_=>_.updateProjectActionRunStatus),D=Ee(_=>_.removeProjectActionRun),[H,ee]=o.useState([]),[Z,ie]=o.useState(null),[$,K]=o.useState(!1),E=o.useRef({}),R=o.useRef({}),Y=o.useRef({}),oe=o.useRef({}),U=o.useRef(new Set),Te=o.useRef(0),Le=e?.id??null,Ve=e?.path??"",Ge=o.useMemo(()=>Le?{id:Le,path:Ve}:null,[Le,Ve]);o.useEffect(()=>{d&&f().catch(()=>{})},[d,f]);const Ke=o.useCallback(async _=>{await qi(_)},[]),Oe=o.useCallback(async()=>{if(!Ge)return;const _=Te.current+1;Te.current=_,K(!0);try{const ye=await Nr(Ge);if(Te.current!==_)return;const be=ye.actions;ee(be),ie(w=>w===Jt||w&&be.some(W=>W.id===w)?w:null)}catch{if(Te.current!==_)return}finally{Te.current===_&&K(!1)}},[Ge]),se=o.useMemo(()=>Oa(s||Ge?.path||""),[s,Ge?.path]),fe=o.useMemo(()=>Z?H.find(_=>_.id===Z)??null:null,[H,Z]),He=o.useMemo(()=>({id:Jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),ke=!c,Ce=o.useMemo(()=>ke?[He,...H]:H,[H,He,ke]);o.useEffect(()=>{Oe()},[Oe]),o.useEffect(()=>{if(typeof window>"u")return;const _=ye=>{const be=ye.detail;Le&&(be?.projectId&&be.projectId!==Le||Oe())};return window.addEventListener(Kr,_),()=>{window.removeEventListener(Kr,_)}},[Oe,Le]),o.useEffect(()=>{Z&&(Z===Jt&&ke||H.some(_=>_.id===Z)||ie(null))},[H,ke,Z]),o.useEffect(()=>{const _=()=>{const ye=Ee.getState(),be=ye.sessions,w=ye.projectActionRuns;for(const[W,ne]of Object.entries(w)){const Se=be.get(ne.directory)?.tabs.find(Ye=>Ye.id===ne.tabId);if(!Se||Se.terminalSessionId!==ne.sessionId){D(W);continue}const De=R.current[W]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};R.current[W]=De;const $e=Ce.find(Ye=>Ye.id===ne.actionId),ht=ye.getBuffer(ne.directory,ne.tabId).chunks;if(!$e||ht.length===0)continue;const kt=ht.filter(Ye=>De.lastSeenChunkId===null||Ye.id>De.lastSeenChunkId);if(kt.length===0)continue;const et=kt.map(Ye=>Ye.data).join(""),pt=`${De.tail}${et}`,gt=!De.openedUrl&&$e.autoOpenUrl===!0?Tg(pt):null,Me=kt[kt.length-1]?.id??De.lastSeenChunkId;if(De.lastSeenChunkId=Me,De.tail=pt.slice(-512),gt)if(De.openedUrl=!0,De.openInPreview){const Ye=w[W];Ye&&(A(Ye.directory,Ye.tabId,gt,{locked:!1,autoOpened:!1}),Ye.status==="waiting-for-preview"&&P(W,"running"),window.clearTimeout(oe.current[W]),delete oe.current[W],j(Ye.directory,gt))}else Ke(gt),le.success("Opened URL from action output");R.current[W]=De}for(const W of Object.keys(R.current))w[W]||(delete R.current[W],window.clearTimeout(oe.current[W]),delete oe.current[W])};return _(),Ee.subscribe((ye,be)=>{(ye.sessions!==be.sessions||ye.buffers!==be.buffers)&&_()})},[Ce,j,Ke,C,D,A,P]);const We=o.useCallback(async(_,ye={})=>{if(!se)throw new Error("No active directory");const be=us(se,_.id);k(se);const w=Ee.getState(),W=w.getDirectoryState(se);let ne=E.current[be]||null;const de=ne?!!W?.tabs.some($e=>$e.id===ne):!1;(!ne||!de)&&(ne=w.createTab(se),E.current[be]=ne),B(se,ne,`Action: ${_.name}`),S(se,ne,_.icon||"play"),v(se,ne),ye.revealTerminal!==!1&&ue.getState().openContextPanelTab(se,{mode:"terminal"});const De=Ee.getState().getDirectoryState(se)?.tabs.find($e=>$e.id===ne);return{key:be,tabId:ne,sessionId:De?.terminalSessionId??null}},[k,se,v,S,B]),tt=o.useCallback(async _=>{if(!i&&c)return;if(!se){le.error("No active directory for action");return}const ye=us(se,_.id),be=C[ye];if(!(be&&be.status==="running")&&!U.current.has(ye)){U.current.add(ye);try{const w=_.id===Jt?await(async()=>{const[Me,Ye]=await Promise.all([Nr({id:Ge?.id??"",path:se}),Cg(se)]),xt=await bg(se,Me.actions,Ye);if(!xt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Jt,name:"Auto-discover",command:xt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:xt.previewUrlHint||""}})():_,W=w.autoOpenUrl===!0&&(w.openUrl||"").trim().length>0,ne=!W&&_.id!==Jt,{key:de,tabId:Se,sessionId:De}=await We(w,{revealTerminal:ne});let $e=De;if(!$e){b(se,Se,!0);try{$e=(await l.createSession({cwd:se,sessionId:Se,shell:p,loginShell:g,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,L(se,Se,$e)}finally{b(se,Se,!1)}}if(!$e)throw new Error("Failed to create terminal session");Y.current[de]?.(),b(se,Se,!0);const ht=l.connect($e,{onEvent:Me=>{Me.type==="snapshot"&&(Ee.getState().replaceBuffer(se,Se,Me.data??"",Me.sequence??0),Ee.getState().setConnecting(se,Se,!1)),Me.type==="data"&&typeof Me.data=="string"&&Me.data.length>0&&Ee.getState().appendToBuffer(se,Se,Me.data,Me.sequence,Me.replayData),Me.type==="exit"&&(Ee.getState().setTabLifecycle(se,Se,"exited"),Ee.getState().setConnecting(se,Se,!1),Ee.getState().removeProjectActionRun(de),delete R.current[de],Y.current[de]?.(),delete Y.current[de],window.clearTimeout(oe.current[de]),delete oe.current[de])},onError:(Me,Ye)=>{Ee.getState().setConnecting(se,Se,!1),Ye&&(Ee.getState().setTabLifecycle(se,Se,"exited"),Ee.getState().setTabSessionId(se,Se,null),Ee.getState().removeProjectActionRun(de))}});Y.current[de]=ht.close;const kt=w.autoOpenUrl===!0&&d&&(w.desktopOpenSshForward||"").trim().length>0,et=w.autoOpenUrl?Eg(w.openUrl):null,pt=w.autoOpenUrl&&d?Rf(w.desktopOpenSshForward,u):null;I({key:de,directory:se,actionId:w.id,tabId:Se,sessionId:$e,status:w.id===Jt&&!et?"waiting-for-preview":"running"}),window.clearTimeout(oe.current[de]),delete oe.current[de],w.id===Jt&&!et&&(oe.current[de]=window.setTimeout(()=>{const Me=Ee.getState(),Ye=Me.projectActionRuns[de];Me.updateProjectActionRunStatus(de,"running"),Ye&&(Me.setActiveTab(Ye.directory,Ye.tabId),ue.getState().openContextPanelTab(Ye.directory,{mode:"terminal"})),delete oe.current[de]},Dg)),R.current[de]={lastSeenChunkId:null,openedUrl:!!pt||!!et||W,tail:"",openInPreview:w.id===Jt};const gt=Pg(w.command.trim().replace(/\r\n|\r/g,`
56
- `));await l.sendInput($e,`${gt}\r`),pt?(A(se,Se,null,{locked:!0}),Ke(pt),le.success("Opened forwarded URL")):et?(A(se,Se,et,{locked:!0,autoOpened:!0}),j(se,et),le.success("Opened action URL")):W?(A(se,Se,null,{locked:!0}),le.error("Invalid custom URL format")):kt?(A(se,Se,null,{locked:!0}),le.error("Selected desktop SSH forward is unavailable")):A(se,Se,null,{locked:!1,autoOpened:!1})}catch(w){D(ye),delete R.current[ye],Y.current[ye]?.(),delete Y.current[ye],window.clearTimeout(oe.current[ye]),delete oe.current[ye],le.error(w instanceof Error?w.message:"Failed to run action")}finally{U.current.delete(ye)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,We,i,c,d,se,g,p,Ke,j,C,D,b,I,A,L,Ge?.id,l]),ze=o.useCallback(async _=>{const ye=us(se,_.id),be=C[ye];if(!be)return;P(ye,"stopping");const w=kg(l,be.sessionId,1e3);try{await l.sendInput(be.sessionId,"")}catch{}const W=await w;if(Ee.getState().getDirectoryState(be.directory)?.tabs.find(Se=>Se.id===be.tabId)?.terminalSessionId===be.sessionId&&!W){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],Y.current[ye]?.(),delete Y.current[ye],window.clearTimeout(oe.current[ye]),delete oe.current[ye]},[se,C,D,L,l,P]),q=o.useCallback(()=>{const _=fe??Ce[0];if(!_)return;const ye=us(se,_.id),be=C[ye];if(be?.status!=="stopping"){if(be){ze(_);return}tt(_)}},[Ce,se,tt,C,fe,ze]),V=o.useCallback((_,ye=!1)=>{if(ie(_.id),!ye){tt(_);return}const be=us(se,_.id),w=C[be];if(w?.status!=="stopping"){if(w){ze(_);return}tt(_)}},[se,tt,C,ze]),ge=o.useCallback(()=>{Ge?.id&&(x(Ge.id),m("projects"),h(!0))},[h,m,x,Ge?.id]),J=fe??Ce[0]??null,we=J?C[us(se,J.id)]:null,xe=Ee(_=>we?_.sessions.get(we.directory)?.tabs.find(ye=>ye.id===we.tabId)?.previewUrl??null:null);if(!i&&c||!Ge||!se)return null;const Ie=fe??Ce[0]??null;if(!Ie)return null;const ft=Ie.icon||"play",mt=Ie.id===Jt?"scan-2":cn[ft]||"play",Ze=us(se,Ie.id),Pe=C[Ze],Re=Pe?.status==="stopping",Ne=Pe?.status==="waiting-for-preview",at=!!(Pe&&xe),Ct=()=>{!Pe||!xe||j(Pe.directory,xe)},st=Ie.id===Jt;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:$||Re,className:O("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:q,"aria-label":Pe?`Stop ${Ie.name}`:`Run ${Ie.name}`,children:Re||Ne?t.jsx(N,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):Pe?t.jsx(N,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(N,{name:mt,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:Ct,children:t.jsx(N,{name:"global",className:"h-4 w-4"})})}),t.jsx(it,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Yt,{children:[t.jsx(Vt,{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(Qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(jt,{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===Jt?"scan-2":cn[ye]||"play",w=us(se,_.id),W=C[w],ne=!!W,de=W?.status==="stopping";return t.jsxs(jt,{className:"flex items-center gap-2",onClick:()=>{V(_,!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||W?.status==="waiting-for-preview"?t.jsx(N,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):ne?t.jsx(N,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]}):t.jsxs("div",{className:O("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:q,disabled:$||Re,className:O("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":Pe?`Stop ${Ie.name}`:`Run ${Ie.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:Re||Ne?t.jsx(N,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):Pe?t.jsx(N,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(N,{name:mt,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:Ct,className:O(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(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O(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(Qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(jt,{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===Jt?"scan-2":cn[ye]||"play",w=us(se,_.id),W=C[w],ne=!!W,de=W?.status==="stopping";return t.jsxs(jt,{className:"flex items-center gap-2",onClick:()=>{V(_,!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||W?.status==="waiting-for-preview"?t.jsx(N,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):ne?t.jsx(N,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},_.id)})]})]})]})},Rg=o.lazy(()=>Is(()=>import("./SessionSwitcherDropdown-CZOFeJHH.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}))),tr="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",Mg="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",Fg=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:O(a??tr,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}),Lg=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(Yt,{children:[t.jsx(Vt,{asChild:!0,children:t.jsx("button",{type:"button",className:O(tr,"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(Qt,{align:"end",className:"w-64",children:[t.jsx(Yd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ys,{}),r.map(d=>{const u=d.user,f=!!d.current,p=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(jt,{className:"gap-2",disabled:l,onSelect:()=>{f||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:p})]}):null]}),f?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"})})}),Og=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:f,remoteUpdateError:p,onOpenRemoteUpdate:g}){return t.jsxs(Yt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx(Vt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:O(tr,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(Qt,{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.`:f?"Looking for updates...":p||"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:g,children:"Update"}):null]})}),t.jsx(Wd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Bg=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},en=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ox=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{rs("ui.header.render");const l=ue(T=>T.setSessionSwitcherOpen),c=ue(T=>T.toggleSidebar),d=ue(T=>T.isSidebarOpen),u=ue(T=>T.activeMainTab),f=ue(T=>T.setActiveMainTab),p=ue(T=>T.shortcutOverrides);ue(T=>T.timeFormatPreference),Vn();const g=_e(T=>!!T.newSessionDraft?.open),m=_e(T=>T.currentSessionId),h=la(m??""),x=_d(m),j=o.useMemo(()=>{if(!x)return null;const T=x;return{title:x.title??null,directory:T.directory??null,created:x.time?.created??null,slug:T.slug??null,shareUrl:x.share?.url??null,parentId:x.parentID??null}},[x]),k=_t(zr(T=>{if(!T.activeProjectId)return null;const me=T.projects.find(Ae=>Ae.id===T.activeProjectId);return me?{id:me.id,path:me.path,label:me.label}:null})),B=o.useMemo(()=>{if(!k)return null;const T=k.label?.trim();if(T)return T;const me=k.path.split(/[\\/]/).filter(Boolean);return me[me.length-1]??null},[k]),{isMobile:S}=Rs(),{enabled:v}=Xr(),b=!!(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,H]=o.useState(()=>typeof window>"u"?!1:ys()),ee=o.useMemo(()=>ga(),[]),Z=zd(),[ie,$]=o.useState(!1),K=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:E,side:R}=ha(),Y=o.useMemo(()=>{if(typeof window>"u")return null;const T=window.__PICHAMBER_MACOS_MAJOR__;if(typeof T=="number"&&Number.isFinite(T)&&T>0)return T;if(typeof navigator>"u")return null;const me=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!me)return null;const Ae=Number.parseInt(me[1],10),z=Number.parseInt(me[2],10);return Number.isNaN(Ae)?null:Ae===10?z:Ae},[]);Qe.useEffect(()=>{typeof window>"u"||H(ys())},[]);const oe=ue(T=>T.isSessionSwitcherOpen),U=null,Te=null,Le=[],[Ve,Ge]=o.useState(!1),[Ke,Oe]=o.useState(!1),[se,fe]=o.useState("Local"),[He,ke]=o.useState(!0),[Ce,We]=o.useState(!1),[tt,ze]=o.useState(null),[q,V]=o.useState(!1),[ge,J]=o.useState(null),we=o.useMemo(()=>Bg(se),[se]),xe=o.useCallback(async()=>{if(!(typeof window>"u"||!D))try{if(fn()){fe("Local"),ke(!0);return}ke(!1);const T=await bu(),me=$d(),Ae=Ud([Gd(me),...T.hosts]);if(Ae.id===Kd){fe("Local"),ke(!0);return}fe(yu(Ae.label.trim()||"Instance"))}catch{fe("Local"),ke(!0)}},[D]);Qe.useEffect(()=>(xe(),vu(()=>{xe()})),[xe]);const Ie=o.useCallback(async()=>{if(He){ze(null),J(null);return}V(!0),J(null);try{const T=new URLSearchParams({appType:"web",instanceMode:"remote"}),me=await Xt(`/api/pi/update-check?${T.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!me.ok)throw new Error(`Server responded with ${me.status}`);const Ae=await me.json();ze({available:Ae.available??!1,version:Ae.version,currentVersion:Ae.currentVersion??"unknown",body:Ae.body,nextSuggestedCheckInSec:typeof Ae.nextSuggestedCheckInSec=="number"?Ae.nextSuggestedCheckInSec:void 0,packageManager:Ae.packageManager,updateCommand:Ae.updateCommand})}catch(T){ze(null),J(T instanceof Error?T.message:"Failed to check remote instance updates")}finally{V(!1)}},[He]);o.useEffect(()=>{ze(null),J(null),We(!1)},[He,se]),o.useEffect(()=>{if(!D||He)return;const T=3e3,me=3600*1e3;let Ae=!1,z=null;const Ue=lt=>{z=window.setTimeout(()=>{if(Ae||typeof document<"u"&&document.visibilityState!=="visible"){Ue(me);return}Ie().finally(()=>{Ae||Ue(me)})},lt)};return Ue(T),()=>{Ae=!0,z!==null&&window.clearTimeout(z)}},[Ie,He,se,D]);const ft=o.useCallback(()=>{if(tt?.available){We(!0);return}Ie()},[Ie,tt?.available]),mt=m?j??null:null,Ze=o.useRef(null),[Pe,Re]=o.useState(0);o.useEffect(()=>{if(!m){Ze.current&&(Ze.current=null,Re(z=>z+1));return}if(mt){Ze.current={sessionId:m,session:mt,expiresAt:Date.now()+2e3};return}const T=Ze.current;if(!T||T.sessionId!==m)return;const me=T.expiresAt-Date.now();if(me<=0){Ze.current=null,Re(z=>z+1);return}const Ae=window.setTimeout(()=>{Ze.current?.sessionId===m&&(Ze.current=null),Re(z=>z+1)},me);return()=>{window.clearTimeout(Ae)}},[m,mt]);const Ne=(()=>{if(mt)return mt;if(!m)return null;const T=Ze.current;return T&&T.sessionId===m&&T.expiresAt>Date.now()?T.session:null})(),at=o.useMemo(()=>{const T=typeof Ne?.directory=="string"?Ne.directory:"";return en(T||"")},[Ne?.directory]),Ct=_e(T=>T.newSessionDraft?.open?en(T.newSessionDraft.directoryOverride??""):""),st=o.useMemo(()=>at||Ct,[Ct,at]),ye=aa(st||null),be=!!(B||ye),w=o.useMemo(()=>{if(!m)return B??"PiChamber";const T=Ne?.title?.trim();return T&&T.length>0?T:"Untitled Session"},[B,Ne?.title,m]),W=ca(),ne=eo(),de=_e(T=>T.updateSessionTitle),Se=_e(T=>T.archiveSessions),De=_e(T=>T.deleteSessions),[$e,ht]=o.useState(!1),[kt,et]=o.useState(!1),pt=o.useRef(!1),[gt,Me]=o.useState(""),[Ye,xt]=o.useState(null),Lt=o.useRef(null);o.useEffect(()=>{pt.current=!1,et(!1),ht(!1),Me(""),xt(null)},[m]);const zt=o.useCallback(()=>{m&&(Me(Ne?.title?.trim()||w),ht(!0))},[Ne?.title,m,w]),At=o.useCallback(async()=>{if(!m)return;const T=gt.trim();T&&T!==Ne?.title?.trim()&&await de(m,T),ht(!1)},[Ne?.title,m,gt,de]);o.useEffect(()=>{if(!$e)return;const T=me=>{const Ae=me.target;(!Ae||!Lt.current?.contains(Ae))&&At()};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[$e,At]);const It=o.useCallback(()=>{m&&un(m).then(T=>{le[T.ok?"success":"error"](T.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[m]),Dt=o.useCallback(async()=>{if(!m||!st){le.error("Nothing to export");return}try{await ne.syncSession(m)}catch{le.error("Failed to load the complete session history");return}const T=Pr(W.getState()).list;if(T.length===0){le.error("Nothing to export");return}const me=tl(T,Ne?.title??null),Ae=rl(Ne?.title??null);await nl(me,Ae)||sl(me,Ae),le.success("Session exported")},[Ne?.title,m,W,st,ne]);h?.type==="busy"||h?.type;const M=o.useCallback(async()=>{if(!m||!Ye)return;const T=Hd(),me=[m];for(let lt=0;lt<me.length;lt+=1){const vt=me[lt];for(const St of T)St.parentID===vt&&!me.includes(St.id)&&me.push(St.id)}const Ae=Ye;if(xt(null),(Ae==="archive"?await Se(me):await De(me)).failedIds.length>0){le.error(Ae==="archive"?"Failed to archive session":"Failed to delete session");return}le.success(Ae==="archive"?"Session archived":"Session deleted")},[Se,m,De,Ye]),je=ue(T=>T.isArchivePageOpen),Be=o.useMemo(()=>je?{title:"Archive",subtitle:null}:null,[je]),ct=o.useMemo(()=>en(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||!ct||(ae.current={projectRef:F,directory:ct})},[ct,F]);const he=o.useMemo(()=>F&&ct?{projectRef:F,directory:ct}:ae.current,[ct,F]),nt=o.useCallback(async T=>{},[]),ve=o.useCallback(()=>{if(typeof document>"u")return;const T=document.activeElement;if(!T)return;const me=T.tagName;(me==="INPUT"||me==="TEXTAREA"||me==="SELECT"||T.isContentEditable)&&T.blur()},[]),Je=o.useCallback(()=>{if(S){ve(),l(!oe);return}c()},[ve,S,oe,l,c]),bt=o.useCallback(()=>{on("desktop_open_draft_mini_chat_window",{directory:en(st||k?.path||""),projectId:k?.id??null,apiBaseUrl:Rr(),clientToken:Tr()}).catch(T=>{console.warn("[header] failed to open draft mini chat window",T)})},[k?.id,k?.path,st]),Nt=o.useCallback(()=>{if(g){bt();return}m&&on("desktop_open_session_mini_chat_window",{sessionId:m,directory:en(st||k?.path||""),apiBaseUrl:Rr(),clientToken:Tr()}).catch(T=>{console.warn("[header] failed to open session mini chat window",T)})},[k?.path,m,bt,g,st]),Mt=tr,Et=Mg,$t=o.useMemo(()=>n?"sessions":b?r&&i?i:null:r?"git":u,[u,b,n,r,i]),Ft=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&oe&&l(!1)},[oe,n,e,s,r,l]),wt=o.useCallback(()=>{e?.()},[e]),qt=o.useCallback(()=>{s?.()},[s]),G=o.useMemo(()=>D&&K&&!ie?"5.5rem":Z?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!D||E?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[D,ie,K,Z,E]);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)",re=d?"0px":D&&E?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":v?"2.75rem":"2.5rem";Qe.useEffect(()=>{if(!D||!K){$(!1);return}let T=!1;const me=async()=>{try{const z=await on("desktop_is_window_fullscreen");T||$(z===!0)}catch{T||$(!1)}},Ae=()=>{me()};return me(),window.addEventListener("pichamber:window-resized",Ae),()=>{T=!0,window.removeEventListener("pichamber:window-resized",Ae)}},[D,K]);const ce=o.useMemo(()=>!D||!K||Y===null?"":Y>=26?"h-12":Y<=15?"h-14":"",[D,K,Y]),pe=o.useMemo(()=>{if(!(D&&!E))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,E]),dt=o.useCallback(()=>{if(typeof document>"u")return;const T=P.current?.getBoundingClientRect().height;T&&document.documentElement.style.setProperty("--oc-header-height",`${T}px`)},[]);Qe.useEffect(()=>{if(typeof window>"u")return;dt();const T=P.current;if(!T||typeof ResizeObserver>"u")return()=>{};let me=0;const Ae=()=>{me||(me=requestAnimationFrame(()=>{me=0,dt()}))},z=new ResizeObserver(Ae);return z.observe(T),window.addEventListener("resize",Ae),window.addEventListener("orientationchange",Ae),()=>{me&&cancelAnimationFrame(me),z.disconnect(),window.removeEventListener("resize",Ae),window.removeEventListener("orientationchange",Ae)}},[dt]),Qe.useEffect(()=>{dt()},[dt,S,ce]);const Tt=o.useCallback(async T=>{const me=T.target;me.closest(".app-region-no-drag")||me.closest("button, a, input, select, textarea")||T.button===0&&D&&await wu()},[D]),yt=o.useMemo(()=>S?[{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"}]:[],[S]),Ut=o.useCallback(T=>oo(rn(T,p)),[p]);Qe.useEffect(()=>{!S&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&f("chat")},[u,S,f]);const ts=o.useMemo(()=>{const T=[];return D&&T.push({value:"instance",label:"Instance",icon:t.jsx(N,{name:"server",className:"h-3.5 w-3.5"})}),T},[D]);Qe.useEffect(()=>{const T=me=>{if(Su(me)&&!me.shiftKey&&!me.altKey){const Ae=parseInt(me.key,10);Ae>=1&&Ae<=yt.length&&(me.preventDefault(),S&&(ve(),Ft()),f(yt[Ae-1].id))}};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[ve,Ft,S,f,yt]),Qe.useEffect(()=>{const T=me=>{const Ae=rn("toggle_services_menu",p);if(ti(me,Ae)){me.preventDefault(),Ke?Oe(!1):(Oe(!0),xe());return}const z=rn("cycle_services_tab",p);if(ti(me,z)){if(me.preventDefault(),ts.length===0)return;Oe(!0),xe();return}};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[p,Ke,ts,xe]);const Pt=T=>{const me=u===T.id,Ae=T.icon==="diff",z=Ae?null:T.icon,Ue=T.id==="chat",lt=St=>Ae?t.jsx(Hi,{size:St}):z?t.jsx(N,{name:z,className:`h-${St/4} w-${St/4}`}):null,vt=t.jsxs("button",{type:"button",onClick:()=>f(T.id),className:O("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",me?"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",Ue&&!S&&"min-w-[100px] justify-center"),"aria-label":T.label,"aria-selected":me,role:"tab",children:[S?lt(20):t.jsxs(t.Fragment,{children:[lt(16),t.jsx("span",{className:"header-tab-label",children:T.label})]}),T.badge!==void 0&&T.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:T.badge})]});return t.jsx(o.Fragment,{children:vt},T.id)},os=t.jsxs(t.Fragment,{children:[t.jsx(mg,{directory:ct,className:"mr-1"}),D?t.jsx(Og,{isDesktopApp:D,currentInstanceLabel:se,compactCurrentInstanceLabel:we,currentInstanceIsLocal:He,isDesktopServicesOpen:Ke,setIsDesktopServicesOpen:Oe,refreshCurrentInstanceLabel:xe,shortcutLabel:Ut,remoteUpdateInfo:tt,remoteUpdateChecking:q,remoteUpdateError:ge,onOpenRemoteUpdate:ft}):null,t.jsx(Lg,{isMobile:S,githubAuthStatus:I,githubAccounts:Le,githubAvatarUrl:U,githubLogin:Te,isSwitchingGitHubAccount:Ve,handleGitHubAccountSwitch:nt})]}),ls=ee&&(g||!!m),ms=()=>t.jsxs("div",{onMouseDown:Tt,className:O("app-region-drag relative flex h-12 select-none items-center pr-3",ce),style:pe,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:re}}),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:Mt,"aria-label":"Open session switcher",children:t.jsx(N,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Rg,{align:"start",children:t.jsx("button",{type:"button",className:Mt,"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:Lt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:T=>{T.preventDefault(),At()},children:[t.jsx("input",{value:gt,onChange:T=>Me(T.target.value),autoFocus:!0,onKeyDown:T=>{T.stopPropagation(),T.key==="Escape"&&ht(!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:()=>ht(!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:g?"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:[B?t.jsx("span",{className:"truncate",children:B}):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:O("flex h-[18px] shrink-0 items-center justify-center",be?"self-start":"self-center"),children:m&&!g&&!$e?t.jsxs(Yt,{open:kt,onOpenChange:et,onOpenChangeComplete:T=>{!T&&pt.current&&(pt.current=!1,zt())},children:[t.jsx(Vt,{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(Qt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(jt,{onClick:()=>{pt.current=!0},children:[t.jsx(N,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(jt,{onClick:It,children:[t.jsx(N,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Ys,{}),t.jsxs(jt,{onClick:()=>{Dt()},children:[t.jsx(N,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ys,{}),t.jsxs(jt,{onClick:()=>xt("archive"),children:[t.jsx(N,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(jt,{className:"text-destructive focus:text-destructive",onClick:()=>xt("delete"),children:[t.jsx(N,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),yt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:yt.map(T=>Pt(T))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[he?t.jsx(Vi,{projectRef:he.projectRef,directory:he.directory,className:"mr-1"}):null,t.jsx(Fg,{visible:ls,title:g?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:g?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Nt,className:O(Mt,"mr-1"),Icon:"picture-in-picture-2"}),os,t.jsx(pa,{visible:E&&R==="right",position:"right"})]})]})]}),Ls=()=>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:re}})]}),!v&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:wt,className:O(Et,$t==="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:!b&&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:yt.map(T=>{const me=u===T.id,Ae=T.icon==="diff",z=Ae?null:T.icon;return t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{S&&(ve(),Ft()),f(T.id)},"aria-label":T.label,"aria-selected":me,role:"tab",className:O(Et,"relative rounded-lg",$t===T.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[Ae?t.jsx(Hi,{className:"h-5 w-5"}):z?t.jsx(N,{name:z,className:"h-5 w-5"}):null,T.badge!==void 0&&T.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:T.badge}),T.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:T.label})})]},T.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b&&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(T=>{const me=r&&i===T.id;return t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{S&&(ve(),Ft()),C(!1),a?.(T.id)},"aria-label":T.label,"aria-selected":me,role:"tab",className:O(Et,"relative rounded-lg",me&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(N,{name:T.icon,className:"h-5 w-5"})})}),t.jsx(it,{children:t.jsx("p",{children:T.label})})]},T.id)})}),t.jsx(kh,{open:A,onOpenChange:C,currentSessionId:m,effectiveDirectory:st||null,isNewSessionDraftOpen:g})]}),he&&t.jsx(Vi,{projectRef:he.projectRef,directory:he.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!b?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:qt,className:O(Et,"relative",$t==="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=O("header-safe-area relative z-10 bg-background",S&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:Qs,style:{"--padding-scale":"1"},children:S?Ls():ms()}),t.jsx(is,{open:Ye!==null,onOpenChange:T=>{T||xt(null)},children:t.jsxs(as,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(vs,{children:[t.jsx(hs,{children:Ye==="delete"?"Delete session?":"Archive session?"}),t.jsx(Ms,{children:Ye==="delete"?`\\"${w}\\" will be permanently deleted.`:`\\"${w}\\" will be archived.`})]}),t.jsxs(Fs,{children:[t.jsx(qe,{variant:"outline",size:"sm",onClick:()=>xt(null),children:"Cancel"}),t.jsx(qe,{variant:"destructive",size:"sm",onClick:()=>{M()},children:Ye==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Ra,{open:Ce,onOpenChange:We,info:tt,downloading:!1,downloaded:!1,progress:null,error:ge,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Qi="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",_g="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",Bx=()=>{const e=ue(x=>x.isSidebarOpen),s=ue(x=>x.toggleSidebar),n=ue(x=>x.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=oo(rn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=ha(),{enabled:d}=Xr(),u=!e,f=l&&c==="left",p=l,g=u||f||p,m=f||p,h=o.useCallback(()=>{on("desktop_show_app_menu").catch(x=>{console.warn("[titlebar] failed to open app menu",x)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const x=b=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(b)}px`)},j=b=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(b)}px`)};if(!m)return;const k=i.current,B=r.current;if(!k||!B){x(0),j(0);return}const S=()=>{const b=Math.max(k.getBoundingClientRect().width,k.scrollWidth);x(b),j(B.getBoundingClientRect().width)};if(S(),typeof ResizeObserver>"u")return;const v=new ResizeObserver(S);return v.observe(k),v.observe(B),()=>{v.disconnect()}},[m]),g?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:[f?t.jsx(pa,{visible:!0,position:"left"}):null,p?t.jsxs(rt,{children:[t.jsx(ot,{asChild:!0,children:t.jsx("button",{type:"button",onClick:h,"aria-label":"Open PiChamber menu",className:O(Qi,"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:O(d?_g:Qi,"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},Tn=200,Rn="cubic-bezier(0.22, 1, 0.36, 1)",_x=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 ${Tn}ms ${Rn}, width ${Tn}ms ${Rn}, min-width ${Tn}ms ${Rn}, max-width ${Tn}ms ${Rn}`}};export{Us as $,vx as A,yx as B,bx as C,Mi as D,Cs as E,kx as F,dx as G,Ox as H,kf as I,fo as J,ax as K,Cf as L,kh as M,ho as N,lx as O,Ex as P,Vf as Q,Un as R,Ax as S,Tx as T,Ra as U,Nf as V,mn as W,bf as X,yf as Y,Ma as Z,gn as _,tn as a,wf as a0,nx as a1,hx as a2,vf as a3,Sf as a4,fx as a5,gx as a6,mx as a7,Af as a8,ks as a9,ux as aa,px as ab,xx as ac,sx as ad,rx as ae,ox as af,ix as ag,Gf as ah,cx as ai,th as aj,sh as ak,jf as al,tx as am,Nx as an,wx as ao,gm as b,Ix as c,_n as d,lh as e,Mx as f,Dx as g,jx as h,ym as i,Cx as j,Sx as k,_x as l,Fx as m,Bx as n,ex as o,Qf as p,qf as q,Rx as r,Px as s,Jf as t,Ln as u,ui as v,Xf as w,qm as x,Lx as y,Zf as z};