@pi-chamber/web 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/bin/cli.js +5 -2
  2. package/bin/cli.test.js +44 -0
  3. package/bin/lib/DOCUMENTATION.md +5 -5
  4. package/bin/lib/cli-args.js +19 -4
  5. package/bin/lib/commands-lifecycle.js +14 -0
  6. package/bin/lib/commands-logs.js +2 -1
  7. package/bin/lib/commands-serve.js +166 -2
  8. package/bin/lib/commands-tunnel.js +21 -0
  9. package/bin/lib/commands-update.js +97 -33
  10. package/bin/lib/commands-update.test.js +96 -1
  11. package/dist/assets/{DiagramEditor-DerMrS6m.js → DiagramEditor-CcbnMl1H.js} +1 -1
  12. package/dist/assets/{DiagramView-DdipXAq8.js → DiagramView-DTW5jwK3.js} +1 -1
  13. package/dist/assets/DiffView-CZyHHAOB.js +18 -0
  14. package/dist/assets/{FilesView-BXp0yc0j.js → FilesView-BJYLFR3H.js} +3 -3
  15. package/dist/assets/GitView-Cg_5UU7E.js +8 -0
  16. package/dist/assets/{JsonTreeView-CxXRXXzk.js → JsonTreeView-GTdKGEdy.js} +1 -1
  17. package/dist/assets/{MarkdownRendererImpl-DNZQgQua.js → MarkdownRendererImpl-WqBwxlso.js} +1 -1
  18. package/dist/assets/{PatchDiff-B_NFEIX7.js → PatchDiff-BRi23N1l.js} +1 -1
  19. package/dist/assets/{SessionSwitcherContent-Q4P2TGBr.js → SessionSwitcherContent-7VAU5pwZ.js} +1 -1
  20. package/dist/assets/{SessionSwitcherDropdown-Cgw2mQIO.js → SessionSwitcherDropdown-BslRtccE.js} +2 -2
  21. package/dist/assets/{SessionUnreadDot-BxtTkvHB.js → SessionUnreadDot-1nV0Z2ZA.js} +1 -1
  22. package/dist/assets/SettingsView-UIaAyjTo.js +2 -0
  23. package/dist/assets/{SettingsWindow-BEjHL1ET.js → SettingsWindow-D4jZHl8X.js} +1 -1
  24. package/dist/assets/{ToolOutputDialog-C_7vJLEq.js → ToolOutputDialog-BoeJONiR.js} +1 -1
  25. package/dist/assets/{ToolPartDiffPreview-ClV785zX.js → ToolPartDiffPreview-9FLv2fWD.js} +1 -1
  26. package/dist/assets/{VirtualizedFileDiff-DrxkW2WQ.js → VirtualizedFileDiff-ywmPBXAG.js} +4 -4
  27. package/dist/assets/{collapsible-CR3-hRMy.js → collapsible-6mCYf7Ky.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-D0mQcleY.js → computeVirtualFileMetrics-3H6mg13G.js} +1 -1
  29. package/dist/assets/{contextFileOpenGuard-BRc5Z0g-.js → contextFileOpenGuard-CKyf-TZ7.js} +1 -1
  30. package/dist/assets/gitStatusPredicates-UsytDMy_.js +134 -0
  31. package/dist/assets/index-C8NYcA8-.css +1 -0
  32. package/dist/assets/{index-CMfiVUIr.js → index-D1IaU-Q7.js} +1 -1
  33. package/dist/assets/index-yWgKW2Fx.js +8 -0
  34. package/dist/assets/{isDiffPlainText-MmBA1REG.js → isDiffPlainText-DPCilEx_.js} +1 -1
  35. package/dist/assets/{isFilePlainText-bQAPxqO9.js → isFilePlainText-XdCAgm8R.js} +1 -1
  36. package/dist/assets/main-DcAMXRSi.js +135 -0
  37. package/dist/assets/{main-zZrKd3hZ.js → main-DhvLreEl.js} +2 -2
  38. package/dist/assets/{markdownCore-B9jXCPry.js → markdownCore-BF0Dqwm4.js} +1 -1
  39. package/dist/assets/{miniChat-Di2oVS5o.js → miniChat-DsCx0dsW.js} +2 -2
  40. package/dist/assets/{mobile-VU_G_SgX.js → mobile-C-IN49xX.js} +2 -2
  41. package/dist/assets/{renderElectronMiniChatApp-Bi1927c8.js → renderElectronMiniChatApp-C13HXGZL.js} +2 -2
  42. package/dist/assets/renderMobileApp-xCdVzvyf.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-CT3WShpj.js +54 -0
  44. package/dist/assets/{runtimeSurface-CBaS2Ank.js → runtimeSurface-C_3mcJ01.js} +1 -1
  45. package/dist/assets/{useAppFontEffects-8ZU-TTIW.js → useAppFontEffects-BgK55NDM.js} +80 -80
  46. package/dist/assets/{useFilesViewSearch-COow9O9x.js → useFilesViewSearch-CWx24PZg.js} +1 -1
  47. package/dist/assets/{usePushVisibilityBeacon-zYd3ppNh.js → usePushVisibilityBeacon-swMQLm-i.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-DOQqhi-e.js → useSwitcherItems-CrS-F6DY.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-language-data-B_0wrsbo.js → vendor-codemirror-language-data-BzeePAPn.js} +2 -2
  50. package/dist/assets/{vendor-dnd-kit-core-CP8ck10N.js → vendor-dnd-kit-core-C9qcAm_1.js} +1 -1
  51. package/dist/assets/{vendor-dnd-kit-sortable-B-Icjoj4.js → vendor-dnd-kit-sortable-D8ozj8M-.js} +1 -1
  52. package/dist/assets/vendor-xterm-addon-fit-DX4qG4td.js +1 -0
  53. package/dist/assets/vendor-xterm-xterm-CrXqRur4.js +16 -0
  54. package/dist/assets/vendor-xterm-xterm-DDGTF8rc.css +1 -0
  55. package/dist/assets/{web-components-C9ENH49P.js → web-components-DAkBDXRk.js} +3 -3
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +1 -2
  60. package/server/lib/stt/DOCUMENTATION.md +1 -1
  61. package/server/lib/terminal/DOCUMENTATION.md +2 -2
  62. package/dist/assets/DiffView-Gh9wjthp.js +0 -18
  63. package/dist/assets/GitView-BmNCkkoC.js +0 -8
  64. package/dist/assets/SettingsView-CFzxRzUq.js +0 -2
  65. package/dist/assets/gitStatusPredicates-DBGDfr1K.js +0 -134
  66. package/dist/assets/index-CzO3ooje.css +0 -1
  67. package/dist/assets/index-ivrh3jfy.js +0 -8
  68. package/dist/assets/main-BoVfUG73.js +0 -135
  69. package/dist/assets/renderMobileApp-D9mxhuaM.js +0 -11
  70. package/dist/assets/runtimeEndpointReset-DImT35Ug.js +0 -54
  71. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
