@pi-chamber/web 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/assets/{CommitSection-IIhrK4u7.js → CommitSection-DuGkZ_bm.js} +1 -1
  2. package/dist/assets/{DiagramEditor-DmDE7OFs.js → DiagramEditor-C7xe1Brl.js} +1 -1
  3. package/dist/assets/{DiagramView-BKKPzX5U.js → DiagramView-BTqROEWP.js} +1 -1
  4. package/dist/assets/{DiffView-BZAyvJ3r.js → DiffView-hcqXTjEc.js} +3 -3
  5. package/dist/assets/{FilesView-mwjEX08j.js → FilesView-GadyKxta.js} +4 -4
  6. package/dist/assets/{GitView-C1ltD6da.js → GitView-BKy-hYUN.js} +3 -3
  7. package/dist/assets/{JsonTreeView-De-9zk3N.js → JsonTreeView-CGc4eTGI.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-BJjIFNhO.js → MarkdownRendererImpl-CqfEAhPM.js} +1 -1
  9. package/dist/assets/{PatchDiff-DuR1fglg.js → PatchDiff-P17-Byb8.js} +1 -1
  10. package/dist/assets/{PierreDiffViewer-B_1JcH3B.js → PierreDiffViewer-BbUCO4IF.js} +1 -1
  11. package/dist/assets/{SessionSwitcherContent-DoEWfM8C.js → SessionSwitcherContent-j6KFBSe0.js} +1 -1
  12. package/dist/assets/{SessionSwitcherDropdown-CJWqyz1O.js → SessionSwitcherDropdown-DSVeuuVL.js} +2 -2
  13. package/dist/assets/{SessionUnreadDot-DB-YvwMh.js → SessionUnreadDot-BVBBEBTg.js} +1 -1
  14. package/dist/assets/SettingsView-FnmtcWZc.js +4 -0
  15. package/dist/assets/{SettingsWindow-nCTzNqyu.js → SettingsWindow-Bascj0V3.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-CIzj2Pxu.js → ToolOutputDialog-CPMzJ27S.js} +5 -5
  17. package/dist/assets/{ToolPartDiffPreview-BgewaN20.js → ToolPartDiffPreview-BZSRKHHM.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-aTd42JT9.js → VirtualizedFileDiff-DFx8xsmh.js} +3 -3
  19. package/dist/assets/{WindowsWindowControls-CdHYDpHx.js → WindowsWindowControls-DIqnZ2uU.js} +109 -109
  20. package/dist/assets/{collapsible-IV1T6v7c.js → collapsible-DlqZyxEY.js} +1 -1
  21. package/dist/assets/{computeVirtualFileMetrics-CcGhkiFO.js → computeVirtualFileMetrics-elCbdk6U.js} +1 -1
  22. package/dist/assets/{contextFileOpenGuard-DRkKhovc.js → contextFileOpenGuard-BmQ7Zu-L.js} +1 -1
  23. package/dist/assets/{index-DmJfzwE5.js → index-BerHSX92.js} +1 -1
  24. package/dist/assets/index-ChFxkws4.js +8 -0
  25. package/dist/assets/index-DZ-f_hCQ.css +1 -0
  26. package/dist/assets/{isDiffPlainText-DL6dDuVG.js → isDiffPlainText-CvfRfc7h.js} +1 -1
  27. package/dist/assets/{isFilePlainText-nuUWsdc6.js → isFilePlainText-_vq9Ghu3.js} +1 -1
  28. package/dist/assets/{main-Bajw-SZm.js → main-DTCOwPr3.js} +2 -2
  29. package/dist/assets/main-DYs-nZO6.js +133 -0
  30. package/dist/assets/{markdownCore-CrfGNEFF.js → markdownCore-CzWR_p3k.js} +2 -2
  31. package/dist/assets/{miniChat-Dfoj435F.js → miniChat-C2XxEA3N.js} +2 -2
  32. package/dist/assets/{mobile-DFIt0gxE.js → mobile-BQhAOqV7.js} +2 -2
  33. package/dist/assets/{renderElectronMiniChatApp-DKsf3ft3.js → renderElectronMiniChatApp-M2bY1WKA.js} +2 -2
  34. package/dist/assets/{renderMobileApp-iiD58RxE.js → renderMobileApp-BnpHUUhY.js} +4 -4
  35. package/dist/assets/{runtimeSurface-D3p7a-uO.js → runtimeSurface-OhCUGSKg.js} +1 -1
  36. package/dist/assets/{useInlineCommentController-5paFhtYM.js → useInlineCommentController-DC0iNSYX.js} +2 -2
  37. package/dist/assets/usePanelSlide-aeAIo1cp.js +56 -0
  38. package/dist/assets/{usePushVisibilityBeacon-BOPrDYSe.js → usePushVisibilityBeacon-om5Qlrt6.js} +2 -2
  39. package/dist/assets/{useSwitcherItems-DP5ufRVs.js → useSwitcherItems-Bln2r_Q2.js} +1 -1
  40. package/dist/assets/{vendor-codemirror-language-data-B9y74Qvn.js → vendor-codemirror-language-data-Dv4zaHRN.js} +2 -2
  41. package/dist/assets/{web-components-CD0f7QZj.js → web-components-BOt08OHk.js} +1 -1
  42. package/dist/index.html +4 -4
  43. package/dist/mini-chat.html +3 -3
  44. package/dist/mobile.html +3 -3
  45. package/package.json +1 -1
  46. package/server/lib/inherited-env.js +1 -1
  47. package/server/lib/pi/routes.js +9 -1
  48. package/server/lib/pi/routes.test.js +24 -0
  49. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -3
  50. package/server/lib/pi/session-daemon/session-daemon.js +64 -24
  51. package/server/lib/pi/session-daemon/session-daemon.test.js +78 -7
  52. package/server/lib/pi/session-daemon/session-jsonl.js +27 -7
  53. package/server/lib/pi/session-daemon/session-jsonl.test.js +31 -0
  54. package/dist/assets/SettingsView-ZwPgZh-7.js +0 -4
  55. package/dist/assets/index--5Zr-fSk.js +0 -8
  56. package/dist/assets/index--zDkVFU6.css +0 -1
  57. package/dist/assets/main-DIAtlyFC.js +0 -133
  58. package/dist/assets/usePanelSlide-D7Cl581q.js +0 -56