@@ -0,0 +1,54 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D1IaU-Q7.js","assets/useAppFontEffects-BgK55NDM.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-yWgKW2Fx.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-C8NYcA8-.css","assets/vendor-base-ui-vkqQ2P9o.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-C_3mcJ01.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-BzeePAPn.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-DYppkHEk.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/computeVirtualFileMetrics-3H6mg13G.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-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.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-XdCAgm8R.js","assets/isDiffPlainText-DPCilEx_.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-Cy8fTs3_.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-BslRtccE.js"])))=>i.map(i=>d[i]);
2
+ import{_ as cs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Pe,j as t,R as i,b as dc}from"./vendor-react-B5Z1Mdn3.js";import{cV as Ls,i as uc,bR as fc,D as Lt,E as Ge,F as Ke,a as Bt,U as Te,I as D,G as He,b as _t,bm as st,t as oe,c as pt,k as Ne,b6 as Ws,bg as dn,M as Ci,aS as Ht,aT as Wt,bi as us,bj as ns,bk as fs,bl as Is,cW as hc,bb as ks,cX as Cs,Z as Xs,cY as rr,cZ as Do,c_ as Ro,c$ as rn,ay as Ai,aq as ws,aN as Eo,af as As,cj as kr,d0 as pc,d1 as mc,d2 as gc,d3 as bc,K as xc,d4 as Cr,d5 as yc,L as Kt,d6 as wc,d7 as vc,cw as Sc,ck as Ni,d8 as jc,cS as kc,au as Ii,av as Di,d9 as Ri,u as Ar,r as Bs,bB as Qr,ba as Cc,Y as Ac,bX as Po,bW as Nc,bV as Ic,c3 as Ei,bO as Ds,da as Dc,g as Vr,j as Ys,Q as Pi,db as lt,d as Nr,dc as Rc,dd as Ec,bS as Pc,de as Hn,df as Mo,dg as Mi,c4 as Ti,dh as Ir,di as Fi,S as Oi,b7 as Mc,dj as Tc,dk as Fc,l as Li,by as Oc,dl as Lc,dm as Bc,m as _c,dn as Uc,dp as Ts,e as zc,dq as $c,bw as Gc,s as Kc,f as Hc,a7 as Bi,dr as Dr,ds as Wc,dt as Yc,c5 as qc,cU as Qc,du as Vc,a3 as Jc,bn as Ns,aP as _i,bH as Xc,aD as Zc,dv as ed,dw as td,bz as sd,dx as nd,R as Ui,ah as rd,dy as od,W as zi,dz as $i,cC as id,cD as ad,dA as ld,cu as cd,bv as dd,dB as ud,dC as fd}from"./useAppFontEffects-BgK55NDM.js";import{g as To,aY as hd,aZ as Fo,a_ as pd,i as md,h as gd,A as bd,r as Dt,C as un,B as xd,a$ as yd,b as zs,b0 as Jr,b1 as Xr,b2 as wd,b3 as vd,f as $s,M as Sd,b4 as jd,b5 as kd,b6 as Cd,as as Zt,p as es,b7 as Ad,b8 as Nd,b9 as Id,y as Zr,ba as Dd,bb as Rd,bc as Ed,u as le,c as _,z as Pd,n as je,bd as Gs,D as Ot,be as Oo,bf as Rr,w as Wn,bg as Md,aA as Td,aa as eo,m as Ln,bh as Fd,bi as Od,T as Gi,G as Ld,l as Ki,j as on,bj as Er,H as Pr,W as jn,bk as Bd,bl as Zs,ay as or,bm as Mr,bn as vs,bo as Lo,bp as Tr,bq as Hi,br as Fr,bs as _d,ah as Ud,bt as zd,bu as $d,bv as Gd,bw as Kd,ak as Hd,a4 as Wd,V as Yd,k as qd,bx as Wi,d as Qd,L as Vd}from"./index-yWgKW2Fx.js";import{c as hs,d as Yi,p as to,u as Or,a as Jd}from"./vendor-zustand-GVb4H8HE.js";import{g as ds,d as Xd,e as qi,r as Zd,h as Qi,i as En,j as Vi,b as fn,c as hn,s as eu,k as tu,l as su,m as Bo,n as Yn,f as nu,S as ru,a as ou,t as iu,o as au}from"./SessionUnreadDot-1nV0Z2ZA.js";import{i as Ji,j as Xi,k as Zi,l as ea,m as ta,M as sa,S as na,D as lu,c as cu,d as du,e as uu,f as fu,g as hu,h as pu}from"./vendor-base-ui-vkqQ2P9o.js";import{c as ra,d as Lr,P as mu,D as oa,e as ia,f as gu,b as bu,a as xu,T as yu,M as wu}from"./vendor-dnd-kit-core-C9qcAm_1.js";import{u as vu}from"./vendor-tanstack-react-virtual-2skouoFw.js";import{S as Su,v as ju,u as ku}from"./vendor-dnd-kit-sortable-D8ozj8M-.js";import{C as Cu}from"./vendor-dnd-kit-utilities-DTY1C6ST.js";import"./vendor-xterm-xterm-CrXqRur4.js";import{usePermissionStore as Au}from"./permissionStore-iKN1K2_x.js";const Nu="chat";function aa(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set(Ls.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set(Ls.SETTINGS,n),s}return e.tab!==Nu&&s.set(Ls.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set(Ls.FILE,e.diffFile),s}function Iu(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Du(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=aa(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!s.has(Ls.SESSION)&&s.set(Ls.SESSION,o);const a=[...s.entries()].sort((c,u)=>c[0].localeCompare(u[0])),l=[...n.entries()].sort((c,u)=>c[0].localeCompare(u[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 Br(e,s={}){if(!(typeof window>"u")&&!(!s.force&&Du(e)))try{const n=aa(e),r=Iu(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Ru=["typescript","javascript","tsx","jsx","json","markdown"],la={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let _o=null;const ca=()=>(_o??=Promise.all([cs(()=>import("./index-D1IaU-Q7.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])),cs(()=>import("./workerFactory-tw7cIdmV.js"),[]),cs(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([110,111,97,98,24,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})),_o),pn={},Uo=new Set,_r=new Set;let Pn={light:"pierre-light",dark:"pierre-dark"};const Eu=()=>{for(const e of _r)e()},da=(e,s)=>{s.setRenderOptions({theme:Pn,lineDiffType:la[e].lineDiffType})},Ur=e=>{typeof window>"u"||Uo.has(e)||(Uo.add(e),ca().then(s=>{if(pn[e])return;const n=la[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ru,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),pn[e]=r,da(e,r),Eu()}))},Pu=e=>(_r.add(e),()=>_r.delete(e)),Mu=e=>{if(!(Pn.light===e.light&&Pn.dark===e.dark)){Pn=e;for(const s of Object.keys(pn)){const n=pn[s];n&&da(s,n)}}},zg=({children:e})=>{const s=uc(),n=To(!1),r=To(!0),o=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(u=>u.metadata.id===o)??n,c=s?.availableThemes.find(u=>u.metadata.id===a)??r;return Pe.useEffect(()=>{let u=!1;return ca().then(d=>{u||(d.ensurePierreThemeRegistered(l),d.ensurePierreThemeRegistered(c),Mu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{u=!0}},[c,l]),Pe.useEffect(()=>{if(typeof window>"u")return;const u=()=>{Ur("unified"),Ur("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(u,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const d=window.setTimeout(u,2e3);return()=>window.clearTimeout(d)},[]),t.jsx(t.Fragment,{children:e})},$g=(e="unified")=>{const s=Pe.useSyncExternalStore(Pu,()=>pn[e],()=>{});return Pe.useEffect(()=>{Ur(e)},[e]),s};function Tu(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=fc();return e}catch{return"unknown"}}function Fu(){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 Ou(){const e=xd();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 Lu(e){const s=new URLSearchParams;return s.set("deviceClass",Tu()),s.set("arch",Fu()),s.set("platform",Ou()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",un()?"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 ir(e,s){try{const n=Lu(e);s&&n.set("currentVersion",s);const r=await Dt(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const o=await r.json();return{available:o.available??!1,version:o.version,currentVersion:o.currentVersion??"unknown",body:o.body,releaseUrl:o.releaseUrl,downloadUrl:o.downloadUrl,nextSuggestedCheckInSec:typeof o.nextSuggestedCheckInSec=="number"&&Number.isFinite(o.nextSuggestedCheckInSec)?o.nextSuggestedCheckInSec:void 0,packageManager:o.packageManager,updateCommand:o.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Bu(){return md()?"mobile":gd()?"desktop":bd()?"web":null}const zo={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Mn=hs()((e,s)=>({...zo,checkForUpdates:async()=>{const n=Bu();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,o=null;if(n==="desktop"){const a="0.9.0",[l,c]=await Promise.allSettled([Fo(),ir("desktop",a)]),u=l.status==="fulfilled"?l.value:null;return o=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:u?.available??!1,info:u,lastChecked:Date.now(),nextCheckInSec:o}),o}else n==="web"?(r=await ir("web"),o=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await ir("mobile","0.9.0"),o=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:o}),o}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const o=await Fo();if(!o?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...o,body:l.info.body||o.body,available:l.info.available}:o})),!await pd(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(o){e({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await hd())throw new Error("Desktop restart only works on Local instance")}catch(o){e({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(zo)}})),_u={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},Uu={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&&Uu[e]||"var(--primary)"}const $o=({icon:e,className:s,colorToken:n})=>{const r=_u[e??"branch"]??"user-3";return t.jsx(D,{name:r,className:s,style:{color:ua(n)}})},zu=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:o=!1})=>{const a=r||s.length===0;return t.jsxs(Lt,{children:[t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx(Bt,{asChild:!0,children:t.jsxs(Te,{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(D,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx($o,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!o&&t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(D,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(He,{sideOffset:8,children:"Git identity"})]}),t.jsx(_t,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(st,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx($o,{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(D,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},$u=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Hs=e=>{if(!e||$u(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},_s=e=>e.endsWith("/"),Bn=e=>{const s=e.trim();return!s||_s(s)?s:`${s}/`},so=e=>e.lastIndexOf("/"),fa=e=>{if(_s(e))return e;const s=so(e);return s<0?e:e.slice(0,s+1)},ha=e=>{const s=so(e);return e.slice(s+1)},pa=e=>{const s=Hs(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=so(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},ma=e=>_s(e)&&pa(e)!==null,Gu=e=>{if(!ma(e))return null;const s=Hs(e.trim());return ha(s)||s},Ku=(e,s)=>`${fa(e)}${s}/`,Ss=e=>{if(!e)return null;const s=Hs(Ks(e.trim()));return s?s.toLowerCase():null},Go=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},Hu=(e,s)=>{const n=Hs(Ks(e.trim())),r=Hs(Ks(s.trim()));if(!n)return"";if(!r)return Bn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Bn(n)},Wu=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,zr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Yu=async()=>yd(),qu=()=>{const[e,s]=Pe.useState(!1),[n,r]=Pe.useState(!1);Pe.useEffect(()=>{s(zs()),r(Jr())},[]);const o=Pe.useCallback(async c=>e?await Xr(c):{success:!0,path:c},[e]),a=Pe.useCallback(async c=>e?await wd():{success:!0},[e]),l=Pe.useCallback(async c=>e?await vd():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:a,stopAccessing:l}};function Qu({open:e,addedProjectPaths:s,shouldSuppressAutoFocus:n}){const r=$s(Z=>Z.homeDirectory),{canRequestAccess:o,startAccessing:a}=qu(),l=i.useRef(null),c=i.useRef(new Map),[u,d]=i.useState(""),[f,p]=i.useState("~/"),[b,m]=i.useState([]),[g,h]=i.useState(!1),[v,x]=i.useState(!1),[I,y]=i.useState(null),[k,A]=i.useState(0),[N,j]=i.useState(0),[w,C]=i.useState(!1),[R,P]=i.useState(!1),[M,F]=i.useState("right"),B=i.useRef("~/"),K=u||r;i.useEffect(()=>{if(!e)return;p("~/"),m([]),j(0),C(!1),P(!1),B.current="~/",F("right"),n||requestAnimationFrame(()=>zr(l.current));let Z=!1;return(async()=>{const q=await Yu();Z||(d(q||r||""),n||requestAnimationFrame(()=>zr(l.current)))})(),()=>{Z=!0}},[r,e,n]);const L=i.useMemo(()=>fa(f),[f]),T=i.useMemo(()=>_s(f)?"":ha(f),[f]),U=i.useMemo(()=>K?Go(L,K):"",[L,K]);i.useEffect(()=>{const Z=B.current;Z!==L&&(F(L.length>=Z.length?"right":"left"),B.current=L)},[L]),i.useEffect(()=>{if(!e||!U){m([]),y(null);return}let Z=!1;return h(!0),x(!1),y(null),Sd(U).then(ue=>{if(Z)return;x(!1),y(null);const q=ue.filter(ye=>ye.isDirectory).map(ye=>({name:ye.name,path:Ks(ye.path)})).sort((ye,_e)=>ye.name.localeCompare(_e.name));m(q)}).catch(ue=>{if(!Z){m([]);const q=jd(ue)?ue.reason:"unknown";y(q),x(q==="not-found")}}).finally(()=>{Z||h(!1)}),()=>{Z=!0}},[U,k,e]);const H=i.useMemo(()=>{const Z=T.toLowerCase(),ue=R||T.startsWith(".");return b.filter(q=>q.name.toLowerCase().startsWith(Z)&&(ue||!q.name.startsWith(".")))},[T,b,R]),ce=i.useMemo(()=>Gu(f),[f]),Q=i.useMemo(()=>pa(f),[f]),z=i.useMemo(()=>{const Z=[],ue=Ss(U);ma(f)&&ce&&Q&&Z.push({type:"parent",value:"browse:up",name:ce,path:Q,alreadyAdded:!!(ue&&s.has(ue))});for(const q of H){const ye=Ss(q.path);Z.push({type:"directory",value:`browse:${q.path}`,name:q.name,path:q.path,alreadyAdded:!!(ye&&s.has(ye))})}return Z},[s,U,ce,H,Q,f]);i.useEffect(()=>{j(0)},[f,z.length]);const Ie=i.useMemo(()=>K?Hs(Go(f,K)):"",[K,f]),O=Ss(Ie),de=!!(O&&s.has(O)),he=i.useMemo(()=>T?H.find(Z=>Z.name===T)??null:null,[T,H]),$=!!(Ie&&!de&&(I===null||I==="not-found")&&(_s(f)&&v||!_s(f)&&T.trim().length>0&&he===null)),G=z[N]??null,J=!!G,se=i.useCallback(Z=>{p(Bn(Z))},[]),fe=i.useCallback(Z=>{p(Ku(f,Z.name))},[f]),ke=i.useCallback(Z=>{if(Z){if(Z.type==="parent"){se(Z.path);return}fe(Z)}},[se,fe]),Me=i.useCallback(async Z=>{const ue=await a(Z);if(!ue.success)return oe.error("Failed to open directory",{description:ue.error||"Desktop could not grant file access."}),!1;const q=K?Hu(Z,K):Bn(Ks(Z));return se(q),!0},[se,K,a]),Re=i.useCallback(async()=>{if(!w){C(!0);try{if(Jr()){const ue=await Xr(Ie);if(!ue.success||!ue.path){ue.error&&ue.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:ue.error});return}await Me(ue.path);return}const Z=await kd(Ie);if(Z.status==="cancelled")return;if(Z.status!=="picked"){oe.error("Couldn't open a folder picker",{description:Z.error});return}await Me(Z.path)}catch(Z){oe.error("Failed to select directory",{description:Z instanceof Error?Z.message:"Unknown error occurred."})}finally{C(!1)}}},[Me,w,Ie]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:g,isBrowseDirectoryMissing:v,browseErrorReason:I,browseReloadKey:k,setBrowseReloadKey:A,highlightedIndex:N,setHighlightedIndex:j,isPickingLocation:w,showHidden:R,setShowHidden:P,folderEnterFrom:M,explorerRootDirectory:K,browseDirectoryDisplayPath:L,browseDirectoryAbsolutePath:U,browseFilterQuery:T,filteredEntries:H,rows:z,targetPath:Ie,isAlreadyAdded:de,shouldCreateTarget:$,highlightedRow:G,hasHighlightedBrowseItem:J,canRequestAccess:o,browseToDisplayPath:se,browseToEntry:fe,executeRow:ke,applyPickedLocation:Me,handleBrowseLocation:Re}}const ys=hs()(Yi(to((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=es()?.git,o=r?await r.getGitIdentities():await Ed();return e({profiles:o,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=es()?.git,r=n?.getGlobalGitIdentity?await n.getGlobalGitIdentity():await Rd();if(r&&r.userName&&r.userEmail){const o={id:"global",name:"Global Identity",userName:r.userName,userEmail:r.userEmail,authType:r.sshCommand?"ssh":void 0,sshKey:r.sshCommand?r.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:o})}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=es()?.git,r=n?.discoverGitCredentials?await n.discoverGitCredentials():await Dd();return e({discoveredCredentials:r}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const o=r.trim();return o.length>0?o:null};try{let r=null;if(r===null){const o=es()?.settings;if(o)try{const l=(await o.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const o=await Dt("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",o=r.length>0?r:"";return await Zr({defaultGitIdentityId:o}),e({defaultGitIdentityId:o.length>0?o:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};Zt("saving");const o=es()?.git;return o?await o.createGitIdentity(r):await Id(r),Zt("saved"),await s().loadProfiles(),!0}catch(r){return Zt("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const o=s().profiles.find(c=>c.id===n);if(!o)throw new Error("Profile not found");const a={...o,...r};Zt("saving");const l=es()?.git;return l?await l.updateGitIdentity(n,a):await Nd(n,a),Zt("saved"),await s().loadProfiles(),!0}catch(o){return Zt("error"),console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async n=>{try{Zt("saving");const r=es()?.git;return r?await r.deleteGitIdentity(n):await Ad(n),Zt("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return Zt("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:o}=s();return n==="global"?o||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(o=>!n.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Cd(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ys);function Vu({open:e,onClose:s,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:a,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:u,isPickingLocation:d}){const f=pt(Q=>Q.addProject),p=le(Q=>Q.setActiveMainTab),b=le(Q=>Q.setSessionSwitcherOpen),m=Ne(Q=>Q.openNewSessionDraft),g=ys(Q=>Q.profiles),h=ys(Q=>Q.globalIdentity),v=ys(Q=>Q.defaultGitIdentityId),x=ys(Q=>Q.loadProfiles),I=ys(Q=>Q.loadGlobalIdentity),y=ys(Q=>Q.loadDefaultGitIdentityId),[k,A]=i.useState(!1),[N,j]=i.useState(!1),[w,C]=i.useState(""),[R,P]=i.useState(null);i.useEffect(()=>{e&&(A(!1),j(!1),C(""),P(null))},[e]),i.useEffect(()=>{e&&(x(),I(),y())},[y,x,I,e]);const M=i.useMemo(()=>{const Q=new Map;h&&Q.set(h.id,h);for(const z of g)Q.set(z.id,z);return Array.from(Q.values())},[g,h]);i.useEffect(()=>{if(!e||!N||R!==null)return;const Q=typeof v=="string"?v.trim():"";if(Q&&M.some(Ie=>Ie.id===Q)){P(Q);return}const z=M.find(Ie=>Ie.authType==="ssh"||Ie.sshKey);z&&P(z.id)},[M,v,N,e,R]);const F=i.useMemo(()=>M.find(Q=>Q.id===R)??null,[M,R]),B=i.useCallback((Q,z)=>{p("chat"),n&&b(!1),m({selectedProjectId:Q,directoryOverride:z}),s()},[n,s,m,p,b]),K=i.useCallback(async Q=>{if(!Q||k)return;const z=Ss(Q);if(z&&r.has(z))return;let Ie=Q;A(!0);try{const O=!N&&a&&Ss(Q)===Ss(o);if(N){const he=w.trim();if(!he){oe.error("Enter a repository URL before cloning.");return}const $=await Dt("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:he,destinationPath:Q,gitIdentityId:F?.id??null})});if(!$.ok)throw new Error("Failed to clone git repository");Ie=(await $.json()).path||Q}else if(O&&!(await Dt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:Q})})).ok)throw new Error("Failed to select directory");const de=f(Ie);if(!de){oe.error("Failed to add folder",{description:"Please select a valid directory path."});return}B(de.id,de.path)}catch(O){oe.error("Failed to select directory",{description:O instanceof Error?O.message:"Unknown error occurred."})}finally{A(!1)}},[f,r,c,w,N,k,B,F?.id,a,o]),L=!k&&!d&&!u&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,T=L&&w.trim().length>0,U=N?T:L,H=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:k,isCloneMode:N,setIsCloneMode:j,cloneRemoteUrl:w,setCloneRemoteUrl:C,selectedGitIdentityId:R,setSelectedGitIdentityId:P,availableGitIdentities:M,selectedGitIdentity:F,canSubmit:U,submitActionLabel:u?"Already added":N?k?"Cloning...":"Clone & add":k?"Adding...":a?"Create & add":"Add folder",submitModifierLabel:H,finalizeSelection:K}}const Ju=({open:e,onOpenChange:s})=>{const n=pt(q=>q.projects),{isMobile:r,isTablet:o}=Ws(),a=r||o,l=i.useMemo(()=>new Set(n.map(q=>Ss(q.path)).filter(q=>!!q)),[n]),c=i.useCallback(()=>{s(!1)},[s]),{inputRef:u,rowRefs:d,query:f,setQuery:p,isLoading:b,browseErrorReason:m,setBrowseReloadKey:g,highlightedIndex:h,setHighlightedIndex:v,isPickingLocation:x,showHidden:I,setShowHidden:y,folderEnterFrom:k,browseDirectoryDisplayPath:A,browseDirectoryAbsolutePath:N,rows:j,targetPath:w,isAlreadyAdded:C,shouldCreateTarget:R,highlightedRow:P,hasHighlightedBrowseItem:M,canRequestAccess:F,executeRow:B,handleBrowseLocation:K}=Qu({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:a}),{isConfirming:L,isCloneMode:T,setIsCloneMode:U,cloneRemoteUrl:H,setCloneRemoteUrl:ce,setSelectedGitIdentityId:Q,availableGitIdentities:z,selectedGitIdentity:Ie,canSubmit:O,submitActionLabel:de,submitModifierLabel:he,finalizeSelection:$}=Vu({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:R,browseErrorReason:m,browseDirectoryAbsolutePath:N,isAlreadyAdded:C,isPickingLocation:x});i.useLayoutEffect(()=>{const q=u.current;q&&(q.scrollLeft=q.scrollWidth)},[u,f]),i.useLayoutEffect(()=>{!e||a||zr(u.current)},[u,e,a]),i.useLayoutEffect(()=>{const q=j[h];q&&d.current.get(q.value)?.scrollIntoView({block:"nearest"})},[h,d,j]);const G=i.useCallback(q=>{if(q.key==="ArrowDown"){q.preventDefault(),v(ye=>Math.min(j.length-1,ye+1));return}if(q.key==="ArrowUp"){q.preventDefault(),v(ye=>Math.max(0,ye-1));return}if(q.key==="Enter"){if(q.preventDefault(),Wu(q)){$(w);return}M&&B(P);return}q.key==="Backspace"&&f===""&&(q.preventDefault(),c())},[B,$,c,M,P,f,j.length,v,w]),J=t.jsxs("button",{type:"button",onClick:()=>y(q=>!q),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:[I?t.jsx(D,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),se=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(D,{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(dn,{ref:u,value:f,onChange:q=>p(Ks(q.target.value)),onKeyDown:G,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(Te,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:L||x,onMouseDown:q=>q.preventDefault(),onClick:()=>{K()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(D,{name:"folder-open",className:"h-3.5 w-3.5"}),x?"Opening...":"Browse"]})]})}),fe=j.some(q=>q.type==="parent"),ke=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(Te,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":T,disabled:L||x,onClick:()=>U(q=>!q),children:[t.jsx(D,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),T?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(dn,{value:H,onChange:q=>ce(q.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(zu,{activeProfile:Ie,identities:z,onSelect:q=>Q(q.id),isApplying:L,iconOnly:!0})]})]}):null,C?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",k==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:b?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):m&&m!=="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:m==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[m==="os-permission"&&F?t.jsx(Te,{size:"xs",onClick:()=>{K()},disabled:x,children:"Grant access"}):null,t.jsx(Te,{variant:"outline",size:"xs",onClick:()=>g(q=>q+1),children:"Try again"})]})]}):j.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:j.map((q,ye)=>{const _e=ye===h,Y=q.type==="directory"&&fe;return t.jsxs("button",{ref:ae=>{ae?d.current.set(q.value,ae):d.current.delete(q.value)},type:"button","aria-label":q.type==="parent"?q.alreadyAdded?`Go back from ${q.name}, already added`:`Go back from ${q.name}`:q.alreadyAdded?`Open ${q.name}, already added`:`Open ${q.name}`,onMouseEnter:()=>v(ye),onMouseDown:ae=>ae.preventDefault(),onClick:()=>B(q),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",_e&&"bg-interactive-selection text-interactive-selection-foreground",!_e&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",Y&&"pl-4"),children:[q.type==="parent"?t.jsx(D,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(D,{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:q.name})]}),q.alreadyAdded?t.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",_e?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,q.type==="parent"?t.jsx(D,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(D,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},q.value)})})},A)]})}),Me=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[se,ke]}),Re=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(D,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(D,{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(D,{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:he}),t.jsx(D,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Z=t.jsx(Te,{size:r?"xs":"default",onClick:()=>{$(w)},disabled:!O,className:_(r&&"w-full flex-1"),children:de}),ue=()=>t.jsxs(t.Fragment,{children:[r?null:Re,t.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:Z})]});return r?t.jsx(Ci,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:ue()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:J}),Me]})}):t.jsx(Ht,{open:e,onOpenChange:s,children:t.jsxs(Wt,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(us,{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(ns,{children:"Add folder"}),t.jsx(fs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),J]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Me}),t.jsx(Is,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:ue()})]})})},kn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Gg=()=>{const[e,s]=i.useState(!1),[n,r]=i.useState(null),[o,a]=i.useState(!1),l=hc,c=Ne(N=>N.deleteSessions),u=le(N=>N.showDeletionDialog),d=le(N=>N.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:b}=Ws(),m=f||p||b;i.useEffect(()=>Pd(()=>{s(!1)}),[]);const g=i.useCallback(N=>{r({sessions:N.sessions,dateLabel:N.dateLabel})},[]),h=i.useCallback(()=>{r(null),a(!1)},[]),v=i.useCallback(async N=>{if(N.sessions.length===0)return;if(N.sessions.length===1){const R=N.sessions[0];await l(R.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const j=N.sessions.map(R=>R.id),{deletedIds:w,failedIds:C}=await c(j);if(w.length>0){const R=C.length>0?C.length===1?`${C.length} session could not be deleted.`:`${C.length} sessions could not be deleted.`:N.dateLabel?`Removed all sessions from ${N.dateLabel}.`:void 0;oe.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:kn(R)})}C.length>0&&oe.error(C.length===1?`Failed to delete ${C.length} session`:`Failed to delete ${C.length} sessions`,{description:kn("Please try again in a moment.")})},[l,c]);i.useEffect(()=>ks.onDeleteRequest(N=>{if(!u){v(N);return}g(N)}),[g,u,v]),i.useEffect(()=>ks.onDirectoryRequest(()=>{s(!0)}),[]);const x=i.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const N=n.sessions[0];if(!await l(N.id)){oe.error("Failed to delete session"),a(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const N=n.sessions.map(R=>R.id),j=await c(N),w=j.deletedIds,C=j.failedIds;if(w.length>0){const R=C.length>0?C.length===1?`${C.length} session could not be deleted.`:`${C.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;oe.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:kn(R),action:{label:"OK",onClick:()=>{}}})}if(C.length>0&&(oe.error(C.length===1?`Failed to delete ${C.length} session`:`Failed to delete ${C.length} sessions`,{description:kn("Please try again in a moment.")}),w.length===0)){a(!1);return}}h()}finally{a(!1)}}},[n,l,c,h]),I=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.`:"",y=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(N=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:ds(N)})},N.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,k=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>d(!u),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!u,children:[u?t.jsx(D,{name:"checkbox-blank",className:"size-4"}):t.jsx(D,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Te,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),t.jsx(Te,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),A=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(Ci,{open:!!n,onClose:()=>{o||h()},title:A,footer:t.jsx("div",{className:"flex justify-end gap-2",children:k}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[I&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),y]})}):t.jsx(Ht,{open:!!n,onOpenChange:N=>{if(!N){if(o)return;h()}},children:t.jsxs(Wt,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(us,{children:[t.jsx(ns,{children:A}),I&&t.jsx(fs,{children:I})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:y}),t.jsx(Is,{className:"mt-2 gap-2 pt-1 pb-1",children:k})]})}),t.jsx(Ju,{open:e,onOpenChange:s})]})},Kg=()=>{const e=Cs(s=>s.entries);return i.useEffect(()=>{for(const s of e.values())!s.receipt||s.notificationSent||(Cs.getState().markNotificationSent(s.key),oe.success("Worktree ready",{id:`worktree-ready:${s.key}`,description:s.receipt.branch||s.receipt.path}))},[e]),null},Xu=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-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:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Zu={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ef(e){const s=e.trim().toLowerCase();return Xu.find(n=>n.slug===s)??null}function tf(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=Zu[s];if(n)return n;const r=ef(s);return r?r.slug:"home"}function Hg(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"snippets":return"chat-thread";case"prompt-templates":return"terminal";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"}}function Wg(){const e=i.useRef(!1),s=i.useRef(!1),n=Ne(f=>f.setCurrentSession),r=le(f=>f.setActiveMainTab),o=le(f=>f.setSettingsDialogOpen),a=le(f=>f.setSettingsPage),l=le(f=>f.navigateToDiff),c=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=Ne.getState().currentSessionId,b=Xs().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==b){const m=Ne.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,m)}}if(f.settingsPath){a(tf(f.settingsPath)),o(!0);return}le.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{s.current=!1}}},[n,r,o,a,l]),u=i.useCallback(()=>{const f=Ne.getState(),p=Xs().getState(),b=le.getState();return{sessionId:rr({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),d=i.useCallback((f={})=>{if(s.current)return;const p=u();Br(p,f)},[u]);i.useEffect(()=>{if(e.current||(e.current=!0,!Do()))return;const f=Ro();(async()=>(await c(f),Br({...u(),sessionId:f.sessionId??rr({currentSessionId:Ne.getState().currentSessionId,piSelectedSessionId:Xs().getState().selectedSessionId,draft:Ne.getState().newSessionDraft}),tab:f.tab??le.getState().activeMainTab,settingsPath:f.settingsPath??le.getState().settingsPage,diffFile:f.diffFile??le.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,u]),i.useEffect(()=>{const f=()=>{const v=Ne.getState(),x=Xs().getState();return rr({currentSessionId:v.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:v.newSessionDraft})};let p=f(),b=Ne.getState().newSessionDraft?.open===!0;const m=()=>{const v=Ne.getState(),x=f(),I=v.newSessionDraft?.open===!0;x===p&&I===b||s.current||(p=x,b=I,d({replace:!0}))},g=Ne.subscribe(()=>{m()}),h=Xs().subscribe(()=>{m()});return()=>{g(),h()}},[d]),i.useEffect(()=>{let f=le.getState().activeMainTab,p=le.getState().isSettingsDialogOpen,b=le.getState().settingsPage,m=le.getState().pendingDiffFile;return le.subscribe(h=>{if(s.current)return;const v=h.activeMainTab!==f,x=h.isSettingsDialogOpen!==p,I=h.settingsPage!==b,y=h.pendingDiffFile!==m&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,b=h.settingsPage,m=h.pendingDiffFile,(v||x||I||y)&&d()})},[d]),i.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Ro();if(Do())c(p);else{const b=le.getState();b.isSettingsDialogOpen&&o(!1),b.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function sf(e=!0){const s=Mn(r=>r.checkForUpdates),n=i.useRef(s);i.useEffect(()=>{n.current=s},[s]),i.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,u=null;const d=p=>{const b=Math.round(p*1e3);return Math.max(a,Math.min(l,b))},f=p=>{c||(u=window.setTimeout(async()=>{const b=await n.current(),m=typeof b=="number"&&Number.isFinite(b)?d(b):o;f(m)},p))};return f(r),()=>{c=!0,u!==null&&window.clearTimeout(u)}},[e])}function Yg(){const e=rn(s=>s.connection==="ready",void 0,"chrome");return sf(e),null}const Ko=12,nf=[{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"}],rf=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:o=nf,onComplete:a})=>{const l=Pe.useRef(!1);Pe.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Pe.useMemo(()=>Array.from({length:Ko},(u,d)=>{const f=Math.PI*2*d/Ko;return{x:Math.cos(f),y:Math.sin(f),delay:d*18}}),[]);return e?t.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:o.map(u=>{const d={"--burst-delay":`${u.delay}ms`,"--burst-x":`${u.x}%`,"--burst-y":`${u.y}%`,"--firework-color":`var(${u.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:d,children:c.map((f,p)=>{const b=f.x*u.radius,m=f.y*u.radius,g={"--translate-x":`${b}px`,"--translate-y":`${m}px`,"--particle-delay":`${f.delay}ms`,color:`var(${u.colorVar})`};return t.jsx("span",{className:"firework-particle",style:g},`${u.id}-${p}-${s}`)})},`${u.id}-${s}`)})}):null},of=({durationMs:e=3400}={})=>{const[s,n]=Pe.useState({isActive:!1,cycle:0}),r=Pe.useRef(null),o=Pe.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Pe.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Pe.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Pe.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},ga=i.createContext(void 0),qg=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:o}=of(),a=i.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return t.jsxs(ga.Provider,{value:a,children:[e,t.jsx(rf,{isActive:s,burstKey:n})]})},af={triggerFireworks:()=>{},dismissFireworks:()=>{}},Qg=()=>i.useContext(ga)??af,Ho="https://github.com/RyderAsKing/PiChamber/releases";function lf(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 cf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Wo(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function df(e,s){const n=e.split(".").map(o=>Number.parseInt(o,10)),r=s.split(".").map(o=>Number.parseInt(o,10));for(let o=0;o<3;o+=1){const a=Number.isFinite(n[o])?n[o]:0,l=Number.isFinite(r[o])?r[o]:0;if(a!==l)return l-a}return 0}function uf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const Yo=2e3,ff=600*1e3;async function hf(){try{const e=await Dt("/api/pi/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 pf(){try{return(await Dt("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function mf(e,s=Math.ceil(ff/Yo),n=Yo){for(let r=0;r<s;r++){try{const o=await Dt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(o.ok){const a=await o.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((o.status===401||o.status===403)&&await pf())return!0}catch{}await new Promise(o=>setTimeout(o,n))}return!1}const ba=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:o,progress:a,error:l,onDownload:c,onRestart:u,runtimeType:d="desktop"})=>{const[f,p]=Pe.useState(!1),[b,m]=Pe.useState("idle"),[g,h]=Pe.useState(null),v=n?.version?n.releaseUrl||`${Ho}/tag/v${n.version}`:Ho,x=n?.downloadUrl||v,I=a?.total?Math.round(a.downloaded/a.total*100):0,y=d==="web",k=d==="mobile",A=n?.updateCommand||"pichamber update";Pe.useEffect(()=>{e||(m("idle"),h(null))},[e]);const N=async()=>{(await As(A)).ok&&(p(!0),setTimeout(()=>p(!1),2e3))},j=Pe.useCallback(async M=>{await Ai(M)},[]),w=Pe.useCallback(async()=>{m("updating"),h(null);const M=await hf();if(!M.success){m("error"),h(M.error||"Update failed");return}M.autoRestart&&(m("restarting"),await new Promise(B=>setTimeout(B,2e3))),m("reconnecting"),await mf(n?.currentVersion)?window.location.reload():(m("error"),h("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),C=Pe.useCallback(()=>{j(x)},[j,x]),R=b!=="idle"&&b!=="error",P=Pe.useMemo(()=>{if(!n?.body)return null;const M=n.body.trim();if(!M)return null;const F=uf(M);return F.length===0?{kind:"raw",title:"What's new",content:Wo(M)}:{kind:"sections",title:"What's new",sections:[...F].sort((K,L)=>df(K.version,L.version)).map(K=>({version:K.version,dateLabel:lf(K.date),content:Wo(cf(K.raw)||M)}))}},[n?.body]);return t.jsx(Ht,{open:e,onOpenChange:R?void 0:s,children:t.jsxs(Wt,{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(ns,{className:"flex items-center gap-2.5",children:[t.jsx(D,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:b==="restarting"||b==="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:[y&&R&&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(D,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[b==="updating"&&"Installing update...",b==="restarting"&&"Server restarting...",b==="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&&!R&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(ws,{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:M=>{const B=M.target.closest("a");B&&B.href&&(M.preventDefault(),M.stopPropagation(),j(B.href))},children:t.jsx(Eo,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:P.sections.map(M=>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",M.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:M.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:F=>{const K=F.target.closest("a");K&&K.href&&(F.preventDefault(),F.stopPropagation(),j(K.href))},children:t.jsx(Eo,{content:M.content,disableLinkSafety:!0,enableFileReferences:!1})})]},M.version))})})}),y&&b==="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(D,{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:A}),t.jsx("button",{onClick:N,className:_("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",f&&"text-[var(--status-success)]"),title:f?"Copied!":"Copy command",children:f?t.jsx(D,{name:"check",className:"h-4 w-4"}):t.jsx(D,{name:"clipboard",className:"h-4 w-4"})})]})]}),!y&&!k&&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:[I,"%"]})]}),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:`${I}%`}})})]}),(l||g)&&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||g})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:v,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(D,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!y&&!k&&!o&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!y&&!k&&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(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!y&&!k&&o&&t.jsxs("button",{onClick:u,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(D,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),k&&t.jsxs(Te,{onClick:C,size:"default",children:[t.jsx(D,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),y&&!R&&t.jsxs("button",{onClick:w,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(D,{name:"download",className:"h-4 w-4"}),"Update Now"]}),y&&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(D,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},gf=i.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:o,className:a,iconClassName:l}){const c=i.useCallback(d=>{d.preventDefault(),d.stopPropagation(),!r&&!s&&n()},[s,r,n]),u=i.useCallback(d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:u,disabled:r,"aria-checked":s,"aria-label":o,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)})})}),mn=({children:e,className:s,contentClassName:n})=>{const[r,o]=i.useState(!1),a=i.useRef(null);return i.useEffect(()=>{if(!r)return;const l=c=>{const u=a.current;u&&c.target instanceof Node&&u.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(Ge,{open:r,onOpenChange:o,children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:_("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(D,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(He,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},Vg="w-full min-w-40 max-w-48",Jg="settings",bf="w-full min-w-40 max-w-48",Xg="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",xf="w-full max-w-[24rem]",Zg="min-w-0 flex-1",eb="flex w-full min-w-0 items-center gap-2",tb="typography-meta shrink-0 text-muted-foreground tabular-nums",xa="space-y-3.5",yf="space-y-1.5",sb="typography-settings-page-title text-muted-foreground",wf="typography-settings-section-title text-foreground",ya="typography-settings-group-title text-foreground",no="typography-settings-field-label text-foreground",vf="typography-settings-description text-muted-foreground",gn="typography-meta text-muted-foreground",nb="typography-meta font-medium text-foreground",rb="typography-settings-section-title text-foreground",Sf=({title:e,description:s,titleAccessory:n,info:r,headerAction:o,children:a,divider:l=!0,className:c,contentClassName:u,settingsItem:d})=>{const f=e!=null||s!=null||o!=null||r!=null;return t.jsxs("section",{"data-settings-item":d,className:_("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:wf,children:e}):e,n,r!=null?t.jsx(mn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:vf,children:s}):null]}),o?t.jsx("div",{className:"shrink-0",children:o}):null]}):null,t.jsx("div",{className:_(u),children:a})]})},ob=({children:e,className:s})=>t.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),jf=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:_(ya,s),children:e}),ib=({title:e,description:s,info:n,children:r,className:o,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:_("space-y-2",o),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(jf,{children:e}),n!=null?t.jsx(mn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:gn,children:s}):null]}):null,t.jsx("div",{className:_(a),children:r})]}),an=({label:e,description:s,info:n,descriptionPlacement:r="before",children:o,settingsItem:a,className:l,controlClassName:c})=>{const u=s!=null?t.jsx("p",{className:gn,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:no,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),r==="before"?u:null]}),t.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?u:null]})},ab=({label:e,description:s,info:n,children:r,settingsItem:o,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":o,className:_("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:no,children:e}),n!=null?t.jsx(mn,{children:n}):null]}),s!=null?t.jsx("p",{className:_(gn,"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})]}),lb=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:_("pt-4",s),children:e}),kf=({checked:e,onChange:s,label:n,description:r,disabled:o=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:u,info:d})=>{const f=()=>{o||s(!e)},p=r!=null;return t.jsxs("div",{"data-settings-item":l,className:_("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:b=>{(b.key===" "||b.key==="Enter")&&(b.preventDefault(),f())},children:[t.jsx(kr,{checked:e,onChange:s,disabled:o,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:no,children:n}),u,d!=null?t.jsx(mn,{children:d}):null]}),p?t.jsx("span",{className:gn,children:r}):null]})]})},cb=({selected:e,onSelect:s,label:n,description:r,ariaLabel:o,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(gf,{checked:e,onChange:s,disabled:a,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:_("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:gn,children:r}):null]})]}),db=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:_(yf,n),children:s});function ub({value:e,options:s,onChange:n,className:r,"aria-label":o}){return t.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Te,{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 Cf extends i.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(pc,{className:"w-full max-w-md",children:[t.jsx(mc,{className:"text-center",children:t.jsxs(gc,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(D,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(bc,{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(Te,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(D,{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 Af(e){return t.jsx(Cf,{...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 fb=({active:e=!0})=>{const s=Ne(n=>n.currentSessionId);return t.jsx(Af,{sessionId:s||void 0,children:t.jsx(xc,{active:e},s??"no-session")})};function Nf({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 wa=Pe.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:u,disabled:d,simple:f,endSlot:p,...b},m)=>{const g=Pe.useRef(null),h=Pe.useRef(null),[v,x]=Pe.useState(null),I=c??v,y=Pe.useCallback(A=>{const N=g.current;if(!N)return;h.current={startY:A.clientY,startHeight:N.getBoundingClientRect().height};const j=A.currentTarget;j.setPointerCapture(A.pointerId);const w=R=>{const P=h.current;if(!P)return;const M=P.startHeight+(R.clientY-P.startY),F=Math.max(82,M);u?u(F):x(F)},C=()=>{h.current=null,j.removeEventListener("pointermove",w),j.removeEventListener("pointerup",C),j.removeEventListener("pointercancel",C)};j.addEventListener("pointermove",w),j.addEventListener("pointerup",C),j.addEventListener("pointercancel",C),A.preventDefault()},[u]),k=Pe.useCallback(A=>{if(A.target.closest('textarea, button, [role="separator"]'))return;const j=g.current?.querySelector("textarea");j&&document.activeElement!==j&&(A.preventDefault(),j.focus())},[]);return f?t.jsx(ws,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,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:d,...b}):t.jsx("div",{ref:g,onPointerDown:k,style:I!==null?{height:`${I}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",!d&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],d&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:d,...b}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,t.jsx(Nf,{onResizeStart:y,ariaLabel:"Resize textarea"})]})]})})});wa.displayName="Textarea";const va=[{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"}],ln=Object.fromEntries(va.map(e=>[e.key,e.Icon])),$r="pichamber:project-actions-updated",Sa=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},ts=(e,s)=>`${Sa(e)}::${s}`,ja=({title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,children:l,className:c,contentClassName:u,divider:d=!0})=>t.jsx(Sf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:o,headerAction:a,divider:d,className:c,contentClassName:u,children:l}),Gr=e=>e.name.trim().length>0&&e.command.trim().length>0,If=e=>e.name.trim().length===0&&e.command.trim().length===0,Df=e=>!Gr(e)&&!If(e),Rf=(e,s)=>e.some(r=>s.has(r.id)&&!Gr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Gr)},Ef=450,Pf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Mf=()=>({id:Pf(),name:"",command:"",icon:"play"}),Tf=({projectRef:e})=>{const[s,n]=i.useState([]),[r,o]=i.useState(!1),[a,l]=i.useState(null),[c,u]=i.useState(new Set),d=i.useRef(!1);i.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const I=await Cr(e);if(x)return;n(I.actions),l(JSON.stringify({actions:I.actions})),u(new Set(I.actions.map(y=>y.id)))}catch{if(x)return;n([]),l(JSON.stringify({actions:[]})),u(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=i.useMemo(()=>Rf(s,c),[s,c]),p=i.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),b=a!==null&&f.canPersist&&p!==a,m=i.useCallback(async x=>await yc(e,{actions:x,primaryActionId:null})?(l(JSON.stringify({actions:x})),u(new Set(x.map(y=>y.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent($r,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);i.useEffect(()=>{if(!b||r||d.current)return;const x=window.setTimeout(()=>{d.current||(d.current=!0,(async()=>{try{await m(f.actions)}finally{d.current=!1}})())},Ef);return()=>{window.clearTimeout(x)}},[b,r,m,f.actions]);const g=i.useCallback(()=>{const x=Mf();n(I=>[...I,x])},[]),h=i.useCallback(x=>{n(I=>I.filter(y=>y.id!==x))},[]),v=i.useCallback((x,I)=>{n(y=>y.map(k=>k.id===x?I(k):k))},[]);return t.jsx(ja,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Te,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:g,children:[t.jsx(D,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):s.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:_("space-y-6",xf),children:s.map((x,I)=>{const y=x.icon||"play",k=ln[y]||"play",A=x.name.trim()||`Action ${I+1}`,N=Df(x);return t.jsxs("div",{className:xa,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:ya,children:A}),t.jsx(Te,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(x.id),"aria-label":`Delete ${A}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(an,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(Lt,{children:[t.jsx(Bt,{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(D,{name:k,className:"h-4 w-4"})})}),t.jsx(_t,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:va.map(j=>{const w=j.Icon,C=(x.icon||"play")===j.key;return t.jsx("button",{type:"button",onClick:()=>v(x.id,R=>({...R,icon:j.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",C&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:t.jsx(D,{name:w,className:"h-4 w-4"})},j.key)})})})]}),t.jsx(dn,{value:x.name,onChange:j=>v(x.id,w=>({...w,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(an,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(wa,{value:x.command,onChange:j=>v(x.id,w=>({...w,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),N?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(kf,{checked:x.autoOpenUrl===!0,onChange:j=>v(x.id,w=>({...w,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${A}`}),x.autoOpenUrl===!0?t.jsx(t.Fragment,{children:t.jsx(an,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(dn,{value:x.openUrl||"",onChange:j=>v(x.id,w=>({...w,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},Ff={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Of=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:a,onChange:l})=>{const c=Kt(w=>w.providers),u=Kt(w=>w.modelsMetadata),d=le(w=>w.hiddenModels),f=le(w=>w.isFavoriteModel),p=le(w=>w.toggleFavoriteModel),b=le(w=>w.reorderFavoriteModel),{favoriteModelsList:m,recentModelsList:g}=wc(),[h,v]=i.useState(!1),[x,I]=i.useState("");i.useEffect(()=>{h||I("")},[h]);const y=e?c.find(w=>w.id===e.providerId):void 0,k=e&&y?(Array.isArray(y.models)?y.models:[]).find(w=>w.id===e.modelId):void 0,A=e?vc(k,e.modelId):s,N=i.useMemo(()=>e?d.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):d,[d,e]),j=i.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),v(!1)},[l]);return t.jsxs(Lt,{modal:!1,open:h,onOpenChange:w=>{r||v(w)},children:[t.jsx(Bt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(Ni({size:"default"}),bf,"min-w-0",o),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Sc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:A})]}),t.jsx(D,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(_t,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(jc,{providers:c,favoriteModels:m,recentModels:g,modelsMetadata:u,searchQuery:x,onSearchQueryChange:I,onSelect:j,labels:{...Ff,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:N,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),v(!1)},disabled:r,autoFocus:!0,onEscape:()=>v(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>p(w.providerID,w.modelID),onReorderFavorite:(w,C)=>b(w.providerID,w.modelID,C.providerID,C.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},ar="w-full max-w-none",Lf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:a}=e,l=Kt(c=>c.loadProviders);return i.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx(ja,{title:"Project",divider:!1,children:t.jsxs("div",{className:xa,children:[t.jsx(an,{label:"Name",settingsItem:"projects.name",controlClassName:ar,children:t.jsx(dn,{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(an,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ar,children:t.jsx(Of,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ar,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Bf=e=>{const[s,n]=i.useState(""),[r,o]=i.useState(void 0);i.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const a=i.useMemo(()=>kc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=i.useCallback((d,f)=>{o(d&&f?`${d}/${f}`:void 0)},[]),u=i.useCallback(async()=>{if(!e)return null;const d=s.trim();return d?{label:d,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:u,project:e}},_f=450,Uf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:a}=e,l=i.useRef(!1);i.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const u=await a();if(u)try{await s(u)}catch{oe.error("Failed to save project settings")}}finally{l.current=!1}})())},_f);return()=>{window.clearTimeout(c)}},[o,n,r,s,a])},zf=({project:e,onIdentitySave:s})=>{const n=Bf(e),r=i.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=i.useCallback(async a=>{await s(a)},[s]);return Uf(n,o),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Lf,{form:n}),t.jsx(Tf,{projectRef:r})]})};function ro({...e}){return t.jsx(Ji,{...e})}function oo({...e}){return t.jsx(Xi,{...e})}function io({className:e,positionerClassName:s,children:n,style:r,...o}){return t.jsx(Zi,{children:t.jsx(ea,{className:_("app-region-no-drag z-50",s),children:t.jsx(ta,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Ii,e),...o,children:n})})})}function Us({className:e,...s}){return t.jsx(sa,{className:_(Di,e),...s})}function ka({className:e,...s}){return t.jsx(na,{className:_(Ri,e),...s})}const Cn=100;function hb(){const e=le(w=>w.isArchivePageOpen),s=le(w=>w.setArchivePageOpen),n=le(w=>w.setActiveMainTab),r=Ne(w=>w.setCurrentSession),o=Ne(w=>w.unarchiveSession),a=$s(w=>w.homeDirectory),l=Ar({archived:!0}),[c,u]=i.useState(""),[d,f]=i.useState(null),[p,b]=i.useState(Cn),m=c.trim().toLowerCase(),g=i.useMemo(()=>e?[...l].sort((w,C)=>(C.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),h=i.useMemo(()=>{const w=new Map;for(const C of g){const R=je(Bs(C))??"",P=w.get(R);if(P){P.sessions.push(C);continue}w.set(R,{directory:R,label:R?Gs(R,a)||R:"other projects",sessions:[C]})}return[...w.values()].sort((C,R)=>R.sessions.length-C.sessions.length)},[a,g]),v=i.useMemo(()=>m?g.filter(w=>(w.title??"").toLowerCase().includes(m)):d===null?g:h.find(w=>w.directory===d)?.sessions??[],[h,m,d,g]),x=v.slice(0,p),I=v.length-x.length,y=l.length,k=i.useCallback(w=>{f(w),b(Cn)},[]),A=i.useCallback(w=>{const C=je(Bs(w));r(w.id,C??void 0),n("chat"),s(!1)},[n,r,s]),N=i.useCallback(w=>{o(w.id).then(C=>{C?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const j=(w,C,R,P,M,F,B)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:M,title:F,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",B?"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:C}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:R})]}),B?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>ks.requestDelete({sessions:B,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 ${C}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return t.jsx(lu,{open:e,onOpenChange:s,children:t.jsxs(cu,{children:[t.jsx(du,{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(uu,{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(fu,{className:"sr-only",children:"Archived sessions"}),t.jsx(hu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(pu,{"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(D,{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:[j("__all__","All directories",y,d===null,()=>k(null)),h.map(w=>j(w.directory||"__none__",w.label,w.sessions.length,d===w.directory,()=>k(w.directory),w.directory||void 0,w.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(D,{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:w=>{u(w.target.value),b(Cn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:v.length===1?`${v.length} archived session`:`${v.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:[x.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"})}):x.map(w=>{const C=je(Bs(w))??"",R=C?Gs(C,a)||C: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:()=>A(w),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),A(w))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:ds(w)}),m&&R?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:C,children:R}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Xd(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),N(w)},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 ${ds(w)}`,children:t.jsx(D,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),ks.requestDelete({sessions:[w],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 ${ds(w)}`,children:t.jsx(D,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),I>0?t.jsx("button",{type:"button",onClick:()=>b(w=>w+Cn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const Ca=380,lr=8,$f=140;function Gf({open:e,onClose:s,anchorRef:n,closeOnWheel:r=!1}){const o=i.useRef(null),a=i.useRef(null),[l,c]=i.useState(e),[u,d]=i.useState(!1),[f,p]=i.useState(null),{enabled:b}=Qr();return i.useLayoutEffect(()=>{if(!e||!b||!l)return;const m=()=>{const v=n.current?.getBoundingClientRect(),x=a.current?.getBoundingClientRect();if(!v||!x){p(null);return}const I=v.left-x.left;p(Math.min(Math.max(I,lr),Math.max(lr,x.width-Ca-lr)))};m();const g=a.current;if(typeof ResizeObserver>"u"||!g)return;const h=new ResizeObserver(m);return h.observe(g),()=>h.disconnect()},[n,b,e,l]),i.useEffect(()=>{if(e){c(!0),d(!1);return}if(!l)return;d(!0);const m=window.setTimeout(()=>{c(!1),d(!1)},$f);return()=>window.clearTimeout(m)},[e,l]),i.useEffect(()=>{if(!e)return;const m=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[s,e]),i.useEffect(()=>{if(!e)return;const m=g=>{const h=g.target;if(!(h instanceof Node)){s();return}o.current?.contains(h)||n.current?.contains(h)||s()};return document.addEventListener("pointerdown",m,!0),r&&document.addEventListener("wheel",m,!0),()=>{document.removeEventListener("pointerdown",m,!0),r&&document.removeEventListener("wheel",m,!0)}},[n,r,s,e]),{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:u,anchorLeft:f,isPopover:b&&f!==null}}const qo=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},_n=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),An=({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(D,{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})]}),Kf=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:a,shouldRender:l,isExiting:c,anchorLeft:u,isPopover:d}=Gf({open:e,onClose:s,anchorRef:n,closeOnWheel:!0});return l?t.jsxs("div",{ref:a,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:o,role:"tooltip","aria-label":"Context usage for current conversation",className:_("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",d?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...d?{top:8,left:u??8,width:`min(${Ca}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(An,{iconNode:t.jsx(Ei,{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(An,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:_n(r.cacheRead)})}),t.jsx(An,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:_n(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(An,{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},Hf=i.memo(function({open:s,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:a}){const l=i.useRef(null),c=Cc(r??""),u=Kt(L=>L.providers),d=Kt(L=>L.currentProviderId),f=Kt(L=>L.currentModelId),p=Kt(L=>L.getCurrentModel()),b=Kt(L=>L.getModelMetadata);Kt(L=>L.modelsMetadata.size);const m=Ac(i.useCallback(L=>r?L.sessionModelSelections.get(r)??null:null,[r])),g=i.useMemo(()=>{for(let L=c.length-1;L>=0;L-=1){const T=c[L]?.info;if(T.role!=="user")continue;const U=T.model,H=U?.providerID??U?.providerId,ce=U?.modelID??U?.modelId,Q=typeof H=="string"&&H.trim().length>0?H:void 0,z=typeof ce=="string"&&ce.trim().length>0?ce:void 0;if(Q&&z)return{providerID:Q,modelID:z}}return null},[c]),h=i.useMemo(()=>{for(let L=c.length-1;L>=0;L-=1){const T=c[L];if(T?.info.role==="assistant"&&Po(T).total>0)return T}return null},[c]),v=g??(()=>{const L=h?.info.model,T=L?.providerID??L?.providerId,U=L?.modelID??L?.modelId;return T&&U?{providerID:T,modelID:U}:null})()??(m?{providerID:m.providerId,modelID:m.modelId}:null)??(d&&f?{providerID:d,modelID:f}:null),I=(v?u.find(L=>L.id===v.providerID):void 0)?.models.find(L=>L.id===v?.modelID),y=v?b(v.providerID,v.modelID):void 0,k=qo(I?.limit,"context")??y?.limit?.context??qo(p?.limit,"context")??0,A=h?Po(h):null,N=h?.info?.usage,j=N?Nc(N):A?.total??0,w=!a&&j>0&&k>0?Math.min(j/k*100,999):null,C=w!==null?`${_n(j)}/${_n(k)}`:null,R=w===null?"":w>=90?"text-[var(--status-error)]":w>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",P=A?.cacheRead??null,M=A?.cacheWrite??null,F=A?Ic({input:A.input,cache:{read:A.cacheRead,write:A.cacheWrite}}):{percent:0,hasInput:!1},B=F.hasInput?F.percent:null,K=w!==null&&C?{percentage:w,tokens:C,colorClass:R,cacheRead:P,cacheWrite:M,cacheHitPercent:B}: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(L=>!L),style:{touchAction:"manipulation"},children:t.jsx(Ei,{percentage:K?.percentage??0,size:20,className:"size-5 -rotate-90"})}),t.jsx(Kf,{open:s,onClose:()=>n(!1),anchorRef:l,contextDisplay:K})]})}),bn="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",Wf="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",Yf=i.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:o,className:a,Icon:l,iconClassName:c,pressed:u=!1}){return s?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":u,className:_(a??bn,u&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(He,{children:t.jsx("p",{children:n})})]}):null}),Aa=({variant:e="desktop"})=>{const s=Cs(f=>f.entries),[n,r]=i.useState(!1),o=i.useRef(null),a=i.useMemo(()=>[...s.values()].sort((f,p)=>p.startedAt-f.startedAt),[s]),l=a.filter(f=>f.state&&f.state.phase!=="failed").length,c=i.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),u=i.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(i.useEffect(()=>()=>c(),[c]),a.length===0)return null;const d=f=>{const p=f.receipt;if(!p)return;const b=Ne.getState();b.newSessionDraft.open?b.setNewSessionDraftTarget({directoryOverride:p.path,worktreeIntent:null}):b.openNewSessionDraft({directoryOverride:p.path}),Cs.getState().clearEntry(f.key),le.getState().setActiveMainTab("chat"),r(!1)};return t.jsxs(Lt,{open:n,onOpenChange:r,children:[t.jsx(Bt,{asChild:!0,children:t.jsxs("button",{type:"button",className:_(e==="desktop"?bn:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&u()},children:[l>0?t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner"}):t.jsx(D,{name:"task",className:"size-[18px]"}),t.jsx("span",{children:"Background tasks"})]})}),t.jsxs(_t,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:u,children:[t.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[t.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:l===1?"1 worktree is being created":`${l} worktrees are being created`})]}),t.jsx("div",{className:"divide-y divide-border",children:a.map(f=>t.jsx(qf,{entry:f,onOpen:()=>d(f)},f.key))})]})]})},qf=({entry:e,onOpen:s})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=!!(e.receipt&&!e.state),a=n?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return t.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[t.jsx("div",{className:"mt-0.5 shrink-0",children:r?t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner"}):n?t.jsx(D,{name:"alert",className:"size-4 text-[var(--status-error)]"}):t.jsx(D,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),t.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:n?e.state?.error:e.path??e.intent.sourceDirectory})]}),n?t.jsx(Te,{type:"button",variant:"ghost",size:"xs",onClick:()=>Cs.getState().dismissFailed(e.key),children:"Dismiss"}):null,o?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Te,{type:"button",size:"xs",onClick:s,children:"Open"}),t.jsx(Te,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Cs.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:t.jsx(D,{name:"close",className:"size-3.5"})})]}):null]})},Qo=600,Qf=1,Vf=e=>{const s=e?.directory;return typeof s=="string"&&s.trim()?s:null},Jf=({enabled:e=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:o})=>{const a=i.useRef(new Map),l=i.useRef([]),c=i.useRef(new Set),u=i.useRef(0),d=!1,f=i.useCallback(g=>`${g.directory}
12
+ ${g.sessionId}`,[]),p=i.useCallback(()=>{u.current+=1,l.current=[],a.current.forEach(g=>window.clearTimeout(g)),a.current.clear()},[]),b=i.useCallback(()=>{if(!(!e||d||typeof window>"u"))for(;c.current.size<Qf&&l.current.length>0;){const g=l.current.shift();if(!g)break;g.generation!==u.current||Ne.getState().currentSessionId===g.sessionId||Dc(g.sessionId,g.directory).renderable}},[e,d,o,f]),m=i.useCallback(g=>{const h=g?.id,v=Vf(g);if(!e||d||!h||!v||h===s||typeof window>"u")return;const x={sessionId:h,directory:v,generation:u.current};f(x)},[s,e,d,b,f]);i.useEffect(()=>{p()},[p,s,e,d]),i.useEffect(()=>{if(!e||d||!s||n.length===0)return;const g=window.setTimeout(()=>{const h=n.findIndex(v=>v.id===s);h<0||(m(n[h-1]),m(n[h+1]))},Qo);return()=>window.clearTimeout(g)},[s,e,d,m,n]),i.useEffect(()=>{if(!e||d||!s||r.length===0)return;const g=window.setTimeout(()=>{const h=r.findIndex(v=>v.id===s);h<0||(m(r[h-1]),m(r[h+1]))},Qo);return()=>window.clearTimeout(g)},[s,e,d,r,m]),i.useEffect(()=>p,[p])},Xf=e=>{const s=Ne(n=>n.currentSessionId);return Jf({...e,currentSessionId:s}),null},Zf=e=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:o,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:u,createFolder:d,addSessionToFolder:f}=e;i.useEffect(()=>{!n||o||!a||l||s.forEach(p=>{if(c.has(p.normalizedPath))return;const b=qi(p.normalizedPath),m=r.archivedSessionsByProject.get(p.id)??[],g=u[b]??[],h=new Map(g.map(v=>[v.name.toLowerCase(),v]));m.forEach(v=>{const x=Zd(v,p.normalizedPath),I=x.toLowerCase();let y=h.get(I);y||(y=d(b,x),h.set(I,y)),y.sessionIds.includes(v.id)||f(b,y.id,v.id)})})},[s,n,r,o,a,l,c,u,d,f])},eh=e=>({getOrderedGroups:i.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const a=new Map(r.map(d=>[d.id,d])),l=[];o.forEach(d=>{const f=a.get(d);f&&(l.push(f),a.delete(d))});const c=[],u=[];return r.forEach(d=>{a.has(d.id)&&(d.isArchivedBucket?u.push(d):c.push(d))}),[...c,...l,...u]},[e])}),th=e=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:a,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:u,hasSessionSearchQuery:d,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:b,foldersMap:m}=e,g=i.useRef(new Map),h=i.useMemo(()=>{const j=g.current,w=new Map;let C=0,R=0;const P=(F,B)=>F.length===B.length&&F.every((K,L)=>K===B[L]),M=s.map(F=>{const B=n(F.id),K=r(F.id),L=a.has(F.id)?!!a.get(F.id):c,T=l.get(F.id)??null,U=o.get(F.normalizedPath)??[],H=j.get(F.id);if(H&&H.project===F&&P(H.activeSessions,B)&&P(H.archivedSessions,K)&&H.rootBranch===T&&H.isRepo===L&&H.worktrees===U&&H.buildGroupedSessions===u)return C+=1,w.set(F.id,H),H.section;R+=1;const ce=Qi([...B,...K]),Q=u(ce,F.normalizedPath,U,T,L),z={project:F,groups:Q};return w.set(F.id,{project:F,activeSessions:B,archivedSessions:K,rootBranch:T,isRepo:L,worktrees:U,buildGroupedSessions:u,section:z}),z});return g.current=w,C>0&&Ot("ui.sidebar.project_section.reused",C),R>0&&Ot("ui.sidebar.project_section.rebuilt",R),M},[s,n,r,o,a,c,u,l]),v=i.useMemo(()=>h,[h]),x=i.useMemo(()=>{const j=new WeakMap;if(!d)return j;const w=C=>C.reduce((R,P)=>R+1+w(P.children),0);return v.forEach(C=>{C.groups.forEach(R=>{const P=p(R.sessions,f),M=w(P),F=b(R).includes(f),B=je(R.directory??null),L=(B?m[B]??[]:[]).filter(T=>T.name.toLowerCase().includes(f)).length;j.set(R,{filteredNodes:P,matchedSessionCount:M,folderNameMatchCount:L,groupMatches:F,hasMatch:F||M>0||L>0})})}),j},[d,v,p,f,b,m]),I=i.useMemo(()=>d?v.map(j=>({...j,groups:j.groups.filter(w=>x.get(w)?.hasMatch===!0)})).filter(j=>j.groups.length>0):v,[d,v,x]),y=d?I:v,k=i.useRef(new WeakMap),A=i.useMemo(()=>{const j=k.current;return y.map(w=>{const C=j.get(w);if(C&&C.query===f)return C.section;const R=w.groups.filter(T=>!T.isArchivedBucket),P=w.groups.filter(T=>T.isArchivedBucket),M=R.flatMap(T=>d?x.get(T)?.filteredNodes??[]:T.sessions),F=R.map(T=>({scopeKey:T.folderScopeKey??je(T.directory??null),directory:T.directory??null})).filter(T=>!!T.scopeKey),B=R.find(T=>T.isMain)??null,K={id:"flat",label:B?.label??"",branch:B?.branch??null,description:B?.description??null,isMain:!0,isArchivedBucket:!1,directory:B?.directory??w.project.normalizedPath,folderScopeKey:B?.folderScopeKey??w.project.normalizedPath,folderScopes:F,sessions:M};if(d){const T=R.map(U=>x.get(U)).filter(U=>!!U);x.set(K,{filteredNodes:M,matchedSessionCount:T.reduce((U,H)=>U+H.matchedSessionCount,0),folderNameMatchCount:T.reduce((U,H)=>U+H.folderNameMatchCount,0),groupMatches:T.some(U=>U.groupMatches),hasMatch:T.some(U=>U.hasMatch)})}const L={project:w.project,groups:[K,...P]};return j.set(w,{query:f,section:L}),L})},[x,d,f,y]),N=i.useMemo(()=>d?y.reduce((j,w)=>j+w.groups.reduce((C,R)=>{const P=x.get(R);if(!P)return C;const M=P.folderNameMatchCount+(P.groupMatches?1:0);return C+P.matchedSessionCount+M},0),0):0,[d,y,x]);return{projectSections:h,visibleProjectSections:v,groupSearchDataByGroup:x,searchableProjectSections:I,sectionsForRender:y,flatSectionsForRender:A,searchMatchCount:N}},sh=e=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:u,openNewSessionDraft:d,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,b=i.useMemo(()=>{const g=new Map,h=new Map,v=(x,I,y,k)=>{g.has(x)||g.set(x,new Map);const A=g.get(x);k.forEach(N=>{const j=je(N.session.directory??y??I);A.set(N.session.id,{directory:j}),h.has(x)||h.set(x,{id:N.session.id,directory:j}),N.children.length>0&&v(x,I,j,N.children)})};return s.forEach(x=>{x.groups.forEach(I=>{v(x.project.id,x.project.normalizedPath,I.directory,I.sessions)})}),{metaByProject:g,firstSessionByProject:h}},[s]),m=i.useRef(null);i.useLayoutEffect(()=>{if(!n)return;if(c){m.current=n;return}if(m.current===n)return;const g=s.find(N=>N.project.id===n);if(!g)return;m.current=n;const h=b.metaByProject.get(n);if(a&&h&&h.has(a)){o(N=>{if(N.get(n)===a)return N;const j=new Map(N);return j.set(n,a),j});return}const v=a?Array.from(b.metaByProject.entries()).some(([N,j])=>N!==n&&j.has(a)):!1;if(a&&h&&!v)return;if(!h||h.size===0){f("chat"),u&&p(!1),d({selectedProjectId:g.project.id,directoryOverride:g.project.normalizedPath});return}const x=r.get(n),I=x&&h.has(x)?x:null,y=b.firstSessionByProject.get(n)?.id??null,k=I??y;if(!k||k===a)return;const A=h.get(k)?.directory??null;l(k,A,{keepPanelOpen:!0})},[n,r,a,l,c,u,d,s,b,f,p,o]),i.useEffect(()=>{if(!n||!a)return;const g=b.metaByProject.get(n);!g||!g.has(a)||o(h=>{if(h.get(n)===a)return h;const v=new Map(h);return v.set(n,a),v})},[n,a,b,o])},nh=({initialActiveSessionByProject:e,persistActiveSessionByProject:s,...n})=>{const r=Ne(c=>c.currentSessionId),o=Ne(c=>!!c.newSessionDraft?.open),[a,l]=i.useState(()=>new Map(e));return sh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),i.useEffect(()=>{s(a)},[a,s]),null},Vo=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],rh=e=>{let s=5381;for(let n=0;n<e.length;n+=1)s=s*33^e.charCodeAt(n);return s>>>0},oh=(e,s,n)=>(n.get(e)??0)>0?e:s.get(e)??null,Na=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const s=rh(e.trim())%Vo.length;return Vo[s]},ih=(e,s)=>{const n=Na(e);return n?s?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Jo=e=>!!e.time?.archived,ah=e=>{const s=i.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=i.useCallback(a=>{const l=je(a.directory??null)??"";return`${ds(a)} ${l}`.toLowerCase()},[]),r=i.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const d=r(c.children,l);return d.length===0?[]:[{...c,children:d}]}):a,[n]),o=i.useCallback((a,l,c=[],u,d)=>{const f=je(l??null),p=Qi(a).sort((j,w)=>Vr(j,w,e.pinnedSessionIds,e.sessionOrderRanks)),b=new Map(p.map(j=>[j.id,j])),m=new Map,g=new Map;p.forEach(j=>{const w=j.parentID??null,C=w?b.get(w):null,R=C&&Jo(C)===Jo(j)?w:null;m.set(j.id,R),R&&g.set(R,(g.get(R)??0)+1)});const h=c.map(j=>({worktree:j,directory:je(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,w)=>w.directory.length-j.directory.length),v=(j,w)=>w===j||w.startsWith(`${j}/`),x=j=>{const w=je(j.directory??null);return w?h.find(C=>v(C.directory,w))?.worktree??null:null},I=(j,w)=>{const C=oh(j.id,m,g);return{session:j,children:[],worktree:w,forkColorId:C}},y=[],k=new Map,A=[];for(const j of h)k.set(j.directory,[]);p.forEach(j=>{const w=x(j),C=I(j,w);j.time?.archived?A.push(C):w?k.get(je(w.path)??"")?.push(C):y.push(C)});const N=[{id:"root",label:d&&u&&u!=="HEAD"?`project root: ${u}`:"project root",branch:u??null,description:f?Oo(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:y}];for(const{worktree:j,directory:w}of h)N.push({id:`worktree:${w}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:Oo(w,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:j,directory:w,folderScopeKey:w,sessions:k.get(w)??[]});return A.length>0&&N.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?qi(f):null,sessions:A}),N},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},lh=({mobileVariant:e,isTablet:s})=>!e&&!s,ch=({enabled:e=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{i.useEffect(()=>{if(!e||!s||typeof window>"u")return;const a=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(a)},[e,s,r]),i.useEffect(()=>{if(!e||!s||typeof document>"u")return;const a=l=>{o.current&&(o.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e,s,n,o])},dh=e=>{const[s,n]=i.useState(null),r=i.useRef(null);i.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=i.useCallback((y,k,A)=>{Rr("navigation.session_select"),le.getState().closeMainSurfaces();const N=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},j=A?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),y===Ne.getState().currentSessionId){e.allowReselect&&j&&e.onSessionSelected?.(y),N();return}Rr("navigation.session_state_set"),e.setCurrentSession(y,k??null),j&&e.onSessionSelected?.(y),N()},[e]),a=i.useCallback((y,k)=>{e.setEditingId(y),e.setEditTitle(k)},[e]),l=i.useCallback(async y=>{if(!e.editingId)return;const k=(y??e.editTitle).trim();k&&await e.updateSessionTitle(e.editingId,k),e.setEditingId(null),e.setEditTitle("")},[e]),c=i.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),u=i.useCallback(async(y,k)=>{try{return(await As(y)).ok?(n(k),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),d=i.useCallback(async y=>{const k=await e.shareSession(y.id);if(!k?.share?.url){oe.error("Unable to share session");return}const A=await u(k.share.url,y.id);oe[A?"success":"warning"]("Session shared",{description:A?"Share link copied to clipboard.":"Failed to copy URL"})},[e,u]),f=i.useCallback((y,k)=>{u(y,k).then(A=>{A||oe.error("Failed to copy URL")})},[u]),p=i.useCallback(y=>{As(y).then(k=>{if(k.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),b=i.useCallback(async y=>{await e.unshareSession(y)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),m=i.useCallback(y=>{const k=[],A=N=>{(e.childrenMap.get(N)??[]).forEach(w=>{k.push(w),A(w.id)})};return A(y),k},[e.childrenMap]),g=i.useCallback((y,k)=>k?y:y.filter(A=>!A.time?.archived),[]),h=i.useCallback(async(y,k,A)=>{const N=k?.archivedBucket===!0||k?.hardDelete===!0,j=A?.descendantIds??g(m(y.id),N).map(P=>P.id);if(j.length===0){(N?await e.deleteSession(y.id):await e.archiveSession(y.id))?oe.success(N?"Session deleted":"Session archived"):oe.error(N?"Failed to delete session":"Failed to archive session");return}const w=[y.id,...j];if(N){const{deletedIds:P,failedIds:M}=await e.deleteSessions(w);if(M.length===0){const F=P.length;oe.success(F===1?`Deleted ${F} session`:`Deleted ${F} sessions`)}else oe.error("Failed to delete session");return}const{archivedIds:C,failedIds:R}=await e.archiveSessions(w);C.length>0&&oe.success(C.length===1?`Archived ${C.length} session`:`Archived ${C.length} sessions`),R.length>0&&oe.error(R.length===1?`Failed to archive ${R.length} session`:`Failed to archive ${R.length} sessions`)},[e,m,g]),v=i.useCallback((y,k)=>{const A=k?.archivedBucket===!0||k?.hardDelete===!0,N=g(m(y.id),A).map(j=>j.id);if(!e.showDeletionDialog||k?.skipConfirm===!0){h(y,k,{descendantIds:N});return}e.setDeleteSessionConfirm({session:y,descendantCount:N.length,descendantIds:N,archivedBucket:A})},[e,m,h,g]),x=i.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:y,archivedBucket:k,descendantIds:A}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(y,{archivedBucket:k},{descendantIds:A})},[e,h]),I=i.useCallback(async y=>{await e.unarchiveSession(y.id)?oe.success("Session restored"):oe.error("Failed to restore session")},[e]);return{copiedSessionId:s,handleSessionSelect:o,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:d,handleCopyShareUrl:f,handleCopySessionId:p,handleUnshareSession:b,handleDeleteSession:v,handleRestoreSession:I,confirmDeleteSession:x}},uh=e=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:a,setCollapsedProjects:l}=e,c=i.useRef(null),u=i.useRef(null),d=i.useCallback(()=>{const p=u.current;if(u.current=null,c.current=null,!p)return;const{projects:b}=pt.getState(),m=b.map(g=>({...g,sidebarCollapsed:p.has(g.id)}));Zr({projects:m}).catch(()=>{})},[]),f=i.useCallback(p=>{typeof window>"u"||(u.current=p,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{d()},700))},[d]);return i.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,u.current=null},[]),i.useEffect(()=>{try{const p=s.getItem(n.sessionExpanded);if(p){const m=JSON.parse(p);Array.isArray(m)&&a(new Set(m.filter(g=>typeof g=="string")))}const b=s.getItem(n.projectCollapse);if(b){const m=JSON.parse(b);Array.isArray(m)&&l(new Set(m.filter(g=>typeof g=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),i.useEffect(()=>{try{const p=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(p))}catch{}},[r,n.groupOrder,s]),i.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:f}},fh=3;let Un=0;const Ia=[],hh=()=>Un<fh?(Un+=1,Promise.resolve()):new Promise(e=>{Ia.push(e)}),ph=()=>{const e=Ia.shift();if(e){e();return}Un=Math.max(0,Un-1)},mh=async e=>{await hh();try{return await e()}finally{ph()}},gh=5*6e4,bh=e=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:a}=e,{git:l}=Ys(),c=Pi(p=>p.ensureStatus);i.useEffect(()=>{if(!n||!l||s.length===0){o(new Map);return}s.forEach(p=>{mh(()=>c(p.normalizedPath,l))})},[n,s,l,c,o]),i.useEffect(()=>{if(!n)return;const p=new Map;s.forEach(b=>{p.set(b.id,r.get(b.normalizedPath)?.isGitRepo??null)}),o(p)},[n,s,r,o]);const u=i.useMemo(()=>s.map(p=>{const b=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${b}`}).join("|"),[s,r]),d=i.useRef(new Map),f=i.useRef(new Map);i.useEffect(()=>{if(!n)return;let p=!1;const b=setTimeout(()=>{(async()=>{const g=new Set(s.map(y=>y.id));for(const y of d.current.keys())g.has(y)||(d.current.delete(y),f.current.delete(y));const h=Date.now();if(s.filter(y=>{const k=r.get(y.normalizedPath);if(k?.isGitRepo===!1)return d.current.delete(y.id),f.current.delete(y.id),!1;if(k?.isGitRepo!==!0||k.branch===null)return!1;const A=k.branch.trim(),N=`${y.normalizedPath}\0${A}`,j=d.current.get(y.id);if(j===N){const w=f.current.get(y.id);return w&&(w.at=h),!1}return!(j!==void 0&&h-(f.current.get(y.id)?.at??0)<gh)}).length===0)return;const x=[];if(s.forEach(y=>{const k=r.get(y.normalizedPath)?.branch?.trim()??"",A=`${y.normalizedPath}\0${k}`;k&&x.push({id:y.id,inputKey:A,branch:k})}),p||x.length===0)return;const I=Date.now();a(y=>{const k=new Map(y);return x.forEach(({id:A,branch:N})=>{N&&k.set(A,N)}),k}),x.forEach(({id:y,inputKey:k,branch:A})=>{d.current.set(y,k),A&&f.current.set(y,{branch:A,at:I})})})()},150);return()=>{p=!0,clearTimeout(b)}},[n,s,u,r,a])},xh=e=>{const{ownership:s}=e,n=i.useCallback(o=>s.sessionsByProject.get(o)??[],[s]),r=i.useCallback(o=>s.archivedSessionsByProject.get(o)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},yh=e=>{if(e.runtimeKey!==Wn()||!e.directory||e.directory==="global"||!e.sessionId)return;const s=Md(e.sessionId,e.directory,e.runtimeKey);s&&Td.getState().clearQueue(s),lt.getState().removeSessionEverywhere(e.runtimeKey,e.sessionId),Nr.getState().clearPinnedSession(e.runtimeKey,e.directory,e.sessionId);const n=Rc(e.runtimeKey,e.directory,e.sessionId);n&&Ec(n,!0),Pc.getState().clearStashedAttachmentsForSession(e)},wh=e=>{const s=new Map;for(const n of e){const r=Bs(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},vh=(e,s)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{s.has(o)||n.push(r)}),n},Sh=e=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=i.useRef(null);i.useEffect(()=>{if(!s||!n)return;const a=Wn(),l=wh(r),c=o.current?.runtimeKey===a?o.current.identities:null;for(const u of vh(c,l))yh({runtimeKey:a,...u});o.current={runtimeKey:a,identities:l}},[s,n,r])},jh=(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,Xo=(e,s,n)=>{jh(e.get(s),n)&&e.set(s,n)},Da=e=>{const s=e;return je(s.directory)??je(s.project?.worktree)},kh=(e,s,n)=>{if(e.time?.archived)return!0;const r=Da(e);if(!r)return n?.allowUnknownDirectory??!0;if(Hn(r,n?.homeDirectory))return!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const a of s)if(je(a)?.toLowerCase()===o)return!0;return!1},Ch=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)},Ah=(e,s,n,r=[])=>{const o=new Map,a=new Map;for(const m of s){const g=je(m.normalizedPath);if(!g)continue;const h=a.get(g);(!h||m.id.localeCompare(h.id)<0)&&a.set(g,m),Xo(o,g,{projectId:m.id,projectRoot:g,scopeDirectory:g,kind:"project"})}if(n)for(const[m,g]of n){const h=je(m),v=h?a.get(h):void 0;if(!(!v||!h))for(const x of g||[]){const I=je(x?.path);I&&Xo(o,I,{projectId:v.id,projectRoot:h,scopeDirectory:I,kind:"worktree"})}}const l=new Map,c=new Map,u=new Map,d=new Map,f=new Map,p=m=>{if(!m)return null;if(l.has(m))return l.get(m)??null;const g=[];let h=m,v=null;for(;h;){if(l.has(h)){v=l.get(h)??null;break}if(g.push(h),v=o.get(h)??null,v)break;h=Ch(h)}for(const x of g)l.set(x,v);return v},b=(m,g,h)=>{for(const v of m){const x=Da(v);if(Hn(x))continue;const I=p(x);if(!I)continue;c.set(v.id,I);const y=g.get(I.projectId);if(y?y.push(v):g.set(I.projectId,[v]),!h)continue;const k=h.get(I.scopeDirectory);k?k.add(v.id):h.set(I.scopeDirectory,new Set([v.id]))}};return b(e,u,f),b(r,d),{bySessionId:c,sessionsByProject:u,archivedSessionsByProject:d,sessionsByScope:f,directoryResolutions:l.size}};function Ra({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(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Nh=({folder:e,displayName:s,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:u,renderSessionNode:d,getRenderExtras:f,groupDirectory:p,projectId:b,mobileVariant:m=!1,alwaysShowActions:g=m,isRenaming:h=!1,renameDraft:v="",onRenameDraftChange:x,onRenameSave:I,onRenameCancel:y,droppableRef:k,isDropTarget:A=!1,onNewSession:N,depth:j=0,hideActions:w=!1,archivedBucket:C=!1})=>{const[R,P]=i.useState(!1),[M,F]=i.useState(""),B=i.useRef(null),K=h||R,L=h?v:M,T=i.useCallback(()=>{F(e.name),P(!0)},[e.name]),U=i.useCallback(()=>{const z=L.trim();z&&z!==e.name&&c(z),h&&I&&I(),P(!1),F("")},[L,e.name,h,c,I]),H=i.useCallback(()=>{h&&y&&y(),P(!1),F("")},[h,y]),ce=i.useCallback(z=>{h&&x?x(z):F(z)},[h,x]);i.useEffect(()=>{if(!h)return;const z=()=>{const de=B.current;de&&(de.focus(),de.select())},Ie=requestAnimationFrame(z),O=window.setTimeout(z,0);return()=>{cancelAnimationFrame(Ie),window.clearTimeout(O)}},[h]);const Q=o?"folder":"folder-open";return t.jsxs("div",{className:"oc-folder",children:[t.jsxs("div",{ref:k,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",A&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:K?void 0:z=>{z.currentTarget.blur(),l()},role:K?void 0:"button",tabIndex:K?void 0:0,onKeyDown:K?void 0:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),l())},"aria-label":o?`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]",C?g?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":g?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[t.jsx(D,{name:Q,className:_(En,A?"text-primary":"text-muted-foreground")}),K?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(),U()},children:[t.jsx("input",{ref:B,value:L,onChange:z=>ce(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(),H();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(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),H()},onPointerDown:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("span",{className:_(Vi,A?"text-primary":"text-muted-foreground"),children:s??e.name})}),t.jsx(He,{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(Ra,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?t.jsx(D,{name:"arrow-right-s",className:_(En,"text-muted-foreground")}):t.jsx(D,{name:"arrow-down-s",className:_(En,"text-muted-foreground")})]})]}),!K&&(!w||C)?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",g?"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:[!C&&N?t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),N()},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(D,{name:"add",className:"size-4"})}):null,C?null:t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),T()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:t.jsx(D,{name:"pencil-ai",className:"size-4"})}),t.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),u()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":C?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:t.jsx(D,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:t.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(z=>t.jsx(i.Fragment,{children:d(z,0,p??null,b??null,C,void 0,"project",f?.(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"})]})]})},Ih=i.memo(Nh),Dh=({sessionId:e,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:o,listeners:a,setNodeRef:l,isDragging:c}=bu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:s,sessionTitle:n}}),u=i.useCallback(d=>{d.stopPropagation(),a?.onPointerDown&&a.onPointerDown(d)},[a]);return t.jsx("div",{ref:l,...o,onPointerDown:u,className:c?"opacity-30":void 0,children:r})},Rh=({folderId:e,children:s})=>{const{setNodeRef:n,isOver:r}=xu({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return t.jsx(t.Fragment,{children:s(n,r)})},Eh=({scopeKey:e,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const o=ra(Lr(mu,{activationConstraint:{distance:8}})),[a,l]=i.useState(null),[c,u]=i.useState("Session"),[d,f]=i.useState(null),[p,b]=i.useState(null);if(!e)return t.jsx(t.Fragment,{children:r});const m=g=>{l(null),f(null),b(null);const{active:h,over:v}=g;if(!v)return;const x=h.data.current,I=v.data.current;x?.type==="session"&&x.sessionId&&I?.type==="folder"&&I.folderId&&n(x.sessionId,I.folderId)};return t.jsxs(oa,{sensors:o,collisionDetection:ia,onDragStart:g=>{const h=g.active.data.current;if(h?.type==="session"&&h.sessionId){l(h.sessionId),u(h.sessionTitle??"Session");const v=g.active.rect.current.initial?.width,x=g.active.rect.current.initial?.height;f(typeof v=="number"?v:null),b(typeof x=="number"?x:null)}},onDragCancel:()=>{l(null),f(null),b(null)},onDragEnd:m,children:[r,t.jsx(gu,{children:a&&s?t.jsxs("div",{style:{width:d?`${d}px`:"auto",height:p?`${p}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[t.jsx(D,{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})]})},js=({icon:e,children:s,onClick:n,className:r,mobileVariant:o=!1})=>t.jsxs("button",{type:"button",onClick:n,className:_(o?eu:tu,r),children:[t.jsx(D,{name:e,className:_(fn(o),"text-muted-foreground")}),t.jsx("span",{className:_(hn(o),"flex-1 text-muted-foreground"),children:s})]}),Zo=(e,s,n)=>{if(!s)return;const r=o=>{let a=o.session.id===s;for(const l of o.children)a=r(l)||a;return a&&n.add(o.session.id),a};for(const o of e)r(o)},ss=(e,s)=>{if(!s)return!1;if(e.session.id===s)return!0;for(const n of e.children)if(ss(n,s))return!0;return!1},Ph=(e,s,n)=>{const r=new Map,o=a=>{const l=Bs(a.session)??n;if(l){const c=r.get(l)??[];c.push(a.session.id),r.set(l,c)}if(!(a===e&&s))for(const c of a.children)o(c)};return o(e),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},Mh=(e,s)=>{const n=new Set(e);return e.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let a=r.session.parentID??null;for(;a&&!o.has(a);){if(n.has(a)&&s.has(a))return!1;o.add(a),a=s.get(a)?.session?.parentID??null}return!0})},ei=new WeakMap;let ti=1;const Th=e=>{const s=ei.get(e);if(s!==void 0)return s;const n=ti;return ti+=1,ei.set(e,n),n},Kr=e=>e.children.length===0?"":e.children.map(n=>{const r=Th(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Kr(n)}`}).join("|"),Ea=(e,s,n,r,o,a)=>{const l=Wn(),c=(u,d)=>{if(u.session.id!==d.session.id||u.children.length!==d.children.length)return!0;const f=u.session.directory??o,p=d.session.directory??a,b=Mo(l,f??"",u.session.id),m=Mo(l,p??"",d.session.id);return(b?n.has(b):!1)!==(m?r.has(m):!1)?!0:u.children.some((g,h)=>c(g,d.children[h]))};return c(e,s)},zn=(e,s,n,r)=>{if(!s)return null;const o=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${o}:${c.session.id}`===s)return a=c.session.id,!0;for(const d of c.children)if(l(d))return!0;return!1};return e.forEach(c=>l(c)),a},Pa=(e,s)=>"",Fh=hs(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),Ma=e=>null,ao=(e,s)=>e==="active"||s==="active"?"active":e==="unread"||s==="unread"?"unread":null,Ta=(e,s,n,r)=>{if(s.has(e.session.id))return"active";let o=null;const a=!!e.session.parentID;n.has(e.session.id)&&(r||!a)&&(o="unread");for(const l of e.children)if(o=ao(o,Ta(l,s,n,r)),o==="active")return o;return o},Fa=(e,s,n,r)=>{let o=null;for(const a of e)if(o=ao(o,Ta(a,s,n,r)),o==="active")return o;return o},Oh=50,Lh=28;function Bh({visibleSessions:e,shouldVirtualize:s,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:a,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:u}){const d=i.useRef(null),[f,p]=i.useState(null),[b,m]=i.useState(0),[,g]=i.useState(0);i.useEffect(()=>{if(!s)return;const x=d.current;if(!x||typeof ResizeObserver>"u")return;const I=new ResizeObserver(()=>g(y=>y+1));return I.observe(x),()=>I.disconnect()},[s]),i.useLayoutEffect(()=>{if(!s){f!==null&&p(null),b!==0&&m(0);return}const x=d.current;if(!x)return;let I=f;const y=r?.current??null;if(y&&y.contains(x)){if(I=y,I!==f){p(I);return}}else if(!I||!I.contains(x)){let A=x.parentElement;for(;A;){const N=window.getComputedStyle(A);if(N.overflowY==="auto"||N.overflowY==="scroll"){I=A;break}A=A.parentElement}if(I!==f){p(I);return}}if(!I)return;const k=x.getBoundingClientRect().top-I.getBoundingClientRect().top+I.scrollTop;m(A=>Math.abs(A-k)<1?A:k)},[f,b,r,s]);const h=s&&f!==null,v=vu({count:e.length,enabled:h,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>Lh,overscan:n?20:8,scrollMargin:b,getItemKey:x=>e[x]?.session.id??x});return t.jsx("div",{ref:d,children:s?t.jsx("div",{style:{height:v.getTotalSize(),position:"relative"},children:v.getVirtualItems().map(x=>{const I=e[x.index];return I?t.jsx("div",{"data-index":x.index,ref:v.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${x.start-b}px)`},children:c(I,0,o,a,l,void 0,"project",u(I))},I.session.id):null})}):e.map(x=>t.jsx(i.Fragment,{children:c(x,0,o,a,l,void 0,"project",u(x))},x.session.id))})}const Tn=(e,s)=>{if(!s)return e;const n=e.toLowerCase(),r=s.toLowerCase(),o=r.length;if(o===0)return e;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(e.slice(l,c));const u=e.slice(c,c+o);a.push(t.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:u},`${c}-${u}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&a.push(e.slice(l)),a.length>0?a:e};function _h({group:e,groupKey:s,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:a,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:u,groupPrSummary:d,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:b,allGroupSessions:m,projectId:g,activeProjectId:h,setActiveProjectIdOnly:v,setActiveMainTab:x,mobileVariant:I,setSessionSwitcherOpen:y,openNewSessionDraft:k}){return 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:()=>r(s),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),r(s))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[t.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.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:e.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(D,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",a?"hidden":"group-hover/gh:hidden")}),t.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(D,{name:"arrow-right-s",className:"size-4"}):t.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 flex-1 truncate",children:Tn(e.label,o)}),f]}):!e.isMain||e.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(D,{name:"git-branch",className:_("size-4 shrink-0",!u&&"text-muted-foreground",a?"hidden":"group-hover/gh:hidden"),style:u?{color:u}:void 0}),t.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",a?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?t.jsx(D,{name:"arrow-right-s",className:"size-4"}):t.jsx(D,{name:"arrow-down-s",className:"size-4"})})]}),t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Tn(e.label,o)}),f,d?t.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:u?{color:u}:void 0,children:["#",d.number]}):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:Tn(e.label,o)}),f]})}),p&&b?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?t.jsx(D,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):t.jsx(D,{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:b.label})]}):null]})}),e.isArchivedBucket&&m.length>0?t.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),ks.requestDelete({sessions:m,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 ${e.label}`,children:t.jsx(D,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?t.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",a?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),g&&g!==h&&v(g),x("chat"),I&&y(!1),k({selectedProjectId:g,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:t.jsx(D,{name:"add",className:"h-4 w-4"})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"New draft session"})})]})}):null]})}const Nn=(e,s)=>s?e.sessions.some(n=>ss(n,s)):!1,Uh=(e,s,n)=>e.sessions.some(r=>Ea(r,r,s,n,e.directory,e.directory)),zh=(e,s,n)=>{const r=o=>{const a=o.session.id;return s.get(a)!==n.get(a)?!0:o.children.some(r)};return e.sessions.some(r)},si=(e,s,n)=>{const r=o=>s.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},$h=(e,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return e.sessions.some(n)},Gh=(e,s,n)=>{const r=e.isArchivedBucket?"archived":"active",o=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(o)};return e.sessions.some(o)},Kh=(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&&Uh(s.group,e.pinnedSessionIds,s.pinnedSessionIds)||e.expandedParents!==s.expandedParents&&Gh(s.group,e.expandedParents,s.expandedParents)||e.sessionOrderIndex!==s.sessionOrderIndex&&zh(s.group,e.sessionOrderIndex,s.sessionOrderIndex)||e.editingId!==s.editingId&&(Nn(e.group,e.editingId)||Nn(s.group,s.editingId))||e.editTitle!==s.editTitle&&(Nn(e.group,e.editingId)||Nn(s.group,s.editingId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=zn(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=zn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==s.activeActivitySessionIds&&si(s.group,e.activeActivitySessionIds,s.activeActivitySessionIds)||e.unreadActivitySessionIds!==s.unreadActivitySessionIds&&si(s.group,e.unreadActivitySessionIds,s.unreadActivitySessionIds)||e.notifyOnSubtasks!==s.notifyOnSubtasks&&$h(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 Hh({group:e,isCollapsed:s}){const n=Mi(),r=i.useMemo(()=>{const b=e.folderScopes?.map(m=>je(m.directory))??[je(e.directory??null)];return[...new Set(b.filter(m=>!!m))]},[e.directory,e.folderScopes]);i.useSyncExternalStore(i.useCallback(b=>r.length>0?n.subscribeBootstrap(b):()=>{},[r.length,n]),i.useCallback(()=>r.map(b=>`${b}\0${n.getBootstrapState(b)??""}\0${n.getBootstrapFailure(b)??""}`).join(""),[r,n]),i.useCallback(()=>"",[]));const o=r.some(b=>{const m=n.getBootstrapState(b);return m==="queued"||m==="running"}),a=r.find(b=>n.getBootstrapState(b)==="failed")??null,l=a?n.getBootstrapFailure(a):void 0,c=l==="os-permission"&&Jr(),[u,d]=i.useState(!1),f=i.useCallback(()=>{a&&n.requestBootstrap({directory:a,priority:s?"visible":"expanded",reason:e.isMain?"project-expanded":"worktree-expanded",force:!0})},[n,a,e.isMain,s]),p=i.useCallback(async()=>{if(!(!a||!c||u)){d(!0);try{(await Xr(a)).success&&f()}finally{d(!1)}}},[c,a,u,f]);return{bootstrapLoading:o,failedBootstrapDirectory:a,bootstrapFailure:l,canGrantBootstrapAccess:c,isRequestingBootstrapAccess:u,retryFailedBootstrap:f,grantFailedBootstrapAccess:p}}function Wh({group:e,sourceGroupNodes:s,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:a,unreadActivitySessionIds:l,notifyOnSubtasks:c,collectGroupSessions:u}){const d=lt(N=>N.foldersMap),f=e.folderScopeKey??je(e.directory??null),p=i.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),b=i.useMemo(()=>p.flatMap(({scopeKey:N,directory:j})=>(d[N]??[]).map(w=>({folder:w,scopeKey:N,scopeDirectory:j}))),[p,d]),m=i.useMemo(()=>{const N=new Map,j=w=>{w.forEach(C=>{N.set(C.session.id,C),C.children.length>0&&j(C.children)})};return j(s),N},[s]),g=i.useMemo(()=>b.map(({folder:N,scopeKey:j,scopeDirectory:w})=>{const C=Mh(N.sessionIds,m).sort(o);return{folder:N,scopeKey:j,scopeDirectory:w,nodes:C}}),[b,m,o]),h=i.useMemo(()=>{const N=new Map(g.map(R=>[R.folder.id,R])),j=new Map;for(const{folder:R}of g){if(!R.parentId)continue;const P=j.get(R.parentId);P?P.push(R.id):j.set(R.parentId,[R.id])}const w=new Map,C=R=>{const P=w.get(R);if(P!==void 0)return P;const M=N.get(R);if(!M)return w.set(R,!1),!1;const F=j.get(R)??[];if(e.isArchivedBucket&&M.nodes.length===0){const L=F.some(T=>C(T));return w.set(R,L),L}if(!n||M.folder.name.toLowerCase().includes(r)||M.nodes.length>0)return w.set(R,!0),!0;const K=F.some(L=>C(L));return w.set(R,K),K};return g.filter(({folder:R})=>C(R.id))},[g,e.isArchivedBucket,n,r]),v=i.useMemo(()=>new Set(h.flatMap(N=>N.folder.sessionIds)),[h]),x=i.useMemo(()=>s.filter(N=>!v.has(N.session.id)),[s,v]),I=i.useMemo(()=>h.filter(({folder:N})=>!N.parentId),[h]),y=i.useMemo(()=>{const N=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const w=N.get(j.folder.parentId)??[];w.push(j),N.set(j.folder.parentId,w)}),N},[h]),k=i.useMemo(()=>{const N=new Map(h.map(C=>[C.folder.id,C])),j=new Map,w=(C,R)=>{const P=j.get(C);if(P!==void 0)return P;if(R.has(C))return null;R.add(C);const M=N.get(C);let F=M?Fa(M.nodes,a,l,c):null;for(const B of y.get(C)??[])if(F=ao(F,w(B.folder.id,R)),F==="active")break;return j.set(C,F),F};return h.forEach(({folder:C})=>w(C.id,new Set)),j},[a,h,y,c,l]),A=i.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const N=new Map,j=new Map;for(const{folder:C}of h){if(!C.parentId)continue;const R=j.get(C.parentId)??[];R.push(C.id),j.set(C.parentId,R)}const w=(C,R)=>{if(R.has(C))return[];R.add(C);const P=h.find(({folder:B})=>B.id===C),M=P?u(P.nodes):[],F=j.get(C)??[];for(const B of F)M.push(...w(B,R));return M};for(const{folder:C}of h)N.set(C.id,w(C.id,new Set));return N},[h,u,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:p,allFoldersForGroup:h,rootFolders:I,ungroupedSessions:x,folderActivityStateById:k,folderSessionsForDeleteById:A}}function Yh(e){const{group:s,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:u,collapsedGroups:d,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:b,renameFolder:m,deleteFolder:g,showDeletionDialog:h,setDeleteFolderConfirm:v,renderSessionNode:x,showMoreGroupSessions:I,resetGroupSessionLimit:y,mobileVariant:k,alwaysShowActions:A,activeProjectId:N,setActiveProjectIdOnly:j,setActiveMainTab:w,setSessionSwitcherOpen:C,openNewSessionDraft:R,addSessionToFolder:P,createFolderAndStartRename:M,renamingFolderId:F,renameFolderDraft:B,setRenameFolderDraft:K,setRenamingFolderId:L,pinnedSessionIds:T,expandedParents:U,sessionOrderIndex:H,editingId:ce,openSidebarMenuKey:Q,activeActivitySessionIds:z,unreadActivitySessionIds:Ie,notifyOnSubtasks:O,onToggleCollapsedGroup:de,dragHandleProps:he,compactBodyPadding:$=!1,scrollContainerRef:G}=e,J=i.useCallback((ve,Be)=>{const pe=H.get(ve.session.id),Le=H.get(Be.session.id);if(pe!==void 0||Le!==void 0){if(pe===void 0)return 1;if(Le===void 0)return-1;if(pe!==Le)return pe-Le}return Vr(ve.session,Be.session,T,Ti)},[T,H]),se=a?c.get(s):null,fe=a?!1:d.has(n);i.useMemo(()=>{if(s.isMain||s.isArchivedBucket||o)return null;const ve=je(s.directory??null),Be=s.branch?.trim();return ve&&Be?Pa():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,o]);const ke=Ma(),Me=void 0,{bootstrapLoading:Re,failedBootstrapDirectory:Z,bootstrapFailure:ue,canGrantBootstrapAccess:q,isRequestingBootstrapAccess:ye,retryFailedBootstrap:_e,grantFailedBootstrapAccess:Y}=Hh({group:s,isCollapsed:fe}),ae=f?10:5,ne=Math.max(ae,u??ae),me=a?se?.groupMatches===!0:!1,De=a,Ce=i.useMemo(()=>[...De?se?.filteredNodes??[]:s.sessions].sort(J),[J,s.sessions,se?.filteredNodes,De]),we=i.useCallback(ve=>{const Be=[],pe=Le=>{Le.forEach(ze=>{Be.push(ze.session),ze.children.length>0&&pe(ze.children)})};return pe(ve),Be},[]),{folderScopeKey:X,folderScopes:xe,allFoldersForGroup:ee,rootFolders:Ae,ungroupedSessions:Ue,folderActivityStateById:Ye,folderSessionsForDeleteById:Se}=Wh({group:s,sourceGroupNodes:Ce,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,compareSessionNodes:J,activeActivitySessionIds:z,unreadActivitySessionIds:Ie,notifyOnSubtasks:O,collectGroupSessions:we}),te="project",Oe=i.useMemo(()=>{const ve=new Set;return Zo(Ce,ce,ve),ee.forEach(({nodes:Be})=>{Zo(Be,ce,ve)}),ve},[Ce,ee,ce]),Fe=i.useMemo(()=>{if(!Q)return null;const ve=zn(Ce,Q,te,!!s.isArchivedBucket);if(ve)return ve;for(const{nodes:Be}of ee){const pe=zn(Be,Q,te,!!s.isArchivedBucket);if(pe)return pe}return null},[Q,Ce,ee,s.isArchivedBucket]),mt=i.useCallback(ve=>{const Be=new WeakMap,pe=Le=>{Be.set(Le,Kr(Le));for(const ze of Le.children)pe(ze)};return ve.forEach(pe),Be},[]),nt=i.useMemo(()=>mt(Ce),[mt,Ce]),Qe=i.useMemo(()=>{const ve=new WeakMap;return ee.forEach(({nodes:Be})=>{Be.forEach(pe=>ve.set(pe,Kr(pe)))}),ve},[ee]),rt=i.useCallback(ve=>nt.get(ve)??Qe.get(ve)??"",[nt,Qe]),xt=i.useCallback(ve=>({subtreeContainsEditing:Oe,menuOpenSessionId:Fe,nodeStructureKey:rt(ve)}),[Oe,Fe,rt]),Xe=Ue.length,dt=s.isArchivedBucket||a?Ue:Ue.slice(0,ne),gt=Xe-dt.length,Ve=!s.isArchivedBucket&&!a&&Xe>ae&&gt===0,Ze=s.isArchivedBucket===!0&&!a&&dt.length>=Oh,kt=s.isArchivedBucket?"archived":"active",Je=Ze&&dt.some(ve=>{if(ve.children.length===0)return!1;const Be=`project:${kt}:${ve.session.id}`;return U.has(Be)}),Yt=i.useMemo(()=>we(Ce),[we,Ce]);if(a&&!me&&Ae.length===0&&Ue.length===0)return null;const Rt=!s.isMain&&!!s.branch,Et=s.branch&&su(s.branch,s.label)?{label:s.branch,color:null}:null,ut=fe?Fa(Ce,z,Ie,O):null,Pt=ut?t.jsx(Ra,{state:ut,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,ps=(ve,Be)=>{const{folder:pe,scopeKey:Le,scopeDirectory:ze,nodes:ot}=ve,ft=Se.get(pe.id)??[],ht=a?!1:p.has(pe.id);return t.jsx(Rh,{folderId:pe.id,children:(Ct,ms)=>t.jsx(Ih,{folder:pe,displayName:Be,sessions:ot,isCollapsed:ht,collapsedActivityState:ht?Ye.get(pe.id)??null:null,onToggle:()=>b(pe.id),onRename:et=>{m(Le,pe.id,et)},onDelete:()=>{if(s.isArchivedBucket){ks.requestDelete({sessions:ft,mode:"session"});return}if(!h){g(Le,pe.id);return}const et=ee.filter(({folder:Vt})=>Vt.parentId===pe.id).length,gs=ot.length;v({scopeKey:Le,folderId:pe.id,folderName:pe.name,subFolderCount:et,sessionCount:gs})},renderSessionNode:x,getRenderExtras:rt?et=>({subtreeContainsEditing:Oe,menuOpenSessionId:Fe,nodeStructureKey:rt(et),childRenderExtrasFor:xt}):void 0,groupDirectory:ze??s.directory,projectId:r,mobileVariant:k,alwaysShowActions:A,isRenaming:F===pe.id,renameDraft:F===pe.id?B:void 0,onRenameDraftChange:et=>K(et),onRenameSave:()=>{const et=B.trim();et&&m(Le,pe.id,et),L(null),K("")},onRenameCancel:()=>{L(null),K("")},droppableRef:Ct,isDropTarget:ms,depth:0,onNewSession:()=>{r&&r!==N&&j(r),w("chat"),k&&C(!1),R({selectedProjectId:r,directoryOverride:ze??s.directory,targetFolderId:pe.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},pe.id)},qt=()=>{const ve=new Map;for(const Le of ee){const ze=Le.folder.parentId;if(!ze)continue;const ot=ve.get(ze);ot?ot.push(Le):ve.set(ze,[Le])}const Be=[],pe=(Le,ze)=>{const ot=ze?`${ze} / ${Le.folder.name}`:Le.folder.name;Be.push(ps(Le,ot)),!(!a&&p.has(Le.folder.id))&&(ve.get(Le.folder.id)??[]).forEach(ht=>pe(ht,ot))};return Ae.forEach(Le=>pe(Le,"")),Be},Qt=A?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",yt=Z?t.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[ue==="os-permission"?"Folder access is required.":"Could not refresh sessions.",q?t.jsx(Te,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:ye,onClick:()=>{Y()},children:"Grant access"}):null,t.jsx(Te,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:_e,children:"Try again"})]}):null,rs=t.jsxs(Eh,{scopeKey:xe[0]?.scopeKey??X,hasFolders:ee.length>0,onSessionDroppedOnFolder:(ve,Be)=>{const pe=ee.find(({folder:ze})=>ze.id===Be);if(!pe)return;const Le=lt.getState();for(const{scopeKey:ze}of xe)ze!==pe.scopeKey&&Le.getSessionFolderId(ze,ve)&&Le.removeSessionFromFolder(ze,ve);P(pe.scopeKey,Be,ve)},children:[qt(),s.isArchivedBucket?t.jsx(Bh,{visibleSessions:dt,shouldVirtualize:Ze,hasExpandedParent:Je,scrollContainerRef:G,groupDirectory:s.directory,projectId:r,isArchivedBucket:s.isArchivedBucket===!0,renderSessionNode:x,getRenderExtras:ve=>({subtreeContainsEditing:Oe,menuOpenSessionId:Fe,nodeStructureKey:rt(ve),childRenderExtrasFor:xt})}):dt.map(ve=>t.jsx(i.Fragment,{children:x(ve,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:Oe,menuOpenSessionId:Fe,nodeStructureKey:rt(ve),childRenderExtrasFor:xt})},ve.session.id)),Xe===0&&ee.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."}):Re?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(D,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):yt?t.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:yt}):t.jsx(js,{icon:"chat-new",onClick:()=>{R({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,Xe>0&&yt?t.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:yt}):null,gt>0?t.jsx(js,{icon:"arrow-down-s",onClick:()=>I(n,dt.length),children:gt===1?"Show 1 more session":`Show ${gt} more sessions`}):null,Ve?t.jsx(js,{icon:"arrow-up-s",onClick:()=>y(n),children:"Show fewer sessions"}):null]});return o?t.jsx("div",{className:"oc-group",children:t.jsx("div",{className:"oc-group-body",children:rs})}):t.jsxs("div",{className:"oc-group",children:[t.jsx(_h,{group:s,groupKey:n,isCollapsed:fe,onToggleCollapsedGroup:de,normalizedSessionSearchQuery:l,alwaysShowActions:A,groupHeaderRightPadding:Qt,dragHandleProps:he,groupPrColor:Me,groupPrSummary:ke,groupActivityIndicator:Pt,showBranchSubtitle:Rt,statusLine:Et,allGroupSessions:Yt,projectId:r,activeProjectId:N,setActiveProjectIdOnly:j,setActiveMainTab:w,mobileVariant:k,setSessionSwitcherOpen:C,openNewSessionDraft:R}),fe?null:t.jsx("div",{className:"oc-group-body",children:rs})]})}const qh=i.memo(Yh,Kh);function Qh(e){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:u,headerActionButtonClass:d,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:b,sessionSearchQuery:m,setSessionSearchQuery:g,hasSessionSearchQuery:h,searchMatchCount:v,selectionModeEnabled:x,onToggleSelectionMode:I,mobileVariant:y=!1}=e;if(s)return null;const k=_(d,"text-muted-foreground hover:text-foreground",!y&&"hover:bg-transparent");return t.jsx("div",{className:_("select-none flex-shrink-0",y?"px-2":"px-3 py-1"),children:t.jsxs("div",{className:_("flex flex-col",y?"gap-0":"h-auto min-h-8 gap-1"),children:[t.jsxs("div",{className:_("flex items-center justify-between",y?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[t.jsxs("div",{className:_("flex min-w-0 items-center",y?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":y?"true":void 0,children:[o?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:k,"aria-label":"Settings",children:t.jsx(D,{name:"settings-3",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}):null,!y&&a?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:a,className:k,"aria-label":l?`Instances: ${l}`:"Instances",children:t.jsx(D,{name:"server",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:l||"Instances"})})]}):null,c?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:c,className:k,"aria-label":"Update",children:t.jsx(D,{name:"download",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Update"})})]}):null,y?null:t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:k,"aria-label":"Add project",children:t.jsx(D,{name:"folder-add",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Add project"})})]}),y?null:t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:r,className:k,"aria-label":"Archive",children:t.jsx(D,{name:"archive",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Archive"})})]})]}),t.jsxs("div",{className:_("flex shrink-0 items-center",y?"gap-1":"gap-1.5"),children:[t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>p(A=>!A),className:k,"aria-label":"Search sessions","aria-expanded":f,children:t.jsx(D,{name:"search",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:"Search sessions"})})]}),t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:I,className:_(k,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:t.jsx(D,{name:"checkbox-multiple",className:u})})}),t.jsx(He,{side:"bottom",sideOffset:4,children:t.jsx("p",{children:x?"Exit selection":"Select sessions"})})]})]})]}),f?t.jsxs("div",{className:_(y?"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:h?t.jsx("span",{children:v===1?`${v} match`:`${v} matches`}):t.jsx("span",{})}),t.jsxs("div",{className:"relative",children:[t.jsx(D,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{ref:b,value:m,onChange:A=>g(A.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:A=>{A.key==="Escape"&&(A.stopPropagation(),h?g(""):p(!1))}}),m.length>0?t.jsx("button",{type:"button",onClick:()=>g(""),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(D,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function Vh(e){const s=le(o=>o.toggleSidebar),n=le(o=>o.shortcutOverrides),r=eo(Ln("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, ${Bo})`}}),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, ${Bo})))`}}),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(D,{name:"chat-new",className:_(En,"text-current")}),t.jsx("span",{className:Vi,children:"New session"})]}),e.showSidebarToggle?t.jsxs(Ge,{children:[t.jsx(Ke,{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(D,{name:"layout-left",className:"size-4"})})}),t.jsx(He,{children:t.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const Oa=500,Jh=({projectId:e,worktree:s,isSelected:n,hasActive:r,onSelect:o,onClose:a,mobileVariant:l=!1})=>{const[c,u]=i.useState(!1),d=i.useRef(null),f=s.branch||(s.detached?"Detached HEAD":s.name),p=i.useCallback(()=>{d.current!==null&&(window.clearTimeout(d.current),d.current=null)},[]);i.useEffect(()=>()=>p(),[p]);const b=i.useCallback(()=>{p(),d.current=window.setTimeout(()=>{d.current=null,u(!0)},Oa)},[p]);return t.jsxs(ro,{open:c,onOpenChange:u,children:[t.jsxs(oo,{render:t.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:b,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_($n(l,n),"pl-6"),"aria-pressed":n,title:s.path}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx(D,{name:"git-branch",className:_(fn(l),"text-muted-foreground")}),t.jsx("span",{className:hn(l),children:f})]}),t.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),t.jsx(io,{className:"min-w-[160px]",children:t.jsxs(Us,{disabled:!a,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>a?.(e,s),className:"text-destructive focus:text-destructive",children:[t.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close worktree"})]})})]})},$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"),Xh=({project:e,label:s,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:a,isExpanded:l,canDrag:c,onSelect:u,onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:b,setNodeRef:m,transform:g,transition:h,isDragging:v}=ku({id:e.id,disabled:!c}),[x,I]=i.useState(!1),y=i.useRef(null),k=i.useCallback(()=>{y.current!==null&&(window.clearTimeout(y.current),y.current=null)},[]);i.useEffect(()=>()=>k(),[k]);const A=i.useCallback(()=>{k(),y.current=window.setTimeout(()=>{y.current=null,I(!0)},Oa)},[k]);return t.jsx("div",{ref:m,style:{transform:Cu.Translate.toString(g),transition:h},className:_(v&&"opacity-60"),children:t.jsxs(ro,{open:x,onOpenChange:I,children:[t.jsxs(oo,{render:t.jsx("button",{type:"button",onClick:()=>{x||u()},onTouchStart:A,onTouchMove:k,onTouchEnd:k,onTouchCancel:k,style:{touchAction:"manipulation"},className:$n(p,n),"aria-pressed":n}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[t.jsx("span",{className:_("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?b:{},children:t.jsx(D,{name:"folder",className:_(fn(p),"text-muted-foreground")})}),t.jsx("span",{className:hn(p),children:s})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?t.jsx(Ds,{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(D,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?t.jsx(D,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),t.jsxs(io,{className:"min-w-[160px]",children:[t.jsxs(Us,{onClick:()=>d(e.id),children:[t.jsx(D,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Edit folder"})]}),t.jsx(ka,{}),t.jsxs(Us,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[t.jsx(D,{name:"close",className:"mr-2 h-3.5 w-3.5"}),t.jsx("span",{children:"Close folder"})]})]})]})})},Zh=({projects:e,selectedProjectId:s,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:a,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:u,onOpenProjectEditDialog:d,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:b,homeDirectory:m,className:g,mobileVariant:h=!1})=>{const v=s===null,x=pt(A=>A.reorderProjects),I=e.length>1,y=ra(Lr(wu,{activationConstraint:{distance:8}}),Lr(yu,{activationConstraint:{delay:200,tolerance:6}})),k=i.useCallback(A=>{const{active:N,over:j}=A;if(!j||N.id===j.id)return;const w=pt.getState().projects,C=w.findIndex(P=>P.id===N.id),R=w.findIndex(P=>P.id===j.id);C<0||R<0||x(C,R)},[x]);return t.jsxs("div",{className:_("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",g),children:[t.jsx("button",{type:"button",onClick:()=>a(null),className:$n(h,v),"aria-pressed":v,children:t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx(D,{name:"chat-history",className:fn(h)}),t.jsx("span",{className:hn(h),children:"All sessions"})]})}),t.jsx(oa,{sensors:y,collisionDetection:ia,onDragEnd:k,children:t.jsx(Su,{items:e.map(A=>A.id),strategy:ju,children:e.map(A=>{const N=s===A.id,j=N&&!n,w=r.get(A.normalizedPath)??[],C=Yn(A.label?.trim()||Gs(A.normalizedPath,m)||A.normalizedPath),R=b?.get(A.id),P=je(A.normalizedPath)?.toLowerCase()??"",M=P?R?.has(P)??!1:!1,F=(R?.size??0)>0,B=p?.(A.id)??!1,K=b?N?M:F:B;return t.jsxs(i.Fragment,{children:[t.jsx(Xh,{project:A,label:C,isSelected:j,hasActive:K,hasWorktrees:w.length>0,worktreeError:o.get(A.normalizedPath),isExpanded:N,canDrag:I,onSelect:()=>a(A.id),onOpenProjectEditDialog:d,onRemoveProject:f,mobileVariant:h}),N?w.map(L=>{const T=n===L.path,U=je(L.path)?.toLowerCase()??"",H=U?R?.has(U)??!1:!1,ce=b?H:!1;return t.jsx(Jh,{projectId:A.id,worktree:L,isSelected:T,hasActive:ce,onSelect:()=>l?.(A.id,L.path),onClose:c,mobileVariant:h},L.path)}):null]},A.id)})})}),t.jsxs("button",{type:"button",onClick:u,className:$n(h,!1),children:[t.jsx(D,{name:"add",className:fn(h)}),t.jsx("span",{className:hn(h),children:"Add folder"})]})]})},cr="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 ep({onOpenSettings:e,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:a=!0}){return!o&&!a?null:t.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?t.jsxs(t.Fragment,{children:[t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:e,className:cr,"aria-label":"Settings",children:t.jsx(D,{name:"settings-3",className:"h-4.5 w-4.5"})})}),t.jsx(He,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Settings"})})]}),t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,className:cr,"aria-label":"Shortcuts",children:t.jsx(D,{name:"command",className:"h-4.5 w-4.5"})})}),t.jsx(He,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Shortcuts"})})]}),t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:cr,"aria-label":"About PiChamber",children:t.jsx(D,{name:"information",className:"h-4.5 w-4.5"})})}),t.jsx(He,{side:"top",sideOffset:4,children:t.jsx("p",{children:"About PiChamber"})})]})]}):null,a?t.jsx(Te,{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 tp=(e,s)=>Yn(e.label?.trim()||Gs(e.normalizedPath,s)||e.normalizedPath);function sp(e){Ot("ui.sidebar_projects_list.render");const s=i.useRef(new Map),n=i.useRef(e.getOrderedGroups);n.current!==e.getOrderedGroups&&(n.current=e.getOrderedGroups,s.current.clear());const r=(p,b)=>{const m=s.current,g=m.get(p);if(g&&g.groups===b)return g.ordered;const h=e.getOrderedGroups(p,b);if(m.set(p,{groups:b,ordered:h}),m.size>256){const v=m.keys().next().value;v!==void 0&&m.delete(v)}return h},o=i.useRef(null),a=i.useMemo(()=>{if(!e.isAllFoldersView)return[];const p=[],b=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const m of b){const g=tp(m.project,e.homeDirectory);for(const h of m.groups)if(!h.isArchivedBucket)for(const v of h.sessions){const x=!!e.pinnedSessionIds?.has(v.session.id),I=v.session.time?.updated||v.session.time?.created||0;p.push({node:v,project:m.project,projectLabel:g,isPinned:x,timestamp:I,globalSession:m===e.allFoldersOnlySection})}}return p.sort((m,g)=>m.isPinned!==g.isPinned?m.isPinned?-1:1:g.timestamp-m.timestamp),p},[e.allFoldersOnlySection,e.isAllFoldersView,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[l,c]=i.useState(30);i.useEffect(()=>{c(30)},[e.hasSessionSearchQuery]);const u=a.slice(0,l),d=a.length-u.length;if(e.sharedSessionsOnly)return t.jsx(ws,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const f=e.isAllFoldersView&&!!e.allFoldersOnlySection;return e.projectSections.length===0&&!f?t.jsx(ws,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:t.jsxs("div",{className:"space-y-1 px-3",children:[e.topContent,e.emptyState]})}):e.sectionsForRender.length===0&&!f?t.jsx(ws,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),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(ws,{ref:o,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-32"),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 p=e.sectionsForRender.find(h=>h.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!p)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const b=p.groups.find(h=>h.isMain&&h.sessions.length>0)??p.groups.find(h=>h.sessions.length>0)??p.groups.find(h=>h.isMain)??p.groups[0];if(!b)return t.jsx(js,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath}),children:"New session"});const m=p.groups.find(h=>h.isArchivedBucket);return[b,...m&&m.id!==b.id?[m]:[]].map(h=>{const v=`${p.project.id}:${h.id}`,x=h.id===b.id;return t.jsx(i.Fragment,{children:e.renderGroupSessions(h,v,p.project.id,x,null,!0,o)},v)})})()}):e.isAllFoldersView&&e.renderSessionNode?t.jsx("div",{children:a.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:t.jsxs(t.Fragment,{children:[u.map(({node:p,project:b,projectLabel:m,globalSession:g})=>{const h=p.session.directory??b.normalizedPath;return t.jsx(i.Fragment,{children:e.renderSessionNode(p,0,h,b.id,!1,{projectLabel:m,showFolderLabel:!0,globalSession:g},"project")},p.session.id)}),d>0?t.jsx(js,{icon:"arrow-down-s",onClick:()=>c(p=>p+30),children:d===1?"Show 1 more session":`Show ${d} more sessions`}):null,l>30&&a.length>30?t.jsx(js,{icon:"arrow-up-s",onClick:()=>c(30),children:"Show fewer sessions"}):null]})}):t.jsx("div",{children:e.sectionsForRender.map(p=>{const b=p.project.id,m=r(b,p.groups),g=m.find(v=>v.isMain)??null,h=g?m.filter(v=>v.id!==g.id):m;return t.jsxs("div",{children:[g?e.renderGroupSessions(g,`${b}:${g.id}`,b,!0,null,void 0,o):null,h.map(v=>{const x=`${b}:${v.id}`,I=m.length===1;return t.jsx(i.Fragment,{children:e.renderGroupSessions(v,x,b,I,null,void 0,o)},v.id)})]},b)})})]})})})}const np=i.memo(sp);let Hr=!1;const Wr=new Set;let ni=!1;function rp(){for(const e of Wr)e()}function lo(e){Hr!==e&&(Hr=e,rp())}function op(e){e.key==="Shift"&&lo(!0)}function ip(e){e.key==="Shift"&&lo(!1)}function ap(){lo(!1)}function lp(){ni||typeof window>"u"||(ni=!0,window.addEventListener("keydown",op),window.addEventListener("keyup",ip),window.addEventListener("blur",ap))}function cp(e){return lp(),Wr.add(e),()=>{Wr.delete(e)}}function dp(){return Hr}function up(){return!1}function fp(){return Pe.useSyncExternalStore(cp,dp,up)}const hp=i.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:u}){const d=fp(),f=d?n:s,p=b=>{if(d||b.shiftKey){u(b);return}c(b)};return t.jsxs(Ge,{children:[t.jsx(Ke,{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",d?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:a,onMouseDown:l,onClick:p,onKeyDown:b=>b.stopPropagation(),children:t.jsx(D,{name:d?"delete-bin":"archive",className:o})})}),t.jsx(He,{side:"left",sideOffset:8,children:f})]})}),pp=i.memo(function({open:s,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:a,onExport:l}){return t.jsx(Ht,{open:s,onOpenChange:n,children:t.jsxs(Wt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(ns,{children:"Export Markdown"}),t.jsx(fs,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} sub-agent tasks. Include them in the export?`})]}),t.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:o,onChange:c=>a(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),t.jsxs(Is,{children:[t.jsx(Te,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),t.jsx(Te,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function mp(e,s){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:a,archivedBucket:l,isElectron:c,pendingRenameRef:u,handleCopySessionId:d,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:b,handleDeleteSession:m,handleRestoreSession:g}=e,{Item:h,Separator:v}=s;return t.jsxs(t.Fragment,{children:[t.jsxs(h,{onClick:()=>{u.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),t.jsxs(h,{onClick:()=>d(n.id),className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),t.jsxs(h,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[a?t.jsx(D,{name:"unpin",className:"mr-1 h-4 w-4"}):t.jsx(D,{name:"pushpin",className:"mr-1 h-4 w-4"}),a?"Unpin session":"Pin session"]}),t.jsxs(h,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?t.jsxs(h,{disabled:!o,onClick:b,className:"[&>svg]:mr-1",children:[t.jsx(D,{name:"window",className:"mr-1 h-4 w-4"}),t.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,t.jsx(v,{}),l?null:t.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>m(n,{archivedBucket:l}),children:[t.jsx(D,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?t.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>g(n),children:[t.jsx(D,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,t.jsxs(h,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>m(n,{archivedBucket:l,hardDelete:!0}),children:[t.jsx(D,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function gp(e){const{renamingFolderId:s,editingIdRef:n}=e;return t.jsx(Zi,{children:t.jsx(ea,{className:"app-region-no-drag z-50",children:t.jsx(ta,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(s||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Ii,"min-w-[180px]"),children:mp(e,{Item:({className:r,...o})=>t.jsx(sa,{className:_(Di,r),...o}),Separator:({className:r,...o})=>t.jsx(na,{className:_(Ri,r),...o})})})})})}const dr=new WeakMap,bp=e=>{if(typeof window>"u")return;const s=e.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;dr.get(n)?.();const r=s.getBoundingClientRect().top;let o=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,dr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},u=()=>{if(a||!s.isConnected||!n.isConnected){c();return}const d=s.getBoundingClientRect().top-r;if(Math.abs(d)>.5&&(n.scrollTop+=d,Ot("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(u)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),dr.set(n,c),l=window.requestAnimationFrame(u)};function xp(e){if(typeof e!="number"||!Number.isFinite(e))return"";const s=new Date(e);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleString("en-US",{month:"short"}),r=s.getDate(),o=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${a}:${l}`}function yp(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 wp(e){const s=e.info.role==="user"?"User":"Assistant",n=xp(e.info.time?.created),r=yp(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${s}**
13
+
14
+ *${o}*`:`**${s}**`}function vp(e){return e.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function La(e){const s=wp(e),n=vp(e.parts).trim();return n?`${s}
15
+
16
+ ${n}`:""}function Ba(e,s){const n="#".repeat(Math.min(s+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
17
+
18
+ ---
19
+
20
+ `,a=e.records.map(La).filter(Boolean).join(`
21
+
22
+ ---
23
+
24
+ `),l=[o+a];for(const c of e.children)l.push(Ba(c,s+1));return l.join(`
25
+
26
+ ---
27
+
28
+ `)}function _a(e,s,n){const r=s?.trim()||"Session",o=new Date().toISOString().split("T")[0],a=`# ${r}
29
+
30
+ *Exported on ${o}*
31
+
32
+ ---
33
+
34
+ `,l=e.map(La).filter(Boolean).join(`
35
+
36
+ ---
37
+
38
+ `);let c=a+l;if(n&&n.length>0){const u=n.map(d=>Ba(d,1)).join(`
39
+
40
+ ---
41
+
42
+ `);c+=`
43
+
44
+ ---
45
+
46
+ `+u}return c}function Ua(e,s){const n=new Blob([e],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=s,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(r)}async function za(e,s){const n=await Fd(s,e);return n||null}async function Sp(e){const s=es()?.files;if(s?.revealPath)try{return!!(await s.revealPath(e))?.success}catch{return!1}return await Od(e)?!0:Gi(e)}function jp(){return Ld()}function $a(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const Gn=e=>{const s=[],n=r=>{r.children.forEach(o=>{s.push(o.session.id),n(o)})};return n(e),s};function kp(e,s){const n=Fi(),[r,o]=i.useState(!1),[a,l]=i.useState(!0),c=e.session,u=i.useMemo(()=>Gn(e).length,[e]),d=i.useCallback(async m=>{const g=[];let h=0;for(const v of m)try{if(!s)throw new Error("Session directory is required for export");const x=Ir(n.getState(),v.session.id).list,I=v.session.title||"Untitled Sub-agent",y=typeof v.session.agent=="string"?v.session.agent:void 0,k=await d(v.children);h+=k.skipped,g.push({title:I,agent:y,records:x,children:k.children})}catch{h+=Gn(v).length+1}return{children:g,skipped:h}},[n,s]),f=i.useCallback(m=>{m<=0||oe.warning(m===1?`Exported session, but skipped ${m} sub-agent task that could not be loaded.`:`Exported session, but skipped ${m} sub-agent tasks that could not be loaded.`)},[]),p=i.useCallback(async m=>{if(!s){oe.error("Nothing to export");return}const g=Ir(n.getState(),c.id).list;if(g.length===0){oe.error("Nothing to export");return}let h,v=0;if(m&&e.children.length>0){const k=await d(e.children);h=k.children,v=k.skipped}const x=_a(g,c.title??null,h),I=$a(c.title??null),y=await za(x,I);if(y){oe.success("Session exported",{action:{label:jp(),onClick:()=>{Sp(y).then(k=>{k||oe.error("Failed to reveal path")})}}}),f(v);return}Ua(x,I),oe.success("Session exported"),f(v)},[d,n,e.children,c.id,c.title,s,f]),b=i.useCallback(async()=>{if(e.children.length>0){l(!0),o(!0);return}await p(!1)},[p,e.children.length]);return{exportDialogOpen:r,setExportDialogOpen:o,exportIncludeSubtasks:a,setExportIncludeSubtasks:l,descendantCount:u,handleExportSession:b,doExportSession:p}}const Cp=(e,s)=>{if(!s)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const a=s.get(o);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},ct=hs()((e,s)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{s().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{s().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,o)=>{const a=s(),l=new Set(a.selectedIds);let c=a.scopeKey,u=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(l.clear(),c=r,u=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const b of f)l.delete(b);u===n&&(u=null)}else{for(const b of f)l.add(b);u=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:u})},setRange:(n,r,o,a,l)=>{const c=s();if(o.length===0)return;const u=n&&o.includes(n)?n:o[0],d=o.indexOf(u),f=o.indexOf(r);if(d<0||f<0)return;const[p,b]=d<=f?[d,f]:[f,d],m=o.slice(p,b+1),g=Cp(m,l),v=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of g)v.add(x);e({selectedIds:v,scopeKey:a??c.scopeKey,anchorId:u})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const a of n)o.delete(a);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),ri=e=>je(e.session.directory??null),Ap=(e,s)=>(e?.projectLabel??null)===(s?.projectLabel??null)&&(e?.branchLabel??null)===(s?.branchLabel??null)&&(e?.showFolderLabel??!1)===(s?.showFolderLabel??!1),Np=e=>{if(!e.openSidebarMenuKey)return null;const s=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${s}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},In=e=>e.menuOpenSessionId??Np(e),Dn=(e,s,n)=>s?n.has(e.node.session.id)?!0:ss(e.node,s):!1,Yr=(e,s,n,r,o)=>{if(e.session.id!==s.session.id)return!0;const a=o(e);if(n.has(a)!==r.has(a)||e.children.length!==s.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(Yr(e.children[l],s.children[l],n,r,o))return!0;return!1},Ip=(e,s)=>{if(e.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return Yr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Yr(e.node,s.node,e.expandedParents,s.expandedParents,o=>`${s.renderContext??"project"}:${r}:${o.session.id}`)},Dp=(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||ri(e.node)!==ri(s.node)||!Ap(e.secondaryMeta,s.secondaryMeta)||e.pinnedSessionIds!==s.pinnedSessionIds&&Ea(e.node,s.node,e.pinnedSessionIds,s.pinnedSessionIds,e.groupDirectory,s.groupDirectory)||e.expandedParents!==s.expandedParents&&Ip(e,s)||e.editingId!==s.editingId&&(Dn(e,e.editingId,e.subtreeContainsEditing)||Dn(s,s.editingId,s.subtreeContainsEditing))||e.editTitle!==s.editTitle&&(Dn(e,e.editingId,e.subtreeContainsEditing)||Dn(s,s.editingId,s.subtreeContainsEditing))||e.copiedSessionId!==s.copiedSessionId&&(ss(e.node,e.copiedSessionId)||ss(s.node,s.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==s.openSidebarMenuKey){const n=In(e),r=In(s);if(ss(e.node,n)||ss(s.node,r))return!1}if(e.renamingFolderId!==s.renamingFolderId){const n=In(e),r=In(s);if(ss(e.node,n)||ss(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};function Rp({node:e,groupDirectory:s,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:a,expansionKey:l,hasSessionSearchQuery:c,notifyOnSubtasks:u}){const d=e.session,f=je(d.directory??null)??je(s??null),p=Ne(Re=>Re.currentSessionId===d.id),b=Oi(f),m=Mc(f),g=pt(i.useCallback(Re=>{if(r?.projectLabel||!n)return null;const Z=Re.projects.find(ue=>ue.id===n);return Z?Z.label?.trim()||Gs(je(Z.path)??Z.path,null)||Z.path:null},[n,r?.projectLabel])),h=r?.projectLabel??(g?Yn(g):null),v=e.worktree,x=r?.branchLabel??v?.branch??(b&&b!=="HEAD"?b:null),I=x,y=m===!0||!!(x||v),k=e.children.length,A=d.agent;i.useMemo(()=>{const Re=v?.branch?.trim()||x?.trim(),Z=je(v?.path??f);return Re&&Z?Pa():null},[x,f,v]);const N=Ma(),j=void 0,w=i.useMemo(()=>null,[N]),C=n??f??null,R=ct(Re=>Re.enabled),P=ct(i.useCallback(Re=>Re.selectedIds.has(d.id),[d.id])),M=ct(Re=>Re.toggleSelected),F=ct(Re=>Re.setRange),B=Tc(i.useCallback(Re=>!!Re.sessionMemoryState.get(Fc(d.id))?.isZombie,[d.id])),L=Li(d.id)?.type??"idle",T=L==="busy"||L==="retry",U=Oc(d.id,T),H=Lc(d.id),ce=ds(d),Q=e.children.length>0,z=Bc(o,f,d.id),Ie=c?!0:a.has(l);i.useMemo(()=>Ph(e,Ie,f),[Ie,e,f]);const O=Uc(),de=!!d.parentID,$=_c(d.id)>0&&(!de||u),G=d.time?.updated||d.time?.created||Date.now(),J=nu(G),se=i.useMemo(()=>Na(e.forkColorId),[e.forkColorId]),fe=i.useMemo(()=>ih(e.forkColorId,{active:p||P}),[e.forkColorId,p,P]),ke=r?.globalSession&&!p&&!P?"var(--surface-elevated)":null;return{session:d,sessionDirectory:f,isActive:p,tooltipProjectLabel:h,tooltipBranchLabel:I,isGitRepo:y,subtaskCount:k,agentName:A,prSummary:N,prIconColor:j,prStatusLabel:w,selectionScopeKey:C,selectionModeEnabled:R,isRowSelected:P,toggleRowSelected:M,setRowRange:F,isZombie:B,isStreaming:T,hasActivityDuration:U,sessionPermissions:H,sessionTitle:ce,hasChildren:Q,isPinnedSession:z,isExpanded:Ie,pendingQuestionCount:O,needsAttention:$,sessionCompactUpdatedLabel:J,forkSolid:se,rowBackground:fe??ke}}function Ep(e){Ot("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:u,normalizedSessionSearchQuery:d,notifyOnSubtasks:f,editingId:p,setEditingId:b,editTitle:m,setEditTitle:g,handleSaveEdit:h,handleCancelEdit:v,toggleParent:x,handleSessionSelect:I,handleSessionDoubleClick:y,togglePinnedSession:k,handleShareSession:A,copiedSessionId:N,handleCopyShareUrl:j,handleCopySessionId:w,handleUnshareSession:C,openSidebarMenuKey:R,setOpenSidebarMenuKey:P,renamingFolderId:M,getFoldersForScope:F,getSessionFolderId:B,removeSessionFromFolder:K,addSessionToFolder:L,createFolderAndStartRename:T,handleDeleteSession:U,handleRestoreSession:H,mobileVariant:ce,alwaysShowActions:Q,allowQuickArchiveAction:z,renderSessionNode:Ie,secondaryMeta:O,renderContext:de="project",subtreeContainsEditing:he,menuOpenSessionId:$,childRenderExtrasFor:G}=e,J=i.useMemo(()=>Ki(),[]),se=!a&&z,fe=i.useRef(!1),ke=i.useRef(p);ke.current=p;const Me=i.useRef(null),Re=i.useRef(h);Re.current=h;const[Z,ue]=i.useState(m),q=i.useRef(Z);q.current=Z;const ye=i.useRef(null),_e=i.useRef(null),ae=`${de}:${a?"archived":"active"}:${s.session.id}`,{session:ne,sessionDirectory:me,isActive:De,tooltipProjectLabel:Ce,tooltipBranchLabel:we,isGitRepo:X,subtaskCount:xe,agentName:ee,prSummary:Ae,selectionScopeKey:Ue,selectionModeEnabled:Ye,isRowSelected:Se,toggleRowSelected:te,setRowRange:Oe,isZombie:Fe,isStreaming:mt,hasActivityDuration:nt,sessionPermissions:Qe,sessionTitle:rt,hasChildren:xt,isPinnedSession:Xe,isExpanded:dt,pendingQuestionCount:gt,needsAttention:Ve,sessionCompactUpdatedLabel:Ze,forkSolid:kt,rowBackground:Je}=Rp({node:s,groupDirectory:r,projectId:o,secondaryMeta:O,pinnedSessionIds:l,expandedParents:c,expansionKey:ae,hasSessionSearchQuery:u,notifyOnSubtasks:f}),{exportDialogOpen:Yt,setExportDialogOpen:Rt,exportIncludeSubtasks:Et,setExportIncludeSubtasks:ut,descendantCount:Pt,handleExportSession:ps,doExportSession:qt}=kp(s,me),[Qt,yt]=i.useState(!1),rs=i.useCallback(()=>{me&&on("desktop_open_session_mini_chat_window",{sessionId:ne.id,directory:me,apiBaseUrl:Pr(),clientToken:Er()}).catch(ie=>{console.warn("[session-sidebar] failed to open mini chat window",ie)})},[ne.id,me]);i.useEffect(()=>{if(p!==ne.id)return;const ie=St=>{const bs=St.target?.closest?.(`[data-session-rename-form="${CSS.escape(ne.id)}"]`);_e.current&&!bs&&Re.current(q.current)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[p,ne.id]),i.useLayoutEffect(()=>{if(p!==ne.id){ye.current===ne.id&&(ye.current=null);return}ye.current!==ne.id&&(ye.current=ne.id,ue(m))},[p,m,ne.id]);const ve=Qe.length,Be=!mt&&Ve&&!De,pe=mt&&nt,Le=Xe,ze=t.jsx(D,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),ot=Le?t.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:ze}):null,ft=xt?t.jsx("button",{type:"button",onClick:ie=>{ie.stopPropagation(),x(ae)},onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),ie.stopPropagation(),x(ae))},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":dt?"Collapse subsessions":"Expand subsessions",children:dt?t.jsx(D,{name:"arrow-down-s",className:"h-3 w-3"}):t.jsx(D,{name:"arrow-right-s",className:"h-3 w-3"})}):null,ht=Fe?t.jsx(D,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Ct=ie=>{if(!ie&&Me.current){const{id:St,title:at}=Me.current;Me.current=null,b(St),g(at)}},ms=ie=>{yt(ie)},et=ie=>{ie.preventDefault(),ie.stopPropagation()},gs=ie=>{ie.preventDefault(),ie.stopPropagation()},Vt=ie=>{ie.preventDefault(),ie.stopPropagation(),P(null),U(ne,{archivedBucket:a})},wt=ie=>{ie.preventDefault(),ie.stopPropagation(),P(null),U(ne,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},Ut=ie=>{if(fe.current){fe.current=!1;return}if(Ye){if(ie?.preventDefault(),ie?.stopPropagation(),ie?.shiftKey){const at=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(os=>os.getAttribute("data-session-row")).filter(os=>typeof os=="string"&&os.length>0),bs=ct.getState().anchorId,Mt=new Map;Mt.set(ne.id,Gn(s)),Oe(bs,ne.id,at,Ue,Mt);return}te(ne.id,Ue,Gn(s));return}ie?.currentTarget&&bp(ie.currentTarget),I(ne.id,me)},it=ie=>{ie.defaultPrevented||ie.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Ut(ie)},qs=ie=>{(ie.button===2||ie.button===0&&ie.ctrlKey&&!Ye)&&(fe.current=!0)},Jt={session:ne,sessionTitle:rt,sessionDirectory:me,isPinnedSession:Xe,archivedBucket:a,isElectron:J,renamingFolderId:M,editingIdRef:ke,pendingRenameRef:Me,handleCopySessionId:w,togglePinnedSession:k,handleExportSession:ps,handleOpenMiniChatWindow:rs,handleDeleteSession:U,handleRestoreSession:H},vt=t.jsx(gp,{...Jt});return t.jsxs(i.Fragment,{children:[t.jsx(Dh,{sessionId:ne.id,sessionDirectory:me??null,sessionTitle:rt,children:t.jsxs(Ji,{open:Qt,onOpenChange:ms,onOpenChangeComplete:Ct,children:[t.jsxs(Xi,{render:t.jsx("div",{"data-session-row":ne.id,"data-session-scope":Ue??"","data-session-archived":a?"1":"0","data-fork-color":kt?s.forkColorId:void 0,"data-global-session":O?.globalSession?"1":void 0,onClick:it,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...Je?{backgroundColor:Je}:void 0},className:_("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",!Je&&n>0?"bg-secondary/30 hover:bg-interactive-hover":Je?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!Je&&De&&!Se&&"bg-interactive-selection",!Je&&Se&&"bg-interactive-selection")}),children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[ft,ot,p===ne.id?t.jsxs("form",{ref:_e,"data-session-rename-form":ne.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:ie=>ie.stopPropagation(),onMouseDown:ie=>ie.stopPropagation(),onSubmit:ie=>{ie.preventDefault(),h(Z)},children:[t.jsx("input",{value:Z,onChange:ie=>ue(ie.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:ie=>{ie.stopPropagation(),ie.key==="Escape"&&v()}}),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(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:v,"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(D,{name:"close",className:"size-4"})})]}):t.jsxs("button",{type:"button",onMouseDown:qs,onClick:ie=>Ut(ie),onDoubleClick:ie=>{ie.stopPropagation(),y(ne.id,rt)},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",Ve?"text-foreground":"text-foreground/90"),children:Tn(rt,d)})}),O?.showFolderLabel&&Ce||we||X||Ae||xe>0||ee&&ee!=="default"||pe||ve>0||gt>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:[O?.showFolderLabel&&Ce?t.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Ce}):null,we?t.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[t.jsx(D,{name:"git-branch",className:_("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),t.jsx("span",{className:"truncate",children:we})]}):X?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(D,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),t.jsx("span",{children:"git"})]}):null,null,xe>0?t.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[t.jsx(D,{name:"node-tree",className:"size-3.5 shrink-0"}),t.jsx("span",{children:xe})]}):null,ee&&ee!=="default"?t.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:ee}):null,pe?t.jsx(ru,{sessionId:ne.id,running:mt,className:"text-muted-foreground/70"}):null,ve>0?t.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[t.jsx(D,{name:"shield",className:"size-3.5"}),t.jsx("span",{children:ve})]}):null,null]}):null]})]}),Xe?t.jsx(D,{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",se&&(Q||Qt)?"opacity-0":se?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:mt?t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):Be?t.jsx(ou,{label:"Session complete"}):t.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:Ze})}),se?t.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",Q||Qt?"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(hp,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:et,onMouseDown:gs,onArchive:Vt,onDelete:wt})}):null]}),ht&&!ce?t.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:ht}):null]}),vt]})}),xt&&dt?s.children.map(ie=>{const St=G?G(ie):{subtreeContainsEditing:he,menuOpenSessionId:$,nodeStructureKey:""};return t.jsx(i.Fragment,{children:Ie(ie,n+1,me??r,o,a,O?.globalSession?{globalSession:!0}:void 0,de,St)},ie.session.id)}):null,t.jsx(pp,{open:Yt,onOpenChange:Rt,descendantCount:Pt,exportIncludeSubtasks:Et,setExportIncludeSubtasks:ut,onExport:qt})]},ne.id)}const Pp=i.memo(Ep,Dp),Mp=({open:e,onOpenChange:s,project:n,onSave:r})=>t.jsx(Ht,{open:e,onOpenChange:s,children:t.jsx(Wt,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:t.jsx(ws,{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(zf,{project:n,onIdentitySave:r}):null})})})});function Ga(e){const{showDeletionDialog:s,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:a}=e;return t.jsxs(Is,{className:"w-full sm:items-center sm:justify-between",children:[t.jsxs("button",{type:"button",onClick:()=>n(!s),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":!s,children:[s?t.jsx(D,{name:"checkbox-blank",className:"h-4 w-4"}):t.jsx(D,{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:r,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),t.jsx("button",{type:"button",onClick:()=>{o()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:a})]})]})}function Tp(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=c=>ds(c);return t.jsx(Ht,{open:!!s,onOpenChange:c=>{c||n(null)},children:t.jsxs(Wt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(ns,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),t.jsx(fs,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`"${l(s.session)}" and its ${s.descendantCount} sub-task will be permanently deleted.`:`"${l(s.session)}" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`"${l(s.session)}" and its ${s.descendantCount} sub-task will be archived.`:`"${l(s.session)}" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`"${s?.session?l(s.session):"Untitled Session"}" will be permanently deleted.`:`"${s?.session?l(s.session):"Untitled Session"}" will be archived.`})]}),t.jsx(Ga,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:s?.archivedBucket?"Delete":"Archive"})]})})}function Fp(e){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:a}=e,l=s?.archivedBucket===!0,c=s?.sessionCount??0,u=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",d=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(Ht,{open:!!s,onOpenChange:f=>{f||n(null)},children:t.jsxs(Wt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(ns,{children:u}),t.jsx(fs,{children:d})]}),t.jsx(Ga,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:a,confirmLabel:l?"Delete":"Archive"})]})})}function Op(e){const{value:s,setValue:n,onConfirm:r}=e,{git:o}=Ys(),[a,l]=i.useState(null),[c,u]=i.useState(!1),[d,f]=i.useState(!1),[p,b]=i.useState(!1),m=s?.worktree.path??null;i.useEffect(()=>{let A=!1;return l(null),u(!1),f(!1),b(!1),!s||!m?()=>{A=!0}:(o.getGitStatus(m).then(N=>{if(!A){if(typeof N?.isClean!="boolean"){u(!0);return}l(N)}}).catch(()=>{A||u(!0)}),()=>{A=!0})},[o,s,m]);const g=a?.isClean===!1,h=(a?.ahead??0)>0,v=h&&!s?.worktree.branch,x=s?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",I=!!(s&&a&&!c&&!s.hasActiveSession&&(!g&&!v||d)&&!p),y=s?.worktree.branch||s?.worktree.name||s?.worktree.path||"",k=async()=>{if(I){b(!0);try{await r({force:g})}finally{b(!1)}}};return t.jsx(Ht,{open:!!s,onOpenChange:A=>{!A&&!p&&n(null)},children:t.jsxs(Wt,{showCloseButton:!1,className:"max-w-md gap-5",children:[t.jsxs(us,{children:[t.jsx(ns,{children:"Close worktree?"}),t.jsx(fs,{children:`Closing "${y}" removes its worktree directory. ${x}`})]}),c?t.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3",children:[t.jsx(D,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):a===null?t.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,s?.hasActiveSession?t.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,g?t.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),t.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[t.jsx(kr,{checked:d,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),t.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,h?t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:a?.ahead===1?`This worktree has 1 unpushed commit. ${x}`:`This worktree has ${a?.ahead} unpushed commits. ${x}`}),v?t.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(D,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),t.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),t.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[t.jsx(kr,{checked:d,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),t.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,t.jsxs(Is,{className:"sm:justify-end",children:[t.jsx(Te,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:p,children:"Cancel"}),t.jsx(Te,{variant:"destructive",size:"sm",onClick:()=>{k()},disabled:!I,children:p?"Closing…":"Close worktree"})]})]})})}function Lp(e){const{value:s,setValue:n,onConfirm:r}=e;return t.jsx(Ht,{open:!!s,onOpenChange:o=>{o||n(null)},children:t.jsxs(Wt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(ns,{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(Is,{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 Bp=({updateDialogOpen:e,setUpdateDialogOpen:s,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:a,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:u,setShowDeletionDialog:d,confirmDeleteSession:f,deleteFolderConfirm:p,setDeleteFolderConfirm:b,confirmDeleteFolder:m,closeWorktreeConfirm:g,setCloseWorktreeConfirm:h,confirmCloseWorktree:v,bulkDeleteConfirm:x,setBulkDeleteConfirm:I,confirmBulkDelete:y})=>t.jsxs(t.Fragment,{children:[t.jsx(ba,{open:e,onOpenChange:s,info:n.info,downloading:n.downloading,downloaded:n.downloaded,progress:n.progress,error:n.error,onDownload:n.downloadUpdate,onRestart:n.restartToUpdate,runtimeType:n.runtimeType}),t.jsx(Mp,{open:!!r,onOpenChange:k=>{k||o(null)},project:r,onSave:a}),t.jsx(Tp,{value:l,setValue:c,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:f}),t.jsx(Lp,{value:p,setValue:b,onConfirm:m}),t.jsx(Op,{value:g,setValue:h,onConfirm:v}),t.jsx(Fp,{value:x,setValue:I,showDeletionDialog:u,setShowDeletionDialog:d,onConfirm:y})]}),_p=({directories:e})=>{const s=i.useMemo(()=>{const r=new Set;return e.forEach(o=>{const a=je(o)?.toLowerCase();a&&r.add(a)}),r},[e]);return rn(r=>{for(const o of r.catalog.byId.values()){if(o.lifecycle!=="busy"&&o.lifecycle!=="retry")continue;const a=je(o.directory)?.toLowerCase();if(a&&s.has(a))return!0}return!1},void 0,"catalog")?t.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:t.jsx(Ds,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},oi={selected:0,"active-project":1,expanded:2,visible:3,background:4};function Up(e){const s=new Map,n=(r,o,a)=>{const l=je(r??null);if(!l)return;const c=s.get(l);c&&oi[c.priority]<=oi[o]||s.set(l,{directory:l,priority:o,reason:a})};for(const r of e.projectSections){const o=!e.collapsedProjects.has(r.project.id);let a="background";r.project.id===e.activeProjectId?a="active-project":o&&(a="expanded"),n(r.project.normalizedPath,a,o?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=o&&!e.collapsedGroups.has(`${r.project.id}:${l.id}`);let u="background";c?u="expanded":o&&(u="visible"),n(l.directory,u,c?"worktree-expanded":"known-worktree")}}return n(e.currentDirectory,"selected","current-directory"),n(e.currentSessionDirectory,"selected","selected-session"),[...s.values()]}const zp=({owner:e,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l})=>{const c=Ne(u=>u.currentSessionDirectory);return i.useEffect(()=>{s.setBootstrapDemand(e,Up({projectSections:n,activeProjectId:r,collapsedProjects:o,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,o,l,c,e,n]),i.useEffect(()=>()=>s.clearBootstrapDemand(e),[s,e]),null},$p=e=>{let s=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(s+=r.sessions.length);return s},Gp=e=>{const s=new Map;for(const n of e){let r=0;for(const o of n.groups)o.isArchivedBucket||(r+=o.sessions.length);s.set(n.project.id,r)}return s},Kp=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),Hp=(e,s)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>s.has(r.session.id))),Wp=(e,s)=>{const n=new Map;for(const r of e){const o=new Set;for(const a of r.groups){if(a.isArchivedBucket)continue;if(a.sessions.some(c=>s.has(c.session.id))&&a.directory){const c=je(a.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},Yp=e=>e.map(s=>s.groups.some(n=>n.isArchivedBucket)?{...s,groups:s.groups.filter(n=>!n.isArchivedBucket)}:s),qp=(e,s,n,r)=>{if(!n)return s;const o=e.find(c=>c.project.id===n);if(!o)return[];const a=je(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&je(c.directory)===a);return l?[{...o,groups:[l]}]:[]},Qp=(e,s)=>{const n=new Map,r=new Map;return e.forEach(o=>{const a=Yn(o.project.label?.trim()||Gs(o.project.normalizedPath,s)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==a?l.branch:null,u={projectLabel:a,branchLabel:c},d=f=>{f.forEach(p=>{const b=o.project.normalizedPath.length,m=r.get(p.session.id)??-1;b<m||(n.set(p.session.id,{node:p,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:u}),r.set(p.session.id,b),p.children.length>0&&d(p.children))})};d(l.sessions)})}),n};function Vp({projectSections:e,flatSectionsForRender:s,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:a,activeSessionIdSet:l,unreadSessionIdSet:c}){const u=i.useMemo(()=>Qp(e,a),[e,a]),d=i.useMemo(()=>Yp(s),[s]),f=i.useMemo(()=>qp(n,d,r,o),[n,d,r,o]),p=i.useMemo(()=>$p(e),[e]),b=i.useMemo(()=>Gp(e),[e]),m=i.useCallback(v=>{const x=e.find(I=>I.project.id===v);return x?Kp(x,l):!1},[l,e]),g=i.useMemo(()=>Wp(e,l),[l,e]),h=i.useCallback(v=>{const x=e.find(I=>I.project.id===v);return x?Hp(x,c):!1},[e,c]);return{sessionSidebarMetaById:u,sectionsForSidebarRender:d,filteredSectionsForSidebarRender:f,totalSessionCount:p,sessionCountByProject:b,hasActiveSessionByProject:m,activeDirectoriesByProject:g,hasUnseenByProject:h}}const Jp=({selectedCount:e,archivedBucket:s,onRestore:n,onDelete:r,onDone:o})=>{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(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:t.jsx(D,{name:"inbox-unarchive",className:"h-4 w-4"})})}),t.jsx(He,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Restore"})})]}):null,t.jsxs(Ge,{children:[t.jsx(Ke,{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(D,{name:"delete-bin",className:"h-4 w-4"})})}),t.jsx(He,{side:"top",sideOffset:4,children:t.jsx("p",{children:a})})]}),t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:t.jsx(D,{name:"close",className:"h-4 w-4"})})}),t.jsx(He,{side:"top",sideOffset:4,children:t.jsx("p",{children:"Exit selection"})})]})]})]})},Xp=e=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:u,unarchiveSessions:d,deleteSessions:f,setBulkDeleteConfirm:p}=e,b=ct(T=>T.enabled),m=ct(T=>T.selectedIds.size),g=m>0,h=ct(T=>T.selectedIds),v=ct(T=>T.scopeKey),x=i.useCallback(()=>{ct.getState().toggleMode()},[]),I=i.useCallback(()=>{ct.getState().disable()},[]),y=i.useMemo(()=>{if(!g||typeof document>"u")return!1;let T=!1,U=!1;for(const H of h){const ce=document.querySelectorAll(`[data-session-row="${CSS.escape(H)}"]`);for(const Q of ce)Q.getAttribute("data-session-archived")==="1"?U=!0:T=!0}return U&&!T},[g,h]),k=i.useMemo(()=>{if(v)return v;if(!g||typeof document>"u")return null;for(const T of h){const H=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(H&&H.length>0)return H}return null},[g,h,v]),A=i.useMemo(()=>{if(!k)return[];const T=o.get(k);return T&&T.length>0?T.map(U=>U.scopeKey):[k]},[k,o]),N=i.useMemo(()=>A.flatMap(T=>r[T]??[]),[r,A]),j=i.useCallback(T=>{for(const U of A)if((r[U]??[]).some(H=>H.id===T))return U;return null},[r,A]),w=i.useMemo(()=>{if(!g)return!1;for(const T of A)for(const U of r[T]??[])for(const H of U.sessionIds)if(h.has(H))return!0;return!1},[r,A,g,h]),C=i.useCallback((T,U)=>{const H=Array.from(h);for(const ce of A)ce!==T&&l(ce,H);a(T,U,H)},[a,l,h,A]),R=i.useCallback(T=>{if(!g)return;const U=j(T);U&&C(U,T)},[g,C,j]),P=i.useCallback(()=>{const T=A[0];if(!T||!g)return;const U=c(T);U&&C(T,U.id)},[c,g,C,A]),M=i.useCallback(()=>{if(!g)return;const T=Array.from(h);for(const U of A)l(U,T)},[l,h,A,g]),F=i.useCallback(async()=>{const T=Array.from(h);if(T.length!==0){if(y){const{deletedIds:U,failedIds:H}=await f(T);U.length>0&&oe.success(U.length===1?`Deleted ${U.length} session`:`Deleted ${U.length} sessions`),H.length>0&&oe.error(H.length===1?`Failed to delete ${H.length} session`:`Failed to delete ${H.length} sessions`)}else{const{archivedIds:U,failedIds:H}=await u(T);U.length>0&&oe.success(U.length===1?`Archived ${U.length} session`:`Archived ${U.length} sessions`),H.length>0&&oe.error(H.length===1?`Failed to archive ${H.length} session`:`Failed to archive ${H.length} sessions`)}ct.getState().clear()}},[u,y,f,h]),B=i.useCallback(()=>{if(!g)return;const T=h.size;if(!n){F();return}p({sessionCount:T,archivedBucket:y})},[y,F,h,n,p,g]),K=i.useCallback(async()=>{if(!g||!y)return;const T=Array.from(h),{restoredIds:U,failedIds:H}=await d(T);U.length>0&&oe.success(U.length===1?`Restored ${U.length} session`:`Restored ${U.length} sessions`),H.length>0&&oe.error(H.length===1?`Failed to restore ${H.length} session`:`Failed to restore ${H.length} sessions`),ct.getState().clear()},[y,g,h,d]),L=i.useCallback(async()=>{p(null),await F()},[F]);return i.useEffect(()=>{if(!b)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),U=H=>{if(s)return;const ce=H.target;if(ce&&(ce.tagName==="INPUT"||ce.tagName==="TEXTAREA"||ce.isContentEditable))return;const Q=T?H.metaKey:H.ctrlKey;if(H.key==="Escape"){H.preventDefault(),ct.getState().disable();return}if(Q&&H.key==="Backspace"){H.preventDefault(),B();return}if(Q&&(H.key==="a"||H.key==="A")){const z=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(z.length===0)return;H.preventDefault();const O=ct.getState().scopeKey??z[0]?.getAttribute("data-session-scope")??null,de=$=>O?$.getAttribute("data-session-scope")===O:!0,he=z.filter(de).map($=>$.getAttribute("data-session-row")).filter($=>typeof $=="string"&&$.length>0);if(he.length===0)return;ct.getState().replaceAll(he,O||null)}};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[B,s,b]),{selectionModeEnabled:b,hasSelection:g,selectedIdsSize:m,bulkScopeIsArchived:y,derivedSelectionScope:k,bulkScopeFolders:N,bulkCanRemoveFromFolder:w,handleToggleSelectionMode:x,handleExitSelectionMode:I,handleBulkMoveToFolder:R,handleBulkCreateFolderAndMove:P,handleBulkRemoveFromFolder:M,handleBulkDelete:B,handleBulkRestore:K,confirmBulkDelete:L}},Zp=(e,s)=>{const n=e??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},em=hs()(to(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:Zp})),ii="oc.sessions.projectCollapse",ai="oc.sessions.groupOrder",li="oc.sessions.groupCollapse",ci="oc.sessions.activeSessionByProject",di="oc.sessions.expandedParents.v3",tm=new Set,ur=[],Nt=e=>{const s=i.useRef(e);return s.current=e,i.useCallback((...n)=>s.current(...n),[])},sm=({isVisible:e=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Rr("react.session_sidebar_render"),Ot("ui.session_sidebar.render"),Ot(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),Ot(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,u]=i.useState(!1),[d,f]=i.useState(""),p=i.useRef(null),b=i.useRef(null),[m,g]=i.useState(null),[h,v]=i.useState(""),[x,I]=i.useState(null),[y,k]=i.useState(new Set),A=i.useMemo(()=>jn(),[]),[N,j]=i.useState(new Set),w=Ts(S=>S.selectedSpaceId),C=Ts(S=>S.selectedWorktreePath),[R,P]=i.useState(new Map),[M,F]=i.useState(new Map),[B,K]=i.useState(!1),[L,T]=i.useState(null),[U,H]=i.useState(null),[ce,Q]=i.useState(""),[z,Ie]=i.useState(null),[O,de]=i.useState(null),[he,$]=i.useState(null),[G,J]=i.useState(null),se=Nr(S=>S.ids),fe=zc(i.useCallback(S=>e?S.rankById:Ti,[e])),ke=rn(S=>e?$c(S.catalog):"",void 0,"catalog"),Me=i.useMemo(()=>ke?ke.split("|"):ur,[ke]),Re=i.useMemo(()=>new Set(Me),[Me]),Z=Gc(Or(S=>e?Object.entries(S.index.session.unseenCount).filter(([,W])=>W>0).map(([W])=>W).sort():ur)),ue=i.useMemo(()=>new Set(Z),[Z]),q=Nr(S=>S.toggle),[ye,_e]=i.useState(()=>{try{const S=jn().getItem(li);if(!S)return new Set;const W=JSON.parse(S);return new Set(Array.isArray(W)?W.filter(V=>typeof V=="string"):[])}catch{return new Set}}),[Y,ae]=i.useState(()=>{try{const S=jn().getItem(ai);if(!S)return new Map;const W=JSON.parse(S),V=new Map;return Object.entries(W).forEach(([Ee,We])=>{Array.isArray(We)&&V.set(Ee,We.filter(qe=>typeof qe=="string"))}),V}catch{return new Map}}),ne=i.useMemo(()=>{try{const S=jn().getItem(ci);if(!S)return new Map;const W=JSON.parse(S),V=new Map;return Object.entries(W).forEach(([Ee,We])=>{typeof We=="string"&&We.length>0&&V.set(Ee,We)}),V}catch{return new Map}},[]),me=i.useCallback(S=>{try{A.setItem(ci,JSON.stringify(Object.fromEntries(S.entries())))}catch{}},[A]),[De,Ce]=i.useState(new Map),we=i.useRef(0),X=$s(S=>S.homeDirectory),xe=$s(S=>S.currentDirectory),ee=pt(S=>S.projects),Ae=pt(S=>S.activeProjectId),Ue=pt(S=>S.removeProject),Ye=pt(S=>S.setActiveProjectIdOnly),Se=pt(S=>S.updateProjectMeta),te=pt(S=>S.reorderProjects),Oe=le(S=>S.setActiveMainTab),Fe=le(S=>S.setSettingsDialogOpen),mt=le(S=>S.setSettingsPage),nt=le(S=>S.toggleHelpDialog),Qe=le(S=>S.setSessionSwitcherOpen),rt=le(S=>S.setArchivePageOpen),xt=le(S=>S.notifyOnSubtasks),Xe=le(S=>S.showDeletionDialog),dt=le(S=>S.setShowDeletionDialog),gt=Kc(d,120),Ve=i.useMemo(()=>gt.trim().toLowerCase(),[gt]),Ze=Ve.length>0,kt=lt(S=>S.collapsedFolderIds),Je=lt(S=>S.foldersMap),Yt=lt(S=>S.getFoldersForScope),Rt=lt(S=>S.createFolder),Et=lt(S=>S.renameFolder),ut=lt(S=>S.deleteFolder),Pt=lt(S=>S.addSessionToFolder),ps=lt(S=>S.addSessionsToFolder),qt=lt(S=>S.removeSessionFromFolder),Qt=lt(S=>S.removeSessionsFromFolders),yt=lt(S=>S.toggleFolderCollapse),rs=lt(S=>S.getSessionFolderId);ch({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchContainerRef:p});const ve=Hc(e),Be=Bi(),{git:pe}=Ys(),Le=Mi(),ze=rn(S=>S.connection,void 0,"chrome"),ot=rn(S=>{for(const W of S.catalog.listStatusByDirectory.values())if(W==="ready")return!0;return!1},void 0,"catalog"),ft=Ar({archived:!1}),ht=Ar({archived:!0}),Ct=`session-sidebar:${i.useId()}`,ms=Ne(S=>S.setCurrentSession),et=Ne(S=>S.updateSessionTitle),gs=Ne(S=>S.shareSession),Vt=Ne(S=>S.unshareSession),wt=Dr(S=>S.projects),Ut=Dr(S=>S.refreshProject),it=i.useMemo(()=>Wc(ee,{projects:wt}),[ee,wt]),qs=i.useMemo(()=>{const S=new Map;for(const W of ee){const V=je(W.path);if(!V)continue;const Ee=wt.get(V)?.error;Ee&&S.set(V,Ee)}return S},[ee,wt]);i.useEffect(()=>{if(!w)return;const S=ee.find(V=>V.id===w);if(!S){Ts.getState().clearSpaceSelection();return}if(!C)return;(it.get(je(S.path)??S.path)??[]).some(V=>je(V.path)===je(C))||(Ts.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[it,ee,w,C]);const Jt=Ne(S=>S.openNewSessionDraft),vt=i.useCallback(S=>{le.getState().closeMainSurfaces(),Jt(S),r?.()},[r,Jt]),ie=Mn(Or(S=>({checkForUpdates:S.checkForUpdates,available:S.available,runtimeType:S.runtimeType,info:S.info,downloading:S.downloading,downloaded:S.downloaded,progress:S.progress,error:S.error,downloadUpdate:S.downloadUpdate,restartToUpdate:S.restartToUpdate}))),St=i.useMemo(()=>Yc(ee,it,{includeWorktrees:!0}),[it,ee]),at=i.useMemo(()=>ft.filter(S=>kh(S,St,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:X})),[ft,X,St]),bs=i.useMemo(()=>[...at,...ht],[ht,at]),Mt=Wn(),os=i.useMemo(()=>`${Mt}|${ee.map(S=>`${S.id}:${je(S.path)??""}`).join("|")}`,[ee,Mt]),zt=i.useMemo(()=>{const S=new Set;let W=!0;for(const V of ee){const Ee=je(V.path);if(!Ee)continue;const We=wt.get(Ee)?.status??"idle";We==="failed"&&S.add(Ee),(We==="idle"||We==="loading")&&(W=!1)}return{complete:W,unresolved:S}},[ee,wt]),qn=zt.complete?os:null,Qn=!zt.complete,xn=zt.unresolved,{isTablet:Qs}=Ws(),Rs=s||Qs,Vn=lh({mobileVariant:s,isTablet:Qs}),{buildGroupSearchText:Jn,filterSessionNodesForSearch:E,buildGroupedSessions:re}=ah({homeDirectory:X,pinnedSessionIds:se,sessionOrderRanks:fe}),{scheduleCollapsedProjectsPersist:be}=uh({safeStorage:A,keys:{sessionExpanded:di,projectCollapse:ii,groupOrder:ai,groupCollapse:li},groupOrderByProject:Y,collapsedGroups:ye,setExpandedParents:k,setCollapsedProjects:j}),$e=i.useMemo(()=>qc(at,se,fe),[se,fe,at]),$t=i.useMemo(()=>$e.map(S=>S.id).join("|"),[$e]),Tt=i.useRef(null),Es=i.useMemo(()=>{const S=Tt.current;if(S&&S.signature===$t)return S.map;const W=new Map($e.map((V,Ee)=>[V.id,Ee]));return Tt.current={signature:$t,map:W},W},[$e,$t]),Xt=i.useMemo(()=>{const S=new Map;return $e.forEach(W=>{const V=W.parentID;if(!V)return;const Ee=S.get(V)??[];Ee.push(W),S.set(V,Ee)}),S.forEach(W=>W.sort((V,Ee)=>Vr(V,Ee,se,fe))),S},[$e,se,fe]),Ya=i.useMemo(()=>t.jsx(js,{icon:"chat-new",mobileVariant:s,onClick:()=>vt(),children:"New session"}),[s,vt]),qa=i.useMemo(()=>ee.find(S=>S.id===x)??null,[ee,x]),Qa=i.useCallback(S=>{x&&Se(x,{label:S.label,defaultModel:S.defaultModel??null})},[x,Se]),Va=i.useCallback(()=>{const S=Mn.getState();if(S.available&&S.info){K(!0);return}ie.checkForUpdates().then(()=>{const{available:W,error:V}=Mn.getState();if(V){oe.error("Failed to check for updates",{description:V});return}if(!W){oe.success("You are on the latest version");return}K(!0)})},[ie]),Ps=Qc(),co=i.useCallback(()=>{if(s&&Qe(!1),r?.(),Ps?.openSettings){Ps.openSettings();return}Fe(!0)},[Ps,s,r,Qe,Fe]),Ja=ie.available&&(ie.runtimeType==="desktop"||ie.runtimeType==="web"),Xa=Ne(S=>S.deleteSession),uo=Ne(S=>S.deleteSessions),Za=Ne(S=>S.archiveSession),fo=Ne(S=>S.archiveSessions),el=Ne(S=>S.unarchiveSession),tl=Ne(S=>S.unarchiveSessions),{copiedSessionId:sl,handleSessionSelect:nl,handleSessionDoubleClick:rl,handleSaveEdit:ol,handleCancelEdit:il,handleShareSession:al,handleCopyShareUrl:ll,handleCopySessionId:cl,handleUnshareSession:dl,handleDeleteSession:ul,handleRestoreSession:fl,confirmDeleteSession:hl}=dh({mobileVariant:s,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:d,setSessionSearchQuery:f,setIsSessionSearchOpen:u,setActiveMainTab:Oe,setSessionSwitcherOpen:Qe,setCurrentSession:ms,updateSessionTitle:et,shareSession:gs,unshareSession:Vt,deleteSession:Xa,deleteSessions:uo,archiveSession:Za,archiveSessions:fo,unarchiveSession:el,childrenMap:Xt,showDeletionDialog:Xe,setDeleteSessionConfirm:Ie,deleteSessionConfirm:z,setEditingId:g,setEditTitle:v,editingId:m,editTitle:h}),pl=i.useCallback(()=>{if(!O)return;const{scopeKey:S,folderId:W}=O;de(null),ut(S,W)},[O,ut]),ho=i.useCallback(()=>{ks.requestDirectoryDialog()},[]),ml=i.useCallback(S=>{k(W=>{const V=iu(W,S);try{A.setItem(di,JSON.stringify(Array.from(V)))}catch{}return V})},[A]),po=i.useCallback((S,W)=>{if(!S)return null;W&&kt.has(W)&&yt(W);const V=Rt(S,"New folder",W);return H(V.id),Q(V.name),V},[kt,yt,Rt]),Vs=Nt(nl),gl=Nt(rl),bl=Nt(ol),xl=Nt(il),yl=Nt(al),wl=Nt(ll),vl=Nt(cl),Sl=Nt(dl),jl=Nt(ul),kl=Nt(fl),Xn=Nt(po),mo=i.useCallback((S,W)=>{F(V=>{const Ee=new Map(V);return Ee.set(S,W+7),Ee})},[]),yn=i.useCallback(S=>{F(W=>{if(!W.has(S))return W;const V=new Map(W);return V.delete(S),V})},[]),go=i.useCallback(S=>{F(W=>{let V=!1;const Ee=new Map(W),We=`${S}:`;for(const qe of Ee.keys())qe.startsWith(We)&&(Ee.delete(qe),V=!0);return V?Ee:W})},[]),Cl=i.useCallback(S=>{we.current=Date.now()+150,go(S),j(W=>{const V=new Set(W);V.has(S)?V.delete(S):V.add(S);try{A.setItem(ii,JSON.stringify(Array.from(V)))}catch{}return be(V),V})},[go,A,be]),is=i.useMemo(()=>ee.map(S=>({...S,normalizedPath:je(S.path)})).filter(S=>!!S.normalizedPath),[ee]),Al=i.useMemo(()=>is.map(S=>S.normalizedPath),[is]),bo=Vc(e?Al:ur);bh({enabled:e,normalizedProjects:is,gitRepoStatus:bo,setProjectRepoStatus:P,setProjectRootBranches:Ce});const Nl=Ne(S=>S.isLoading),xo=i.useMemo(()=>Ah(at,is,it,ht),[ht,it,is,at]);Sh({enabled:e,hasAuthoritativeGlobalSessions:ot,sessions:bs});const{getSessionsForProject:Il,getArchivedSessionsForProject:Dl}=xh({ownership:xo});Zf({enabled:e,normalizedProjects:is,ownership:xo,isSessionsLoading:Nl,hasAuthoritativeGlobalSessions:ot,isWorktreeTopologyLoading:Qn,unresolvedWorktreeProjectPaths:xn,foldersMap:Je,createFolder:Rt,addSessionToFolder:Pt});const yo=i.useRef(!1);Ae&&R.has(Ae)&&(yo.current=!!R.get(Ae));const Rl=em(S=>S.showArchivedSessions),Zn=pt(S=>S.manualProjectOrder),wo=i.useRef(new Set),wn=au(wo.current,y,"project");wo.current=wn;const er={isVisible:e,mobileVariant:s,onSessionSelected:n,allowReselect:o,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:Qs,catalogSessions:ft,archivedSessions:ht,projects:ee,activeProjectId:Ae,manualProjectOrder:Zn,currentDirectory:xe,availableWorktreesByProject:it,pinnedSessionIds:se,sessionOrderRanks:fe,foldersMap:Je,collapsedFolderIds:kt,gitBranches:ve,gitRepoStatus:bo,updateStore:ie,showArchivedSessions:Rl,projectRepoStatus:R,projectRootBranches:De,resolvedWorktreeTopologyKey:qn,unresolvedWorktreeProjectPaths:xn,isSessionSearchOpen:c,sessionSearchQuery:d,editingId:m,editTitle:h,editingProjectDialogId:x,expandedParents:y,collapsedProjects:N,visibleSessionCountByGroup:M,updateDialogOpen:B,openSidebarMenuKey:L,renamingFolderId:U,renameFolderDraft:ce,deleteSessionConfirm:z,deleteFolderConfirm:O,bulkDeleteConfirm:G,collapsedGroups:ye},vo=i.useRef(null),So=vo.current;if(So){let S=!1;for(const W of Object.keys(er))Object.is(So[W],er[W])||(Ot(`ui.session_sidebar.source.${W}`),S=!0);S||Ot("ui.session_sidebar.source.parent_or_context")}vo.current=er;const El=i.useMemo(()=>{const S=new Map(Zn.map((W,V)=>[W,V]));return[...is].sort((W,V)=>(S.get(W.id)??1/0)-(S.get(V.id)??1/0))},[Zn,is]),{projectSections:At,groupSearchDataByGroup:jo,sectionsForRender:Pl,flatSectionsForRender:tr,searchMatchCount:Ml}=th({normalizedProjects:El,getSessionsForProject:Il,getArchivedSessionsForProject:Dl,availableWorktreesByProject:it,projectRepoStatus:R,projectRootBranches:De,lastRepoStatus:yo.current,buildGroupedSessions:re,hasSessionSearchQuery:Ze,normalizedSessionSearchQuery:Ve,filterSessionNodesForSearch:E,buildGroupSearchText:Jn,foldersMap:Je}),vn=i.useMemo(()=>{const S=at.filter(V=>Hn(Bs(V),X));if(S.length===0)return null;const W=re(S,"~",[],null,!1).map(V=>Ze?{...V,sessions:E(V.sessions,Ve)}:V).filter(V=>V.sessions.length>0&&!V.isArchivedBucket);return W.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:W}},[re,E,Ze,X,Ve,at]),Tl=i.useMemo(()=>{if(!Ze||!vn)return 0;const S=W=>W.reduce((V,Ee)=>V+1+S(Ee.children),0);return vn.groups.reduce((W,V)=>W+S(V.sessions),0)},[vn,Ze]),Fl=i.useMemo(()=>t.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[t.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),t.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Ol}=eh(Y),ko=i.useRef(!1);i.useEffect(()=>{if(ko.current||At.length===0)return;const S=At.flatMap(W=>W.groups.filter(V=>V.isArchivedBucket).map(V=>`${W.project.id}:${V.id}`));S.length>0&&_e(W=>new Set([...W,...S])),ko.current=!0},[At]);const{filteredSectionsForSidebarRender:Ll,totalSessionCount:Bl,sessionCountByProject:_l,hasActiveSessionByProject:Ul,activeDirectoriesByProject:Js,hasUnseenByProject:zl}=Vp({projectSections:At,flatSectionsForRender:tr,sectionsForRender:Pl,selectedSpaceId:w,selectedWorktreePath:C,homeDirectory:X,activeSessionIdSet:Re,unreadSessionIdSet:ue}),sr=i.useCallback(S=>{if(Ts.getState().selectSpace(S),!S)return;Ye(S);const W=At.find(We=>We.project.id===S),V=W?.groups.find(We=>We.isMain),Ee=V?.sessions[0]?.session;Ee?Vs(Ee.id,V?.directory??W?.project.normalizedPath??null,{keepPanelOpen:!0}):W&&vt({selectedProjectId:S,directoryOverride:W.project.normalizedPath})},[vt,At,Ye,Vs]),$l=s?"flex size-10 shrink-0 items-center justify-center rounded-full leading-none text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Gl=s?"size-5":"h-4.5 w-4.5",Sn=Nt((S,W=0,V,Ee,We=!1,qe,Gt="project",Ms)=>t.jsx(Pp,{node:S,depth:W,groupDirectory:V,projectId:Ee,archivedBucket:We,pinnedSessionIds:se,expandedParents:wn,hasSessionSearchQuery:Ze,normalizedSessionSearchQuery:Ve,notifyOnSubtasks:xt,editingId:m,setEditingId:g,editTitle:h,setEditTitle:v,handleSaveEdit:bl,handleCancelEdit:xl,toggleParent:ml,handleSessionSelect:Vs,handleSessionDoubleClick:gl,togglePinnedSession:q,handleShareSession:yl,copiedSessionId:sl,handleCopyShareUrl:wl,handleCopySessionId:vl,handleUnshareSession:Sl,openSidebarMenuKey:L,setOpenSidebarMenuKey:T,renamingFolderId:U,getFoldersForScope:Yt,getSessionFolderId:rs,removeSessionFromFolder:qt,addSessionToFolder:Pt,createFolderAndStartRename:Xn,handleDeleteSession:jl,handleRestoreSession:kl,mobileVariant:s,alwaysShowActions:Rs,allowQuickArchiveAction:Vn,renderSessionNode:Sn,secondaryMeta:qe,renderContext:Gt,subtreeContainsEditing:Ms?.subtreeContainsEditing??tm,menuOpenSessionId:Ms?.menuOpenSessionId??null,nodeStructureKey:Ms?.nodeStructureKey??"",childRenderExtrasFor:Ms?.childRenderExtrasFor})),Kl=i.useMemo(()=>{const S=new Map;return tr.forEach(W=>{const V=W.groups.find(Ee=>!Ee.isArchivedBucket);V?.folderScopes&&V.folderScopes.length>0&&S.set(W.project.id,V.folderScopes)}),S},[tr]),Hl=i.useCallback((S,W)=>{const V=[];return W.forEach(Ee=>{Ee.isArchivedBucket||(V.push(Ee.directory),Ee.folderScopes?.forEach(We=>V.push(We.directory)))}),t.jsx(_p,{directories:V})},[]),Co=i.useCallback(S=>{yn(S),_e(W=>{const V=new Set(W);return V.has(S)?V.delete(S):V.add(S),V})},[yn]),Wl=i.useCallback((S,W,V,Ee,We,qe,Gt)=>t.jsx(qh,{group:S,groupKey:W,projectId:V,hideGroupLabel:Ee,dragHandleProps:We,compactBodyPadding:qe,hasSessionSearchQuery:Ze,normalizedSessionSearchQuery:Ve,groupSearchDataByGroup:jo,visibleSessionCount:M.get(W),collapsedGroups:ye,hideDirectoryControls:a,collapsedFolderIds:kt,toggleFolderCollapse:yt,renameFolder:Et,deleteFolder:ut,showDeletionDialog:Xe,setDeleteFolderConfirm:de,renderSessionNode:Sn,showMoreGroupSessions:mo,resetGroupSessionLimit:yn,mobileVariant:s,alwaysShowActions:Rs,activeProjectId:Ae,setActiveProjectIdOnly:Ye,setActiveMainTab:Oe,setSessionSwitcherOpen:Qe,openNewSessionDraft:vt,addSessionToFolder:Pt,createFolderAndStartRename:Xn,renamingFolderId:U,renameFolderDraft:ce,setRenameFolderDraft:Q,setRenamingFolderId:H,pinnedSessionIds:se,expandedParents:wn,sessionOrderIndex:Es,editingId:m,editTitle:h,openSidebarMenuKey:L,activeActivitySessionIds:Re,unreadActivitySessionIds:ue,notifyOnSubtasks:xt,onToggleCollapsedGroup:Co,scrollContainerRef:Gt}),[Ze,Ve,jo,M,ye,a,kt,yt,Et,ut,Xe,Sn,mo,yn,s,Rs,Ae,Ye,Oe,Qe,vt,Pt,Xn,U,ce,se,wn,Es,m,h,L,Re,ue,xt,Co]),Ao=!!(U||m||x),{selectionModeEnabled:nr,hasSelection:No,selectedIdsSize:Yl,bulkScopeIsArchived:ql,derivedSelectionScope:Ql,bulkScopeFolders:Vl,bulkCanRemoveFromFolder:Jl,handleToggleSelectionMode:Xl,handleExitSelectionMode:Zl,handleBulkMoveToFolder:ec,handleBulkCreateFolderAndMove:tc,handleBulkRemoveFromFolder:sc,handleBulkDelete:nc,handleBulkRestore:rc,confirmBulkDelete:oc}=Xp({isInlineEditing:Ao,showDeletionDialog:Xe,foldersMap:Je,folderScopesByProject:Kl,addSessionsToFolder:ps,removeSessionsFromFolders:Qt,createFolderAndStartRename:po,archiveSessions:fo,unarchiveSessions:tl,deleteSessions:uo,setBulkDeleteConfirm:J}),Io=i.useCallback(()=>{le.getState().closeMainSurfaces(),Oe("chat"),s&&Qe(!1),Jt(),r?.()},[s,r,Jt,Oe,Qe]),ic=i.useCallback((S,W)=>{const V=ee.find(qe=>qe.id===S);if(!V)return;const Ee=je(W.path)?.toLowerCase(),We=!!(Ee&&Js.get(S)?.has(Ee));$({projectId:S,projectPath:V.path,worktree:W,hasActiveSession:We})},[Js,ee]),ac=i.useCallback(async({force:S})=>{const W=he;if(!W)return;const V=je(W.worktree.path)?.toLowerCase();if(!!(V&&Js.get(W.projectId)?.has(V))){$({...W,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!pe.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await pe.deleteGitWorktree(W.projectPath,{directory:W.worktree.path,force:S}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let qe=await Ut(W.projectPath,pe);const Gt=je(W.worktree.path);qe!==null&&Gt!==null&&qe.some(cc=>je(cc.path)===Gt)&&(qe=await Ut(W.projectPath,pe));const Ms=Gt!==null&&je(xe)===Gt,lc=Gt!==null&&w===W.projectId&&je(C)===Gt;(Ms||lc)&&sr(W.projectId),$(null),qe===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(We){const qe=We instanceof Error?We.message:"Try again.";oe.error("Failed to close worktree.",{description:qe})}},[Js,he,xe,pe,sr,Ut,w,C]);return t.jsx(Jc,{delay:400,closeDelay:150,timeout:600,children:t.jsxs("div",{ref:p,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[t.jsx(zp,{owner:Ct,childStores:Le,projectSections:At,activeProjectId:Ae,collapsedProjects:N,collapsedGroups:ye,currentDirectory:xe}),t.jsx(nh,{projectSections:At,activeProjectId:Ae,initialActiveSessionByProject:ne,persistActiveSessionByProject:me,handleSessionSelect:Vs,mobileVariant:s,openNewSessionDraft:Jt,setActiveMainTab:Oe,setSessionSwitcherOpen:Qe}),t.jsx(Xf,{enabled:e,sortedSessions:$e,prefetchSession:async S=>{await Be.syncSession(S)}}),!a&&!s?t.jsx(Vh,{onNewSession:Io,showSidebarToggle:!0}):null,t.jsx(Qh,{hideDirectoryControls:a,handleOpenDirectoryDialog:ho,onOpenArchive:()=>{s&&Qe(!1),rt(!0)},onOpenSettings:s?co:void 0,onOpenInstances:s?Ps?.openInstances:void 0,instanceLabel:s?Ps?.instanceLabel:void 0,onOpenUpdate:s?Ps?.openUpdate:void 0,headerActionIconClass:Gl,headerActionButtonClass:$l,isSessionSearchOpen:c,setIsSessionSearchOpen:u,sessionSearchInputRef:b,sessionSearchQuery:d,setSessionSearchQuery:f,hasSessionSearchQuery:Ze,searchMatchCount:Ml+(w===null?Tl:0),selectionModeEnabled:nr,onToggleSelectionMode:Xl,mobileVariant:s}),ze==="error"||ze==="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&&At.length>0?t.jsx(Zh,{projects:At.map(S=>S.project),selectedProjectId:w,selectedWorktreePath:C,worktreesByProject:it,worktreeErrorsByProject:qs,onSelectProject:sr,onSelectWorktree:(S,W)=>{Ts.getState().selectWorktree(S,W),Ye(S);const We=At.find(qe=>qe.project.id===S)?.groups.find(qe=>je(qe.directory)===je(W))?.sessions[0]?.session;We?Vs(We.id,W,{keepPanelOpen:!0}):vt({selectedProjectId:S,directoryOverride:W})},onCloseWorktree:ic,onOpenDirectoryDialog:ho,onOpenProjectEditDialog:I,onRemoveProject:Ue,totalSessionCount:Bl,getSessionCountForProject:S=>_l.get(S)??0,hasActiveSessionByProject:Ul,activeDirectoriesByProject:Js,hasUnseenByProject:zl,homeDirectory:X,mobileVariant:s}):null,t.jsx(np,{sectionsForRender:Ll,allFoldersOnlySection:w===null?vn:null,projectSections:At,activeProjectId:Ae,showOnlyMainWorkspace:l,hasSessionSearchQuery:Ze,emptyState:Ya,searchEmptyState:Fl,isAllFoldersView:w===null,pinnedSessionIds:se,renderSessionNode:Sn,renderGroupSessions:Wl,homeDirectory:X,collapsedProjects:N,hideDirectoryControls:a,projectRepoStatus:R,mobileVariant:s,alwaysShowActions:Rs,toggleProject:Cl,setActiveProjectIdOnly:Ye,setActiveMainTab:Oe,setSessionSwitcherOpen:Qe,openNewSessionDraft:vt,openProjectEditDialog:I,removeProject:Ue,reorderProjects:te,getOrderedGroups:Ol,setGroupOrderByProject:ae,renderProjectStatusIndicator:Hl,openSidebarMenuKey:L,setOpenSidebarMenuKey:T,isInlineEditing:Ao}),s&&!(nr&&No)?t.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex flex-col gap-2 bg-gradient-to-t from-sidebar via-sidebar/85 to-transparent px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-10",children:[t.jsx(Aa,{variant:"mobile"}),t.jsx(Te,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:Io,"aria-label":"New session",children:t.jsx(D,{name:"chat-new",className:"size-4"})})]}):null,nr&&No?t.jsx(Jp,{selectedCount:Yl,scopeKey:Ql,scopeFolders:Vl,archivedBucket:ql,onMoveToFolder:ec,onCreateFolderAndMove:tc,onRemoveFromFolder:sc,canRemoveFromFolder:Jl,onRestore:rc,onDelete:nc,onDone:Zl}):null,s?null:t.jsx(ep,{onOpenSettings:co,onOpenShortcuts:nt,onOpenAbout:()=>{mt("about"),Fe(!0)},onOpenUpdate:Va,showRuntimeButtons:!0,showUpdateButton:Ja}),t.jsx(Bp,{updateDialogOpen:B,setUpdateDialogOpen:K,updateStore:ie,editingProject:qa,setEditingProjectDialogId:I,handleSaveProjectEdit:Qa,deleteSessionConfirm:z,setDeleteSessionConfirm:Ie,showDeletionDialog:Xe,setShowDeletionDialog:dt,confirmDeleteSession:hl,deleteFolderConfirm:O,setDeleteFolderConfirm:de,confirmDeleteFolder:pl,closeWorktreeConfirm:he,setCloseWorktreeConfirm:$,confirmCloseWorktree:ac,bulkDeleteConfirm:G,setBulkDeleteConfirm:J,confirmBulkDelete:oc})]})})},pb=i.memo(sm),ui=6,It=.18,tn=1.2,sn=.38,Fn=48,nm=(e,s)=>e==="left"?s<0:s>0,mb=(e,s,n)=>Math.min(1,Math.max(0,e==="left"?1+s/n:1-s/n)),gb=(e,s)=>s>=.999?"none":e==="left"?`translateX(${(s-1)*100}%)`:`translateX(${(1-s)*100}%)`,fi=(e,s,n,r)=>e==="left"?s?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):s?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),bb=e=>{const{side:s,dx:n,dy:r,dt:o,progress:a,isDragging:l}=e,c=n/Math.max(1,o);if(l){const u=s==="left"?c<-It:c>It,d=s==="left"?c>It:c<-It;return u||!d&&a<sn}return Math.abs(n)>=Fn&&Math.abs(r)<=Math.abs(n)*tn&&nm(s,n)},rm=e=>{const{side:s,isOpenAtStart:n,dx:r,dt:o,progress:a}=e,l=r/Math.max(1,o);return s==="left"?n?l<-It?!1:l>It?!0:a>sn:l>It?!0:l<-It?!1:a>sn:n?l>It?!1:l<-It?!0:a>sn:l<-It?!0:l>It?!1:a>sn},om='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',im=(e,s,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const a=e.closest(om);if(a&&s.contains(a))return!0}else{const a=e.closest("[data-no-drawer-swipe]");if(a&&s.contains(a))return!0}let o=e;for(;o&&o!==s;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const a=getComputedStyle(o).overflowX;if(a==="auto"||a==="scroll")return!0}o=o.parentElement}return!1},On=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),qr=512*1024,am=new TextEncoder,lm=new TextDecoder,fr=e=>{const s=am.encode(e);if(s.byteLength<=qr)return{text:e,byteLength:s.byteLength};let n=s.byteLength-qr;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:lm.decode(r),byteLength:r.byteLength}},Fs=(e,s)=>`${e}\0${s}`,hr=(e,s)=>{let n=null;for(const r of e.keys())s(r)&&(n??=new Map(e),n.delete(r));return n},cm="terminal-store";let hi=!1,pi=0;const Rn=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(pi+=1,`tab-${Date.now().toString(36)}-${pi.toString(36)}`),pr=e=>typeof e=="object"&&e!==null,dm=e=>{const s=/^tab-(\d+)$/.exec(e);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function tt(e){let s=e.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const um=/^Terminal(?: (\d+))?$/,fm=e=>{let s=0;for(const n of e){const r=um.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(s=Math.max(s,o))}return s===0?"Terminal":`Terminal ${s+1}`},mr=(e,s)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),gr=e=>({tabs:[e],activeTabId:e.id}),Ft=(e,s)=>e.tabs.findIndex(n=>n.id===s);let br=null,xr=null;const hm=e=>{if(xr&&br?.sessions===e.sessions&&br.nextTabId===e.nextTabId)return xr;const s={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return br={sessions:e.sessions,nextTabId:e.nextTabId},xr=s,s},pm=()=>{const e=Jd(()=>Bd());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))}},ge=hs()(Yi(to((e,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=tt(n);r&&e(o=>{if(o.sessions.has(r))return o;const a=new Map(o.sessions),l=Rn(),c=mr(l,"Terminal");return a.set(r,gr(c)),{sessions:a,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=tt(n);return s().sessions.get(r)},getActiveTab:n=>{const r=tt(n),o=s().sessions.get(r);if(!o)return;const a=o.activeTabId;return a?o.tabs.find(l=>l.id===a)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>s().buffers.get(Fs(tt(n),r))??On,createTab:n=>{const r=tt(n);if(!r)return"tab-invalid";const o=Rn();return e(a=>{const l=new Map(a.sessions),c=l.get(r),u=a.nextTabId+1,d=fm(c?.tabs??[]),f=mr(o,d);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,gr(f)),{sessions:l,nextTabId:u}}),o},setActiveTab:(n,r)=>{const o=tt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);return!c||c.activeTabId===r||Ft(c,r)<0?a:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const a=tt(n),l=o.trim();l&&e(c=>{const u=new Map(c.sessions),d=u.get(a);if(!d)return c;const f=Ft(d,r);if(f<0||d.tabs[f]?.label===l)return c;const p=[...d.tabs];return p[f]={...p[f],label:l},u.set(a,{...d,tabs:p}),{sessions:u}})},setTabIconKey:(n,r,o)=>{const a=tt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(u,r);if(d<0)return l;const f=o?.trim()||null;if(u.tabs[d]?.iconKey===f)return l;const p=[...u.tabs];return p[d]={...p[d],iconKey:f},c.set(a,{...u,tabs:p}),{sessions:c}})},closeTab:(n,r)=>{const o=tt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const u=Ft(c,r);if(u<0)return a;const d=c.tabs.filter(h=>h.id!==r),f=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,h])=>!(h.directory===o&&h.tabId===r))),p=Object.keys(f).length!==Object.keys(a.projectActionRuns).length,b=Fs(o,r),m=a.buffers.has(b)?hr(a.buffers,h=>h===b):null;if(d.length===0){const h=Rn(),v=mr(h,"Terminal");return l.set(o,gr(v)),{sessions:l,nextTabId:a.nextTabId+1,...m?{buffers:m}:{},...p?{projectActionRuns:f}:{}}}let g=c.activeTabId;return c.activeTabId===r&&(g=d[Math.min(u,d.length-1)]?.id??d[0]?.id??null),l.set(o,{...c,tabs:d,activeTabId:g}),{sessions:l,...m?{buffers:m}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const a=tt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(u,r);if(d<0)return l;const f=u.tabs[d],p=o!==null&&f.terminalSessionId!==o,b=o?"running":f.terminalSessionId?"exited":f.lifecycle,m={...f,terminalSessionId:o,lifecycle:b,isConnecting:!1},g=Fs(a,r),h=p&&l.buffers.has(g)?hr(l.buffers,x=>x===g):null,v=[...u.tabs];return v[d]=m,c.set(a,{...u,tabs:v}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(n,r,o)=>{const a=tt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(u,r);if(d<0)return l;const f=[...u.tabs];return f[d]={...f[d],lifecycle:o,isConnecting:!1},c.set(a,{...u,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const a=tt(n);e(l=>{const c=new Map(l.sessions),u=c.get(a);if(!u)return l;const d=Ft(u,r);if(d<0)return l;const f=[...u.tabs];return f[d]={...f[d],isConnecting:o},c.set(a,{...u,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,a)=>{const l=tt(n);e(c=>{const u=c.sessions.get(l);if(!u||Ft(u,r)<0)return c;const d=Fs(l,r),f=c.buffers.get(d)??On;if(f.lastSequence>a)return c;const p=fr(o);if(f.lastSequence===a&&f.byteLength===p.byteLength&&f.chunks.map(g=>g.data).join("")===p.text)return c;const b=c.nextChunkId,m=new Map(c.buffers);return m.set(d,{chunks:p.text?[{id:b,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:a}),{buffers:m,nextChunkId:p.text?b+1:b}})},appendToBuffer:(n,r,o,a,l)=>{if(!o)return;const c=tt(n);e(u=>{const d=u.sessions.get(c);if(!d||Ft(d,r)<0)return u;const f=Fs(c,r),p=u.buffers.get(f)??On;if(a!==void 0&&a<=p.lastSequence)return u;const b=u.nextChunkId,m=fr(o),g=l!==void 0&&l!==o?fr(l).text:void 0,h={id:b,data:m.text,...g!==void 0?{replayData:g}:{},byteLength:m.byteLength},v=[...p.chunks,h];let x=p.byteLength+h.byteLength;for(;x>qr&&v.length>1;){const y=v.shift();if(!y)break;x-=y.byteLength}const I=new Map(u.buffers);return I.set(f,{chunks:v,byteLength:x,lastSequence:a??p.lastSequence}),{buffers:I,nextChunkId:b+1}})},setTabPreviewUrl:(n,r,o,a={})=>{const l=tt(n);e(c=>{const u=new Map(c.sessions),d=u.get(l);if(!d)return c;const f=Ft(d,r);if(f<0)return c;const p=d.tabs[f],b=a.autoOpened??p.previewAutoOpened,m=a.locked??p.previewUrlLocked;if(p.previewUrl===o&&p.previewAutoOpened===b&&p.previewUrlLocked===m)return c;const g=[...d.tabs];return g[f]={...p,previewUrl:o,previewAutoOpened:b,previewUrlLocked:m},u.set(l,{...d,tabs:g}),{sessions:u}})},markPreviewAutoOpened:(n,r)=>{const o=tt(n);e(a=>{const l=new Map(a.sessions),c=l.get(o);if(!c)return a;const u=Ft(c,r);if(u<0)return a;const d=c.tabs[u];if(!d.previewUrl||d.previewAutoOpened)return a;const f=[...c.tabs];return f[u]={...d,previewAutoOpened:!0},l.set(o,{...c,tabs:f}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(o=>{const a=o.projectActionRuns[n];return!a||a.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=tt(n);e(o=>{const a=new Map(o.sessions);a.delete(r);const l=Fs(r,""),c=hr(o.buffers,d=>d.startsWith(l)),u=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,d])=>d.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:u}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:cm,storage:pm(),partialize:hm,merge:(e,s)=>{if(!pr(e))return s;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[u,d]=c;if(typeof u!="string"||!pr(d))continue;const f=Array.isArray(d.tabs)?d.tabs:[],p=[],b=new Map;for(const v of f){if(!pr(v))continue;const x=typeof v.id=="string"?v.id:null;if(!x)continue;const I=dm(x);I!==null&&(o=Math.max(o,I));const y=I===null?x:Rn();b.set(x,y),p.push({id:y,label:typeof v.label=="string"?v.label:"Terminal",iconKey:typeof v.iconKey=="string"?v.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof v.createdAt=="number"?v.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const m=typeof d.activeTabId=="string"?d.activeTabId:null,g=m?b.get(m)??m:null,h=g?p.some(v=>v.id===g):!1;r.set(u,{tabs:p,activeTabId:h?g:p[0].id})}const a=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(s.nextTabId,a,o+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!hi){hi=!0;const e=ge.persist,s=()=>{ge.getState().hasHydrated||ge.setState({hasHydrated:!0})};e?.hasHydrated?.()?s():e?.onFinishHydration?e.onFinishHydration(s):s()}function mm(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 yr(e,s,n){const o=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",cursorInactiveStyle:"none",fontSize:s,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,selectionInactiveBackground:n.selectionInactiveBackground,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}}}const gm=(e,s)=>{const n=`${e??""} ${s??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},bm=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),xm=(e,s,n)=>{if(e.altKey)return null;const r=bm(e);return s==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?n?"copy":"ignore":null:e.metaKey?null:e.shiftKey&&!e.ctrlKey&&r==="insert"?"paste":e.ctrlKey&&!e.shiftKey&&r==="insert"?n?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?n?"copy":"ignore":r==="v"?"paste":null},nn=e=>typeof e=="string"&&e.trim().length>0;async function mi(e){return nn(e)?(await As(e)).ok:!1}async function gi(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const ym=(e,s,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const a=Math.floor((e-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(o-1,l))}},wm=(e,s)=>{const n=Math.max(0,Math.min(e.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,a=n;for(;o>0&&r(e[o-1]);)o-=1;for(;a<e.length-1&&r(e[a+1]);)a+=1;return{startColumn:o,endColumn:a}};let vm=null;const Sm=()=>vm??=Promise.all([cs(()=>import("./vendor-xterm-xterm-CrXqRur4.js"),__vite__mapDeps([112,113])),cs(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,s])=>({Xterm:e,Fit:s})),jm=2e3,km=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(s=>setTimeout(s,jm))]).then(()=>{})},Cm=(e,s,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${n}px ${s}`;const o=r.measureText("M"),a=Math.ceil(o.width),l=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(a<1||l<1)return null;const c=window.getComputedStyle(e),u=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),d=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-u-15)/a)),rows:Math.max(1,Math.floor((e.clientHeight-d)/l))}},Ka=i.forwardRef(({sessionKey:e,chunks:s,onInput:n,onResize:r,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:u=!1,autoFocus:d=!0,isVisible:f=!0},p)=>{const b=i.useRef(null),m=i.useRef(null),g=i.useRef(null),h=i.useRef(n),v=i.useRef(r),x=i.useRef(o),I=i.useRef(a),y=i.useRef(l),k=i.useRef(null),A=i.useRef(null),N=i.useRef(null),j=i.useRef(""),w=i.useRef(!1),C=i.useRef(0),R=i.useRef(f),P=i.useRef(!1),[M,F]=i.useState(0),[B,K]=i.useState(0),[L,T]=i.useState(!1),[U,H]=i.useState(!1);h.current=n,v.current=r,R.current=f,x.current=o,I.current=a,y.current=l,i.useLayoutEffect(()=>{const $=b.current;if(!$)return;const G=Cm($,a,l);A.current=G,G&&v.current(G.cols,G.rows)},[a,l]);const ce=i.useCallback(()=>{const $=b.current,G=m.current;if(!$||!G||!g.current||!R.current)return;const J=$.getBoundingClientRect();if(!(J.width<24||J.height<24))try{g.current.fit();const se={cols:G.cols,rows:G.rows};(!k.current||k.current.cols!==se.cols||k.current.rows!==se.rows)&&(k.current=se,v.current(se.cols,se.rows)),P.current||(P.current=!0,F(fe=>fe+1))}catch{}},[]),Q=i.useCallback(()=>{if(w.current||!j.current||!m.current)return;const $=m.current,G=j.current;if(j.current="",!G)return;w.current=!0;const J=C.current;$.write(G,()=>{m.current!==$||C.current!==J||(w.current=!1,j.current&&Q())})},[]),z=i.useCallback(()=>{N.current=null,j.current="",w.current=!1,C.current+=1;const $=m.current;if(!$){K(G=>G+1);return}try{$.reset()}catch{K(G=>G+1)}},[]),Ie=i.useCallback($=>{$?.preventDefault(),H(nn(m.current?.getSelection())),T(!0)},[]),O=i.useCallback($=>{$.stopPropagation();const G=m.current,J=G?.getSelection()??"";G?.focus(),nn(J)&&mi(J)},[]),de=i.useCallback($=>{$.stopPropagation();const G=m.current;G?.focus(),gi().then(J=>{J&&m.current===G&&G&&G.paste(J)})},[]),he=i.useCallback($=>{$.stopPropagation();const G=m.current;G?.focus();try{G?.selectAll()}catch{}H(nn(G?.getSelection()))},[]);return i.useEffect(()=>{const $=b.current;if(!$)return;let G=!1,J=null,se=null,fe=null,ke=null,Me=[];const Re=()=>{J&&R.current&&(J.options.cursorBlink=!0)},Z=ye=>{ye.relatedTarget instanceof Node&&$.contains(ye.relatedTarget)||J&&(J.options.cursorBlink=!1)},ue=()=>{J&&R.current&&$.contains(document.activeElement)&&(J.options.cursorBlink=!0)},q=()=>{J&&(J.options.cursorBlink=!1)};return $.addEventListener("focusin",Re),$.addEventListener("focusout",Z),window.addEventListener("focus",ue),window.addEventListener("blur",q),Promise.all([Sm(),km()]).then(([{Xterm:ye,Fit:_e}])=>{if(G)return;const Y=x.current,ae=I.current,ne=y.current;J=new ye.Terminal({...yr(ae,ne,Y),...A.current??{}});const me=new _e.FitAddon;J.loadAddon(me),J.open($),m.current=J,g.current=me;const De=typeof navigator>"u"?"other":gm(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Ce=J;J.attachCustomKeyEventHandler(we=>{if(we.type!=="keydown")return!0;const X=Ce.getSelection(),xe=xm({key:we.key,code:we.code,ctrlKey:we.ctrlKey,shiftKey:we.shiftKey,metaKey:we.metaKey,altKey:we.altKey},De,nn(X));return xe==="copy"?(mi(X),!1):xe==="paste"?(gi().then(ee=>{ee&&m.current===Ce&&Ce.paste(ee)}),!1):xe!=="ignore"}),Me=[J.onData(we=>h.current(we))],se=new ResizeObserver(()=>{fe&&clearTimeout(fe),fe=setTimeout(ce,80)}),se.observe($),ce(),ke=requestAnimationFrame(ce)}),()=>{G=!0;const ye=document.activeElement;ye instanceof HTMLElement&&$.contains(ye)&&(ye.blur(),window.Capacitor?.getPlatform?.()==="android"&&cs(async()=>{const{Keyboard:Y}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:Y}},__vite__mapDeps([114,115])).then(({Keyboard:Y})=>Y.hide()).catch(()=>{})),se?.disconnect(),fe&&clearTimeout(fe),ke!==null&&cancelAnimationFrame(ke),$.removeEventListener("focusin",Re),$.removeEventListener("focusout",Z),window.removeEventListener("focus",ue),window.removeEventListener("blur",q),Me.forEach(_e=>_e.dispose()),J?.dispose(),m.current=null,g.current=null,k.current=null,N.current=null,j.current="",w.current=!1,C.current+=1,P.current=!1}},[ce,B]),i.useEffect(()=>{const $=m.current;$&&($.options.theme=yr(a,l,o).theme,$.options.fontFamily=yr(a,l,o).fontFamily,$.options.fontSize=l)},[a,l,o]),i.useEffect(()=>{const $=m.current,G=b.current;!$||!G||($.options.cursorBlink=f&&document.hasFocus()&&G.contains(document.activeElement))},[f,M]),i.useEffect(()=>{if(!m.current)return;if(s.length===0){N.current!==null&&z();return}const G=N.current;let J=-1;if(G!==null){for(let ke=s.length-1;ke>=0;ke-=1){const Me=s[ke].id;if(Me===G){J=ke;break}if(Me<G)break}if(J<0){z();return}}const se=J<0,fe=J>=0?s.slice(J+1):s;j.current+=fe.map(ke=>se?ke.replayData??ke.data:ke.data).join(""),N.current=s.at(-1)?.id??null,Q()},[s,Q,M,z]),i.useEffect(()=>{if(!d||!f)return;const $=requestAnimationFrame(()=>m.current?.focus());return()=>cancelAnimationFrame($)},[d,f,M,e]),i.useEffect(()=>{const $=b.current,G=m.current;if(!u||!$||!G)return;let J=null,se=null,fe="idle",ke=0,Me=0,Re=0,Z=0,ue=null;const q=Math.max(12,l+2),ye=()=>{window.Capacitor?.getPlatform?.()==="android"&&cs(async()=>{const{Keyboard:xe}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:xe}},__vite__mapDeps([114,115])).then(({Keyboard:xe})=>xe.show()).catch(()=>{})},_e=()=>{se&&(clearTimeout(se),se=null)},Y=(X,xe)=>{const ee=$.querySelector("canvas");return ee?ym(X,xe,ee.getBoundingClientRect(),G.cols,G.rows):null},ae=(X,xe)=>{const ee=$.querySelector("canvas");if(!ee)return;const Ae=ee.getBoundingClientRect(),Ue=Ae.left+(xe.column+.5)/G.cols*Ae.width,Ye=Ae.top+(xe.row+.5)/G.rows*Ae.height;ee.dispatchEvent(new MouseEvent(X,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:Ue,clientY:Ye}))},ne=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},me=X=>{X.pointerType!=="touch"||J!==null||(J=X.pointerId,fe="pending",ke=X.clientX,Me=X.clientY,Re=X.clientY,Z=0,ue=null,$.setPointerCapture(X.pointerId),se=setTimeout(()=>{if(se=null,J!==X.pointerId||fe!=="pending")return;const xe=Y(ke,Me);if(!xe)return;const ee=G.buffer.active,Ae=Math.max(0,ee.length-G.rows-ee.viewportY+xe.row),Ue=ee.getLine(Ae),Ye=Array.from({length:G.cols},(Oe,Fe)=>Ue?.getCell(Fe)?.getChars()??""),Se=wm(Ye,xe.column),te={column:Se.startColumn,row:xe.row};ue={column:Se.endColumn,row:xe.row},fe="selecting",ae("mousedown",te),ae("mousemove",ue)},350))},De=X=>{if(J!==X.pointerId)return;if(fe==="selecting"){const Ae=Y(X.clientX,X.clientY);Ae&&(!ue||Ae.column!==ue.column||Ae.row!==ue.row)&&(ue=Ae,ae("mousemove",Ae)),X.cancelable&&X.preventDefault();return}if(fe==="pending"){if(Math.hypot(X.clientX-ke,X.clientY-Me)<8)return;_e(),fe="scrolling"}if(fe!=="scrolling")return;const xe=Re-X.clientY;Re=X.clientY,Z+=xe;const ee=Math.trunc(Z/q);ee&&(G.scrollLines(ee),Z-=ee*q),X.cancelable&&X.preventDefault()},Ce=X=>{if(J!==X.pointerId)return;const xe=fe==="pending",ee=fe==="selecting";_e(),$.hasPointerCapture(X.pointerId)&&$.releasePointerCapture(X.pointerId),J=null,fe="idle",ee&&ne(),xe&&(G.focus(),ye())},we=X=>{if(J!==X.pointerId)return;const xe=fe==="selecting";_e(),$.hasPointerCapture(X.pointerId)&&$.releasePointerCapture(X.pointerId),J=null,fe="idle",xe&&ne()};return $.addEventListener("pointerdown",me),$.addEventListener("pointermove",De,{passive:!1}),$.addEventListener("pointerup",Ce),$.addEventListener("pointercancel",we),()=>{_e(),$.removeEventListener("pointerdown",me),$.removeEventListener("pointermove",De),$.removeEventListener("pointerup",Ce),$.removeEventListener("pointercancel",we)}},[u,l,M]),i.useImperativeHandle(p,()=>({focus:()=>m.current?.focus(),fit:ce,getSelection:()=>{const $=m.current,G=$?.getSelectionPosition(),J=$?.getSelection()??"";return!G||!J.trim()?null:{text:J,startLine:G.start.y+1,endLine:G.end.y+1}}}),[ce]),t.jsxs(ro,{open:L,onOpenChange:T,children:[t.jsx(oo,{render:t.jsx("div",{ref:b,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:Ie})}),t.jsxs(io,{className:"min-w-[180px]",children:[t.jsxs(Us,{disabled:!U,onClick:O,children:[t.jsx(D,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),t.jsxs(Us,{onClick:de,children:[t.jsx(D,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),t.jsx(ka,{}),t.jsx(Us,{onClick:he,children:"Select All"})]})]})});Ka.displayName="TerminalViewport";const Am=({directory:e,tabId:s,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:a,terminal:l,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,lastViewportSizeRef:p,onInput:b,controllerRef:m})=>{const g=ge(y=>e&&s?y.getBuffer(e,s).chunks:On.chunks),h=i.useRef(null),v=o&&a,x=i.useCallback(y=>{h.current=y,m&&(m.current=o?y:m.current),!o&&m&&m.current===y&&(m.current=null)},[m,o]);i.useEffect(()=>{if(!o||!a)return;const y=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(y)},[o,a,r,n]);const I=i.useCallback((y,k)=>{if(!o)return;const A=p.current;(!A||A.cols!==y||A.rows!==k)&&(p.current={cols:y,rows:k}),n&&l.resize({sessionId:n,cols:y,rows:k}).catch(()=>{})},[o,p,n,l]);return t.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:t.jsx(Ka,{ref:x,sessionKey:r,chunks:g,onInput:b,onResize:I,theme:c,fontFamily:u,fontSize:d,enableTouchScroll:f,autoFocus:v,isVisible:v},r)})},Nm=({items:e,activeId:s,onSelect:n,onClose:r,onCreate:o,disabled:a=!1})=>{const l=e.find(c=>c.id===s)??e[0]??null;return t.jsxs(Lt,{modal:!1,children:[t.jsx(Bt,{asChild:!0,children:t.jsxs("button",{type:"button",disabled:a,title:l?`Switch terminal, current: ${l.label}`:"Switch terminal","aria-label":l?`Switch terminal, current: ${l.label}`:"Switch terminal",className:_(Ni({size:"sm"}),"min-w-0 max-w-full"),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l?.icon??t.jsx(D,{name:"terminal",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:l?.label??"Terminal"})]}),t.jsx(D,{name:"arrow-down-s",className:"size-3.5 shrink-0"})]})}),t.jsxs(_t,{align:"start",className:"w-64",children:[e.map(c=>{const u=c.id===(l?.id??s);return t.jsxs(st,{title:c.title??c.label,onClick:()=>n(c.id),className:"group/tab min-w-0",children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,t.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),u?t.jsx(D,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,t.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:d=>{d.preventDefault(),d.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:t.jsx(D,{name:"close",className:"size-3"})})]},c.id)}),t.jsx(Ns,{}),t.jsxs(st,{onClick:o,children:[t.jsx(D,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},Im=({isTouchTerminal:e,activeModifier:s,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const a=e?"lg":"xs",l=e?"w-10 p-0":"w-9 p-0",c=u=>{e&&u.preventDefault()};return t.jsxs(t.Fragment,{children:[t.jsx(Te,{type:"button",size:a,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[t.jsx(D,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Te,{type:"button",size:a,variant:"chip","aria-pressed":s==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Te,{type:"button",size:a,variant:"chip","aria-pressed":s==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[t.jsx(D,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[t.jsx(D,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[t.jsx(D,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[t.jsx(D,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Te,{type:"button",size:a,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[t.jsx(D,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Dm="\x1B",Rm=new RegExp(`${Dm}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Em=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Pm=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Mm=/Serving HTTP on .*? port (\d{2,5})/i,Tm=new Set([".",",",";",":","!","?"]),Fm=e=>{let s=e;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=s.slice(0,-1),a=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=o;continue}if(Tm.has(n)){s=s.slice(0,-1);continue}break}return s},bi=e=>{let s=Fm(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},Om=e=>{if(!e)return null;const s=e.replace(Rm,""),n=s.match(Mm);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=s.split(`
47
+ `);for(const o of r){if(!Pm.test(o))continue;const a=Array.from(o.matchAll(Em));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(bi(c[1])).port}catch{return!1}});return bi((l??a[0])[1])}return null},Lm=async(e,s=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,a=window.setTimeout(()=>o.abort(),s);try{const l=await Dt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},Bm={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},_m=(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 Bm[e]},Ha=e=>{const s=e[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},Um=(e,s)=>e&&(s==="ctrl"?Ha(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),Wa={cols:80,rows:24},xi={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class zm{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(s,n,r,o){if(!r)return;const a=`${this.tail}${r}`.replace(/\r\n|\r/g,`
48
+ `),l=a.split(`
49
+ `),c=a.endsWith(`
50
+ `)?l.join(`
51
+ `):l.slice(0,-1).join(`
52
+ `);if(this.tail=a.endsWith(`
53
+ `)?"":(l[l.length-1]??"").slice(-1024),!c)return;const u=Om(c);if(!u||this.pendingUrls.has(u))return;const d=this.probeGeneration;this.pendingUrls.add(u),Lm(u).then(f=>{if(this.pendingUrls.delete(u),!f||this.probeGeneration!==d)return;const p=ge.getState().getDirectoryState(s)?.tabs.find(b=>b.id===n);!p||p.previewUrlLocked||p.previewUrl===u||o(s,n,u,{locked:!1,autoOpened:!1})})}}const $m=(e,s)=>{if(s!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?Ha(o):null};function Gm({terminal:e,effectiveDirectory:s,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:a,terminalHydrated:l,terminalShell:c,terminalLoginShell:u,terminalAppearanceRef:d,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:b,tabs:m}){const g=ge(O=>O.ensureDirectory),h=ge(O=>O.setTabSessionId),v=ge(O=>O.setTabLifecycle),x=ge(O=>O.setConnecting),I=ge(O=>O.appendToBuffer),y=ge(O=>O.replaceBuffer),k=ge(O=>O.setTabPreviewUrl),[A,N]=i.useState(null),[j,w]=i.useState(!1),[C,R]=i.useState(!1),P=i.useRef(new Map),M=i.useRef(null),F=i.useRef(n),B=i.useRef(r),K=i.useRef(s),L=i.useRef(null),T=i.useRef(new Set),U=i.useRef(new Map),H=i.useCallback(()=>{const O=F.current;O&&U.current.get(O)?.reset()},[]);i.useEffect(()=>{B.current=r},[r]),i.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,d.current).catch(()=>{})},[d,e,r]),i.useEffect(()=>{F.current=n},[n]),i.useEffect(()=>{K.current=s},[s]);const ce=i.useCallback(()=>{for(const O of P.current.values())try{O()}catch{}P.current.clear(),M.current=null,R(!1)},[]);i.useEffect(()=>()=>{ce(),B.current=null},[ce]);const Q=i.useCallback((O,de,he)=>{let $=U.current.get(de);$||($=new zm,U.current.set(de,$)),$.scan(O,de,he,k)},[k]),z=i.useCallback((O,de,he)=>{if(P.current.has(he)){M.current=he;return}const $=e.connect(he,{onEvent:G=>{if(K.current===O)switch(G.type){case"snapshot":{F.current===de&&B.current===he?(x(O,de,!1),N(null),w(!1),R(!1),b()):x(O,de,!1),y(O,de,G.data??"",G.sequence??0),Q(O,de,G.data??""),G.status==="exited"&&v(O,de,"exited");break}case"reconnecting":{F.current===de&&(N(null),w(!1),R(!0));break}case"data":{G.data&&(I(O,de,G.data,G.sequence,G.replayData),Q(O,de,G.data));break}case"exit":{const J=typeof G.exitCode=="number"?G.exitCode:null,se=typeof G.signal=="number"?G.signal:null,ke=!!ge.getState().getDirectoryState(O)?.tabs.find(Me=>Me.id===de)?.label?.startsWith("Action:");I(O,de,`\\r\\n[Process exited${J!==null?` with code ${J}`:""}${se!==null?` (signal ${se})`:""}]\\r\\n`),v(O,de,"exited"),F.current===de&&(x(O,de,!1),N(ke?null:"Terminal session ended"),w(!1),R(!1));break}}},onError:(G,J)=>{if(K.current!==O)return;const se=F.current===de;if(!J){se&&(N(null),w(!1));return}if(G.code==="SESSION_NOT_FOUND"&&!ge.getState().getDirectoryState(O)?.tabs.find(ke=>ke.id===de)?.label?.startsWith("Action:")){se&&(N(null),w(!1),x(O,de,!1),R(!1)),h(O,de,null),v(O,de,"idle");return}se&&(R(!1),N(`Connection failed: ${G.message}`),w(!0),x(O,de,!1),v(O,de,"exited"),h(O,de,null))}});P.current.set(he,()=>$.close()),M.current=he},[I,b,y,Q,x,v,h,e]),Ie=i.useMemo(()=>m.map(O=>`${O.id}:${O.terminalSessionId??""}`).join(","),[m]);return i.useEffect(()=>{if(!l||!a||!s)return;const O=s,de=new Set;for(const he of m)he.terminalSessionId&&(de.add(he.terminalSessionId),z(O,he.id,he.terminalSessionId));for(const[he,$]of P.current)if(!de.has(he)){try{$()}catch{}P.current.delete(he)}},[Ie,m,s,l,a,z]),i.useEffect(()=>{let O=!1;if(!l||!a)return;if(!s){N(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const he=s;if(!K.current||K.current!==he)return;if(!ge.getState().getDirectoryState(he)){g(he);return}const G=ge.getState().getDirectoryState(he);if(!G||G.tabs.length===0)return;const J=G.activeTabId??G.tabs[0]?.id??null;if(!J)return;const se=G.tabs.find(ue=>ue.id===J)??G.tabs[0],fe=se?.terminalSessionId??null,ke=se?.lifecycle??"idle",Me=!!se?.label?.startsWith("Action:"),Re=ge.getState().getBuffer(he,J),Z=Re.byteLength>0||Re.chunks.length>0;if(!fe){if(ke==="exited"){x(he,J,!1);return}if(Me&&Z){x(he,J,!1);return}const ue=`${he}\0${J}`;if(T.current.has(ue))return;const q=L.current??Wa;T.current.add(ue),N(null),w(!1),R(!1),x(he,J,!0);try{const ye=await e.createSession({cwd:he,sessionId:J,cols:q.cols,rows:q.rows,shell:c,loginShell:u,...d.current});if(!ge.getState().getDirectoryState(he)?.tabs.find(ae=>ae.id===J)){try{await e.close(ye.sessionId)}catch{}return}h(he,J,ye.sessionId);const Y=L.current;Y&&(Y.cols!==q.cols||Y.rows!==q.rows)&&e.resize({sessionId:ye.sessionId,...Y}).catch(()=>{});return}catch(ye){const _e=ge.getState().getDirectoryState(he)?.tabs.find(Y=>Y.id===J);if(!_e||_e.terminalSessionId||(x(he,J,!1),K.current!==he||F.current!==J))return;N(ye instanceof Error?ye.message:"Failed to start terminal session"),w(!0),R(!1);return}finally{T.current.delete(ue)}}!fe||O||(B.current=fe)})(),()=>{O=!0}},[p,s,r,o,n,a,f,l,g,x,v,h,e,u,c,d]),{connectionError:A,setConnectionError:N,isFatalError:j,setIsFatalError:w,isReconnectPending:C,setIsReconnectPending:R,terminalIdRef:B,lastViewportSizeRef:L,directoryRef:K,activeTabIdRef:F,disconnectStream:ce,resetTerminalPreviewScan:H,startStream:z}}function Km({terminal:e,terminalIdRef:s,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:a,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:u}){const[d,f]=i.useState(null),p=i.useRef(null),b=i.useCallback(()=>{u||p.current?.focus()},[u]),m=i.useCallback(()=>{u||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[u]);i.useEffect(()=>{!o&&d!==null&&f(null)},[o,d]),i.useEffect(()=>{!c&&d!==null&&f(null)},[c,d]);const g=i.useCallback(y=>{if(!y||n)return;let k=y,A=!1;d&&y.length>0&&(k=Um(y,d),A=!0);const N=s.current;N&&(e.sendInput(N,k).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),A&&(f(null),b()))},[d,b,n,r,e,s]),h=i.useCallback((y,k)=>{const A=l.current;if((!A||A.cols!==y||A.rows!==k)&&(l.current={cols:y,rows:k}),!a)return;const N=s.current;N&&e.resize({sessionId:N,cols:y,rows:k}).catch(()=>{})},[a,l,e,s]),v=i.useCallback(y=>{f(k=>k===y?null:y),b()},[b]),x=i.useCallback(y=>{const k=_m(y,d);k&&(g(k),f(null),b())},[d,b,g]),I=i.useCallback(y=>{if(y.repeat)return;const k=y.key;if(!k||k==="Control"||k==="Meta"||k==="Alt"||k==="Shift")return;const A=k.length===1?k.toLowerCase():k;if(A in xi){y.preventDefault(),y.stopPropagation(),x(xi[A]);return}const N=$m(y,d);N&&(y.preventDefault(),y.stopPropagation(),g(N),f(null),b())},[d,b,x,g]);return i.useEffect(()=>{if(!(!o||!d||!c))return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[d,I,o,c]),{activeModifier:d,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:b,focusTerminalWhenWindowActive:m,handleViewportInput:g,handleViewportResize:h,handleModifierToggle:v,handleMobileKeyPress:x}}function Hm({terminal:e,effectiveDirectory:s,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:a,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:u,activeTabIdRef:d,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:b,setConnectionError:m,setIsFatalError:g,setIsReconnectPending:h}){const v=ge(M=>M.createTab),x=ge(M=>M.setActiveTab),I=ge(M=>M.closeTab),y=ge(M=>M.setTabSessionId),k=ge(M=>M.setTabLifecycle),[A,N]=i.useState(!1),j=i.useCallback(async()=>{if(!s||A)return;const M=ge.getState().getDirectoryState(s),F=n??M?.activeTabId??M?.tabs[0]?.id??null;if(!F)return;const B=M?.tabs.find(K=>K.id===F)?.terminalSessionId??null;if(!(!B||!e.restartSession)){N(!0),m(null),g(!1),h(!1),p();try{const K=c.current??Wa,L=await e.restartSession(B,{cwd:s,shell:o,loginShell:a,...K,...l.current});if(ge.getState().getDirectoryState(s)?.tabs.find(U=>U.id===F)?.terminalSessionId!==B||(y(s,F,L.sessionId),k(s,F,"running"),u.current!==s||d.current!==F))return;f.current=L.sessionId,b(s,F,L.sessionId)}catch(K){if(ge.getState().getDirectoryState(s)?.tabs.find(T=>T.id===F)?.terminalSessionId!==B||u.current!==s||d.current!==F)return;m(K instanceof Error?K.message:"Failed to restart terminal"),g(!1),h(!1),f.current=B,b(s,F,B)}finally{N(!1)}}},[n,d,u,s,r,A,c,p,m,g,h,k,y,b,e,l,f,a,o]),w=i.useCallback(async()=>{await j()},[j]),C=i.useCallback(()=>{if(!s)return;const M=v(s);x(s,M),m(null),g(!1),h(!1)},[v,s,x,m,g,h]),R=i.useCallback(M=>{s&&(x(s,M),m(null),g(!1),h(!1))},[s,x,m,g,h]),P=i.useCallback(M=>{if(!s)return;m(null),g(!1),h(!1);const F=ge.getState().getDirectoryState(s)?.tabs.find(B=>B.id===M)?.terminalSessionId;(async()=>{F&&await e.close(F),I(s,M)})().catch(B=>m(B instanceof Error?B.message:"Terminal session ended"))},[I,s,m,g,h,e]);return{isRestarting:A,handleRestart:j,handleHardRestart:w,handleCreateTab:C,handleSelectTab:R,handleCloseTab:P}}const xb=({visible:e,onCloseView:s,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Ys(),{currentTheme:a}=_i(),l=i.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground};const{monoFont:c}=Xc(),u=le(te=>te.terminalFontSize),d=le(te=>te.terminalShell),f=le(te=>te.terminalLoginShells.includes(te.terminalShell)),{isMobile:p,isTablet:b,hasTouchOnlyPointer:m}=Ws(),g=p||b,h=(g||m)&&o.platform==="web",v=!0,x=le(te=>te.showTerminalQuickKeysOnDesktop),I=g||x,y=Ne(te=>te.currentSessionId),k=Ne(te=>te.newSessionDraft),A=y!==null||k?.open===!0,N=Zc()??null,j=ge(te=>N?te.sessions.get(N):void 0),w=ge(te=>te.hasHydrated),C=le(te=>te.openContextPreview),R=i.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,v]),P=i.useMemo(()=>{if(j)return R?j.tabs.find(te=>te.id===R)??j.tabs[0]:j.tabs[0]},[j,R]),M=i.useMemo(()=>(j?.tabs??[]).map(te=>({icon:(()=>{const Oe=te.iconKey?ln[te.iconKey]??"terminal":"terminal";return t.jsx(D,{name:Oe,className:"h-4 w-4"})})(),id:te.id,label:te.label,title:te.label,closeLabel:"Close tab"})),[j?.tabs]),F=P?.terminalSessionId??null,B=P?.lifecycle??"idle",K=i.useMemo(()=>(j?.tabs??[]).map(te=>({id:te.id,terminalSessionId:te.terminalSessionId,label:te.label})),[j?.tabs]),L=P?.isConnecting??!1,T=P?.previewUrl??null,H=le(te=>te.activeMainTab)==="terminal",ce=e??H,[Q,z]=i.useState(ce);i.useEffect(()=>{ce&&z(!0)},[ce]);const{connectionError:Ie,setConnectionError:O,isFatalError:de,setIsFatalError:he,isReconnectPending:$,setIsReconnectPending:G,terminalIdRef:J,lastViewportSizeRef:se,directoryRef:fe,activeTabIdRef:ke,resetTerminalPreviewScan:Me,startStream:Re}=Gm({terminal:r,effectiveDirectory:N,activeTabId:R,terminalSessionId:F,terminalLifecycle:B,hasOpenedTerminalViewport:Q,terminalHydrated:w,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:v,hasActiveContext:A,tabs:K,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ue.current?.focus()}}),{activeModifier:Z,terminalControllerRef:ue,focusTerminalWhenWindowActive:q,handleViewportInput:ye,handleModifierToggle:_e,handleMobileKeyPress:Y}=Km({terminal:r,terminalIdRef:J,isReconnectPending:$,setConnectionError:O,showQuickKeys:I,isTerminalVisible:ce,lastViewportSizeRef:se,terminalSessionId:F,useTouchTerminalInput:h}),{isRestarting:ae,handleRestart:ne,handleHardRestart:me,handleCreateTab:De,handleSelectTab:Ce,handleCloseTab:we}=Hm({terminal:r,effectiveDirectory:N,activeTabId:R,enableTabs:v,terminalShell:d,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:se,directoryRef:fe,activeTabIdRef:ke,terminalIdRef:J,resetTerminalPreviewScan:Me,startStream:Re,setConnectionError:O,setIsFatalError:he,setIsReconnectPending:G});i.useEffect(()=>{if(!ce||h)return;if(typeof window>"u"){q();return}const te=window.requestAnimationFrame(()=>{q()});return()=>{window.cancelAnimationFrame(te)}},[R,q,ce,h]);const X=i.useMemo(()=>{const te=Zs[or].stack;if(typeof window>"u")return(Zs[c]??Zs[or]).stack;const Fe=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Fe&&Fe.trim().length>0?Fe.trim():(Zs[c]??Zs[or]).stack??te},[c]),xe=i.useMemo(()=>mm(a),[a]),ee=`${N??"no-dir"}::${R??"no-tab"}`;if(i.useEffect(()=>{if(!ce||h)return;const te=ue.current;if(!te)return;const Oe=()=>{te.fit()};if(typeof window<"u"){const Fe=window.requestAnimationFrame(()=>{Oe(),q()}),mt=[220,400].map(nt=>window.setTimeout(Oe,nt));return()=>{window.cancelAnimationFrame(Fe),mt.forEach(nt=>window.clearTimeout(nt))}}Oe()},[q,ce,h,ue,ee,F]),i.useEffect(()=>{if(!ce||!h)return;let te=null;const Oe=()=>{te!==null&&window.cancelAnimationFrame(te),te=window.requestAnimationFrame(()=>{te=null,ue.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Oe),()=>{window.removeEventListener("oc:keyboard-settled",Oe),te!==null&&window.cancelAnimationFrame(te)}},[ce,ue,ee,h]),!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(!N)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:ne,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Ae=!F||L||ae||$,Ue=Q,Ye=j?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx(Nm,{items:M,activeId:R,onSelect:Ce,onClose:we,onCreate:De})}),t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:_("shrink-0",g?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:De,title:"New tab","aria-label":"New tab",children:t.jsx(D,{name:"add",className:`${g?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ne()},disabled:ae,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(D,{name:"restart",className:"h-4 w-4"})}),T?t.jsxs(Te,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{N&&C(N,T)},title:"Open preview pane",children:[t.jsx(D,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,Se=t.jsx(Im,{isTouchTerminal:g,activeModifier:Z,disabled:Ae,onKeyPress:Y,onModifierToggle:_e});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",g?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[Ye?n?dc.createPortal(t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ye}),n):t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ye,s?t.jsx(Te,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:s,title:"Close terminal view","aria-label":"Close terminal view",children:t.jsx(D,{name:"close",className:"h-4 w-4"})}):null]}):null,!g&&I&&v&&j?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Se}):null,!g&&I&&!j?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Se}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:xe.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Ue&&N&&j?j.tabs.map(te=>{const Oe=te.id===R;return t.jsx(Am,{directory:N,tabId:te.id,sessionId:te.terminalSessionId,sessionKey:`${N}::${te.id}`,isActive:Oe,isTerminalVisible:ce,terminal:r,theme:xe,fontFamily:X,fontSize:u,enableTouchScroll:h,lastViewportSizeRef:se,onInput:ye,controllerRef:ue},te.id)}):null}),!$&&Ie&&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:Ie}),de&&g&&t.jsx(Te,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:me,disabled:ae,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),g&&I?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:Se})}):null]})},Wm=48,Ym=96,bt=(e,...s)=>{try{e?.(...s)}catch{}},wr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},yb=(e,s)=>{const n=i.useRef(s);n.current=s;const r=s.enabled;i.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const a=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?Ym:Wm;let u=!1,d=!1,f=!1,p=null,b=!1,m=0,g=0,h=0,v=0;const x=()=>{u=!1,d=!1,f=!1,p=null},I=()=>{const C=n.current,R=p,P=b;d&&R&&(bt(R==="left"?C.onLeftProgress:C.onRightProgress,P?1:0),bt(C.onDragEnd,R,P)),x()},y=()=>{I(),d||x()},k=C=>{const R=n.current;if(R.enabled===!1){d&&p?I():x();return}if(C.touches.length!==1){d&&p?I():x();return}const P=C.touches[0],M=o.getBoundingClientRect(),F=o.clientWidth,B=!!R.leftOpen,K=!!R.rightOpen,L=T=>im(T,o);if(B||K){if(L(C.target)){x();return}if(B&&K){const T=P.clientX<=M.left+c;P.clientX>=M.right-c?(p="right",b=!0):T?(p="left",b=!0):(p=B?"left":"right",b=!0)}else B?(p="left",b=!0):(p="right",b=!0);v=wr(p==="left"?R.leftWidth:R.rightWidth,F),v<10&&(v=F||window.innerWidth||320),v<10&&(v=320),u=!0}else{if(L(C.target)){x();return}p=null,b=!1,v=0,u=!0}m=P.clientX,g=P.clientY,h=Date.now(),d=!1,f=!1},A=C=>{if(!u)return;if(C.touches.length!==1){y();return}const R=C.touches[0],P=R.clientX-m,M=R.clientY-g;if(!f){if(Math.abs(P)<ui&&Math.abs(M)<ui)return;if(Math.abs(M)>Math.abs(P)*tn){x();return}if(!p){const K=n.current;p=P>0?"left":"right",v=wr(p==="left"?K.leftWidth:K.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(p==="left"){if(!b&&P<=0){x();return}if(b&&P>=0){x();return}}else{if(!b&&P>=0){x();return}if(b&&P<=0){x();return}}f=!0,d=!0,bt(n.current.onDragStart,p)}if(!d)return;C.cancelable&&C.preventDefault();const F=n.current,B=fi(p,b,P,v);bt(p==="left"?F.onLeftProgress:F.onRightProgress,B)},N=(C,R)=>{if(!u){x();return}const P=C-m,M=R-g;if(!p&&!b&&Math.abs(P)>=Fn&&Math.abs(M)<=Math.abs(P)*tn){const U=n.current;p=P>0?"left":"right",v=wr(p==="left"?U.leftWidth:U.rightWidth,o.clientWidth),v<10&&(v=window.innerWidth||320)}if(!p){x();return}const F=Math.max(1,Date.now()-h),B=n.current;if(!d){const U=Math.abs(P),H=Math.abs(M);U>=Fn&&H<=U*tn?p==="left"&&!b&&P>0?(bt(B.onLeftProgress,1),bt(B.onLeftOpen)):p==="right"&&!b&&P<0?(bt(B.onRightProgress,1),bt(B.onRightOpen)):bt(p==="left"?B.onLeftProgress:B.onRightProgress,b?1:0):bt(p==="left"?B.onLeftProgress:B.onRightProgress,b?1:0);const ce=p;x(),bt(B.onDragEnd,ce);return}const K=fi(p,b,P,v),L=rm({side:p,isOpenAtStart:b,dx:P,dt:F,progress:K}),T=p;bt(T==="left"?L?B.onLeftOpen:B.onLeftClose:L?B.onRightOpen:B.onRightClose),x(),bt(B.onDragEnd,T,L)},j=C=>{const R=C.changedTouches[0];if(!R){x();return}const P=R.clientX-m,M=R.clientY-g;u&&(d||Math.abs(P)>=Fn&&Math.abs(M)<=Math.abs(P)*tn)&&C.cancelable&&C.preventDefault(),N(R.clientX,R.clientY)},w=()=>{y()};return o.addEventListener("touchstart",k,{passive:!0}),o.addEventListener("touchmove",A,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{d&&p&&I()}catch{}o.style.touchAction=a,o.removeEventListener("touchstart",k),o.removeEventListener("touchmove",A),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",w)}},[e,r])};function wb({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(D,{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 qm=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,Qm=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Hn(s,n)?null:e,vr=()=>vs.filter(e=>Tr.has(e.id)).map(e=>({...Hi(e)})),Vm=()=>{if(typeof window>"u")return Fr;const e=window.localStorage.getItem("openInAppId");return e&&Mr(e)?e:Fr};let Sr=!1,Os=!1,as=!1,ls=0,cn=null;const wi=()=>{cn&&(clearTimeout(cn),cn=null)},xs=hs()((e,s)=>({selectedAppId:Vm(),availableApps:vr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Sr||typeof window>"u")return;Sr=!0;const n=(u,d=!0)=>{if(!Array.isArray(u)||u.length===0){e({availableApps:vr(),hasLoadedApps:d});return}const f=new Set(u.map(g=>g.name)),p=new Map(u.map(g=>[g.name,g.iconDataUrl??void 0])),m=vs.filter(g=>f.has(g.appName)||Tr.has(g.id)).map(g=>({...Hi(g),iconDataUrl:p.get(g.appName)}));e({availableApps:m,hasLoadedApps:!0})},r=async u=>{if(!zs()||!un()||Os||s().hasLoadedApps&&!u)return;const f=vs.map(p=>p.appName);wi(),Os=!0,as=!1,e({isScanning:!0});try{const{apps:p,success:b,hasCache:m,isCacheStale:g}=await Lo(f,u),h=b&&!m&&p.length===0&&ls<3;if(e({isCacheStale:m?g:!1}),n(p,b?!h:!1),b){if(h){const x=[800,1600,3200][ls]??3200;ls+=1,as=!0,cn=setTimeout(()=>{r()},x);return}ls=0,as=!1;return}if(ls<3){const x=[1e3,3e3,7e3][ls]??7e3;ls+=1,as=!0,cn=setTimeout(()=>{r()},x)}}finally{Os=!1,as||e({isScanning:!1})}};r();const o=u=>{const d=u.detail,f=d&&typeof d.openInAppId=="string"&&d.openInAppId.length>0&&Mr(d.openInAppId)?d.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},a=()=>{r()},l=u=>{const d=u.detail;Array.isArray(d)&&(ls=3,as=!1,e({isScanning:!1,isCacheStale:!1}),n(d))};window.addEventListener("pichamber:settings-synced",o),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(Sr||s().initialize(),!zs()||!un()||Os||s().hasLoadedApps&&!n)return;const o=vs.map(a=>a.appName);wi(),n&&e({hasLoadedApps:!1}),Os=!0,as=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await Lo(o,n),u=new Set(a.map(b=>b.name)),d=new Map(a.map(b=>[b.name,b.iconDataUrl??void 0])),p=vs.filter(b=>u.has(b.appName)||Tr.has(b.id)).map(b=>({...b,iconDataUrl:d.get(b.appName)}));e({availableApps:p.length>0?p:vr(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Os=!1,as||e({isScanning:!1})}},selectApp:async n=>{Mr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Zr({openInAppId:n}))}})),Jm="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",Xm="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",jr=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Jm:e.id==="terminal"?Xm:void 0}),vi=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,o]=i.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:()=>o(!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})},Zm=({directory:e,className:s})=>{const n=xs(g=>g.selectedAppId),r=xs(g=>g.availableApps),o=xs(g=>g.isCacheStale),a=xs(g=>g.isScanning),l=xs(g=>g.initialize),c=xs(g=>g.loadInstalledApps),u=xs(g=>g.selectApp);i.useEffect(()=>{l()},[l]);const d=zs()&&un(),f=i.useMemo(()=>{const g=r.find(h=>h.id===n)??r.find(h=>h.id===Fr)??r[0]??vs[0];return jr(g||vs[0])},[r,n]);if(!d||!e||r.length===0)return null;const p=async g=>{await _d(e,g.id,g.appName)||await Gi(e,g.appName)},b=async g=>{await u(g.id),await p(g)},m=async()=>{(await As(e)).ok&&oe.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:()=>{p(f)},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 ${f.label}`,children:t.jsx(vi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),t.jsxs(Lt,{children:[t.jsx(Bt,{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(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(_t,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(st,{className:"flex items-center gap-2",onClick:()=>{m()},children:[t.jsx(D,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Ns,{}),r.map(g=>{const h=jr(g);return t.jsxs(st,{className:"flex items-center gap-2",onClick:()=>{b(g)},children:[t.jsx(vi,{label:g.label,iconDataUrl:g.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:g.label}),f.id===g.id?t.jsx(D,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},g.id)}),o?t.jsxs(st,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(D,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},eg="\x1B",tg=new RegExp(`${eg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),sg=/https?:\/\/[^\s<>'"`]+/gi,jt="__pichamber_auto_discover_preview__",ng=15e3,rg=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},og=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}},ig=e=>{const n=e.replace(tg,"").match(sg);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&o.push({raw:a,parsed:l})}catch{}if(o.length>0){const a=l=>{const{parsed:c}=l,u=c.hostname.toLowerCase(),d=u==="localhost"||u==="127.0.0.1"||u==="0.0.0.0"||u==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,b=f==="/"||f==="",m=!!(c.search||c.hash);let g=0;return d&&(g+=50),b&&(g+=30),g-=Math.min(p*5,20),m&&(g-=10),g};return o.sort((l,c)=>a(c)-a(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},ag=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],lg=["dev","start","preview","serve"];async function cg(e,s,n){if(!e)return null;const r=fg(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=hg(n);if(o){const a=await pg(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await dg(e)){const o=await ug(),a=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function dg(e){const s=`${e}/index.html`,n=await Kn(s,e);return typeof n=="string"&&n.trim().length>0}async function ug(){try{const e=await Dt("/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 fg(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(lg.some(o=>n.includes(o)))return s}return null}function hg(e){for(const{pattern:s}of ag)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function pg(e){const s=await Kn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const a=await Kn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return o}return"npm"}async function Kn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),o=await Dt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=es()?.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 Dt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function mg(e){try{const s=await Kn(`${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 gg=(e,s,n)=>new Promise(r=>{let o=!1,a=null,l=null;const c=u=>{o||(o=!0,l&&clearTimeout(l),a?.close(),r(u))};a=e.connect(s,{onEvent:u=>{(u.type==="exit"||u.type==="snapshot"&&u.status==="exited")&&c(!0)},onError:(u,d)=>{d&&c(!0)}}),o?a.close():l=setTimeout(()=>c(!1),n)});function bg({projectRef:e,directory:s,allowMobile:n=!1}){const{currentTheme:r}=_i(),{terminal:o}=Ys(),{isMobile:a}=Ws(),l=le(Y=>Y.terminalShell),c=le(Y=>Y.terminalLoginShells.includes(Y.terminalShell)),u=le(Y=>Y.setSettingsPage),d=le(Y=>Y.setSettingsDialogOpen),f=le(Y=>Y.setSettingsProjectsSelectedId),p=le(Y=>Y.openContextPreview),b=ge(Y=>Y.ensureDirectory),m=ge(Y=>Y.setTabLabel),g=ge(Y=>Y.setTabIconKey),h=ge(Y=>Y.setActiveTab),v=ge(Y=>Y.setConnecting),x=ge(Y=>Y.setTabSessionId),I=ge(Y=>Y.setTabPreviewUrl),y=ge(Y=>Y.projectActionRuns),k=ge(Y=>Y.setProjectActionRun),A=ge(Y=>Y.updateProjectActionRunStatus),N=ge(Y=>Y.removeProjectActionRun),[j,w]=i.useState([]),[C,R]=i.useState(null),[P,M]=i.useState(!1),F=i.useRef({}),B=i.useRef({}),K=i.useRef({}),L=i.useRef({}),T=i.useRef(new Set),U=i.useRef(0),H=e?.id??null,ce=e?.path??"",Q=i.useMemo(()=>H?{id:H,path:ce}:null,[H,ce]),z=i.useCallback(async Y=>{await Ai(Y)},[]),Ie=i.useCallback(async()=>{if(!Q)return;const Y=U.current+1;U.current=Y,M(!0);try{const ae=await Cr(Q);if(U.current!==Y)return;const ne=ae.actions;w(ne),R(me=>me===jt||me&&ne.some(De=>De.id===me)?me:null)}catch{if(U.current!==Y)return}finally{U.current===Y&&M(!1)}},[Q]),O=i.useMemo(()=>Sa(s||Q?.path||""),[s,Q?.path]),de=i.useMemo(()=>C?j.find(Y=>Y.id===C)??null:null,[j,C]),he=i.useMemo(()=>({id:jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),$=!a,G=i.useMemo(()=>$?[he,...j]:j,[j,he,$]);i.useEffect(()=>{Ie()},[Ie]),i.useEffect(()=>{if(typeof window>"u")return;const Y=ae=>{const ne=ae.detail;H&&(ne?.projectId&&ne.projectId!==H||Ie())};return window.addEventListener($r,Y),()=>{window.removeEventListener($r,Y)}},[Ie,H]),i.useEffect(()=>{C&&(C===jt&&$||j.some(Y=>Y.id===C)||R(null))},[j,$,C]),i.useEffect(()=>{const Y=()=>{const ae=ge.getState(),ne=ae.sessions,me=ae.projectActionRuns;for(const[De,Ce]of Object.entries(me)){const X=ne.get(Ce.directory)?.tabs.find(Fe=>Fe.id===Ce.tabId);if(!X||X.terminalSessionId!==Ce.sessionId){N(De);continue}const xe=B.current[De]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};B.current[De]=xe;const ee=G.find(Fe=>Fe.id===Ce.actionId),Ae=ae.getBuffer(Ce.directory,Ce.tabId).chunks;if(!ee||Ae.length===0)continue;const Ue=Ae.filter(Fe=>xe.lastSeenChunkId===null||Fe.id>xe.lastSeenChunkId);if(Ue.length===0)continue;const Ye=Ue.map(Fe=>Fe.data).join(""),Se=`${xe.tail}${Ye}`,te=!xe.openedUrl&&ee.autoOpenUrl===!0?ig(Se):null,Oe=Ue[Ue.length-1]?.id??xe.lastSeenChunkId;if(xe.lastSeenChunkId=Oe,xe.tail=Se.slice(-512),te)if(xe.openedUrl=!0,xe.openInPreview){const Fe=me[De];Fe&&(I(Fe.directory,Fe.tabId,te,{locked:!1,autoOpened:!1}),Fe.status==="waiting-for-preview"&&A(De,"running"),window.clearTimeout(L.current[De]),delete L.current[De],p(Fe.directory,te))}else z(te),oe.success("Opened URL from action output");B.current[De]=xe}for(const De of Object.keys(B.current))me[De]||(delete B.current[De],window.clearTimeout(L.current[De]),delete L.current[De])};return Y(),ge.subscribe((ae,ne)=>{(ae.sessions!==ne.sessions||ae.buffers!==ne.buffers)&&Y()})},[G,p,z,y,N,I,A]);const J=i.useCallback(async(Y,ae={})=>{if(!O)throw new Error("No active directory");const ne=ts(O,Y.id);b(O);const me=ge.getState(),De=me.getDirectoryState(O);let Ce=F.current[ne]||null;const we=Ce?!!De?.tabs.some(ee=>ee.id===Ce):!1;(!Ce||!we)&&(Ce=me.createTab(O),F.current[ne]=Ce),m(O,Ce,`Action: ${Y.name}`),g(O,Ce,Y.icon||"play"),h(O,Ce),ae.revealTerminal!==!1&&le.getState().openContextPanelTab(O,{mode:"terminal"});const xe=ge.getState().getDirectoryState(O)?.tabs.find(ee=>ee.id===Ce);return{key:ne,tabId:Ce,sessionId:xe?.terminalSessionId??null}},[b,O,h,g,m]),se=i.useCallback(async Y=>{if(!n&&a)return;if(!O){oe.error("No active directory for action");return}const ae=ts(O,Y.id),ne=y[ae];if(!(ne&&ne.status==="running")&&!T.current.has(ae)){T.current.add(ae);try{const me=Y.id===jt?await(async()=>{const[Se,te]=await Promise.all([Cr({id:Q?.id??"",path:O}),mg(O)]),Oe=await cg(O,Se.actions,te);if(!Oe)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:jt,name:"Auto-discover",command:Oe.command,icon:"scan-2",autoOpenUrl:!0,openUrl:Oe.previewUrlHint||""}})():Y,De=me.autoOpenUrl===!0&&(me.openUrl||"").trim().length>0,Ce=!De&&Y.id!==jt,{key:we,tabId:X,sessionId:xe}=await J(me,{revealTerminal:Ce});let ee=xe;if(!ee){v(O,X,!0);try{ee=(await o.createSession({cwd:O,sessionId:X,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(O,X,ee)}finally{v(O,X,!1)}}if(!ee)throw new Error("Failed to create terminal session");K.current[we]?.(),v(O,X,!0);const Ae=o.connect(ee,{onEvent:Se=>{Se.type==="snapshot"&&(ge.getState().replaceBuffer(O,X,Se.data??"",Se.sequence??0),ge.getState().setConnecting(O,X,!1)),Se.type==="data"&&typeof Se.data=="string"&&Se.data.length>0&&ge.getState().appendToBuffer(O,X,Se.data,Se.sequence,Se.replayData),Se.type==="exit"&&(ge.getState().setTabLifecycle(O,X,"exited"),ge.getState().setConnecting(O,X,!1),ge.getState().removeProjectActionRun(we),delete B.current[we],K.current[we]?.(),delete K.current[we],window.clearTimeout(L.current[we]),delete L.current[we])},onError:(Se,te)=>{ge.getState().setConnecting(O,X,!1),te&&(ge.getState().setTabLifecycle(O,X,"exited"),ge.getState().setTabSessionId(O,X,null),ge.getState().removeProjectActionRun(we))}});K.current[we]=Ae.close;const Ue=me.autoOpenUrl?og(me.openUrl):null;k({key:we,directory:O,actionId:me.id,tabId:X,sessionId:ee,status:me.id===jt&&!Ue?"waiting-for-preview":"running"}),window.clearTimeout(L.current[we]),delete L.current[we],me.id===jt&&!Ue&&(L.current[we]=window.setTimeout(()=>{const Se=ge.getState(),te=Se.projectActionRuns[we];Se.updateProjectActionRunStatus(we,"running"),te&&(Se.setActiveTab(te.directory,te.tabId),le.getState().openContextPanelTab(te.directory,{mode:"terminal"})),delete L.current[we]},ng)),B.current[we]={lastSeenChunkId:null,openedUrl:!!Ue||De,tail:"",openInPreview:me.id===jt};const Ye=rg(me.command.trim().replace(/\r\n|\r/g,`
54
+ `));await o.sendInput(ee,`${Ye}\r`),Ue?(I(O,X,Ue,{locked:!0,autoOpened:!0}),p(O,Ue),oe.success("Opened action URL")):De?(I(O,X,null,{locked:!0}),oe.error("Invalid custom URL format")):I(O,X,null,{locked:!1,autoOpened:!1})}catch(me){N(ae),delete B.current[ae],K.current[ae]?.(),delete K.current[ae],window.clearTimeout(L.current[ae]),delete L.current[ae],oe.error(me instanceof Error?me.message:"Failed to run action")}finally{T.current.delete(ae)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,J,n,a,O,c,l,p,y,N,v,k,I,x,Q?.id,o]),fe=i.useCallback(async Y=>{const ae=ts(O,Y.id),ne=y[ae];if(!ne)return;A(ae,"stopping");const me=gg(o,ne.sessionId,1e3);try{await o.sendInput(ne.sessionId,"")}catch{}const De=await me;if(ge.getState().getDirectoryState(ne.directory)?.tabs.find(X=>X.id===ne.tabId)?.terminalSessionId===ne.sessionId&&!De){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:ne.sessionId})}catch{}else try{await o.close(ne.sessionId)}catch{}x(ne.directory,ne.tabId,null)}N(ae),delete B.current[ae],K.current[ae]?.(),delete K.current[ae],window.clearTimeout(L.current[ae]),delete L.current[ae]},[O,y,N,x,o,A]),ke=i.useCallback(()=>{const Y=de??G[0];if(!Y)return;const ae=ts(O,Y.id),ne=y[ae];if(ne?.status!=="stopping"){if(ne){fe(Y);return}se(Y)}},[G,O,se,y,de,fe]),Me=i.useCallback((Y,ae=!1)=>{if(R(Y.id),!ae){se(Y);return}const ne=ts(O,Y.id),me=y[ne];if(me?.status!=="stopping"){if(me){fe(Y);return}se(Y)}},[O,se,y,fe]),Re=i.useCallback(()=>{Q?.id&&(f(Q.id),u("projects"),d(!0))},[d,u,f,Q?.id]),Z=de??G[0]??null,ue=Z?y[ts(O,Z.id)]:null,q=ge(Y=>ue?Y.sessions.get(ue.directory)?.tabs.find(ae=>ae.id===ue.tabId)?.previewUrl??null:null),ye=!!((n||!a)&&Q&&O),_e=de??G[0]??null;return{shouldRender:ye,isLoading:P,normalizedDirectory:O,resolvedSelected:_e,displayActions:G,projectActionRuns:y,selectedRunPreviewUrl:q,handlePrimaryClick:ke,handleSelectAction:Me,openProjectActionsSettings:Re,openContextPreview:p}}const Si=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:a,isLoading:l,normalizedDirectory:c,resolvedSelected:u,displayActions:d,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:b,handleSelectAction:m,openProjectActionsSettings:g,openContextPreview:h}=bg({projectRef:e,directory:s,allowMobile:o});if(!a||!u)return null;const v=u.icon||"play",x=u.id===jt?"scan-2":ln[v]||"play",I=ts(c,u.id),y=f[I],k=y?.status==="stopping",A=y?.status==="waiting-for-preview",N=!!(y&&p),j=()=>{!y||!p||h(y.directory,p)},w=u.id===jt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",disabled:l||k,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:b,"aria-label":y?`Stop ${u.name}`:`Run ${u.name}`,children:k||A?t.jsx(D,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):y?t.jsx(D,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(D,{name:x,className:"h-5 w-5"})})}),w?t.jsx(He,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),N?t.jsxs(Ge,{children:[t.jsx(Ke,{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:j,children:t.jsx(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(He,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Lt,{children:[t.jsx(Bt,{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(D,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(_t,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(st,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ns,{}),d.map(C=>{const R=C.icon||"play",P=C.id===jt?"scan-2":ln[R]||"play",M=ts(c,C.id),F=f[M],B=!!F,K=F?.status==="stopping";return t.jsxs(st,{className:"flex items-center gap-2",onClick:()=>{m(C,!0)},children:[t.jsx(D,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:C.name}),K||F?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):B?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},C.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(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:b,disabled:l||k,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":y?`Stop ${u.name}`:`Run ${u.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:k||A?t.jsx(D,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):y?t.jsx(D,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(D,{name:x,className:"h-4 w-4"})})})}),w?t.jsx(He,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),N?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:j,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(D,{name:"global",className:"h-4 w-4"})})}),t.jsx(He,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(Lt,{children:[t.jsx(Bt,{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(D,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(_t,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(st,{className:"flex items-center gap-2",onClick:g,children:[t.jsx(D,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Ns,{}),d.map(C=>{const R=C.icon||"play",P=C.id===jt?"scan-2":ln[R]||"play",M=ts(c,C.id),F=f[M],B=!!F,K=F?.status==="stopping";return t.jsxs(st,{className:"flex items-center gap-2",onClick:()=>{m(C,!0)},children:[t.jsx(D,{name:P,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:C.name}),K||F?.status==="waiting-for-preview"?t.jsx(D,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):B?t.jsx(D,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},C.id)})]})]})]})},xg=i.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:o,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(Lt,{children:[t.jsx(Bt,{asChild:!0,children:t.jsx("button",{type:"button",className:_(bn,"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:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(_t,{align:"end",className:"w-64",children:[t.jsx(ed,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Ns,{}),r.map(u=>{const d=u.user,f=!!u.current,p=u.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(st,{className:"gap-2",disabled:l,onSelect:()=>{f||c(u.id)},children:[d?.avatarUrl?t.jsx("img",{src:d.avatarUrl,alt:d.login?`${d.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(D,{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:d?.name?.trim()||d?.login||"GitHub"}),d?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:d.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:p})]}):null]}),f?t.jsx(D,{name:"check",className:"h-4 w-4 text-primary"}):null]},u.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:o?t.jsx("img",{src:o,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(D,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),yg=i.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:u,remoteUpdateInfo:d,remoteUpdateChecking:f,remoteUpdateError:p,onOpenRemoteUpdate:b}){return t.jsxs(Lt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx(Bt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(bn,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(D,{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(He,{children:t.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),t.jsx(_t,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[o?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:d?.available?`Version ${d.version||""} is available for this instance.`:f?"Looking for updates...":p||"This instance is up to date."})]}),d?.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:b,children:"Update"}):null]})}),t.jsx(td,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),wg=({action:e,onClose:s,sessionTitle:n,onConfirm:r})=>t.jsx(Ht,{open:e!==null,onOpenChange:o=>{o||s()},children:t.jsxs(Wt,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(us,{children:[t.jsx(ns,{children:e==="delete"?"Delete session?":"Archive session?"}),t.jsx(fs,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),t.jsxs(Is,{children:[t.jsx(Te,{variant:"outline",size:"sm",onClick:s,children:"Cancel"}),t.jsx(Te,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),vg=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),a=`${r} ${o}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},en=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Sg=i.lazy(()=>cs(()=>import("./SessionSwitcherDropdown-BslRtccE.js"),__vite__mapDeps([116,24,3,4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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}))),vb=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:a})=>{Ot("ui.header.render");const l=le(E=>E.setSessionSwitcherOpen),c=le(E=>E.toggleSidebar),u=le(E=>E.isSidebarOpen),d=le(E=>E.activeMainTab),f=le(E=>E.setActiveMainTab),p=le(E=>E.shortcutOverrides);le(E=>E.timeFormatPreference),Ys();const b=Ne(E=>!!E.newSessionDraft?.open),m=Ne(E=>E.currentSessionId),g=Li(m??""),h=sd(m),v=i.useMemo(()=>{if(!h)return null;const E=h;return{title:h.title??null,directory:E.directory??null,created:h.time?.created??null,slug:E.slug??null,shareUrl:h.share?.url??null,parentId:h.parentID??null}},[h]),x=pt(Or(E=>{if(!E.activeProjectId)return null;const re=E.projects.find(be=>be.id===E.activeProjectId);return re?{id:re.id,path:re.path,label:re.label}:null})),I=$s(E=>E.homeDirectory),y=i.useMemo(()=>{if(!x)return null;const E=x.label?.trim();if(E)return E;const re=x.path.split(/[\\/]/).filter(Boolean);return re[re.length-1]??null},[x]),{isMobile:k}=Ws(),{enabled:A}=Qr(),N=!!(A&&a&&o!==void 0),j=i.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"}],[]),[w,C]=i.useState(!1),R=null,P=i.useRef(null),[M,F]=i.useState(()=>typeof window>"u"?!1:zs()),B=i.useMemo(()=>Ki(),[]),K=nd(),[L,T]=i.useState(!1),U=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:H,side:ce}=Ui(),Q=i.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 re=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!re)return null;const be=Number.parseInt(re[1],10),$e=Number.parseInt(re[2],10);return Number.isNaN(be)?null:be===10?$e:be},[]);Pe.useEffect(()=>{typeof window>"u"||F(zs())},[]);const z=le(E=>E.isSessionSwitcherOpen),Ie=null,O=null,de=[],[he,$]=i.useState(!1),[G,J]=i.useState(!1),[se,fe]=i.useState("Local"),[ke,Me]=i.useState(!0),[Re,Z]=i.useState(!1),[ue,q]=i.useState(null),[ye,_e]=i.useState(!1),[Y,ae]=i.useState(null),ne=i.useMemo(()=>vg(se),[se]),me=i.useCallback(async()=>{if(!(typeof window>"u"||!M))try{if(un()){fe("Local"),Me(!0);return}Me(!1);const E=await Ud(),re=zd(),be=$d([Gd(re),...E.hosts]);if(be.id===Kd){fe("Local"),Me(!0);return}fe(Hd(be.label.trim()||"Instance"))}catch{fe("Local"),Me(!0)}},[M]);Pe.useEffect(()=>(me(),Wd(()=>{me()})),[me]);const De=i.useCallback(async()=>{if(ke){q(null),ae(null);return}_e(!0),ae(null);try{const E=new URLSearchParams({appType:"web",instanceMode:"remote"}),re=await Dt(`/api/pi/update-check?${E.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!re.ok)throw new Error(`Server responded with ${re.status}`);const be=await re.json();q({available:be.available??!1,version:be.version,currentVersion:be.currentVersion??"unknown",body:be.body,nextSuggestedCheckInSec:typeof be.nextSuggestedCheckInSec=="number"?be.nextSuggestedCheckInSec:void 0,packageManager:be.packageManager,updateCommand:be.updateCommand})}catch(E){q(null),ae(E instanceof Error?E.message:"Failed to check remote instance updates")}finally{_e(!1)}},[ke]);i.useEffect(()=>{q(null),ae(null),Z(!1)},[ke,se]),i.useEffect(()=>{if(!M||ke)return;const E=3e3,re=3600*1e3;let be=!1,$e=null;const $t=Tt=>{$e=window.setTimeout(()=>{if(be||typeof document<"u"&&document.visibilityState!=="visible"){$t(re);return}De().finally(()=>{be||$t(re)})},Tt)};return $t(E),()=>{be=!0,$e!==null&&window.clearTimeout($e)}},[De,ke,se,M]);const Ce=i.useCallback(()=>{if(ue?.available){Z(!0);return}De()},[De,ue?.available]),we=m?v??null:null,X=i.useRef(null),[xe,ee]=i.useState(0);i.useEffect(()=>{if(!m){X.current&&(X.current=null,ee($e=>$e+1));return}if(we){X.current={sessionId:m,session:we,expiresAt:Date.now()+2e3};return}const E=X.current;if(!E||E.sessionId!==m)return;const re=E.expiresAt-Date.now();if(re<=0){X.current=null,ee($e=>$e+1);return}const be=window.setTimeout(()=>{X.current?.sessionId===m&&(X.current=null),ee($e=>$e+1)},re);return()=>{window.clearTimeout(be)}},[m,we]);const Ae=(()=>{if(we)return we;if(!m)return null;const E=X.current;return E&&E.sessionId===m&&E.expiresAt>Date.now()?E.session:null})(),Ue=i.useMemo(()=>{const E=typeof Ae?.directory=="string"?Ae.directory:"";return en(E||"")},[Ae?.directory]),Ye=Ne(E=>E.newSessionDraft?.open?en(E.newSessionDraft.directoryOverride??""):""),Se=i.useMemo(()=>qm({sessionDirectory:Ue,draftDirectory:Ye,isNewSessionDraftOpen:b}),[Ye,b,Ue]),Oe=Oi(Se||null),Fe=i.useMemo(()=>Qm({activeProjectLabel:y,openDirectory:Se,homeDirectory:I}),[y,I,Se]),mt=!!(Fe||Oe),nt=i.useMemo(()=>m?ds(Ae):Fe??"PiChamber",[Ae,m,Fe]),Qe=Fi(),rt=Bi(),xt=Ne(E=>E.updateSessionTitle),Xe=Ne(E=>E.archiveSessions),dt=Ne(E=>E.deleteSessions),[gt,Ve]=i.useState(!1),[Ze,kt]=i.useState(!1),Je=i.useRef(!1),[Yt,Rt]=i.useState(""),[Et,ut]=i.useState(null),Pt=i.useRef(null);i.useEffect(()=>{Je.current=!1,kt(!1),Ve(!1),Rt(""),ut(null)},[m]);const ps=i.useCallback(()=>{m&&(Rt(Ae?.title?.trim()||nt),Ve(!0))},[Ae?.title,m,nt]),qt=i.useCallback(async()=>{if(!m)return;const E=Yt.trim();E&&E!==Ae?.title?.trim()&&await xt(m,E),Ve(!1)},[Ae?.title,m,Yt,xt]);i.useEffect(()=>{if(!gt)return;const E=re=>{const be=re.target;(!be||!Pt.current?.contains(be))&&qt()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[gt,qt]);const Qt=i.useCallback(()=>{m&&As(m).then(E=>{oe[E.ok?"success":"error"](E.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[m]),yt=i.useCallback(async()=>{if(!m||!Se){oe.error("Nothing to export");return}try{await rt.syncSession(m)}catch{oe.error("Failed to load the complete session history");return}const E=Ir(Qe.getState()).list;if(E.length===0){oe.error("Nothing to export");return}const re=_a(E,Ae?.title??null),be=$a(Ae?.title??null);await za(re,be)||Ua(re,be),oe.success("Session exported")},[Ae?.title,m,Qe,Se,rt]);g?.type==="busy"||g?.type;const rs=i.useCallback(async()=>{if(!m||!Et)return;const E=rd(),re=[m];for(let Tt=0;Tt<re.length;Tt+=1){const Es=re[Tt];for(const Xt of E)Xt.parentID===Es&&!re.includes(Xt.id)&&re.push(Xt.id)}const be=Et;if(ut(null),(be==="archive"?await Xe(re):await dt(re)).failedIds.length>0){oe.error(be==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(be==="archive"?"Session archived":"Session deleted")},[Xe,m,dt,Et]),ve=le(E=>E.isArchivePageOpen),Be=i.useMemo(()=>ve?{title:"Archive",subtitle:null}:null,[ve]),pe=i.useMemo(()=>en(Se||x?.path||""),[x?.path,Se]),Le=i.useCallback(()=>{pe&&As(pe).then(E=>{oe[E.ok?"success":"error"](E.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[pe]),ze=i.useMemo(()=>x?{id:x.id,path:x.path}:null,[x]),ot=i.useRef(null);i.useEffect(()=>{!ze||!pe||(ot.current={projectRef:ze,directory:pe})},[pe,ze]);const ft=i.useMemo(()=>ze&&pe?{projectRef:ze,directory:pe}:ot.current,[pe,ze]),ht=i.useCallback(async E=>{},[]),Ct=i.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const re=E.tagName;(re==="INPUT"||re==="TEXTAREA"||re==="SELECT"||E.isContentEditable)&&E.blur()},[]),ms=i.useCallback(()=>{if(k){Ct(),l(!z);return}c()},[Ct,k,z,l,c]),et=i.useCallback(()=>{on("desktop_open_draft_mini_chat_window",{directory:en(Se||x?.path||""),projectId:x?.id??null,apiBaseUrl:Pr(),clientToken:Er()}).catch(E=>{console.warn("[header] failed to open draft mini chat window",E)})},[x?.id,x?.path,Se]),gs=i.useCallback(()=>{if(b){et();return}m&&on("desktop_open_session_mini_chat_window",{sessionId:m,directory:en(Se||x?.path||""),apiBaseUrl:Pr(),clientToken:Er()}).catch(E=>{console.warn("[header] failed to open session mini chat window",E)})},[x?.path,m,et,b,Se]),Vt=bn,wt=Wf,Ut=i.useMemo(()=>n?"sessions":N?r&&o?o:null:r?"git":d,[d,N,n,r,o]),it=i.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&z&&l(!1)},[z,n,e,s,r,l]),qs=i.useCallback(()=>{e?.()},[e]),Jt=i.useCallback(()=>{s?.()},[s]),vt=i.useMemo(()=>M&&U&&!L?"5.5rem":K?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!M||H?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[M,L,U,K,H]);Pe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",vt)},[vt]);const ie=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",St=u?"0px":M&&H?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":A?"2.75rem":"2.5rem";Pe.useEffect(()=>{if(!M||!U){T(!1);return}let E=!1;const re=async()=>{try{const $e=await on("desktop_is_window_fullscreen");E||T($e===!0)}catch{E||T(!1)}},be=()=>{re()};return re(),window.addEventListener("pichamber:window-resized",be),()=>{E=!0,window.removeEventListener("pichamber:window-resized",be)}},[M,U]);const at=i.useMemo(()=>!M||!U||Q===null?"":Q>=26?"h-12":Q<=15?"h-14":"",[M,U,Q]),bs=i.useMemo(()=>{if(!(M&&!H))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))"}},[M,H]),Mt=i.useCallback(()=>{if(typeof document>"u")return;const E=P.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Pe.useEffect(()=>{if(typeof window>"u")return;Mt();const E=P.current;if(!E||typeof ResizeObserver>"u")return()=>{};let re=0;const be=()=>{re||(re=requestAnimationFrame(()=>{re=0,Mt()}))},$e=new ResizeObserver(be);return $e.observe(E),window.addEventListener("resize",be),window.addEventListener("orientationchange",be),()=>{re&&cancelAnimationFrame(re),$e.disconnect(),window.removeEventListener("resize",be),window.removeEventListener("orientationchange",be)}},[Mt]),Pe.useEffect(()=>{Mt()},[Mt,k,at]);const os=i.useCallback(async E=>{const re=E.target;re.closest(".app-region-no-drag")||re.closest("button, a, input, select, textarea")||E.button===0&&M&&await od()},[M]),zt=i.useMemo(()=>k?[{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"}]:[],[k]),qn=i.useCallback(E=>eo(Ln(E,p)),[p]);Pe.useEffect(()=>{!k&&d!=="chat"&&d!=="terminal"&&d!=="diagram"&&f("chat")},[d,k,f]),Pe.useEffect(()=>{const E=re=>{if(Yd(re)&&!re.shiftKey&&!re.altKey){const be=parseInt(re.key,10);be>=1&&be<=zt.length&&(re.preventDefault(),k&&(Ct(),it()),f(zt[be-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[Ct,it,k,f,zt]),Pe.useEffect(()=>{const E=re=>{const be=Ln("toggle_services_menu",p);if(qd(re,be)){re.preventDefault(),G?J(!1):(J(!0),me());return}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[p,G,me]);const Qn=E=>{const re=d===E.id,be=E.icon==="diff",$e=be?null:E.icon,$t=E.id==="chat",Tt=Xt=>be?t.jsx(yi,{size:Xt}):$e?t.jsx(D,{name:$e,className:`h-${Xt/4} w-${Xt/4}`}):null,Es=t.jsxs("button",{type:"button",onClick:()=>f(E.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",re?"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",$t&&!k&&"min-w-[100px] justify-center"),"aria-label":E.label,"aria-selected":re,role:"tab",children:[k?Tt(20):t.jsxs(t.Fragment,{children:[Tt(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(i.Fragment,{children:Es},E.id)},xn=t.jsxs(t.Fragment,{children:[t.jsx(Zm,{directory:pe,className:"mr-1"}),M?t.jsx(yg,{isDesktopApp:M,currentInstanceLabel:se,compactCurrentInstanceLabel:ne,currentInstanceIsLocal:ke,isDesktopServicesOpen:G,setIsDesktopServicesOpen:J,refreshCurrentInstanceLabel:me,shortcutLabel:qn,remoteUpdateInfo:ue,remoteUpdateChecking:ye,remoteUpdateError:Y,onOpenRemoteUpdate:Ce}):null,t.jsx(xg,{isMobile:k,githubAuthStatus:R,githubAccounts:de,githubAvatarUrl:Ie,githubLogin:O,isSwitchingGitHubAccount:he,handleGitHubAccountSwitch:ht})]}),Qs=B&&(b||!!m),Rs=()=>t.jsxs("div",{onMouseDown:os,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",at),style:bs,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ie}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:St}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Be?t.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Be.title}),Be.subtitle?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:Be.subtitle})]}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[u?null:t.jsx(i.Suspense,{fallback:t.jsx("button",{type:"button",className:Vt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(Sg,{align:"start",children:t.jsx("button",{type:"button",className:Vt,"aria-label":"Open session switcher",children:t.jsx(D,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[gt?t.jsxs("form",{ref:Pt,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:E=>{E.preventDefault(),qt()},children:[t.jsx("input",{value:Yt,onChange:E=>Rt(E.target.value),autoFocus:!0,onKeyDown:E=>{E.stopPropagation(),E.key==="Escape"&&Ve(!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(D,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>Ve(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(D,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":nt}),mt?t.jsxs(t.Fragment,{children:[t.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),t.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[Fe?t.jsx("span",{className:"truncate",children:Fe}):null,Oe?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(D,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:Oe})]}):null]})]}):null]}),t.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!b&&!gt?t.jsxs(Lt,{open:Ze,onOpenChange:kt,onOpenChangeComplete:E=>{!E&&Je.current&&(Je.current=!1,ps())},children:[t.jsx(Bt,{asChild:!0,children:t.jsx(Te,{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(D,{name:"more",className:"size-4"})})}),t.jsxs(_t,{align:"end",className:"min-w-[190px]",children:[t.jsxs(st,{onClick:()=>{Je.current=!0},children:[t.jsx(D,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(st,{onClick:Qt,children:[t.jsx(D,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsxs(st,{onClick:Le,disabled:!pe,children:[t.jsx(D,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),t.jsx(Ns,{}),t.jsxs(st,{onClick:()=>{yt()},children:[t.jsx(D,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Ns,{}),t.jsxs(st,{onClick:()=>ut("archive"),children:[t.jsx(D,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(st,{className:"text-destructive focus:text-destructive",onClick:()=>ut("delete"),children:[t.jsx(D,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),zt.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:zt.map(E=>Qn(E))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Aa,{}),ft?t.jsx(Si,{projectRef:ft.projectRef,directory:ft.directory,className:"mr-1"}):null,t.jsx(Yf,{visible:Qs,title:b?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:gs,className:_(Vt,"mr-1"),Icon:"picture-in-picture-2"}),xn,t.jsx(zi,{visible:H&&ce==="right",position:"right"})]})]})]}),Vn=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[A&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:ie}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:St}})]}),!A&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:qs,className:_(wt,Ut==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(D,{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(D,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:ms,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(D,{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:!N&&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:zt.map(E=>{const re=d===E.id,be=E.icon==="diff",$e=be?null:E.icon;return t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{k&&(Ct(),it()),f(E.id)},"aria-label":E.label,"aria-selected":re,role:"tab",className:_(wt,"relative rounded-lg",Ut===E.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[be?t.jsx(yi,{className:"h-5 w-5"}):$e?t.jsx(D,{name:$e,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(He,{children:t.jsx("p",{children:E.label})})]},E.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[N&&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:j.map(E=>{const re=r&&o===E.id;return t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{k&&(Ct(),it()),C(!1),a?.(E.id)},"aria-label":E.label,"aria-selected":re,role:"tab",className:_(wt,"relative rounded-lg",re&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(D,{name:E.icon,className:"h-5 w-5"})})}),t.jsx(He,{children:t.jsx("p",{children:E.label})})]},E.id)})}),t.jsx(Hf,{open:w,onOpenChange:C,currentSessionId:m,effectiveDirectory:Se||null,isNewSessionDraftOpen:b})]}),ft&&t.jsx(Si,{projectRef:ft.projectRef,directory:ft.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!N?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Jt,className:_(wt,"relative",Ut==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(D,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(He,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Jn=_("header-safe-area relative z-10 bg-background",k&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:Jn,style:{"--padding-scale":"1"},children:k?Vn():Rs()}),t.jsx(wg,{action:Et,onClose:()=>ut(null),sessionTitle:nt,onConfirm:()=>{rs()}}),t.jsx(ba,{open:Re,onOpenChange:Z,info:ue,downloading:!1,downloaded:!1,progress:null,error:Y,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",jg="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Sb=()=>{const e=le(h=>h.isSidebarOpen),s=le(h=>h.toggleSidebar),n=le(h=>h.shortcutOverrides),r=i.useRef(null),o=i.useRef(null),a=eo(Ln("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=Ui(),{enabled:u}=Qr(),d=!e,f=l&&c==="left",p=l,b=d||f||p,m=f||p,g=i.useCallback(()=>{on("desktop_show_app_menu").catch(h=>{console.warn("[titlebar] failed to open app menu",h)})},[]);return i.useEffect(()=>{if(typeof document>"u")return;const h=A=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(A)}px`)},v=A=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(A)}px`)};if(!m)return;const x=o.current,I=r.current;if(!x||!I){h(0),v(0);return}const y=()=>{const A=Math.max(x.getBoundingClientRect().width,x.scrollWidth);h(A),v(I.getBoundingClientRect().width)};if(y(),typeof ResizeObserver>"u")return;const k=new ResizeObserver(y);return k.observe(x),k.observe(I),()=>{k.disconnect()}},[m]),b?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[f?t.jsx(zi,{visible:!0,position:"left"}):null,p?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:g,"aria-label":"Open PiChamber menu",className:_(ji,"shrink-0"),children:t.jsx(D,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(He,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,d?t.jsxs(Ge,{children:[t.jsx(Ke,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:_(u?jg:ji,"shrink-0"),children:t.jsx(D,{name:"layout-left",className:u?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(He,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},ki=200,kg="cubic-bezier(0.22, 1, 0.36, 1)",jb=e=>{const s=i.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=i.useState(e),[o,a]=i.useState(e);return i.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const u=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(u),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),ki);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:o,prefersReducedMotion:s,transition:s?"none":`transform ${ki}ms ${kg}`}},Cg=hs(()=>({statusById:new Map})),kb=()=>{Wi(),$i()},Cb=e=>{Ne.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),le.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),Wi(),ge.getState().clearAll(),$s.getState().resetForRuntimeSwitch(),id.getState().resetForRuntimeSwitch(),ad.getState().resetForRuntimeSwitch(),ld(),cd.getState().resetForRuntimeSwitch(),Kt.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),pt.getState().resetForRuntimeSwitch(),dd.getState().resetForRuntimeSwitch(),Cg.setState({statusById:new Map}),ud(),fd(),Au.getState().reset(),Qd.getState().resetForRuntimeSwitch(),Pi.getState().resetForRuntimeSwitch(e.runtimeKey),Dr.getState().resetForRuntimeSwitch(e.runtimeKey),Cs.getState().resetForRuntimeSwitch(e.runtimeKey),Fh.getState().resetForRuntimeSwitch(),lt.getState().resetForRuntimeSwitch(e.runtimeKey),Vd.getState().resetForRuntimeSwitch(e.runtimeKey),Ne.getState().restoreForRuntimeSwitch(e.runtimeKey),le.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=le.getState();Br({sessionId:Ne.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),$i()};export{gn as $,hb as A,wb as B,ro as C,ui as D,Xu as E,qg as F,Hg as G,vb as H,zu as I,ys as J,Qg as K,rb as L,Ca as M,Sf as N,no as O,sb as P,vf as Q,wa as R,pb as S,xb as T,ba as U,zf as V,Kg as W,gf as X,jf as Y,mn as Z,xa as _,oo as a,an as a0,xf as a1,Xg as a2,ab as a3,bf as a4,Jg as a5,yf as a6,ib as a7,db as a8,cb as a9,kf as aa,ob as ab,lb as ac,ub as ad,Vg as ae,Zg as af,eb as ag,tb as ah,Of as ai,nb as aj,ef as ak,wf as al,tf as am,io as b,Us as c,ka as d,xs as e,Mn as f,Gf as g,Hf as h,im as i,tn as j,nm as k,gb as l,mb as m,Fn as n,jb as o,yb as p,Sb as q,fb as r,bb as s,kb as t,$g as u,Cb as v,Wg as w,Yg as x,Gg as y,zg as z};