@@ -1,56 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DmJfzwE5.js","assets/WindowsWindowControls-CdHYDpHx.js","assets/index--5Zr-fSk.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index--zDkVFU6.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-D3p7a-uO.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-B9y74Qvn.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-CcGhkiFO.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-nuUWsdc6.js","assets/isDiffPlainText-DL6dDuVG.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-CJWqyz1O.js"])))=>i.map(i=>d[i]);
2
- import{_ as Ps}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Je,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{a_ as $s,a$ as Cc,ai as kc,o as Xi,D as as,n as ls,q as hs,I as C,ar as Is,b0 as $o,B as Ze,ap as fn,T as st,l as nt,m as rt,b1 as Zi,b2 as Nc,b3 as Ac,b4 as Ic,b5 as Dc,g as Oe,b6 as Pc,b7 as Uo,b8 as Ec,b9 as Tc,ba as Go,bb as Rc,bc as Mc,bd as Fc,be as Lc,bf as Dr,bg as Oc,t as le,am as Qt,an as Jt,ao as Xt,R as Ws,bh as Bc,bi as _c,bj as zc,bk as $c,bl as Ko,W as _t,bm as Uc,bn as Gc,bo as Kc,bp as Hc,bq as Wc,br as Yc,bs as Pr,bt as ea,bu as ta,bv as Vc,bw as qc,bx as Qc,by as Jc,bz as Xc,bA as Zc,aO as Er,r as Gs,aQ as Ts,aT as ed,aU as td,aV as sd,aW as nd,aX as lr,aY as Xs,bB as Ho,as as Ct,b as $t,aJ as Ms,bC as sa,p as Ss,s as Fs,v as Ls,bD as rd,a2 as Zs,bE as cr,bF as Wo,bG as Yo,bH as rn,av as od,aK as na,aA as Vo,ay as id,ax as ad,aN as ra,f as to,bI as ld,e as so,w as Jn,C as oa,bJ as cd,bK as Wt,aF as ia,c as Tr,bL as dd,bM as ud,bN as Xn,bO as gn,bP as qo,aP as aa,bQ as la,bR as ca,z as fd,bS as no,bT as hd,bU as pd,h as da,j as md,bV as gd,bW as xd,i as bd,bX as Rr,bY as ua,bZ as yd,b_ as vd,d as wd,b$ as Sd,a as jd,aq as Cd,aS as kd,c0 as fa,c1 as Nd,c2 as Ad,aR as Id,c3 as Dd,c4 as Pd,a8 as Ed,c5 as Td,aG as Rd,c6 as Md,c7 as Fd,c8 as kn,c9 as Qo,ca as Ld,cb as Jo,cc as Xo,cd as Od,aE as ha,U as Bd,x as _d,ce as pa,u as zd,cf as $d,cg as Ud,at as Ys,k as Gd,ch as Kd,ci as ma,cj as Hd,ck as Wd,cl as Yd,cm as Vd,cn as qd,co as ga,cp as Qd,cq as Jd}from"./WindowsWindowControls-CdHYDpHx.js";import{V as Zo,W as Xd,X as ei,Y as Zd,i as eu,Z as tu,P as su,r as es,_ as hn,b as nu,m as _,O as vs,u as fe,$ as ru,a0 as ds,a1 as ro,t as oo,n as ws,a2 as Qe,a3 as Rs,a4 as io,a5 as ao,a6 as ou,a7 as iu,F as au,a8 as lu,a9 as cu,aa as du,ab as uu,ac as is,ad as ti,ae as Mr,a as Zn,af as fu,ag as hu,Q as lo,R as on,ah as pu,ai as mu,aj as xa,A as gu,N as ba,G as an,ak as Fr,e as Lr,d as Nn,al as xu,am as bu,an as en,ao as dr,ap as ya,E as yu,q as vu,aq as Or,ar as Ds,as as si,at as Br,au as va,av as _r,aw as wu,ax as Su,ay as ju,x as Cu,az as ku,aA as Nu,aB as ni}from"./index--5Zr-fSk.js";import{d as Au,g as wa,r as Iu,e as Sa,h as On,i as ja,b as ln,c as cn,s as Du,j as Pu,k as Eu,l as ri,m as er,a as Tu,S as Ru,f as Mu,t as Fu,n as Lu}from"./SessionUnreadDot-DB-YvwMh.js";import{C as Ca,a as ka,M as zr,b as $r,c as Ur,d as Na,S as Aa,D as Ou,e as Bu,f as _u,g as zu,h as $u,i as Uu,j as Gu,k as Ku,l as Hu}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as Ia,p as co,u as Gr,a as Wu}from"./vendor-zustand-CnsBKjP5.js";import{u as Yu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as tr,d as pn,P as uo,D as sr,e as nr,f as Da,b as Vu,a as qu,T as Qu,M as Ju}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as fo,v as Pa,u as ho,a as Xu,h as Zu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as po}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as ef}from"./permissionStore-BRcQ9Jgt.js";const tf="chat";function Ea(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!==tf&&s.set($s.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set($s.FILE,e.diffFile),s}function sf(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 nf(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Ea(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 Kr(e,s={}){if(!(typeof window>"u")&&!(!s.force&&nf(e)))try{const n=Ea(e),r=sf(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const rf=["typescript","javascript","tsx","jsx","json","markdown"],Ta={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let oi=null;const Ra=()=>(oi??=Promise.all([Ps(()=>import("./index-DmJfzwE5.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])),Ps(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ps(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,11,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),oi),mn={},ii=new Set,Hr=new Set;let Bn={light:"pierre-light",dark:"pierre-dark"};const of=()=>{for(const e of Hr)e()},Ma=(e,s)=>{s.setRenderOptions({theme:Bn,lineDiffType:Ta[e].lineDiffType})},Wr=e=>{typeof window>"u"||ii.has(e)||(ii.add(e),Ra().then(s=>{if(mn[e])return;const n=Ta[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:rf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),mn[e]=r,Ma(e,r),of()}))},af=e=>(Hr.add(e),()=>Hr.delete(e)),lf=e=>{if(!(Bn.light===e.light&&Bn.dark===e.dark)){Bn=e;for(const s of Object.keys(mn)){const n=mn[s];n&&Ma(s,n)}}},ox=({children:e})=>{const s=Cc(),n=Zo(!1),r=Zo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Je.useEffect(()=>{let d=!1;return Ra().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),lf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Je.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Wr("unified"),Wr("split")};if(typeof window.requestIdleCallback=="function"){const p=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(p)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},ix=(e="unified")=>{const s=Je.useSyncExternalStore(af,()=>mn[e],()=>{});return Je.useEffect(()=>{Wr(e)},[e]),s};function cf(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=kc();return e}catch{return"unknown"}}function df(){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 uf(){const e=nu();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 ff(e){const s=new URLSearchParams;return s.set("deviceClass",cf()),s.set("arch",df()),s.set("platform",uf()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",hn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function ur(e,s){try{const n=ff(e);s&&n.set("currentVersion",s);const r=await es(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function hf(){return eu()?"mobile":tu()?"desktop":su()?"web":null}const ai={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},_n=ps()((e,s)=>({...ai,checkForUpdates:async()=>{const n=hf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.6.0",[l,c]=await Promise.allSettled([ei(),ur("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 ur("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ur("mobile","0.6.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 ei();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await Zd(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 Xd())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ai)}})),li="https://github.com/RyderAsKing/PiChamber/releases";function pf(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 mf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function ci(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function gf(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 xf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const di=2e3,bf=600*1e3;async function yf(){try{const e=await es("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function vf(){try{return(await es("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function wf(e,s=Math.ceil(bf/di),n=di){for(let r=0;r<s;r++){try{const i=await es("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await vf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Fa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[p,h]=Je.useState(!1),[x,m]=Je.useState("idle"),[f,g]=Je.useState(null),S=n?.version?n.releaseUrl||`${li}/tag/v${n.version}`:li,j=n?.downloadUrl||S,B=a?.total?Math.round(a.downloaded/a.total*100):0,A=u==="web",b=u==="mobile",v=n?.updateCommand||"pichamber update";Je.useEffect(()=>{e||(m("idle"),g(null))},[e]);const M=async()=>{(await fn(v)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},N=Je.useCallback(async G=>{await Xi(G)},[]),k=Je.useCallback(async()=>{m("updating"),g(null);const G=await yf();if(!G.success){m("error"),g(G.error||"Update failed");return}G.autoRestart&&(m("restarting"),await new Promise(Z=>setTimeout(Z,2e3))),m("reconnecting"),await wf(n?.currentVersion)?window.location.reload():(m("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),I=Je.useCallback(()=>{N(j)},[N,j]),D=x!=="idle"&&x!=="error",P=Je.useMemo(()=>{if(!n?.body)return null;const G=n.body.trim();if(!G)return null;const ee=xf(G);return ee.length===0?{kind:"raw",title:"What's new",content:ci(G)}:{kind:"sections",title:"What's new",sections:[...ee].sort((te,U)=>gf(te.version,U.version)).map(te=>({version:te.version,dateLabel:pf(te.date),content:ci(mf(te.raw)||G)}))}},[n?.body]);return t.jsx(as,{open:e,onOpenChange:D?void 0:s,children:t.jsxs(ls,{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(C,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[A&&D&&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(C,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),P&&!D&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Is,{className:"max-h-[400px] p-0",fillContainer:!1,children:P.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:G=>{const Z=G.target.closest("a");Z&&Z.href&&(G.preventDefault(),G.stopPropagation(),N(Z.href))},children:t.jsx($o,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:P.sections.map(G=>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",G.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:G.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 te=ee.target.closest("a");te&&te.href&&(ee.preventDefault(),ee.stopPropagation(),N(te.href))},children:t.jsx($o,{content:G.content,disableLinkSafety:!0,enableFileReferences:!1})})]},G.version))})})}),A&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(C,{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:v}),t.jsx("button",{onClick:M,className:_("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",p&&"text-[var(--status-success)]"),title:p?"Copied!":"Copy command",children:p?t.jsx(C,{name:"check",className:"h-4 w-4"}):t.jsx(C,{name:"clipboard",className:"h-4 w-4"})})]})]}),!A&&!b&&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||f)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||f})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(C,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!A&&!b&&!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(C,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!A&&!b&&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(C,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!A&&!b&&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(C,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),b&&t.jsxs(Ze,{onClick:I,size:"default",children:[t.jsx(C,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),A&&!D&&t.jsxs("button",{onClick:k,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(C,{name:"download",className:"h-4 w-4"}),"Update Now"]}),A&&D&&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(C,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Sf=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:_("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:_("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),xn=({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(st,{open:r,onOpenChange:i,children:[t.jsx(nt,{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:_("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(C,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},ax="w-full min-w-40 max-w-48",jf="settings",Cf="w-full min-w-40 max-w-48",lx="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",kf="w-full max-w-[24rem]",cx="min-w-0 flex-1",dx="flex w-full min-w-0 items-center gap-2",ux="typography-meta shrink-0 text-muted-foreground tabular-nums",La="space-y-3.5",Nf="space-y-1.5",fx="typography-settings-page-title text-muted-foreground",Af="typography-settings-section-title text-foreground",hx="typography-settings-section-title text-foreground",Oa="typography-settings-group-title text-foreground",mo="typography-settings-field-label text-foreground",If="typography-settings-description text-muted-foreground",bn="typography-meta text-muted-foreground",px="typography-meta font-medium text-foreground",mx="typography-settings-section-title text-foreground",Df=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const p=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:_("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[p?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:Af,children:e}):e,n,r!=null?t.jsx(xn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:If,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:_(d),children:a})]})},gx=({children:e,className:s})=>t.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Pf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:_(Oa,s),children:e}),xx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:_("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(Pf,{children:e}),n!=null?t.jsx(xn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:bn,children:s}):null]}):null,t.jsx("div",{className:_(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:bn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:_("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:mo,children:e}),n!=null?t.jsx(xn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},bx=({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:_("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:mo,children:e}),n!=null?t.jsx(xn,{children:n}):null]}),s!=null?t.jsx("p",{className:_(bn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:_("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),yx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:_("pt-4",s),children:e}),Ef=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const p=()=>{i||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:_("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:p,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),p())},children:[t.jsx(Zi,{checked:e,onChange:s,disabled:i,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:mo,children:n}),d,u!=null?t.jsx(xn,{children:u}):null]}),h?t.jsx("span",{className:bn,children:r}):null]})]})},vx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:_("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(Sf,{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:_("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:bn,children:r}):null]})]}),wx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:_(Nf,n),children:s});function Sx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:_("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Ze,{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 Tf 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(Nc,{className:"w-full max-w-md",children:[t.jsx(Ac,{className:"text-center",children:t.jsxs(Ic,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(C,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Dc,{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(Ze,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(C,{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 Rf(e){return t.jsx(Tf,{...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 jx=({active:e=!0})=>{const s=Oe(n=>n.currentSessionId);return t.jsx(Rf,{sessionId:s||void 0,children:t.jsx(Pc,{active:e},s??"no-session")})};function Mf({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 go=Je.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:p,endSlot:h,...x},m)=>{const f=Je.useRef(null),g=Je.useRef(null),[S,j]=Je.useState(null),B=c??S,A=Je.useCallback(v=>{const M=f.current;if(!M)return;g.current={startY:v.clientY,startHeight:M.getBoundingClientRect().height};const N=v.currentTarget;N.setPointerCapture(v.pointerId);const k=D=>{const P=g.current;if(!P)return;const G=P.startHeight+(D.clientY-P.startY),ee=Math.max(82,G);d?d(ee):j(ee)},I=()=>{g.current=null,N.removeEventListener("pointermove",k),N.removeEventListener("pointerup",I),N.removeEventListener("pointercancel",I)};N.addEventListener("pointermove",k),N.addEventListener("pointerup",I),N.addEventListener("pointercancel",I),v.preventDefault()},[d]),b=Je.useCallback(v=>{if(v.target.closest('textarea, button, [role="separator"]'))return;const N=f.current?.querySelector("textarea");N&&document.activeElement!==N&&(v.preventDefault(),N.focus())},[]);return p?t.jsx(Is,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:f,onPointerDown:b,style:B!==null?{height:`${B}px`}:void 0,className:_("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],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:_("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(Mf,{onResizeStart:A,ariaLabel:"Resize textarea"})]})]})})});go.displayName="Textarea";const ui=(e,s)=>s.updatedAtMs-e.updatedAtMs,Hn=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([Mc(),Go()]),i={};for(const a of r.sort(ui))i[a.id]=a;s().listenerReady||await Fc(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 Rc();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Go(),r={};for(const i of n.sort(ui))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Tc({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=Lc(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await Uo(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 Ec(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 Uo(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})})),Ba=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],dn=Object.fromEntries(Ba.map(e=>[e.key,e.Icon])),Yr="pichamber:project-actions-updated",_a=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},us=(e,s)=>`${_a(e)}::${s}`,Ff=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},fi=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Lf=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=fi(s.localPort),r=fi(s.remotePort);if(!n||!r)return null;const i=Ff(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}`}},za=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Lf(n,r);i&&s.push(i)}return s},Of=(e,s)=>{const n=(e||"").trim();return n&&za(s).find(a=>a.id===n)?.url||null},Bf=kf,$a=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Df,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Vr=e=>e.name.trim().length>0&&e.command.trim().length>0,_f=e=>e.name.trim().length===0&&e.command.trim().length===0,zf=e=>!Vr(e)&&!_f(e),$f=(e,s)=>e.some(r=>s.has(r.id)&&!Vr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Vr)},Uf=450,Gf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Kf=()=>({id:Gf(),name:"",command:"",icon:"play"}),Hf=({projectRef:e})=>{const s=o.useMemo(()=>vs(),[]),n=Hn(v=>v.instances),r=Hn(v=>v.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[p,h]=o.useState(new Set),x=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let v=!1;return c(!0),(async()=>{try{const M=await Dr(e);if(v)return;a(M.actions),u(JSON.stringify({actions:M.actions})),h(new Set(M.actions.map(N=>N.id)))}catch{if(v)return;a([]),u(JSON.stringify({actions:[]})),h(new Set)}finally{v||c(!1)}})(),()=>{v=!0}},[e]);const m=o.useMemo(()=>s?za(n):[],[n,s]),f=o.useMemo(()=>$f(i,p),[i,p]),g=o.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),S=d!==null&&f.canPersist&&g!==d,j=o.useCallback(async v=>await Oc(e,{actions:v,primaryActionId:null})?(u(JSON.stringify({actions:v})),h(new Set(v.map(N=>N.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Yr,{detail:{projectId:e.id}})),!0):(le.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!S||l||x.current)return;const v=window.setTimeout(()=>{x.current||(x.current=!0,(async()=>{try{await j(f.actions)}finally{x.current=!1}})())},Uf);return()=>{window.clearTimeout(v)}},[S,l,j,f.actions]);const B=o.useCallback(()=>{const v=Kf();a(M=>[...M,v])},[]),A=o.useCallback(v=>{a(M=>M.filter(N=>N.id!==v))},[]),b=o.useCallback((v,M)=>{a(N=>N.map(k=>k.id===v?M(k):k))},[]);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(Ze,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:B,children:[t.jsx(C,{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:_("space-y-6",Bf),children:i.map((v,M)=>{const N=v.icon||"play",k=dn[N]||"play",I=v.name.trim()||`Action ${M+1}`,D=zf(v);return t.jsxs("div",{className:La,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Oa,children:I}),t.jsx(Ze,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>A(v.id),"aria-label":`Delete ${I}`,children:t.jsx(C,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Us,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(C,{name:k,className:"h-4 w-4"})})}),t.jsx(Xt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ba.map(P=>{const G=P.Icon,ee=(v.icon||"play")===P.key;return t.jsx("button",{type:"button",onClick:()=>b(v.id,Z=>({...Z,icon:P.key})),className:_("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 ${P.label}`,children:t.jsx(C,{name:G,className:"h-4 w-4"})},P.key)})})})]}),t.jsx(Ws,{value:v.name,onChange:P=>b(v.id,G=>({...G,name:P.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(go,{value:v.command,onChange:P=>b(v.id,G=>({...G,command:P.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),D?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Ef,{checked:v.autoOpenUrl===!0,onChange:P=>b(v.id,G=>({...G,...P?{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}`}),v.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:v.openUrl||"",onChange:P=>b(v.id,G=>({...G,openUrl:P.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(Bc,{value:v.desktopOpenSshForward&&m.some(P=>P.id===v.desktopOpenSshForward)?v.desktopOpenSshForward:"__none__",onValueChange:P=>{b(v.id,G=>({...G,...P==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:P}}))},children:[t.jsx(_c,{size:jf,className:"w-full",children:t.jsx(zc,{placeholder:"Use output/manual URL"})}),t.jsxs($c,{children:[t.jsx(Ko,{value:"__none__",children:"Use output/manual URL"}),m.map(P=>t.jsx(Ko,{value:P.id,children:P.label},P.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},v.id)})})})},Wf={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)"},Yf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=_t(D=>D.providers),d=_t(D=>D.modelsMetadata),u=fe(D=>D.hiddenModels),p=fe(D=>D.providerOrder),h=fe(D=>D.setProviderOrder),x=fe(D=>D.isFavoriteModel),m=fe(D=>D.toggleFavoriteModel),f=fe(D=>D.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:S}=Uc(),[j,B]=o.useState(!1),[A,b]=o.useState("");o.useEffect(()=>{j||b("")},[j]);const v=e?c.find(D=>D.id===e.providerId):void 0,M=e&&v?(Array.isArray(v.models)?v.models:[]).find(D=>D.id===e.modelId):void 0,N=e?Gc(M,e.modelId):s,k=o.useMemo(()=>e?u.filter(D=>!(D.providerID===e.providerId&&D.modelID===e.modelId)):u,[u,e]),I=o.useCallback(D=>{l({providerId:D.providerID,modelId:D.modelID}),B(!1)},[l]);return t.jsxs(Qt,{modal:!1,open:j,onOpenChange:D=>{r||B(D)},children:[t.jsx(Jt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(Hc({size:"default"}),Cf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Kc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:N})]}),t.jsx(C,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Xt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Wc,{providers:c,favoriteModels:g,recentModels:S,modelsMetadata:d,searchQuery:A,onSearchQueryChange:b,onSelect:I,labels:{...Wf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:k,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),B(!1)},disabled:r,autoFocus:!0,onEscape:()=>B(!1),isFavorite:D=>x(D.providerID,D.modelID),onToggleFavorite:D=>m(D.providerID,D.modelID),onReorderFavorite:(D,P)=>f(D.providerID,D.modelID,P.providerID,P.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:p,onReorderProvider:h,reorderProviderTitle:"Drag to reorder provider"})})]})},fr="w-full max-w-none",Vf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=_t(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx($a,{title:"Project",divider:!1,children:t.jsxs("div",{className:La,children:[t.jsx(Us,{label:"Name",settingsItem:"projects.name",controlClassName:fr,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:fr,children:t.jsx(Yf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:fr,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},qf=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(()=>Yc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,p)=>{i(u&&p?`${u}/${p}`:void 0)},[]),d=o.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Qf=450,Jf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{le.error("Failed to save project settings")}}finally{l.current=!1}})())},Qf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Xf=({project:e,onIdentitySave:s})=>{const n=qf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Jf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Vf,{form:n}),t.jsx(Hf,{projectRef:r})]})};function Zf({...e}){return t.jsx(Ca,{...e})}function eh({...e}){return t.jsx(ka,{...e})}function th({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(zr,{children:t.jsx($r,{className:_("app-region-no-drag z-50",s),children:t.jsx(Ur,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Pr,e),...i,children:n})})})}function hi({className:e,...s}){return t.jsx(Na,{className:_(ea,e),...s})}function sh({className:e,...s}){return t.jsx(Aa,{className:_(ta,e),...s})}const As=ps()(Ia(co((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 Zc();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 Xc();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 Jc();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=oo()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await es("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await ro({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 Qc(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 qc(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 Vc(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:ru(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=As);const nh=[{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"]}],rh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function oh(e){const s=e.trim().toLowerCase();return nh.find(n=>n.slug===s)??null}function ih(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=rh[s];if(n)return n;const r=oh(s);return r?r.slug:"home"}function Cx(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 An=100;function kx(){const e=fe(k=>k.isArchivePageOpen),s=fe(k=>k.setArchivePageOpen),n=fe(k=>k.setActiveMainTab),r=Oe(k=>k.setCurrentSession),i=Oe(k=>k.unarchiveSession),a=ws(k=>k.homeDirectory),l=Er({archived:!0}),[c,d]=o.useState(""),[u,p]=o.useState(null),[h,x]=o.useState(An),m=c.trim().toLowerCase(),f=o.useMemo(()=>e?[...l].sort((k,I)=>(I.time?.archived??0)-(k.time?.archived??0)):[],[l,e]),g=o.useMemo(()=>{const k=new Map;for(const I of f){const D=Qe(Gs(I))??"",P=k.get(D);if(P){P.sessions.push(I);continue}k.set(D,{directory:D,label:D?Rs(D,a)||D:"other projects",sessions:[I]})}return[...k.values()].sort((I,D)=>D.sessions.length-I.sessions.length)},[a,f]),S=o.useMemo(()=>m?f.filter(k=>(k.title??"").toLowerCase().includes(m)):u===null?f:g.find(k=>k.directory===u)?.sessions??[],[g,m,u,f]),j=S.slice(0,h),B=S.length-j.length,A=l.length,b=o.useCallback(k=>{p(k),x(An)},[]),v=o.useCallback(k=>{const I=Qe(Gs(k));r(k.id,I??void 0),n("chat"),s(!1)},[n,r,s]),M=o.useCallback(k=>{i(k.id).then(I=>{I?le.success("Session restored"):le.error("Failed to restore session")})},[i]);if(!e)return null;const N=(k,I,D,P,G,ee,Z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:G,title:ee,className:_("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"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:D})]}),Z?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Ts.requestDelete({sessions:Z,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${I}`,children:t.jsx(C,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},k);return t.jsx(Ou,{open:e,onOpenChange:s,children:t.jsxs(Bu,{children:[t.jsx(_u,{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(zu,{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($u,{className:"sr-only",children:"Archived sessions"}),t.jsx(Uu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Gu,{"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(C,{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:[N("__all__","All directories",A,u===null,()=>b(null)),g.map(k=>N(k.directory||"__none__",k.label,k.sessions.length,u===k.directory,()=>b(k.directory),k.directory||void 0,k.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(C,{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:k=>{d(k.target.value),x(An)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:S.length===1?`${S.length} archived session`:`${S.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[j.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"})}):j.map(k=>{const I=Qe(Gs(k))??"",D=I?Rs(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:()=>v(k),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v(k))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:k.title||"Untitled Session"}),m&&D?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:I,children:D}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Au(k.time?.archived??k.time?.updated??k.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),M(k)},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 ${k.title||"Untitled Session"}`,children:t.jsx(C,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),Ts.requestDelete({sessions:[k],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity 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 ${k.title||"Untitled Session"}`,children:t.jsx(C,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},k.id)}),B>0?t.jsx("button",{type:"button",onClick:()=>x(k=>k+An),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 ah=()=>{const[e,s]=Je.useState(!1),[n,r]=Je.useState(!1);Je.useEffect(()=>{s(vs()),r(io())},[]);const i=Je.useCallback(async c=>e?await ao(c):{success:!0,path:c},[e]),a=Je.useCallback(async c=>e?await ou():{success:!0},[e]),l=Je.useCallback(async c=>e?await iu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},lh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ch=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[p,h]=o.useState(""),[x,m]=o.useState(!1),[f,g]=o.useState(!1),[S,j]=o.useState(""),[B,A]=o.useState(!1),b=o.useRef(null),v=o.useCallback(U=>{U.stopPropagation()},[]),M=l.length>1,N=o.useMemo(()=>lh(S),[S]),k=o.useMemo(()=>{const U=p.toLowerCase();return U?s.filter(K=>K.toLowerCase().includes(U)):s},[p,s]),I=o.useMemo(()=>{const U=p.toLowerCase();return U?n.filter(K=>K.toLowerCase().includes(U)):n},[p,n]),D=U=>{if(U===e){u(!1);return}i(U),u(!1),h("")},P=()=>{m(!0),setTimeout(()=>b.current?.focus(),50)},G=async()=>{if(!(!N||B)){if(M){g(!0);return}A(!0);try{await a(N,l[0]),j(""),m(!1),u(!1)}finally{A(!1)}}},ee=async U=>{if(!(!N||B)){A(!0);try{await a(N,U),j(""),m(!1),g(!1),u(!1)}finally{A(!1)}}},Z=()=>{g(!1)},te=()=>{j(""),m(!1),g(!1)};return o.useEffect(()=>{d||(h(""),m(!1),g(!1),j(""))},[d]),t.jsxs(Qt,{open:d,onOpenChange:u,children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Ze,{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(C,{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(C,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(rt,{sideOffset:8,children:"Current branch"})]}),t.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(ed,{className:"h-full min-h-0",children:[t.jsx(td,{placeholder:"Search branches...",value:p,onValueChange:h,onKeyDown:v}),t.jsxs(sd,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(nd,{children:"No branches found."}),t.jsx(lr,{children:f?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:Z,disabled:B,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(C,{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:N})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(U=>t.jsxs("button",{type:"button",onClick:()=>ee(U),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(C,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,U.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:U.pushUrl})]},U.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:b,placeholder:"New branch name",value:S,onChange:U=>j(U.target.value),onClick:U=>U.stopPropagation(),onKeyDown:U=>{v(U),U.key==="Enter"?(U.preventDefault(),G()):U.key==="Escape"&&(U.preventDefault(),te())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:G,disabled:!N||B,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:B?t.jsx(C,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(C,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:te,disabled:B,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(C,{name:"close",className:"size-4"})})]}):t.jsxs(Xs,{onSelect:P,children:[t.jsx(C,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ho,{}),t.jsxs(lr,{heading:"Local branches",children:[k.map(U=>t.jsxs(Xs,{onSelect:()=>D(U),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:U}),(r?.[U]?.ahead||r?.[U]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[U].ahead||0," ahead ·"," ",r[U].behind||0," behind"]})]}),e===U&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${U}`)),k.length===0&&t.jsx(Xs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ho,{}),t.jsxs(lr,{heading:"Remote branches",children:[I.map(U=>t.jsx(Xs,{onSelect:()=>D(U),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:U})},`remote-${U}`)),I.length===0&&t.jsx(Xs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},dh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),uh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),p=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const f=dh(a);if(f===e){i(!1);return}d(!0);try{await s(e,f),i(!1),l("")}finally{d(!1)}},x=()=>{i(!1),l("")},m=f=>{f.key==="Enter"?(f.preventDefault(),h()):f.key==="Escape"&&(f.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:f=>{f.preventDefault(),h()},children:[t.jsx(C,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:f=>l(f.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown: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(C,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(C,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(C,{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(C,{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(Ze,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:p,title:"Rename branch",children:t.jsx(C,{name:"edit",className:"size-4"})})]})]})},fh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:p=!1})=>{const h=o.useRef(!1),x=!!l,m=s.find(v=>v.name===u)??s[0],f=d>0&&p,g=a||e!==null||x||!m||f,S=a||e!==null||x||s.length===0,j=c>0||d>0,B=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),A=f?"Commit or stash your changes before syncing":m?j?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",b=()=>{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(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:f?0:void 0,children:t.jsxs("button",{type:"button",onClick:b,disabled:g,className:_("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(C,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(C,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:B})]})})}),t.jsx(rt,{sideOffset:8,children:A})]}),t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:_("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:S,"aria-label":"More sync actions",children:t.jsx(C,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Xt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(v=>t.jsx(Ct,{onSelect:M=>{if(h.current){M.preventDefault(),h.current=!1;return}n(v)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(C,{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 ${v.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:v.fetchUrl})]})}),i&&v.name!==u?t.jsx(Ze,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:M=>{h.current=!0,M.preventDefault(),M.stopPropagation()},onClick:M=>{h.current=!0,M.preventDefault(),M.stopPropagation(),i(v)},"aria-label":`Remove remote ${v.name}`,title:`Remove remote ${v.name}`,children:l===v.name?t.jsx(C,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(C,{name:"close",className:"size-3.5"})}):null]})},v.name))})]})]})},hh={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},ph={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 Ua(e){return e&&ph[e]||"var(--primary)"}const pi=({icon:e,className:s,colorToken:n})=>{const r=hh[e??"branch"]??"user-3";return t.jsx(C,{name:r,className:s,style:{color:Ua(n)}})},Ga=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(Qt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Ze,{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:Ua(e?.color)},disabled:a,children:[r?t.jsx(C,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(pi,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(C,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(rt,{sideOffset:8,children:"Git identity"})]}),t.jsx(Xt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(Ct,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(pi,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(C,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},mh=({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(st,{delayDuration:n,children:[t.jsx(nt,{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(C,{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(rt,{sideOffset:8,children:a})]})},Nx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:p,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:m,availableIdentities:f,onSelectIdentity:g,isApplyingIdentity:S,isWorktreeMode:j,onOpenHistory:B,onOpenGraph:A,onOpenStashes:b,onOpenUpdateBranch:v,onOpenReintegrateCommits:M,pullRequest:N,prChecks:k,onOpenPullRequest:I})=>{if(!e)return null;const D=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:B||A||b||v?t.jsxs(Qt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsx(Ze,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(C,{name:"more-fill",className:"size-4"})})})}),t.jsx(rt,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Xt,{align:"end",children:[B?t.jsxs(Ct,{onSelect:B,children:[t.jsx(C,{name:"history",className:"size-4"}),"History"]}):null,A?t.jsxs(Ct,{onSelect:A,children:[t.jsx(C,{name:"git-branch",className:"size-4"}),"Graph"]}):null,b?t.jsxs(Ct,{onSelect:b,children:[t.jsx(C,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,v?t.jsxs(Ct,{onSelect:v,children:[t.jsx(C,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,M?t.jsxs(Ct,{onSelect:M,children:[t.jsx(C,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),P=k?k.state==="success"?"var(--status-success)":k.state==="failure"?"var(--status-error)":"var(--status-warning)":null,G=N?N.state==="merged"?"merged":N.state==="closed"?"closed":N.draft?"draft":k?.state==="failure"||N.mergeable===!1||N.mergeableState==="blocked"||N.mergeableState==="dirty"?"blocked":"open":null,ee=N&&I?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs(Ze,{variant:"ghost",size:"sm",onClick:I,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(C,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${G})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${N.number}`}),P?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:P}}):null]})}),t.jsx(rt,{sideOffset:8,children:"Open pull request"})]}):null,Z=t.jsx(fh,{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}),te=e.upstreamComparison?t.jsx(mh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,U=t.jsx(Ga,{activeProfile:m,identities:f,onSelect:g,isApplying:S,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:j?t.jsx(uh,{currentBranch:e.current,onRename:x}):t.jsx(ch,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:p,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:U})]}),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"}),te?t.jsx("div",{className:"min-w-0 shrink",children:te}):null,D,t.jsx("div",{className:"shrink-0",children:Z})]})]})},gh=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Vs=e=>{if(!e||gh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Hs=e=>e.endsWith("/"),Wn=e=>{const s=e.trim();return!s||Hs(s)?s:`${s}/`},xo=e=>e.lastIndexOf("/"),Ka=e=>{if(Hs(e))return e;const s=xo(e);return s<0?e:e.slice(0,s+1)},Ha=e=>{const s=xo(e);return e.slice(s+1)},Wa=e=>{const s=Vs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=xo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Ya=e=>Hs(e)&&Wa(e)!==null,xh=e=>{if(!Ya(e))return null;const s=Vs(e.trim());return Ha(s)||s},bh=(e,s)=>`${Ka(e)}${s}/`,ks=e=>{if(!e)return null;const s=Vs(Ks(e.trim()));return s?s.toLowerCase():null},mi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},yh=(e,s)=>{const n=Vs(Ks(e.trim())),r=Vs(Ks(s.trim()));if(!n)return"";if(!r)return Wn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Wn(n)},vh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,hr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},wh=async()=>du(),Sh=({open:e,onOpenChange:s})=>{const n=ws(F=>F.homeDirectory),r=$t(F=>F.projects),i=$t(F=>F.addProject),a=fe(F=>F.setActiveMainTab),l=fe(F=>F.setSessionSwitcherOpen),c=Oe(F=>F.openNewSessionDraft),d=As(F=>F.profiles),u=As(F=>F.globalIdentity),p=As(F=>F.defaultGitIdentityId),h=As(F=>F.loadProfiles),x=As(F=>F.loadGlobalIdentity),m=As(F=>F.loadDefaultGitIdentityId),{canRequestAccess:f,startAccessing:g}=ah(),{isMobile:S,isTablet:j}=Ms(),B=S||j,A=o.useRef(null),b=o.useRef(new Map),[v,M]=o.useState(""),[N,k]=o.useState("~/"),[I,D]=o.useState([]),[P,G]=o.useState(!1),[ee,Z]=o.useState(!1),[te,U]=o.useState(null),[K,T]=o.useState(0),[R,Q]=o.useState(0),[ae,z]=o.useState(!1),[Re,Te]=o.useState(!1),[Ye,_e]=o.useState(!1),[Ve,Be]=o.useState(""),[ie,pe]=o.useState(null),[We,Ce]=o.useState(!1),[ve,$e]=o.useState("right"),ot=o.useRef("~/"),ze=v||n,J=o.useMemo(()=>new Set(r.map(F=>ks(F.path)).filter(F=>!!F)),[r]);o.useEffect(()=>{if(!e)return;k("~/"),D([]),Q(0),z(!1),Te(!1),_e(!1),Be(""),pe(null),Ce(!1),ot.current="~/",$e("right"),B||requestAnimationFrame(()=>hr(A.current));let F=!1;return(async()=>{const Ue=await wh();F||(M(Ue||n||""),B||requestAnimationFrame(()=>hr(A.current)))})(),()=>{F=!0}},[n,e,B]),o.useEffect(()=>{e&&(h(),x(),m())},[m,h,x,e]);const q=o.useMemo(()=>{const F=new Map;u&&F.set(u.id,u);for(const Ne of d)F.set(Ne.id,Ne);return Array.from(F.values())},[d,u]);o.useEffect(()=>{if(!e||!Ye||ie!==null)return;const F=typeof p=="string"?p.trim():"";if(F&&q.some(Ue=>Ue.id===F)){pe(F);return}const Ne=q.find(Ue=>Ue.authType==="ssh"||Ue.sshKey);Ne&&pe(Ne.id)},[q,p,Ye,e,ie]);const ge=o.useMemo(()=>q.find(F=>F.id===ie)??null,[q,ie]),X=o.useMemo(()=>Ka(N),[N]),be=o.useMemo(()=>Hs(N)?"":Ha(N),[N]),Ae=o.useMemo(()=>ze?mi(X,ze):"",[X,ze]);o.useEffect(()=>{const F=ot.current;F!==X&&($e(X.length>=F.length?"right":"left"),ot.current=X)},[X]),o.useEffect(()=>{if(!e||!Ae){D([]),U(null);return}let F=!1;return G(!0),Z(!1),U(null),au(Ae).then(Ne=>{if(F)return;Z(!1),U(null);const Ue=Ne.filter(pt=>pt.isDirectory).map(pt=>({name:pt.name,path:Ks(pt.path)})).sort((pt,L)=>pt.name.localeCompare(L.name));D(Ue)}).catch(Ne=>{if(!F){D([]);const Ue=lu(Ne)?Ne.reason:"unknown";U(Ue),Z(Ue==="not-found")}}).finally(()=>{F||G(!1)}),()=>{F=!0}},[Ae,K,e]);const je=o.useMemo(()=>{const F=be.toLowerCase(),Ne=We||be.startsWith(".");return I.filter(Ue=>Ue.name.toLowerCase().startsWith(F)&&(Ne||!Ue.name.startsWith(".")))},[be,I,We]),lt=o.useMemo(()=>xh(N),[N]),jt=o.useMemo(()=>Wa(N),[N]),it=o.useMemo(()=>{const F=[],Ne=ks(Ae);Ya(N)&&lt&&jt&&F.push({type:"parent",value:"browse:up",name:lt,path:jt,alreadyAdded:!!(Ne&&J.has(Ne))});for(const Ue of je){const pt=ks(Ue.path);F.push({type:"directory",value:`browse:${Ue.path}`,name:Ue.name,path:Ue.path,alreadyAdded:!!(pt&&J.has(pt))})}return F},[J,Ae,lt,je,jt,N]);o.useEffect(()=>{Q(0)},[N,it.length]);const xe=o.useMemo(()=>ze?Vs(mi(N,ze)):"",[ze,N]),Fe=ks(xe),Le=!!(Fe&&J.has(Fe)),Ke=o.useMemo(()=>be?je.find(F=>F.name===be)??null:null,[be,je]),kt=!!(xe&&!Le&&(te===null||te==="not-found")&&(Hs(N)&&ee||!Hs(N)&&be.trim().length>0&&Ke===null)),ht=!ae&&!Re&&!Le&&te!=="os-permission"&&te!=="invalid-response"&&te!=="unknown"&&!!xe,O=ht&&Ve.trim().length>0,ke=it[R]??null,ye=!!ke,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",V=Le?"Already added":Ye?ae?"Cloning...":"Clone & add":ae?"Adding...":kt?"Create & add":"Add folder",se=Ye?O:ht;o.useLayoutEffect(()=>{const F=A.current;F&&(F.scrollLeft=F.scrollWidth)},[N]),o.useLayoutEffect(()=>{!e||B||hr(A.current)},[e,B]),o.useLayoutEffect(()=>{const F=it[R];F&&b.current.get(F.value)?.scrollIntoView({block:"nearest"})},[R,it]);const de=o.useCallback(()=>{s(!1)},[s]),Se=o.useCallback((F,Ne)=>{a("chat"),S&&l(!1),c({selectedProjectId:F,directoryOverride:Ne}),de()},[de,S,c,a,l]),Pe=o.useCallback(async F=>{if(!F||ae)return;const Ne=ks(F);if(Ne&&J.has(Ne))return;let Ue=F;z(!0);try{const pt=!Ye&&kt&&ks(F)===ks(xe);if(Ye){const re=Ve.trim();if(!re){le.error("Enter a repository URL before cloning.");return}const me=await es("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:re,destinationPath:F,gitIdentityId:ge?.id??null})});if(!me.ok)throw new Error("Failed to clone git repository");Ue=(await me.json()).path||F}else if(pt&&!(await es("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:Ae?{directory:Ae}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const L=i(Ue);if(!L){le.error("Failed to add folder",{description:"Please select a valid directory path."});return}Se(L.id,L.path)}catch(pt){le.error("Failed to select directory",{description:pt instanceof Error?pt.message:"Unknown error occurred."})}finally{z(!1)}},[i,J,Ae,Ve,Ye,ae,Se,ge?.id,kt,xe]),He=o.useCallback(F=>{k(Wn(F))},[]),mt=o.useCallback(F=>{k(bh(N,F.name))},[N]),bt=o.useCallback(F=>{if(F){if(F.type==="parent"){He(F.path);return}mt(F)}},[He,mt]),qe=o.useCallback(async F=>{const Ne=await g(F);if(!Ne.success)return le.error("Failed to open directory",{description:Ne.error||"Desktop could not grant file access."}),!1;const Ue=ze?yh(F,ze):Wn(Ks(F));return He(Ue),!0},[He,ze,g]),dt=o.useCallback(async()=>{if(!Re){Te(!0);try{if(io()){const Ne=await ao(xe);if(!Ne.success||!Ne.path){Ne.error&&Ne.error!=="Directory selection cancelled"&&le.error("Failed to select directory",{description:Ne.error});return}await qe(Ne.path);return}const F=await cu(xe);if(F.status==="cancelled")return;if(F.status!=="picked"){le.error("Couldn't open a folder picker",{description:F.error});return}await qe(F.path)}catch(F){le.error("Failed to select directory",{description:F instanceof Error?F.message:"Unknown error occurred."})}finally{Te(!1)}}},[qe,Re,xe]),xt=o.useCallback(F=>{if(F.key==="ArrowDown"){F.preventDefault(),Q(Ne=>Math.min(it.length-1,Ne+1));return}if(F.key==="ArrowUp"){F.preventDefault(),Q(Ne=>Math.max(0,Ne-1));return}if(F.key==="Enter"){if(F.preventDefault(),vh(F)){Pe(xe);return}ye&&bt(ke);return}F.key==="Backspace"&&N===""&&(F.preventDefault(),de())},[bt,Pe,de,ye,ke,N,it.length,xe]),Me=t.jsxs("button",{type:"button",onClick:()=>Ce(F=>!F),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:[We?t.jsx(C,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(C,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Xe=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(C,{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:A,value:N,onChange:F=>k(Ks(F.target.value)),onKeyDown:xt,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Ze,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:ae||Re,onMouseDown:F=>F.preventDefault(),onClick:()=>{dt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(C,{name:"folder-open",className:"h-3.5 w-3.5"}),Re?"Opening...":"Browse"]})]})}),yt=it.some(F=>F.type==="parent"),Nt=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(Ze,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ye,disabled:ae||Re,onClick:()=>_e(F=>!F),children:[t.jsx(C,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ye?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{value:Ve,onChange:F=>Be(F.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(Ga,{activeProfile:ge,identities:q,onSelect:F=>pe(F.id),isApplying:ae,iconOnly:!0})]})]}):null,Le?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:_("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",ve==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:P?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):te&&te!=="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:te==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[te==="os-permission"&&f?t.jsx(Ze,{size:"xs",onClick:()=>{dt()},disabled:Re,children:"Grant access"}):null,t.jsx(Ze,{variant:"outline",size:"xs",onClick:()=>T(F=>F+1),children:"Try again"})]})]}):it.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:it.map((F,Ne)=>{const Ue=Ne===R,pt=F.type==="directory"&&yt;return t.jsxs("button",{ref:L=>{L?b.current.set(F.value,L):b.current.delete(F.value)},type:"button","aria-label":F.type==="parent"?F.alreadyAdded?`Go back from ${F.name}, already added`:`Go back from ${F.name}`:F.alreadyAdded?`Open ${F.name}, already added`:`Open ${F.name}`,onMouseEnter:()=>Q(Ne),onMouseDown:L=>L.preventDefault(),onClick:()=>bt(F),className:_("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Ue&&"bg-interactive-selection text-interactive-selection-foreground",!Ue&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",pt&&"pl-4"),children:[F.type==="parent"?t.jsx(C,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(C,{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:F.name})]}),F.alreadyAdded?t.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Ue?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,F.type==="parent"?t.jsx(C,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(C,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},F.value)})})},X)]})}),Pt=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Xe,Nt]}),Et=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(C,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(C,{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(C,{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(C,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),It=t.jsx(Ze,{size:S?"xs":"default",onClick:()=>{Pe(xe)},disabled:!se,className:_(S&&"w-full flex-1"),children:V}),At=()=>t.jsxs(t.Fragment,{children:[S?null:Et,t.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",S&&"justify-stretch"),children:It})]});return S?t.jsx(sa,{open:e,onClose:de,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:At()}),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}),Pt]})}):t.jsx(as,{open:e,onOpenChange:s,children:t.jsxs(ls,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(Ss,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Fs,{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:Pt}),t.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:At()})]})})},In=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Ax=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=rd,c=Oe(M=>M.deleteSessions),d=fe(M=>M.showDeletionDialog),u=fe(M=>M.setShowDeletionDialog),{isMobile:p,isTablet:h,hasTouchInput:x}=Ms(),m=p||h||x;o.useEffect(()=>uu(()=>{s(!1)}),[]);const f=o.useCallback(M=>{r({sessions:M.sessions,dateLabel:M.dateLabel})},[]),g=o.useCallback(()=>{r(null),a(!1)},[]),S=o.useCallback(async M=>{if(M.sessions.length===0)return;if(M.sessions.length===1){const D=M.sessions[0];await l(D.id)?le.success("Session deleted"):le.error("Failed to delete session");return}const N=M.sessions.map(D=>D.id),{deletedIds:k,failedIds:I}=await c(N);if(k.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:M.dateLabel?`Removed all sessions from ${M.dateLabel}.`:void 0;le.success(k.length===1?"Deleted {count} session":`Deleted ${k.length} sessions`,{description:In(D)})}I.length>0&&le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:In("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Ts.onDeleteRequest(M=>{if(!d){S(M);return}f(M)}),[f,d,S]),o.useEffect(()=>Ts.onDirectoryRequest(()=>{s(!0)}),[]);const j=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const M=n.sessions[0];if(!await l(M.id)){le.error("Failed to delete session"),a(!1);return}le.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const M=n.sessions.map(D=>D.id),N=await c(M),k=N.deletedIds,I=N.failedIds;if(k.length>0){const D=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(k.length===1?"Deleted {count} session":`Deleted ${k.length} sessions`,{description:In(D),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:In("Please try again in a moment.")}),k.length===0)){a(!1);return}}g()}finally{a(!1)}}},[n,l,c,g]),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.`:"",A=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(M=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:M.title||"Untitled Session"})},M.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,b=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(C,{name:"checkbox-blank",className:"size-4"}):t.jsx(C,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ze,{variant:"ghost",onClick:g,disabled:i,children:"Cancel"}),t.jsx(Ze,{variant:"destructive",onClick:j,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),v=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(sa,{open:!!n,onClose:()=>{i||g()},title:v,footer:t.jsx("div",{className:"flex justify-end gap-2",children:b}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[B&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:B}),A]})}):t.jsx(as,{open:!!n,onOpenChange:M=>{if(!M){if(i)return;g()}},children:t.jsxs(ls,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:v}),B&&t.jsx(Fs,{children:B})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:A}),t.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:b})]})}),t.jsx(Sh,{open:e,onOpenChange:s})]})};function Ix(){const e=o.useRef(!1),s=o.useRef(!1),n=Oe(p=>p.setCurrentSession),r=fe(p=>p.setActiveMainTab),i=fe(p=>p.setSettingsDialogOpen),a=fe(p=>p.setSettingsPage),l=fe(p=>p.navigateToDiff),c=o.useCallback(async p=>{if(!s.current){s.current=!0;try{if(p.sessionId){const h=Oe.getState().currentSessionId,x=Zs().getState().selectedSessionId;if(p.sessionId!==h||p.sessionId!==x){const m=Oe.getState().getDirectoryForSession(p.sessionId);n(p.sessionId,m)}}if(p.settingsPath){a(ih(p.settingsPath)),i(!0);return}fe.getState().isSettingsDialogOpen&&i(!1),p.tab&&r(p.tab),p.diffFile&&(p.tab==="diff"||!p.tab)&&l(p.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const p=Oe.getState(),h=Zs().getState(),x=fe.getState();return{sessionId:cr({currentSessionId:p.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:p.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=o.useCallback((p={})=>{if(s.current)return;const h=d();Kr(h,p)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Wo()))return;const p=Yo();(async()=>(await c(p),Kr({...d(),sessionId:p.sessionId??cr({currentSessionId:Oe.getState().currentSessionId,piSelectedSessionId:Zs().getState().selectedSessionId,draft:Oe.getState().newSessionDraft}),tab:p.tab??fe.getState().activeMainTab,settingsPath:p.settingsPath??fe.getState().settingsPage,diffFile:p.diffFile??fe.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const p=()=>{const S=Oe.getState(),j=Zs().getState();return cr({currentSessionId:S.currentSessionId,piSelectedSessionId:j.selectedSessionId,draft:S.newSessionDraft})};let h=p(),x=Oe.getState().newSessionDraft?.open===!0;const m=()=>{const S=Oe.getState(),j=p(),B=S.newSessionDraft?.open===!0;j===h&&B===x||s.current||(h=j,x=B,u({replace:!0}))},f=Oe.subscribe(()=>{m()}),g=Zs().subscribe(()=>{m()});return()=>{f(),g()}},[u]),o.useEffect(()=>{let p=fe.getState().activeMainTab,h=fe.getState().isSettingsDialogOpen,x=fe.getState().settingsPage,m=fe.getState().pendingDiffFile;return fe.subscribe(g=>{if(s.current)return;const S=g.activeMainTab!==p,j=g.isSettingsDialogOpen!==h,B=g.settingsPage!==x,A=g.pendingDiffFile!==m&&g.activeMainTab==="diff";p=g.activeMainTab,h=g.isSettingsDialogOpen,x=g.settingsPage,m=g.pendingDiffFile,(S||j||B||A)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const p=()=>{const h=Yo();if(Wo())c(h);else{const x=fe.getState();x.isSettingsDialogOpen&&i(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",p),()=>{window.removeEventListener("popstate",p)}},[c,r,i])}function jh(e=!0){const s=_n(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=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},p=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),m=typeof x=="number"&&Number.isFinite(x)?u(x):i;p(m)},h))};return p(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Dx(){const e=rn(s=>s.connection==="ready",void 0,"chrome");return jh(e),null}const gi=12,Ch=[{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"}],kh=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=Ch,onComplete:a})=>{const l=Je.useRef(!1);Je.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Je.useMemo(()=>Array.from({length:gi},(d,u)=>{const p=Math.PI*2*u/gi;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return e?t.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((p,h)=>{const x=p.x*d.radius,m=p.y*d.radius,f={"--translate-x":`${x}px`,"--translate-y":`${m}px`,"--particle-delay":`${p.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:f},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},Nh=({durationMs:e=3400}={})=>{const[s,n]=Je.useState({isActive:!1,cycle:0}),r=Je.useRef(null),i=Je.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Je.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Je.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 Je.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Va=o.createContext(void 0),Px=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Nh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Va.Provider,{value:a,children:[e,t.jsx(kh,{isActive:s,burstKey:n})]})},Ah={triggerFireworks:()=>{},dismissFireworks:()=>{}},Ex=()=>o.useContext(Va)??Ah,xi=380,bi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Yn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Dn=({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(C,{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})]}),Ih=({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}=to(),p=o.useRef(null),[h,x]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const f=()=>{const j=n.current?.getBoundingClientRect(),B=p.current?.getBoundingClientRect();if(!j||!B){x(null);return}const A=j.left-B.left,b=Math.min(Math.max(A,8),Math.max(8,B.width-xi-8));x(b)};f();const g=p.current;if(typeof ResizeObserver>"u"||!g)return;const S=new ResizeObserver(f);return S.observe(g),()=>S.disconnect()},[n,u,e,a]);const m=u&&h!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const f=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(f)},[e,a]),o.useEffect(()=>{if(!e)return;const f=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s,e]),o.useEffect(()=>{if(!e)return;const f=g=>{const S=g.target;if(!(S instanceof Node)){s();return}i.current?.contains(S)||n.current?.contains(S)||s()};return document.addEventListener("pointerdown",f,!0),document.addEventListener("wheel",f,!0),()=>{document.removeEventListener("pointerdown",f,!0),document.removeEventListener("wheel",f,!0)}},[n,s,e]),a?t.jsxs("div",{ref:p,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:i,role:"tooltip","aria-label":"Context usage for current conversation",className:_("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:h??8,width:`min(${xi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Dn,{iconNode:t.jsx(ra,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:_("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(Dn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Yn(r.cacheRead)})}),t.jsx(Dn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Yn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Dn,{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},Dh=o.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:i,isNewSessionDraftOpen:a}){const l=o.useRef(null),c=od(r??""),d=_t(U=>U.providers),u=_t(U=>U.currentProviderId),p=_t(U=>U.currentModelId),h=_t(U=>U.getCurrentModel()),x=_t(U=>U.getModelMetadata);_t(U=>U.modelsMetadata.size);const m=na(o.useCallback(U=>r?U.sessionModelSelections.get(r)??null:null,[r])),f=o.useMemo(()=>{for(let U=c.length-1;U>=0;U-=1){const K=c[U]?.info;if(K.role!=="user")continue;const T=K.model,R=T?.providerID??T?.providerId,Q=T?.modelID??T?.modelId,ae=typeof R=="string"&&R.trim().length>0?R:void 0,z=typeof Q=="string"&&Q.trim().length>0?Q:void 0;if(ae&&z)return{providerID:ae,modelID:z}}return null},[c]),g=o.useMemo(()=>{for(let U=c.length-1;U>=0;U-=1){const K=c[U];if(K?.info.role==="assistant"&&Vo(K).total>0)return K}return null},[c]),S=f??(()=>{const U=g?.info.model,K=U?.providerID??U?.providerId,T=U?.modelID??U?.modelId;return K&&T?{providerID:K,modelID:T}:null})()??(m?{providerID:m.providerId,modelID:m.modelId}:null)??(u&&p?{providerID:u,modelID:p}:null),B=(S?d.find(U=>U.id===S.providerID):void 0)?.models.find(U=>U.id===S?.modelID),A=S?x(S.providerID,S.modelID):void 0,b=bi(B?.limit,"context")??A?.limit?.context??bi(h?.limit,"context")??0,v=g?Vo(g):null,M=g?.info?.usage,N=M?id(M):v?.total??0,k=!a&&N>0&&b>0?Math.min(N/b*100,999):null,I=k!==null?`${Yn(N)}/${Yn(b)}`:null,D=k===null?"":k>=90?"text-[var(--status-error)]":k>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",P=v?.cacheRead??null,G=v?.cacheWrite??null,ee=v?ad({input:v.input,cache:{read:v.cacheRead,write:v.cacheWrite}}):{percent:0,hasInput:!1},Z=ee.hasInput?ee.percent:null,te=k!==null&&I?{percentage:k,tokens:I,colorClass:D,cacheRead:P,cacheWrite:G,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(U=>!U),style:{touchAction:"manipulation"},children:t.jsx(ra,{percentage:te?.percentage??0})}),t.jsx(Ih,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:te})]})}),yi=600,Ph=1,Eh=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},Th=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:i})=>{const a=o.useRef(new Map),l=o.useRef([]),c=o.useRef(new Set),d=o.useRef(0),u=!1,p=o.useCallback(f=>`${f.directory}
12
- ${f.sessionId}`,[]),h=o.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(f=>window.clearTimeout(f)),a.current.clear()},[]),x=o.useCallback(()=>{if(!(!e||u||typeof window>"u"))for(;c.current.size<Ph&&l.current.length>0;){const f=l.current.shift();if(!f)break;f.generation!==d.current||Oe.getState().currentSessionId===f.sessionId||ld(f.sessionId,f.directory).renderable}},[e,u,i,p]),m=o.useCallback(f=>{const g=f?.id,S=Eh(f);if(!e||u||!g||!S||g===s||typeof window>"u")return;const j={sessionId:g,directory:S,generation:d.current};p(j)},[s,e,u,x,p]);o.useEffect(()=>{h()},[h,s,e,u]),o.useEffect(()=>{if(!e||u||!s||n.length===0)return;const f=window.setTimeout(()=>{const g=n.findIndex(S=>S.id===s);g<0||(m(n[g-1]),m(n[g+1]))},yi);return()=>window.clearTimeout(f)},[s,e,u,m,n]),o.useEffect(()=>{if(!e||u||!s||r.length===0)return;const f=window.setTimeout(()=>{const g=r.findIndex(S=>S.id===s);g<0||(m(r[g-1]),m(r[g+1]))},yi);return()=>window.clearTimeout(f)},[s,e,u,r,m]),o.useEffect(()=>h,[h])},Rh=e=>{const s=Oe(n=>n.currentSessionId);return Th({...e,currentSessionId:s}),null},Mh=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:i,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:p}=e;o.useEffect(()=>{!n||i||!a||l||s.forEach(h=>{if(c.has(h.normalizedPath))return;const x=wa(h.normalizedPath),m=r.archivedSessionsByProject.get(h.id)??[],f=d[x]??[],g=new Map(f.map(S=>[S.name.toLowerCase(),S]));m.forEach(S=>{const j=Iu(S,h.normalizedPath),B=j.toLowerCase();let A=g.get(B);A||(A=u(x,j),g.set(B,A)),A.sessionIds.includes(S.id)||p(x,A.id,S.id)})})},[s,n,r,i,a,l,c,d,u,p])},Fh=e=>({getOrderedGroups:o.useCallback((n,r)=>{const i=e.get(n);if(!i||i.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];i.forEach(u=>{const p=a.get(u);p&&(l.push(p),a.delete(u))});const c=[],d=[];return r.forEach(u=>{a.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[e])}),Lh=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:i,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:p,filterSessionNodesForSearch:h,buildGroupSearchText:x,foldersMap:m}=e,f=o.useRef(new Map),g=o.useMemo(()=>{const N=f.current,k=new Map;let I=0,D=0;const P=(ee,Z)=>ee.length===Z.length&&ee.every((te,U)=>te===Z[U]),G=s.map(ee=>{const Z=n(ee.id),te=r(ee.id),U=a.has(ee.id)?!!a.get(ee.id):c,K=l.get(ee.id)??null,T=i.get(ee.normalizedPath)??[],R=N.get(ee.id);if(R&&R.project===ee&&P(R.activeSessions,Z)&&P(R.archivedSessions,te)&&R.rootBranch===K&&R.isRepo===U&&R.worktrees===T&&R.buildGroupedSessions===d)return I+=1,k.set(ee.id,R),R.section;D+=1;const Q=Sa([...Z,...te]),ae=d(Q,ee.normalizedPath,T,K,U),z={project:ee,groups:ae};return k.set(ee.id,{project:ee,activeSessions:Z,archivedSessions:te,rootBranch:K,isRepo:U,worktrees:T,buildGroupedSessions:d,section:z}),z});return f.current=k,I>0&&is("ui.sidebar.project_section.reused",I),D>0&&is("ui.sidebar.project_section.rebuilt",D),G},[s,n,r,i,a,c,d,l]),S=o.useMemo(()=>g,[g]),j=o.useMemo(()=>{const N=new WeakMap;if(!u)return N;const k=I=>I.reduce((D,P)=>D+1+k(P.children),0);return S.forEach(I=>{I.groups.forEach(D=>{const P=h(D.sessions,p),G=k(P),ee=x(D).includes(p),Z=Qe(D.directory??null),U=(Z?m[Z]??[]:[]).filter(K=>K.name.toLowerCase().includes(p)).length;N.set(D,{filteredNodes:P,matchedSessionCount:G,folderNameMatchCount:U,groupMatches:ee,hasMatch:ee||G>0||U>0})})}),N},[u,S,h,p,x,m]),B=o.useMemo(()=>u?S.map(N=>({...N,groups:N.groups.filter(k=>j.get(k)?.hasMatch===!0)})).filter(N=>N.groups.length>0):S,[u,S,j]),A=u?B:S,b=o.useRef(new WeakMap),v=o.useMemo(()=>{const N=b.current;return A.map(k=>{const I=N.get(k);if(I&&I.query===p)return I.section;const D=k.groups.filter(K=>!K.isArchivedBucket),P=k.groups.filter(K=>K.isArchivedBucket),G=D.flatMap(K=>u?j.get(K)?.filteredNodes??[]:K.sessions),ee=D.map(K=>({scopeKey:K.folderScopeKey??Qe(K.directory??null),directory:K.directory??null})).filter(K=>!!K.scopeKey),Z=D.find(K=>K.isMain)??null,te={id:"flat",label:Z?.label??"",branch:Z?.branch??null,description:Z?.description??null,isMain:!0,isArchivedBucket:!1,directory:Z?.directory??k.project.normalizedPath,folderScopeKey:Z?.folderScopeKey??k.project.normalizedPath,folderScopes:ee,sessions:G};if(u){const K=D.map(T=>j.get(T)).filter(T=>!!T);j.set(te,{filteredNodes:G,matchedSessionCount:K.reduce((T,R)=>T+R.matchedSessionCount,0),folderNameMatchCount:K.reduce((T,R)=>T+R.folderNameMatchCount,0),groupMatches:K.some(T=>T.groupMatches),hasMatch:K.some(T=>T.hasMatch)})}const U={project:k.project,groups:[te,...P]};return N.set(k,{query:p,section:U}),U})},[j,u,p,A]),M=o.useMemo(()=>u?A.reduce((N,k)=>N+k.groups.reduce((I,D)=>{const P=j.get(D);if(!P)return I;const G=P.folderNameMatchCount+(P.groupMatches?1:0);return I+P.matchedSessionCount+G},0),0):0,[u,A,j]);return{projectSections:g,visibleProjectSections:S,groupSearchDataByGroup:j,searchableProjectSections:B,sectionsForRender:A,flatSectionsForRender:v,searchMatchCount:M}},Oh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:i,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:p,setSessionSwitcherOpen:h}=e,x=o.useMemo(()=>{const f=new Map,g=new Map,S=(j,B,A,b)=>{f.has(j)||f.set(j,new Map);const v=f.get(j);b.forEach(M=>{const N=Qe(M.session.directory??A??B);v.set(M.session.id,{directory:N}),g.has(j)||g.set(j,{id:M.session.id,directory:N}),M.children.length>0&&S(j,B,N,M.children)})};return s.forEach(j=>{j.groups.forEach(B=>{S(j.project.id,j.project.normalizedPath,B.directory,B.sessions)})}),{metaByProject:f,firstSessionByProject:g}},[s]),m=o.useRef(null);o.useLayoutEffect(()=>{if(!n)return;if(c){m.current=n;return}if(m.current===n)return;const f=s.find(M=>M.project.id===n);if(!f)return;m.current=n;const g=x.metaByProject.get(n);if(a&&g&&g.has(a)){i(M=>{if(M.get(n)===a)return M;const N=new Map(M);return N.set(n,a),N});return}const S=a?Array.from(x.metaByProject.entries()).some(([M,N])=>M!==n&&N.has(a)):!1;if(a&&g&&!S)return;if(!g||g.size===0){p("chat"),d&&h(!1),u({selectedProjectId:f.project.id,directoryOverride:f.project.normalizedPath});return}const j=r.get(n),B=j&&g.has(j)?j:null,A=x.firstSessionByProject.get(n)?.id??null,b=B??A;if(!b||b===a)return;const v=g.get(b)?.directory??null;l(b,v,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,x,p,h,i]),o.useEffect(()=>{if(!n||!a)return;const f=x.metaByProject.get(n);!f||!f.has(a)||i(g=>{if(g.get(n)===a)return g;const S=new Map(g);return S.set(n,a),S})},[n,a,x,i])},Bh=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Oe(c=>c.currentSessionId),i=Oe(c=>!!c.newSessionDraft?.open),[a,l]=o.useState(()=>new Map(e));return Oh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:i}),o.useEffect(()=>{s(a)},[a,s]),null},vi=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],_h=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},zh=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,qa=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=_h(e.trim())%vi.length;return vi[s]},$h=(e,s)=>{const n=qa(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},wi=e=>!!e.time?.archived,Uh=e=>{const s=o.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=o.useCallback(a=>{const l=Qe(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${l}`.toLowerCase()},[]),r=o.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):a,[n]),i=o.useCallback((a,l,c=[],d,u)=>{const p=Qe(l??null),h=Sa(a).sort((N,k)=>so(N,k,e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(h.map(N=>[N.id,N])),m=new Map,f=new Map;h.forEach(N=>{const k=N.parentID??null,I=k?x.get(k):null,D=I&&wi(I)===wi(N)?k:null;m.set(N.id,D),D&&f.set(D,(f.get(D)??0)+1)});const g=c.map(N=>({worktree:N,directory:Qe(N.path)})).filter(N=>!!N.directory&&!N.worktree.isPrimary).sort((N,k)=>k.directory.length-N.directory.length),S=(N,k)=>k===N||k.startsWith(`${N}/`),j=N=>{const k=Qe(N.directory??null);return k?g.find(I=>S(I.directory,k))?.worktree??null:null},B=(N,k)=>{const I=zh(N.id,m,f);return{session:N,children:[],worktree:k,forkColorId:I}},A=[],b=new Map,v=[];for(const N of g)b.set(N.directory,[]);h.forEach(N=>{const k=j(N),I=B(N,k);N.time?.archived?v.push(I):k?b.get(Qe(k.path)??"")?.push(I):A.push(I)});const M=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:p?ti(p,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:p,folderScopeKey:p,sessions:A}];for(const{worktree:N,directory:k}of g)M.push({id:`worktree:${k}`,label:N.branch||(N.detached?"Detached HEAD":N.name),branch:N.branch,description:ti(k,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:N,directory:k,folderScopeKey:k,sessions:b.get(k)??[]});return v.length>0&&M.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:p?wa(p):null,sessions:v}),M},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:i}},Gh=({mobileVariant:e,isTablet:s})=>!e&&!s,Kh=({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])},Hh=e=>{const[s,n]=o.useState(null),r=o.useRef(null);o.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const i=o.useCallback((A,b,v)=>{Mr("navigation.session_select"),fe.getState().closeMainSurfaces();const M=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},N=v?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),A===Oe.getState().currentSessionId){e.allowReselect&&N&&e.onSessionSelected?.(A),M();return}Mr("navigation.session_state_set"),e.setCurrentSession(A,b??null),N&&e.onSessionSelected?.(A),M()},[e]),a=o.useCallback((A,b)=>{e.setEditingId(A),e.setEditTitle(b)},[e]),l=o.useCallback(async A=>{if(!e.editingId)return;const b=(A??e.editTitle).trim();b&&await e.updateSessionTitle(e.editingId,b),e.setEditingId(null),e.setEditTitle("")},[e]),c=o.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=o.useCallback(async(A,b)=>{try{return(await fn(A)).ok?(n(b),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=o.useCallback(async A=>{const b=await e.shareSession(A.id);if(!b?.share?.url){le.error("Unable to share session");return}const v=await d(b.share.url,A.id);le[v?"success":"warning"]("Session shared",{description:v?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),p=o.useCallback((A,b)=>{d(A,b).then(v=>{v||le.error("Failed to copy URL")})},[d]),h=o.useCallback(A=>{fn(A).then(b=>{if(b.ok){le.success("Session ID copied");return}le.error("Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[]),x=o.useCallback(async A=>{await e.unshareSession(A)?le.success("Session unshared"):le.error("Unable to unshare session")},[e]),m=o.useCallback(A=>{const b=[],v=M=>{(e.childrenMap.get(M)??[]).forEach(k=>{b.push(k),v(k.id)})};return v(A),b},[e.childrenMap]),f=o.useCallback((A,b)=>b?A:A.filter(v=>!v.time?.archived),[]),g=o.useCallback(async(A,b,v)=>{const M=b?.archivedBucket===!0||b?.hardDelete===!0,N=v?.descendantIds??f(m(A.id),M).map(P=>P.id);if(N.length===0){(M?await e.deleteSession(A.id):await e.archiveSession(A.id))?le.success(M?"Session deleted":"Session archived"):le.error(M?"Failed to delete session":"Failed to archive session");return}const k=[A.id,...N];if(M){const{deletedIds:P,failedIds:G}=await e.deleteSessions(k);if(G.length===0){const ee=P.length;le.success(ee===1?`Deleted ${ee} session`:`Deleted ${ee} sessions`)}else le.error("Failed to delete session");return}const{archivedIds:I,failedIds:D}=await e.archiveSessions(k);I.length>0&&le.success(I.length===1?`Archived ${I.length} session`:`Archived ${I.length} sessions`),D.length>0&&le.error(D.length===1?`Failed to archive ${D.length} session`:`Failed to archive ${D.length} sessions`)},[e,m,f]),S=o.useCallback((A,b)=>{const v=b?.archivedBucket===!0||b?.hardDelete===!0,M=f(m(A.id),v).map(N=>N.id);if(!e.showDeletionDialog||b?.skipConfirm===!0){g(A,b,{descendantIds:M});return}e.setDeleteSessionConfirm({session:A,descendantCount:M.length,descendantIds:M,archivedBucket:v})},[e,m,g,f]),j=o.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:A,archivedBucket:b,descendantIds:v}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await g(A,{archivedBucket:b},{descendantIds:v})},[e,g]),B=o.useCallback(async A=>{await e.unarchiveSession(A.id)?le.success("Session restored"):le.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:i,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:p,handleCopySessionId:h,handleUnshareSession:x,handleDeleteSession:S,handleRestoreSession:B,confirmDeleteSession:j}},Wh=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 h=d.current;if(d.current=null,c.current=null,!h)return;const{projects:x}=$t.getState(),m=x.map(f=>({...f,sidebarCollapsed:h.has(f.id)}));ro({projects:m}).catch(()=>{})},[]),p=o.useCallback(h=>{typeof window>"u"||(d.current=h,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 h=s.getItem(n.sessionExpanded);if(h){const m=JSON.parse(h);Array.isArray(m)&&a(new Set(m.filter(f=>typeof f=="string")))}const x=s.getItem(n.projectCollapse);if(x){const m=JSON.parse(x);Array.isArray(m)&&l(new Set(m.filter(f=>typeof f=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),o.useEffect(()=>{try{const h=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(h))}catch{}},[r,n.groupOrder,s]),o.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(i)))}catch{}},[i,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:p}},Yh=3;let Vn=0;const Qa=[],Vh=()=>Vn<Yh?(Vn+=1,Promise.resolve()):new Promise(e=>{Qa.push(e)}),qh=()=>{const e=Qa.shift();if(e){e();return}Vn=Math.max(0,Vn-1)},Qh=async e=>{await Vh();try{return await e()}finally{qh()}},Jh=5*6e4,Xh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:i,setProjectRootBranches:a}=e,{git:l}=Jn(),c=oa(h=>h.ensureStatus);o.useEffect(()=>{if(!n||!l||s.length===0){i(new Map);return}s.forEach(h=>{Qh(()=>c(h.normalizedPath,l))})},[n,s,l,c,i]),o.useEffect(()=>{if(!n)return;const h=new Map;s.forEach(x=>{h.set(x.id,r.get(x.normalizedPath)?.isGitRepo??null)}),i(h)},[n,s,r,i]);const d=o.useMemo(()=>s.map(h=>{const x=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${x}`}).join("|"),[s,r]),u=o.useRef(new Map),p=o.useRef(new Map);o.useEffect(()=>{if(!n)return;let h=!1;const x=setTimeout(()=>{(async()=>{const f=new Set(s.map(A=>A.id));for(const A of u.current.keys())f.has(A)||(u.current.delete(A),p.current.delete(A));const g=Date.now();if(s.filter(A=>{const b=r.get(A.normalizedPath);if(b?.isGitRepo===!1)return u.current.delete(A.id),p.current.delete(A.id),!1;if(b?.isGitRepo!==!0||b.branch===null)return!1;const v=b.branch.trim(),M=`${A.normalizedPath}\0${v}`,N=u.current.get(A.id);if(N===M){const k=p.current.get(A.id);return k&&(k.at=g),!1}return!(N!==void 0&&g-(p.current.get(A.id)?.at??0)<Jh)}).length===0)return;const j=[];if(s.forEach(A=>{const b=r.get(A.normalizedPath)?.branch?.trim()??"",v=`${A.normalizedPath}\0${b}`;b&&j.push({id:A.id,inputKey:v,branch:b})}),h||j.length===0)return;const B=Date.now();a(A=>{const b=new Map(A);return j.forEach(({id:v,branch:M})=>{M&&b.set(v,M)}),b}),j.forEach(({id:A,inputKey:b,branch:v})=>{u.current.set(A,b),v&&p.current.set(A,{branch:v,at:B})})})()},150);return()=>{h=!0,clearTimeout(x)}},[n,s,d,r,a])},Zh=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}},ep=e=>{if(e.runtimeKey!==Zn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=fu(e.sessionId,e.directory,e.runtimeKey);s&&hu.getState().clearQueue(s),cd.getState().clearSessionTodos(e.runtimeKey,e.directory,e.sessionId),Wt.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),ia.getState().clearSessionDrafts(e.runtimeKey,e.directory,e.sessionId),Tr.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=dd(e.runtimeKey,e.directory,e.sessionId);n&&ud(n,!0)},tp=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},sp=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,i)=>{s.has(i)||n.push(r)}),n},np=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,i=o.useRef(null);o.useEffect(()=>{if(!s||!n)return;const a=Zn(),l=tp(r),c=i.current?.runtimeKey===a?i.current.identities:null;for(const d of sp(c,l))ep({runtimeKey:a,...d});i.current={runtimeKey:a,identities:l}},[s,n,r])},rp=(e,s)=>e?s.kind!==e.kind?s.kind==="project":s.projectRoot.length!==e.projectRoot.length?s.projectRoot.length>e.projectRoot.length:s.projectId.localeCompare(e.projectId)<0:!0,Si=(e,s,n)=>{rp(e.get(s),n)&&e.set(s,n)},Ja=e=>{const s=e;return Qe(s.directory)??Qe(s.project?.worktree)},op=(e,s,n)=>{if(e.time?.archived)return!0;const r=Ja(e);if(!r)return n?.allowUnknownDirectory??!0;if(Xn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const i=r.toLowerCase();for(const a of s)if(Qe(a)?.toLowerCase()===i)return!0;return!1},ip=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)},ap=(e,s,n,r=[])=>{const i=new Map,a=new Map;for(const m of s){const f=Qe(m.normalizedPath);if(!f)continue;const g=a.get(f);(!g||m.id.localeCompare(g.id)<0)&&a.set(f,m),Si(i,f,{projectId:m.id,projectRoot:f,scopeDirectory:f,kind:"project"})}if(n)for(const[m,f]of n){const g=Qe(m),S=g?a.get(g):void 0;if(!(!S||!g))for(const j of f||[]){const B=Qe(j?.path);B&&Si(i,B,{projectId:S.id,projectRoot:g,scopeDirectory:B,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,p=new Map,h=m=>{if(!m)return null;if(l.has(m))return l.get(m)??null;const f=[];let g=m,S=null;for(;g;){if(l.has(g)){S=l.get(g)??null;break}if(f.push(g),S=i.get(g)??null,S)break;g=ip(g)}for(const j of f)l.set(j,S);return S},x=(m,f,g)=>{for(const S of m){const j=Ja(S);if(Xn(j))continue;const B=h(j);if(!B)continue;c.set(S.id,B);const A=f.get(B.projectId);if(A?A.push(S):f.set(B.projectId,[S]),!g)continue;const b=g.get(B.scopeDirectory);b?b.add(S.id):g.set(B.scopeDirectory,new Set([S.id]))}};return x(e,d,p),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:p,directoryResolutions:l.size}},lp=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(as,{open:e,onOpenChange:s,children:t.jsx(ls,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(Is,{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(Xf,{project:n,onIdentitySave:r}):null})})})});function Xa({state:e,activeLabel:s,unreadLabel:n,className:r}){return e==="unread"?t.jsx("span",{className:_("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:_("inline-flex items-center",r),"aria-label":s,title:s,children:t.jsx(gn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const cp=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:i,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:p,groupDirectory:h,projectId:x,mobileVariant:m=!1,alwaysShowActions:f=m,isRenaming:g=!1,renameDraft:S="",onRenameDraftChange:j,onRenameSave:B,onRenameCancel:A,droppableRef:b,isDropTarget:v=!1,onNewSession:M,depth:N=0,hideActions:k=!1,archivedBucket:I=!1})=>{const[D,P]=o.useState(!1),[G,ee]=o.useState(""),Z=o.useRef(null),te=g||D,U=g?S:G,K=o.useCallback(()=>{ee(e.name),P(!0)},[e.name]),T=o.useCallback(()=>{const z=U.trim();z&&z!==e.name&&c(z),g&&B&&B(),P(!1),ee("")},[U,e.name,g,c,B]),R=o.useCallback(()=>{g&&A&&A(),P(!1),ee("")},[g,A]),Q=o.useCallback(z=>{g&&j?j(z):ee(z)},[g,j]);o.useEffect(()=>{if(!g)return;const z=()=>{const Ye=Z.current;Ye&&(Ye.focus(),Ye.select())},Re=requestAnimationFrame(z),Te=window.setTimeout(z,0);return()=>{cancelAnimationFrame(Re),window.clearTimeout(Te)}},[g]);const ae=i?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:b,className:_("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",v&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:te?void 0:z=>{z.currentTarget.blur(),l()},role:te?void 0:"button",tabIndex:te?void 0:0,onKeyDown:te?void 0:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),l())},"aria-label":i?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[t.jsxs("div",{className:_("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",I?f?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":f?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(C,{name:ae,className:_(On,v?"text-primary":"text-muted-foreground")}),te?t.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),onSubmit:z=>{z.preventDefault(),T()},children:[t.jsx("input",{ref:Z,value:U,onChange:z=>Q(z.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:z=>z.stopPropagation(),onPointerDown:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),onKeyDown:z=>{if(z.key==="Escape"){z.stopPropagation(),R();return}(z.key===" "||z.key==="Enter")&&z.stopPropagation()}}),t.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:z=>z.stopPropagation(),onPointerDown:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),children:t.jsx(C,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),R()},onPointerDown:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(C,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("span",{className:_(ja,v?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(rt,{side:"right",sideOffset:8,className:"max-w-xs",children:s??e.name})]}),t.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),a?t.jsx(Xa,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,i?t.jsx(C,{name:"arrow-right-s",className:_(On,"text-muted-foreground")}):t.jsx(C,{name:"arrow-down-s",className:_(On,"text-muted-foreground")})]})]}),!te&&(!k||I)?t.jsx("div",{className:_("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",f?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:t.jsxs("div",{className:"flex items-center gap-0.5",children:[!I&&M?t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),M()},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(C,{name:"add",className:"size-4"})}):null,I?null:t.jsx("button",{type:"button",onClick:z=>{z.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(C,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:z=>{z.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(C,{name:"delete-bin",className:"size-4"})})]})}):null]}),i?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(z=>t.jsx(o.Fragment,{children:u(z,0,h??null,x??null,I,void 0,"project",p?.(z))},z.session.id)):r?null:t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},dp=o.memo(cp),up=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:i,listeners:a,setNodeRef:l,isDragging:c}=Vu({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})},fp=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=qu({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},hp=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const i=tr(pn(uo,{activationConstraint:{distance:8}})),[a,l]=o.useState(null),[c,d]=o.useState("Session"),[u,p]=o.useState(null),[h,x]=o.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const m=f=>{l(null),p(null),x(null);const{active:g,over:S}=f;if(!S)return;const j=g.data.current,B=S.data.current;j?.type==="session"&&j.sessionId&&B?.type==="folder"&&B.folderId&&n(j.sessionId,B.folderId)};return t.jsxs(sr,{sensors:i,collisionDetection:nr,onDragStart:f=>{const g=f.active.data.current;if(g?.type==="session"&&g.sessionId){l(g.sessionId),d(g.sessionTitle??"Session");const S=f.active.rect.current.initial?.width,j=f.active.rect.current.initial?.height;p(typeof S=="number"?S:null),x(typeof j=="number"?j:null)}},onDragCancel:()=>{l(null),p(null),x(null)},onDragEnd:m,children:[r,t.jsx(Da,{children:a&&s?t.jsxs("div",{style:{width:u?`${u}px`:"auto",height:h?`${h}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(C,{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})]})},zn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),i=r.length;if(i===0)return e;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(e.slice(l,c));const d=e.slice(c,c+i);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+i,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e},Es=({icon:e,children:s,onClick:n,className:r,mobileVariant:i=!1})=>t.jsxs("button",{type:"button",onClick:n,className:_(i?Du:Pu,r),children:[t.jsx(C,{name:e,className:_(ln(i),"text-muted-foreground")}),t.jsx("span",{className:_(cn(i),"flex-1 text-muted-foreground"),children:s})]}),ji=(e,s,n)=>{if(!s)return;const r=i=>{let a=i.session.id===s;for(const l of i.children)a=r(l)||a;return a&&n.add(i.session.id),a};for(const i of e)r(i)},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},pp=(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}))},mp=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const i=new Set;let a=r.session.parentID??null;for(;a&&!i.has(a);){if(n.has(a)&&s.has(a))return!1;i.add(a),a=s.get(a)?.session?.parentID??null}return!0})},Ci=new WeakMap;let ki=1;const gp=e=>{const s=Ci.get(e);if(s!==void 0)return s;const n=ki;return ki+=1,Ci.set(e,n),n},qr=e=>e.children.length===0?"":e.children.map(n=>{const r=gp(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${qr(n)}`}).join("|"),Za=(e,s,n,r,i,a)=>{const l=Zn(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const p=d.session.directory??i,h=u.session.directory??a,x=qo(l,p??"",d.session.id),m=qo(l,h??"",u.session.id);return(x?n.has(x):!1)!==(m?r.has(m):!1)?!0:d.children.some((f,g)=>c(f,u.children[g]))};return c(e,s)},qn=(e,s,n,r)=>{if(!s)return null;const i=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${i}:${c.session.id}`===s)return a=c.session.id,!0;for(const u of c.children)if(l(u))return!0;return!1};return e.forEach(c=>l(c)),a},el=(e,s)=>"",xp=ps(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),bp=e=>null,bo=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,tl=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let i=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(i="unread");for(const l of e.children)if(i=bo(i,tl(l,s,n,r)),i==="active")return i;return i},Ni=(e,s,n,r)=>{let i=null;for(const a of e)if(i=bo(i,tl(a,s,n,r)),i==="active")return i;return i},yp=50,vp=28,Pn=(e,s)=>s?e.sessions.some(n=>fs(n,s)):!1,wp=(e,s,n)=>e.sessions.some(r=>Za(r,r,s,n,e.directory,e.directory)),Sp=(e,s,n)=>{const r=i=>{const a=i.session.id;return s.get(a)!==n.get(a)?!0:i.children.some(r)};return e.sessions.some(r)},Ai=(e,s,n)=>{const r=i=>s.has(i.session.id)!==n.has(i.session.id)?!0:i.children.some(r);return e.sessions.some(r)},jp=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},Cp=(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)},kp=(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&&wp(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&Cp(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&Sp(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(Pn(e.group,e.editingId)||Pn(s.group,s.editingId))||e.editTitle!==s.editTitle&&(Pn(e.group,e.editingId)||Pn(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=qn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=qn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&Ai(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&Ai(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&jp(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 Np(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:i,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:p,collapsedFolderIds:h,toggleFolderCollapse:x,renameFolder:m,deleteFolder:f,showDeletionDialog:g,setDeleteFolderConfirm:S,renderSessionNode:j,showMoreGroupSessions:B,resetGroupSessionLimit:A,mobileVariant:b,alwaysShowActions:v,activeProjectId:M,setActiveProjectIdOnly:N,setActiveMainTab:k,setSessionSwitcherOpen:I,openNewSessionDraft:D,addSessionToFolder:P,createFolderAndStartRename:G,renamingFolderId:ee,renameFolderDraft:Z,setRenameFolderDraft:te,setRenamingFolderId:U,pinnedSessionIds:K,expandedParents:T,sessionOrderIndex:R,editingId:Q,openSidebarMenuKey:ae,activeActivitySessionIds:z,unreadActivitySessionIds:Re,notifyOnSubtasks:Te,onToggleCollapsedGroup:Ye,dragHandleProps:_e,compactBodyPadding:Ve=!1,scrollContainerRef:Be}=e,ie=o.useCallback((H,ne)=>{const oe=R.get(H.session.id),ce=R.get(ne.session.id);if(oe!==void 0||ce!==void 0){if(oe===void 0)return 1;if(ce===void 0)return-1;if(oe!==ce)return oe-ce}return so(H.session,ne.session,K,aa)},[K,R]),pe=a?c.get(s):null,We=Wt(H=>H.foldersMap),Ce=a?!1:u.has(n);o.useMemo(()=>{if(s.isMain||s.isArchivedBucket||i)return null;const H=Qe(s.directory??null),ne=s.branch?.trim();return H&&ne?el():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,i]);const ve=la(),$e=o.useMemo(()=>{const H=s.folderScopes?.map(ne=>Qe(ne.directory))??[Qe(s.directory??null)];return[...new Set(H.filter(ne=>!!ne))]},[s.directory,s.folderScopes]);o.useSyncExternalStore(o.useCallback(H=>$e.length>0?ve.subscribeBootstrap(H):()=>{},[$e.length,ve]),o.useCallback(()=>$e.map(H=>`${H}\0${ve.getBootstrapState(H)??""}\0${ve.getBootstrapFailure(H)??""}`).join(""),[$e,ve]),o.useCallback(()=>"",[]));const ot=$e.some(H=>{const ne=ve.getBootstrapState(H);return ne==="queued"||ne==="running"}),ze=$e.find(H=>ve.getBootstrapState(H)==="failed")??null,J=ze?ve.getBootstrapFailure(ze):void 0,q=J==="os-permission"&&io(),[ge,X]=o.useState(!1),be=o.useCallback(()=>{ze&&ve.requestBootstrap({directory:ze,priority:Ce?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[ve,ze,s.isMain,Ce]),Ae=o.useCallback(async()=>{if(!(!ze||!q||ge)){X(!0);try{(await ao(ze)).success&&be()}finally{X(!1)}}},[q,ze,ge,be]),je=p?10:5,lt=Math.max(je,d??je),jt=a?pe?.groupMatches===!0:!1,it=a,xe=o.useMemo(()=>[...it?pe?.filteredNodes??[]:s.sessions].sort(ie),[ie,s.sessions,pe?.filteredNodes,it]),Fe=s.folderScopeKey??Qe(s.directory??null),Le=o.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:Fe?[{scopeKey:Fe,directory:s.directory??null}]:[],[Fe,s.directory,s.folderScopes]),Ke=o.useMemo(()=>Le.flatMap(({scopeKey:H,directory:ne})=>(We[H]??[]).map(oe=>({folder:oe,scopeKey:H,scopeDirectory:ne}))),[Le,We]),kt=o.useMemo(()=>{const H=new Map,ne=oe=>{oe.forEach(ce=>{H.set(ce.session.id,ce),ce.children.length>0&&ne(ce.children)})};return ne(xe),H},[xe]),ht=o.useMemo(()=>Ke.map(({folder:H,scopeKey:ne,scopeDirectory:oe})=>{const ce=mp(H.sessionIds,kt).sort(ie);return{folder:H,scopeKey:ne,scopeDirectory:oe,nodes:ce}}),[Ke,kt,ie]),O=o.useMemo(()=>{const H=new Map(ht.map(he=>[he.folder.id,he])),ne=new Map;for(const{folder:he}of ht){if(!he.parentId)continue;const ft=ne.get(he.parentId);ft?ft.push(he.id):ne.set(he.parentId,[he.id])}const oe=new Map,ce=he=>{const ft=oe.get(he);if(ft!==void 0)return ft;const Mt=H.get(he);if(!Mt)return oe.set(he,!1),!1;const vt=ne.get(he)??[];if(s.isArchivedBucket&&Mt.nodes.length===0){const Tt=vt.some(ns=>ce(ns));return oe.set(he,Tt),Tt}if(!a||Mt.folder.name.toLowerCase().includes(l)||Mt.nodes.length>0)return oe.set(he,!0),!0;const Ht=vt.some(Tt=>ce(Tt));return oe.set(he,Ht),Ht};return ht.filter(({folder:he})=>ce(he.id))},[ht,s.isArchivedBucket,a,l]),ke=o.useMemo(()=>new Set(O.flatMap(H=>H.folder.sessionIds)),[O]),ye=o.useMemo(()=>xe.filter(H=>!ke.has(H.session.id)),[xe,ke]),w=o.useMemo(()=>O.filter(({folder:H})=>!H.parentId),[O]),V=o.useMemo(()=>{const H=new Map;return O.forEach(ne=>{if(!ne.folder.parentId)return;const oe=H.get(ne.folder.parentId)??[];oe.push(ne),H.set(ne.folder.parentId,oe)}),H},[O]),se=o.useMemo(()=>{const H=new Map(O.map(ce=>[ce.folder.id,ce])),ne=new Map,oe=(ce,he)=>{const ft=ne.get(ce);if(ft!==void 0)return ft;if(he.has(ce))return null;he.add(ce);const Mt=H.get(ce);let vt=Mt?Ni(Mt.nodes,z,Re,Te):null;for(const Kt of V.get(ce)??[])if(vt=bo(vt,oe(Kt.folder.id,he)),vt==="active")break;return ne.set(ce,vt),vt};return O.forEach(({folder:ce})=>oe(ce.id,new Set)),ne},[z,O,V,Te,Re]),de="project",Se=o.useMemo(()=>{const H=new Set;return ji(xe,Q,H),O.forEach(({nodes:ne})=>{ji(ne,Q,H)}),H},[xe,O,Q]),Pe=o.useMemo(()=>{if(!ae)return null;const H=qn(xe,ae,de,!!s.isArchivedBucket);if(H)return H;for(const{nodes:ne}of O){const oe=qn(ne,ae,de,!!s.isArchivedBucket);if(oe)return oe}return null},[ae,xe,O,s.isArchivedBucket]),He=o.useCallback(H=>{const ne=new WeakMap,oe=ce=>{ne.set(ce,qr(ce));for(const he of ce.children)oe(he)};return H.forEach(oe),ne},[]),mt=o.useMemo(()=>He(xe),[He,xe]),bt=o.useMemo(()=>{const H=new WeakMap;return O.forEach(({nodes:ne})=>{ne.forEach(oe=>H.set(oe,qr(oe)))}),H},[O]),qe=o.useCallback(H=>mt.get(H)??bt.get(H)??"",[mt,bt]),dt=o.useCallback(H=>({subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:qe(H)}),[Se,Pe,qe]),xt=ye.length,Me=s.isArchivedBucket||a?ye:ye.slice(0,lt),Xe=xt-Me.length,yt=!s.isArchivedBucket&&!a&&xt>je&&Xe===0,Nt=s.isArchivedBucket===!0&&!a&&Me.length>=yp,Pt=s.isArchivedBucket?"archived":"active",Et=Nt&&Me.some(H=>{if(H.children.length===0)return!1;const ne=`project:${Pt}:${H.session.id}`;return T.has(ne)}),It=o.useRef(null),[At,F]=o.useState(null),[Ne,Ue]=o.useState(0),[,pt]=o.useState(0);o.useEffect(()=>{if(!Nt)return;const H=It.current;if(!H||typeof ResizeObserver>"u")return;const ne=new ResizeObserver(()=>pt(oe=>oe+1));return ne.observe(H),()=>ne.disconnect()},[Nt]),o.useLayoutEffect(()=>{if(!Nt){At!==null&&F(null),Ne!==0&&Ue(0);return}const H=It.current;if(!H)return;let ne=At;const oe=Be?.current??null;if(oe&&oe.contains(H)){if(ne=oe,ne!==At){F(ne);return}}else if(!ne||!ne.contains(H)){let he=H.parentElement;for(;he;){const ft=window.getComputedStyle(he);if(ft.overflowY==="auto"||ft.overflowY==="scroll"){ne=he;break}he=he.parentElement}if(ne!==At){F(ne);return}}if(!ne)return;const ce=H.getBoundingClientRect().top-ne.getBoundingClientRect().top+ne.scrollTop;Ue(he=>Math.abs(he-ce)<1?he:ce)});const L=Nt&&At!==null,re=Yu({count:Me.length,enabled:L,getScrollElement:()=>At,initialOffset:()=>At?.scrollTop??0,estimateSize:()=>vp,overscan:Et?20:8,scrollMargin:Ne,getItemKey:H=>Me[H]?.session.id??H}),me=o.useCallback(H=>{const ne=[],oe=ce=>{ce.forEach(he=>{ne.push(he.session),he.children.length>0&&oe(he.children)})};return oe(H),ne},[]),tt=o.useMemo(()=>me(xe),[me,xe]),we=o.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const H=new Map,ne=new Map;for(const{folder:ce}of O){if(!ce.parentId)continue;const he=ne.get(ce.parentId)??[];he.push(ce.id),ne.set(ce.parentId,he)}const oe=(ce,he)=>{if(he.has(ce))return[];he.add(ce);const ft=O.find(({folder:Kt})=>Kt.id===ce),Mt=ft?me(ft.nodes):[],vt=ne.get(ce)??[];for(const Kt of vt)Mt.push(...oe(Kt,he));return Mt};for(const{folder:ce}of O)H.set(ce.id,oe(ce.id,new Set));return H},[O,me,s.isArchivedBucket]);if(a&&!jt&&w.length===0&&ye.length===0)return null;const et=!s.isMain&&!!s.branch,ut=s.branch&&Eu(s.branch,s.label)?{label:s.branch}:null,Ot=Ce?Ni(xe,z,Re,Te):null,Ut=Ot?t.jsx(Xa,{state:Ot,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,Rt=(H,ne)=>{const{folder:oe,scopeKey:ce,scopeDirectory:he,nodes:ft}=H,Mt=we.get(oe.id)??[],vt=a?!1:h.has(oe.id);return t.jsx(fp,{folderId:oe.id,children:(Kt,Ht)=>t.jsx(dp,{folder:oe,displayName:ne,sessions:ft,isCollapsed:vt,collapsedActivityState:vt?se.get(oe.id)??null:null,onToggle:()=>x(oe.id),onRename:Tt=>{m(ce,oe.id,Tt)},onDelete:()=>{if(s.isArchivedBucket){Ts.requestDelete({sessions:Mt,mode:"session"});return}if(!g){f(ce,oe.id);return}const Tt=O.filter(({folder:cs})=>cs.parentId===oe.id).length,ns=ft.length;S({scopeKey:ce,folderId:oe.id,folderName:oe.name,subFolderCount:Tt,sessionCount:ns})},renderSessionNode:j,getRenderExtras:qe?Tt=>({subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:qe(Tt),childRenderExtrasFor:dt}):void 0,groupDirectory:he??s.directory,projectId:r,mobileVariant:b,alwaysShowActions:v,isRenaming:ee===oe.id,renameDraft:ee===oe.id?Z:void 0,onRenameDraftChange:Tt=>te(Tt),onRenameSave:()=>{const Tt=Z.trim();Tt&&m(ce,oe.id,Tt),U(null),te("")},onRenameCancel:()=>{U(null),te("")},droppableRef:Kt,isDropTarget:Ht,depth:0,onNewSession:()=>{r&&r!==M&&N(r),k("chat"),b&&I(!1),D({selectedProjectId:r,directoryOverride:he??s.directory,targetFolderId:oe.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},oe.id)},Gt=()=>{const H=new Map;for(const ce of O){const he=ce.folder.parentId;if(!he)continue;const ft=H.get(he);ft?ft.push(ce):H.set(he,[ce])}const ne=[],oe=(ce,he)=>{const ft=he?`${he} / ${ce.folder.name}`:ce.folder.name;ne.push(Rt(ce,ft)),!(!a&&h.has(ce.folder.id))&&(H.get(ce.folder.id)??[]).forEach(vt=>oe(vt,ft))};return w.forEach(ce=>oe(ce,"")),ne},Ft=v?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",gt=ze?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[J==="os-permission"?"Folder access is required.":"Could not refresh sessions.",q?t.jsx(Ze,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:ge,onClick:()=>{Ae()},children:"Grant access"}):null,t.jsx(Ze,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:be,children:"Try again"})]}):null,Bt=t.jsxs(hp,{scopeKey:Le[0]?.scopeKey??Fe,hasFolders:O.length>0,onSessionDroppedOnFolder:(H,ne)=>{const oe=O.find(({folder:he})=>he.id===ne);if(!oe)return;const ce=Wt.getState();for(const{scopeKey:he}of Le)he!==oe.scopeKey&&ce.getSessionFolderId(he,H)&&ce.removeSessionFromFolder(he,H);P(oe.scopeKey,ne,H)},children:[Gt(),Nt?t.jsx("div",{ref:It,children:L?t.jsx("div",{style:{height:re.getTotalSize(),position:"relative"},children:re.getVirtualItems().map(H=>{const ne=Me[H.index];return ne?t.jsx("div",{"data-index":H.index,ref:re.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${H.start-Ne}px)`},children:j(ne,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:qe(ne),childRenderExtrasFor:dt})},ne.session.id):null})}):Me.map(H=>t.jsx(o.Fragment,{children:j(H,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:qe(H),childRenderExtrasFor:dt})},H.session.id))}):Me.map(H=>t.jsx(o.Fragment,{children:j(H,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Se,menuOpenSessionId:Pe,nodeStructureKey:qe(H),childRenderExtrasFor:dt})},H.session.id)),xt===0&&O.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."}):ot?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(C,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):gt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:gt}):t.jsx(Es,{icon:"chat-new",onClick:()=>{D({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,xt>0&&gt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:gt}):null,Xe>0?t.jsx(Es,{icon:"arrow-down-s",onClick:()=>B(n,Me.length),children:Xe===1?"Show 1 more session":`Show ${Xe} more sessions`}):null,yt?t.jsx(Es,{icon:"arrow-up-s",onClick:()=>A(n),children:"Show fewer sessions"}):null]});return i?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:Bt})}):t.jsxs("div",{className:"oc-group",children:[t.jsxs("div",{className:_("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>Ye(n),role:"button",tabIndex:0,onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),Ye(n))},"aria-label":Ce?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!Ce,children:[t.jsx("div",{ref:_e?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",Ft),..._e?.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(C,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",v?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",v?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ce?t.jsx(C,{name:"arrow-right-s",className:"size-4"}):t.jsx(C,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:zn(s.label,l)}),Ut]}):!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(C,{name:"git-branch",className:_("size-4 shrink-0","text-muted-foreground",v?"hidden":"group-hover/gh:hidden"),style:void 0}),t.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",v?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ce?t.jsx(C,{name:"arrow-right-s",className:"size-4"}):t.jsx(C,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:zn(s.label,l)}),Ut,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:zn(s.label,l)}),Ut]})}),et&&ut?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[s.isArchivedBucket?t.jsx(C,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(C,{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:ut.label})]}):null]})}),s.isArchivedBucket&&tt.length>0?t.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",v?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:H=>{H.stopPropagation(),Ts.requestDelete({sessions:tt,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(C,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,s.directory?t.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",v?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:H=>{H.stopPropagation(),r&&r!==M&&N(r),k("chat"),b&&I(!1),D({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(C,{name:"add",className:"h-4 w-4"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]}),Ce?null:t.jsx("div",{className:"oc-group-body",children:Bt})]})}const Ap=o.memo(Np,kp);function Ip(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:i,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:p,setIsSessionSearchOpen:h,sessionSearchInputRef:x,sessionSearchQuery:m,setSessionSearchQuery:f,hasSessionSearchQuery:g,searchMatchCount:S,selectionModeEnabled:j,onToggleSelectionMode:B,mobileVariant:A=!1}=e;if(s)return null;const b=_(u,"text-muted-foreground hover:text-foreground",!A&&"hover:bg-transparent");return t.jsx("div",{className:_("select-none flex-shrink-0",A?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:_("flex flex-col",A?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:_("flex items-center justify-between",A?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:_("flex min-w-0 items-center",A?"gap-0.5 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":A?"true":void 0,children:[i?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:b,"aria-label":"Settings",children:t.jsx(C,{name:"settings-3",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!A&&a?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:b,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(C,{name:"server",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:b,"aria-label":"Update",children:t.jsx(C,{name:"download",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,A?null:t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:b,"aria-label":"Add project",children:t.jsx(C,{name:"folder-add",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),A?null:t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:b,"aria-label":"Archive",children:t.jsx(C,{name:"archive",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:_("flex shrink-0 items-center",A?"gap-0.5":"gap-1.5"),children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>h(v=>!v),className:b,"aria-label":"Search sessions","aria-expanded":p,children:t.jsx(C,{name:"search",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:B,className:_(b,j&&"bg-interactive-hover text-primary"),"aria-label":j?"Exit selection":"Select sessions","aria-pressed":j,children:t.jsx(C,{name:"checkbox-multiple",className:d})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:j?"Exit selection":"Select sessions"})})]})]})]}),p?t.jsxs("div",{className:_(A?"pb-2":"pb-1"),children:[t.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:g?t.jsx("span",{children:S===1?`${S} match`:`${S} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(C,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{ref:x,value:m,onChange:v=>f(v.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:v=>{v.key==="Escape"&&(v.stopPropagation(),g?f(""):h(!1))}}),m.length>0?t.jsx("button",{type:"button",onClick:()=>f(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:t.jsx(C,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function Dp(e){const s=fe(i=>i.toggleSidebar),n=fe(i=>i.shortcutOverrides),r=lo(on("toggle_sidebar",n));return t.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${ri})`}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${ri})))`}}),t.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsxs("button",{type:"button",onClick:e.onNewSession,className:_("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(C,{name:"chat-new",className:_(On,"text-current")}),t.jsx("span",{className:ja,children:"New session"})]}),e.showSidebarToggle?t.jsxs(st,{children:[t.jsx(nt,{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(C,{name:"layout-left",className:"size-4"})})}),t.jsx(rt,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Pp=500,$n=(e,s)=>_("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"),Ep=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:i,worktreeError:a,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:p,mobileVariant:h=!1})=>{const{listeners:x,setNodeRef:m,transform:f,transition:g,isDragging:S}=ho({id:e.id,disabled:!c}),[j,B]=o.useState(!1),A=o.useRef(null),b=o.useCallback(()=>{A.current!==null&&(window.clearTimeout(A.current),A.current=null)},[]);o.useEffect(()=>()=>b(),[b]);const v=o.useCallback(()=>{b(),A.current=window.setTimeout(()=>{A.current=null,B(!0)},Pp)},[b]);return t.jsx("div",{ref:m,style:{transform:po.Translate.toString(f),transition:g},className:_(S&&"opacity-60"),children:t.jsxs(Zf,{open:j,onOpenChange:B,children:[t.jsxs(eh,{render:t.jsx("button",{type:"button",onClick:()=>{j||d()},onTouchStart:v,onTouchMove:b,onTouchEnd:b,onTouchCancel:b,style:{touchAction:"manipulation"},className:$n(h,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:_("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${s}`:void 0,...c?x:{},children:t.jsx(C,{name:"folder",className:_(ln(h),"text-muted-foreground")})}),t.jsx("span",{className:cn(h),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(gn,{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(C,{name:"error-warning",className:"size-4 text-[var(--status-warning-foreground)]"})}):null,i?t.jsx(C,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(th,{className:"min-w-[160px]",children:[t.jsxs(hi,{onClick:()=>u(e.id),children:[t.jsx(C,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(sh,{}),t.jsxs(hi,{onClick:()=>p(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(C,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},Tp=({projects:e,selectedProjectId:s,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:i=new Map,onSelectProject:a,onSelectWorktree:l,onOpenDirectoryDialog:c,onOpenProjectEditDialog:d,onRemoveProject:u,hasActiveSessionByProject:p,activeDirectoriesByProject:h,homeDirectory:x,className:m,mobileVariant:f=!1})=>{const g=s===null,S=$t(b=>b.reorderProjects),j=e.length>1,B=tr(pn(Ju,{activationConstraint:{distance:8}}),pn(Qu,{activationConstraint:{delay:200,tolerance:6}})),A=o.useCallback(b=>{const{active:v,over:M}=b;if(!M||v.id===M.id)return;const N=$t.getState().projects,k=N.findIndex(D=>D.id===v.id),I=N.findIndex(D=>D.id===M.id);k<0||I<0||S(k,I)},[S]);return t.jsxs("div",{className:_("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:$n(f,g),"aria-pressed":g,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(C,{name:"chat-history",className:ln(f)}),t.jsx("span",{className:cn(f),children:"All sessions"})]})}),t.jsx(sr,{sensors:B,collisionDetection:nr,onDragEnd:A,children:t.jsx(fo,{items:e.map(b=>b.id),strategy:Pa,children:e.map(b=>{const v=s===b.id,M=v&&!n,N=r.get(b.normalizedPath)??[],k=er(b.label?.trim()||Rs(b.normalizedPath,x)||b.normalizedPath),I=h?.get(b.id),D=Qe(b.normalizedPath)?.toLowerCase()??"",P=D?I?.has(D)??!1:!1,G=(I?.size??0)>0,ee=p?.(b.id)??!1,Z=h?v?P:G:ee;return t.jsxs(o.Fragment,{children:[t.jsx(Ep,{project:b,label:k,isSelected:M,hasActive:Z,hasWorktrees:N.length>0,worktreeError:i.get(b.normalizedPath),isExpanded:v,canDrag:j,onSelect:()=>a(b.id),onOpenProjectEditDialog:d,onRemoveProject:u,mobileVariant:f}),v?N.map(te=>{const U=n===te.path,K=Qe(te.path)?.toLowerCase()??"",T=K?I?.has(K)??!1:!1,R=h?T:!1;return t.jsxs("button",{type:"button",onClick:()=>l?.(b.id,te.path),className:_($n(f,U)),"aria-pressed":U,title:te.path,children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx(C,{name:"git-branch",className:_(ln(f),"text-muted-foreground")}),t.jsx("span",{className:cn(f),children:te.branch||(te.detached?"Detached HEAD":te.name)})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:R?t.jsx(gn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]},te.path)}):null]},b.id)})})}),t.jsxs("button",{type:"button",onClick:c,className:$n(f,!1),children:[t.jsx(C,{name:"add",className:ln(f)}),t.jsx("span",{className:cn(f),children:"Add folder"})]})]})},pr="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 Rp({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(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:pr,"aria-label":"Settings",children:t.jsx(C,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:pr,"aria-label":"Shortcuts",children:t.jsx(C,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:pr,"aria-label":"About PiChamber",children:t.jsx(C,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Ze,{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 Mp=(e,s)=>er(e.label?.trim()||Rs(e.normalizedPath,s)||e.normalizedPath);function Fp(e){is("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=(h,x)=>{const m=s.current,f=m.get(h);if(f&&f.groups===x)return f.ordered;const g=e.getOrderedGroups(h,x);if(m.set(h,{groups:x,ordered:g}),m.size>256){const S=m.keys().next().value;S!==void 0&&m.delete(S)}return g},i=o.useRef(null),a=o.useMemo(()=>{if(!e.isAllFoldersView)return[];const h=[],x=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const m of x){const f=Mp(m.project,e.homeDirectory);for(const g of m.groups)if(!g.isArchivedBucket)for(const S of g.sessions){const j=!!e.pinnedSessionIds?.has(S.session.id),B=S.session.time?.updated||S.session.time?.created||0;h.push({node:S,project:m.project,projectLabel:f,isPinned:j,timestamp:B,globalSession:m===e.allFoldersOnlySection})}}return h.sort((m,f)=>m.isPinned!==f.isPinned?m.isPinned?-1:1:f.timestamp-m.timestamp),h},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=o.useState(30);o.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const d=a.slice(0,l),u=a.length-d.length;if(e.sharedSessionsOnly)return t.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const p=e.isAllFoldersView&&!!e.allFoldersOnlySection;return e.projectSections.length===0&&!p?t.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-20"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0&&!p?t.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("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(Is,{ref:i,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-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 h=e.sectionsForRender.find(g=>g.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!h)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const x=h.groups.find(g=>g.isMain&&g.sessions.length>0)??h.groups.find(g=>g.sessions.length>0)??h.groups.find(g=>g.isMain)??h.groups[0];if(!x)return t.jsx(Es,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath}),children:"New session"});const m=h.groups.find(g=>g.isArchivedBucket);return[x,...m&&m.id!==x.id?[m]:[]].map(g=>{const S=`${h.project.id}:${g.id}`,j=g.id===x.id;return t.jsx(o.Fragment,{children:e.renderGroupSessions(g,S,h.project.id,j,null,!0,i)},S)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[d.map(({node:h,project:x,projectLabel:m,globalSession:f})=>{const g=h.session.directory??x.normalizedPath;return t.jsx(o.Fragment,{children:e.renderSessionNode(h,0,g,x.id,!1,{projectLabel:m,showFolderLabel:!0,globalSession:f},"project")},h.session.id)}),u>0?t.jsx(Es,{icon:"arrow-down-s",onClick:()=>c(h=>h+30),children:u===1?"Show 1 more session":`Show ${u} more sessions`}):null,l>30&&a.length>30?t.jsx(Es,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(h=>{const x=h.project.id,m=r(x,h.groups),f=m.find(S=>S.isMain)??null,g=f?m.filter(S=>S.id!==f.id):m;return t.jsxs("div",{children:[f?e.renderGroupSessions(f,`${x}:${f.id}`,x,!0,null,void 0,i):null,g.map(S=>{const j=`${x}:${S.id}`,B=m.length===1;return t.jsx(o.Fragment,{children:e.renderGroupSessions(S,j,x,B,null,void 0,i)},S.id)})]},x)})})]})})})}const Lp=o.memo(Fp);function Op(e){if(typeof e!="number"||!Number.isFinite(e))return"";const s=new Date(e);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleString("en-US",{month:"short"}),r=s.getDate(),i=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${i}, ${a}:${l}`}function Bp(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 _p(e){const s=e.info.role==="user"?"User":"Assistant",n=Op(e.info.time?.created),r=Bp(e),i=n&&r?`${n} (${r})`:n||r;return i?`**${s}**
13
-
14
- *${i}*`:`**${s}**`}function zp(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function sl(e){const s=_p(e),n=zp(e.parts).trim();return n?`${s}
15
-
16
- ${n}`:""}function nl(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",i=`${n} Sub-agent: ${e.title}${r}
17
-
18
- ---
19
-
20
- `,a=e.records.map(sl).filter(Boolean).join(`
21
-
22
- ---
23
-
24
- `),l=[i+a];for(const c of e.children)l.push(nl(c,s+1));return l.join(`
25
-
26
- ---
27
-
28
- `)}function rl(e,s,n){const r=s?.trim()||"Session",i=new Date().toISOString().split("T")[0],a=`# ${r}
29
-
30
- *Exported on ${i}*
31
-
32
- ---
33
-
34
- `,l=e.map(sl).filter(Boolean).join(`
35
-
36
- ---
37
-
38
- `);let c=a+l;if(n&&n.length>0){const d=n.map(u=>nl(u,1)).join(`
39
-
40
- ---
41
-
42
- `);c+=`
43
-
44
- ---
45
-
46
- `+d}return c}function ol(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=s,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}async function il(e,s){const n=await pu(s,e);return n||null}async function $p(e){const s=oo()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await mu(e)?!0:xa(e)}function Up(){return gu()}function al(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",i=new Date().toISOString().split("T")[0];return`${r}-${i}.md`}const Gp=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},Kp=ps()(co(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:Gp})),Hp=(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},Yt=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 p=i&&i.length>0?[n,...i]:[n];if(l.has(n)){for(const x of p)l.delete(x);d===n&&(d=null)}else{for(const x of p)l.add(x);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,i,a,l)=>{const c=s();if(i.length===0)return;const d=n&&i.includes(n)?n:i[0],u=i.indexOf(d),p=i.indexOf(r);if(u<0||p<0)return;const[h,x]=u<=p?[u,p]:[p,u],m=i.slice(h,x+1),f=Hp(m,l),S=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const j of f)S.add(j);e({selectedIds:S,scopeKey:a??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const i=new Set(r.selectedIds);for(const a of n)i.delete(a);i.size!==r.selectedIds.size&&(i.size===0?e({selectedIds:i,scopeKey:null,anchorId:null}):e({selectedIds:i}))}}));let Qr=!1;const Jr=new Set;let Ii=!1;function Wp(){for(const e of Jr)e()}function yo(e){Qr!==e&&(Qr=e,Wp())}function Yp(e){e.key==="Shift"&&yo(!0)}function Vp(e){e.key==="Shift"&&yo(!1)}function qp(){yo(!1)}function Qp(){Ii||typeof window>"u"||(Ii=!0,window.addEventListener("keydown",Yp),window.addEventListener("keyup",Vp),window.addEventListener("blur",qp))}function Jp(e){return Qp(),Jr.add(e),()=>{Jr.delete(e)}}function Xp(){return Qr}function Zp(){return!1}function em(){return Je.useSyncExternalStore(Jp,Xp,Zp)}const mr=new WeakMap,tm=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;mr.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,mr.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,is("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}),mr.set(n,c),l=window.requestAnimationFrame(d)},sm=o.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:i,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=em(),p=u?n:s,h=x=>{if(u||x.shiftKey){d(x);return}c(x)};return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",className:_("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":p,onPointerDown:a,onMouseDown:l,onClick:h,onKeyDown:x=>x.stopPropagation(),children:t.jsx(C,{name:u?"delete-bin":"archive",className:i})})}),t.jsx(rt,{side:"left",sideOffset:8,children:p})]})});function nm(e){is("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:i,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:p,editingId:h,setEditingId:x,editTitle:m,setEditTitle:f,handleSaveEdit:g,handleCancelEdit:S,toggleParent:j,handleSessionSelect:B,handleSessionDoubleClick:A,togglePinnedSession:b,handleShareSession:v,copiedSessionId:M,handleCopyShareUrl:N,handleCopySessionId:k,handleUnshareSession:I,openSidebarMenuKey:D,setOpenSidebarMenuKey:P,renamingFolderId:G,getFoldersForScope:ee,getSessionFolderId:Z,removeSessionFromFolder:te,addSessionToFolder:U,createFolderAndStartRename:K,handleDeleteSession:T,handleRestoreSession:R,mobileVariant:Q,alwaysShowActions:ae,allowQuickArchiveAction:z,renderSessionNode:Re,secondaryMeta:Te,renderContext:Ye="project",subtreeContainsEditing:_e,menuOpenSessionId:Ve,childRenderExtrasFor:Be}=e,ie=o.useMemo(()=>ba(),[]),pe=!a&&z,We=o.useRef(!1),Ce=o.useRef(h);Ce.current=h;const ve=o.useRef(null),$e=o.useRef(g);$e.current=g;const[ot,ze]=o.useState(m),J=o.useRef(ot);J.current=ot;const q=o.useRef(null),ge=o.useRef(null),X=s.session,be=X,Ae=Qe(X.directory??null)??Qe(r??null),je=Oe($=>$.currentSessionId===X.id),lt=ca(Ae),jt=fd(Ae),it=$t(o.useCallback($=>{if(Te?.projectLabel||!i)return null;const Ge=$.projects.find(at=>at.id===i);return Ge?Ge.label?.trim()||Rs(Qe(Ge.path)??Ge.path,null)||Ge.path:null},[i,Te?.projectLabel])),xe=Te?.projectLabel??(it?er(it):null),Fe=Te?.branchLabel??s.worktree?.branch??(lt&&lt!=="HEAD"?lt:null),Le=Fe,Ke=jt===!0||!!(Fe||s.worktree),kt=s.children.length,ht=be.agent;o.useMemo(()=>{const $=s.worktree?.branch?.trim()||Fe?.trim(),Ge=Qe(s.worktree?.path??Ae);return $&&Ge?el():null},[s.worktree,Fe,Ae]);const O=bp();o.useMemo(()=>null,[O]);const ke=i??Ae??null,ye=ua(),w=no(),V=Yt($=>$.enabled),se=Yt(o.useCallback($=>$.selectedIds.has(X.id),[X.id])),de=Yt($=>$.toggleSelected),Se=Yt($=>$.setRange),Pe=o.useCallback($=>{const Ge=[],at=wt=>{wt.children.forEach(St=>{Ge.push(St.session.id),at(St)})};return at($),Ge},[]);o.useCallback($=>{const Ge=[],at=wt=>{wt.children.forEach(St=>{Ge.push(St.session),at(St)})};return at($),Ge},[]);const[He,mt]=o.useState(!1),[bt,qe]=o.useState(!0),dt=`${Ye}:${a?"archived":"active"}:${X.id}`,xt=hd(o.useCallback($=>!!$.sessionMemoryState.get(pd(X.id))?.isZombie,[X.id])),Xe=da(X.id)?.type??"idle",yt=Xe==="busy"||Xe==="retry",Nt=md(X.id,yt),Pt=gd(X.id),Et=be.title||"Untitled Session",It=s.children.length>0,At=xd(l,Ae,X.id),F=dt,Ne=d?!0:c.has(F);o.useMemo(()=>pp(s,Ne,Ae),[Ne,s,Ae]);const Ue=vd(),pt=!!be.parentID,re=bd(X.id)>0&&(!pt||p),me=be.time?.updated||be.time?.created||Date.now(),tt=Mu(me),[we,et]=o.useState(!1),ut=o.useMemo(()=>qa(s.forkColorId),[s.forkColorId]),Ot=o.useMemo(()=>$h(s.forkColorId,{active:je||se}),[s.forkColorId,je,se]),Ut=Te?.globalSession&&!je&&!se?"var(--surface-elevated)":null,Rt=Ot??Ut,Gt=o.useMemo(()=>Pe(s).length,[Pe,s]),Ft=o.useCallback(async $=>{const Ge=[];let at=0;for(const wt of $)try{if(!Ae)throw new Error("Session directory is required for export");await w.loadCompleteHistory?.(wt.session.id,Ae);const St=Rr(ye.getState(),wt.session.id).list,rs=wt.session.title||"Untitled Sub-agent",Os=wt.session.agent,Vt=await Ft(wt.children);at+=Vt.skipped,Ge.push({title:rs,agent:Os,records:St,children:Vt.children})}catch{at+=Pe(wt).length+1}return{children:Ge,skipped:at}},[Pe,ye,Ae,w]),gt=o.useCallback($=>{$<=0||le.warning($===1?`Exported session, but skipped ${$} sub-agent task that could not be loaded.`:`Exported session, but skipped ${$} sub-agent tasks that could not be loaded.`)},[]),Bt=o.useCallback(async $=>{if(!Ae){le.error("Nothing to export");return}try{await w.loadCompleteHistory?.(X.id,Ae)}catch{le.error("Failed to load the complete session history");return}const Ge=Rr(ye.getState(),X.id).list;if(Ge.length===0){le.error("Nothing to export");return}let at,wt=0;if($&&s.children.length>0){const Vt=await Ft(s.children);at=Vt.children,wt=Vt.skipped}const St=rl(Ge,be.title??null,at),rs=al(be.title??null),Os=await il(St,rs);if(Os){le.success("Session exported",{action:{label:Up(),onClick:()=>{$p(Os).then(Vt=>{Vt||le.error("Failed to reveal path")})}}}),gt(wt);return}ol(St,rs),le.success("Session exported"),gt(wt)},[Ft,ye,s.children,be.title,X.id,Ae,gt,w]),H=o.useCallback(async()=>{if(s.children.length>0){qe(!0),mt(!0);return}await Bt(!1)},[Bt,s.children.length]),ne=o.useCallback(()=>{Ae&&an("desktop_open_session_mini_chat_window",{sessionId:X.id,directory:Ae,apiBaseUrl:Lr(),clientToken:Fr()}).catch($=>{console.warn("[session-sidebar] failed to open mini chat window",$)})},[X.id,Ae]);o.useEffect(()=>{if(h!==X.id)return;const $=Ge=>{const wt=Ge.target?.closest?.(`[data-session-rename-form="${CSS.escape(X.id)}"]`);ge.current&&!wt&&$e.current(J.current)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[h,X.id]),o.useLayoutEffect(()=>{if(h!==X.id){q.current===X.id&&(q.current=null);return}q.current!==X.id&&(q.current=X.id,ze(m))},[h,m,X.id]);const oe=Pt.length,ce=!yt&&re&&!je,he=yt&&Nt,ft=At,Mt=t.jsx(C,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),vt=ft?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:Mt}):null,Kt=It?t.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),j(F)},onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),$.stopPropagation(),j(F))},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":Ne?"Collapse subsessions":"Expand subsessions",children:Ne?t.jsx(C,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(C,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Ht=xt?t.jsx(C,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Tt=$=>{if(!$&&ve.current){const{id:Ge,title:at}=ve.current;ve.current=null,x(Ge),f(at)}},ns=$=>{et($)},cs=$=>{$.preventDefault(),$.stopPropagation()},ms=$=>{$.preventDefault(),$.stopPropagation()},qs=$=>{$.preventDefault(),$.stopPropagation(),P(null),T(X,{archivedBucket:a})},Qs=$=>{$.preventDefault(),$.stopPropagation(),P(null),T(X,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},gs=$=>{if(We.current){We.current=!1;return}if(V){if($?.preventDefault(),$?.stopPropagation(),$?.shiftKey){const at=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(rs=>rs.getAttribute("data-session-row")).filter(rs=>typeof rs=="string"&&rs.length>0),wt=Yt.getState().anchorId,St=new Map;St.set(X.id,Pe(s)),Se(wt,X.id,at,ke,St);return}de(X.id,ke,Pe(s));return}$?.currentTarget&&tm($.currentTarget),B(X.id,Ae)},js=$=>{$.defaultPrevented||$.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||gs($)},E=$=>{($.button===2||$.button===0&&$.ctrlKey&&!V)&&(We.current=!0)},ue=({Item:$,Separator:Ge,Sub:at,SubTrigger:wt,SubContent:St})=>t.jsxs(t.Fragment,{children:[t.jsxs($,{onClick:()=>{ve.current={id:X.id,title:Et}},className:"[&>svg]:mr-1",children:[t.jsx(C,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs($,{onClick:()=>k(X.id),className:"[&>svg]:mr-1",children:[t.jsx(C,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs($,{onClick:()=>Ae&&b({directory:Ae,sessionId:X.id}),className:"[&>svg]:mr-1",children:[At?t.jsx(C,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(C,{name:"pushpin",className:"mr-1 h-4 w-4"}),At?"Unpin session":"Pin session"]}),t.jsxs($,{onClick:()=>{H()},className:"[&>svg]:mr-1",children:[t.jsx(C,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),ie?t.jsxs($,{disabled:!Ae,onClick:ne,className:"[&>svg]:mr-1",children:[t.jsx(C,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(Ge,{}),a?null:t.jsxs($,{className:"[&>svg]:mr-1",onClick:()=>T(X,{archivedBucket:a}),children:[t.jsx(C,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?t.jsxs($,{className:"[&>svg]:mr-1",onClick:()=>R(X),children:[t.jsx(C,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs($,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>T(X,{archivedBucket:a,hardDelete:!0}),children:[t.jsx(C,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]}),Ie=t.jsx(zr,{children:t.jsx($r,{className:"app-region-no-drag z-50",children:t.jsx(Ur,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(G||Ce.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Pr,"min-w-[180px]"),children:ue({Item:({className:$,...Ge})=>t.jsx(Na,{className:_(ea,$),...Ge}),Separator:({className:$,...Ge})=>t.jsx(Aa,{className:_(ta,$),...Ge}),Sub:Ku,SubTrigger:({className:$,children:Ge,...at})=>t.jsxs(Hu,{className:_(yd,$),...at,children:[Ge,t.jsx(C,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:$,children:Ge,...at})=>t.jsx(zr,{children:t.jsx($r,{className:"app-region-no-drag z-50",children:t.jsx(Ur,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:_(Pr,$),...at,children:Ge})})})})})})});return t.jsxs(o.Fragment,{children:[t.jsx(up,{sessionId:X.id,sessionDirectory:Ae??null,sessionTitle:Et,children:t.jsxs(Ca,{open:we,onOpenChange:ns,onOpenChangeComplete:Tt,children:[t.jsxs(ka,{render:t.jsx("div",{"data-session-row":X.id,"data-session-scope":ke??"","data-session-archived":a?"1":"0","data-fork-color":ut?s.forkColorId:void 0,"data-global-session":Te?.globalSession?"1":void 0,onClick:js,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...Rt?{backgroundColor:Rt}:void 0},className:_("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!Rt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":Rt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!Rt&&je&&!se&&"bg-interactive-selection",!Rt&&se&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[Kt,vt,h===X.id?t.jsxs("form",{ref:ge,"data-session-rename-form":X.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onSubmit:$=>{$.preventDefault(),g(ot)},children:[t.jsx("input",{value:ot,onChange:$=>ze($.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:$=>{$.stopPropagation(),$.key==="Escape"&&S()}}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(C,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:S,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(C,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:E,onClick:$=>gs($),onDoubleClick:$=>{$.stopPropagation(),A(X.id,Et)},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:_("block min-w-0 flex-1 truncate font-normal typography-ui-label",re?"text-foreground":"text-foreground/90"),children:zn(Et,u)})}),Te?.showFolderLabel&&xe||Le||Ke||O||kt>0||ht&&ht!=="default"||he||oe>0||Ue>0?t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[Te?.showFolderLabel&&xe?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:xe}):null,Le?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(C,{name:"git-branch",className:_("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:Le})]}):Ke?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(C,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,kt>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(C,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:kt})]}):null,ht&&ht!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:ht}):null,he?t.jsx(Tu,{sessionId:X.id,running:yt,className:"text-muted-foreground/70"}):null,oe>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[t.jsx(C,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:oe})]}):null,null]}):null]})]}),At?t.jsx(C,{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:_("flex items-center justify-end",pe&&(ae||we)?"opacity-0":pe?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:yt?t.jsx(gn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):ce?t.jsx(Ru,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:tt})}),pe?t.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",ae||we?"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(sm,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:cs,onMouseDown:ms,onArchive:qs,onDelete:Qs})}):null]}),Ht&&!Q?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:Ht}):null]}),Ie]})}),It&&Ne?s.children.map($=>{const Ge=Be?Be($):{subtreeContainsEditing:_e,menuOpenSessionId:Ve,nodeStructureKey:""};return t.jsx(o.Fragment,{children:Re($,n+1,Ae??r,i,a,Te?.globalSession?{globalSession:!0}:void 0,Ye,Ge)},$.session.id)}):null,t.jsx(as,{open:He,onOpenChange:mt,children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:"Export Markdown"}),t.jsx(Fs,{children:Gt===1?`This session has ${Gt} sub-agent task. Include it in the export?`:`This session has ${Gt} 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:bt,onChange:$=>qe($.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Ls,{children:[t.jsx(Ze,{type:"button",onClick:()=>mt(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Ze,{type:"button",onClick:()=>{mt(!1),Bt(bt)},size:"sm",children:"Export"})]})]})})]},X.id)}const Di=e=>Qe(e.session.directory??null),rm=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),om=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},En=e=>e.menuOpenSessionId??om(e),Tn=(e,s,n)=>s?n.has(e.node.session.id)?!0:fs(e.node,s):!1,Xr=(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(Xr(e.children[l],s.children[l],n,r,i))return!0;return!1},im=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Xr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${e.renderContext??"project"}:${n}:${i.session.id}`)||Xr(e.node,s.node,e.expandedParents,s.expandedParents,i=>`${s.renderContext??"project"}:${r}:${i.session.id}`)},am=(e,s)=>{if(e.node.session.id!==s.node.session.id||e.node.session!==s.node.session||e.depth!==s.depth||e.groupDirectory!==s.groupDirectory||e.projectId!==s.projectId||e.archivedBucket!==s.archivedBucket||(e.renderContext??"project")!==(s.renderContext??"project")||e.mobileVariant!==s.mobileVariant||e.alwaysShowActions!==s.alwaysShowActions||e.allowQuickArchiveAction!==s.allowQuickArchiveAction||e.hasSessionSearchQuery!==s.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||e.notifyOnSubtasks!==s.notifyOnSubtasks||e.nodeStructureKey!==s.nodeStructureKey||Di(e.node)!==Di(s.node)||!rm(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Za(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&im(e,s)||e.editingId!==s.editingId&&(Tn(e,e.editingId,e.subtreeContainsEditing)||Tn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(Tn(e,e.editingId,e.subtreeContainsEditing)||Tn(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=En(e),r=En(s);if(fs(e.node,n)||fs(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=En(e),r=En(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},lm=o.memo(nm,am),Pi={selected:0,"active-project":1,expanded:2,visible:3,background:4};function cm(e){const s=new Map,n=(r,i,a)=>{const l=Qe(r??null);if(!l)return;const c=s.get(l);c&&Pi[c.priority]<=Pi[i]||s.set(l,{directory:l,priority:i,reason:a})};for(const r of e.projectSections){const i=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":i&&(a="expanded"),n(r.project.normalizedPath,a,i?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=i&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":i&&(d="visible"),n(l.directory,d,c?"worktree-expanded":"known-worktree")}}return n(e.currentDirectory,"selected","current-directory"),n(e.currentSessionDirectory,"selected","selected-session"),[...s.values()]}function dm(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=e,l="Untitled Session";return t.jsx(as,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(Fs,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be permanently deleted.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be archived.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`\\"${s?.session.title||l}\\" will be permanently deleted.`:`\\"${s?.session.title||l}\\" will be archived.`})]}),t.jsxs(Ls,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>i(!r),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!r,children:[r?t.jsx(C,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(C,{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 um(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(as,{open:!!s,onOpenChange:p=>{p||n(null)},children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:d}),t.jsx(Fs,{children:u})]}),t.jsxs(Ls,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>i(!r),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!r,children:[r?t.jsx(C,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(C,{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 fm(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(as,{open:!!s,onOpenChange:i=>{i||n(null)},children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:"Delete folder?"}),t.jsx(Fs,{children:s&&(s.subFolderCount>0||s.sessionCount>0)?s.subFolderCount>0?s.subFolderCount===1?`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted. Sessions inside will not be deleted.`:`\\"${s?.folderName??""}\\" will be permanently deleted.`})]}),t.jsxs(Ls,{children:[t.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})}const hm=({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(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(C,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:_("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(C,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,className:l,"aria-label":"Exit selection",children:t.jsx(C,{name:"close",className:"h-4 w-4"})})}),t.jsx(rt,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},pm=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:i,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:p,setBulkDeleteConfirm:h}=e,x=Yt(K=>K.enabled),m=Yt(K=>K.selectedIds.size),f=m>0,g=Yt(K=>K.selectedIds),S=Yt(K=>K.scopeKey),j=o.useCallback(()=>{Yt.getState().toggleMode()},[]),B=o.useCallback(()=>{Yt.getState().disable()},[]),A=o.useMemo(()=>{if(!f||typeof document>"u")return!1;let K=!1,T=!1;for(const R of g){const Q=document.querySelectorAll(`[data-session-row="${CSS.escape(R)}"]`);for(const ae of Q)ae.getAttribute("data-session-archived")==="1"?T=!0:K=!0}return T&&!K},[f,g]),b=o.useMemo(()=>{if(S)return S;if(!f||typeof document>"u")return null;for(const K of g){const R=document.querySelector(`[data-session-row="${CSS.escape(K)}"]`)?.getAttribute("data-session-scope");if(R&&R.length>0)return R}return null},[f,g,S]),v=o.useMemo(()=>{if(!b)return[];const K=i.get(b);return K&&K.length>0?K.map(T=>T.scopeKey):[b]},[b,i]),M=o.useMemo(()=>v.flatMap(K=>r[K]??[]),[r,v]),N=o.useCallback(K=>{for(const T of v)if((r[T]??[]).some(R=>R.id===K))return T;return null},[r,v]),k=o.useMemo(()=>{if(!f)return!1;for(const K of v)for(const T of r[K]??[])for(const R of T.sessionIds)if(g.has(R))return!0;return!1},[r,v,f,g]),I=o.useCallback((K,T)=>{const R=Array.from(g);for(const Q of v)Q!==K&&l(Q,R);a(K,T,R)},[a,l,g,v]),D=o.useCallback(K=>{if(!f)return;const T=N(K);T&&I(T,K)},[f,I,N]),P=o.useCallback(()=>{const K=v[0];if(!K||!f)return;const T=c(K);T&&I(K,T.id)},[c,f,I,v]),G=o.useCallback(()=>{if(!f)return;const K=Array.from(g);for(const T of v)l(T,K)},[l,g,v,f]),ee=o.useCallback(async()=>{const K=Array.from(g);if(K.length!==0){if(A){const{deletedIds:T,failedIds:R}=await p(K);T.length>0&&le.success(T.length===1?`Deleted ${T.length} session`:`Deleted ${T.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to delete ${R.length} session`:`Failed to delete ${R.length} sessions`)}else{const{archivedIds:T,failedIds:R}=await d(K);T.length>0&&le.success(T.length===1?`Archived ${T.length} session`:`Archived ${T.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to archive ${R.length} session`:`Failed to archive ${R.length} sessions`)}Yt.getState().clear()}},[d,A,p,g]),Z=o.useCallback(()=>{if(!f)return;const K=g.size;if(!n){ee();return}h({sessionCount:K,archivedBucket:A})},[A,ee,g,n,h,f]),te=o.useCallback(async()=>{if(!f||!A)return;const K=Array.from(g),{restoredIds:T,failedIds:R}=await u(K);T.length>0&&le.success(T.length===1?`Restored ${T.length} session`:`Restored ${T.length} sessions`),R.length>0&&le.error(R.length===1?`Failed to restore ${R.length} session`:`Failed to restore ${R.length} sessions`),Yt.getState().clear()},[A,f,g,u]),U=o.useCallback(async()=>{h(null),await ee()},[ee]);return o.useEffect(()=>{if(!x)return;const K=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),T=R=>{if(s)return;const Q=R.target;if(Q&&(Q.tagName==="INPUT"||Q.tagName==="TEXTAREA"||Q.isContentEditable))return;const ae=K?R.metaKey:R.ctrlKey;if(R.key==="Escape"){R.preventDefault(),Yt.getState().disable();return}if(ae&&R.key==="Backspace"){R.preventDefault(),Z();return}if(ae&&(R.key==="a"||R.key==="A")){const z=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(z.length===0)return;R.preventDefault();const Te=Yt.getState().scopeKey??z[0]?.getAttribute("data-session-scope")??null,Ye=Ve=>Te?Ve.getAttribute("data-session-scope")===Te:!0,_e=z.filter(Ye).map(Ve=>Ve.getAttribute("data-session-row")).filter(Ve=>typeof Ve=="string"&&Ve.length>0);if(_e.length===0)return;Yt.getState().replaceAll(_e,Te||null)}};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[Z,s,x]),{selectionModeEnabled:x,hasSelection:f,selectedIdsSize:m,bulkScopeIsArchived:A,derivedSelectionScope:b,bulkScopeFolders:M,bulkCanRemoveFromFolder:k,handleToggleSelectionMode:j,handleExitSelectionMode:B,handleBulkMoveToFolder:D,handleBulkCreateFolderAndMove:P,handleBulkRemoveFromFolder:G,handleBulkDelete:Z,handleBulkRestore:te,confirmBulkDelete:U}},Ei="oc.sessions.projectCollapse",Ti="oc.sessions.groupOrder",Ri="oc.sessions.groupCollapse",Mi="oc.sessions.activeSessionByProject",Fi="oc.sessions.expandedParents.v3",mm=new Set,gr=[],ts=e=>{const s=o.useRef(e);return s.current=e,o.useCallback((...n)=>s.current(...n),[])},gm=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l})=>{const c=Oe(d=>d.currentSessionDirectory);return o.useEffect(()=>{s.setBootstrapDemand(e,cm({projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,i,l,c,e,n]),o.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},xm=({directories:e})=>{const s=o.useMemo(()=>{const r=new Set;return e.forEach(i=>{const a=Qe(i)?.toLowerCase();a&&r.add(a)}),r},[e]);return rn(r=>{for(const i of r.catalog.byId.values()){if(i.lifecycle!=="busy"&&i.lifecycle!=="retry")continue;const a=Qe(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(gn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},bm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:i=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Mr("react.session_sidebar_render"),is("ui.session_sidebar.render"),is(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),is(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=o.useState(!1),[u,p]=o.useState(""),h=o.useRef(null),x=o.useRef(null),[m,f]=o.useState(null),[g,S]=o.useState(""),[j,B]=o.useState(null),[A,b]=o.useState(new Set),v=o.useMemo(()=>Nn(),[]),[M,N]=o.useState(new Set),[k,I]=o.useState(null),[D,P]=o.useState(null),[G,ee]=o.useState(new Map),[Z,te]=o.useState(new Map),[U,K]=o.useState(!1),[T,R]=o.useState(null),[Q,ae]=o.useState(null),[z,Re]=o.useState(""),[Te,Ye]=o.useState(null),[_e,Ve]=o.useState(null),[Be,ie]=o.useState(null),pe=Tr(y=>y.ids),We=wd(o.useCallback(y=>e?y.rankById:aa,[e])),Ce=rn(y=>e?Sd(y.catalog):"",void 0,"catalog"),ve=o.useMemo(()=>Ce?Ce.split("|"):gr,[Ce]),$e=o.useMemo(()=>new Set(ve),[ve]),ot=jd(Gr(y=>e?Object.entries(y.index.session.unseenCount).filter(([,Y])=>Y>0).map(([Y])=>Y).sort():gr)),ze=o.useMemo(()=>new Set(ot),[ot]),J=Tr(y=>y.toggle),[q,ge]=o.useState(()=>{try{const y=Nn().getItem(Ri);if(!y)return new Set;const Y=JSON.parse(y);return new Set(Array.isArray(Y)?Y.filter(W=>typeof W=="string"):[])}catch{return new Set}}),[X,be]=o.useState(()=>{try{const y=Nn().getItem(Ti);if(!y)return new Map;const Y=JSON.parse(y),W=new Map;return Object.entries(Y).forEach(([De,ct])=>{Array.isArray(ct)&&W.set(De,ct.filter(Lt=>typeof Lt=="string"))}),W}catch{return new Map}}),Ae=o.useMemo(()=>{try{const y=Nn().getItem(Mi);if(!y)return new Map;const Y=JSON.parse(y),W=new Map;return Object.entries(Y).forEach(([De,ct])=>{typeof ct=="string"&&ct.length>0&&W.set(De,ct)}),W}catch{return new Map}},[]),je=o.useCallback(y=>{try{v.setItem(Mi,JSON.stringify(Object.fromEntries(y.entries())))}catch{}},[v]),[lt,jt]=o.useState(new Map),it=o.useRef(0),xe=ws(y=>y.homeDirectory),Fe=ws(y=>y.currentDirectory),Le=$t(y=>y.projects),Ke=$t(y=>y.activeProjectId),kt=$t(y=>y.removeProject),ht=$t(y=>y.setActiveProjectIdOnly),O=$t(y=>y.updateProjectMeta),ke=$t(y=>y.reorderProjects),ye=fe(y=>y.setActiveMainTab),w=fe(y=>y.setSettingsDialogOpen),V=fe(y=>y.setSettingsPage),se=fe(y=>y.toggleHelpDialog),de=fe(y=>y.setSessionSwitcherOpen),Se=fe(y=>y.setArchivePageOpen),Pe=fe(y=>y.notifyOnSubtasks),He=fe(y=>y.showDeletionDialog),mt=fe(y=>y.setShowDeletionDialog),bt=Cd(u,120),qe=o.useMemo(()=>bt.trim().toLowerCase(),[bt]),dt=qe.length>0,xt=Wt(y=>y.collapsedFolderIds),Me=Wt(y=>y.foldersMap),Xe=Wt(y=>y.getFoldersForScope),yt=Wt(y=>y.createFolder),Nt=Wt(y=>y.renameFolder),Pt=Wt(y=>y.deleteFolder),Et=Wt(y=>y.addSessionToFolder),It=Wt(y=>y.addSessionsToFolder),At=Wt(y=>y.removeSessionFromFolder),F=Wt(y=>y.removeSessionsFromFolders),Ne=Wt(y=>y.toggleFolderCollapse),Ue=Wt(y=>y.getSessionFolderId);Kh({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:h});const pt=kd(e),L=no(),re=la(),me=rn(y=>y.connection,void 0,"chrome"),tt=rn(y=>{for(const Y of y.catalog.listStatusByDirectory.values())if(Y==="ready")return!0;return!1},void 0,"catalog"),we=Er({archived:!1}),et=Er({archived:!0}),ut=`session-sidebar:${o.useId()}`,Ot=Oe(y=>y.setCurrentSession),Ut=Oe(y=>y.updateSessionTitle),Rt=Oe(y=>y.shareSession),Gt=Oe(y=>y.unshareSession),Ft=fa(y=>y.projects),gt=o.useMemo(()=>Nd(Le,{projects:Ft}),[Le,Ft]),Bt=o.useMemo(()=>{const y=new Map;for(const Y of Le){const W=Qe(Y.path);if(!W)continue;const De=Ft.get(W)?.error;De&&y.set(W,De)}return y},[Le,Ft]);o.useEffect(()=>{if(!k)return;const y=Le.find(W=>W.id===k);if(!y){I(null),P(null);return}if(!D)return;(gt.get(Qe(y.path)??y.path)??[]).some(W=>Qe(W.path)===Qe(D))||(P(null),le.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[gt,Le,k,D]);const H=Oe(y=>y.openNewSessionDraft),ne=o.useCallback(y=>{fe.getState().closeMainSurfaces(),H(y),r?.()},[r,H]),oe=_n(Gr(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(()=>Ad(Le,gt,{includeWorktrees:!0}),[gt,Le]),he=o.useMemo(()=>we.filter(y=>op(y,ce,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:xe})),[we,xe,ce]),ft=o.useMemo(()=>[...he,...et],[et,he]),Mt=Zn(),vt=o.useMemo(()=>`${Mt}|${Le.map(y=>`${y.id}:${Qe(y.path)??""}`).join("|")}`,[Le,Mt]),Kt=o.useMemo(()=>{const y=new Set;let Y=!0;for(const W of Le){const De=Qe(W.path);if(!De)continue;const ct=Ft.get(De)?.status??"idle";ct==="failed"&&y.add(De),(ct==="idle"||ct==="loading")&&(Y=!1)}return{complete:Y,unresolved:y}},[Le,Ft]),Ht=Kt.complete?vt:null,Tt=!Kt.complete,ns=Kt.unresolved,{isTablet:cs}=Ms(),ms=s||cs,qs=Gh({mobileVariant:s,isTablet:cs}),{buildGroupSearchText:Qs,filterSessionNodesForSearch:gs,buildGroupedSessions:js}=Uh({homeDirectory:xe,pinnedSessionIds:pe,sessionOrderRanks:We}),{scheduleCollapsedProjectsPersist:E}=Wh({safeStorage:v,keys:{sessionExpanded:Fi,projectCollapse:Ei,groupOrder:Ti,groupCollapse:Ri},groupOrderByProject:X,collapsedGroups:q,setExpandedParents:b,setCollapsedProjects:N}),ue=o.useMemo(()=>Id(he,pe,We),[pe,We,he]),Ie=o.useMemo(()=>ue.map(y=>y.id).join("|"),[ue]),$=o.useRef(null),Ge=o.useMemo(()=>{const y=$.current;if(y&&y.signature===Ie)return y.map;const Y=new Map(ue.map((W,De)=>[W.id,De]));return $.current={signature:Ie,map:Y},Y},[ue,Ie]),at=o.useMemo(()=>{const y=new Map;return ue.forEach(Y=>{const W=Y.parentID;if(!W)return;const De=y.get(W)??[];De.push(Y),y.set(W,De)}),y.forEach(Y=>Y.sort((W,De)=>so(W,De,pe,We))),y},[ue,pe,We]),wt=o.useMemo(()=>t.jsx(Es,{icon:"chat-new",mobileVariant:s,onClick:()=>ne(),children:"New session"}),[s,ne]),St=o.useMemo(()=>Le.find(y=>y.id===j)??null,[Le,j]),rs=o.useCallback(y=>{j&&O(j,{label:y.label,defaultModel:y.defaultModel??null})},[j,O]),Os=o.useCallback(()=>{const y=_n.getState();if(y.available&&y.info){K(!0);return}oe.checkForUpdates().then(()=>{const{available:Y,error:W}=_n.getState();if(W){le.error("Failed to check for updates",{description:W});return}if(!Y){le.success("You are on the latest version");return}K(!0)})},[oe]),Vt=Dd(),vo=o.useCallback(()=>{if(s&&de(!1),r?.(),Vt?.openSettings){Vt.openSettings();return}w(!0)},[Vt,s,r,de,w]),ul=oe.available&&(oe.runtimeType==="desktop"||oe.runtimeType==="web"),fl=Oe(y=>y.deleteSession),wo=Oe(y=>y.deleteSessions),hl=Oe(y=>y.archiveSession),So=Oe(y=>y.archiveSessions),pl=Oe(y=>y.unarchiveSession),ml=Oe(y=>y.unarchiveSessions),{copiedSessionId:gl,handleSessionSelect:xl,handleSessionDoubleClick:bl,handleSaveEdit:yl,handleCancelEdit:vl,handleShareSession:wl,handleCopyShareUrl:Sl,handleCopySessionId:jl,handleUnshareSession:Cl,handleDeleteSession:kl,handleRestoreSession:Nl,confirmDeleteSession:Al}=Hh({mobileVariant:s,allowReselect:i,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:p,setIsSessionSearchOpen:d,setActiveMainTab:ye,setSessionSwitcherOpen:de,setCurrentSession:Ot,updateSessionTitle:Ut,shareSession:Rt,unshareSession:Gt,deleteSession:fl,deleteSessions:wo,archiveSession:hl,archiveSessions:So,unarchiveSession:pl,childrenMap:at,showDeletionDialog:He,setDeleteSessionConfirm:Ye,deleteSessionConfirm:Te,setEditingId:f,setEditTitle:S,editingId:m,editTitle:g}),Il=o.useCallback(()=>{if(!_e)return;const{scopeKey:y,folderId:Y}=_e;Ve(null),Pt(y,Y)},[_e,Pt]),jo=o.useCallback(()=>{Ts.requestDirectoryDialog()},[]),Dl=o.useCallback(y=>{b(Y=>{const W=Fu(Y,y);try{v.setItem(Fi,JSON.stringify(Array.from(W)))}catch{}return W})},[v]),Co=o.useCallback((y,Y)=>{if(!y)return null;Y&&xt.has(Y)&&Ne(Y);const W=yt(y,"New folder",Y);return ae(W.id),Re(W.name),W},[xt,Ne,yt]),yn=ts(xl),Pl=ts(bl),El=ts(yl),Tl=ts(vl),Rl=ts(wl),Ml=ts(Sl),Fl=ts(jl),Ll=ts(Cl),Ol=ts(kl),Bl=ts(Nl),or=ts(Co),ko=o.useCallback((y,Y)=>{te(W=>{const De=new Map(W);return De.set(y,Y+7),De})},[]),vn=o.useCallback(y=>{te(Y=>{if(!Y.has(y))return Y;const W=new Map(Y);return W.delete(y),W})},[]),No=o.useCallback(y=>{te(Y=>{let W=!1;const De=new Map(Y),ct=`${y}:`;for(const Lt of De.keys())Lt.startsWith(ct)&&(De.delete(Lt),W=!0);return W?De:Y})},[]),_l=o.useCallback(y=>{it.current=Date.now()+150,No(y),N(Y=>{const W=new Set(Y);W.has(y)?W.delete(y):W.add(y);try{v.setItem(Ei,JSON.stringify(Array.from(W)))}catch{}return E(W),W})},[No,v,E]),xs=o.useMemo(()=>Le.map(y=>({...y,normalizedPath:Qe(y.path)})).filter(y=>!!y.normalizedPath),[Le]),zl=o.useMemo(()=>xs.map(y=>y.normalizedPath),[xs]),Ao=Pd(e?zl:gr);Xh({enabled:e,normalizedProjects:xs,gitRepoStatus:Ao,setProjectRepoStatus:ee,setProjectRootBranches:jt});const $l=Oe(y=>y.isLoading),Io=o.useMemo(()=>ap(he,xs,gt,et),[et,gt,xs,he]);np({enabled:e,hasAuthoritativeGlobalSessions:tt,sessions:ft});const{getSessionsForProject:Ul,getArchivedSessionsForProject:Gl}=Zh({ownership:Io});Mh({enabled:e,normalizedProjects:xs,ownership:Io,isSessionsLoading:$l,hasAuthoritativeGlobalSessions:tt,isWorktreeTopologyLoading:Tt,unresolvedWorktreeProjectPaths:ns,foldersMap:Me,createFolder:yt,addSessionToFolder:Et});const Do=o.useRef(!1);Ke&&G.has(Ke)&&(Do.current=!!G.get(Ke));const Kl=Kp(y=>y.showArchivedSessions),ir=$t(y=>y.manualProjectOrder),Po=o.useRef(new Set),wn=Lu(Po.current,A,"project");Po.current=wn;const ar={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:i,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:cs,catalogSessions:we,archivedSessions:et,projects:Le,activeProjectId:Ke,manualProjectOrder:ir,currentDirectory:Fe,availableWorktreesByProject:gt,pinnedSessionIds:pe,sessionOrderRanks:We,foldersMap:Me,collapsedFolderIds:xt,gitBranches:pt,gitRepoStatus:Ao,updateStore:oe,showArchivedSessions:Kl,projectRepoStatus:G,projectRootBranches:lt,resolvedWorktreeTopologyKey:Ht,unresolvedWorktreeProjectPaths:ns,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:m,editTitle:g,editingProjectDialogId:j,expandedParents:A,collapsedProjects:M,visibleSessionCountByGroup:Z,updateDialogOpen:U,openSidebarMenuKey:T,renamingFolderId:Q,renameFolderDraft:z,deleteSessionConfirm:Te,deleteFolderConfirm:_e,bulkDeleteConfirm:Be,collapsedGroups:q},Eo=o.useRef(null),To=Eo.current;if(To){let y=!1;for(const Y of Object.keys(ar))Object.is(To[Y],ar[Y])||(is(`ui.session_sidebar.source.${Y}`),y=!0);y||is("ui.session_sidebar.source.parent_or_context")}Eo.current=ar;const Hl=o.useMemo(()=>{const y=new Map(ir.map((Y,W)=>[Y,W]));return[...xs].sort((Y,W)=>(y.get(Y.id)??1/0)-(y.get(W.id)??1/0))},[ir,xs]),{projectSections:Dt,groupSearchDataByGroup:Ro,sectionsForRender:Mo,flatSectionsForRender:Sn,searchMatchCount:Wl}=Lh({normalizedProjects:Hl,getSessionsForProject:Ul,getArchivedSessionsForProject:Gl,availableWorktreesByProject:gt,projectRepoStatus:G,projectRootBranches:lt,lastRepoStatus:Do.current,buildGroupedSessions:js,hasSessionSearchQuery:dt,normalizedSessionSearchQuery:qe,filterSessionNodesForSearch:gs,buildGroupSearchText:Qs,foldersMap:Me}),jn=o.useMemo(()=>{const y=he.filter(W=>Xn(Gs(W),xe));if(y.length===0)return null;const Y=js(y,"~",[],null,!1).map(W=>dt?{...W,sessions:gs(W.sessions,qe)}:W).filter(W=>W.sessions.length>0&&!W.isArchivedBucket);return Y.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Y}},[js,gs,dt,xe,qe,he]),Yl=o.useMemo(()=>{if(!dt||!jn)return 0;const y=Y=>Y.reduce((W,De)=>W+1+y(De.children),0);return jn.groups.reduce((Y,W)=>Y+y(W.sessions),0)},[jn,dt]),Vl=o.useMemo(()=>t.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[t.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),t.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:ql}=Fh(X),Fo=o.useRef(!1);o.useEffect(()=>{if(Fo.current||Dt.length===0)return;const y=Dt.flatMap(Y=>Y.groups.filter(W=>W.isArchivedBucket).map(W=>`${Y.project.id}:${W.id}`));y.length>0&&ge(Y=>new Set([...Y,...y])),Fo.current=!0},[Dt]),o.useMemo(()=>{const y=new Map,Y=new Map;return Dt.forEach(W=>{const De=er(W.project.label?.trim()||Rs(W.project.normalizedPath,xe)||W.project.normalizedPath);W.groups.forEach(ct=>{const Lt=ct.branch&&ct.branch!=="HEAD"&&ct.branch!==De?ct.branch:null,Js={projectLabel:De,branchLabel:Lt},Cs=Sc=>{Sc.forEach(Bs=>{const zo=W.project.normalizedPath.length,jc=Y.get(Bs.session.id)??-1;zo<jc||(y.set(Bs.session.id,{node:Bs,projectId:W.project.id,groupDirectory:ct.directory,secondaryMeta:Js}),Y.set(Bs.session.id,zo),Bs.children.length>0&&Cs(Bs.children))})};Cs(ct.sessions)})}),y},[Dt,xe]);const Lo=o.useMemo(()=>Sn.map(y=>y.groups.some(Y=>Y.isArchivedBucket)?{...y,groups:y.groups.filter(Y=>!Y.isArchivedBucket)}:y),[Sn]),Ql=o.useMemo(()=>{if(!k)return Lo;const y=Mo.find(De=>De.project.id===k);if(!y)return[];const Y=Qe(D??y.project.normalizedPath),W=y.groups.find(De=>!De.isArchivedBucket&&Qe(De.directory)===Y);return W?[{...y,groups:[W]}]:[]},[Mo,Lo,k,D]),Jl=o.useMemo(()=>{let y=0;for(const Y of Dt)for(const W of Y.groups)W.isArchivedBucket||(y+=W.sessions.length);return y},[Dt]),Xl=o.useMemo(()=>{const y=new Map;for(const Y of Dt){let W=0;for(const De of Y.groups)De.isArchivedBucket||(W+=De.sessions.length);y.set(Y.project.id,W)}return y},[Dt]),Zl=o.useCallback(y=>{const Y=Dt.find(W=>W.project.id===y);return Y?Y.groups.some(W=>W.isArchivedBucket?!1:W.sessions.some(De=>$e.has(De.session.id))):!1},[$e,Dt]),ec=o.useMemo(()=>{const y=new Map;for(const Y of Dt){const W=new Set;for(const De of Y.groups){if(De.isArchivedBucket)continue;if(De.sessions.some(Lt=>$e.has(Lt.session.id))&&De.directory){const Lt=Qe(De.directory)?.toLowerCase();Lt&&W.add(Lt)}}W.size>0&&y.set(Y.project.id,W)}return y},[$e,Dt]),tc=o.useCallback(y=>{const Y=Dt.find(W=>W.project.id===y);return Y?Y.groups.some(W=>W.isArchivedBucket?!1:W.sessions.some(De=>ze.has(De.session.id))):!1},[Dt,ze]),sc=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",nc=s?"size-4":"h-4.5 w-4.5",Cn=ts((y,Y=0,W,De,ct=!1,Lt,Js="project",Cs)=>t.jsx(lm,{node:y,depth:Y,groupDirectory:W,projectId:De,archivedBucket:ct,pinnedSessionIds:pe,expandedParents:wn,hasSessionSearchQuery:dt,normalizedSessionSearchQuery:qe,notifyOnSubtasks:Pe,editingId:m,setEditingId:f,editTitle:g,setEditTitle:S,handleSaveEdit:El,handleCancelEdit:Tl,toggleParent:Dl,handleSessionSelect:yn,handleSessionDoubleClick:Pl,togglePinnedSession:J,handleShareSession:Rl,copiedSessionId:gl,handleCopyShareUrl:Ml,handleCopySessionId:Fl,handleUnshareSession:Ll,openSidebarMenuKey:T,setOpenSidebarMenuKey:R,renamingFolderId:Q,getFoldersForScope:Xe,getSessionFolderId:Ue,removeSessionFromFolder:At,addSessionToFolder:Et,createFolderAndStartRename:or,handleDeleteSession:Ol,handleRestoreSession:Bl,mobileVariant:s,alwaysShowActions:ms,allowQuickArchiveAction:qs,renderSessionNode:Cn,secondaryMeta:Lt,renderContext:Js,subtreeContainsEditing:Cs?.subtreeContainsEditing??mm,menuOpenSessionId:Cs?.menuOpenSessionId??null,nodeStructureKey:Cs?.nodeStructureKey??"",childRenderExtrasFor:Cs?.childRenderExtrasFor})),rc=o.useMemo(()=>{const y=new Map;return Sn.forEach(Y=>{const W=Y.groups.find(De=>!De.isArchivedBucket);W?.folderScopes&&W.folderScopes.length>0&&y.set(Y.project.id,W.folderScopes)}),y},[Sn]),oc=o.useCallback((y,Y)=>{const W=[];return Y.forEach(De=>{De.isArchivedBucket||(W.push(De.directory),De.folderScopes?.forEach(ct=>W.push(ct.directory)))}),t.jsx(xm,{directories:W})},[]),Oo=o.useCallback(y=>{vn(y),ge(Y=>{const W=new Set(Y);return W.has(y)?W.delete(y):W.add(y),W})},[vn]),ic=o.useCallback((y,Y,W,De,ct,Lt,Js)=>t.jsx(Ap,{group:y,groupKey:Y,projectId:W,hideGroupLabel:De,dragHandleProps:ct,compactBodyPadding:Lt,hasSessionSearchQuery:dt,normalizedSessionSearchQuery:qe,groupSearchDataByGroup:Ro,visibleSessionCount:Z.get(Y),collapsedGroups:q,hideDirectoryControls:a,collapsedFolderIds:xt,toggleFolderCollapse:Ne,renameFolder:Nt,deleteFolder:Pt,showDeletionDialog:He,setDeleteFolderConfirm:Ve,renderSessionNode:Cn,showMoreGroupSessions:ko,resetGroupSessionLimit:vn,mobileVariant:s,alwaysShowActions:ms,activeProjectId:Ke,setActiveProjectIdOnly:ht,setActiveMainTab:ye,setSessionSwitcherOpen:de,openNewSessionDraft:ne,addSessionToFolder:Et,createFolderAndStartRename:or,renamingFolderId:Q,renameFolderDraft:z,setRenameFolderDraft:Re,setRenamingFolderId:ae,pinnedSessionIds:pe,expandedParents:wn,sessionOrderIndex:Ge,editingId:m,editTitle:g,openSidebarMenuKey:T,activeActivitySessionIds:$e,unreadActivitySessionIds:ze,notifyOnSubtasks:Pe,onToggleCollapsedGroup:Oo,scrollContainerRef:Js}),[dt,qe,Ro,Z,q,a,xt,Ne,Nt,Pt,He,Cn,ko,vn,s,ms,Ke,ht,ye,de,ne,Et,or,Q,z,pe,wn,Ge,m,g,T,$e,ze,Pe,Oo]),Bo=!!(Q||m||j),{selectionModeEnabled:_o,hasSelection:ac,selectedIdsSize:lc,bulkScopeIsArchived:cc,derivedSelectionScope:dc,bulkScopeFolders:uc,bulkCanRemoveFromFolder:fc,handleToggleSelectionMode:hc,handleExitSelectionMode:pc,handleBulkMoveToFolder:mc,handleBulkCreateFolderAndMove:gc,handleBulkRemoveFromFolder:xc,handleBulkDelete:bc,handleBulkRestore:yc,confirmBulkDelete:vc}=pm({isInlineEditing:Bo,showDeletionDialog:He,foldersMap:Me,folderScopesByProject:rc,addSessionsToFolder:It,removeSessionsFromFolders:F,createFolderAndStartRename:Co,archiveSessions:So,unarchiveSessions:ml,deleteSessions:wo,setBulkDeleteConfirm:ie}),wc=o.useCallback(()=>{fe.getState().closeMainSurfaces(),ye("chat"),s&&de(!1),H(),r?.()},[s,r,H,ye,de]);return t.jsx(Ed,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:h,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(gm,{owner:ut,childStores:re,projectSections:Dt,activeProjectId:Ke,collapsedProjects:M,collapsedGroups:q,currentDirectory:Fe}),t.jsx(Bh,{projectSections:Dt,activeProjectId:Ke,initialActiveSessionByProject:Ae,persistActiveSessionByProject:je,handleSessionSelect:yn,mobileVariant:s,openNewSessionDraft:H,setActiveMainTab:ye,setSessionSwitcherOpen:de}),t.jsx(Rh,{enabled:e,sortedSessions:ue,prefetchSession:async y=>{await L.syncSession(y)}}),!a&&!s?t.jsx(Dp,{onNewSession:wc,showSidebarToggle:!0}):null,t.jsx(Ip,{hideDirectoryControls:a,handleOpenDirectoryDialog:jo,onOpenArchive:()=>{s&&de(!1),Se(!0)},onOpenSettings:s?vo:void 0,onOpenInstances:s?Vt?.openInstances:void 0,instanceLabel:s?Vt?.instanceLabel:void 0,onOpenUpdate:s?Vt?.openUpdate:void 0,headerActionIconClass:nc,headerActionButtonClass:sc,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:p,hasSessionSearchQuery:dt,searchMatchCount:Wl+(k===null?Yl:0),selectionModeEnabled:_o,onToggleSelectionMode:hc,mobileVariant:s}),me==="error"||me==="unavailable"?t.jsx("div",{role:"alert",className:"mx-3 mb-2 rounded bg-[var(--status-error-background)] p-2 text-xs text-[var(--status-error-foreground)]",children:"Unable to reach server"}):null,!a&&Dt.length>0?t.jsx(Tp,{projects:Dt.map(y=>y.project),selectedProjectId:k,selectedWorktreePath:D,worktreesByProject:gt,worktreeErrorsByProject:Bt,onSelectProject:y=>{if(I(y),P(null),!y)return;ht(y);const Y=Dt.find(ct=>ct.project.id===y),W=Y?.groups.find(ct=>ct.isMain),De=W?.sessions[0]?.session;De?yn(De.id,W?.directory??Y?.project.normalizedPath??null,{keepPanelOpen:!0}):Y&&ne({selectedProjectId:y,directoryOverride:Y.project.normalizedPath})},onSelectWorktree:(y,Y)=>{I(y),P(Y),ht(y);const ct=Dt.find(Lt=>Lt.project.id===y)?.groups.find(Lt=>Qe(Lt.directory)===Qe(Y))?.sessions[0]?.session;ct?yn(ct.id,Y,{keepPanelOpen:!0}):ne({selectedProjectId:y,directoryOverride:Y})},onOpenDirectoryDialog:jo,onOpenProjectEditDialog:B,onRemoveProject:kt,totalSessionCount:Jl,getSessionCountForProject:y=>Xl.get(y)??0,hasActiveSessionByProject:Zl,activeDirectoriesByProject:ec,hasUnseenByProject:tc,homeDirectory:xe,mobileVariant:s}):null,t.jsx(Lp,{sectionsForRender:Ql,allFoldersOnlySection:k===null?jn:null,projectSections:Dt,activeProjectId:Ke,showOnlyMainWorkspace:l,hasSessionSearchQuery:dt,emptyState:wt,searchEmptyState:Vl,isAllFoldersView:k===null,pinnedSessionIds:pe,renderSessionNode:Cn,renderGroupSessions:ic,homeDirectory:xe,collapsedProjects:M,hideDirectoryControls:a,projectRepoStatus:G,mobileVariant:s,alwaysShowActions:ms,toggleProject:_l,setActiveProjectIdOnly:ht,setActiveMainTab:ye,setSessionSwitcherOpen:de,openNewSessionDraft:ne,openProjectEditDialog:B,removeProject:kt,reorderProjects:ke,getOrderedGroups:ql,setGroupOrderByProject:be,renderProjectStatusIndicator:oc,openSidebarMenuKey:T,setOpenSidebarMenuKey:R,isInlineEditing:Bo}),_o&&ac?t.jsx(hm,{selectedCount:lc,scopeKey:dc,scopeFolders:uc,archivedBucket:cc,onMoveToFolder:mc,onCreateFolderAndMove:gc,onRemoveFromFolder:xc,canRemoveFromFolder:fc,onRestore:yc,onDelete:bc,onDone:pc}):null,s?null:t.jsx(Rp,{onOpenSettings:vo,onOpenShortcuts:se,onOpenAbout:()=>{V("about"),w(!0)},onOpenUpdate:Os,showRuntimeButtons:!0,showUpdateButton:ul}),t.jsx(Fa,{open:U,onOpenChange:K,info:oe.info,downloading:oe.downloading,downloaded:oe.downloaded,progress:oe.progress,error:oe.error,onDownload:oe.downloadUpdate,onRestart:oe.restartToUpdate,runtimeType:oe.runtimeType}),t.jsx(lp,{open:!!St,onOpenChange:y=>{y||B(null)},project:St,onSave:rs}),t.jsx(dm,{value:Te,setValue:Ye,showDeletionDialog:He,setShowDeletionDialog:mt,onConfirm:Al}),t.jsx(fm,{value:_e,setValue:Ve,onConfirm:Il}),t.jsx(um,{value:Be,setValue:ie,showDeletionDialog:He,setShowDeletionDialog:mt,onConfirm:vc})]})})},Tx=o.memo(bm),Li=6,ss=.18,sn=1.2,nn=.38,Un=48,ym=(e,s)=>e==="left"?s<0:s>0,Rx=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),Mx=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,Oi=(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)),Fx=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<-ss:c>ss,u=s==="left"?c>ss:c<-ss;return d||!u&&a<nn}return Math.abs(n)>=Un&&Math.abs(r)<=Math.abs(n)*sn&&ym(s,n)},vm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:i,progress:a}=e,l=r/Math.max(1,i);return s==="left"?n?l<-ss?!1:l>ss?!0:a>nn:l>ss?!0:l<-ss?!1:a>nn:n?l>ss?!1:l<-ss?!0:a>nn:l<-ss?!0:l>ss?!1:a>nn},wm='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Sm=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(wm);if(a&&s.contains(a))return!0}else{const a=e.closest("[data-no-drawer-swipe]");if(a&&s.contains(a))return!0}let i=e;for(;i&&i!==s;){if(i instanceof HTMLElement&&i.scrollWidth>i.clientWidth){const a=getComputedStyle(i).overflowX;if(a==="auto"||a==="scroll")return!0}i=i.parentElement}return!1},jm=({value:e,options:s,disabled:n,onChange:r})=>{const i=e||"Default",a=t.jsxs("div",{className:_("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(C,{name:"arrow-down-s",className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]});return n?a:t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:a}),t.jsxs(Xt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[t.jsx(Ct,{className:"typography-meta",onSelect:()=>r(""),children:t.jsx("span",{className:_("font-medium",!e&&"text-primary"),children:"Default"})}),s.map(l=>t.jsx(Ct,{className:"typography-meta",onSelect:()=>r(l),children:t.jsx("span",{className:_("font-medium capitalize",e===l&&"text-primary"),children:l})},l))]})]})},Bi=e=>({providerID:e.providerID,modelID:e.modelID,variant:e.variant,agent:e.agent});function Cm(e){const{open:s,onOpenChange:n,projectDirectory:r,submitting:i=!1,onConfirm:a}=e,l=_t(b=>b.loadProviders),c=_t(b=>b.loadAgents),d=_t(b=>b.providers),u=_t(b=>b.currentProviderId),p=_t(b=>b.currentModelId),h=_t(b=>b.currentVariant||""),x=_t(b=>b.currentAgentName||""),[m,f]=o.useState(()=>Bi({providerID:u,modelID:p,variant:h,agent:x}));o.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),o.useEffect(()=>{s&&f(Bi({providerID:u,modelID:p,variant:h,agent:x}))},[s,u,p,h,x]),o.useEffect(()=>{if(!s||d.length===0)return;const b=d.find(k=>k.id===m.providerID)??d[0],v=Array.isArray(b?.models)?b.models:[],M=v.some(k=>k.id===m.modelID),N=v[0]?.id??"";b?.id===m.providerID&&M||f(k=>({...k,providerID:typeof b?.id=="string"?b.id:"",modelID:typeof N=="string"?M?k.modelID:N:"",variant:""}))},[s,d,m.providerID,m.modelID]),o.useCallback(b=>Td(b.mode),[]);const g=o.useMemo(()=>{const v=d.find(M=>M.id===m.providerID)?.models?.find(M=>M.id===m.modelID);return v?.variants?Object.keys(v.variants):[]},[d,m.providerID,m.modelID]),S=g.length>0;o.useEffect(()=>{S||!m.variant||f(b=>({...b,variant:""}))},[S,m.variant]);const j=m.providerID.trim().length>0&&m.modelID.trim().length>0,B=o.useCallback(()=>{!j||i||a(m)},[j,i,a,m]);return o.useEffect(()=>{if(!s)return;const b=v=>{(v.metaKey||v.ctrlKey)&&v.key==="Enter"&&(v.preventDefault(),B())};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[s,B]),t.jsx(as,{open:s,onOpenChange:b=>{i||n(b)},children:t.jsxs(ls,{className:"max-w-md overflow-visible",children:[t.jsx(Ss,{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(jm,{value:m.variant,options:g,disabled:!S,onChange:b=>f(v=>({...v,variant:b}))})]})}),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(Ze,{variant:"ghost",size:"sm",onClick:()=>n(!1),disabled:i,children:"Cancel"}),t.jsx(Ze,{size:"sm",onClick:B,disabled:!j||i,children:i?"Sending":"Send"})]})})]})})}const Zr=5,ll=15,Rn=new Map,Gn=e=>{const s=Math.sqrt(e/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},km=(e,s)=>{const n=Gn(s);return Math.max(n*Zr,Math.min(n*ll,n*e))},Nm=async(e,s)=>{const n=await Od(e.path);return{...e,title:n?.title||e.path.split("/").pop()||s}},Am=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_i=e=>[...e.filter(s=>!s.completed),...e.filter(s=>s.completed)],zi=(e,s)=>{const n=e.findIndex(r=>r.completed);return n===-1?[...e,s]:[...e.slice(0,n),s,...e.slice(n)]},Im=({id:e,children:s})=>{const{attributes:n,listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=ho({id:e});return t.jsx("li",{ref:i,style:{transform:po.Transform.toString(l),transition:c},className:_(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},Dm=({projectRef:e,projectLabel:s,onActionComplete:n,className:r})=>{const[i,a]=o.useState(!1),[l,c]=o.useState(""),[d,u]=o.useState([]),[p,h]=o.useState(""),[x,m]=o.useState(null),[f,g]=o.useState(()=>new Set),[S,j]=o.useState([]),[B,A]=o.useState(null),[b,v]=o.useState(!1),[M,N]=o.useState(0),k=o.useRef(!1),I=o.useRef(""),D=o.useRef(null),P=fe(w=>w.todoPanelHeight),G=fe(w=>w.setTodoPanelHeight),ee=fe(w=>w.notesPanelHeight),Z=fe(w=>w.setNotesPanelHeight),[te,U]=o.useState(!1),K=o.useRef(0),T=o.useRef(P),R=Oe(w=>w.currentSessionId),Q=Oe(w=>w.createSession),ae=Oe(w=>w.initializeNewPiChamberSession),z=Oe(w=>w.sendMessage),Re=Oe(w=>w.setCurrentSession),Te=Rd(w=>w.setPendingInputText),Ye=ws(w=>w.currentDirectory),_e=fe(w=>w.openContextPanelTab),Ve=fe(w=>w.setActiveMainTab),Be=fe(w=>w.setSessionSwitcherOpen),ie=fe(w=>w.padding),pe=o.useCallback(async(w,V)=>{if(!e)return!1;const se=e.id,Se=(Rn.get(se)??Promise.resolve()).catch(()=>{}).then(()=>Md(e,{notes:w,todos:V}));Rn.set(se,Se);try{const Pe=await Se;return Pe||le.error("Failed to save project notes"),Pe}finally{Rn.get(se)===Se&&Rn.delete(se)}},[e]);o.useEffect(()=>{if(!e){c(""),u([]),j([]),h(""),g(new Set);return}let w=!1;return a(!0),(async()=>{try{const V=await Fd(e),se=await Promise.all(V.plans.map(de=>Nm(de,"Plan")));if(w)return;c(V.notes),u(_i(V.todos)),j(se),I.current=V.notes,k.current=!0,h(""),g(new Set)}catch{w||(le.error("Failed to load project notes"),c(""),u([]),j([]),I.current="",k.current=!0)}finally{w||a(!1)}})(),()=>{w=!0}},[M,e]),o.useEffect(()=>{if(!e)return;const w=V=>{const se=V.detail;se?.projectId&&se.projectId!==e.id||N(de=>de+1)};return window.addEventListener("pichamber:project-plan-saved",w),window.addEventListener("pichamber:project-notes-updated",w),()=>{window.removeEventListener("pichamber:project-plan-saved",w),window.removeEventListener("pichamber:project-notes-updated",w)}},[e]),o.useEffect(()=>{if(d.length<7)return;const w=km(d.length,ie),V=Gn(ie)*Zr;P!==w&&(P<V||P>w)&&G(w)},[d.length,ie,P,G]),o.useEffect(()=>{if(!te)return;const w=se=>{const de=se.clientY-K.current,Se=Math.min(Gn(ie)*ll,Math.max(Gn(ie)*Zr,T.current+de));G(Se)},V=()=>{U(!1)};return window.addEventListener("pointermove",w),window.addEventListener("pointerup",V,{once:!0}),window.addEventListener("pointercancel",V,{once:!0}),()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",V),window.removeEventListener("pointercancel",V)}},[te,ie,G]);const We=o.useCallback(w=>{U(!0),K.current=w.clientY,T.current=P,w.preventDefault()},[P]),Ce=o.useCallback(()=>{D.current!==null&&(window.clearTimeout(D.current),D.current=null)},[]),ve=o.useCallback(()=>{Ce(),I.current=l,pe(l,d)},[Ce,l,pe,d]);o.useEffect(()=>{if(!(!e||!k.current)&&l!==I.current)return D.current=window.setTimeout(()=>{D.current=null,I.current=l,pe(l,d)},400),()=>{Ce()}},[Ce,l,pe,e,d]),o.useEffect(()=>()=>Ce(),[Ce]);const $e=o.useCallback(()=>{const w=p.trim();if(!w)return;const V=zi(d,{id:Am(),text:w.slice(0,kn),completed:!1,createdAt:Date.now()});u(V),h(""),pe(l,V)},[p,l,pe,d]),ot=o.useCallback(w=>{g(V=>{const se=new Set(V);return se.has(w)?se.delete(w):se.add(w),se})},[]),ze=o.useCallback((w,V)=>{const se=d.find(He=>He.id===w);if(!se||se.completed===V)return;const de=d.filter(He=>He.id!==w),Se={...se,completed:V},Pe=V?[...de,Se]:zi(de,Se);u(Pe),pe(l,Pe)},[l,pe,d]),J=o.useCallback(w=>{const V=d.filter(se=>se.id!==w);u(V),pe(l,V)},[l,pe,d]),q=o.useCallback(()=>{const w=d.filter(V=>!V.completed);w.length!==d.length&&(u(w),pe(l,w))},[l,pe,d]),ge=o.useCallback(w=>{const{active:V,over:se}=w;if(!se||V.id===se.id)return;const de=d.findIndex(He=>He.id===V.id),Se=d.findIndex(He=>He.id===se.id);if(de===-1||Se===-1)return;const Pe=_i(Xu(d,de,Se));u(Pe),pe(l,Pe)},[l,pe,d]),X=tr(pn(uo,{activationConstraint:{distance:8}})),be=p.slice(0,kn),Ae=d.reduce((w,V)=>w+(V.completed?1:0),0),je=o.useCallback(()=>{Ve("chat"),Be(!1)},[Ve,Be]),lt=o.useCallback((w,V)=>{!e||x!==null||A({todoId:w,todoText:V})},[e,x]),jt=o.useCallback(w=>{if(!R){le.error("No active session selected");return}je();const V=`\`\`\`md
47
- ${w}
48
- \`\`\``;Te(V,"append"),le.success("Todo sent to current session"),n?.()},[R,n,je,Te]),it=o.useCallback(async w=>{if(!e||!B)return;const V=await Qo("plan.todo.visible",{todo_text:B.todoText}),de=[{synthetic:!0,text:await Qo("plan.todo.instructions",{todo_text:B.todoText})}];v(!0),m(B.todoId);try{je();const Se=await Q(void 0,e.path,null);if(!Se?.id){le.error("Failed to create session");return}const Pe=Se.id,He=Se.directory??e.path;ae(Se.id,_t.getState().agents??[]);const mt=na.getState();mt.saveSessionModelSelection(Pe,w.providerID,w.modelID),w.agent.trim()&&(mt.saveSessionAgentSelection(Pe,w.agent),mt.saveAgentModelForSession(Pe,w.agent,w.providerID,w.modelID),mt.saveAgentModelVariantForSession(Pe,w.agent,w.providerID,w.modelID,w.variant||void 0)),Re(Pe,He),await z(V,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"),A(null),n?.()}catch{le.error("Failed to send note")}finally{v(!1),m(null)}},[Q,ae,n,B,e,je,z,Re]),xe=o.useRef(null),[Fe,Le]=o.useState(!1),[Ke,kt]=o.useState(null),ht=o.useCallback(async w=>{if(!(!e||Ke)){kt(w);try{if(!await Ld(e,w)){le.error("Failed to delete plan");return}j(se=>se.filter(de=>de.id!==w)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}}))}finally{kt(null)}}},[Ke,e]),O=o.useCallback(async()=>{if(!e||Fe)return;const w=await xu({defaultPath:e.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(w.success&&w.path){Le(!0);try{const V=new URLSearchParams({path:w.path,allowOutsideWorkspace:"true"});w.outsideFileGrant&&V.set("outsideFileGrant",w.outsideFileGrant);const se=await es(`/api/fs/read?${V.toString()}`,{cache:"no-store"});if(!se.ok){le.error("Failed to read plan file");return}const de=await se.text();if(!de.trim()){le.error("Plan file is empty");return}const Se=w.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await Jo(e,de,Se)){le.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:e.id}})),le.success("Plan imported")}catch(V){const se=V instanceof Error?V.message:void 0;le.error("Failed to read plan file",se?{description:se}:void 0)}finally{Le(!1)}}else w.error==="Native file picker not available"&&xe.current?.click()},[Fe,e]),ke=o.useCallback(async w=>{if(!(!e||!w)){Le(!0);try{const V=await w.text();if(!V.trim()){le.error("Plan file is empty");return}const se=w.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await Jo(e,V,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(V){const se=V instanceof Error?V.message:void 0;le.error("Failed to read plan file",se?{description:se}:void 0)}finally{Le(!1)}}},[e]),ye=o.useCallback(w=>{const V=e?.path?.trim(),se=Ye?.trim()||V;se&&_e(se,{mode:"file",targetPath:w.path,dedupeKey:w.path,label:w.title})},[Ye,_e,e]);return e?t.jsxs("div",{className:_("w-full min-w-0 space-y-3 p-3",r),children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:e.path,children:`Quick notes - ${s?.trim()||e.path.split("/").filter(Boolean).pop()||e.path}`}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length,"/",Xo]})]}),t.jsx(go,{value:l,onChange:w=>c(w.target.value.slice(0,Xo)),onBlur:ve,placeholder:"Capture context, reminders, or links",resizedHeight:ee,onResizeHeightChange:Z,useScrollShadow:!0,scrollShadowSize:56,disabled:i})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Todo"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:d.length===1?`${d.length} item`:`${d.length} items`}),t.jsx("button",{type:"button",onClick:q,disabled:i||Ae===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:[be.length,"/",kn]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{value:be,onChange:w=>h(w.target.value.slice(0,kn)),onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),$e())},placeholder:"Add a todo",disabled:i,className:"h-8"}),t.jsx("button",{type:"button",onClick:$e,disabled:i||be.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(C,{name:"add",className:"h-4 w-4"})})]}),t.jsx("div",{className:_("overflow-y-auto rounded-lg border border-border/60 bg-background/40",te&&"transition-none"),style:d.length<7?void 0:{height:`${P}px`,maxHeight:`${P}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(sr,{sensors:X,collisionDetection:nr,onDragEnd:ge,children:t.jsx(fo,{items:d.map(w=>w.id),strategy:Pa,children:t.jsx("ul",{className:"divide-y divide-border/50",children:d.map(w=>{const V=f.has(w.id);return t.jsx(Im,{id:w.id,children:se=>t.jsxs("div",{className:_("flex gap-1.5 px-2.5 py-1.5",V?"items-start":"items-center"),children:[t.jsx("button",{type:"button",ref:se.setActivatorNodeRef,...se.attributes,...se.listeners,onClick:de=>{de.preventDefault(),de.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":`Reorder \\"${w.text}\\"`,title:`Reorder \\"${w.text}\\"`,children:t.jsx(C,{name:"draggable",className:"h-3.5 w-3.5"})}),t.jsx("div",{className:"flex h-6 items-center",children:t.jsx(Zi,{checked:w.completed,onChange:de=>ze(w.id,de),ariaLabel:`Mark \\"${w.text}\\" complete`})}),t.jsx("button",{type:"button",onClick:()=>ot(w.id),className:_("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",V?"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:V?void 0:w.text,"aria-label":V?`Collapse todo \\"${w.text}\\"`:`Expand todo \\"${w.text}\\"`,children:w.text}),t.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:()=>J(w.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete \\"${w.text}\\"`,title:`Delete \\"${w.text}\\"`,children:t.jsx(C,{name:"delete-bin",className:"h-3.5 w-3.5"})}),t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:x===w.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Send \\"${w.text}\\"`,title:`Send \\"${w.text}\\"`,children:t.jsx(C,{name:"send-plane",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-56",children:[t.jsx(Ct,{onClick:()=>jt(w.text),children:"Send to current session"}),t.jsx(Ct,{onClick:()=>lt(w.id,w.text),children:"Send to new session"})]})]})]})]})},w.id)})})})})}),d.length>=7&&t.jsx("div",{className:_("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",te&&"bg-[var(--interactive-border)]"),onPointerDown:We,role:"separator","aria-orientation":"horizontal","aria-label":"Resize todo list"})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Plans"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:S.length===1?`${S.length} file`:`${S.length} files`})]}),t.jsx("input",{ref:xe,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:w=>{const V=w.target.files?.[0]??null;ke(V),w.currentTarget.value=""}}),t.jsx("button",{type:"button",onClick:O,disabled:!e||Fe,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Import plan from file",title:"Import plan from file",children:t.jsx(C,{name:"add",className:"h-3.5 w-3.5"})})]}),t.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:S.length===0?t.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No saved plans yet."}):t.jsx("ul",{className:"divide-y divide-border/50",children:S.map(w=>t.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[t.jsxs("button",{type:"button",onClick:()=>ye(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:()=>{ht(w.id)},disabled:Ke===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(C,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id))})})]}),t.jsx(Cm,{open:B!==null,onOpenChange:w=>{!w&&!b&&A(null)},projectDirectory:e?.path??null,submitting:b,onConfirm:it})]}):t.jsx("div",{className:_("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."})})},Lx=({onActionComplete:e})=>{const s=$t(c=>c.activeProjectId),n=$t(c=>c.projects),r=ws(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()||Rs(i.path,r)||i.path:null,[i,r]);return t.jsx("div",{className:"h-full min-h-0 overflow-auto bg-transparent",children:t.jsx(Dm,{projectRef:a,projectLabel:l,onActionComplete:e})})},Kn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),eo=512*1024,Pm=new TextEncoder,Em=new TextDecoder,xr=e=>{const s=Pm.encode(e);if(s.byteLength<=eo)return{text:e,byteLength:s.byteLength};let n=s.byteLength-eo;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:Em.decode(r),byteLength:r.byteLength}},_s=(e,s)=>`${e}\0${s}`,br=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},Tm="terminal-store";let $i=!1,Ui=0;const Mn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Ui+=1,`tab-${Date.now().toString(36)}-${Ui.toString(36)}`),yr=e=>typeof e=="object"&&e!==null,Rm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function zt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const Mm=/^Terminal(?: (\d+))?$/,Fm=e=>{let s=0;for(const n of e){const r=Mm.exec(n.label);if(!r)continue;const i=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(i)&&(s=Math.max(s,i))}return s===0?"Terminal":`Terminal ${s+1}`},vr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),wr=e=>({tabs:[e],activeTabId:e.id}),os=(e,s)=>e.tabs.findIndex(n=>n.id===s);let Sr=null,jr=null;const Lm=e=>{if(jr&&Sr?.sessions===e.sessions&&Sr.nextTabId===e.nextTabId)return jr;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 Sr={sessions:e.sessions,nextTabId:e.nextTabId},jr=s,s},Om=()=>{const e=Wu(()=>bu());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()(Ia(co((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=zt(n);r&&e(i=>{if(i.sessions.has(r))return i;const a=new Map(i.sessions),l=Mn(),c=vr(l,"Terminal");return a.set(r,wr(c)),{sessions:a,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const r=zt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=zt(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(zt(n),r))??Kn,createTab:n=>{const r=zt(n);if(!r)return"tab-invalid";const i=Mn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=Fm(c?.tabs??[]),p=vr(i,u);return c?l.set(r,{...c,tabs:[...c.tabs,p]}):l.set(r,wr(p)),{sessions:l,nextTabId:d}}),i},setActiveTab:(n,r)=>{const i=zt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);return!c||c.activeTabId===r||os(c,r)<0?a:(l.set(i,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,i)=>{const a=zt(n),l=i.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const p=os(u,r);if(p<0||u.tabs[p]?.label===l)return c;const h=[...u.tabs];return h[p]={...h[p],label:l},d.set(a,{...u,tabs:h}),{sessions:d}})},setTabIconKey:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=os(d,r);if(u<0)return l;const p=i?.trim()||null;if(d.tabs[u]?.iconKey===p)return l;const h=[...d.tabs];return h[u]={...h[u],iconKey:p},c.set(a,{...d,tabs:h}),{sessions:c}})},closeTab:(n,r)=>{const i=zt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=os(c,r);if(d<0)return a;const u=c.tabs.filter(g=>g.id!==r),p=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,g])=>!(g.directory===i&&g.tabId===r))),h=Object.keys(p).length!==Object.keys(a.projectActionRuns).length,x=_s(i,r),m=a.buffers.has(x)?br(a.buffers,g=>g===x):null;if(u.length===0){const g=Mn(),S=vr(g,"Terminal");return l.set(i,wr(S)),{sessions:l,nextTabId:a.nextTabId+1,...m?{buffers:m}:{},...h?{projectActionRuns:p}:{}}}let f=c.activeTabId;return c.activeTabId===r&&(f=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(i,{...c,tabs:u,activeTabId:f}),{sessions:l,...m?{buffers:m}:{},...h?{projectActionRuns:p}:{}}})},setTabSessionId:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=os(d,r);if(u<0)return l;const p=d.tabs[u],h=i!==null&&p.terminalSessionId!==i,x=i?"running":p.terminalSessionId?"exited":p.lifecycle,m={...p,terminalSessionId:i,lifecycle:x,isConnecting:!1},f=_s(a,r),g=h&&l.buffers.has(f)?br(l.buffers,j=>j===f):null,S=[...d.tabs];return S[u]=m,c.set(a,{...d,tabs:S}),{sessions:c,...g?{buffers:g}:{}}})},setTabLifecycle:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=os(d,r);if(u<0)return l;const p=[...d.tabs];return p[u]={...p[u],lifecycle:i,isConnecting:!1},c.set(a,{...d,tabs:p}),{sessions:c}})},setConnecting:(n,r,i)=>{const a=zt(n);e(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=os(d,r);if(u<0)return l;const p=[...d.tabs];return p[u]={...p[u],isConnecting:i},c.set(a,{...d,tabs:p}),{sessions:c}})},replaceBuffer:(n,r,i,a)=>{const l=zt(n);e(c=>{const d=c.sessions.get(l);if(!d||os(d,r)<0)return c;const u=_s(l,r),p=c.buffers.get(u)??Kn;if(p.lastSequence>a)return c;const h=xr(i);if(p.lastSequence===a&&p.byteLength===h.byteLength&&p.chunks.map(f=>f.data).join("")===h.text)return c;const x=c.nextChunkId,m=new Map(c.buffers);return m.set(u,{chunks:h.text?[{id:x,data:h.text,byteLength:h.byteLength}]:[],byteLength:h.byteLength,lastSequence:a}),{buffers:m,nextChunkId:h.text?x+1:x}})},appendToBuffer:(n,r,i,a,l)=>{if(!i)return;const c=zt(n);e(d=>{const u=d.sessions.get(c);if(!u||os(u,r)<0)return d;const p=_s(c,r),h=d.buffers.get(p)??Kn;if(a!==void 0&&a<=h.lastSequence)return d;const x=d.nextChunkId,m=xr(i),f=l!==void 0&&l!==i?xr(l).text:void 0,g={id:x,data:m.text,...f!==void 0?{replayData:f}:{},byteLength:m.byteLength},S=[...h.chunks,g];let j=h.byteLength+g.byteLength;for(;j>eo&&S.length>1;){const A=S.shift();if(!A)break;j-=A.byteLength}const B=new Map(d.buffers);return B.set(p,{chunks:S,byteLength:j,lastSequence:a??h.lastSequence}),{buffers:B,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,i,a={})=>{const l=zt(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const p=os(u,r);if(p<0)return c;const h=u.tabs[p],x=a.autoOpened??h.previewAutoOpened,m=a.locked??h.previewUrlLocked;if(h.previewUrl===i&&h.previewAutoOpened===x&&h.previewUrlLocked===m)return c;const f=[...u.tabs];return f[p]={...h,previewUrl:i,previewAutoOpened:x,previewUrlLocked:m},d.set(l,{...u,tabs:f}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const i=zt(n);e(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=os(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const p=[...c.tabs];return p[d]={...u,previewAutoOpened:!0},l.set(i,{...c,tabs:p}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const i=r.projectActionRuns[n.key];return i&&i.directory===n.directory&&i.actionId===n.actionId&&i.tabId===n.tabId&&i.sessionId===n.sessionId&&i.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(i=>{const a=i.projectActionRuns[n];return!a||a.status===r?i:{projectActionRuns:{...i.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const i={...r.projectActionRuns};return delete i[n],{projectActionRuns:i}})},removeDirectory:n=>{const r=zt(n);e(i=>{const a=new Map(i.sessions);a.delete(r);const l=_s(r,""),c=br(i.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Tm,storage:Om(),partialize:Lm,merge:(e,s)=>{if(!yr(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"||!yr(u))continue;const p=Array.isArray(u.tabs)?u.tabs:[],h=[],x=new Map;for(const S of p){if(!yr(S))continue;const j=typeof S.id=="string"?S.id:null;if(!j)continue;const B=Rm(j);B!==null&&(i=Math.max(i,B));const A=B===null?j:Mn();x.set(j,A),h.push({id:A,label:typeof S.label=="string"?S.label:"Terminal",iconKey:typeof S.iconKey=="string"?S.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof S.createdAt=="number"?S.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(h.length===0)continue;const m=typeof u.activeTabId=="string"?u.activeTabId:null,f=m?x.get(m)??m:null,g=f?h.some(S=>S.id===f):!1;r.set(d,{tabs:h,activeTabId:g?f:h[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,i+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!$i){$i=!0;const e=Ee.persist,s=()=>{Ee.getState().hasHydrated||Ee.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function Bm(e){const{colors:s}=e,n=s.syntax.base;return{background:s.surface.background,foreground:n.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:s.surface.elevatedForeground}}function _m(e,s,n,r,i=!1){const l=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",fontSize:s,fontFamily:l,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:i}}const Cr=["\x1B[0m","\x1B[m"],zm=e=>{const s=e.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(s)?.[1];if(n){const a=n.length<=4?n.slice(0,3).split("").map(l=>l+l).join(""):n.slice(0,6);return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16)]}const r=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(s);if(!r)return null;const i=r.slice(1,4).map(Number);return i.some(a=>a<0||a>255)?null:i},Gi=e=>{const s=zm(e);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},$m=(e,s,n)=>{const r=s+e;if(!n)return{data:r,carry:""};let i=0;const a=Math.max(...Cr.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);Cr.some(p=>p.length>u.length&&p.startsWith(u))&&(i=d)}const l=i>0?r.slice(-i):"";let c=i>0?r.slice(0,-i):r;for(const d of Cr)c=c.replaceAll(d,n);return{data:c,carry:l}},Um=(e,s,n,r,i)=>{if(n.width<=0||n.height<=0||r<=0||i<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*i);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(i-1,l))}},Gm=(e,s)=>{const n=Math.max(0,Math.min(e.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let i=n,a=n;for(;i>0&&r(e[i-1]);)i-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:i,endColumn:a}};let Km=null;const Hm=()=>Km??=Ps(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,11])).then(async e=>({module:e,ghostty:await e.Ghostty.load()})),Wm=2e3,Ym=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(s=>setTimeout(s,Wm))]).then(()=>{})},Vm=(e,s,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${n}px ${s}`;const i=r.measureText("M"),a=Math.ceil(i.width),l=Math.ceil((i.actualBoundingBoxAscent||n*.8)+(i.actualBoundingBoxDescent||n*.2))+2;if(a<1||l<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/a)),rows:Math.max(1,Math.floor((e.clientHeight-u)/l))}},cl=o.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:i,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:p=!0},h)=>{const x=o.useRef(null),m=o.useRef(null),f=o.useRef(null),g=o.useRef(n),S=o.useRef(r),j=o.useRef(null),B=o.useRef(null),A=o.useRef(null),b=o.useRef(""),v=o.useRef(""),M=o.useRef(Gi(i.background)),N=o.useRef(!1),k=o.useRef(0),I=o.useRef(p),D=o.useRef(!1),[P,G]=o.useState(0),[ee,Z]=o.useState(0);g.current=n,S.current=r,I.current=p,M.current=Gi(i.background),o.useLayoutEffect(()=>{const T=x.current;if(!T)return;const R=Vm(T,a,l);B.current=R,R&&S.current(R.cols,R.rows)},[a,l]);const te=o.useCallback(()=>{const T=x.current,R=m.current;if(!T||!R||!f.current||!I.current)return;const Q=T.getBoundingClientRect();if(!(Q.width<24||Q.height<24))try{f.current.fit();const ae={cols:R.cols,rows:R.rows};(!j.current||j.current.cols!==ae.cols||j.current.rows!==ae.rows)&&(j.current=ae,S.current(ae.cols,ae.rows)),D.current||(D.current=!0,G(z=>z+1))}catch{}},[]),U=o.useCallback(()=>{if(N.current||!b.current||!m.current)return;const T=m.current,R=b.current;b.current="";const Q=$m(R,v.current,M.current);if(v.current=Q.carry,!Q.data){b.current&&U();return}N.current=!0;const ae=k.current;T.write(Q.data,()=>{m.current!==T||k.current!==ae||(N.current=!1,b.current&&U())})},[]),K=o.useCallback(()=>{A.current=null,b.current="",v.current="",N.current=!1,k.current+=1;const T=m.current;if(!T){Z(R=>R+1);return}try{T.reset();const R=M.current;R&&T.write(`${R}\x1B[2J\x1B[H`)}catch{Z(R=>R+1)}},[]);return o.useEffect(()=>{const T=x.current;if(!T)return;let R=!1,Q=null,ae=null,z=null,Re=null,Te=[];const Ye=()=>{Q&&I.current&&(Q.options.cursorBlink=!0)},_e=ie=>{ie.relatedTarget instanceof Node&&T.contains(ie.relatedTarget)||Q&&(Q.options.cursorBlink=!1)},Ve=()=>{Q&&I.current&&T.contains(document.activeElement)&&(Q.options.cursorBlink=!0)},Be=()=>{Q&&(Q.options.cursorBlink=!1)};return T.addEventListener("focusin",Ye),T.addEventListener("focusout",_e),window.addEventListener("focus",Ve),window.addEventListener("blur",Be),Promise.all([Hm(),Ym()]).then(([{module:ie,ghostty:pe}])=>{if(R)return;Q=new ie.Terminal({..._m(a,l,i,pe,!1),...B.current??{}});const We=new ie.FitAddon;Q.loadAddon(We),Q.open(T),m.current=Q,f.current=We,Te=[Q.onData(ve=>g.current(ve))],ae=new ResizeObserver(()=>{z&&clearTimeout(z),z=setTimeout(te,80)}),ae.observe(T),te();const Ce=M.current;Ce&&Q.write(`${Ce}\x1B[2J\x1B[H`),Re=requestAnimationFrame(te)}),()=>{R=!0;const ie=document.activeElement;ie instanceof HTMLElement&&T.contains(ie)&&(ie.blur(),window.Capacitor?.getPlatform?.()==="android"&&Ps(async()=>{const{Keyboard:We}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:We}},__vite__mapDeps([113,114])).then(({Keyboard:We})=>We.hide()).catch(()=>{})),ae?.disconnect(),z&&clearTimeout(z),Re!==null&&cancelAnimationFrame(Re),T.removeEventListener("focusin",Ye),T.removeEventListener("focusout",_e),window.removeEventListener("focus",Ve),window.removeEventListener("blur",Be),Te.forEach(pe=>pe.dispose()),Q?.dispose(),m.current=null,f.current=null,j.current=null,A.current=null,b.current="",v.current="",N.current=!1,k.current+=1,D.current=!1}},[te,a,l,ee,i]),o.useEffect(()=>{const T=m.current,R=x.current;!T||!R||(T.options.cursorBlink=p&&document.hasFocus()&&R.contains(document.activeElement))},[p,P]),o.useEffect(()=>{if(!m.current)return;if(s.length===0){A.current!==null&&K();return}const R=A.current;let Q=-1;if(R!==null){for(let Re=s.length-1;Re>=0;Re-=1){const Te=s[Re].id;if(Te===R){Q=Re;break}if(Te<R)break}if(Q<0){K();return}}const ae=Q<0,z=Q>=0?s.slice(Q+1):s;b.current+=z.map(Re=>ae?Re.replayData??Re.data:Re.data).join(""),A.current=s.at(-1)?.id??null,U()},[s,U,P,K]),o.useEffect(()=>{if(!u||!p)return;const T=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame(T)},[u,p,P,e]),o.useEffect(()=>{const T=x.current;if(!d||!T)return;const R=Q=>{const ae=Q;if(!ae.isComposing)switch(ae.inputType){case"insertText":ae.data&&g.current(ae.data);break;case"insertLineBreak":case"insertParagraph":g.current("\r");break;case"deleteContentBackward":g.current("");break}};return T.addEventListener("beforeinput",R),()=>T.removeEventListener("beforeinput",R)},[d,P]),o.useEffect(()=>{const T=x.current,R=m.current;if(!d||!T||!R)return;let Q=null,ae=null,z="idle",Re=0,Te=0,Ye=0,_e=0,Ve=null;const Be=Math.max(12,l+2),ie=()=>{window.Capacitor?.getPlatform?.()==="android"&&Ps(async()=>{const{Keyboard:ge}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ge}},__vite__mapDeps([113,114])).then(({Keyboard:ge})=>ge.show()).catch(()=>{})},pe=()=>{ae&&(clearTimeout(ae),ae=null)},We=(q,ge)=>{const X=T.querySelector("canvas");return X?Um(q,ge,X.getBoundingClientRect(),R.cols,R.rows):null},Ce=(q,ge)=>{const X=T.querySelector("canvas");if(!X)return;const be=X.getBoundingClientRect(),Ae=be.left+(ge.column+.5)/R.cols*be.width,je=be.top+(ge.row+.5)/R.rows*be.height;X.dispatchEvent(new MouseEvent(q,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:Ae,clientY:je}))},ve=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},$e=q=>{q.pointerType!=="touch"||Q!==null||(Q=q.pointerId,z="pending",Re=q.clientX,Te=q.clientY,Ye=q.clientY,_e=0,Ve=null,T.setPointerCapture(q.pointerId),ae=setTimeout(()=>{if(ae=null,Q!==q.pointerId||z!=="pending")return;const ge=We(Re,Te);if(!ge)return;const X=R.buffer.active,be=Math.max(0,X.length-R.rows-X.viewportY+ge.row),Ae=X.getLine(be),je=Array.from({length:R.cols},(it,xe)=>Ae?.getCell(xe)?.getChars()??""),lt=Gm(je,ge.column),jt={column:lt.startColumn,row:ge.row};Ve={column:lt.endColumn,row:ge.row},z="selecting",Ce("mousedown",jt),Ce("mousemove",Ve)},350))},ot=q=>{if(Q!==q.pointerId)return;if(z==="selecting"){const be=We(q.clientX,q.clientY);be&&(!Ve||be.column!==Ve.column||be.row!==Ve.row)&&(Ve=be,Ce("mousemove",be)),q.cancelable&&q.preventDefault();return}if(z==="pending"){if(Math.hypot(q.clientX-Re,q.clientY-Te)<8)return;pe(),z="scrolling"}if(z!=="scrolling")return;const ge=Ye-q.clientY;Ye=q.clientY,_e+=ge;const X=Math.trunc(_e/Be);X&&(R.scrollLines(X),_e-=X*Be),q.cancelable&&q.preventDefault()},ze=q=>{if(Q!==q.pointerId)return;const ge=z==="pending",X=z==="selecting";pe(),T.hasPointerCapture(q.pointerId)&&T.releasePointerCapture(q.pointerId),Q=null,z="idle",X&&ve(),ge&&(R.focus(),ie())},J=q=>{if(Q!==q.pointerId)return;const ge=z==="selecting";pe(),T.hasPointerCapture(q.pointerId)&&T.releasePointerCapture(q.pointerId),Q=null,z="idle",ge&&ve()};return T.addEventListener("pointerdown",$e),T.addEventListener("pointermove",ot,{passive:!1}),T.addEventListener("pointerup",ze),T.addEventListener("pointercancel",J),()=>{pe(),T.removeEventListener("pointerdown",$e),T.removeEventListener("pointermove",ot),T.removeEventListener("pointerup",ze),T.removeEventListener("pointercancel",J)}},[d,l,P]),o.useImperativeHandle(h,()=>({focus:()=>m.current?.focus(),fit:te,getSelection:()=>{const T=m.current,R=T?.getSelectionPosition(),Q=T?.getSelection()??"";return!R||!Q.trim()?null:{text:Q,startLine:R.start.y+1,endLine:R.end.y+1}}}),[te]),t.jsx("div",{ref:x,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});cl.displayName="TerminalViewport";const qm=280,Ki=4,Qm=({transform:e})=>({...e,y:0}),Jm=({id:e,children:s,className:n})=>{const{attributes:r,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:d}=ho({id:e});return t.jsx("div",{ref:a,"data-sortable-tab-id":e,style:{transform:po.Transform.toString(l),transition:c},className:_("h-full rounded-md",n,d&&"opacity-50"),...r,...i,children:s})},Xm=({id:e,children:s,className:n})=>t.jsx("div",{className:_("h-full",n),"data-sortable-tab-id":e,children:s}),Zm=({items:e,activeId:s,onSelect:n,onClose:r,onReorder:i,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:p,activePillLowercase:h=!0,nonCompositedIndicator:x=!1,className:m})=>{const f=fe(J=>J.isMobile),{isTablet:g}=Ms(),S=f||g,j=o.useRef(null),[B,A]=o.useState({left:!1,right:!1}),b=o.useMemo(()=>e.map(J=>J.id),[e]),v=a==="scrollable",M=l==="default",N=l==="active-pill",I=N||l==="animated",D=M,P=I||D,G=N&&v,ee=I,Z=p??I,te=typeof i=="function",U=te?Jm:Xm,K=o.useRef(new Map),[T,R]=o.useState(null),[Q,ae]=o.useState(!1),[z,Re]=o.useState(null),Te=o.useRef(!1),Ye=o.useRef(0),_e=o.useRef(s),Ve=o.useRef(null),Be=o.useMemo(()=>{if(!P||!z||!s||z===s)return 0;const J=e.findIndex(ge=>ge.id===z),q=e.findIndex(ge=>ge.id===s);return J<0||q<0?0:J>q?Ki:-Ki},[s,e,z,P]),ie=tr(pn(uo,{activationConstraint:{distance:8}})),pe=o.useCallback((J,q)=>!J||!q?J===q:Math.abs(J.left-q.left)<.5&&Math.abs(J.top-q.top)<.5&&Math.abs(J.width-q.width)<.5&&Math.abs(J.height-q.height)<.5,[]),We=o.useCallback((J,q)=>{if(q){K.current.set(J,q);return}K.current.delete(J)},[]),Ce=o.useCallback(()=>{if(!P||!s){R(je=>je===null?je:null);return}const J=j.current,q=K.current.get(s);if(!J||!q){R(je=>je===null?je:null);return}let ge=0,X=0,be=q;for(;be&&be!==J;)ge+=be.offsetLeft,X+=be.offsetTop,be=be.offsetParent;const Ae={left:ge,top:X,width:q.offsetWidth,height:q.offsetHeight};R(je=>pe(je,Ae)?je:Ae)},[s,pe,P]),ve=o.useCallback(()=>{if(!v){A({left:!1,right:!1});return}const J=j.current;if(!J){A({left:!1,right:!1});return}A({left:J.scrollLeft>2,right:J.scrollLeft+J.clientWidth<J.scrollWidth-2})},[v]);o.useEffect(()=>{if(!v){A({left:!1,right:!1});return}const J=j.current;if(!J)return;ve(),J.addEventListener("scroll",ve,{passive:!0});const q=new ResizeObserver(ve);return q.observe(J),()=>{J.removeEventListener("scroll",ve),q.disconnect()}},[v,e.length,ve]),o.useEffect(()=>{if(!P){R(null);return}Ce();const J=j.current;if(!J)return;const q=new ResizeObserver(()=>{performance.now()-Ye.current>qm&&ae(!1),Ce()});if(q.observe(J),s){const ge=K.current.get(s);ge&&q.observe(ge)}return()=>{q.disconnect()}},[s,e.length,Ce,P]),o.useLayoutEffect(()=>{Ce()});const $e=b.join("\0");o.useLayoutEffect(()=>{if(!P){Te.current=!1,ae(!1);return}const J=Ve.current!==$e;if(Ve.current=$e,!Te.current){Te.current=!0,_e.current=s;return}const q=_e.current!==s;if(_e.current=s,!q||J){ae(!1);return}Ye.current=performance.now(),ae(!0)},[s,$e,P]),o.useEffect(()=>{if(!v||!s)return;const J=j.current;if(!J)return;const q=window.requestAnimationFrame(()=>{const ge=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),X=J.querySelector(`[data-sortable-tab-id="${ge}"]`);X&&(X.scrollIntoView({block:"nearest",inline:"nearest"}),ve())});return()=>{window.cancelAnimationFrame(q)}},[s,v,e.length,ve]);const ot=o.useCallback(J=>{if(!i)return;const{active:q,over:ge}=J;!ge||q.id===ge.id||i(String(q.id),String(ge.id))},[i]),ze=t.jsxs("div",{className:_("relative flex h-full min-w-0 flex-1",m),children:[v&&B.left?t.jsx("div",{className:_("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,v&&B.right?t.jsx("div",{className:_("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:j,className:_("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"),D&&"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",v?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:v?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[I&&T?t.jsx("div",{className:_("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&&Q&&(x?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:x?{left:`${T.left+Be}px`,top:`${T.top}px`,width:`${T.width}px`,height:`${T.height}px`}:{transform:`translate3d(${T.left+Be}px, ${T.top}px, 0)`,width:`${T.width}px`,height:`${T.height}px`}}):null,D&&T?t.jsx("div",{className:_("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",Q&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${T.left+Be}px, 0, 0)`,width:`${T.width}px`},"aria-hidden":!0}):null,e.map(J=>{const q=J.id===s,ge=u&&I&&!q&&!!J.icon,X=!ge,be=!!J.icon,Ae=u&&I&&q&&!v&&!G,je=J.closable!==!1&&!!r,lt=je&&!!J.icon,jt=v||G?void 0:I?Ae?"flex-none basis-auto":f?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",it=je?Fe=>{Fe.button===1&&(Fe.preventDefault(),Fe.stopPropagation(),r?.(J.id))}:void 0,xe=je?Fe=>{Fe.button===1&&Fe.preventDefault()}:void 0;return t.jsx(U,{id:J.id,className:jt,children:t.jsxs("div",{ref:Fe=>We(J.id,Fe),onAuxClick:it,onMouseDown:xe,className:_("group flex h-full min-w-0 flex-nowrap items-center",v||G?"shrink-0":I?"w-full":"w-full min-w-0",I?"relative z-10 bg-transparent":q?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[t.jsx("button",{type:"button",role:"tab","aria-selected":q,"aria-label":ge?J.title??J.label:void 0,onClick:()=>n(J.id),onPointerDown:P?()=>{ae(!0),Re(J.id)}:void 0,onPointerUp:P?()=>Re(null):void 0,onPointerLeave:P?()=>Re(null):void 0,onPointerCancel:P?()=>Re(null):void 0,className:_(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&&h?"lowercase":null,I&&(ge?"gap-0":"gap-1.5"),I?G?"shrink-0 whitespace-nowrap px-3 text-center":v?"max-w-56 shrink-0 px-3 text-center":ge?"px-2 !min-w-0 text-center":Ae?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":v?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",I?d??(N?f?"h-[38px]":"h-[31px]":"h-7"):null,I?q?"text-foreground":"text-muted-foreground hover:text-foreground":null,I?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:J.title??J.label,children:I?t.jsxs(t.Fragment,{children:[be?t.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[t.jsx("span",{className:_("flex items-center justify-center transition-opacity",lt&&(S?"opacity-0":"group-hover:opacity-0")),children:J.icon}),lt?t.jsx("span",{role:"button",tabIndex:-1,className:_("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",S?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Fe=>{Fe.stopPropagation()},onClick:Fe=>{Fe.stopPropagation(),r?.(J.id)},"aria-label":J.closeLabel??`Close ${J.label} tab`,title:J.closeLabel??`Close ${J.label} tab`,children:t.jsx(C,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,X?t.jsx("span",{className:"animated-tabs__label truncate",children:J.label}):null]}):t.jsxs("span",{className:_("flex min-w-0 flex-nowrap items-center gap-1.5",!v&&"justify-center"),children:[be?t.jsxs("span",{className:_("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",q?"text-[var(--primary-base)]":"text-muted-foreground"),children:[t.jsx("span",{className:_("flex items-center justify-center transition-opacity",lt&&(S?"opacity-0":"group-hover:opacity-0")),children:J.icon}),lt?t.jsx("span",{role:"button",tabIndex:-1,className:_("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",S?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Fe=>{Fe.stopPropagation()},onClick:Fe=>{Fe.stopPropagation(),r?.(J.id)},"aria-label":J.closeLabel??`Close ${J.label} tab`,title:J.closeLabel??`Close ${J.label} tab`,children:t.jsx(C,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,t.jsx("span",{className:"truncate leading-[1.2]",children:J.label})]})}),je&&!lt?t.jsx("button",{type:"button",onPointerDown:Fe=>{Fe.stopPropagation()},onClick:Fe=>{Fe.stopPropagation(),r?.(J.id)},className:_("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",I?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",I?q?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":q?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":J.closeLabel??`Close ${J.label} tab`,title:J.closeLabel??`Close ${J.label} tab`,children:t.jsx(C,{name:"close",className:"h-3 w-3"})}):null]})},J.id)})]})]});return te?t.jsxs(sr,{sensors:ie,collisionDetection:nr,onDragEnd:ot,modifiers:[Qm],children:[t.jsx(fo,{items:b,strategy:Zu,children:ze}),t.jsx(Da,{dropAnimation:null})]}):ze},eg="\x1B",tg=new RegExp(`${eg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),sg=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,ng=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,rg=/Serving HTTP on .*? port (\d{2,5})/i,og=new Set([".",",",";",":","!","?"]),ig=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",i=s.slice(0,-1),a=(i.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(i.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=i;continue}if(og.has(n)){s=s.slice(0,-1);continue}break}return s},Hi=e=>{let s=ig(e);return s=s.replace("0.0.0.0","127.0.0.1"),s=s.replace("[::1]","127.0.0.1"),s=s.replace("[::]","127.0.0.1"),s},ag=e=>{if(!e)return null;const s=e.replace(tg,""),n=s.match(rg);if(n?.[1]){const i=Number.parseInt(n[1],10);if(Number.isFinite(i)&&i>0&&i<=65535)return`http://127.0.0.1:${i}/`}const r=s.split(`
49
- `);for(const i of r){if(!ng.test(i))continue;const a=Array.from(i.matchAll(sg));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Hi(c[1])).port}catch{return!1}});return Hi((l??a[0])[1])}return null},lg=async(e,s=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const i=new AbortController,a=window.setTimeout(()=>i.abort(),s);try{const l=await es("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:i.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},cg={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},dg=(e,s)=>{if(s&&e.startsWith("arrow-")){const n=s==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return cg[e]},dl=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},ug=(e,s)=>e&&(s==="ctrl"?dl(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Wi={cols:80,rows:24},Ox=({visible:e})=>{const{terminal:s,runtime:n}=Jn(),{currentTheme:r}=ha(),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}=Bd(),l=fe(L=>L.terminalFontSize),c=fe(L=>L.terminalShell),d=fe(L=>L.terminalLoginShells.includes(L.terminalShell)),{isMobile:u,isTablet:p,hasTouchOnlyPointer:h}=Ms(),x=u||p,m=(x||h)&&n.platform==="web",f=!0,g=fe(L=>L.showTerminalQuickKeysOnDesktop),S=x||g,j=Oe(L=>L.currentSessionId),B=Oe(L=>L.newSessionDraft),A=j!==null||B?.open===!0,b=_d()??null,v=Ee(L=>b?L.sessions.get(b):void 0),M=Ee(L=>L.hasHydrated),N=Ee(L=>L.ensureDirectory),k=Ee(L=>L.createTab),I=Ee(L=>L.setActiveTab),D=Ee(L=>L.closeTab),P=Ee(L=>L.setTabSessionId),G=Ee(L=>L.setTabLifecycle),ee=Ee(L=>L.setConnecting),Z=Ee(L=>L.appendToBuffer),te=Ee(L=>L.replaceBuffer),U=Ee(L=>L.setTabPreviewUrl),K=ia(L=>L.addDraft),T=fe(L=>L.openContextPreview),R=o.useMemo(()=>v?v.activeTabId??v.tabs[0]?.id??null:null,[v,f]),Q=o.useMemo(()=>{if(v)return R?v.tabs.find(L=>L.id===R)??v.tabs[0]:v.tabs[0]},[v,R]),ae=o.useMemo(()=>(v?.tabs??[]).map(L=>({icon:(()=>{const re=L.iconKey?dn[L.iconKey]??"terminal":"terminal";return t.jsx(C,{name:re,className:"h-4 w-4"})})(),id:L.id,label:L.label,title:L.label,closeLabel:"Close tab"})),[v?.tabs]),z=Q?.terminalSessionId??null,Re=Q?.lifecycle??"idle",Te=Ee(L=>b&&R?L.getBuffer(b,R).chunks:Kn.chunks),Ye=Q?.isConnecting??!1,_e=Q?.previewUrl??null,[Ve,Be]=o.useState(null),[ie,pe]=o.useState(!1),[We,Ce]=o.useState(!1),[ve,$e]=o.useState(null),[ot,ze]=o.useState(!1),J=o.useRef(null),q=o.useRef(null),ge=o.useRef(R),X=o.useRef(z),be=o.useRef(b),Ae=o.useRef(null),je=o.useRef(null),lt=o.useRef(new Set),jt=o.useRef(""),it=o.useRef(new Set),xe=o.useRef(0),Fe=o.useCallback(()=>{jt.current="",it.current.clear(),xe.current+=1},[]),Le=o.useCallback(()=>{m||typeof document<"u"&&!document.hasFocus()||Ae.current?.focus()},[m]),Ke=o.useCallback(()=>{m||Ae.current?.focus()},[m]),ht=fe(L=>L.activeMainTab)==="terminal",O=e??ht,[ke,ye]=o.useState(O);o.useEffect(()=>{O&&ye(!0)},[O]),o.useEffect(()=>{X.current=z},[z]),o.useEffect(()=>{!z||!s.updateAppearance||s.updateAppearance(z,i.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,z]),o.useEffect(()=>{ge.current=R,Fe()},[R,Fe]),o.useEffect(()=>{be.current=b},[b]),o.useEffect(()=>{!S&&ve!==null&&$e(null)},[S,ve,$e]),o.useEffect(()=>{!z&&ve!==null&&$e(null)},[z,ve,$e]);const w=o.useCallback(()=>{J.current?.(),J.current=null,q.current=null,Ce(!1)},[]);o.useEffect(()=>()=>{w(),X.current=null},[w]);const V=o.useCallback((L,re,me)=>{if(!me)return;const tt=`${jt.current}${me}`.replace(/\r\n|\r/g,`
50
- `),we=tt.split(`
51
- `),et=tt.endsWith(`
52
- `)?we.join(`
53
- `):we.slice(0,-1).join(`
54
- `);if(jt.current=tt.endsWith(`
55
- `)?"":(we[we.length-1]??"").slice(-1024),!et)return;const ut=ag(et);if(!ut||it.current.has(ut))return;const Ot=xe.current;it.current.add(ut),lg(ut).then(Ut=>{if(it.current.delete(ut),!Ut||xe.current!==Ot)return;const Rt=Ee.getState().getDirectoryState(L)?.tabs.find(Gt=>Gt.id===re);!Rt||Rt.previewUrlLocked||Rt.previewUrl===ut||U(L,re,ut,{locked:!1,autoOpened:!1})})},[U]),se=o.useCallback((L,re,me)=>{if(q.current===me)return;w(),q.current=me;const tt=s.connect(me,{onEvent:we=>{if(q.current===me)switch(we.type){case"snapshot":{ee(L,re,!1),Be(null),pe(!1),Ce(!1),Le(),te(L,re,we.data??"",we.sequence??0),V(L,re,we.data??""),we.status==="exited"&&G(L,re,"exited");break}case"reconnecting":{Be(null),pe(!1),Ce(!0);break}case"data":{we.data&&(Z(L,re,we.data,we.sequence,we.replayData),V(L,re,we.data));break}case"exit":{const et=typeof we.exitCode=="number"?we.exitCode:null,ut=typeof we.signal=="number"?we.signal:null,Ut=!!Ee.getState().getDirectoryState(L)?.tabs.find(Rt=>Rt.id===re)?.label?.startsWith("Action:");Z(L,re,`\\r\\n[Process exited${et!==null?` with code ${et}`:""}${ut!==null?` (signal ${ut})`:""}]\\r\\n`),G(L,re,"exited"),ee(L,re,!1),Be(Ut?null:"Terminal session ended"),pe(!1),Ce(!1),w();break}}},onError:(we,et)=>{if(q.current===me){if(!et){Be(null),pe(!1);return}if(Ce(!1),we.code==="SESSION_NOT_FOUND"&&!Ee.getState().getDirectoryState(L)?.tabs.find(Ot=>Ot.id===re)?.label?.startsWith("Action:")){Be(null),pe(!1),ee(L,re,!1),P(L,re,null),G(L,re,"idle"),w();return}Be(`Connection failed: ${we.message}`),pe(!0),ee(L,re,!1),G(L,re,"exited"),P(L,re,null),w()}}});J.current=()=>{tt.close(),q.current=null}},[Z,te,w,Le,V,ee,G,P,s]);o.useEffect(()=>{let L=!1;if(!M||!ke)return;if(!b){Be(A?"No working directory available for terminal.":"Select a session to open the terminal."),w();return}return(async()=>{const me=b;if(!be.current||be.current!==me)return;if(!Ee.getState().getDirectoryState(me)){N(me);return}const we=Ee.getState().getDirectoryState(me);if(!we||we.tabs.length===0)return;const et=we.activeTabId??we.tabs[0]?.id??null;if(!et)return;const ut=we.tabs.find(gt=>gt.id===et)??we.tabs[0],Ot=ut?.terminalSessionId??null,Ut=ut?.lifecycle??"idle",Rt=!!ut?.label?.startsWith("Action:"),Gt=Ee.getState().getBuffer(me,et),Ft=Gt.byteLength>0||Gt.chunks.length>0;if(!Ot){if(Ut==="exited"){ee(me,et,!1);return}if(Rt&&Ft){ee(me,et,!1);return}const gt=`${me}\0${et}`;if(lt.current.has(gt))return;const Bt=je.current??Wi;lt.current.add(gt),Be(null),pe(!1),Ce(!1),ee(me,et,!0);try{const H=await s.createSession({cwd:me,sessionId:et,cols:Bt.cols,rows:Bt.rows,shell:c,loginShell:d,...i.current}),ne=!L&&be.current===me&&ge.current===et;if(!Ee.getState().getDirectoryState(me)?.tabs.find(he=>he.id===et)){try{await s.close(H.sessionId)}catch{}return}if(P(me,et,H.sessionId),!ne)return;const ce=je.current;ce&&(ce.cols!==Bt.cols||ce.rows!==Bt.rows)&&s.resize({sessionId:H.sessionId,...ce}).catch(()=>{});return}catch(H){const ne=Ee.getState().getDirectoryState(me)?.tabs.find(oe=>oe.id===et);if(!ne||ne.terminalSessionId||(ee(me,et,!1),be.current!==me||ge.current!==et))return;Be(H instanceof Error?H.message:"Failed to start terminal session"),pe(!0),Ce(!1);return}finally{lt.current.delete(gt)}}!Ot||L||(X.current=Ot,se(me,et,Ot))})(),()=>{L=!0,X.current=null,w()}},[A,b,z,Re,R,ke,f,M,N,ee,G,P,se,w,s,d,c]),o.useEffect(()=>{if(!O||m)return;if(typeof window>"u"){Le();return}const L=window.requestAnimationFrame(()=>{Le()});return()=>{window.cancelAnimationFrame(L)}},[R,Le,O,m]);const de=o.useCallback(async()=>{if(!b||ot)return;const L=Ee.getState().getDirectoryState(b),re=R??L?.activeTabId??L?.tabs[0]?.id??null;if(!re)return;const me=L?.tabs.find(tt=>tt.id===re)?.terminalSessionId??null;if(!(!me||!s.restartSession)){ze(!0),Be(null),pe(!1),Ce(!1),w(),Fe();try{const tt=je.current??Wi,we=await s.restartSession(me,{cwd:b,shell:c,loginShell:d,...tt,...i.current});if(Ee.getState().getDirectoryState(b)?.tabs.find(ut=>ut.id===re)?.terminalSessionId!==me||(P(b,re,we.sessionId),G(b,re,"running"),be.current!==b||ge.current!==re))return;X.current=we.sessionId,se(b,re,we.sessionId)}catch(tt){if(Ee.getState().getDirectoryState(b)?.tabs.find(et=>et.id===re)?.terminalSessionId!==me||be.current!==b||ge.current!==re)return;Be(tt instanceof Error?tt.message:"Failed to restart terminal"),pe(!1),Ce(!1),X.current=me,se(b,re,me)}finally{ze(!1)}}},[R,w,b,f,ot,Fe,G,P,se,s,d,c]),Se=o.useCallback(async()=>{await de()},[de]),Pe=o.useCallback(()=>{if(!b)return;const L=k(b);I(b,L),Be(null),pe(!1),Ce(!1),w()},[k,w,b,I]),He=o.useCallback(()=>{const L=Ae.current?.getSelection(),re=j??(B?.open?"draft":null);!L||!re||!Q||!b||K({directory:b,sessionKey:re},{source:"terminal",fileLabel:Q.label,startLine:L.startLine,endLine:L.endLine,code:L.text,language:Q.terminalSessionId??Q.id,text:""})},[Q,K,j,b,B?.open]),mt=o.useCallback(L=>{b&&(I(b,L),Be(null),pe(!1),Ce(!1),w())},[w,b,I]),bt=o.useCallback(L=>{if(!b)return;L===R&&w(),Be(null),pe(!1),Ce(!1);const re=Ee.getState().getDirectoryState(b)?.tabs.find(me=>me.id===L)?.terminalSessionId;(async()=>{re&&await s.close(re),D(b,L)})().catch(me=>Be(me instanceof Error?me.message:"Terminal session ended"))},[R,D,w,b,s]),qe=o.useCallback(L=>{if(!L||We)return;let re=L,me=!1;ve&&L.length>0&&(re=ug(L,ve),me=!0);const tt=X.current;tt&&(s.sendInput(tt,re).catch(we=>{We||Be(we instanceof Error?we.message:"Failed to send input")}),me&&($e(null),Ke()))},[ve,Ke,We,$e,s]),dt=o.useCallback((L,re)=>{const me=je.current;if((!me||me.cols!==L||me.rows!==re)&&(je.current={cols:L,rows:re}),!O)return;const tt=X.current;tt&&s.resize({sessionId:tt,cols:L,rows:re}).catch(()=>{})},[O,s]),xt=o.useCallback(L=>{$e(re=>re===L?null:L),Ke()},[Ke,$e]),Me=o.useCallback(L=>{const re=dg(L,ve);re&&(qe(re),$e(null),Ke())},[ve,Ke,qe,$e]),Xe=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),yt=o.useCallback(L=>{if(L.repeat)return;const re=L.key;if(!re||re==="Control"||re==="Meta"||re==="Alt"||re==="Shift")return;const me=re.length===1?re.toLowerCase():re;if(me in Xe){L.preventDefault(),L.stopPropagation(),Me(Xe[me]);return}if(ve!=="ctrl")return;const tt=L.code??"",we=re.length===1&&/[a-zA-Z]/.test(re)?re.toUpperCase():tt.startsWith("Key")&&tt.length===4?tt.slice(3).toUpperCase():null;if(we&&we.length===1&&we>="A"&&we<="Z"){const et=dl(we);if(!et)return;L.preventDefault(),L.stopPropagation(),qe(et),$e(null),Ke()}},[ve,Ke,Me,qe,Xe,$e]);o.useEffect(()=>{if(!(!S||!ve||!z))return window.addEventListener("keydown",yt),()=>window.removeEventListener("keydown",yt)},[ve,yt,S,z]);const Nt=o.useMemo(()=>{const L=en[dr].stack;if(typeof window>"u")return(en[a]??en[dr]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(en[a]??en[dr]).stack??L},[a]),Pt=o.useMemo(()=>Bm(r),[r]),Et=`${b??"no-dir"}::${R??"no-tab"}`;if(o.useEffect(()=>{if(!O||m)return;const L=Ae.current;if(!L)return;const re=()=>{L.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{re(),Le()}),tt=[220,400].map(we=>window.setTimeout(re,we));return()=>{window.cancelAnimationFrame(me),tt.forEach(we=>window.clearTimeout(we))}}re()},[Le,O,m,Et,z]),o.useEffect(()=>{if(!O||!m)return;let L=null;const re=()=>{L!==null&&window.cancelAnimationFrame(L),L=window.requestAnimationFrame(()=>{L=null,Ae.current?.fit()})};return window.addEventListener("oc:keyboard-settled",re),()=>{window.removeEventListener("oc:keyboard-settled",re),L!==null&&window.cancelAnimationFrame(L)}},[O,Et,m]),!A)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(!b)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=!z||Ye||ot||We,At=ke,F=x?"lg":"xs",Ne=x?"w-10 p-0":"w-9 p-0",Ue=L=>{x&&L.preventDefault()},pt=t.jsxs(t.Fragment,{children:[t.jsx(Ze,{type:"button",size:F,variant:"outline",onPointerDown:Ue,onClick:()=>Me("esc"),disabled:It,children:"Esc"}),t.jsxs(Ze,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("tab"),disabled:It,children:[t.jsx(C,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Ze,{type:"button",size:F,variant:"chip","aria-pressed":ve==="ctrl",className:x?"px-3":"px-2",onPointerDown:Ue,onClick:()=>xt("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(Ze,{type:"button",size:F,variant:"chip","aria-pressed":ve==="alt",className:x?"px-3":"px-2",onPointerDown:Ue,onClick:()=>xt("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(Ze,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-up"),disabled:It,children:[t.jsx(C,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Ze,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-left"),disabled:It,children:[t.jsx(C,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Ze,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-down"),disabled:It,children:[t.jsx(C,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Ze,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-right"),disabled:It,children:[t.jsx(C,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Ze,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("enter"),disabled:It,children:[t.jsx(C,{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:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[v?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:_("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(Zm,{items:ae,activeId:R,onSelect:mt,onClose:bt,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Ze,{type:"button",size:"xs",variant:"ghost",className:_("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Pe,title:"New tab",children:t.jsx(C,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Ze,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{de()},disabled:ot,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(C,{name:"restart",className:"h-4 w-4"})}),t.jsx(Ze,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:He,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(C,{name:"attachment-2",className:"h-4 w-4"})}),_e?t.jsxs(Ze,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{b&&T(b,_e)},title:"Open preview pane",children:[t.jsx(C,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&S&&f&&v?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:pt}):null,!x&&S&&!v?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:pt}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Pt.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:At?t.jsx(cl,{ref:L=>{Ae.current=L},sessionKey:Et,chunks:Te,onInput:qe,onResize:dt,theme:Pt,fontFamily:Nt,fontSize:l,enableTouchScroll:m,autoFocus:O,isVisible:O},Et):null}),!We&&Ve&&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:Ve}),ie&&x&&t.jsx(Ze,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Se,disabled:ot,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&S?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:pt})}):null]})},fg=ps(()=>({statusById:new Map})),Bx=()=>{ya(),pa()},_x=e=>{Oe.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),fe.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ya(),Ee.getState().clearAll(),ws.getState().resetForRuntimeSwitch(),_t.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),$t.getState().resetForRuntimeSwitch(),zd.getState().resetForRuntimeSwitch(),fg.setState({statusById:new Map}),$d(),Ud(),ef.getState().reset(),yu.getState().resetForRuntimeSwitch(),oa.getState().resetForRuntimeSwitch(e.runtimeKey),fa.getState().resetForRuntimeSwitch(e.runtimeKey),xp.getState().resetForRuntimeSwitch(),Wt.getState().resetForRuntimeSwitch(e.runtimeKey),vu.getState().resetForRuntimeSwitch(e.runtimeKey),Oe.getState().restoreForRuntimeSwitch(e.runtimeKey),fe.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=fe.getState();Kr({sessionId:Oe.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),pa()},hg=48,pg=96,qt=(e,...s)=>{try{e?.(...s)}catch{}},kr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},zx=(e,s)=>{const n=o.useRef(s);n.current=s;const r=s.enabled;o.useEffect(()=>{const i=e.current;if(!i||r===!1)return;const a=i.style.touchAction;i.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?pg:hg;let d=!1,u=!1,p=!1,h=null,x=!1,m=0,f=0,g=0,S=0;const j=()=>{d=!1,u=!1,p=!1,h=null},B=()=>{const I=n.current,D=h,P=x;u&&D&&(qt(D==="left"?I.onLeftProgress:I.onRightProgress,P?1:0),qt(I.onDragEnd,D,P)),j()},A=()=>{B(),u||j()},b=I=>{const D=n.current;if(D.enabled===!1){u&&h?B():j();return}if(I.touches.length!==1){u&&h?B():j();return}const P=I.touches[0],G=i.getBoundingClientRect(),ee=i.clientWidth,Z=!!D.leftOpen,te=!!D.rightOpen,U=K=>Sm(K,i);if(Z||te){if(U(I.target)){j();return}if(Z&&te){const K=P.clientX<=G.left+c;P.clientX>=G.right-c?(h="right",x=!0):K?(h="left",x=!0):(h=Z?"left":"right",x=!0)}else Z?(h="left",x=!0):(h="right",x=!0);S=kr(h==="left"?D.leftWidth:D.rightWidth,ee),S<10&&(S=ee||window.innerWidth||320),S<10&&(S=320),d=!0}else{if(U(I.target)){j();return}h=null,x=!1,S=0,d=!0}m=P.clientX,f=P.clientY,g=Date.now(),u=!1,p=!1},v=I=>{if(!d)return;if(I.touches.length!==1){A();return}const D=I.touches[0],P=D.clientX-m,G=D.clientY-f;if(!p){if(Math.abs(P)<Li&&Math.abs(G)<Li)return;if(Math.abs(G)>Math.abs(P)*sn){j();return}if(!h){const te=n.current;h=P>0?"left":"right",S=kr(h==="left"?te.leftWidth:te.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(h==="left"){if(!x&&P<=0){j();return}if(x&&P>=0){j();return}}else{if(!x&&P>=0){j();return}if(x&&P<=0){j();return}}p=!0,u=!0,qt(n.current.onDragStart,h)}if(!u)return;I.cancelable&&I.preventDefault();const ee=n.current,Z=Oi(h,x,P,S);qt(h==="left"?ee.onLeftProgress:ee.onRightProgress,Z)},M=(I,D)=>{if(!d){j();return}const P=I-m,G=D-f;if(!h&&!x&&Math.abs(P)>=Un&&Math.abs(G)<=Math.abs(P)*sn){const T=n.current;h=P>0?"left":"right",S=kr(h==="left"?T.leftWidth:T.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(!h){j();return}const ee=Math.max(1,Date.now()-g),Z=n.current;if(!u){const T=Math.abs(P),R=Math.abs(G);T>=Un&&R<=T*sn?h==="left"&&!x&&P>0?(qt(Z.onLeftProgress,1),qt(Z.onLeftOpen)):h==="right"&&!x&&P<0?(qt(Z.onRightProgress,1),qt(Z.onRightOpen)):qt(h==="left"?Z.onLeftProgress:Z.onRightProgress,x?1:0):qt(h==="left"?Z.onLeftProgress:Z.onRightProgress,x?1:0);const Q=h;j(),qt(Z.onDragEnd,Q);return}const te=Oi(h,x,P,S),U=vm({side:h,isOpenAtStart:x,dx:P,dt:ee,progress:te}),K=h;qt(K==="left"?U?Z.onLeftOpen:Z.onLeftClose:U?Z.onRightOpen:Z.onRightClose),j(),qt(Z.onDragEnd,K,U)},N=I=>{const D=I.changedTouches[0];if(!D){j();return}const P=D.clientX-m,G=D.clientY-f;d&&(u||Math.abs(P)>=Un&&Math.abs(G)<=Math.abs(P)*sn)&&I.cancelable&&I.preventDefault(),M(D.clientX,D.clientY)},k=()=>{A()};return i.addEventListener("touchstart",b,{passive:!0}),i.addEventListener("touchmove",v,{passive:!1}),i.addEventListener("touchend",N,{passive:!1}),i.addEventListener("touchcancel",k,{passive:!0}),()=>{try{u&&h&&B()}catch{}i.style.touchAction=a,i.removeEventListener("touchstart",b),i.removeEventListener("touchmove",v),i.removeEventListener("touchend",N),i.removeEventListener("touchcancel",k)}},[e,r])};function $x({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(C,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Yi({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const mg=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,gg=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Xn(s,n)?null:e,Nr=()=>Ds.filter(e=>Br.has(e.id)).map(e=>({...va(e)})),xg=()=>{if(typeof window>"u")return _r;const e=window.localStorage.getItem("openInAppId");return e&&Or(e)?e:_r};let Ar=!1,zs=!1,bs=!1,ys=0,un=null;const Vi=()=>{un&&(clearTimeout(un),un=null)},Ns=ps()((e,s)=>({selectedAppId:xg(),availableApps:Nr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Ar||typeof window>"u")return;Ar=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Nr(),hasLoadedApps:u});return}const p=new Set(d.map(f=>f.name)),h=new Map(d.map(f=>[f.name,f.iconDataUrl??void 0])),m=Ds.filter(f=>p.has(f.appName)||Br.has(f.id)).map(f=>({...va(f),iconDataUrl:h.get(f.appName)}));e({availableApps:m,hasLoadedApps:!0})},r=async d=>{if(!vs()||!hn()||zs||s().hasLoadedApps&&!d)return;const p=Ds.map(h=>h.appName);Vi(),zs=!0,bs=!1,e({isScanning:!0});try{const{apps:h,success:x,hasCache:m,isCacheStale:f}=await si(p,d),g=x&&!m&&h.length===0&&ys<3;if(e({isCacheStale:m?f:!1}),n(h,x?!g:!1),x){if(g){const j=[800,1600,3200][ys]??3200;ys+=1,bs=!0,un=setTimeout(()=>{r()},j);return}ys=0,bs=!1;return}if(ys<3){const j=[1e3,3e3,7e3][ys]??7e3;ys+=1,bs=!0,un=setTimeout(()=>{r()},j)}}finally{zs=!1,bs||e({isScanning:!1})}};r();const i=d=>{const u=d.detail,p=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Or(u.openInAppId)?u.openInAppId:null;p&&(window.localStorage.setItem("openInAppId",p),e({selectedAppId:p}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(ys=3,bs=!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(Ar||s().initialize(),!vs()||!hn()||zs||s().hasLoadedApps&&!n)return;const i=Ds.map(a=>a.appName);Vi(),n&&e({hasLoadedApps:!1}),zs=!0,bs=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await si(i,n),d=new Set(a.map(x=>x.name)),u=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),h=Ds.filter(x=>d.has(x.appName)||Br.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:h.length>0?h:Nr(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{zs=!1,bs||e({isScanning:!1})}},selectApp:async n=>{Or(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await ro({openInAppId:n}))}})),bg="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",yg="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",Ir=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?bg:e.id==="terminal"?yg:void 0}),qi=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,i]=o.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>i(!0)}):t.jsx("span",{className:_("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},vg=({directory:e,className:s})=>{const n=Ns(f=>f.selectedAppId),r=Ns(f=>f.availableApps),i=Ns(f=>f.isCacheStale),a=Ns(f=>f.isScanning),l=Ns(f=>f.initialize),c=Ns(f=>f.loadInstalledApps),d=Ns(f=>f.selectApp);o.useEffect(()=>{l()},[l]);const u=vs()&&hn(),p=o.useMemo(()=>{const f=r.find(g=>g.id===n)??r.find(g=>g.id===_r)??r[0]??Ds[0];return Ir(f||Ds[0])},[r,n]);if(!u||!e||r.length===0)return null;const h=async f=>{await wu(e,f.id,f.appName)||await xa(e,f.appName)},x=async f=>{await d(f.id),await h(f)},m=async()=>{(await fn(e)).ok&&le.success("Path copied to clipboard")};return t.jsxs("div",{className:_("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{h(p)},className:_("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${p.label}`,children:t.jsx(qi,{label:p.label,iconDataUrl:p.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl})}),t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:_("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(C,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{m()},children:[t.jsx(C,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Ys,{}),r.map(f=>{const g=Ir(f);return t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{x(f)},children:[t.jsx(qi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:g.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:f.label}),p.id===f.id?t.jsx(C,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},f.id)}),i?t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(C,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},wg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Sg=["dev","start","preview","serve"];async function jg(e,s,n){if(!e)return null;const r=Ng(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=Ag(n);if(i){const a=await Ig(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 Cg(e)){const i=await kg(),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 Cg(e){const s=`${e}/index.html`,n=await Qn(s,e);return typeof n=="string"&&n.trim().length>0}async function kg(){try{const e=await es("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Ng(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(Sg.some(i=>n.includes(i)))return s}return null}function Ag(e){for(const{pattern:s}of wg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Ig(e){const s=await Qn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),i=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(i.startsWith("bun@"))return"bun";if(i.startsWith("pnpm@"))return"pnpm";if(i.startsWith("yarn@"))return"yarn";if(i.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,i]of n){const a=await Qn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function Qn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),i=await es(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=oo()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await es(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Dg(e){try{const s=await Qn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Pg=(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)}),Eg="\x1B",Tg=new RegExp(`${Eg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Rg=/https?:\/\/[^\s<>'"`]+/gi,Zt="__pichamber_auto_discover_preview__",Mg=15e3,Fg=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},Lg=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}},Og=e=>{const n=e.replace(Tg,"").match(Rg);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const i=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&i.push({raw:a,parsed:l})}catch{}if(i.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",p=c.pathname||"/",h=p.split("/").filter(Boolean).length,x=p==="/"||p==="",m=!!(c.search||c.hash);let f=0;return u&&(f+=50),x&&(f+=30),f-=Math.min(h*5,20),m&&(f-=10),f};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},Qi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=ha(),{terminal:l}=Jn(),{isMobile:c}=Ms(),d=o.useMemo(()=>vs(),[]),u=Hn(O=>O.instances),p=Hn(O=>O.load),h=fe(O=>O.terminalShell),x=fe(O=>O.terminalLoginShells.includes(O.terminalShell)),m=fe(O=>O.setSettingsPage),f=fe(O=>O.setSettingsDialogOpen),g=fe(O=>O.setSettingsProjectsSelectedId),S=fe(O=>O.openContextPreview),j=Ee(O=>O.ensureDirectory),B=Ee(O=>O.setTabLabel),A=Ee(O=>O.setTabIconKey),b=Ee(O=>O.setActiveTab),v=Ee(O=>O.setConnecting),M=Ee(O=>O.setTabSessionId),N=Ee(O=>O.setTabPreviewUrl),k=Ee(O=>O.projectActionRuns),I=Ee(O=>O.setProjectActionRun),D=Ee(O=>O.updateProjectActionRunStatus),P=Ee(O=>O.removeProjectActionRun),[G,ee]=o.useState([]),[Z,te]=o.useState(null),[U,K]=o.useState(!1),T=o.useRef({}),R=o.useRef({}),Q=o.useRef({}),ae=o.useRef({}),z=o.useRef(new Set),Re=o.useRef(0),Te=e?.id??null,Ye=e?.path??"",_e=o.useMemo(()=>Te?{id:Te,path:Ye}:null,[Te,Ye]);o.useEffect(()=>{d&&p().catch(()=>{})},[d,p]);const Ve=o.useCallback(async O=>{await Xi(O)},[]),Be=o.useCallback(async()=>{if(!_e)return;const O=Re.current+1;Re.current=O,K(!0);try{const ke=await Dr(_e);if(Re.current!==O)return;const ye=ke.actions;ee(ye),te(w=>w===Zt||w&&ye.some(V=>V.id===w)?w:null)}catch{if(Re.current!==O)return}finally{Re.current===O&&K(!1)}},[_e]),ie=o.useMemo(()=>_a(s||_e?.path||""),[s,_e?.path]),pe=o.useMemo(()=>Z?G.find(O=>O.id===Z)??null:null,[G,Z]),We=o.useMemo(()=>({id:Zt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Ce=!c,ve=o.useMemo(()=>Ce?[We,...G]:G,[G,We,Ce]);o.useEffect(()=>{Be()},[Be]),o.useEffect(()=>{if(typeof window>"u")return;const O=ke=>{const ye=ke.detail;Te&&(ye?.projectId&&ye.projectId!==Te||Be())};return window.addEventListener(Yr,O),()=>{window.removeEventListener(Yr,O)}},[Be,Te]),o.useEffect(()=>{Z&&(Z===Zt&&Ce||G.some(O=>O.id===Z)||te(null))},[G,Ce,Z]),o.useEffect(()=>{const O=()=>{const ke=Ee.getState(),ye=ke.sessions,w=ke.projectActionRuns;for(const[V,se]of Object.entries(w)){const Se=ye.get(se.directory)?.tabs.find(Xe=>Xe.id===se.tabId);if(!Se||Se.terminalSessionId!==se.sessionId){P(V);continue}const Pe=R.current[V]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};R.current[V]=Pe;const He=ve.find(Xe=>Xe.id===se.actionId),mt=ke.getBuffer(se.directory,se.tabId).chunks;if(!He||mt.length===0)continue;const bt=mt.filter(Xe=>Pe.lastSeenChunkId===null||Xe.id>Pe.lastSeenChunkId);if(bt.length===0)continue;const qe=bt.map(Xe=>Xe.data).join(""),dt=`${Pe.tail}${qe}`,xt=!Pe.openedUrl&&He.autoOpenUrl===!0?Og(dt):null,Me=bt[bt.length-1]?.id??Pe.lastSeenChunkId;if(Pe.lastSeenChunkId=Me,Pe.tail=dt.slice(-512),xt)if(Pe.openedUrl=!0,Pe.openInPreview){const Xe=w[V];Xe&&(N(Xe.directory,Xe.tabId,xt,{locked:!1,autoOpened:!1}),Xe.status==="waiting-for-preview"&&D(V,"running"),window.clearTimeout(ae.current[V]),delete ae.current[V],S(Xe.directory,xt))}else Ve(xt),le.success("Opened URL from action output");R.current[V]=Pe}for(const V of Object.keys(R.current))w[V]||(delete R.current[V],window.clearTimeout(ae.current[V]),delete ae.current[V])};return O(),Ee.subscribe((ke,ye)=>{(ke.sessions!==ye.sessions||ke.buffers!==ye.buffers)&&O()})},[ve,S,Ve,k,P,N,D]);const $e=o.useCallback(async(O,ke={})=>{if(!ie)throw new Error("No active directory");const ye=us(ie,O.id);j(ie);const w=Ee.getState(),V=w.getDirectoryState(ie);let se=T.current[ye]||null;const de=se?!!V?.tabs.some(He=>He.id===se):!1;(!se||!de)&&(se=w.createTab(ie),T.current[ye]=se),B(ie,se,`Action: ${O.name}`),A(ie,se,O.icon||"play"),b(ie,se),ke.revealTerminal!==!1&&fe.getState().openContextPanelTab(ie,{mode:"terminal"});const Pe=Ee.getState().getDirectoryState(ie)?.tabs.find(He=>He.id===se);return{key:ye,tabId:se,sessionId:Pe?.terminalSessionId??null}},[j,ie,b,A,B]),ot=o.useCallback(async O=>{if(!i&&c)return;if(!ie){le.error("No active directory for action");return}const ke=us(ie,O.id),ye=k[ke];if(!(ye&&ye.status==="running")&&!z.current.has(ke)){z.current.add(ke);try{const w=O.id===Zt?await(async()=>{const[Me,Xe]=await Promise.all([Dr({id:_e?.id??"",path:ie}),Dg(ie)]),yt=await jg(ie,Me.actions,Xe);if(!yt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Zt,name:"Auto-discover",command:yt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:yt.previewUrlHint||""}})():O,V=w.autoOpenUrl===!0&&(w.openUrl||"").trim().length>0,se=!V&&O.id!==Zt,{key:de,tabId:Se,sessionId:Pe}=await $e(w,{revealTerminal:se});let He=Pe;if(!He){v(ie,Se,!0);try{He=(await l.createSession({cwd:ie,sessionId:Se,shell:h,loginShell:x,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,M(ie,Se,He)}finally{v(ie,Se,!1)}}if(!He)throw new Error("Failed to create terminal session");Q.current[de]?.(),v(ie,Se,!0);const mt=l.connect(He,{onEvent:Me=>{Me.type==="snapshot"&&(Ee.getState().replaceBuffer(ie,Se,Me.data??"",Me.sequence??0),Ee.getState().setConnecting(ie,Se,!1)),Me.type==="data"&&typeof Me.data=="string"&&Me.data.length>0&&Ee.getState().appendToBuffer(ie,Se,Me.data,Me.sequence,Me.replayData),Me.type==="exit"&&(Ee.getState().setTabLifecycle(ie,Se,"exited"),Ee.getState().setConnecting(ie,Se,!1),Ee.getState().removeProjectActionRun(de),delete R.current[de],Q.current[de]?.(),delete Q.current[de],window.clearTimeout(ae.current[de]),delete ae.current[de])},onError:(Me,Xe)=>{Ee.getState().setConnecting(ie,Se,!1),Xe&&(Ee.getState().setTabLifecycle(ie,Se,"exited"),Ee.getState().setTabSessionId(ie,Se,null),Ee.getState().removeProjectActionRun(de))}});Q.current[de]=mt.close;const bt=w.autoOpenUrl===!0&&d&&(w.desktopOpenSshForward||"").trim().length>0,qe=w.autoOpenUrl?Lg(w.openUrl):null,dt=w.autoOpenUrl&&d?Of(w.desktopOpenSshForward,u):null;I({key:de,directory:ie,actionId:w.id,tabId:Se,sessionId:He,status:w.id===Zt&&!qe?"waiting-for-preview":"running"}),window.clearTimeout(ae.current[de]),delete ae.current[de],w.id===Zt&&!qe&&(ae.current[de]=window.setTimeout(()=>{const Me=Ee.getState(),Xe=Me.projectActionRuns[de];Me.updateProjectActionRunStatus(de,"running"),Xe&&(Me.setActiveTab(Xe.directory,Xe.tabId),fe.getState().openContextPanelTab(Xe.directory,{mode:"terminal"})),delete ae.current[de]},Mg)),R.current[de]={lastSeenChunkId:null,openedUrl:!!dt||!!qe||V,tail:"",openInPreview:w.id===Zt};const xt=Fg(w.command.trim().replace(/\r\n|\r/g,`
56
- `));await l.sendInput(He,`${xt}\r`),dt?(N(ie,Se,null,{locked:!0}),Ve(dt),le.success("Opened forwarded URL")):qe?(N(ie,Se,qe,{locked:!0,autoOpened:!0}),S(ie,qe),le.success("Opened action URL")):V?(N(ie,Se,null,{locked:!0}),le.error("Invalid custom URL format")):bt?(N(ie,Se,null,{locked:!0}),le.error("Selected desktop SSH forward is unavailable")):N(ie,Se,null,{locked:!1,autoOpened:!1})}catch(w){P(ke),delete R.current[ke],Q.current[ke]?.(),delete Q.current[ke],window.clearTimeout(ae.current[ke]),delete ae.current[ke],le.error(w instanceof Error?w.message:"Failed to run action")}finally{z.current.delete(ke)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,$e,i,c,d,ie,x,h,Ve,S,k,P,v,I,N,M,_e?.id,l]),ze=o.useCallback(async O=>{const ke=us(ie,O.id),ye=k[ke];if(!ye)return;D(ke,"stopping");const w=Pg(l,ye.sessionId,1e3);try{await l.sendInput(ye.sessionId,"")}catch{}const V=await w;if(Ee.getState().getDirectoryState(ye.directory)?.tabs.find(Se=>Se.id===ye.tabId)?.terminalSessionId===ye.sessionId&&!V){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:ye.sessionId})}catch{}else try{await l.close(ye.sessionId)}catch{}M(ye.directory,ye.tabId,null)}P(ke),delete R.current[ke],Q.current[ke]?.(),delete Q.current[ke],window.clearTimeout(ae.current[ke]),delete ae.current[ke]},[ie,k,P,M,l,D]),J=o.useCallback(()=>{const O=pe??ve[0];if(!O)return;const ke=us(ie,O.id),ye=k[ke];if(ye?.status!=="stopping"){if(ye){ze(O);return}ot(O)}},[ve,ie,ot,k,pe,ze]),q=o.useCallback((O,ke=!1)=>{if(te(O.id),!ke){ot(O);return}const ye=us(ie,O.id),w=k[ye];if(w?.status!=="stopping"){if(w){ze(O);return}ot(O)}},[ie,ot,k,ze]),ge=o.useCallback(()=>{_e?.id&&(g(_e.id),m("projects"),f(!0))},[f,m,g,_e?.id]),X=pe??ve[0]??null,be=X?k[us(ie,X.id)]:null,Ae=Ee(O=>be?O.sessions.get(be.directory)?.tabs.find(ke=>ke.id===be.tabId)?.previewUrl??null:null);if(!i&&c||!_e||!ie)return null;const je=pe??ve[0]??null;if(!je)return null;const lt=je.icon||"play",jt=je.id===Zt?"scan-2":dn[lt]||"play",it=us(ie,je.id),xe=k[it],Fe=xe?.status==="stopping",Le=xe?.status==="waiting-for-preview",Ke=!!(xe&&Ae),kt=()=>{!xe||!Ae||S(xe.directory,Ae)},ht=je.id===Zt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:U||Fe,className:_("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:J,"aria-label":xe?`Stop ${je.name}`:`Run ${je.name}`,children:Fe||Le?t.jsx(C,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):xe?t.jsx(C,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(C,{name:jt,className:"h-5 w-5"})})}),ht?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),Ke?t.jsxs(st,{children:[t.jsx(nt,{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:kt,children:t.jsx(C,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(C,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Ct,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(C,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ys,{}),ve.map(O=>{const ke=O.icon||"play",ye=O.id===Zt?"scan-2":dn[ke]||"play",w=us(ie,O.id),V=k[w],se=!!V,de=V?.status==="stopping";return t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{q(O,!0)},children:[t.jsx(C,{name:ye,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),de||V?.status==="waiting-for-preview"?t.jsx(C,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(C,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]}):t.jsxs("div",{className:_("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:J,disabled:U||Fe,className:_("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":xe?`Stop ${je.name}`:`Run ${je.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:Fe||Le?t.jsx(C,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):xe?t.jsx(C,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(C,{name:jt,className:"h-4 w-4"})})})}),ht?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),Ke?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:kt,className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(C,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(C,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(Ct,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(C,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ys,{}),ve.map(O=>{const ke=O.icon||"play",ye=O.id===Zt?"scan-2":dn[ke]||"play",w=us(ie,O.id),V=k[w],se=!!V,de=V?.status==="stopping";return t.jsxs(Ct,{className:"flex items-center gap-2",onClick:()=>{q(O,!0)},children:[t.jsx(C,{name:ye,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),de||V?.status==="waiting-for-preview"?t.jsx(C,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(C,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]})},Bg=o.lazy(()=>Ps(()=>import("./SessionSwitcherDropdown-CJWqyz1O.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}))),rr="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",_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",zg=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(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:_(a??rr,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(C,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:n})})]}):null}),$g=o.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:i,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:_(rr,"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(C,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Xt,{align:"end",className:"w-64",children:[t.jsx(Jd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ys,{}),r.map(d=>{const u=d.user,p=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(Ct,{className:"gap-2",disabled:l,onSelect:()=>{p||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(C,{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:h})]}):null]}),p?t.jsx(C,{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(C,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Ug=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:p,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(Qt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(rr,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(C,{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(rt,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Xt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[i?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:p?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(Qd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Gg=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],i=n[1].slice(0,3),a=`${r} ${i}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},tn=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ux=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{is("ui.header.render");const l=fe(E=>E.setSessionSwitcherOpen),c=fe(E=>E.toggleSidebar),d=fe(E=>E.isSidebarOpen),u=fe(E=>E.activeMainTab),p=fe(E=>E.setActiveMainTab),h=fe(E=>E.shortcutOverrides);fe(E=>E.timeFormatPreference),Jn();const x=Oe(E=>!!E.newSessionDraft?.open),m=Oe(E=>E.currentSessionId),f=da(m??""),g=Gd(m),S=o.useMemo(()=>{if(!g)return null;const E=g;return{title:g.title??null,directory:E.directory??null,created:g.time?.created??null,slug:E.slug??null,shareUrl:g.share?.url??null,parentId:g.parentID??null}},[g]),j=$t(Gr(E=>{if(!E.activeProjectId)return null;const ue=E.projects.find(Ie=>Ie.id===E.activeProjectId);return ue?{id:ue.id,path:ue.path,label:ue.label}:null})),B=ws(E=>E.homeDirectory),A=o.useMemo(()=>{if(!j)return null;const E=j.label?.trim();if(E)return E;const ue=j.path.split(/[\\/]/).filter(Boolean);return ue[ue.length-1]??null},[j]),{isMobile:b}=Ms(),{enabled:v}=to(),M=!!(v&&a&&i!==void 0),N=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"}],[]),[k,I]=o.useState(!1),D=null,P=o.useRef(null),[G,ee]=o.useState(()=>typeof window>"u"?!1:vs()),Z=o.useMemo(()=>ba(),[]),te=Kd(),[U,K]=o.useState(!1),T=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:R,side:Q}=ma(),ae=o.useMemo(()=>{if(typeof window>"u")return null;const E=window.__PICHAMBER_MACOS_MAJOR__;if(typeof E=="number"&&Number.isFinite(E)&&E>0)return E;if(typeof navigator>"u")return null;const ue=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ue)return null;const Ie=Number.parseInt(ue[1],10),$=Number.parseInt(ue[2],10);return Number.isNaN(Ie)?null:Ie===10?$:Ie},[]);Je.useEffect(()=>{typeof window>"u"||ee(vs())},[]);const z=fe(E=>E.isSessionSwitcherOpen),Re=null,Te=null,Ye=[],[_e,Ve]=o.useState(!1),[Be,ie]=o.useState(!1),[pe,We]=o.useState("Local"),[Ce,ve]=o.useState(!0),[$e,ot]=o.useState(!1),[ze,J]=o.useState(null),[q,ge]=o.useState(!1),[X,be]=o.useState(null),Ae=o.useMemo(()=>Gg(pe),[pe]),je=o.useCallback(async()=>{if(!(typeof window>"u"||!G))try{if(hn()){We("Local"),ve(!0);return}ve(!1);const E=await Su(),ue=Hd(),Ie=Wd([Yd(ue),...E.hosts]);if(Ie.id===Vd){We("Local"),ve(!0);return}We(ju(Ie.label.trim()||"Instance"))}catch{We("Local"),ve(!0)}},[G]);Je.useEffect(()=>(je(),Cu(()=>{je()})),[je]);const lt=o.useCallback(async()=>{if(Ce){J(null),be(null);return}ge(!0),be(null);try{const E=new URLSearchParams({appType:"web",instanceMode:"remote"}),ue=await es(`/api/pi/update-check?${E.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ue.ok)throw new Error(`Server responded with ${ue.status}`);const Ie=await ue.json();J({available:Ie.available??!1,version:Ie.version,currentVersion:Ie.currentVersion??"unknown",body:Ie.body,nextSuggestedCheckInSec:typeof Ie.nextSuggestedCheckInSec=="number"?Ie.nextSuggestedCheckInSec:void 0,packageManager:Ie.packageManager,updateCommand:Ie.updateCommand})}catch(E){J(null),be(E instanceof Error?E.message:"Failed to check remote instance updates")}finally{ge(!1)}},[Ce]);o.useEffect(()=>{J(null),be(null),ot(!1)},[Ce,pe]),o.useEffect(()=>{if(!G||Ce)return;const E=3e3,ue=3600*1e3;let Ie=!1,$=null;const Ge=at=>{$=window.setTimeout(()=>{if(Ie||typeof document<"u"&&document.visibilityState!=="visible"){Ge(ue);return}lt().finally(()=>{Ie||Ge(ue)})},at)};return Ge(E),()=>{Ie=!0,$!==null&&window.clearTimeout($)}},[lt,Ce,pe,G]);const jt=o.useCallback(()=>{if(ze?.available){ot(!0);return}lt()},[lt,ze?.available]),it=m?S??null:null,xe=o.useRef(null),[Fe,Le]=o.useState(0);o.useEffect(()=>{if(!m){xe.current&&(xe.current=null,Le($=>$+1));return}if(it){xe.current={sessionId:m,session:it,expiresAt:Date.now()+2e3};return}const E=xe.current;if(!E||E.sessionId!==m)return;const ue=E.expiresAt-Date.now();if(ue<=0){xe.current=null,Le($=>$+1);return}const Ie=window.setTimeout(()=>{xe.current?.sessionId===m&&(xe.current=null),Le($=>$+1)},ue);return()=>{window.clearTimeout(Ie)}},[m,it]);const Ke=(()=>{if(it)return it;if(!m)return null;const E=xe.current;return E&&E.sessionId===m&&E.expiresAt>Date.now()?E.session:null})(),kt=o.useMemo(()=>{const E=typeof Ke?.directory=="string"?Ke.directory:"";return tn(E||"")},[Ke?.directory]),ht=Oe(E=>E.newSessionDraft?.open?tn(E.newSessionDraft.directoryOverride??""):""),O=o.useMemo(()=>mg({sessionDirectory:kt,draftDirectory:ht,isNewSessionDraftOpen:x}),[ht,x,kt]),ye=ca(O||null),w=o.useMemo(()=>gg({activeProjectLabel:A,openDirectory:O,homeDirectory:B}),[A,B,O]),V=!!(w||ye),se=o.useMemo(()=>{if(!m)return w??"PiChamber";const E=Ke?.title?.trim();return E&&E.length>0?E:"Untitled Session"},[Ke?.title,m,w]),de=ua(),Se=no(),Pe=Oe(E=>E.updateSessionTitle),He=Oe(E=>E.archiveSessions),mt=Oe(E=>E.deleteSessions),[bt,qe]=o.useState(!1),[dt,xt]=o.useState(!1),Me=o.useRef(!1),[Xe,yt]=o.useState(""),[Nt,Pt]=o.useState(null),Et=o.useRef(null);o.useEffect(()=>{Me.current=!1,xt(!1),qe(!1),yt(""),Pt(null)},[m]);const It=o.useCallback(()=>{m&&(yt(Ke?.title?.trim()||se),qe(!0))},[Ke?.title,m,se]),At=o.useCallback(async()=>{if(!m)return;const E=Xe.trim();E&&E!==Ke?.title?.trim()&&await Pe(m,E),qe(!1)},[Ke?.title,m,Xe,Pe]);o.useEffect(()=>{if(!bt)return;const E=ue=>{const Ie=ue.target;(!Ie||!Et.current?.contains(Ie))&&At()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[bt,At]);const F=o.useCallback(()=>{m&&fn(m).then(E=>{le[E.ok?"success":"error"](E.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[m]),Ne=o.useCallback(async()=>{if(!m||!O){le.error("Nothing to export");return}try{await Se.syncSession(m)}catch{le.error("Failed to load the complete session history");return}const E=Rr(de.getState()).list;if(E.length===0){le.error("Nothing to export");return}const ue=rl(E,Ke?.title??null),Ie=al(Ke?.title??null);await il(ue,Ie)||ol(ue,Ie),le.success("Session exported")},[Ke?.title,m,de,O,Se]);f?.type==="busy"||f?.type;const Ue=o.useCallback(async()=>{if(!m||!Nt)return;const E=qd(),ue=[m];for(let at=0;at<ue.length;at+=1){const wt=ue[at];for(const St of E)St.parentID===wt&&!ue.includes(St.id)&&ue.push(St.id)}const Ie=Nt;if(Pt(null),(Ie==="archive"?await He(ue):await mt(ue)).failedIds.length>0){le.error(Ie==="archive"?"Failed to archive session":"Failed to delete session");return}le.success(Ie==="archive"?"Session archived":"Session deleted")},[He,m,mt,Nt]),pt=fe(E=>E.isArchivePageOpen),L=o.useMemo(()=>pt?{title:"Archive",subtitle:null}:null,[pt]),re=o.useMemo(()=>tn(O||j?.path||""),[j?.path,O]),me=o.useMemo(()=>j?{id:j.id,path:j.path}:null,[j]),tt=o.useRef(null);o.useEffect(()=>{!me||!re||(tt.current={projectRef:me,directory:re})},[re,me]);const we=o.useMemo(()=>me&&re?{projectRef:me,directory:re}:tt.current,[re,me]),et=o.useCallback(async E=>{},[]),ut=o.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const ue=E.tagName;(ue==="INPUT"||ue==="TEXTAREA"||ue==="SELECT"||E.isContentEditable)&&E.blur()},[]),Ot=o.useCallback(()=>{if(b){ut(),l(!z);return}c()},[ut,b,z,l,c]),Ut=o.useCallback(()=>{an("desktop_open_draft_mini_chat_window",{directory:tn(O||j?.path||""),projectId:j?.id??null,apiBaseUrl:Lr(),clientToken:Fr()}).catch(E=>{console.warn("[header] failed to open draft mini chat window",E)})},[j?.id,j?.path,O]),Rt=o.useCallback(()=>{if(x){Ut();return}m&&an("desktop_open_session_mini_chat_window",{sessionId:m,directory:tn(O||j?.path||""),apiBaseUrl:Lr(),clientToken:Fr()}).catch(E=>{console.warn("[header] failed to open session mini chat window",E)})},[j?.path,m,Ut,x,O]),Gt=rr,Ft=_g,gt=o.useMemo(()=>n?"sessions":M?r&&i?i:null:r?"git":u,[u,M,n,r,i]),Bt=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&z&&l(!1)},[z,n,e,s,r,l]),H=o.useCallback(()=>{e?.()},[e]),ne=o.useCallback(()=>{s?.()},[s]),oe=o.useMemo(()=>G&&T&&!U?"5.5rem":te?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!G||R?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[G,U,T,te,R]);Je.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",oe)},[oe]);const ce=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",he=d?"0px":G&&R?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":v?"2.75rem":"2.5rem";Je.useEffect(()=>{if(!G||!T){K(!1);return}let E=!1;const ue=async()=>{try{const $=await an("desktop_is_window_fullscreen");E||K($===!0)}catch{E||K(!1)}},Ie=()=>{ue()};return ue(),window.addEventListener("pichamber:window-resized",Ie),()=>{E=!0,window.removeEventListener("pichamber:window-resized",Ie)}},[G,T]);const ft=o.useMemo(()=>!G||!T||ae===null?"":ae>=26?"h-12":ae<=15?"h-14":"",[G,T,ae]),Mt=o.useMemo(()=>{if(!(G&&!R))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[G,R]),vt=o.useCallback(()=>{if(typeof document>"u")return;const E=P.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Je.useEffect(()=>{if(typeof window>"u")return;vt();const E=P.current;if(!E||typeof ResizeObserver>"u")return()=>{};let ue=0;const Ie=()=>{ue||(ue=requestAnimationFrame(()=>{ue=0,vt()}))},$=new ResizeObserver(Ie);return $.observe(E),window.addEventListener("resize",Ie),window.addEventListener("orientationchange",Ie),()=>{ue&&cancelAnimationFrame(ue),$.disconnect(),window.removeEventListener("resize",Ie),window.removeEventListener("orientationchange",Ie)}},[vt]),Je.useEffect(()=>{vt()},[vt,b,ft]);const Kt=o.useCallback(async E=>{const ue=E.target;ue.closest(".app-region-no-drag")||ue.closest("button, a, input, select, textarea")||E.button===0&&G&&await ku()},[G]),Ht=o.useMemo(()=>b?[{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"}]:[],[b]),Tt=o.useCallback(E=>lo(on(E,h)),[h]);Je.useEffect(()=>{!b&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&p("chat")},[u,b,p]);const ns=o.useMemo(()=>{const E=[];return G&&E.push({value:"instance",label:"Instance",icon:t.jsx(C,{name:"server",className:"h-3.5 w-3.5"})}),E},[G]);Je.useEffect(()=>{const E=ue=>{if(Nu(ue)&&!ue.shiftKey&&!ue.altKey){const Ie=parseInt(ue.key,10);Ie>=1&&Ie<=Ht.length&&(ue.preventDefault(),b&&(ut(),Bt()),p(Ht[Ie-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[ut,Bt,b,p,Ht]),Je.useEffect(()=>{const E=ue=>{const Ie=on("toggle_services_menu",h);if(ni(ue,Ie)){ue.preventDefault(),Be?ie(!1):(ie(!0),je());return}const $=on("cycle_services_tab",h);if(ni(ue,$)){if(ue.preventDefault(),ns.length===0)return;ie(!0),je();return}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[h,Be,ns,je]);const cs=E=>{const ue=u===E.id,Ie=E.icon==="diff",$=Ie?null:E.icon,Ge=E.id==="chat",at=St=>Ie?t.jsx(Yi,{size:St}):$?t.jsx(C,{name:$,className:`h-${St/4} w-${St/4}`}):null,wt=t.jsxs("button",{type:"button",onClick:()=>p(E.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ue?"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",Ge&&!b&&"min-w-[100px] justify-center"),"aria-label":E.label,"aria-selected":ue,role:"tab",children:[b?at(20):t.jsxs(t.Fragment,{children:[at(16),t.jsx("span",{className:"header-tab-label",children:E.label})]}),E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:E.badge})]});return t.jsx(o.Fragment,{children:wt},E.id)},ms=t.jsxs(t.Fragment,{children:[t.jsx(vg,{directory:re,className:"mr-1"}),G?t.jsx(Ug,{isDesktopApp:G,currentInstanceLabel:pe,compactCurrentInstanceLabel:Ae,currentInstanceIsLocal:Ce,isDesktopServicesOpen:Be,setIsDesktopServicesOpen:ie,refreshCurrentInstanceLabel:je,shortcutLabel:Tt,remoteUpdateInfo:ze,remoteUpdateChecking:q,remoteUpdateError:X,onOpenRemoteUpdate:jt}):null,t.jsx($g,{isMobile:b,githubAuthStatus:D,githubAccounts:Ye,githubAvatarUrl:Re,githubLogin:Te,isSwitchingGitHubAccount:_e,handleGitHubAccountSwitch:et})]}),qs=Z&&(x||!!m),Qs=()=>t.jsxs("div",{onMouseDown:Kt,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",ft),style:Mt,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:ce}}),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:he}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[L?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:L.title}),L.subtitle?t.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:L.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:Gt,"aria-label":"Open session switcher",children:t.jsx(C,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Bg,{align:"start",children:t.jsx("button",{type:"button",className:Gt,"aria-label":"Open session switcher",children:t.jsx(C,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[bt?t.jsxs("form",{ref:Et,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:E=>{E.preventDefault(),At()},children:[t.jsx("input",{value:Xe,onChange:E=>yt(E.target.value),autoFocus:!0,onKeyDown:E=>{E.stopPropagation(),E.key==="Escape"&&qe(!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(C,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>qe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(C,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:x?"New session":se}),V?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:[w?t.jsx("span",{className:"truncate",children:w}):null,ye?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(C,{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:_("flex h-[18px] shrink-0 items-center justify-center",V?"self-start":"self-center"),children:m&&!x&&!bt?t.jsxs(Qt,{open:dt,onOpenChange:xt,onOpenChangeComplete:E=>{!E&&Me.current&&(Me.current=!1,It())},children:[t.jsx(Jt,{asChild:!0,children:t.jsx(Ze,{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(C,{name:"more",className:"size-4"})})}),t.jsxs(Xt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(Ct,{onClick:()=>{Me.current=!0},children:[t.jsx(C,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(Ct,{onClick:F,children:[t.jsx(C,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Ys,{}),t.jsxs(Ct,{onClick:()=>{Ne()},children:[t.jsx(C,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ys,{}),t.jsxs(Ct,{onClick:()=>Pt("archive"),children:[t.jsx(C,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(Ct,{className:"text-destructive focus:text-destructive",onClick:()=>Pt("delete"),children:[t.jsx(C,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Ht.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ht.map(E=>cs(E))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[we?t.jsx(Qi,{projectRef:we.projectRef,directory:we.directory,className:"mr-1"}):null,t.jsx(zg,{visible:qs,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Rt,className:_(Gt,"mr-1"),Icon:"picture-in-picture-2"}),ms,t.jsx(ga,{visible:R&&Q==="right",position:"right"})]})]})]}),gs=()=>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:ce}}),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:he}})]}),!v&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:H,className:_(Ft,gt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(C,{name:"layout-left",className:"h-5 w-5"})}):z?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(C,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Ot,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(C,{name:"play-list-add",className:"h-5 w-5"})}),!e&&z&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!z||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!M&&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:Ht.map(E=>{const ue=u===E.id,Ie=E.icon==="diff",$=Ie?null:E.icon;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{b&&(ut(),Bt()),p(E.id)},"aria-label":E.label,"aria-selected":ue,role:"tab",className:_(Ft,"relative rounded-lg",gt===E.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[Ie?t.jsx(Yi,{className:"h-5 w-5"}):$?t.jsx(C,{name:$,className:"h-5 w-5"}):null,E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:E.badge}),E.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(rt,{children:t.jsx("p",{children:E.label})})]},E.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[M&&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:N.map(E=>{const ue=r&&i===E.id;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{b&&(ut(),Bt()),I(!1),a?.(E.id)},"aria-label":E.label,"aria-selected":ue,role:"tab",className:_(Ft,"relative rounded-lg",ue&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(C,{name:E.icon,className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:E.label})})]},E.id)})}),t.jsx(Dh,{open:k,onOpenChange:I,currentSessionId:m,effectiveDirectory:O||null,isNewSessionDraftOpen:x})]}),we&&t.jsx(Qi,{projectRef:we.projectRef,directory:we.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!M?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ne,className:_(Ft,"relative",gt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(C,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),js=_("header-safe-area relative z-10 bg-background",b&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:js,style:{"--padding-scale":"1"},children:b?gs():Qs()}),t.jsx(as,{open:Nt!==null,onOpenChange:E=>{E||Pt(null)},children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:Nt==="delete"?"Delete session?":"Archive session?"}),t.jsx(Fs,{children:Nt==="delete"?`\\"${se}\\" will be permanently deleted.`:`\\"${se}\\" will be archived.`})]}),t.jsxs(Ls,{children:[t.jsx(Ze,{variant:"outline",size:"sm",onClick:()=>Pt(null),children:"Cancel"}),t.jsx(Ze,{variant:"destructive",size:"sm",onClick:()=>{Ue()},children:Nt==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Fa,{open:$e,onOpenChange:ot,info:ze,downloading:!1,downloaded:!1,progress:null,error:X,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Ji="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",Kg="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",Gx=()=>{const e=fe(g=>g.isSidebarOpen),s=fe(g=>g.toggleSidebar),n=fe(g=>g.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=lo(on("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=ma(),{enabled:d}=to(),u=!e,p=l&&c==="left",h=l,x=u||p||h,m=p||h,f=o.useCallback(()=>{an("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const g=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},S=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!m)return;const j=i.current,B=r.current;if(!j||!B){g(0),S(0);return}const A=()=>{const v=Math.max(j.getBoundingClientRect().width,j.scrollWidth);g(v),S(B.getBoundingClientRect().width)};if(A(),typeof ResizeObserver>"u")return;const b=new ResizeObserver(A);return b.observe(j),b.observe(B),()=>{b.disconnect()}},[m]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 top-0 z-40 flex select-none items-center pr-2",style:{height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:i,className:"flex items-center gap-2",children:[p?t.jsx(ga,{visible:!0,position:"left"}):null,h?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:f,"aria-label":"Open PiChamber menu",className:_(Ji,"shrink-0"),children:t.jsx(C,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:_(d?Kg:Ji,"shrink-0"),children:t.jsx(C,{name:"layout-left",className:d?"h-5 w-5":"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Fn=200,Ln="cubic-bezier(0.22, 1, 0.36, 1)",Kx=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 ${Fn}ms ${Ln}, width ${Fn}ms ${Ln}, min-width ${Fn}ms ${Ln}, max-width ${Fn}ms ${Ln}`}};export{Us as $,kx as A,Cx as B,jx as C,Li as D,Ns as E,Px as F,mx as G,Ux as H,Df as I,mo as J,fx as K,If as L,Dh as M,go as N,hx as O,Lx as P,Xf as Q,Hn as R,Tx as S,Ox as T,Fa as U,Pf as V,xn as W,Sf as X,jf as Y,La as Z,bn as _,sn as a,kf as a0,lx as a1,bx as a2,Cf as a3,Nf as a4,xx as a5,wx as a6,vx as a7,Ef as a8,As as a9,gx as aa,yx as ab,Sx as ac,ax as ad,cx as ae,dx as af,ux as ag,Yf as ah,px as ai,oh as aj,ih as ak,Af as al,ix as am,Ex as an,Nx as ao,ym as b,Rx as c,Un as d,fh as e,_x as f,Mx as g,Ix as h,Sm as i,Dx as j,Ax as k,Kx as l,zx as m,Gx as n,ox as o,Zf as p,eh as q,Bx as r,Fx as s,th as t,_n as u,hi as v,sh as w,Zm as x,$x as y,nh as z};