@pi-chamber/web 1.0.6-rc.2 → 1.0.6-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView-BdDt1SI7.js → DiagramView-BZ--w7Lh.js} +1 -1
- package/dist/assets/DiffView-Dtn6otnT.js +18 -0
- package/dist/assets/{FileSaveConflictDialog-DpyPjMH1.js → FileSaveConflictDialog-p1ik30al.js} +2 -2
- package/dist/assets/FilesView-D0Z0VmQm.js +6 -0
- package/dist/assets/{GitHubDetailScaffold-CW2ZqU0Y.js → GitHubDetailScaffold-a27RksFo.js} +4 -4
- package/dist/assets/{GitHubLinkPicker-BjJNQ7Ap.js → GitHubLinkPicker-B0CfzNfk.js} +1 -1
- package/dist/assets/GitHubListPrimitives-LFdR70l6.js +1 -0
- package/dist/assets/GitView-BNkoaVYl.js +9 -0
- package/dist/assets/{IssuesSurface-CDZENHrE.js → IssuesSurface-D4kD7_VW.js} +3 -3
- package/dist/assets/{JsonTreeView-DpCgOUXg.js → JsonTreeView-CEiJsFnP.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-418ChlsN.js +12 -0
- package/dist/assets/{PatchDiff-Dcr3EQgA.js → PatchDiff-BtOv_oLB.js} +1 -1
- package/dist/assets/{PierreDiffViewer-o_Edh6ny.js → PierreDiffViewer-CkuyY9ne.js} +15 -3
- package/dist/assets/{PullRequestsSurface-eSXl6sef.js → PullRequestsSurface-PML07zr-.js} +2 -2
- package/dist/assets/SessionSwitcherContent-DkfjRgwv.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-CFj9VWSa.js → SessionSwitcherDropdown-CEw8BEs6.js} +2 -2
- package/dist/assets/SessionUnreadDot-DXUn8-ss.js +1 -0
- package/dist/assets/SettingsView-BvUeFUqw.js +6 -0
- package/dist/assets/{SettingsWindow-BMzUErrM.js → SettingsWindow-D03Z9QyW.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-p7EbL2-E.js → StickyHorizontalScrollbar-CONTbZgX.js} +1 -1
- package/dist/assets/{ToolOutputDialog-QC8IoeBH.js → ToolOutputDialog-DibddNlz.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-BigGwtul.js → ToolPartDiffPreview-Bx7T1M2f.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DvLCd7Qq.js → VirtualizedFileDiff-BY-mDMT8.js} +4 -4
- package/dist/assets/{Virtualizer-DNJrJKVb.js → Virtualizer-cIf8dSOQ.js} +1 -1
- package/dist/assets/{collapsible-0yfy07W2.js → collapsible-BhQdnj8G.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-aX6tjjqv.js → computeVirtualFileMetrics-CzkFqhaU.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-CZKJuHxf.js → contextFileOpenGuard-CjCOK8EB.js} +1 -1
- package/dist/assets/fileTreeStatus-CPTpyKOV.js +7 -0
- package/dist/assets/gitStatusPredicates-_GNbGCCb.js +1 -0
- package/dist/assets/{githubLink-BvevcNay.js → githubLink-CwIFogWd.js} +2 -2
- package/dist/assets/index-Cfrwo5uQ.js +11 -0
- package/dist/assets/index-D7k62S9M.css +1 -0
- package/dist/assets/{index-BMdbHCFt.js → index-DjOKW10B.js} +1 -1
- package/dist/assets/main-1wmEZ4Is.js +137 -0
- package/dist/assets/{main-BM-b2y8p.js → main-C51a3z3b.js} +2 -2
- package/dist/assets/{markdownCore-DbS8DkKw.js → markdownCore-Dsr6dY5C.js} +1 -1
- package/dist/assets/{miniChat-DO3DW6kJ.js → miniChat-DCxCx1fF.js} +2 -2
- package/dist/assets/{mobile-BgWLkut6.js → mobile-D6Ac2Mu3.js} +2 -2
- package/dist/assets/{nativeFileSave-Bhafll_7.js → nativeFileSave-P_Eg5Dgb.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-ChYVctYk.js → pi-session-focus-preference-DjDyjZ1C.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-xlvSvnTf.js → renderDiffWithHighlighter-CK_inhQE.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-wBNgFl0U.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-CCoYfC-t.js → renderFileWithHighlighter-B_PFeRW5.js} +1 -1
- package/dist/assets/renderMobileApp-B3mhxGnb.js +11 -0
- package/dist/assets/runtimeEndpointReset-D8lAOCUB.js +62 -0
- package/dist/assets/{runtimeSurface-CJN1oo_1.js → runtimeSurface-C3YPOBlg.js} +1 -1
- package/dist/assets/useAppFontEffects-CoFst31H.js +215 -0
- package/dist/assets/{useGitHubRemoteSearch-CevR5iLf.js → useGitHubRemoteSearch-C0-6hhMJ.js} +1 -1
- package/dist/assets/useSwitcherItems-DHCCg4GF.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js → vendor-aparajita-capacitor-secure-storage-B9_YeZyx.js} +1 -1
- package/dist/assets/{vendor-base-ui-C7vVMZTg.js → vendor-base-ui-CKSCJw-4.js} +1 -1
- package/dist/assets/{vendor-boot-CoTxysn6.js → vendor-boot-Ciu-Edvy.js} +18 -18
- package/dist/assets/{vendor-capacitor-app-NX6DULfp.js → vendor-capacitor-app-Bpy_aPMq.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-DJD81I9f.js → vendor-capacitor-keyboard-DO8AIjrZ.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-DV24OoQV.js → vendor-capacitor-status-bar-SQkytwUW.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-qsuH4Dh-.js → vendor-codemirror-autocomplete-CInQsE8a.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-ZHWyBf7j.js → vendor-codemirror-lang-angular-QbsN3LGE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-pCTOmv-k.js → vendor-codemirror-lang-cpp-BT5U7lxV.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-2bFuyM70.js → vendor-codemirror-lang-css-dF-Dxbty.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-DrG_c7D7.js → vendor-codemirror-lang-go-e4dp1bar.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-BV8lrR8v.js → vendor-codemirror-lang-html-DKcbBVQ4.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-DrsvH6T2.js → vendor-codemirror-lang-java-CB2-FWv6.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Dkzl3s07.js → vendor-codemirror-lang-javascript-B1zJk7xE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-8Nn3bnoP.js → vendor-codemirror-lang-jinja-BsERjdSd.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-CsdmtHhi.js → vendor-codemirror-lang-json-C0pZ0NhY.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-DJuZ4cZe.js → vendor-codemirror-lang-less-_N9HmR4h.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-D2RO-Pzr.js → vendor-codemirror-lang-liquid-D02xJRCD.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-C0Zu3b3n.js → vendor-codemirror-lang-markdown-_6ojeUuZ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-CuDtt2Zj.js → vendor-codemirror-lang-php-DguCnbJA.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-Cv2exx_M.js → vendor-codemirror-lang-python-Byr5gw5f.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-C4TxJ6Rg.js → vendor-codemirror-lang-rust-DN6Wh0eK.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-BmtPz8kf.js → vendor-codemirror-lang-sass-DOlEW7q1.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-BF1ZaXqJ.js → vendor-codemirror-lang-sql-BJzE9Dby.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-DZgXrP2k.js → vendor-codemirror-lang-vue-DR8E-2nr.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-DsnaGtL_.js → vendor-codemirror-lang-wast-n6lcDH5S.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-D8DzzFat.js → vendor-codemirror-lang-xml-Cf2lmlmY.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-D5hBv7m6.js → vendor-codemirror-lang-yaml-DSR_E0yh.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-vn2RyN9T.js → vendor-codemirror-language-data-CSid5JuX.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-BVCYIV0D.js → vendor-codemirror-search-8lY3lt6q.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-vqXSn3lv.js → vendor-lezer-cpp-DZYTDKiD.js} +1 -1
- package/dist/assets/{vendor-lezer-css-JnEzSyZR.js → vendor-lezer-css-6qV4fYNQ.js} +1 -1
- package/dist/assets/{vendor-lezer-go-dD2gQMIL.js → vendor-lezer-go-BDi_Iblq.js} +1 -1
- package/dist/assets/{vendor-lezer-html-Cr3U-1pu.js → vendor-lezer-html-BjqcY-oJ.js} +1 -1
- package/dist/assets/{vendor-lezer-java-CRM0IMCo.js → vendor-lezer-java-J2BXqz1h.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-B3s21DIS.js → vendor-lezer-javascript-CiQ9F8yX.js} +1 -1
- package/dist/assets/{vendor-lezer-json-DPFM6EBV.js → vendor-lezer-json-BxN83KKR.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-Bllrq8hY.js → vendor-lezer-lr-BVsDua_K.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-6-3PLvXG.js → vendor-lezer-markdown-BkMtRQ3X.js} +1 -1
- package/dist/assets/{vendor-lezer-php-DOyzfHRl.js → vendor-lezer-php-B3XqnXdP.js} +1 -1
- package/dist/assets/{vendor-lezer-python-CdHdN5qt.js → vendor-lezer-python-D342CidI.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-CqnW8EMH.js → vendor-lezer-rust-Dbfg_4LA.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-BbcF4y6A.js → vendor-lezer-sass-ClxPaFt1.js} +1 -1
- package/dist/assets/{vendor-lezer-xml-C31AyWoo.js → vendor-lezer-xml-I_S6FQ1u.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-Cv908yC2.js → vendor-lezer-yaml-COA6HWLP.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-Cwhyn_5f.js → vendor-replit-codemirror-vim-7IE2zVmx.js} +1 -1
- package/dist/assets/{web-components-6ORYp3Iv.js → web-components-CzkvK_V5.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/git/DOCUMENTATION.md +1 -0
- package/server/lib/git/routes.js +14 -0
- package/server/lib/git/routes.test.js +37 -0
- package/server/lib/git/service.js +27 -0
- package/server/lib/git/service.test.js +32 -0
- package/server/lib/pi/routes.js +63 -1
- package/server/lib/pi/routes.test.js +77 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-shelf-store.js +181 -0
- package/server/lib/pi/session-shelf-store.test.js +73 -0
- package/server/lib/pi/ui-settings-store.js +1 -0
- package/dist/assets/DiffView-Dk3VIX9E.js +0 -18
- package/dist/assets/FilesView-CumrwioK.js +0 -6
- package/dist/assets/GitHubListPrimitives-BcB-cCTs.js +0 -1
- package/dist/assets/GitView-BoCaX5AO.js +0 -9
- package/dist/assets/MarkdownRendererImpl-BkT5TUWF.js +0 -12
- package/dist/assets/SessionSwitcherContent-Dm30bfpn.js +0 -1
- package/dist/assets/SessionUnreadDot-CHlK2awX.js +0 -1
- package/dist/assets/SettingsView-CcHRUyev.js +0 -6
- package/dist/assets/gitStatusPredicates-3i8CcYWJ.js +0 -1
- package/dist/assets/index-C2ISrmRR.js +0 -11
- package/dist/assets/index-DgwThEwf.css +0 -1
- package/dist/assets/main-BXZ561E3.js +0 -137
- package/dist/assets/renderElectronMiniChatApp-CgVqxKDm.js +0 -2
- package/dist/assets/renderMobileApp-CoY1tsk5.js +0 -11
- package/dist/assets/runtimeEndpointReset-fozcAShH.js +0 -62
- package/dist/assets/useAppFontEffects-D_gtiA95.js +0 -215
- package/dist/assets/useFilesViewSearch-BUxcZj60.js +0 -7
- package/dist/assets/useSwitcherItems-kaRkXggX.js +0 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DjOKW10B.js","assets/useAppFontEffects-CoFst31H.js","assets/index-Cfrwo5uQ.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-D7k62S9M.css","assets/vendor-boot-Ciu-Edvy.js","assets/runtimeSurface-C3YPOBlg.js","assets/nativeFileSave-P_Eg5Dgb.js","assets/computeVirtualFileMetrics-CzkFqhaU.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.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-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.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/renderFileWithHighlighter-B_PFeRW5.js","assets/renderDiffWithHighlighter-CK_inhQE.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-BbiDqlyL.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/vendor-capacitor-keyboard-DO8AIjrZ.js","assets/SessionSwitcherDropdown-CEw8BEs6.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as xt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as s,aS as ou,aT as iu,aU as au,aV as lu,aW as cu,aX as du,aY as uu,aZ as _r,a_ as fn,a$ as rl,b0 as zr,b1 as pi,b2 as ol,b3 as fu,b4 as il,b5 as hu,b6 as al,b7 as ll,b8 as Eo,b9 as Do,ba as Ro,bb as cl,bc as dl,bd as ul,be as fl,bf as hl,bg as pl,bh as mi,bi as gi,bj as pu,bk as mu,bl as gu,bm as Po,aP as bu}from"./vendor-boot-Ciu-Edvy.js";import{a as Re,R as l}from"./vendor-react-Bz1tRBxM.js";import{aq as rn,ar as xu,a as ut,h as Me,t as ie,as as bn,I as P,at as Yn,au as zn,av as as,aw as ls,ax as bs,ay as Ns,B as Ne,az as zs,v as js,aA as yu,aB as Ws,aC as xn,aD as Us,aE as wu,g as sn,aF as no,aG as Gi,aH as Hi,aI as Un,e as xr,aJ as vu,aK as Su,aL as ju,aM as ku,aN as Cu,aO as Au,o as ml,aP as Ls,aQ as qi,ah as ps,aR as Ke,aS as We,aT as Ge,aU as Nu,aV as Iu,aW as Eu,aX as Du,aY as Ru,aZ as To,a_ as Pu,a$ as Yt,b0 as Vt,b1 as Qt,b2 as Mo,O as Gt,b3 as Tu,b4 as Mu,b5 as Fu,b6 as Lu,b7 as Ou,b8 as Bu,b9 as Fo,r as $n,G as bi,ba as _u,bb as zu,bc as gl,bd as bl,Z as Cs,be as Uu,bf as $u,bg as Ku,bh as Wu,d as xl,z as Gs,bi as yl,bj as Ur,bk as Yi,bl as wl,bm as yt,bn as Gu,bo as Hu,bp as vl,bq as Lo,br as Sl,bs as jl,bt as xi,bu as ft,bv as qu,b as Vn,bw as Qn,bx as Yu,by as Oo,bz as Vu,i as kl,p as Qu,j as Ju,u as Cl,k as Xu,m as Zu,bA as Al,n as ef,q as Vi,bB as tf,bC as Xs,c as sf,bD as nf,bE as rf,bF as of,bG as Bo,bH as af,bI as lf,bJ as cf,bK as df,bL as uf,a4 as ff,bM as hn,bN as Nl,M as hf,y as pf,bO as mf,w as gf,bP as bf,bQ as xf,bR as Il,bS as yf,aj as wf,bT as vf,bU as Sf,bV as jf,bW as kf,bX as Cf,bY as Af,bZ as Nf,b_ as If,b$ as Ef,c0 as Df}from"./useAppFontEffects-CoFst31H.js";import{A as Qi,f as _,B as Rf,h as de,z as ot,a as pn,C as El,D as Dl,E as Pf,F as Tf,u as mn,G as Mf,H as Ff,I as Lf,J as Of,K as et,b as lt,o as yn,L as Bf,M as _f,N as zf,O as Uf,q as Ee,P as Ji,Q as Ht,R as _o,T as zo,U as Rl,n as ms,V as yi,W as Ir,X as $f,x as Xi,Y as Kf,Z as Wf,_ as Gf,$ as Hf,a0 as qf,e as on,a1 as Yf,a2 as Vf,v as Pl,a3 as Qf,a4 as Tl,a5 as Jf,a6 as Ml,a7 as Kn,a8 as Uo,j as $o,a9 as Xf,aa as Zf,ab as eh,ac as th,ad as sh,ae as Zi,af as Dn,ag as ro,ah as Ko,ai as Er,aj as Os,ak as ea,al as Wo,am as Fl,an as Go,ao as nh,ap as rh,aq as oh,ar as ih,as as ah,at as lh,au as ch,av as dh,aw as uh,ax as Ll,ay as fh,az as hh,aA as ph,aB as mh,aC as gh}from"./index-Cfrwo5uQ.js";import{b as bh,g as Ol,r as xh,d as Bl,s as yr,c as _l,e as $s,h as gn,i as yh,j as wh,k as vh,l as Sh,m as er,f as jh,a as ta,S as kh,t as Ch,n as Ah}from"./SessionUnreadDot-DXUn8-ss.js";import{c as Is,d as $r,p as zl,a as Nh}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{saveOrShareFile as Ih}from"./nativeFileSave-P_Eg5Dgb.js";import{usePermissionStore as Eh}from"./permissionStore-zIpxq9Pq.js";const Dh="chat";function Ul(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(rn.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(rn.SETTINGS,n),t}return e.tab!==Dh&&t.set(rn.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(rn.FILE,e.diffFile),t}function Rh(e,t){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 Ph(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=Ul(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(rn.SESSION)&&t.set(rn.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),a=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==a[c][0]||i[c][1]!==a[c][1])return!1;return!0}catch{return!0}}function Ho(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Ph(e)))try{const n=Ul(e),r=Rh(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Th=["typescript","javascript","tsx","jsx","json","markdown"],$l={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let sa=null;const Kl=()=>(sa??=Promise.all([xt(()=>import("./index-DjOKW10B.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])),xt(()=>import("./workerFactory-DlGfNFqf.js"),[]),xt(()=>import("./appThemeRegistry-Ca8eGRB9.js"),__vite__mapDeps([43,44,30,31,5,15,16,17,18,19,20,21,22,23,24,25,26,27,28]))]).then(([e,t,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),sa),Jn={},na=new Set,qo=new Set;let wr={light:"pierre-light",dark:"pierre-dark"};const Mh=()=>{for(const e of qo)e()},Wl=(e,t)=>{t.setRenderOptions({theme:wr,lineDiffType:$l[e].lineDiffType})},Yo=e=>{typeof window>"u"||na.has(e)||(na.add(e),Kl().then(t=>{if(Jn[e])return;const n=$l[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Th,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Jn[e]=r,Wl(e,r),Mh()}))},Fh=e=>(qo.add(e),()=>qo.delete(e)),Lh=e=>{if(!(wr.light===e.light&&wr.dark===e.dark)){wr=e;for(const t of Object.keys(Jn)){const n=Jn[t];n&&Wl(t,n)}}},Jy=({children:e})=>{const t=xu(),n=Qi(!1),r=Qi(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,a=t?.availableThemes.find(d=>d.metadata.id===o)??n,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Re.useEffect(()=>{let d=!1;return Kl().then(u=>{d||(u.ensurePierreThemeRegistered(a),u.ensurePierreThemeRegistered(c),Lh({light:a.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,a]),Re.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Yo("unified"),Yo("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),s.jsx(s.Fragment,{children:e})},Xy=(e="unified")=>{const t=Re.useSyncExternalStore(Fh,()=>Jn[e],()=>{});return Re.useEffect(()=>{Yo(e)},[e]),t},Oh=e=>{const t=e.trim();return t&&(t.split(/[?#]/,1)[0]||t).match(/([^/:]+?)(?:\.git)?\/?$/)?.[1]?.trim()||""},Bh=e=>{const t=e.trim();return t?/[/\\]/.test(t)?"A name can’t contain / or \\.":t==="."||t===".."?"Choose a different name.":null:"Enter a name for the folder."},ra=(e,t)=>e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t,Vo=({children:e,className:t})=>s.jsx("kbd",{className:_("inline-flex h-4 min-w-4 normal-case items-center justify-center rounded border border-border bg-[var(--surface-muted)] px-1 font-sans typography-micro text-muted-foreground",t),children:e}),_h=({hints:e})=>s.jsx("span",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",children:e.map(t=>{const n=s.jsxs(s.Fragment,{children:[t.keys.map(r=>s.jsx(Vo,{children:r},r)),s.jsx("span",{children:t.label})]});return t.onSelect?s.jsx("button",{type:"button",onClick:t.onSelect,className:"-mx-1 flex items-center gap-1 rounded px-1 transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:n},t.label):s.jsx("span",{className:"flex items-center gap-1",children:n},t.label)})}),Gl=l.forwardRef(({id:e,active:t,onSelect:n,onHover:r,ariaLabel:o,ariaChecked:i,className:a,quiet:c=!1,children:d},u)=>s.jsx("div",{ref:u,id:e,role:"option","aria-selected":t,"aria-checked":i,"aria-label":o,onMouseMove:t?void 0:r,onMouseDown:f=>f.preventDefault(),onClick:n,className:_("flex w-full cursor-pointer select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left typography-ui-label text-foreground",t&&(c?"group-focus-within/palette:bg-interactive-hover":"group-focus-within/palette:bg-interactive-selection group-focus-within/palette:text-interactive-selection-foreground"),!t&&"hover:bg-interactive-hover/60",a),children:d}));Gl.displayName="PaletteRow";const zh=e=>e==="/",As=e=>e.replace(/\\/g,"/"),gs=e=>{if(!e||zh(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},ln=e=>e.endsWith("/"),Wn=e=>{const t=e.trim();return!t||ln(t)?t:`${t}/`},wi=e=>e.lastIndexOf("/"),Uh=e=>{if(ln(e))return e;const t=wi(e);return t<0?e:e.slice(0,t+1)},$h=e=>{const t=wi(e);return e.slice(t+1)},Hl=e=>{const t=gs(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=wi(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},Kh=e=>ln(e)&&Hl(e)!==null,vr=e=>{if(!e)return null;const t=gs(As(e.trim()));return t?t.toLowerCase():null},oo=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},Wh=(e,t)=>{const n=gs(As(e.trim())),r=gs(As(t.trim()));if(!n)return"";if(!r)return Wn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Wn(n)},ql=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),Gh=e=>ql()?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,Hh=()=>ql()?"⌘":"Ctrl",qh=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Yh=async()=>Rf({fresh:!0}),lr=async(e,t)=>{try{const n=await e.json();if(typeof n.error=="string"&&n.error.trim())return n.error.trim()}catch{}return t},io=(e,t,n)=>ot(e,{method:"POST",headers:{"Content-Type":"application/json"},query:n,body:JSON.stringify(t)});function Vh({open:e,onClose:t,isMobile:n}){const r=ut(g=>g.addProject),o=de(g=>g.setActiveMainTab),i=de(g=>g.setSessionSwitcherOpen),a=Me(g=>g.openNewSessionDraft),[c,d]=l.useState(null),[u,f]=l.useState(null);l.useEffect(()=>{e&&(d(null),f(null))},[e]);const m=l.useCallback(g=>{const k=r(g);return k?(o("chat"),n&&i(!1),a({selectedProjectId:k.id,directoryOverride:k.path}),t(),!0):(f("PiChamber couldn’t add this folder. Check that the path is a folder."),!1)},[r,n,t,a,o,i]),x=l.useCallback(async(g,k)=>{if(!c){d(g),f(null);try{await k()}catch(b){f(b instanceof Error&&b.message?b.message:"Something went wrong. Try again.")}finally{d(null)}}},[c]),y=l.useCallback((g,k)=>x("add",async()=>{if(k.create){const b=await io("/api/fs/mkdir",{path:g},{directory:k.location});if(!b.ok)throw new Error(await lr(b,"Couldn’t create the folder."))}m(g)}),[m,x]),p=l.useCallback((g,k)=>x("clone",async()=>{const b=await io("/api/fs/clone",{remoteUrl:g.trim(),destinationPath:`${gs(k)}/`});if(!b.ok){const j=(await lr(b,"The clone failed.")).replace(/^Cloning into '[^']*'\.\.\.\s*/,"").replace(/^fatal:\s*/,"");throw new Error(j.charAt(0).toUpperCase()+j.slice(1))}const A=await b.json();if(typeof A.path!="string"||!A.path)throw new Error("The clone finished, but the server didn’t say where. Add the folder from Folder on this server.");m(A.path)}),[m,x]),h=l.useCallback((g,k,b)=>x("create",async()=>{const A=`${gs(g)}/${k.trim()}`,j=await io("/api/fs/mkdir",{path:A},{directory:g});if(!j.ok)throw new Error(await lr(j,"Couldn’t create the folder."));if(b){const C=await ot("/api/git/init",{method:"POST",query:{directory:A}});if(!C.ok){const w=await lr(C,"git init failed.");throw new Error(`The folder was created, but git init failed: ${w}`)}}m(A)}),[m,x]),S=l.useCallback(()=>f(null),[]);return{pending:c,error:u,clearError:S,addFolder:y,cloneRepository:p,createProject:h}}const Qh=()=>{const[e,t]=Re.useState(!1),[n,r]=Re.useState(!1);Re.useEffect(()=>{t(pn()),r(El())},[]);const o=Re.useCallback(async c=>e?await Dl(c):{success:!0,path:c},[e]),i=Re.useCallback(async c=>e?await Pf():{success:!0},[e]),a=Re.useCallback(async c=>e?await Tf():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:a}},ao=async(e,t)=>{try{const r=(await Ff(t)).filter(o=>o.isDirectory).map(o=>({name:o.name,path:As(o.path)})).sort((o,i)=>o.name.localeCompare(i.name));return{displayDir:e,absoluteDir:t,entries:r,error:null}}catch(n){return{displayDir:e,absoluteDir:t,entries:[],error:Lf(n)?n.reason:"unknown"}}},Jh=250;function Xh({open:e,addedProjectPaths:t}){const n=mn(G=>G.homeDirectory),{canRequestAccess:r,startAccessing:o}=Qh(),[i,a]=l.useState(""),[c,d]=l.useState("~/"),[u,f]=l.useState(null),[m,x]=l.useState(!1),[y,p]=l.useState(!1),[h,S]=l.useState(!1),g=l.useRef(0),k=i||n;l.useEffect(()=>{if(!e)return;g.current+=1,d("~/"),f(null),p(!1),S(!1);let G=!1;return(async()=>{const le=await Yh();G||a(le||n||"")})(),()=>{G=!0}},[n,e]);const b=l.useMemo(()=>Uh(c),[c]),A=l.useMemo(()=>ln(c)?"":$h(c),[c]),j=l.useMemo(()=>k?oo(b,k):"",[b,k]),C=!!(u&&u.displayDir===b&&u.absoluteDir===j);l.useEffect(()=>{if(!e||!j||C)return;const G=++g.current;ao(b,j).then(L=>{G===g.current&&f(L)})},[j,b,C,e]),l.useEffect(()=>{if(C||!j){x(!1);return}const G=window.setTimeout(()=>x(!0),Jh);return()=>window.clearTimeout(G)},[j,C]);const w=l.useCallback(async G=>{const L=Wn(G);if(!k)return d(L),!0;const le=++g.current,H=await ao(L,oo(L,k));return le!==g.current?!1:(f(H),d(L),!0)},[k]),v=l.useCallback(()=>{if(!j)return;const G=++g.current;ao(b,j).then(L=>{G===g.current&&f(L)})},[j,b]),I=l.useMemo(()=>C?A:!u||!c.startsWith(u.displayDir)?"":c.slice(u.displayDir.length).split("/")[0]??"",[A,C,u,c]),D=l.useMemo(()=>{if(!u)return[];const G=I.toLowerCase(),L=h||I.startsWith(".");return u.entries.filter(le=>le.name.toLowerCase().startsWith(G)&&(L||!le.name.startsWith(".")))},[I,u,h]),z=l.useMemo(()=>{if(!u||u.error)return[];const G=[],L=Kh(u.displayDir)?Hl(u.displayDir):null;if(L){const le=vr(u.absoluteDir);G.push({type:"parent",value:"browse:up",name:"..",path:u.absoluteDir,target:L,alreadyAdded:!!(le&&t.has(le))})}for(const le of D){const H=vr(le.path);G.push({type:"directory",value:`browse:${le.path}`,name:le.name,path:le.path,target:`${Wn(u.displayDir)}${le.name}/`,alreadyAdded:!!(H&&t.has(H))})}return G},[t,D,u]),W=C?u?.error??null:null,$=l.useMemo(()=>C&&u?u.entries:[],[C,u]),K=l.useMemo(()=>k?gs(oo(c,k)):"",[k,c]),B=vr(K),R=!!(B&&t.has(B)),T=l.useMemo(()=>A?$.find(G=>G.name===A)??null:null,[A,$]),E=!!(C&&K&&!R&&(W===null||W==="not-found")&&(ln(c)&&W==="not-found"||!ln(c)&&A.trim().length>0&&T===null)),F=l.useCallback(async G=>{const L=await o(G);if(!L.success)return ie.error("Failed to open directory",{description:L.error||"Desktop could not grant file access."}),!1;const le=k?Wh(G,k):Wn(As(G));return await w(le),!0},[k,w,o]),q=l.useCallback(async()=>{if(!y){p(!0);try{if(El()){const L=await Dl(K);if(!L.success||!L.path){L.error&&L.error!=="Directory selection cancelled"&&ie.error("Failed to select directory",{description:L.error});return}await F(L.path);return}const G=await Mf(K);if(G.status==="cancelled")return;if(G.status!=="picked"){ie.error("Couldn't open a folder picker",{description:G.error});return}await F(G.path)}catch(G){ie.error("Failed to select directory",{description:G instanceof Error?G.message:"Unknown error occurred."})}finally{p(!1)}}},[F,y,K]);return{query:c,setQuery:d,isSettled:C,showLoading:m,browseErrorReason:W,reload:v,isPickingLocation:y,showHidden:h,setShowHidden:S,explorerRootDirectory:k,browseDirectoryDisplayPath:b,browseDirectoryAbsolutePath:j,browseFilterQuery:A,entries:$,rows:z,targetPath:K,isAlreadyAdded:R,shouldCreateTarget:E,canRequestAccess:r,navigate:w,handleBrowseLocation:q}}const Zh={folder:"source","clone-url":"source","clone-location":"clone-url","new-name":"source","new-location":"new-name"},$t=e=>e==="folder"||e==="clone-location"||e==="new-location",ep=[{step:"folder",icon:"folder-6",title:"Folder on this server",description:"Pick a folder that’s already here."},{step:"clone-url",icon:"download-cloud",title:"Clone a repository",description:"Copy a Git repository from a URL."},{step:"new-name",icon:"folder-add",title:"New project",description:"Start an empty folder, with Git if you want it."}],tp={folder:"Open folder","clone-url":"Clone","clone-location":"Clone","new-name":"New project","new-location":"New project"},sp={source:"Choose where the project comes from, type a folder path, or paste a Git URL.",folder:"Pick a folder on this server or type its path.","clone-url":"Paste the URL of the repository to clone.","clone-location":"Pick the folder the repository is cloned into.","new-name":"Name the new project.","new-location":"Pick the folder the new project goes in."},np={source:"Filter sources, type a folder path, or paste a Git URL",folder:"Folder path","clone-url":"Repository URL","clone-location":"Location","new-name":"Project name","new-location":"Location"},rp={source:"Choose a source, type a path, or paste a Git URL",folder:"~/","clone-url":"https://github.com/owner/repo.git","clone-location":"~/","new-name":"Project name","new-location":"~/"},op=e=>/^(~|\/|[a-zA-Z]:[\\/])/.test(e),ip=e=>/^(https?:\/\/|ssh:\/\/|git:\/\/|git@)/i.test(e)||/^[\w.-]+@[\w.-]+:/.test(e),ap=e=>gs(As(e)).split("/").pop()??"",lp=({open:e,onOpenChange:t})=>{const n=ut(U=>U.projects),{isMobile:r,isTablet:o}=bn(),i=r||o,[a,c]=l.useState("source"),[d,u]=l.useState(""),[f,m]=l.useState(""),[x,y]=l.useState(""),[p,h]=l.useState(!0),[S,g]=l.useState(null),k=l.useRef(null),b=l.useRef(new Map),A=l.useId(),j=l.useMemo(()=>new Set(n.map(U=>vr(U.path)).filter(U=>!!U)),[n]),C=l.useCallback(()=>t(!1),[t]),w=Xh({open:e,addedProjectPaths:j}),{pending:v,error:I,clearError:D,addFolder:z,cloneRepository:W,createProject:$}=Vh({open:e,onClose:C,isMobile:r});l.useEffect(()=>{e&&(c("source"),u(""),m(""),y(""),h(!0),g(null))},[e]),l.useEffect(()=>{D()},[w.query,D,x,f,a]),l.useLayoutEffect(()=>{e&&(i&&a!=="clone-url"&&a!=="new-name"||qh(k.current))},[i,e,a]);const K=l.useCallback(U=>{c(U),g(null)},[]),B=l.useCallback(()=>{v||a==="source"||K(Zh[a])},[K,v,a]),{navigate:R}=w,T=l.useCallback(U=>{const pe=U.type==="parent"?`dir:${ap(U.path)}`:null;R(U.target).then(se=>{se&&g(pe)})},[R]),E=l.useMemo(()=>new Set(w.entries.map(U=>U.name)),[w.entries]),F=w.browseDirectoryDisplayPath,q=w.browseErrorReason==="not-found"?"This folder doesn’t exist. Pick a location that does.":w.browseErrorReason?"PiChamber can’t read this location.":null,G=!w.isSettled||w.isPickingLocation,L=Oh(f),le=x.trim(),H=Bh(le);let Ae=!1,Pe="",J="",M=null;if(a==="folder"){J="Adding…";const U=gs(w.query.trim())||w.query.trim();if(w.isAlreadyAdded)Pe="Added",U&&(M={tone:"outcome",text:"Already added:",path:U});else{Pe=w.shouldCreateTarget?"Create and add":"Add";const pe=w.browseErrorReason&&w.browseErrorReason!=="not-found";Ae=!!w.targetPath&&!pe&&!G,U&&!pe&&(M={tone:"outcome",text:w.shouldCreateTarget?"Creates and adds":"Adds",path:U})}}else if(a==="clone-location"){Pe="Clone",J="Cloning…";const U=ra(F,L);q?M={tone:"problem",text:q}:E.has(L)?M={tone:"problem",text:"Already exists:",path:U}:(M={tone:"outcome",text:"Clones into",path:U},Ae=!!L&&!G)}else if(a==="new-location"){Pe="Create",J="Creating…";const U=ra(F,le);q?M={tone:"problem",text:q}:H?M={tone:"problem",text:H,path:U}:E.has(le)?M={tone:"problem",text:"Already exists:",path:U}:(M={tone:"outcome",text:"Creates",path:U},Ae=!G)}Ae=Ae&&v===null;const Y=()=>{Ae&&(a==="folder"?z(w.targetPath,{create:w.shouldCreateTarget,location:w.browseDirectoryAbsolutePath}):a==="clone-location"?W(f,w.browseDirectoryAbsolutePath):a==="new-location"&&$(w.browseDirectoryAbsolutePath,le,p))},Q=a==="clone-url"?!!L:a==="new-name"?!!le&&!H:!1,ne=()=>{Q&&K(a==="clone-url"?"clone-location":"new-location")},ae=[];if(a==="source"){const U=d.trim().toLowerCase();for(const pe of ep)U&&!`${pe.title} ${pe.description}`.toLowerCase().includes(U)||ae.push({key:`source:${pe.step}`,kind:"source",select:()=>K(pe.step),content:s.jsxs(s.Fragment,{children:[s.jsx(P,{name:pe.icon,className:"size-4 shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col py-0.5",children:[s.jsx("span",{className:"truncate",children:pe.title}),s.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:pe.description})]})]})})}else if($t(a)){a==="new-location"&&ae.push({key:"toggle:git",kind:"toggle",select:()=>h(U=>!U),ariaChecked:p,ariaLabel:"Initialize a Git repository",content:s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pointer-events-none flex size-4 shrink-0 items-center justify-center",children:s.jsx(Yn,{checked:p,onChange:h})}),s.jsx("span",{className:"flex-1 truncate",children:"Initialize a Git repository"})]})});for(const U of w.rows){const pe=U.type==="parent";ae.push({key:pe?"browse:up":`dir:${U.name}`,kind:pe?"parent":"directory",select:()=>T(U),ariaLabel:pe?`Up to ${U.target}`:`${U.name}${U.alreadyAdded?", already added":""}`,content:s.jsxs(s.Fragment,{children:[s.jsx(P,{name:pe?"arrow-up-s":"folder-6",className:"size-4 shrink-0 text-muted-foreground"}),pe?s.jsxs("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[s.jsx("span",{className:"shrink-0",children:"Up to"}),s.jsx(zn,{value:U.target,className:"min-w-0 font-mono typography-meta text-muted-foreground"})]}):s.jsx("span",{className:"min-w-0 flex-1 truncate",children:U.name}),!pe&&U.alreadyAdded?s.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:"Added"}):null]})})}}const me=$t(a)?ae.findIndex(U=>U.kind==="directory"):ae.length>0?0:-1,ge=S?ae.findIndex(U=>U.key===S):-1,ke=ge>=0?ge:me,ve=ke>=0?ae[ke]:void 0,De=ve?.key,xe=U=>`${A}-option-${U}`;l.useLayoutEffect(()=>{De&&b.current.get(De)?.scrollIntoView({block:"nearest"})},[De]);const ze=U=>{if(ae.length===0)return;const pe=ke>=0?ke:U>0?-1:ae.length,se=Math.min(ae.length-1,Math.max(0,pe+U));g(ae[se]?.key??null)},X=a==="source"?d:a==="clone-url"?f:a==="new-name"?x:w.query,oe=U=>{if(g(null),a==="source"){const pe=U.trimStart();if(ip(pe)){u(""),m(pe),K("clone-url");return}if(op(pe)){u(""),w.setQuery(pe==="~"?"~/":As(pe)),K("folder");return}u(U);return}if(a==="clone-url"){m(U);return}if(a==="new-name"){y(U);return}w.setQuery(As(U).replace(/\/{2,}/g,"/"))},te=U=>{if(!U.nativeEvent.isComposing){if(U.key==="ArrowDown"||U.key==="ArrowUp"){if(ae.length===0)return;U.preventDefault(),ze(U.key==="ArrowDown"?1:-1);return}if(U.key==="Enter"){if(U.preventDefault(),v)return;if($t(a)&&Gh(U)){Y();return}if(a==="clone-url"||a==="new-name"){ne();return}ve?ve.select():$t(a)&&Y();return}if(U.key==="Tab"&&!U.shiftKey&&ve?.kind==="directory"){U.preventDefault(),ve.select();return}U.key==="Backspace"&&X===""&&a!=="source"&&(U.preventDefault(),B())}},fe=Hh(),he=[];ae.length>1&&he.push({keys:["↑","↓"],label:"Navigate"}),a==="source"?ve&&he.push({keys:["↵"],label:"Select"}):a==="clone-url"||a==="new-name"?he.push({keys:["↵"],label:"Continue"}):ve?he.push({keys:["↵"],label:ve.kind==="toggle"?"Toggle":"Open"}):he.push({keys:["↵"],label:Pe}),a!=="source"&&X===""&&he.push({keys:["⌫"],label:"Back"}),he.push({keys:["Esc"],label:"Close",onSelect:()=>t(!1)});const _e=$t(a)&&ve?[fe,"↵"]:["↵"];let je=null;$t(a)?je=s.jsxs(Ne,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!Ae,onMouseDown:U=>U.preventDefault(),onClick:Y,children:[v?J:Pe,!r&&!v&&Ae?s.jsx("span",{className:"flex items-center gap-0.5",children:_e.map(U=>s.jsx(Vo,{className:"border-current/30 bg-transparent text-current",children:U},U))}):null]}):(a==="clone-url"||a==="new-name")&&(je=s.jsxs(Ne,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!Q,onMouseDown:U=>U.preventDefault(),onClick:ne,children:["Continue",!r&&Q?s.jsx(Vo,{className:"border-current/30 bg-transparent text-current",children:"↵"}):null]}));let V=null;const we=ae.filter(U=>U.kind==="directory").length;a==="source"&&ae.length===0?V={tone:"quiet",text:"Nothing matches. Type a folder path, or paste a Git URL."}:a==="clone-url"?f.trim()?L?V={tone:"quiet",text:s.jsxs(s.Fragment,{children:["Clones as ",s.jsx("span",{className:"font-mono text-foreground",children:L}),". Press Enter to choose where it goes."]})}:V={tone:"problem",text:"This URL doesn’t name a repository."}:V={tone:"quiet",text:"Paste the repository’s HTTPS or SSH URL, then press Enter to choose where it goes."}:a==="new-name"?le?H?V={tone:"problem",text:H}:V={tone:"quiet",text:s.jsxs(s.Fragment,{children:["Press Enter to choose where ",s.jsx("span",{className:"font-mono text-foreground",children:le})," goes."]})}:V={tone:"quiet",text:"Name the project, then press Enter to choose where it goes."}:$t(a)&&(w.browseErrorReason==="not-found"?V=a==="folder"?{tone:"quiet",text:"This folder doesn’t exist yet. Adding it creates it."}:{tone:"problem",text:"This folder doesn’t exist. Pick a location that does."}:w.browseErrorReason?V={tone:"problem",text:w.browseErrorReason==="os-permission"?"PiChamber needs access to this folder.":"Couldn’t read this folder.",actions:s.jsxs(s.Fragment,{children:[w.browseErrorReason==="os-permission"&&w.canRequestAccess?s.jsx(Ne,{size:"xs",onClick:()=>{w.handleBrowseLocation()},disabled:w.isPickingLocation,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:w.reload,children:"Try again"})]})}:w.showLoading&&we===0?V={tone:"quiet",text:"Loading folders…"}:w.isSettled&&we===0&&(V={tone:"quiet",text:w.browseFilterQuery?a==="folder"?s.jsxs(s.Fragment,{children:["No folder named ",s.jsx("span",{className:"font-mono text-foreground",children:w.browseFilterQuery})," here. Adding it creates it."]}):"No folders match.":"No folders in here."}));const ue=I?s.jsx("p",{role:"alert",className:"border-b border-border/60 px-4 py-2 typography-meta text-[var(--status-error)] text-pretty",children:I}):null,Se=(U,pe)=>s.jsx("button",{type:"button",onClick:B,disabled:v!==null,"aria-label":pe,className:"ml-auto shrink-0 rounded px-1 typography-ui-label text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:pointer-events-none disabled:opacity-50",children:U}),Ye=M?s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/60 px-4 py-2",children:[a==="new-location"?s.jsxs("div",{className:"flex min-w-0 items-center gap-2 typography-ui-label",children:[s.jsx("label",{htmlFor:"new-project-name",className:"shrink-0 text-muted-foreground",children:"Name"}),s.jsx("input",{value:x,onChange:U=>y(U.target.value),onKeyDown:U=>{U.nativeEvent.isComposing||U.key==="Enter"&&(U.preventDefault(),Y())},id:"new-project-name",spellCheck:!1,autoComplete:"off",disabled:v!==null,className:"h-7 min-w-0 flex-1 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-1.5 font-mono text-foreground outline-none focus-visible:border-[var(--interactive-focus)] focus-visible:ring-2 focus-visible:ring-primary/30"})]}):null,s.jsxs("p",{className:_("flex min-w-0 items-baseline gap-1.5 typography-ui-label",M.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:[s.jsx("span",{className:"shrink-0",children:M.text}),M.path?s.jsx(zn,{value:M.path,className:"min-w-0 font-mono text-foreground"}):null]}),a==="clone-location"?s.jsxs("p",{className:"flex min-w-0 items-baseline gap-1.5 typography-ui-label text-muted-foreground",children:[s.jsx("span",{className:"shrink-0",children:"From"}),s.jsx(zn,{value:f.trim(),className:"min-w-0 font-mono text-foreground"}),Se("Change","Change the repository URL")]}):null]}):null,Ue=a!=="source"&&a!=="new-name";return s.jsx(as,{open:e,onOpenChange:t,children:s.jsxs(ls,{showCloseButton:!1,initialFocus:i?!1:k,className:_("group/palette w-full max-w-xl gap-0 self-start overflow-hidden rounded-2xl p-0","mt-[max(env(safe-area-inset-top),0.25rem)] max-h-[calc(100%-0.5rem)] sm:mt-[10vh] sm:max-h-[80vh]"),children:[s.jsx(bs,{className:"sr-only",children:"Add folder"}),s.jsx(Ns,{className:"sr-only",children:sp[a]}),s.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-border/60 pl-2.5 pr-2",children:[a==="source"?s.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center text-muted-foreground",children:s.jsx(P,{name:"folder-add",className:"size-4"})}):s.jsx(Ne,{variant:"ghost",size:"icon",className:"size-7 shrink-0",onMouseDown:U=>U.preventDefault(),onClick:B,disabled:v!==null,"aria-label":"Back",title:"Back",children:s.jsx(P,{name:"arrow-left-s",className:"size-4"})}),a!=="source"?s.jsxs("span",{className:"flex shrink-0 items-center gap-2 typography-ui-label font-medium text-foreground","aria-hidden":"true",children:[tp[a],s.jsx("span",{className:"h-4 w-px bg-border"})]}):null,s.jsx("input",{ref:k,value:X,onChange:U=>oe(U.target.value),onKeyDown:te,readOnly:v!==null,"aria-busy":v!==null||void 0,"aria-label":np[a],placeholder:rp[a],role:"combobox","aria-expanded":ae.length>0,"aria-controls":A,"aria-autocomplete":"list","aria-activedescendant":ke>=0?xe(ke):void 0,"aria-invalid":V?.tone==="problem"&&!$t(a)?!0:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("min-w-0 flex-1 text-foreground outline-none placeholder:text-muted-foreground",a==="source"?"h-full bg-transparent":"h-8 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2","typography-markdown md:typography-ui-label",Ue&&"font-mono")}),je]}),Ye,ue,s.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain sm:max-h-[min(24rem,52vh)]",children:[ae.length>0?s.jsx("div",{id:A,role:"listbox","aria-label":a==="source"?"Sources":"Folders",className:"flex flex-col gap-px p-1.5",children:ae.map((U,pe)=>s.jsxs(l.Fragment,{children:[pe>0&&ae[pe-1]?.kind==="toggle"?s.jsx("div",{role:"presentation",className:"mx-2.5 my-1 h-px bg-border/60"}):null,s.jsx(Gl,{ref:se=>{se?b.current.set(U.key,se):b.current.delete(U.key)},id:xe(pe),active:pe===ke,onSelect:U.select,onHover:()=>g(U.key),ariaLabel:U.ariaLabel,ariaChecked:U.ariaChecked,className:U.kind==="source"?"py-2":void 0,quiet:$t(a),children:U.content})]},U.key))}):null,V?s.jsxs("div",{className:_("flex flex-col items-center gap-3 px-6 text-center",ae.length>0?"pb-6 pt-3":"py-8"),children:[s.jsx("p",{className:_("typography-meta text-balance",V.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:V.text}),V.actions?s.jsx("div",{className:"flex items-center gap-2",children:V.actions}):null]}):null]}),!r||$t(a)?s.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-3 border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:[r?s.jsx("span",{}):s.jsx(_h,{hints:he}),$t(a)?s.jsxs("span",{className:"flex shrink-0 items-center gap-3",children:[s.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5",children:[s.jsx(Yn,{checked:w.showHidden,onChange:w.setShowHidden,ariaLabel:"Show hidden folders"}),"Hidden"]}),s.jsx(Ne,{variant:"ghost",size:"xs",disabled:v!==null||w.isPickingLocation,onMouseDown:U=>U.preventDefault(),onClick:()=>{w.handleBrowseLocation()},title:"Pick a folder with the system dialog",children:w.isPickingLocation?"Opening…":"Browse…"})]}):null]}):null]})})},cr=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Zy=()=>{const[e,t]=l.useState(!1),[n,r]=l.useState(null),[o,i]=l.useState(!1),a=Me(C=>C.deleteSession),c=Me(C=>C.deleteSessions),d=de(C=>C.showDeletionDialog),u=de(C=>C.setShowDeletionDialog),{isMobile:f,isTablet:m,hasTouchInput:x}=bn(),y=f||m||x;l.useEffect(()=>Of(()=>{t(!1)}),[]);const p=l.useCallback(C=>{r({sessions:C.sessions,dateLabel:C.dateLabel})},[]),h=l.useCallback(()=>{r(null),i(!1)},[]),S=l.useCallback(async C=>{if(C.sessions.length===0)return;if(C.sessions.length===1){const D=C.sessions[0];await a(D.id)?ie.success("Session deleted"):ie.error("Failed to delete session");return}const w=C.sessions.map(D=>D.id),{deletedIds:v,failedIds:I}=await c(w);if(v.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:C.dateLabel?`Removed all sessions from ${C.dateLabel}.`:void 0;ie.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:cr(D)})}I.length>0&&ie.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:cr("Please try again in a moment.")})},[a,c]);l.useEffect(()=>zs.onDeleteRequest(C=>{if(!d){S(C);return}p(C)}),[p,d,S]),l.useEffect(()=>zs.onDirectoryRequest(()=>{t(!0)}),[]);const g=l.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const C=n.sessions[0];if(!await a(C.id)){ie.error("Failed to delete session"),i(!1);return}ie.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const C=n.sessions.map(D=>D.id),w=await c(C),v=w.deletedIds,I=w.failedIds;if(v.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ie.success(v.length===1?"Deleted {count} session":`Deleted ${v.length} sessions`,{description:cr(D),action:{label:"OK",onClick:()=>{}}})}if(I.length>0&&(ie.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:cr("Please try again in a moment.")}),v.length===0)){i(!1);return}}h()}finally{i(!1)}}},[n,a,c,h]),k=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.`:"",b=n?s.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&s.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(C=>s.jsx("li",{className:"typography-micro text-subtle-foreground",children:s.jsx("span",{className:"truncate",children:js(C)})},C.id)),n.sessions.length>5&&s.jsx("li",{className:"typography-micro text-subtle-foreground",children:`+${n.sessions.length-5} more`})]})}),s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-subtle-foreground",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?s.jsx(P,{name:"checkbox-blank",className:"size-4"}):s.jsx(P,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ne,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",onClick:g,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),j=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(yu,{open:!!n,onClose:()=>{o||h()},title:j,footer:s.jsx("div",{className:"flex justify-end gap-2",children:A}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[k&&s.jsx("p",{className:"typography-meta text-subtle-foreground",children:k}),b]})}):s.jsx(as,{open:!!n,onOpenChange:C=>{if(!C){if(o)return;h()}},children:s.jsxs(ls,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:j}),k&&s.jsx(Ns,{children:k})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:b}),s.jsx(xn,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),s.jsx(lp,{open:e,onOpenChange:t})]})},ew=()=>{const e=Us(t=>t.entries);return l.useEffect(()=>{for(const t of e.values())!wu(t)||!t.receipt||(Us.getState().markNotificationSent(t.key),ie.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},cp=[{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-access",title:"Remote access",group:"projects",kind:"single",description:"How other devices reach this computer.",keywords:["remote","access","mobile","phone","pair","qr","device","devices","tailscale","funnel","lan","network","wifi","password","passkey"],isAvailable:e=>!e.isMobile&&(e.isDesktop||e.isWeb)},{slug:"servers",title:"Servers",group:"projects",kind:"single",description:"Which PiChamber server this app uses.",keywords:["server","servers","instance","switch","connect","import link","host"],isAvailable:e=>!e.isMobile&&e.isDesktop||e.isMobile&&e.isCapacitor===!0},{slug:"remote-instances",title:"Remote instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"],isAvailable:()=>!1},{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","ssh","commit","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"]}],dp={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function up(e){const t=e.trim().toLowerCase();return cp.find(n=>n.slug===t)??null}function fp(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const n=dp[t];if(n)return n;const r=up(t);return r?r.slug:"home"}function tw(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-access":return"server";case"servers":return"server";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function sw(){const e=l.useRef(!1),t=l.useRef(!1),n=Me(f=>f.setCurrentSession),r=de(f=>f.setActiveMainTab),o=de(f=>f.setSettingsDialogOpen),i=de(f=>f.setSettingsPage),a=de(f=>f.navigateToDiff),c=l.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const m=Me.getState().currentSessionId,x=sn().getState().selectedSessionId;if(f.sessionId!==m||f.sessionId!==x){const y=Me.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(fp(f.settingsPath)),o(!0);return}de.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&a(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,a]),d=l.useCallback(()=>{const f=Me.getState(),m=sn().getState(),x=de.getState();return{sessionId:no({currentSessionId:f.currentSessionId,piSelectedSessionId:m.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=l.useCallback((f={})=>{if(t.current)return;const m=d();Ho(m,f)},[d]);l.useEffect(()=>{if(e.current||(e.current=!0,!Gi()))return;const f=Hi();(async()=>(await c(f),Ho({...d(),sessionId:f.sessionId??no({currentSessionId:Me.getState().currentSessionId,piSelectedSessionId:sn().getState().selectedSessionId,draft:Me.getState().newSessionDraft}),tab:f.tab??de.getState().activeMainTab,settingsPath:f.settingsPath??de.getState().settingsPage,diffFile:f.diffFile??de.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),l.useEffect(()=>{const f=()=>{const S=Me.getState(),g=sn().getState();return no({currentSessionId:S.currentSessionId,piSelectedSessionId:g.selectedSessionId,draft:S.newSessionDraft})};let m=f(),x=Me.getState().newSessionDraft?.open===!0;const y=()=>{const S=Me.getState(),g=f(),k=S.newSessionDraft?.open===!0;g===m&&k===x||t.current||(m=g,x=k,u({replace:!0}))},p=Me.subscribe(()=>{y()}),h=sn().subscribe(()=>{y()});return()=>{p(),h()}},[u]),l.useEffect(()=>{let f=de.getState().activeMainTab,m=de.getState().isSettingsDialogOpen,x=de.getState().settingsPage,y=de.getState().pendingDiffFile;return de.subscribe(h=>{if(t.current)return;const S=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==m,k=h.settingsPage!==x,b=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,m=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(S||g||k||b)&&u()})},[u]),l.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const m=Hi();if(Gi())c(m);else{const x=de.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function hp(e=!0){const t=xr(r=>r.checkForUpdates),n=l.useRef(t);l.useEffect(()=>{n.current=t},[t]),l.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,a=1440*60*1e3;let c=!1,d=null;const u=m=>{const x=Math.round(m*1e3);return Math.max(i,Math.min(a,x))},f=m=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),y=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(y)},m))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function nw(){const e=Un(t=>t.connection==="ready",void 0,"chrome");return hp(e),null}const pp=200,mp=15e3,gp=e=>{const{id:t,url:n}=e.payload,r=Su(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=ju(ku(n),r.target,{isMobile:de.getState().isMobile});if(!i.canOpen){ie.info(i.title,{id:o,description:i.description,duration:mp});return}ie.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Cu(r.target,n,Au()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{ie.dismiss(o)}}})},rw=()=>(l.useEffect(()=>{const e=new Set;return vu(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>pp){const n=e.values().next().value;n!==void 0&&e.delete(n)}gp(t)}})},[]),null),oa=12,bp=[{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"}],xp=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=bp,onComplete:i})=>{const a=Re.useRef(!1);Re.useEffect(()=>{!e&&a.current&&i?.(),e&&(a.current=!0)},[e,i]);const c=Re.useMemo(()=>Array.from({length:oa},(d,u)=>{const f=Math.PI*2*u/oa;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?s.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":t,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return s.jsx("div",{className:"firework-burst",style:u,children:c.map((f,m)=>{const x=f.x*d.radius,y=f.y*d.radius,p={"--translate-x":`${x}px`,"--translate-y":`${y}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return s.jsx("span",{className:"firework-particle",style:p},`${d.id}-${m}-${t}`)})},`${d.id}-${t}`)})}):null},yp=({durationMs:e=3400}={})=>{const[t,n]=Re.useState({isActive:!1,cycle:0}),r=Re.useRef(null),o=Re.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Re.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),a=Re.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 Re.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:a,dismissFireworks:i}},Yl=l.createContext(void 0),ow=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=yp(),i=l.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(Yl.Provider,{value:i,children:[e,s.jsx(xp,{isActive:t,burstKey:n})]})},wp={triggerFireworks:()=>{},dismissFireworks:()=>{}},iw=()=>l.useContext(Yl)??wp,Dr=2e3,Vl=600*1e3;async function vp(){try{const e=await ot("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const t=await e.json().catch(()=>({}));return{success:!0,autoRestart:t.autoRestart!==!1,jobId:typeof t.jobId=="string"?t.jobId:void 0,channel:t.channel==="rc"?"rc":t.channel==="stable"?"stable":void 0,targetVersion:typeof t.targetVersion=="string"?t.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function Sp(e,t=Math.ceil(Vl/Dr),n=Dr,r=et()){for(let o=0;o<t;o++){if(et()!==r)return{applied:!1,stale:!0};try{const i=await ot("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(et()!==r)return{applied:!1,stale:!0};if(i.ok){const a=await i.json().catch(()=>null);if(et()!==r)return{applied:!1,stale:!0};if(typeof a?.error=="string"&&a.error.length>0)return{applied:!1,error:a.error};if(a&&a.available===!1)return{applied:!0};if(a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(et()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function jp(e,t,n=Math.ceil(Vl/Dr),r=Dr,o=et()){for(let i=0;i<n;i++){if(et()!==o)return{applied:!1,stale:!0};try{const a=await ot(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(et()!==o)return{applied:!1,stale:!0};if(a.ok){const c=await a.json().catch(()=>null);if(et()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?t("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&t("updating")}else{if(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(a.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(a.status===503){const c=await a.json().catch(()=>null);if(et()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};t("reconnecting")}else t("reconnecting")}}catch{if(et()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(a=>setTimeout(a,r))}return{applied:!1}}const ia="https://github.com/RyderAsKing/PiChamber/releases";function kp(e){const t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(t)}function Cp(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function aa(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function Ap(e,t){const n=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=n(e),[i,a]=n(t),c=r.split(".").map(u=>Number.parseInt(u,10)),d=i.split(".").map(u=>Number.parseInt(u,10));for(let u=0;u<3;u+=1){const f=Number.isFinite(c[u])?c[u]:0,m=Number.isFinite(d[u])?d[u]:0;if(f!==m)return m-f}return!o||!a?(o?1:0)-(a?1:0):a.localeCompare(o,void 0,{numeric:!0})}function Np(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=t.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,i)=>{const a=n[i+1]?.start??e.length,c=e.slice(o.start,a).trim();return{version:o.version,date:o.date,start:o.start,end:a,raw:c}})}const Ql=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:a,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,m]=Re.useState(null),[x,y]=Re.useState("idle"),[p,h]=Re.useState(null),[S,g]=Re.useState(null),[k,b]=Re.useState({}),A=n?.version?n.releaseUrl||`${ia}/tag/v${n.version}`:ia,j=n?.downloadUrl||A,C=i?.total?Math.round(i.downloaded/i.total*100):0,w=u==="web",v=u==="mobile",I=n?.updateCommand||"pichamber update",D=k.version||n?.version,z=k.channel||n?.channel;Re.useEffect(()=>{e||(y("idle"),h(null),g(null),b({}))},[e]);const W=async(E=I)=>{(await ps(E)).ok&&(m(E),setTimeout(()=>m(null),2e3))},$=Re.useCallback(async E=>{await ml(E)},[]),K=Re.useCallback(async()=>{const E=et();y("updating"),h(null),g(null),b({});const F=await vp();if(et()!==E)return;if(!F.success){y("error"),h(F.error||"Update failed"),g(F.commands??null);return}if(b({version:F.targetVersion,channel:F.channel}),F.jobId){const G=await jp(F.jobId,L=>{et()===E&&y(L)},void 0,void 0,E);if(G.stale||et()!==E)return;if(G.applied){window.location.reload();return}y("error"),h(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(F.autoRestart?"restarting":"reconnecting");const q=await Sp(n?.currentVersion,void 0,void 0,E);if(!(q.stale||et()!==E)){if(q.applied){window.location.reload();return}y("error"),h(q.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),B=Re.useCallback(()=>{$(j)},[$,j]),R=x!=="idle"&&x!=="error",T=Re.useMemo(()=>{if(!n?.body)return null;const E=n.body.trim();if(!E)return null;const F=Np(E);return F.length===0?{kind:"raw",title:"What's new",content:aa(E)}:{kind:"sections",title:"What's new",sections:[...F].sort((G,L)=>Ap(G.version,L.version)).map(G=>({version:G.version,dateLabel:kp(G.date),content:aa(Cp(G.raw)||E)}))}},[n?.body]);return s.jsx(as,{open:e,onOpenChange:R?void 0:t,children:s.jsxs(ls,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[s.jsxs(bs,{className:"flex items-center gap-2.5",children:[s.jsx(P,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(n?.currentVersion||D||w&&z)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||D)&&s.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&D&&s.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"→"}),D&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:D})]}),w&&z&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:z==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[w&&R&&s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(P,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),T&&!R&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Ls,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:T.kind==="raw"?s.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:E=>{const q=E.target.closest("a");q&&q.href&&(E.preventDefault(),E.stopPropagation(),$(q.href))},children:s.jsx(qi,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.sections.map(E=>s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.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",E.version]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:E.dateLabel})]}),s.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 G=F.target.closest("a");G&&G.href&&(F.preventDefault(),F.stopPropagation(),$(G.href))},children:s.jsx(qi,{content:E.content,disableLinkSafety:!0,enableFileReferences:!1})})]},E.version))})})}),(a||p)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:a||p})}),w&&x==="error"&&(S??[I]).length>0&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(P,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:S?"Run these commands:":"Or update via terminal:"})]}),(S??[I]).map(E=>s.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:[s.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:E}),s.jsx(Ne,{variant:"ghost",size:"icon",onClick:()=>{W(E)},className:f===E?"text-[var(--status-success)]":void 0,title:f===E?"Copied!":"Copy command","aria-label":f===E?"Copied!":"Copy command",children:f===E?s.jsx(P,{name:"check",className:"h-4 w-4"}):s.jsx(P,{name:"clipboard",className:"h-4 w-4"})})]},E))]}),!w&&!v&&r&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),s.jsxs("span",{className:"font-mono text-foreground",children:[C,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${C}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[s.jsxs("a",{href:A,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:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!w&&!v&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!w&&!v&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!w&&!v&&o&&s.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[s.jsx(P,{name:"restart",className:"h-4 w-4"}),"Restart to update"]}),v&&s.jsxs(Ne,{onClick:B,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),w&&!R&&s.jsxs(Ne,{onClick:K,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),w&&R&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Jl=l.memo(function({checked:t,onChange:n,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:a,iconClassName:c}){const d=l.useCallback(x=>{x.preventDefault(),x.stopPropagation(),!r&&!t&&n()},[t,r,n]),u=l.useCallback(x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),!r&&!t&&n())},[t,r,n]),f=s.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),m=_("relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full","transition-[background-color,box-shadow] duration-200 ease-out",t?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none":"bg-background shadow-[inset_0_0_0_1px_var(--interactive-border-hover)]");return i?s.jsx("span",{"aria-hidden":!0,className:_(m,r&&"opacity-50",a),children:f}):s.jsx("button",{type:"button",role:"radio",onClick:d,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",m,t?"hover:bg-[var(--primary-base)]":"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:f})}),tr=({children:e,className:t,contentClassName:n})=>{const[r,o]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>{if(!r)return;const a=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[r]),s.jsxs(Ke,{open:r,onOpenChange:o,children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:a=>{a.preventDefault(),a.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-subtle-foreground hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:s.jsx(P,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(Ge,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},aw="w-full min-w-40 max-w-48",lw="settings",Ip="w-full min-w-40 max-w-48",cw="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Ep="w-full max-w-[24rem]",dw="min-w-0 flex-1",uw="flex w-full min-w-0 items-center gap-2",fw="typography-meta shrink-0 text-muted-foreground tabular-nums",Xl="space-y-3.5",Dp="space-y-1.5",hw="typography-settings-page-title text-foreground",Rp="typography-settings-section-title text-foreground",Zl="typography-settings-group-title text-foreground",vi="typography-settings-field-label text-foreground",Pp="typography-settings-description text-muted-foreground",sr="typography-meta text-muted-foreground",pw="typography-meta font-medium text-foreground",mw="typography-settings-section-title text-foreground",Tp=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:a=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return s.jsxs("section",{"data-settings-item":u,className:_("space-y-4",a?"border-t border-border/60 py-6":"pb-6",c),children:[f?s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?s.jsx("h2",{className:Rp,children:e}):e,n,r!=null?s.jsx(tr,{children:r}):null]}):null,t!=null?s.jsx("div",{className:Pp,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},gw=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),Mp=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(Zl,t),children:e}),bw=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:a})=>s.jsxs("div",{"data-settings-item":a,className:_("space-y-2",o),children:[e!=null||t!=null||n!=null?s.jsxs("div",{className:"space-y-0.5",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Mp,{children:e}),n!=null?s.jsx(tr,{children:n}):null]}):null,t!=null?s.jsx("p",{className:sr,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),Gn=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:a,controlClassName:c})=>{const d=t!=null?s.jsx("p",{className:sr,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:_("space-y-2",a),children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:vi,children:e}),n!=null?s.jsx(tr,{children:n}):null]}),r==="before"?d:null]}),s.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},xw=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:a,controlClassName:c,alignEnd:d=!0})=>s.jsxs("div",{"data-settings-item":o,className:_("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",i),children:[s.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",a),children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:vi,children:e}),n!=null?s.jsx(tr,{children:n}):null]}),t!=null?s.jsx("p",{className:_(sr,"mt-0.5"),children:t}):null]}),s.jsx("div",{className:_("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",d&&"@xl:justify-end",c),children:r})]}),yw=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),ww=({label:e,children:t,divider:n=!0,className:r,contentClassName:o})=>s.jsxs("details",{className:_("group/disclosure",n?"border-t border-border/60 py-6":"pb-6",r),children:[s.jsxs("summary",{className:"flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md typography-ui-label text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] [&::-webkit-details-marker]:hidden",children:[s.jsx(P,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),s.jsx("div",{className:_("pt-4",o),children:t})]}),Fp=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:a,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},m=r!=null;return s.jsxs("div",{"data-settings-item":a,className:_("group flex cursor-pointer gap-2 py-0.5",m?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[s.jsx(Yn,{checked:e,onChange:t,disabled:o,ariaLabel:i}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:vi,children:n}),d,u!=null?s.jsx(tr,{children:u}):null]}),m?s.jsx("span",{className:sr,children:r}):null]})]})},vw=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:a})=>s.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",a),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.jsx(Jl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:_("typography-settings-field-label font-normal","text-foreground"),children:n}),r!=null?s.jsx("span",{className:sr,children:r}):null]})]}),Sw=({selected:e,onSelect:t,label:n,preview:r,description:o,ariaLabel:i,disabled:a=!1,className:c})=>{const d=l.useId();return s.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",a&&"cursor-not-allowed opacity-60",c),role:"radio",tabIndex:a?-1:0,"aria-checked":e,"aria-label":i,"aria-describedby":o?d:void 0,"aria-disabled":a||void 0,onClick:()=>{a||t()},onKeyDown:u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),a||t())},children:[s.jsx("div",{"aria-hidden":!0,className:_("aspect-[4/3] overflow-hidden rounded-lg border transition-colors",e?"border-[var(--primary-base)] ring-1 ring-[var(--primary-base)]":"border-[var(--interactive-border)] group-hover/preview:border-foreground/30"),children:r}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(Jl,{checked:e,onChange:t,disabled:a,decorative:!0}),s.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal","text-foreground"),children:n})]}),o?s.jsx("p",{id:d,className:"-mt-1 pl-[20px] typography-meta text-muted-foreground text-pretty",children:o}):null]})},jw=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(Dp,n),children:t});function kw({value:e,options:t,onChange:n,className:r,"aria-label":o}){return s.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>s.jsx(Ne,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>n(i.value),children:i.label},i.value))})}const Qo="pichamber:server-update-channel-changed",Cw=()=>{typeof window<"u"&&window.dispatchEvent(new Event(Qo))},Lp=e=>typeof window>"u"?()=>{}:(window.addEventListener(Qo,e),()=>window.removeEventListener(Qo,e));class Op extends l.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?s.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:s.jsxs(Nu,{className:"w-full max-w-md",children:[s.jsx(Iu,{className:"text-center",children:s.jsxs(Eu,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(P,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(Du,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&s.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&s.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[s.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),s.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(P,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),s.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Bp(e){return s.jsx(Op,{...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 Aw=({active:e=!0})=>{const t=Me(n=>n.currentSessionId);return s.jsx(Bp,{sessionId:t||void 0,children:s.jsx(Ru,{active:e},t??"no-session")})};function _p({onResizeStart:e,ariaLabel:t}){return s.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":t,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:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:s.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const ec=Re.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:a,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:m,...x},y)=>{const p=Re.useRef(null),h=Re.useRef(null),[S,g]=Re.useState(null),k=c??S,b=Re.useCallback(j=>{const C=p.current;if(!C)return;h.current={startY:j.clientY,startHeight:C.getBoundingClientRect().height};const w=j.currentTarget;w.setPointerCapture(j.pointerId);const v=D=>{const z=h.current;if(!z)return;const W=z.startHeight+(D.clientY-z.startY),$=Math.max(82,W);d?d($):g($)},I=()=>{h.current=null,w.removeEventListener("pointermove",v),w.removeEventListener("pointerup",I),w.removeEventListener("pointercancel",I)};w.addEventListener("pointermove",v),w.addEventListener("pointerup",I),w.addEventListener("pointercancel",I),j.preventDefault()},[d]),A=Re.useCallback(j=>{if(j.target.closest('textarea, button, [role="separator"]'))return;const w=p.current?.querySelector("textarea");w&&document.activeElement!==w&&(j.preventDefault(),w.focus())},[]);return f?s.jsx(Ls,{as:"textarea",ref:y,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:n,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):s.jsx("div",{ref:p,onPointerDown:A,style:k!==null?{height:`${k}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",!a&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],a&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[s.jsx("textarea",{ref:y,className:_("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-subtle-foreground placeholder:text-subtle-foreground",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,s.jsx(_p,{onResizeStart:b,ariaLabel:"Resize textarea"})]})]})})});ec.displayName="Textarea";const tc=[{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"}],Hn=Object.fromEntries(tc.map(e=>[e.key,e.Icon])),Jo="pichamber:project-actions-updated",sc=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},fs=(e,t)=>`${sc(e)}::${t}`,nc=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:a,className:c,contentClassName:d,divider:u=!0})=>s.jsx(Tp,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:a}),Xo=e=>e.name.trim().length>0&&e.command.trim().length>0,zp=e=>e.name.trim().length===0&&e.command.trim().length===0,Up=e=>!Xo(e)&&!zp(e),$p=(e,t)=>e.some(r=>t.has(r.id)&&!Xo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Xo)},Kp=450,Wp=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Gp=()=>({id:Wp(),name:"",command:"",icon:"play"}),Hp=({projectRef:e})=>{const[t,n]=l.useState([]),[r,o]=l.useState(!1),[i,a]=l.useState(null),[c,d]=l.useState(new Set),u=l.useRef(!1);l.useEffect(()=>{let g=!1;return o(!0),(async()=>{try{const k=await To(e);if(g)return;n(k.actions),a(JSON.stringify({actions:k.actions})),d(new Set(k.actions.map(b=>b.id)))}catch{if(g)return;n([]),a(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=l.useMemo(()=>$p(t,c),[t,c]),m=l.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=i!==null&&f.canPersist&&m!==i,y=l.useCallback(async g=>await Pu(e,{actions:g,primaryActionId:null})?(a(JSON.stringify({actions:g})),d(new Set(g.map(b=>b.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Jo,{detail:{projectId:e.id}})),!0):(ie.error("Failed to save actions"),!1),[e]);l.useEffect(()=>{if(!x||r||u.current)return;const g=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await y(f.actions)}finally{u.current=!1}})())},Kp);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const p=l.useCallback(()=>{const g=Gp();n(k=>[...k,g])},[]),h=l.useCallback(g=>{n(k=>k.filter(b=>b.id!==g))},[]),S=l.useCallback((g,k)=>{n(b=>b.map(A=>A.id===g?k(A):A))},[]);return s.jsx(nc,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ne,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:p,children:[s.jsx(P,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):s.jsx("div",{className:_("space-y-6",Ep),children:t.map((g,k)=>{const b=g.icon||"play",A=Hn[b]||"play",j=g.name.trim()||`Action ${k+1}`,C=Up(g);return s.jsxs("div",{className:Xl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Zl,children:j}),s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(g.id),"aria-label":`Delete ${j}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(Gn,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Yt,{children:[s.jsx(Vt,{asChild:!0,children:s.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:s.jsx(P,{name:A,className:"h-4 w-4"})})}),s.jsx(Qt,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:tc.map(w=>{const v=w.Icon,I=(g.icon||"play")===w.key;return s.jsx("button",{type:"button",onClick:()=>S(g.id,D=>({...D,icon:w.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",I&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${w.label}`,children:s.jsx(P,{name:v,className:"h-4 w-4"})},w.key)})})})]}),s.jsx(Mo,{value:g.name,onChange:w=>S(g.id,v=>({...v,name:w.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(Gn,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(ec,{value:g.command,onChange:w=>S(g.id,v=>({...v,command:w.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),C?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(Fp,{checked:g.autoOpenUrl===!0,onChange:w=>S(g.id,v=>({...v,...w?{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 ${j}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(Gn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Mo,{value:g.openUrl||"",onChange:w=>S(g.id,v=>({...v,openUrl:w.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},qp={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)"},Yp=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:a})=>{const c=Gt(v=>v.providers),d=Gt(v=>v.modelsMetadata),u=de(v=>v.hiddenModels),f=de(v=>v.isFavoriteModel),m=de(v=>v.toggleFavoriteModel),x=de(v=>v.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:p}=Tu(),[h,S]=l.useState(!1),[g,k]=l.useState("");l.useEffect(()=>{h?Gt.getState().ensureModelMetadata():k("")},[h]);const b=e?c.find(v=>v.id===e.providerId):void 0,A=e&&b?(Array.isArray(b.models)?b.models:[]).find(v=>v.id===e.modelId):void 0,j=e?Mu(A,e.modelId):t,C=l.useMemo(()=>e?u.filter(v=>!(v.providerID===e.providerId&&v.modelID===e.modelId)):u,[u,e]),w=l.useCallback(v=>{a({providerId:v.providerID,modelId:v.modelID}),S(!1)},[a]);return s.jsxs(Yt,{modal:!1,open:h,onOpenChange:v=>{r||S(v)},children:[s.jsx(Vt,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(Lu({size:"default"}),Ip,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(Fu,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:j})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(Qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(Ou,{providers:c,favoriteModels:y,recentModels:p,modelsMetadata:d,searchQuery:g,onSearchQueryChange:k,onSelect:w,labels:{...qp,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{a(null),S(!1)},disabled:r,autoFocus:!0,onEscape:()=>S(!1),isFavorite:v=>f(v.providerID,v.modelID),onToggleFavorite:v=>m(v.providerID,v.modelID),onReorderFavorite:(v,I)=>x(v.providerID,v.modelID,I.providerID,I.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},lo="w-full max-w-none",Vp=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,a=Gt(c=>c.loadProviders);return l.useEffect(()=>{a({source:"projectSettings"})},[a]),i?s.jsx(nc,{title:"Project",divider:!1,children:s.jsxs("div",{className:Xl,children:[s.jsx(Gn,{label:"Name",settingsItem:"projects.name",controlClassName:lo,children:s.jsx(Mo,{value:t,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),s.jsx(Gn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:lo,children:s.jsx(Yp,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:lo,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Qp=e=>{const[t,n]=l.useState(""),[r,o]=l.useState(void 0);l.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const i=l.useMemo(()=>Bu(r),[r]),a=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=l.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=l.useCallback(async()=>{if(!e)return null;const u=t.trim();return u?{label:u,defaultModel:r??null}:null},[r,t,e]);return{name:t,setName:n,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:a,prepareSaveData:d,project:e}},Jp=450,Xp=(e,t)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:i}=e,a=l.useRef(!1);l.useEffect(()=>{if(!n||!r.trim()||a.current)return;const c=window.setTimeout(()=>{a.current||(a.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{ie.error("Failed to save project settings")}}finally{a.current=!1}})())},Jp);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Zp=({project:e,onIdentitySave:t})=>{const n=Qp(e),r=l.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=l.useCallback(async i=>{await t(i)},[t]);return Xp(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(Vp,{form:n}),s.jsx(Hp,{projectRef:r})]})},em=6e4,tm=3e4,Rn=new Map;let la=0,ca=!1;const sm=()=>{if(ca||typeof window>"u")return;ca=!0;const e=()=>{const t=Date.now();t-la<tm||typeof document<"u"&&document.hidden||(la=t,xt(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-Cfrwo5uQ.js").then(r=>r.cU);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&Kr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},Kr=Is()($r((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:lt(),resetForRuntimeSwitch:n=>{const r=n??lt();Rn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{sm();const o=lt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),a=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&a-i.fetchedAt<em)return i.status;const c=Rn.get(o);if(c)return c;const d=n??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return lt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return lt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();Rn.set(o,u);try{return await u}finally{Rn.get(o)===u&&Rn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&yn(e=>{Kr.getState().resetForRuntimeSwitch(e.runtimeKey)});const nm=()=>Kr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),Nw=e=>{if(e.byteLength<4)return null;const t=new DataView(e).getUint32(0);if(t<=0||4+t>e.byteLength)return null;try{const n=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(n?.width)||!Number.isFinite(n?.height)?null:{header:n,jpeg:new Uint8Array(e,4+t)}}catch{return null}},Iw=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},Ew=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",Dw=50*1024*1024-1,Rw=[250,1e3,2e3,4e3,8e3],rm=(e,t)=>{const n=r=>{let o=r>>>0;for(const i of`${e}\0${t}`)o^=i.codePointAt(0)??0,o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0")};return`tab-${n(2166136261)}${n(16777619)}`},Pw=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),Tw=(e,t,n,r)=>{if(n.width<=0||n.height<=0)return null;const o=(e-n.left)/n.width*r.width,i=(t-n.top)/n.height*r.height;return{x:Math.round(Math.max(0,Math.min(r.width-1,o))*100)/100,y:Math.round(Math.max(0,Math.min(r.height-1,i))*100)/100}},Mw=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,Fw=(e,t)=>{const n=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(n)&&n>0?n:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},wn=async(e,t)=>{const n=await e.json().catch(()=>null);return new Error(typeof n?.error=="string"?n.error:t)},Lw=async()=>{const e=await ot("/api/server-browser/status");if(!e.ok)throw await wn(e,"Could not check the server browser");return await e.json()},Ow=async e=>{const t=await ot("/api/server-browser/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await wn(t,"Could not save the server browser settings");return await t.json()},Bw=async(e,t)=>{const n=await ot("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!n.ok)throw await wn(n,"Could not find dev servers");const r=await n.json();return Array.isArray(r.servers)?r.servers:[]},_w=async(e,t,n)=>{const r=await ot("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:n});if(!r.ok)return{framing:"unknown"};const o=await r.json().catch(()=>null);return o?.framing==="refused"||o?.framing==="allowed"?{framing:o.framing,reason:o.reason==="frame-ancestors"?"frame-ancestors":"x-frame-options"}:{framing:"unknown"}},zw=async()=>{const e=await ot("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await wn(e,"Could not clear browsing data")},Uw=(e,t)=>{const n=rm(e,t);ot(`/api/server-browser/tabs/${encodeURIComponent(n)}`,{method:"DELETE"}).catch(()=>{})},$w=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),n=await ot(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!n.ok)throw await wn(n,`Could not upload ${e.name}`);const r=await n.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},Kw=async(e,t)=>{const n=await ot(`/api/server-browser/downloads/${encodeURIComponent(e)}`);if(!n.ok)throw await wn(n,`Could not download ${t}`);const r=await n.blob(),o=URL.createObjectURL(r);try{const i=document.createElement("a");i.href=o,i.download=t,i.rel="noopener",document.body.appendChild(i),i.click(),i.remove()}finally{setTimeout(()=>URL.revokeObjectURL(o),6e4)}},Ww=async(e,t,n)=>{const r=await _f();return{socket:zf(Uf().websocket("/api/server-browser/ws",{tab:e,url:t,popup:n},r)),urlAuthToken:r}},Gw=e=>{Bf(e)},dr=100;function Hw(){const e=de(v=>v.isArchivePageOpen),t=de(v=>v.setArchivePageOpen),n=de(v=>v.setActiveMainTab),r=Me(v=>v.setCurrentSession),o=Me(v=>v.unarchiveSession),i=mn(v=>v.homeDirectory),a=Fo({archived:!0}),[c,d]=l.useState(""),[u,f]=l.useState(null),[m,x]=l.useState(dr),y=c.trim().toLowerCase(),p=l.useMemo(()=>e?[...a].sort((v,I)=>(I.time?.archived??0)-(v.time?.archived??0)):[],[a,e]),h=l.useMemo(()=>{const v=new Map;for(const I of p){const D=Ee($n(I))??"",z=v.get(D);if(z){z.sessions.push(I);continue}v.set(D,{directory:D,label:D?Ji(D,i)||D:"other projects",sessions:[I]})}return[...v.values()].sort((I,D)=>D.sessions.length-I.sessions.length)},[i,p]),S=l.useMemo(()=>y?p.filter(v=>(v.title??"").toLowerCase().includes(y)):u===null?p:h.find(v=>v.directory===u)?.sessions??[],[h,y,u,p]),g=S.slice(0,m),k=S.length-g.length,b=a.length,A=l.useCallback(v=>{f(v),x(dr)},[]),j=l.useCallback(v=>{const I=Ee($n(v));r(v.id,I??void 0),n("chat"),t(!1)},[n,r,t]),C=l.useCallback(v=>{o(v.id).then(I=>{I?ie.success("Session restored"):ie.error("Failed to restore session")})},[o]);if(!e)return null;const w=(v,I,D,z,W,$,K)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:W,title:$,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",K?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",z?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:I}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:D})]}),K?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>zs.requestDelete({sessions:K,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${I}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},v);return s.jsx(ou,{open:e,onOpenChange:t,children:s.jsxs(iu,{children:[s.jsx(au,{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"}),s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:s.jsxs(lu,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[s.jsx(cu,{className:"sr-only",children:"Archived sessions"}),s.jsx(du,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(uu,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(P,{name:"close",className:"size-4"})}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:s.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[w("__all__","All directories",b,u===null,()=>A(null)),h.map(v=>w(v.directory||"__none__",v.label,v.sessions.length,u===v.directory,()=>A(v.directory),v.directory||void 0,v.sessions))]})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{value:c,onChange:v=>{d(v.target.value),x(dr)},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"})]}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:S.length===1?`${S.length} archived session`:`${S.length} archived sessions`})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[g.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:y?"No matching archived sessions":"No archived sessions"})}):g.map(v=>{const I=Ee($n(v))??"",D=I?Ji(I,i)||I:null;return s.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:()=>j(v),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),j(v))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:js(v)}),y&&D?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate typography-micro text-subtle-foreground",title:I,children:D}):null,s.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:bh(v.time?.archived??v.time?.updated??v.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),C(v)},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 ${js(v)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),zs.requestDelete({sessions:[v],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 ${js(v)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},v.id)}),k>0?s.jsx("button",{type:"button",onClick:()=>x(v=>v+dr),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-subtle-foreground leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const om=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+n+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,n);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},im=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+n+r},os=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,am=e=>{if(!e||typeof e!="object")return null;const t=os(e.input),n=os(e.output),r=os(e.cacheRead),o=os(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},da=e=>{const t=am(e.info.usage);if(t)return t;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:os(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=os(o.input),a=os(o.output),c=os(o.reasoning),d=os(o.cache?.read),u=os(o.cache?.write);return{input:i,output:a,reasoning:c,cacheRead:d,cacheWrite:u,total:i+a+c+d+u}},rc=380,co=8,lm=140;function cm({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=l.useRef(null),i=l.useRef(null),[a,c]=l.useState(e),[d,u]=l.useState(!1),[f,m]=l.useState(null),{enabled:x}=bi();return l.useLayoutEffect(()=>{if(!e||!x||!a)return;const y=()=>{const S=n.current?.getBoundingClientRect(),g=i.current?.getBoundingClientRect();if(!S||!g){m(null);return}const k=S.left-g.left;m(Math.min(Math.max(k,co),Math.max(co,g.width-rc-co)))};y();const p=i.current;if(typeof ResizeObserver>"u"||!p)return;const h=new ResizeObserver(y);return h.observe(p),()=>h.disconnect()},[n,x,e,a]),l.useEffect(()=>{if(e){c(!0),u(!1);return}if(!a)return;u(!0);const y=window.setTimeout(()=>{c(!1),u(!1)},lm);return()=>window.clearTimeout(y)},[e,a]),l.useEffect(()=>{if(!e)return;const y=p=>{p.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,e]),l.useEffect(()=>{if(!e)return;const y=p=>{const h=p.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||n.current?.contains(h)||t()};return document.addEventListener("pointerdown",y,!0),r&&document.addEventListener("wheel",y,!0),()=>{document.removeEventListener("pointerdown",y,!0),r&&document.removeEventListener("wheel",y,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const ua=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Rr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),ur=({icon:e,iconNode:t,label:n,children:r})=>s.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[s.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?s.jsx(P,{name:e,className:"size-[18px]"}):null)}),s.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),dm=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:c,anchorLeft:d,isPopover:u}=cm({open:e,onClose:t,anchorRef:n,closeOnWheel:!0});return a?s.jsxs("div",{ref:i,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:[s.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",u?"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))",...u?{top:8,left:d??8,width:`min(${rc}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(ur,{iconNode:s.jsx(gl,{percentage:r.percentage}),label:"Context",children:s.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[s.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),s.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?s.jsxs(s.Fragment,{children:[s.jsx(ur,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:Rr(r.cacheRead)})}),s.jsx(ur,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:Rr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(ur,{icon:"check",label:"Cache hit",children:s.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):s.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),s.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},um=l.memo(function({open:t,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const a=l.useRef(null),c=_u(r??""),d=Gt(R=>R.providers),u=Gt(R=>R.currentProviderId),f=Gt(R=>R.currentModelId),m=Gt(R=>R.getCurrentModel()),x=Gt(R=>R.getModelMetadata);Gt(R=>R.modelsMetadata.size);const y=zu(l.useCallback(R=>r?R.sessionModelSelections.get(r)??null:null,[r])),p=l.useMemo(()=>{for(let R=c.length-1;R>=0;R-=1){const T=c[R]?.info;if(T.role!=="user")continue;const E=T.model,F=E?.providerID??E?.providerId,q=E?.modelID??E?.modelId,G=typeof F=="string"&&F.trim().length>0?F:void 0,L=typeof q=="string"&&q.trim().length>0?q:void 0;if(G&&L)return{providerID:G,modelID:L}}return null},[c]),h=l.useMemo(()=>{for(let R=c.length-1;R>=0;R-=1){const T=c[R];if(T?.info.role==="assistant"&&da(T).total>0)return T}return null},[c]),S=p??(()=>{const R=h?.info.model,T=R?.providerID??R?.providerId,E=R?.modelID??R?.modelId;return T&&E?{providerID:T,modelID:E}:null})()??(y?{providerID:y.providerId,modelID:y.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),k=(S?d.find(R=>R.id===S.providerID):void 0)?.models.find(R=>R.id===S?.modelID),b=S?x(S.providerID,S.modelID):void 0,A=ua(k?.limit,"context")??b?.limit?.context??ua(m?.limit,"context")??0,j=h?da(h):null,C=h?.info?.usage,w=C?im(C):j?.total??0,v=!i&&w>0&&A>0?Math.min(w/A*100,999):null,I=v!==null?`${Rr(w)}/${Rr(A)}`:null,D=v===null?"":v>=90?"text-[var(--status-error)]":v>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",z=j?.cacheRead??null,W=j?.cacheWrite??null,$=j?om({input:j.input,cache:{read:j.cacheRead,write:j.cacheWrite}}):{percent:0,hasInput:!1},K=$.hasInput?$.percent:null,B=v!==null&&I?{percentage:v,tokens:I,colorClass:D,cacheRead:z,cacheWrite:W,cacheHitPercent:K}:null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:a,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":t,onClick:()=>n(R=>!R),style:{touchAction:"manipulation"},children:B?s.jsx(gl,{percentage:B.percentage,size:20,className:"size-5 -rotate-90"}):s.jsx(P,{name:"pie-chart",className:"size-5"})}),s.jsx(dm,{open:t,onClose:()=>n(!1),anchorRef:a,contextDisplay:B})]})}),vn="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",fm="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",hm=l.memo(function({visible:t=!0,title:n,ariaLabel:r,onClick:o,className:i,Icon:a,iconClassName:c,pressed:d=!1}){return t?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:_(i??vn,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:a,className:c??"h-[18px] w-[18px]"})})}),s.jsx(Ge,{children:s.jsx("p",{children:n})})]}):null}),pm=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36).padStart(7,"0").slice(-6)},oc=({variant:e="desktop"})=>{const t=Us(f=>f.entries),[n,r]=l.useState(!1),o=l.useRef(null),i=l.useMemo(()=>[...t.values()].sort((f,m)=>m.startedAt-f.startedAt),[t]),a=i.filter(f=>f.state&&f.state.phase!=="failed"||bl(f)).length,c=l.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=l.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(l.useEffect(()=>()=>c(),[c]),i.length===0)return null;const u=f=>{if(!Wu(f))return;const m=f.receipt;if(!m)return;const x=Me.getState();x.newSessionDraft.open?x.setNewSessionDraftTarget({directoryOverride:m.path,worktreeIntent:null}):x.openNewSessionDraft({directoryOverride:m.path}),Us.getState().clearEntry(f.key),de.getState().setActiveMainTab("chat"),r(!1)};return s.jsxs(Yt,{open:n,onOpenChange:r,children:[s.jsx(Vt,{asChild:!0,children:s.jsxs("button",{type:"button",className:_(e==="desktop"?vn:"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"&&d()},children:[a>0?s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner"}):s.jsx(P,{name:"task",className:"size-[18px]"}),s.jsx("span",{children:"Background tasks"})]})}),s.jsxs(Qt,{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:d,children:[s.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[s.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:a===1?"1 worktree is being created":`${a} worktrees are being created`})]}),s.jsx("div",{className:"divide-y divide-border",children:i.map(f=>s.jsx(mm,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},mm=({entry:e,onOpen:t})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=bl(e),i=Uu(e),a=n?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":o?"Sending prompt...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return s.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[s.jsx("div",{className:"mt-0.5 shrink-0",children:r||o?s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner"}):n?s.jsx(P,{name:"alert",className:"size-4 text-[var(--status-error)]"}):s.jsx(P,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate typography-ui-label text-foreground",children:a}),s.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:n?e.state?.error:e.path??e.intent.sourceDirectory})]}),n?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.failedSend?s.jsx(Ne,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${pm(e.key)})`,onClick:()=>{const c=$u(e.key),d=Ku(c,"background-task");d&&ie.error(d.title,{description:d.description})},children:"Restore draft"}):null,s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",onClick:()=>Us.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Ne,{type:"button",size:"xs",onClick:t,children:"Open"}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Us.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:s.jsx(P,{name:"close",className:"size-3.5"})})]}):null]})},gm=["pinned","today","yesterday","thisWeek","lastWeek","older"],bm={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},xm=(e,t)=>{if(e==="sunday")return 0;if(e==="monday")return 1;try{const n=t||(typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().locale:"en-US");if(typeof Intl<"u"&&typeof Intl.Locale=="function"){const r=new Intl.Locale(n),i=(typeof r.getWeekInfo=="function"?r.getWeekInfo():r.weekInfo)?.firstDay;if(i===7||i===0)return 0;if(i!==void 0)return 1}}catch{}return 1},Zo=(e,t)=>{const n=new Date(e);n.setHours(0,0,0,0);const r=n.getTime(),o=new Date(r);o.setDate(o.getDate()-1),o.setHours(0,0,0,0);const i=o.getTime(),c=(n.getDay()-t+7)%7,d=new Date(r);d.setDate(d.getDate()-c),d.setHours(0,0,0,0);const u=d.getTime(),f=new Date(u);f.setDate(f.getDate()-7),f.setHours(0,0,0,0);const m=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:u,startOfLastWeek:m}},ym=(e,t)=>!Number.isFinite(e)||e<=0?"older":e>=t.startOfToday?"today":e>=t.startOfYesterday?"yesterday":e>=t.startOfThisWeek?"thisWeek":e>=t.startOfLastWeek?"lastWeek":"older",wm=(e,t)=>{const n={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,a=e.length;for(let d=0;d<a;d++){const u=e[d];if(o(u))n.pinned.push(u);else{const f=r(u),m=ym(f,i);n[m].push(u)}}const c=[];for(const d of gm){const u=n[d];u.length>0&&c.push({id:d,items:u})}return c},vm=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},Sm=(e,t)=>{const[n,r]=l.useState(0),o=l.useMemo(()=>e?Zo(Date.now(),t):null,[e,t,n]),i=o?.startOfToday??null;return l.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const a=Date.now(),c=window.setTimeout(()=>{r(u=>u+1)},Math.max(50,vm(a)-a+50)),d=()=>{document.visibilityState==="visible"&&Zo(Date.now(),t).startOfToday!==i&&r(u=>u+1)};return document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(c),document.removeEventListener("visibilitychange",d)}},[i,t,n]),o},jm=e=>{const{normalizedProjects:t,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:i,unresolvedWorktreeProjectPaths:a,foldersMap:c,createFolder:d,addSessionToFolder:u}=e;l.useEffect(()=>{!n||!o||i||t.forEach(f=>{if(a.has(f.normalizedPath))return;const m=Ol(f.normalizedPath),x=r.archivedSessionsByProject.get(f.id)??[],y=c[m]??[],p=new Map(y.map(h=>[h.name.toLowerCase(),h]));x.forEach(h=>{const S=xh(h,f.normalizedPath),g=S.toLowerCase();let k=p.get(g);k||(k=d(m,S),p.set(g,k)),k.sessionIds.includes(h.id)||u(m,k.id,h.id)})})},[t,n,r,o,i,a,c,d,u])},km=e=>({getOrderedGroups:l.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const i=new Map(r.map(u=>[u.id,u])),a=[];o.forEach(u=>{const f=i.get(u);f&&(a.push(f),i.delete(u))});const c=[],d=[];return r.forEach(u=>{i.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...a,...d]},[e])}),Cm=e=>{const{normalizedProjects:t,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:m,buildGroupSearchText:x,foldersMap:y}=e,p=l.useRef(new Map),h=l.useMemo(()=>{const w=p.current,v=new Map;let I=0,D=0;const z=($,K)=>$.length===K.length&&$.every((B,R)=>B===K[R]),W=t.map($=>{const K=n($.id),B=r($.id),R=i.has($.id)?!!i.get($.id):c,T=a.get($.id)??null,E=o.get($.normalizedPath)??[],F=w.get($.id);if(F&&F.project===$&&z(F.activeSessions,K)&&z(F.archivedSessions,B)&&F.rootBranch===T&&F.isRepo===R&&F.worktrees===E&&F.buildGroupedSessions===d)return I+=1,v.set($.id,F),F.section;D+=1;const q=Bl([...K,...B]),G=d(q,$.normalizedPath,E,T,R),L={project:$,groups:G};return v.set($.id,{project:$,activeSessions:K,archivedSessions:B,rootBranch:T,isRepo:R,worktrees:E,buildGroupedSessions:d,section:L}),L});return p.current=v,I>0&&Ht("ui.sidebar.project_section.reused",I),D>0&&Ht("ui.sidebar.project_section.rebuilt",D),W},[t,n,r,o,i,c,d,a]),S=l.useMemo(()=>h,[h]),g=l.useMemo(()=>{const w=new WeakMap;if(!u)return w;const v=I=>I.reduce((D,z)=>D+1+v(z.children),0);return S.forEach(I=>{I.groups.forEach(D=>{const z=m(D.sessions,f),W=v(z),$=x(D).includes(f),K=Ee(D.directory??null),R=(K?y[K]??[]:[]).filter(T=>T.name.toLowerCase().includes(f)).length;w.set(D,{filteredNodes:z,matchedSessionCount:W,folderNameMatchCount:R,groupMatches:$,hasMatch:$||W>0||R>0})})}),w},[u,S,m,f,x,y]),k=l.useMemo(()=>u?S.map(w=>({...w,groups:w.groups.filter(v=>g.get(v)?.hasMatch===!0)})).filter(w=>w.groups.length>0):S,[u,S,g]),b=u?k:S,A=l.useRef(new WeakMap),j=l.useMemo(()=>{const w=A.current;return b.map(v=>{const I=w.get(v);if(I&&I.query===f)return I.section;const D=v.groups.filter(T=>!T.isArchivedBucket),z=v.groups.filter(T=>T.isArchivedBucket),W=D.flatMap(T=>u?g.get(T)?.filteredNodes??[]:T.sessions),$=D.map(T=>({scopeKey:T.folderScopeKey??Ee(T.directory??null),directory:T.directory??null})).filter(T=>!!T.scopeKey),K=D.find(T=>T.isMain)??null,B={id:"flat",label:K?.label??"",branch:K?.branch??null,description:K?.description??null,isMain:!0,isArchivedBucket:!1,directory:K?.directory??v.project.normalizedPath,folderScopeKey:K?.folderScopeKey??v.project.normalizedPath,folderScopes:$,sessions:W};if(u){const T=D.map(E=>g.get(E)).filter(E=>!!E);g.set(B,{filteredNodes:W,matchedSessionCount:T.reduce((E,F)=>E+F.matchedSessionCount,0),folderNameMatchCount:T.reduce((E,F)=>E+F.folderNameMatchCount,0),groupMatches:T.some(E=>E.groupMatches),hasMatch:T.some(E=>E.hasMatch)})}const R={project:v.project,groups:[B,...z]};return w.set(v,{query:f,section:R}),R})},[g,u,f,b]),C=l.useMemo(()=>u?b.reduce((w,v)=>w+v.groups.reduce((I,D)=>{const z=g.get(D);if(!z)return I;const W=z.folderNameMatchCount+(z.groupMatches?1:0);return I+z.matchedSessionCount+W},0),0):0,[u,b,g]);return{projectSections:h,visibleProjectSections:S,groupSearchDataByGroup:g,searchableProjectSections:k,sectionsForRender:b,flatSectionsForRender:j,searchMatchCount:C}},Am=e=>{const{projectSections:t,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:a,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:m}=e,x=l.useMemo(()=>{const p=new Map,h=new Map,S=(g,k,b,A)=>{p.has(g)||p.set(g,new Map);const j=p.get(g);A.forEach(C=>{const w=Ee(C.session.directory??b??k);j.set(C.session.id,{directory:w}),h.has(g)||h.set(g,{id:C.session.id,directory:w}),C.children.length>0&&S(g,k,w,C.children)})};return t.forEach(g=>{g.groups.forEach(k=>{S(g.project.id,g.project.normalizedPath,k.directory,k.sessions)})}),{metaByProject:p,firstSessionByProject:h}},[t]),y=l.useRef(null);l.useLayoutEffect(()=>{if(!n)return;if(c){y.current=n;return}if(y.current===n)return;const p=t.find(C=>C.project.id===n);if(!p)return;y.current=n;const h=x.metaByProject.get(n);if(i&&h&&h.has(i)){o(C=>{if(C.get(n)===i)return C;const w=new Map(C);return w.set(n,i),w});return}const S=i?Array.from(x.metaByProject.entries()).some(([C,w])=>C!==n&&w.has(i)):!1;if(i&&h&&!S)return;if(!h||h.size===0){f("chat"),d&&m(!1),u({selectedProjectId:p.project.id,directoryOverride:p.project.normalizedPath});return}const g=r.get(n),k=g&&h.has(g)?g:null,b=x.firstSessionByProject.get(n)?.id??null,A=k??b;if(!A||A===i)return;const j=h.get(A)?.directory??null;a(A,j,{keepPanelOpen:!0})},[n,r,i,a,c,d,u,t,x,f,m,o]),l.useEffect(()=>{if(!n||!i)return;const p=x.metaByProject.get(n);!p||!p.has(i)||o(h=>{if(h.get(n)===i)return h;const S=new Map(h);return S.set(n,i),S})},[n,i,x,o])},Nm=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...n})=>{const r=Me(c=>c.currentSessionId),o=Me(c=>!!c.newSessionDraft?.open),[i,a]=l.useState(()=>new Map(e));return Am({...n,activeSessionByProject:i,setActiveSessionByProject:a,currentSessionId:r,newSessionDraftOpen:o}),l.useEffect(()=>{t(i)},[i,t]),null},fa=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Im=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return t>>>0},Em=(e,t,n)=>(n.get(e)??0)>0?e:t.get(e)??null,ic=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=Im(e.trim())%fa.length;return fa[t]},Dm=(e,t)=>{const n=ic(e);return n?t?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},ha=e=>!!e.time?.archived,Rm=e=>{const t=l.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),n=l.useCallback(i=>{const a=Ee(i.directory??null)??"";return`${js(i)} ${a}`.toLowerCase()},[]),r=l.useCallback((i,a)=>a?i.flatMap(c=>{if(n(c.session).includes(a))return[c];const u=r(c.children,a);return u.length===0?[]:[{...c,children:u}]}):i,[n]),o=l.useCallback((i,a,c=[],d,u)=>{const f=Ee(a??null),m=Bl(i).sort(xl(e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(m.map(w=>[w.id,w])),y=new Map,p=new Map;m.forEach(w=>{const v=w.parentID??null,I=v?x.get(v):null,D=I&&ha(I)===ha(w)?v:null;y.set(w.id,D),D&&p.set(D,(p.get(D)??0)+1)});const h=c.map(w=>({worktree:w,directory:Ee(w.path)})).filter(w=>!!w.directory&&!w.worktree.isPrimary).sort((w,v)=>v.directory.length-w.directory.length),S=(w,v)=>v===w||v.startsWith(`${w}/`),g=w=>{const v=Ee(w.directory??null);return v?h.find(I=>S(I.directory,v))?.worktree??null:null},k=(w,v)=>{const I=Em(w.id,y,p);return{session:w,children:[],worktree:v,forkColorId:I}},b=[],A=new Map,j=[];for(const w of h)A.set(w.directory,[]);m.forEach(w=>{const v=g(w),I=k(w,v);w.time?.archived?j.push(I):v?A.get(Ee(v.path)??"")?.push(I):b.push(I)});const C=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?_o(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:b}];for(const{worktree:w,directory:v}of h)C.push({id:`worktree:${v}`,label:w.branch||(w.detached?"Detached HEAD":w.name),branch:w.branch,description:_o(v,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:w,directory:v,folderScopeKey:v,sessions:A.get(v)??[]});return j.length>0&&C.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?Ol(f):null,sessions:j}),C},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Pm=({mobileVariant:e,isTablet:t})=>!e&&!t,Tm=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{l.useEffect(()=>{if(!e||!t||typeof window>"u")return;const i=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(i)},[e,t,r]),l.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=a=>{o.current&&(o.current.contains(a.target)||n(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,n,o])},Mm=e=>{const[t,n]=l.useState(null),r=l.useRef(null);l.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=l.useCallback((b,A,j)=>{zo("navigation.session_select"),de.getState().closeMainSurfaces();const C=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},w=j?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),b===Me.getState().currentSessionId){e.allowReselect&&w&&e.onSessionSelected?.(b),C();return}zo("navigation.session_state_set"),e.setCurrentSession(b,A??null),w&&e.onSessionSelected?.(b),C()},[e]),i=l.useCallback((b,A)=>{e.setEditingId(b),e.setEditTitle(A)},[e]),a=l.useCallback(async b=>{if(!e.editingId)return;const A=(b??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=l.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=l.useCallback(async(b,A)=>{try{return(await ps(b)).ok?(n(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=l.useCallback(async b=>{const A=await e.shareSession(b.id);if(!A?.share?.url){ie.error("Unable to share session");return}const j=await d(A.share.url,b.id);ie[j?"success":"warning"]("Session shared",{description:j?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=l.useCallback((b,A)=>{d(b,A).then(j=>{j||ie.error("Failed to copy URL")})},[d]),m=l.useCallback(b=>{ps(b).then(A=>{if(A.ok){ie.success("Session ID copied");return}ie.error("Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[]),x=l.useCallback(async b=>{await e.unshareSession(b)?ie.success("Session unshared"):ie.error("Unable to unshare session")},[e]),y=l.useCallback(b=>{const A=[],j=C=>{(e.childrenMap.get(C)??[]).forEach(v=>{A.push(v),j(v.id)})};return j(b),A},[e.childrenMap]),p=l.useCallback((b,A)=>A?b:b.filter(j=>!j.time?.archived),[]),h=l.useCallback(async(b,A,j)=>{const C=A?.archivedBucket===!0||A?.hardDelete===!0,w=j?.descendantIds??p(y(b.id),C).map(z=>z.id);if(w.length===0){(C?await e.deleteSession(b.id):await e.archiveSession(b.id))?ie.success(C?"Session deleted":"Session archived"):ie.error(C?"Failed to delete session":"Failed to archive session");return}const v=[b.id,...w];if(C){const{deletedIds:z,failedIds:W}=await e.deleteSessions(v);if(W.length===0){const $=z.length;ie.success($===1?`Deleted ${$} session`:`Deleted ${$} sessions`)}else ie.error("Failed to delete session");return}const{archivedIds:I,failedIds:D}=await e.archiveSessions(v);I.length>0&&ie.success(I.length===1?`Archived ${I.length} session`:`Archived ${I.length} sessions`),D.length>0&&ie.error(D.length===1?`Failed to archive ${D.length} session`:`Failed to archive ${D.length} sessions`)},[e,y,p]),S=l.useCallback((b,A)=>{const j=A?.archivedBucket===!0||A?.hardDelete===!0,C=p(y(b.id),j).map(w=>w.id);if(!e.showDeletionDialog||A?.skipConfirm===!0){h(b,A,{descendantIds:C});return}e.setDeleteSessionConfirm({session:b,descendantCount:C.length,descendantIds:C,archivedBucket:j})},[e,y,h,p]),g=l.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:b,archivedBucket:A,descendantIds:j}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(b,{archivedBucket:A},{descendantIds:j})},[e,h]),k=l.useCallback(async b=>{await e.unarchiveSession(b.id)?ie.success("Session restored"):ie.error("Failed to restore session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:a,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:m,handleUnshareSession:x,handleDeleteSession:S,handleRestoreSession:k,confirmDeleteSession:g}},Fm=e=>{const{safeStorage:t,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:a}=e,c=l.useRef(null),d=l.useRef(null),u=l.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:x}=ut.getState(),y=x.map(p=>({...p,sidebarCollapsed:m.has(p.id)}));Rl({projects:y}).catch(()=>{})},[]),f=l.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return l.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),l.useEffect(()=>{try{const m=t.getItem(n.sessionExpanded);if(m){const y=JSON.parse(m);Array.isArray(y)&&i(new Set(y.filter(p=>typeof p=="string")))}const x=t.getItem(n.projectCollapse);if(x){const y=JSON.parse(x);Array.isArray(y)&&a(new Set(y.filter(p=>typeof p=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,t,a,i]),l.useEffect(()=>{try{const m=Object.fromEntries(r.entries());t.setItem(n.groupOrder,JSON.stringify(m))}catch{}},[r,n.groupOrder,t]),l.useEffect(()=>{try{t.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},Lm=3;let Pr=0;const ac=[],Om=()=>Pr<Lm?(Pr+=1,Promise.resolve()):new Promise(e=>{ac.push(e)}),Bm=()=>{const e=ac.shift();if(e){e();return}Pr=Math.max(0,Pr-1)},_m=async e=>{await Om();try{return await e()}finally{Bm()}},zm=5*6e4,Um=e=>{const{normalizedProjects:t,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:a}=Gs(),c=yl(p=>p.ensureStatus),d=l.useMemo(()=>t.map(p=>p.normalizedPath).slice().sort().join("\0"),[t]),u=l.useRef(null);l.useEffect(()=>{if(!n||!a||t.length===0){u.current=null,o(new Map);return}const p=`${lt()}\0${d}`;u.current!==p&&(u.current=p,t.forEach(h=>{_m(()=>c(h.normalizedPath,a))}))},[n,t,d,a,c,o]);const f=l.useRef(null);l.useEffect(()=>{if(!n){f.current=null;return}const p=new Map;t.forEach(S=>{p.set(S.id,r.get(S.normalizedPath)?.isGitRepo??null)});const h=t.map(S=>`${S.id}:${String(p.get(S.id))}`).join("|");f.current!==h&&(f.current=h,o(p))},[n,t,d,r,o]);const m=l.useMemo(()=>t.map(p=>{const h=r.get(p.normalizedPath)?.branch??"";return`${p.id}:${h}`}).join("|"),[t,r]),x=l.useRef(new Map),y=l.useRef(new Map);l.useEffect(()=>{if(!n)return;let p=!1;const h=setTimeout(()=>{(async()=>{const g=new Set(t.map(C=>C.id));for(const C of x.current.keys())g.has(C)||(x.current.delete(C),y.current.delete(C));const k=Date.now();if(t.filter(C=>{const w=r.get(C.normalizedPath);if(w?.isGitRepo===!1)return x.current.delete(C.id),y.current.delete(C.id),!1;if(w?.isGitRepo!==!0||w.branch===null)return!1;const v=w.branch.trim(),I=`${C.normalizedPath}\0${v}`,D=x.current.get(C.id);if(D===I){const z=y.current.get(C.id);return z&&(z.at=k),!1}return!(D!==void 0&&k-(y.current.get(C.id)?.at??0)<zm)}).length===0)return;const A=[];if(t.forEach(C=>{const w=r.get(C.normalizedPath)?.branch?.trim()??"",v=`${C.normalizedPath}\0${w}`;w&&A.push({id:C.id,inputKey:v,branch:w})}),p||A.length===0)return;const j=Date.now();i(C=>{const w=new Map(C);return A.forEach(({id:v,branch:I})=>{I&&w.set(v,I)}),w}),A.forEach(({id:C,inputKey:w,branch:v})=>{x.current.set(C,w),v&&y.current.set(C,{branch:v,at:j})})})()},150);return()=>{p=!0,clearTimeout(h)}},[n,t,m,r,i])},$m=e=>{const{ownership:t}=e,n=l.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=l.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Km=e=>{const t=new Map;for(const n of e){const r=$n(n);r&&t.set(n.id,{directory:r,sessionId:n.id})}return t},Wm=(e,t)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{t.has(o)||n.push(r)}),n},Gm=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=l.useRef(null);l.useEffect(()=>{if(!t||!n)return;const i=lt(),a=Km(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const d of Wm(c,a))sn().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:i,identities:a}},[t,n,r])},Hm=(e,t)=>e?t.kind!==e.kind?t.kind==="project":t.projectRoot.length!==e.projectRoot.length?t.projectRoot.length>e.projectRoot.length:t.projectId.localeCompare(e.projectId)<0:!0,pa=(e,t,n)=>{Hm(e.get(t),n)&&e.set(t,n)},lc=e=>{const t=e;return Ee(t.directory)??Ee(t.project?.worktree)},qm=(e,t,n)=>{if(e.time?.archived)return!0;const r=lc(e);if(!r)return n?.allowUnknownDirectory??!0;if(Ur(r,n?.homeDirectory))return!0;if(t.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Ee(i)?.toLowerCase()===o)return!0;return!1},Ym=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const t=e.lastIndexOf("/");return t<0?null:t===0?"/":t===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,t)},Vm=(e,t,n,r=[])=>{const o=new Map,i=new Map;for(const y of t){const p=Ee(y.normalizedPath);if(!p)continue;const h=i.get(p);(!h||y.id.localeCompare(h.id)<0)&&i.set(p,y),pa(o,p,{projectId:y.id,projectRoot:p,scopeDirectory:p,kind:"project"})}if(n)for(const[y,p]of n){const h=Ee(y),S=h?i.get(h):void 0;if(!(!S||!h))for(const g of p||[]){const k=Ee(g?.path);k&&pa(o,k,{projectId:S.id,projectRoot:h,scopeDirectory:k,kind:"worktree"})}}const a=new Map,c=new Map,d=new Map,u=new Map,f=new Map,m=y=>{if(!y)return null;if(a.has(y))return a.get(y)??null;const p=[];let h=y,S=null;for(;h;){if(a.has(h)){S=a.get(h)??null;break}if(p.push(h),S=o.get(h)??null,S)break;h=Ym(h)}for(const g of p)a.set(g,S);return S},x=(y,p,h)=>{for(const S of y){const g=lc(S);if(Ur(g))continue;const k=m(g);if(!k)continue;c.set(S.id,k);const b=p.get(k.projectId);if(b?b.push(S):p.set(k.projectId,[S]),!h)continue;const A=h.get(k.scopeDirectory);A?A.add(S.id):h.set(k.scopeDirectory,new Set([S.id]))}};return x(e,d,f),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:a.size}};function cc({state:e,activeLabel:t,unreadLabel:n,inputLabel:r,className:o}){if(e==="input"){const i=r??"Needs input";return s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":i,title:i,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return e==="unread"?s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":n??t,title:n??t,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":t,title:t,children:s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Qm=({folder:e,displayName:t,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:a,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:m,projectId:x,mobileVariant:y=!1,alwaysShowActions:p=y,isRenaming:h=!1,renameDraft:S="",onRenameDraftChange:g,onRenameSave:k,onRenameCancel:b,droppableRef:A,isDropTarget:j=!1,onNewSession:C,depth:w=0,hideActions:v=!1,archivedBucket:I=!1})=>{const[D,z]=l.useState(!1),[W,$]=l.useState(""),K=l.useRef(null),B=h||D,R=h?S:W,T=l.useCallback(()=>{$(e.name),z(!0)},[e.name]),E=l.useCallback(()=>{const L=R.trim();L&&L!==e.name&&c(L),h&&k&&k(),z(!1),$("")},[R,e.name,h,c,k]),F=l.useCallback(()=>{h&&b&&b(),z(!1),$("")},[h,b]),q=l.useCallback(L=>{h&&g?g(L):$(L)},[h,g]);l.useEffect(()=>{if(!h)return;const L=()=>{const Ae=K.current;Ae&&(Ae.focus(),Ae.select())},le=requestAnimationFrame(L),H=window.setTimeout(L,0);return()=>{cancelAnimationFrame(le),window.clearTimeout(H)}},[h]);const G=o?"folder":"folder-open";return s.jsxs("div",{className:"oc-folder",children:[s.jsxs("div",{ref:A,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",j&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:B?void 0:L=>{L.currentTarget.blur(),a()},role:B?void 0:"button",tabIndex:B?void 0:0,onKeyDown:B?void 0:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),a())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[s.jsxs("div",{className:_("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",I?p?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":p?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[s.jsx(P,{name:G,className:_(yr,j?"text-primary":"text-muted-foreground")}),B?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onSubmit:L=>{L.preventDefault(),E()},children:[s.jsx("input",{ref:K,value:R,onChange:L=>q(L.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:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onKeyDown:L=>{if(L.key==="Escape"){L.stopPropagation(),F();return}(L.key===" "||L.key==="Enter")&&L.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),F()},onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("span",{className:_(_l,j?"text-primary":"text-muted-foreground"),children:t??e.name})}),s.jsx(Ge,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),s.jsxs("span",{className:"typography-micro text-subtle-foreground flex-shrink-0",children:["• ",n.length]}),i?s.jsx(cc,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?s.jsx(P,{name:"arrow-right-s",className:_(yr,"text-muted-foreground")}):s.jsx(P,{name:"arrow-down-s",className:_(yr,"text-muted-foreground")})]})]}),!B&&(!v||I)?s.jsx("div",{className:_("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",p?"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:s.jsxs("div",{className:"flex items-center gap-0.5",children:[!I&&C?s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),C()},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:s.jsx(P,{name:"add",className:"size-4"})}):null,I?null:s.jsx("button",{type:"button",onClick:L=>{L.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:s.jsx(P,{name:"pencil-ai",className:"size-4"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":I?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:s.jsx(P,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:s.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(L=>s.jsx(l.Fragment,{children:u(L,0,m??null,x??null,I,void 0,"project",f?.(L))},L.session.id)):r?null:s.jsx("div",{className:"py-1 px-3 text-left typography-micro text-subtle-foreground",children:"Empty folder"})]})]})},Jm=l.memo(Qm),Wr=l.createContext(null),Xm=({sessionId:e,sessionDirectory:t,sessionTitle:n,children:r})=>{const{attributes:o,listeners:i,setNodeRef:a,isDragging:c}=fu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:n}}),d=l.useCallback(u=>{u.stopPropagation(),i?.onPointerDown&&i.onPointerDown(u)},[i]);return s.jsx("div",{ref:a,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Zm=({folderId:e,children:t})=>{const{setNodeRef:n,isOver:r}=il({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return s.jsx(s.Fragment,{children:t(n,r)})},eg=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:n,children:r})=>{const o=_r(fn(rl,{activationConstraint:{distance:8}})),[i,a]=l.useState(null),[c,d]=l.useState("Session"),[u,f]=l.useState(null),[m,x]=l.useState(null);if(!e)return s.jsx(s.Fragment,{children:r});const y=p=>{a(null),f(null),x(null);const{active:h,over:S}=p;if(!S)return;const g=h.data.current,k=S.data.current;g?.type==="session"&&g.sessionId&&k?.type==="folder"&&k.folderId&&n(g.sessionId,k.folderId)};return s.jsxs(zr,{sensors:o,collisionDetection:pi,onDragStart:p=>{const h=p.active.data.current;if(h?.type==="session"&&h.sessionId){a(h.sessionId),d(h.sessionTitle??"Session");const S=p.active.rect.current.initial?.width,g=p.active.rect.current.initial?.height;f(typeof S=="number"?S:null),x(typeof g=="number"?g:null)}},onDragCancel:()=>{a(null),f(null),x(null)},onDragEnd:y,children:[r,s.jsx(ol,{children:i&&t?s.jsxs("div",{style:{width:u?`${u}px`:"auto",height:m?`${m}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[s.jsx(P,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Gr="gap-2",dc="my-0.5 rounded-lg py-1.5",Xn=l.createContext("card"),qt=({icon:e,children:t,onClick:n,className:r,mobileVariant:o=!1})=>{const i=l.useContext(Xn)==="tree";return s.jsxs("button",{type:"button",onClick:n,"data-sidebar-tree-row":i?"":void 0,className:_(o?yh:wh,i&&Gr,i&&dc,r),children:[s.jsx(P,{name:e,className:_($s(o),"text-muted-foreground")}),s.jsx("span",{className:_(gn(o),"flex-1 text-muted-foreground"),children:t})]})},tg="select-none px-3 pb-1 typography-ui-label font-semibold text-muted-foreground",cn=({label:e,first:t=!1,count:n,expanded:r,onToggle:o})=>{const i=t?"pt-1":"pt-3",a=typeof n=="number"?s.jsx("span",{className:"font-normal tabular-nums text-subtle-foreground",children:n}):null;return o?s.jsx("div",{role:"heading","aria-level":3,className:i,children:s.jsxs("button",{type:"button","aria-expanded":r,onClick:o,className:"group/heading flex h-7 w-full select-none items-center gap-1.5 rounded-md px-3 text-left typography-ui-label font-semibold text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e,a,s.jsx(P,{name:r?"arrow-down-s":"arrow-right-s",className:"ml-auto size-4 shrink-0 text-muted-foreground group-hover/heading:text-foreground"})]})}):s.jsxs("div",{role:"heading","aria-level":3,className:_(tg,i,"flex items-center gap-1.5"),children:[e,a]})},ma=(e,t,n)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const a of o.children)i=r(a)||i;return i&&n.add(o.session.id),i};for(const o of e)r(o)},hs=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const n of e.children)if(hs(n,t))return!0;return!1},sg=(e,t)=>{const n=new Set(e);return e.map(r=>t.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let i=r.session.parentID??null;for(;i&&!o.has(i);){if(n.has(i)&&t.has(i))return!1;o.add(i),i=t.get(i)?.session?.parentID??null}return!0})},ga=new WeakMap;let ba=1;const ng=e=>{const t=ga.get(e);if(t!==void 0)return t;const n=ba;return ba+=1,ga.set(e,n),n},ei=e=>e.children.length===0?"":e.children.map(n=>{const r=ng(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${ei(n)}`}).join("|"),uc=(e,t,n,r,o,i)=>{const a=lt(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,m=u.session.directory??i,x=Yi(a,f??"",d.session.id),y=Yi(a,m??"",u.session.id);return(x?n.has(x):!1)!==(y?r.has(y):!1)?!0:d.children.some((p,h)=>c(p,u.children[h]))};return c(e,t)},Tr=(e,t,n,r)=>{if(!t)return null;const o=r?"archived":"active";let i=null;const a=c=>{if(`${n}:${o}:${c.session.id}`===t)return i=c.session.id,!0;for(const u of c.children)if(a(u))return!0;return!1};return e.forEach(c=>a(c)),i},rg=5*6e4,og=6e4,xa=5*6e4,ya=100,Pn=new Map,nn=new Map,Bs=new Map,dn=new Map,Zn=(e,t)=>{const n=ms((e??"").trim()),r=(t??"").trim();return!n||!r?"":`${lt()}
|
|
12
|
+
${n}
|
|
13
|
+
${r}`},wa=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),ig=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},ag=e=>{const t=Object.keys(e);if(t.length<=ya)return e;const n=t.sort((o,i)=>(dn.get(o)??0)-(dn.get(i)??0)),r={...e};for(let o=0;o<n.length-ya;o+=1){const i=n[o];delete r[i],dn.delete(i),nn.delete(i);const a=Bs.get(i);a!==void 0&&(clearTimeout(a),Bs.delete(i))}return r},fc=e=>e.pr?e.pr.state!=="open"?xa:e.checks?.state==="pending"?og:xa:rg,ti=(e,t,n,r)=>{if(typeof window>"u"||Bs.has(e))return;const o=is.getState().results[e];if(!o)return;const i=fc(o),a=setTimeout(()=>{if(Bs.delete(e),!!is.getState().results[e]){if(typeof document<"u"&&document.hidden){ti(e,t,n,r);return}is.getState().refresh(t,n,r)}},i);typeof a=="object"&&a!==null&&typeof a.unref=="function"&&a.unref(),Bs.set(e,a)},is=Is()($r((e,t)=>({results:{},refresh:async(n,r,o,i)=>{const a=ms((n||"").trim()),c=(r||"").trim();if(!a||!c)return null;const d=Zn(a,c);if(!d)return null;const u=Pn.get(d);if(u&&!i?.force)return u;const f=o??null;if(!f)return t().results[d]??null;const m=(nn.get(d)??0)+1;nn.set(d,m);const x=t().results[d]??wa();e(p=>({results:{...p.results,[d]:{...x,isLoading:!0}}}));const y=(async()=>{try{const p=await f.prStatus(a,c);if(nn.get(d)!==m||lt()!==d.split(`
|
|
14
|
+
`)[0])return t().results[d]??null;const h={pr:p.pr??null,checks:p.checks??null,checksStale:p.checksStale,defaultBranch:p.defaultBranch??null,skippedDefaultBranch:p.skippedDefaultBranch,fetchedAt:p.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return dn.set(d,Date.now()),e(S=>({results:ag({...S.results,[d]:h})})),ti(d,a,c,f),h}catch(p){if(nn.get(d)!==m)return t().results[d]??null;const h=ig(p),S=x.pr||x.fetchedAt?{...x,isLoading:!1,stale:!0,error:h}:{...wa(),error:h};return e(g=>({results:{...g.results,[d]:S}})),ti(d,a,c,f),S}})();Pn.set(d,y);try{return await y}finally{Pn.get(d)===y&&Pn.delete(d)}},load:async(n,r,o)=>{const i=ms((n||"").trim()),a=(r||"").trim();if(!i||!a)return null;const c=Zn(i,a);dn.set(c,Date.now());const d=t().results[c];return d&&(d.pr||d.fetchedAt)?(t().refresh(i,a,o),d):t().refresh(i,a,o)},resetForRuntimeSwitch:()=>{Pn.clear(),nn.clear(),dn.clear(),Fn=null;for(const n of Bs.values())clearTimeout(n);Bs.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(yn(()=>{is.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await xt(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-Cfrwo5uQ.js").then(o=>o.cU);return{getRegisteredRuntimeAPIs:r}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:r})=>r()?.github??null).catch(()=>null);if(!e)return;const t=Date.now(),n=Object.entries(is.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=fc(r)).map(([r])=>r);for(const r of n){const[,o,i]=r.split(`
|
|
15
|
+
`);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await is.getState().refresh(o,i,e).catch(()=>null)}}})()}));let Fn=null;const qw=e=>{if(Fn&&Fn.results===e)return Fn.index;const t=new Map;for(const n of Object.values(e)){const r=n.pr?.url;!r||t.has(r)||t.set(r,n.checks?.state??null)}return Fn={results:e,index:t},t},lg=e=>{const t=e?.pr;if(!t)return null;if(t.state==="merged")return{visualState:"merged",number:t.number,draft:t.draft,title:t.title};if(t.state==="closed")return{visualState:"closed",number:t.number,draft:t.draft,title:t.title};if(t.draft)return{visualState:"draft",number:t.number,draft:!0,title:t.title,mergeableState:t.mergeableState??void 0,checks:e?.checks?{state:e.checks.state}:void 0};const n=e?.checks?.state,r=t.mergeableState??void 0;return r==="dirty"||r==="blocked"||n==="failure"?{visualState:"blocked",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}:{visualState:"open",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}},hc=e=>{const t=is(n=>e?n.results[e]??null:null);return l.useMemo(()=>lg(t),[t])},pc=(e,t,n)=>{const r=l.useMemo(()=>Zn(e,t),[e,t]),o=n??null;l.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return xt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-Cfrwo5uQ.js").then(c=>c.cU);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{if(i)return;const c=o??a()?.github??null;c&&is.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},mc=new Set,Si=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,si=(e,t,n,r=mc)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(si(i,t,n,r)==="input")return"input";return"active"}let o=n.has(e.session.id)?"unread":null;for(const i of e.children)if(o=Si(o,si(i,t,n,r)),o==="input")return o;return o},gc=(e,t,n,r=mc)=>{let o=null;for(const i of e)if(o=Si(o,si(i,t,n,r)),o==="input")return o;return o},cg=50,dg=28;function ug({visibleSessions:e,shouldVirtualize:t,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:i,isArchivedBucket:a,renderSessionNode:c,getRenderExtras:d}){const u=l.useRef(null),[f,m]=l.useState(null),[x,y]=l.useState(0),[,p]=l.useState(0);l.useEffect(()=>{if(!t)return;const g=u.current;if(!g||typeof ResizeObserver>"u")return;const k=new ResizeObserver(()=>p(b=>b+1));return k.observe(g),()=>k.disconnect()},[t]),l.useLayoutEffect(()=>{if(!t){f!==null&&m(null),x!==0&&y(0);return}const g=u.current;if(!g)return;let k=f;const b=r?.current??null;if(b&&b.contains(g)){if(k=b,k!==f){m(k);return}}else if(!k||!k.contains(g)){let j=g.parentElement;for(;j;){const C=window.getComputedStyle(j);if(C.overflowY==="auto"||C.overflowY==="scroll"){k=j;break}j=j.parentElement}if(k!==f){m(k);return}}if(!k)return;const A=g.getBoundingClientRect().top-k.getBoundingClientRect().top+k.scrollTop;y(j=>Math.abs(j-A)<1?j:A)},[f,x,r,t]);const h=t&&f!==null,S=hu({count:e.length,enabled:h,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>dg,overscan:n?20:8,scrollMargin:x,getItemKey:g=>e[g]?.session.id??g});return s.jsx("div",{ref:u,children:t?s.jsx("div",{style:{height:S.getTotalSize(),position:"relative"},children:S.getVirtualItems().map(g=>{const k=e[g.index];return k?s.jsx("div",{"data-index":g.index,ref:S.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${g.start-x}px)`},children:c(k,0,o,i,a,void 0,"project",d(k))},k.session.id):null})}):e.map(g=>s.jsx(l.Fragment,{children:c(g,0,o,i,a,void 0,"project",d(g))},g.session.id))})}const Sr=(e,t)=>{if(!t)return e;const n=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let a=0,c=n.indexOf(r,a);for(;c!==-1;){c>a&&i.push(e.slice(a,c));const d=e.slice(c,c+o);i.push(s.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),a=c+o,c=n.indexOf(r,a)}return a<e.length&&i.push(e.slice(a)),i.length>0?i:e},Sn=e=>[lt(),...e.map(t=>(t??"").toString())].join(`
|
|
16
|
+
`),fr=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},fg=200,an=(e={})=>{const t=e.maxEntries??fg,n=new Map,r=new Map,o=new Map;let i=0;const a=new Map,c=new Map,d=h=>{const S=n.get(h)??null;return S&&a.set(h,i+=1),S},u=h=>{const S=c.get(h);if(S)for(const g of[...S])try{g()}catch{}},f=()=>{if(n.size<=t)return;const h=[...n.keys()].filter(g=>!r.has(g)&&(c.get(g)?.size??0)===0).sort((g,k)=>(a.get(g)??0)-(a.get(k)??0)),S=n.size-t;for(let g=0;g<S&&g<h.length;g+=1){const k=h[g];n.delete(k),a.delete(k),o.set(k,(o.get(k)??0)+1)}};let m=!1;const x=()=>{if(m||n.size<=t)return;m=!0;const h=()=>{m=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(h):setTimeout(h,0)},y=(h,S)=>{const k={...n.get(h)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(h)??0},...S};return n.set(h,k),a.set(h,i+=1),x(),u(h),k},p=async(h,S)=>{const g=r.get(h);if(g)return g;const k=(o.get(h)??0)+1;o.set(h,k);const b=n.get(h);y(h,{isLoading:!0,generation:k});const A=(async()=>{try{const j=await S();return o.get(h)!==k?n.get(h)??{data:j,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:k}:y(h,{data:j,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:k})}catch(j){return o.get(h)!==k?n.get(h)??{data:b?.data??null,fetchedAt:b?.fetchedAt??null,isLoading:!1,stale:!0,error:fr(j),generation:k}:b?.data!=null?y(h,{isLoading:!1,stale:!0,error:fr(j),generation:k}):y(h,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:fr(j),generation:k})}})();r.set(h,A);try{return await A}finally{r.get(h)===A&&r.delete(h),e.onSettle?.(h)}};return{getEntry:d,snapshot:()=>Object.fromEntries(n),subscribe:(h,S)=>{let g=c.get(h);return g||(g=new Set,c.set(h,g)),g.add(S),()=>{const k=c.get(h);k&&(k.delete(S),k.size===0&&c.delete(h))}},ensure:(h,S,g)=>!g?.force&&r.has(h)?r.get(h):!g?.force&&n.get(h)?.data!=null&&n.get(h)?.isLoading?r.get(h)??Promise.resolve(n.get(h)):!g?.force&&n.get(h)?.data!=null?(p(h,S),Promise.resolve(n.get(h))):p(h,S),refresh:(h,S)=>p(h,S),invalidate:async(h,S,g)=>{if(g?.exact??!0)return o.set(h,(o.get(h)??0)+1),n.delete(h),a.delete(h),r.has(h)&&r.delete(h),u(h),S?p(h,S):null;for(const b of[...n.keys()])(b===h||b.startsWith(h))&&(o.set(b,(o.get(b)??0)+1),n.delete(b),a.delete(b),r.delete(b),u(b));return null},markStale:h=>{const S=n.get(h);S?.data&&(S.stale||y(h,{stale:!0}))},setError:(h,S)=>{const g=n.get(h);return g?.data?y(h,{isLoading:!1,stale:!0,error:fr(S)}):g??null},remove:h=>{o.set(h,(o.get(h)??0)+1),n.delete(h),a.delete(h),r.delete(h),u(h)},reset:()=>{const h=[...n.keys()];n.clear(),r.clear(),o.clear(),a.clear();for(const S of h)u(S)}}},jn=(e,t)=>Re.useSyncExternalStore(n=>t?e.subscribe(t,n):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),Yw=e=>{const t=e.trim().match(/^#?(\d{1,7})$/);if(!t)return null;const n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:null},bc=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),ni=e=>{if(!e)return[];const t=[];for(const n of e)n?.login&&t.push(n.login.toLowerCase());return t},xc=e=>{const t=[],n=[];for(const r of e.trim().toLowerCase().split(/\s+/))r&&(r.startsWith("label:")&&r.length>6?n.push(r.slice(6)):t.push(r));return{tokens:t,labelTokens:n}},ji=e=>{if(!e)return[];const t=[];for(const n of e)n?.name&&t.push(n.name.toLowerCase());return t},yc=(e,t,n)=>{const r=ji(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...n])if(!r.some(a=>a===i||a.includes(i)))return!1;return!0},hg=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const n of ji(e.labels))t.push(n);return t},pg=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const n of ji(e.labels))t.push(n);return t},wc=(e,t)=>{for(const n of t){let r=!1;for(const o of e)if(o.includes(n)){r=!0;break}if(!r)return!1}return!0},va=e=>e.state==="merged"||!!e.mergedAt,mg=(e,t)=>t==="all"?e:t==="open"?e.filter(n=>n.state==="open"):t==="merged"?e.filter(n=>va(n)):e.filter(n=>n.state==="closed"&&!va(n)),gg=(e,t)=>t==="all"?e:e.filter(n=>n.state===t),bg=(e,t,n)=>t==="all"||!n?!0:t==="mine"?bc(e.author?.login,n):t==="review"?ni(e.requestedReviewers).includes(n.toLowerCase()):ni(e.assignees).includes(n.toLowerCase()),xg=(e,t,n)=>t==="all"||!n||t==="mentioned"?!0:t==="mine"?bc(e.author?.login,n):ni(e.assignees).includes(n.toLowerCase()),Zs=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},vc=(e,t)=>{const n=[...e];return t==="newest"?(n.sort((r,o)=>Zs(o.createdAt)-Zs(r.createdAt)||o.number-r.number),n):t==="oldest"?(n.sort((r,o)=>Zs(r.createdAt)-Zs(o.createdAt)||r.number-o.number),n):(n.sort((r,o)=>Zs(o.updatedAt)-Zs(r.updatedAt)||o.number-r.number),n)},Vw=(e,t)=>{const{tokens:n,labelTokens:r}=xc(t.search),o=[];for(const i of mg(e,t.state))bg(i,t.involvement,t.viewerLogin)&&yc(i.labels,"",r)&&wc(hg(i),n)&&o.push(i);return vc(o,t.sort)},Qw=(e,t)=>{const{tokens:n,labelTokens:r}=xc(t.search),o=[];for(const i of gg(e,t.state))xg(i,t.involvement,t.viewerLogin)&&yc(i.labels,t.labels,r)&&wc(pg(i),n)&&o.push(i);return vc(o,t.sort)},hr=(e,t)=>{if(t.length===0)return e;const n=new Map;for(const i of t)n.set(i.number,i);const r=e.map(i=>n.get(i.number)??i),o=new Set(e.map(i=>i.number));for(const i of t)o.has(i.number)||r.push(i);return r},Jw=(e,t)=>e.filter(n=>!t.has(n.number)),yg=(e,t)=>{if(t.length===0)return e;const n=new Set(e.map(o=>o.id)),r=[...e];for(const o of t)n.has(o.id)||(n.add(o.id),r.push(o));return r},Sa=Object.freeze({repo:null,number:null}),uo=e=>e.split(`
|
|
17
|
+
`)[1]??"",ri=(e,t)=>`${ms(e)}
|
|
18
|
+
${t}`,Tn=(e,t)=>`${e}#${t}`,wg=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},Fs=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},ja=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,ka=10,vg=(e,t)=>{const n=an(),r=an({maxEntries:60}),o=an(),i=an(),a=new Map,c=new Map,d=async(B,R)=>{const T=c.get(B);if(T)return await T.catch(()=>null),{ran:!1,result:null};const E=R();c.set(B,E);try{return{ran:!0,result:await E}}finally{c.get(B)===E&&c.delete(B)}},u=(B,R)=>{if(R.length===0)return;const T=e.collectionKeyFor(B,e.openCollection);let E=a.get(T);E||(E=new Map,a.set(T,E));for(const F of R)E.set(F.number,F)},f=B=>{const R=Object.keys(r.snapshot()).filter(E=>uo(E)===B&&!r.getEntry(E)?.isLoading);if(R.length<=ka)return;const T=R.map(E=>({key:E,fetchedAt:r.getEntry(E)?.data?.fetchedAt??0})).sort((E,F)=>E.fetchedAt-F.fetchedAt);for(let E=0;E<T.length-ka;E+=1)r.remove(T[E].key)},m=B=>{const R=n.getEntry(e.collectionKeyFor(B,e.openCollection))?.data?.items??[],T=n.getEntry(e.collectionKeyFor(B,e.closedCollection))?.data?.items??[],E=hr(R,T),F=a.get(e.collectionKeyFor(B,e.openCollection));return!F||F.size===0?E:hr(E,[...F.values()])},x=(B,R,T)=>{const E=ri(B,R),F=t.get().filtersByScope[E]??e.defaultFilters;t.set(q=>({filtersByScope:{...q.filtersByScope,[E]:{...F,...T}}}))},y=(B,R)=>{const T=ri(B,R);t.set(E=>({filtersByScope:{...E.filtersByScope,[T]:{...e.defaultFilters}}}))},p=(B,R,T)=>{const E=ms(B);E&&t.set(F=>({selectionByDirectory:{...F.selectionByDirectory,[E]:{repo:R,number:T}}}))},h=(B,R,T,E)=>{const F=e.collectionKeyFor(R,T);return n.ensure(F,async()=>{const q=await e.fetchList(E,B,R,e.buildCollectionQuery(T));return{items:q.items,nextCursor:q.nextCursor,fetchedAt:q.fetchedAt}})},S=(B,R,T)=>{const E=e.collectionKeyFor(R,e.closedCollection);n.getEntry(E)?.data||n.getEntry(E)?.isLoading||h(B,R,e.closedCollection,T).catch(()=>null)},g=async(B,R,T,E)=>{const F=T==="open"||T==="both",q=T==="closed"||T==="both",G=[],L=n.getEntry(e.collectionKeyFor(R,e.openCollection)),le=n.getEntry(e.collectionKeyFor(R,e.closedCollection));F&&(!ja(L,e.freshWindowMs)||L?.stale)&&G.push(h(B,R,e.openCollection,E)),q&&(!ja(le,e.freshWindowMs)||le?.stale)&&G.push(h(B,R,e.closedCollection,E)),await Promise.all(G.map(H=>H.catch(()=>null))),F&&!n.getEntry(e.collectionKeyFor(R,e.closedCollection))?.data&&S(B,R,E)},k=async(B,R,T,E)=>{const F=e.collectionKeyFor(R,T),q=n.getEntry(F),G=q?.data?.nextCursor??null;if(!G||q?.isLoading)return q;try{const L=await d(`${F}:more`,async()=>{const le=await e.fetchList(E,B,R,{...e.buildCollectionQuery(T),cursor:G}),H=n.getEntry(F)?.data,Ae={items:hr(H?.items??[],le.items),nextCursor:le.nextCursor,fetchedAt:le.fetchedAt};return n.refresh(F,async()=>Ae)});return L.ran?L.result??n.getEntry(F):n.getEntry(F)}catch(L){return n.setError(F,L)??n.getEntry(F)}},b=async(B,R,T,E)=>{const F=T==="both"?[e.openCollection,e.closedCollection]:[T];await Promise.all(F.map(q=>{const G=e.collectionKeyFor(R,q);return n.refresh(G,async()=>{const L=await e.fetchList(E,B,R,e.buildCollectionQuery(q));return{items:L.items,nextCursor:L.nextCursor,fetchedAt:L.fetchedAt}}).catch(()=>null)}))},A=async(B,R,T,E)=>{const F=e.remoteKeyFor(R,T),q=await r.refresh(F,async()=>{const G=await e.fetchList(E,B,R,e.buildRemoteQuery(T));return{items:G.items,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}});return q.data&&(u(R,q.data.items),f(R)),q},j=async(B,R,T,E)=>{const F=e.remoteKeyFor(R,T),q=r.getEntry(F),G=q?.data?.nextCursor??null;if(!G||q?.isLoading)return q;try{const L=await e.fetchList(E,B,R,e.buildRemoteQuery(T,G)),le=r.getEntry(F)?.data,H={items:hr(le?.items??[],L.items),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt},Ae=await r.refresh(F,async()=>H);return Ae.data&&(u(R,Ae.data.items),f(R)),Ae}catch(L){return r.setError(F,L)??r.getEntry(F)}},C=B=>{for(const R of Object.keys(r.snapshot()))uo(R)===B&&r.remove(R);for(const R of[...a.keys()])uo(R)===B&&a.delete(R)},w=(B,R,T,E)=>{const F=e.detailKeyFor(R,T);return o.refresh(F,async()=>({detail:await e.fetchDetail(E,B,R,T)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:n,remote:r,details:o,comments:i},setFilters:x,resetFilters:y,select:p,ensureCollection:h,ensureCollectionsFresh:g,prefetchClosedCollection:S,loadMoreCollection:k,refreshCollections:b,searchRemote:A,loadMoreRemote:j,dropRemoteForRepo:C,refreshAllForScope:async(B,R,T)=>{await Fs(T,{directory:B,repo:R,kind:e.serverKind}),C(R),await b(B,R,"both",T).catch(()=>null);const E=t.get().selectionByDirectory[ms(B)];E?.repo===R&&typeof E.number=="number"&&await w(B,R,E.number,T).catch(()=>null)},ensureDetail:(B,R,T,E)=>{const F=e.detailKeyFor(R,T);return o.ensure(F,async()=>({detail:await e.fetchDetail(E,B,R,T)}))},refreshDetail:w,ensureComments:(B,R,T,E)=>{const F=e.commentsKeyFor(R,T);return i.ensure(F,async()=>{const q=await e.fetchComments(E,B,R,T);return{comments:q.comments,nextCursor:q.nextCursor,fetchedAt:q.fetchedAt}})},loadMoreComments:async(B,R,T,E)=>{const F=e.commentsKeyFor(R,T),q=i.getEntry(F),G=q?.data?.nextCursor??null;if(!G||q?.isLoading)return q;try{const L=await e.fetchComments(E,B,R,T,G),le=i.getEntry(F)?.data,H={comments:yg(le?.comments??[],L.comments),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt};return await i.refresh(F,async()=>H)}catch(L){return i.setError(F,L)??i.getEntry(F)}},refreshComments:(B,R,T,E)=>{const F=e.commentsKeyFor(R,T);return i.refresh(F,async()=>{const q=await e.fetchComments(E,B,R,T);return{comments:q.comments,nextCursor:q.nextCursor,fetchedAt:q.fetchedAt}})},markCollectionsStale:B=>{n.markStale(e.collectionKeyFor(B,e.openCollection)),n.markStale(e.collectionKeyFor(B,e.closedCollection))},getLocalIndex:m,withSingleFlight:d,resetCore:()=>{n.reset(),r.reset(),a.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:B=>wg(B,e.errorFallback)}},oi={state:"open",involvement:"all",search:"",sort:"updated"},Sg=3e4,jg=100,kg=50,Sc=(e,t)=>Sn([e,"pulls-collection",t]),jc=(e,t)=>Sn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),Mr=(e,t)=>Sn([e,"pull-detail",t]),ki=(e,t)=>Sn([e,"pull-comments",t]),ii=(e,t)=>Sn([e,"pull-files",t]),ai=(e,t)=>Sn([e,"pull-checks",t]),Cg=e=>({state:e,perPage:jg}),Ag=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:kg,...t?{cursor:t}:{}}),Fr=e=>`pichamber:pr-merge-method:${e}`,kc=new Map,Ng=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},Ig=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},Xw=e=>{if(!e)return null;const t=Ng(Fr(e));return t==="merge"||t==="squash"||t==="rebase"?t:kc.get(Fr(e))??null},Eg=(e,t)=>{if(e){kc.set(Fr(e),t);try{Ig(Fr(e),t)}catch{}}},Dg={set:e=>{typeof e=="function"?ks.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):ks.setState(e)},get:()=>{const e=ks.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Te=vg({openCollection:"open",closedCollection:"closed",defaultFilters:oi,freshWindowMs:Sg,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Sc,remoteKeyFor:jc,detailKeyFor:Mr,commentsKeyFor:ki,buildCollectionQuery:e=>({...Cg(e)}),buildRemoteQuery:(e,t)=>({...Ag(e,t)}),fetchList:async(e,t,n,r)=>{const o=await e.pullsList(t,n,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,n,r)=>e.pullGet(t,n,r),fetchComments:async(e,t,n,r,o)=>{const i=await e.pullComments(t,n,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},Dg),rs=an(),jr=an(),ks=Is()($r((e,t)=>({...Te.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Te.setFilters,resetFilters:Te.resetFilters,selectPullRequest:Te.select,ensureCollection:Te.ensureCollection,ensureCollectionsFresh:Te.ensureCollectionsFresh,prefetchClosedCollection:Te.prefetchClosedCollection,loadMoreCollection:Te.loadMoreCollection,refreshCollections:Te.refreshCollections,searchRemote:Te.searchRemote,loadMoreRemote:Te.loadMoreRemote,dropRemoteForRepo:Te.dropRemoteForRepo,refreshAllForScope:Te.refreshAllForScope,ensureDetail:Te.ensureDetail,refreshDetail:Te.refreshDetail,ensureComments:Te.ensureComments,loadMoreComments:Te.loadMoreComments,refreshComments:Te.refreshComments,ensureFiles:(n,r,o,i)=>{const a=ii(r,o);return rs.ensure(a,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const a=ii(r,o),c=rs.getEntry(a),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Te.withSingleFlight(`${a}:more`,async()=>{const f=await i.pullFiles(n,r,o,d),m=rs.getEntry(a)?.data,x=new Set((m?.files??[]).map(p=>p.filename)),y={repo:f.repo,number:f.number,files:[...m?.files??[],...f.files.filter(p=>!x.has(p.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return rs.refresh(a,async()=>y)});return u.ran?u.result??rs.getEntry(a):rs.getEntry(a)}catch(u){return rs.setError(a,u)??rs.getEntry(a)}},ensureChecks:(n,r,o,i)=>{const a=ai(r,o);return jr.ensure(a,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const a=ai(r,o);return jr.refresh(a,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,a)=>{const c=Tn(r,o),d=Mr(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(x=>({actingActions:{...x.actingActions,[c]:!0},actionErrorByDetail:{...x.actionErrorByDetail,[c]:null}}));const u=Te.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=f?{...f,state:i==="close"?"closed":i==="reopen"?"open":i==="merge"||i==="squash"||i==="rebase"?"merged":f.state,draft:i==="ready"?!1:i==="draft"?!0:f.draft}:null;m&&u&&await Te.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullAction(n,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Fs(a,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",a).catch(()=>null),await t().refreshDetail(n,r,o,a).catch(()=>null),await t().refreshChecks(n,r,o,a).catch(()=>null),e(x=>({actingActions:{...x.actingActions,[c]:!1}})),{ok:!0}}catch(x){const y=Te.toStoreError(x);return u&&await Te.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(p=>({actingActions:{...p.actingActions,[c]:!1},actionErrorByDetail:{...p.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},updateTitleBody:async(n,r,o,i,a)=>{const c=Tn(r,o),d=Mr(r,o),u=Te.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;m&&u&&await Te.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullUpdate(n,r,o,i),await Fs(a,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",a).catch(()=>null),await t().refreshDetail(n,r,o,a).catch(()=>null),{ok:!0}}catch(x){const y=Te.toStoreError(x);return u&&await Te.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},addComment:async(n,r,o,i,a)=>{const c=Tn(r,o),d=ki(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},m=Te.resources.comments.getEntry(d)?.data??null;if(m){const x={comments:[...m.comments,f],nextCursor:m.nextCursor,fetchedAt:m.fetchedAt};await Te.resources.comments.refresh(d,async()=>x).catch(()=>null)}try{return await a.pullComment(n,r,o,u),await Fs(a,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshComments(n,r,o,a).catch(()=>null),await t().refreshDetail(n,r,o,a).catch(()=>null),{ok:!0}}catch(x){const y=Te.toStoreError(x);return m?await Te.resources.comments.refresh(d,async()=>m).catch(()=>null):Te.resources.comments.remove(d),e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},submitReview:async(n,r,o,i,a)=>{const c=Tn(r,o);try{return await a.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await Fs(a,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,a).catch(()=>null),{ok:!0}}catch(d){const u=Te.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(n,r,o,i,a,c)=>{const d=Tn(r,o);try{return await c.pullThread(n,r,o,i,a),await Fs(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Te.toStoreError(u);return e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[d]:f}})),{ok:!1,error:f}}},checkout:async(n,r,o,i,a)=>{try{const c=await a.pullCheckout(n,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Te.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await Fs(r,{directory:n.directory,repo:n.repo,kind:"pulls"}),t().dropRemoteForRepo(n.repo),await t().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Te.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(a){return{ok:!1,error:Te.toStoreError(a)}}},setMergeMethod:(n,r)=>{Eg(n,r)},notifyAgentTurnComplete:n=>{const r=ms((n||"").trim());if(!r)return;const o=is.getState();for(const a of Object.keys(o.results)){const[,c]=a.split(`
|
|
19
|
+
`);if(c!==r)continue;const[,,d]=a.split(`
|
|
20
|
+
`);d&&xt(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-Cfrwo5uQ.js").then(f=>f.cU);return{getRegisteredRuntimeAPIs:u}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:u})=>{const f=u()?.github??null;if(f)return o.refresh(r,d,f,{force:!0})}).catch(()=>{})}const i=t().selectionByDirectory[r];i?.repo&&typeof i.number=="number"&&(Te.markCollectionsStale(i.repo),xt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-Cfrwo5uQ.js").then(c=>c.cU);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{const c=a()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Te.resetCore(),rs.reset(),jr.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(yn(()=>{ks.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Zw=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return xt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-CoFst31H.js").then(a=>a.eo);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const a=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!n){t=d,n=!0;return}for(const u of c){const f=`${u.type}:${u.session??""}:${u.time}`;t.has(f)||(t.add(f),u.type==="turn-complete"&&u.directory&&(ks.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};a(),o=i.subscribe(a)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},ev=e=>Te.getLocalIndex(e),tv=(e,t)=>Te.getLocalIndex(e).find(n=>n.number===t)??null,sv=(e,t)=>jn(Te.resources.collections,e?Sc(e,t):null),nv=(e,t)=>jn(Te.resources.remote,e?jc(e,t):null),rv=(e,t)=>jn(Te.resources.details,e!=null&&t!=null?Mr(e,t):null),ov=(e,t)=>jn(Te.resources.comments,e!=null&&t!=null?ki(e,t):null),iv=(e,t)=>jn(rs,e!=null&&t!=null?ii(e,t):null),av=(e,t)=>jn(jr,e!=null&&t!=null?ai(e,t):null),lv=(e,t)=>ks(n=>!e||!t?oi:n.filtersByScope[ri(e,t)]??oi),cv=e=>ks(t=>e?t.selectionByDirectory[ms(e)]??Sa:Sa),Cc=(e,t,n)=>{ks.getState().selectPullRequest(e,t,n);const r=ms(e);xt(async()=>{const{useUIStore:o}=await import("./index-Cfrwo5uQ.js").then(i=>i.cX);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),xt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-CoFst31H.js").then(i=>i.eq);return{useGitHubScopeStore:o}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useGitHubScopeStore:o})=>{o.getState().setSelectedRepo(e,t)}).catch(()=>{})},Rg=({directory:e,number:t,color:n})=>{const r=wl(e);return!e||!r?s.jsxs("span",{className:"ml-auto flex-shrink-0 typography-micro font-medium leading-none",style:n?{color:n}:void 0,children:["#",t]}):s.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Cc(e,r,t)},className:"ml-auto flex-shrink-0 rounded typography-micro font-medium leading-none hover:bg-interactive-hover",style:n?{color:n}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function Pg({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:a,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:m,statusLine:x,allGroupSessions:y,projectId:p,activeProjectId:h,setActiveProjectIdOnly:S,setActiveMainTab:g,mobileVariant:k,setSessionSwitcherOpen:b,openNewSessionDraft:A}){return s.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(t),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),r(t))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[s.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",a),...c?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground",children:e.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",i?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:Sr(e.label,o)}),f]}):!e.isMain||e.worktree?s.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Sr(e.label,o)}),f,u?s.jsx(Rg,{directory:e.directory??null,number:u.number,color:d}):null]}):s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsx("span",{className:"min-w-0 truncate",children:Sr(e.label,o)}),f]})}),m&&x?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?s.jsx(P,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):s.jsx(P,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 truncate typography-micro font-medium text-subtle-foreground",children:x.label})]}):null]})}),e.isArchivedBucket&&y.length>0?s.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),zs.requestDelete({sessions:y,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:s.jsx(P,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?s.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),p&&p!==h&&S(p),g("chat"),k&&b(!1),A({selectedProjectId:p,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:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const pr=(e,t)=>t?e.sessions.some(n=>hs(n,t)):!1,Tg=(e,t,n)=>e.sessions.some(r=>uc(r,r,t,n,e.directory,e.directory)),Mg=(e,t,n)=>{const r=o=>{const i=o.session.id;return t.get(i)!==n.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},Ca=(e,t,n)=>{const r=o=>t.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},Fg=(e,t,n)=>{const r=e.isArchivedBucket?"archived":"active",o=i=>{const a=`project:${r}:${i.session.id}`;return t.has(a)!==n.has(a)?!0:i.children.some(o)};return e.sessions.some(o)},Lg=(e,t)=>{if(e.group!==t.group||e.groupKey!==t.groupKey||e.projectId!==t.projectId||e.hideGroupLabel!==t.hideGroupLabel||e.compactBodyPadding!==t.compactBodyPadding||e.groupSearchDataByGroup!==t.groupSearchDataByGroup||e.visibleSessionCount!==t.visibleSessionCount||e.collapsedGroups!==t.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==t.collapsedGroups.has(t.groupKey)||e.pinnedSessionIds!==t.pinnedSessionIds&&Tg(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Fg(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Mg(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(pr(e.group,e.editingId)||pr(t.group,t.editingId))||e.editTitle!==t.editTitle&&(pr(e.group,e.editingId)||pr(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=Tr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=Tr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&Ca(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&Ca(t.group,e.unreadActivitySessionIds,t.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===t.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===t.normalizedSessionSearchQuery&&e.hideDirectoryControls===t.hideDirectoryControls&&e.collapsedFolderIds===t.collapsedFolderIds&&e.toggleFolderCollapse===t.toggleFolderCollapse&&e.renameFolder===t.renameFolder&&e.deleteFolder===t.deleteFolder&&e.showDeletionDialog===t.showDeletionDialog&&e.setDeleteFolderConfirm===t.setDeleteFolderConfirm&&e.renderSessionNode===t.renderSessionNode&&e.showMoreGroupSessions===t.showMoreGroupSessions&&e.resetGroupSessionLimit===t.resetGroupSessionLimit&&e.mobileVariant===t.mobileVariant&&e.alwaysShowActions===t.alwaysShowActions&&e.activeProjectId===t.activeProjectId&&e.setActiveProjectIdOnly===t.setActiveProjectIdOnly&&e.setActiveMainTab===t.setActiveMainTab&&e.setSessionSwitcherOpen===t.setSessionSwitcherOpen&&e.openNewSessionDraft===t.openNewSessionDraft&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.renamingFolderId===t.renamingFolderId&&e.renameFolderDraft===t.renameFolderDraft&&e.setRenameFolderDraft===t.setRenameFolderDraft&&e.setRenamingFolderId===t.setRenamingFolderId&&e.onToggleCollapsedGroup===t.onToggleCollapsedGroup&&e.dragHandleProps===t.dragHandleProps&&e.scrollContainerRef===t.scrollContainerRef};function Og({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:a,inputActivitySessionIds:c,collectGroupSessions:d}){const u=yt(C=>C.foldersMap),f=e.folderScopeKey??Ee(e.directory??null),m=l.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=l.useMemo(()=>m.flatMap(({scopeKey:C,directory:w})=>(u[C]??[]).map(v=>({folder:v,scopeKey:C,scopeDirectory:w}))),[m,u]),y=l.useMemo(()=>{const C=new Map,w=v=>{v.forEach(I=>{C.set(I.session.id,I),I.children.length>0&&w(I.children)})};return w(t),C},[t]),p=l.useMemo(()=>x.map(({folder:C,scopeKey:w,scopeDirectory:v})=>{const I=sg(C.sessionIds,y).sort(o);return{folder:C,scopeKey:w,scopeDirectory:v,nodes:I}}),[x,y,o]),h=l.useMemo(()=>{const C=new Map(p.map(D=>[D.folder.id,D])),w=new Map;for(const{folder:D}of p){if(!D.parentId)continue;const z=w.get(D.parentId);z?z.push(D.id):w.set(D.parentId,[D.id])}const v=new Map,I=D=>{const z=v.get(D);if(z!==void 0)return z;const W=C.get(D);if(!W)return v.set(D,!1),!1;const $=w.get(D)??[];if(e.isArchivedBucket&&W.nodes.length===0){const R=$.some(T=>I(T));return v.set(D,R),R}if(!n||W.folder.name.toLowerCase().includes(r)||W.nodes.length>0)return v.set(D,!0),!0;const B=$.some(R=>I(R));return v.set(D,B),B};return p.filter(({folder:D})=>I(D.id))},[p,e.isArchivedBucket,n,r]),S=l.useMemo(()=>new Set(h.flatMap(C=>C.folder.sessionIds)),[h]),g=l.useMemo(()=>t.filter(C=>!S.has(C.session.id)),[t,S]),k=l.useMemo(()=>h.filter(({folder:C})=>!C.parentId),[h]),b=l.useMemo(()=>{const C=new Map;return h.forEach(w=>{if(!w.folder.parentId)return;const v=C.get(w.folder.parentId)??[];v.push(w),C.set(w.folder.parentId,v)}),C},[h]),A=l.useMemo(()=>{const C=new Map(h.map(I=>[I.folder.id,I])),w=new Map,v=(I,D)=>{const z=w.get(I);if(z!==void 0)return z;if(D.has(I))return null;D.add(I);const W=C.get(I);let $=W?gc(W.nodes,i,a,c):null;for(const K of b.get(I)??[])if($=Si($,v(K.folder.id,D)),$==="input")break;return w.set(I,$),$};return h.forEach(({folder:I})=>v(I.id,new Set)),w},[i,h,b,c,a]),j=l.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const C=new Map,w=new Map;for(const{folder:I}of h){if(!I.parentId)continue;const D=w.get(I.parentId)??[];D.push(I.id),w.set(I.parentId,D)}const v=(I,D)=>{if(D.has(I))return[];D.add(I);const z=h.find(({folder:K})=>K.id===I),W=z?d(z.nodes):[],$=w.get(I)??[];for(const K of $)W.push(...v(K,D));return W};for(const{folder:I}of h)C.set(I.id,v(I.id,new Set));return C},[h,d,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:m,allFoldersForGroup:h,rootFolders:k,ungroupedSessions:g,folderActivityStateById:A,folderSessionsForDeleteById:j}}function Bg(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:m,toggleFolderCollapse:x,renameFolder:y,deleteFolder:p,showDeletionDialog:h,setDeleteFolderConfirm:S,renderSessionNode:g,showMoreGroupSessions:k,resetGroupSessionLimit:b,mobileVariant:A,alwaysShowActions:j,activeProjectId:C,setActiveProjectIdOnly:w,setActiveMainTab:v,setSessionSwitcherOpen:I,openNewSessionDraft:D,addSessionToFolder:z,createFolderAndStartRename:W,renamingFolderId:$,renameFolderDraft:K,setRenameFolderDraft:B,setRenamingFolderId:R,pinnedSessionIds:T,expandedParents:E,sessionOrderIndex:F,editingId:q,openSidebarMenuKey:G,activeActivitySessionIds:L,unreadActivitySessionIds:le,onToggleCollapsedGroup:H,dragHandleProps:Ae,compactBodyPadding:Pe=!1,scrollContainerRef:J}=e,M=l.useCallback((Ce,Oe)=>{const Ie=F.get(Ce.session.id),Be=F.get(Oe.session.id);if(Ie!==void 0||Be!==void 0){if(Ie===void 0)return 1;if(Be===void 0)return-1;if(Ie!==Be)return Ie-Be}return Gu(Ce.session,Oe.session,T,vl)},[T,F]),Y=i?c.get(t):null,Q=i?!1:u.has(n),ne=!t.isMain&&!t.isArchivedBucket&&!o?Ee(t.directory??null):null,ae=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,me=l.useMemo(()=>ne&&ae?Zn(ne,ae):null,[ne,ae]),ge=hc(me);pc(ne,ae);const ke=ge?`var(--pr-${ge.visualState})`:void 0,ve=l.useContext(Wr)!==null,De=f?10:5,xe=Math.max(De,d??De),ze=i?Y?.groupMatches===!0:!1,X=i,oe=l.useMemo(()=>[...X?Y?.filteredNodes??[]:t.sessions].sort(M),[M,t.sessions,Y?.filteredNodes,X]),te=l.useCallback(Ce=>{const Oe=[],Ie=Be=>{Be.forEach(qe=>{Oe.push(qe.session),qe.children.length>0&&Ie(qe.children)})};return Ie(Ce),Oe},[]),fe=Hu(),he=l.useMemo(()=>new Set(fe.map(Ce=>Ce.sessionId)),[fe]),{folderScopeKey:_e,folderScopes:je,allFoldersForGroup:V,rootFolders:we,ungroupedSessions:ue,folderActivityStateById:Se,folderSessionsForDeleteById:Ye}=Og({group:t,sourceGroupNodes:oe,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,compareSessionNodes:M,activeActivitySessionIds:L,unreadActivitySessionIds:le,inputActivitySessionIds:he,collectGroupSessions:te}),Ue="project",U=l.useMemo(()=>{const Ce=new Set;return ma(oe,q,Ce),V.forEach(({nodes:Oe})=>{ma(Oe,q,Ce)}),Ce},[oe,V,q]),pe=l.useMemo(()=>{if(!G)return null;const Ce=Tr(oe,G,Ue,!!t.isArchivedBucket);if(Ce)return Ce;for(const{nodes:Oe}of V){const Ie=Tr(Oe,G,Ue,!!t.isArchivedBucket);if(Ie)return Ie}return null},[G,oe,V,t.isArchivedBucket]),se=l.useCallback(Ce=>{const Oe=new WeakMap,Ie=Be=>{Oe.set(Be,ei(Be));for(const qe of Be.children)Ie(qe)};return Ce.forEach(Ie),Oe},[]),Le=l.useMemo(()=>se(oe),[se,oe]),ht=l.useMemo(()=>{const Ce=new WeakMap;return V.forEach(({nodes:Oe})=>{Oe.forEach(Ie=>Ce.set(Ie,ei(Ie)))}),Ce},[V]),ct=l.useCallback(Ce=>Le.get(Ce)??ht.get(Ce)??"",[Le,ht]),Qe=l.useCallback(Ce=>({subtreeContainsEditing:U,menuOpenSessionId:pe,nodeStructureKey:ct(Ce)}),[U,pe,ct]),Dt=ue.length,Xe=t.isArchivedBucket||ve||i?ue:ue.slice(0,xe),Jt=Dt-Xe.length,wt=!t.isArchivedBucket&&!ve&&!i&&Dt>De&&Jt===0,tt=t.isArchivedBucket===!0&&!i&&Xe.length>=cg,Rt=t.isArchivedBucket?"archived":"active",Bt=tt&&Xe.some(Ce=>{if(Ce.children.length===0)return!1;const Oe=`project:${Rt}:${Ce.session.id}`;return E.has(Oe)}),Pt=l.useMemo(()=>te(oe),[te,oe]);if(i&&!ze&&we.length===0&&ue.length===0)return null;const Tt=!t.isMain&&!!t.branch,cs=t.branch&&vh(t.branch,t.label)?{label:t.branch,color:null}:null,ds=Q?gc(oe,L,le,he):null,rt=ds?s.jsx(cc,{state:ds,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,pt=(Ce,Oe)=>{const{folder:Ie,scopeKey:Be,scopeDirectory:qe,nodes:mt}=Ce,st=Ye.get(Ie.id)??[],Ze=i?!1:m.has(Ie.id);return s.jsx(Zm,{folderId:Ie.id,children:(xs,Zt)=>s.jsx(Jm,{folder:Ie,displayName:Oe,sessions:mt,isCollapsed:Ze,collapsedActivityState:Ze?Se.get(Ie.id)??null:null,onToggle:()=>x(Ie.id),onRename:Ve=>{y(Be,Ie.id,Ve)},onDelete:()=>{if(t.isArchivedBucket){zs.requestDelete({sessions:st,mode:"session"});return}if(!h){p(Be,Ie.id);return}const Ve=V.filter(({folder:zt})=>zt.parentId===Ie.id).length,vt=mt.length;S({scopeKey:Be,folderId:Ie.id,folderName:Ie.name,subFolderCount:Ve,sessionCount:vt})},renderSessionNode:g,getRenderExtras:ct?Ve=>({subtreeContainsEditing:U,menuOpenSessionId:pe,nodeStructureKey:ct(Ve),childRenderExtrasFor:Qe}):void 0,groupDirectory:qe??t.directory,projectId:r,mobileVariant:A,alwaysShowActions:j,isRenaming:$===Ie.id,renameDraft:$===Ie.id?K:void 0,onRenameDraftChange:Ve=>B(Ve),onRenameSave:()=>{const Ve=K.trim();Ve&&y(Be,Ie.id,Ve),R(null),B("")},onRenameCancel:()=>{R(null),B("")},droppableRef:xs,isDropTarget:Zt,depth:0,onNewSession:()=>{r&&r!==C&&w(r),v("chat"),A&&I(!1),D({selectedProjectId:r,directoryOverride:qe??t.directory,targetFolderId:Ie.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},Ie.id)},_t=()=>{const Ce=new Map;for(const Be of V){const qe=Be.folder.parentId;if(!qe)continue;const mt=Ce.get(qe);mt?mt.push(Be):Ce.set(qe,[Be])}const Oe=[],Ie=(Be,qe)=>{const mt=qe?`${qe} / ${Be.folder.name}`:Be.folder.name;Oe.push(pt(Be,mt)),!(!i&&m.has(Be.folder.id))&&(Ce.get(Be.folder.id)??[]).forEach(Ze=>Ie(Ze,mt))};return we.forEach(Be=>Ie(Be,"")),Oe},Xt=j?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",us=s.jsxs(eg,{scopeKey:je[0]?.scopeKey??_e,hasFolders:V.length>0,onSessionDroppedOnFolder:(Ce,Oe)=>{const Ie=V.find(({folder:qe})=>qe.id===Oe);if(!Ie)return;const Be=yt.getState();for(const{scopeKey:qe}of je)qe!==Ie.scopeKey&&Be.getSessionFolderId(qe,Ce)&&Be.removeSessionFromFolder(qe,Ce);z(Ie.scopeKey,Oe,Ce)},children:[_t(),t.isArchivedBucket?s.jsx(ug,{visibleSessions:Xe,shouldVirtualize:tt,hasExpandedParent:Bt,scrollContainerRef:J,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:Ce=>({subtreeContainsEditing:U,menuOpenSessionId:pe,nodeStructureKey:ct(Ce),childRenderExtrasFor:Qe})}):Xe.map(Ce=>s.jsx(l.Fragment,{children:g(Ce,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:U,menuOpenSessionId:pe,nodeStructureKey:ct(Ce),childRenderExtrasFor:Qe})},Ce.session.id)),Dt===0&&V.length===0&&!ve?t.isArchivedBucket?s.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):s.jsx(qt,{icon:"chat-new",onClick:()=>{D({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,Jt>0?s.jsx(qt,{icon:"arrow-down-s",onClick:()=>k(n,Xe.length),children:Jt===1?"Show 1 more session":`Show ${Jt} more sessions`}):null,wt?s.jsx(qt,{icon:"arrow-up-s",onClick:()=>b(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:us})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(Pg,{group:t,groupKey:n,isCollapsed:Q,onToggleCollapsedGroup:H,normalizedSessionSearchQuery:a,alwaysShowActions:j,groupHeaderRightPadding:Xt,dragHandleProps:Ae,groupPrColor:ke,groupPrSummary:ge,groupActivityIndicator:rt,showBranchSubtitle:Tt,statusLine:cs,allGroupSessions:Pt,projectId:r,activeProjectId:C,setActiveProjectIdOnly:w,setActiveMainTab:v,mobileVariant:A,setSessionSwitcherOpen:I,openNewSessionDraft:D}),Q?null:s.jsx("div",{className:"oc-group-body",children:us})]})}const _g=l.memo(Bg,Lg);function zg(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:a,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:m,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:p,hasSessionSearchQuery:h,searchMatchCount:S,selectionModeEnabled:g,onToggleSelectionMode:k,mobileVariant:b=!1,onClose:A}=e;if(t)return null;const j=_(u,"text-muted-foreground hover:text-foreground",!b&&"hover:bg-transparent"),C=o?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:j,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,w=c?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:j,"aria-label":"Update",children:s.jsx(P,{name:"download",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null;return s.jsx("div",{className:_("select-none flex-shrink-0",b?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",b?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",b?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[s.jsxs("div",{className:_("flex min-w-0 items-center",b?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":b?"true":void 0,children:[b?s.jsx("h2",{className:"truncate pl-2 typography-ui-header font-semibold text-foreground",children:"Sessions"}):s.jsxs(s.Fragment,{children:[C,w]}),!b&&i?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:j,"aria-label":a?`Servers: ${a}`:"Servers",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:a||"Servers"})})]}):null,b?null:s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:j,"aria-label":"Add folder",children:s.jsx(P,{name:"folder-add",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add folder"})})]}),b?null:s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:j,"aria-label":"Archive",children:s.jsx(P,{name:"archive",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",b?"gap-1":"gap-1.5"),children:[b?s.jsxs(s.Fragment,{children:[C,w]}):null,s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>m(v=>!v),className:j,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k,className:_(j,g&&"bg-interactive-hover text-primary"),"aria-label":g?"Exit selection":"Select sessions","aria-pressed":g,children:s.jsx(P,{name:"checkbox-multiple",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]}),b&&A?s.jsx("button",{type:"button",onClick:A,className:j,"aria-label":"Close sessions",children:s.jsx(P,{name:"close",className:d})}):null]})]}),f?s.jsxs("div",{className:_(b?"pb-2":"pb-1"),children:[s.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-subtle-foreground",children:h?s.jsx("span",{children:S===1?`${S} match`:`${S} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:x,value:y,onChange:v=>p(v.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:v=>{v.key==="Escape"&&(v.stopPropagation(),h?p(""):m(!1))}}),y.length>0?s.jsx("button",{type:"button",onClick:()=>p(""),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:s.jsx(P,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const fo="0.75rem";function Ug(e){const t=de(o=>o.toggleSidebar),n=de(o=>o.shortcutOverrides),r=yi(Ir("toggle_sidebar",n));return s.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${fo})`}}),s.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, ${fo})))`}}),s.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsxs("button",{type:"button",onClick:e.onNewSession,className:_("group flex min-w-0 flex-1 items-center gap-1.5 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"),style:{paddingLeft:`max(3px, calc(${Sh} - max(var(--oc-titlebar-left-inset, ${fo}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(yr,"text-current")}),s.jsx("span",{className:_l,children:"New session"})]}),e.showSidebarToggle?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,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:s.jsx(P,{name:"layout-left",className:"size-4"})})}),s.jsx(Ge,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function Hr({...e}){return s.jsx(al,{...e})}function qr({...e}){return s.jsx(ll,{...e})}function Yr({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Eo,{children:s.jsx(Do,{className:_("app-region-no-drag z-50",t),children:s.jsx(Ro,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Lo,e),...o,children:n})})})}function _s({className:e,...t}){return s.jsx(cl,{className:_(Sl,e),...t})}function Ac({className:e,...t}){return s.jsx(dl,{className:_(jl,e),...t})}const Nc=500,$g=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:a=!1})=>{const[c,d]=l.useState(!1),u=l.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),m=l.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);l.useEffect(()=>()=>m(),[m]);const x=l.useCallback(()=>{m(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},Nc)},[m]);return s.jsxs(Hr,{open:c,onOpenChange:d,children:[s.jsxs(qr,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:m,onTouchEnd:m,onTouchCancel:m,style:{touchAction:"manipulation"},className:_(Lr(a,n),"pl-6"),"aria-pressed":n,title:t.path}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx(P,{name:"git-branch",className:_($s(a),"text-muted-foreground")}),t.branch?s.jsx(zn,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):s.jsx("span",{className:gn(a),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Yr,{className:"min-w-[160px]",children:s.jsxs(_s,{disabled:!i,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>i?.(e,t),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},Lr=(e,t)=>_("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",t?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),Kg=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:a,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:m=!1})=>{const{listeners:x,setNodeRef:y,transform:p,transition:h,isDragging:S}=mi({id:e.id,disabled:!c}),[g,k]=l.useState(!1),b=l.useRef(null),A=l.useCallback(()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null)},[]);l.useEffect(()=>()=>A(),[A]);const j=l.useCallback(()=>{A(),b.current=window.setTimeout(()=>{b.current=null,k(!0)},Nc)},[A]);return s.jsx("div",{ref:y,style:{transform:gi.Translate.toString(p),transition:h},className:_(S&&"opacity-60"),children:s.jsxs(Hr,{open:g,onOpenChange:k,children:[s.jsxs(qr,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:j,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Lr(m,n),"aria-pressed":n}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.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 ${t}`:void 0,...c?x:{},children:s.jsx(xi,{directory:e.normalizedPath,label:t,className:$s(m)})}),s.jsx("span",{className:gn(m),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?s.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:s.jsx(P,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(P,{name:a?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(Yr,{className:"min-w-[160px]",children:[s.jsxs(_s,{onClick:()=>u(e.id),children:[s.jsx(P,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(Ac,{}),s.jsxs(_s,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},Wg=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:a,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:m,activeDirectoriesByProject:x,homeDirectory:y,className:p,mobileVariant:h=!1})=>{const S=t===null,g=ut(j=>j.reorderProjects),k=e.length>1,b=_r(fn(pl,{activationConstraint:{distance:8}}),fn(hl,{activationConstraint:{delay:200,tolerance:6}})),A=l.useCallback(j=>{const{active:C,over:w}=j;if(!w||C.id===w.id)return;const v=ut.getState().projects,I=v.findIndex(z=>z.id===C.id),D=v.findIndex(z=>z.id===w.id);I<0||D<0||g(I,D)},[g]);return s.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",p),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:Lr(h,S),"aria-pressed":S,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(P,{name:"chat-history",className:$s(h)}),s.jsx("span",{className:gn(h),children:"All sessions"})]})}),s.jsx(zr,{sensors:b,collisionDetection:pi,onDragEnd:A,children:s.jsx(ul,{items:e.map(j=>j.id),strategy:fl,children:e.map(j=>{const C=t===j.id,w=C&&!n,v=r.get(j.normalizedPath)??[],I=er(j,y),D=x?.get(j.id),z=Ee(j.normalizedPath)?.toLowerCase()??"",W=z?D?.has(z)??!1:!1,$=(D?.size??0)>0,K=m?.(j.id)??!1,B=x?C?W:$:K;return s.jsxs(l.Fragment,{children:[s.jsx(Kg,{project:j,label:I,isSelected:w,hasActive:B,hasWorktrees:v.length>0,worktreeError:o.get(j.normalizedPath),isExpanded:C,canDrag:k,onSelect:()=>i(j.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),C?v.map(R=>{const T=n===R.path,E=Ee(R.path)?.toLowerCase()??"",F=E?D?.has(E)??!1:!1,q=x?F:!1;return s.jsx($g,{projectId:j.id,worktree:R,isSelected:T,hasActive:q,onSelect:()=>a?.(j.id,R.path),onClose:c,mobileVariant:h},R.path)}):null]},j.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:Lr(h,!1),children:[s.jsx(P,{name:"add",className:$s(h)}),s.jsx("span",{className:gn(h),children:"Add folder"})]})]})},ho="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 Gg({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?s.jsxs(s.Fragment,{children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:ho,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:ho,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:ho,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ne,{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 Aa="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-[opacity,background-color,color] hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Na="opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto",Ic=({projectLabel:e,projectPath:t=null,mobileVariant:n=!1})=>{const r=$s(n),o=gn(n);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?s.jsx(xi,{directory:t,label:e,className:r}):s.jsx(P,{name:"folder",className:_(r,"text-subtle-foreground")})}),s.jsx("span",{className:_(o,"font-medium text-foreground"),children:e})]})},Ec=({isCollapsed:e,mobileVariant:t=!1,className:n})=>s.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",n),children:s.jsx(P,{name:e?"arrow-right-s":"arrow-down-s",className:$s(t)})}),Hg=({id:e,disabled:t=!1,projectLabel:n,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:a,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:m,onRenameStart:x,onClose:y,children:p,showCreateButtons:h=!0,hideHeader:S=!1,openSidebarMenuKey:g,setOpenSidebarMenuKey:k,statusIndicator:b=null,sessionCount:A=null,isEmpty:j=!1})=>{const{listeners:C,setNodeRef:w,transform:v,transition:I,isDragging:D}=mi({id:e,disabled:t}),z=l.useRef(!1),W=`project:${e}`,$=g===W,[K,B]=l.useState(!1),R=u&&!i,T=l.useCallback(H=>{H&&B(!1),k(H?W:null)},[W,k]),E=H=>s.jsxs(s.Fragment,{children:[h&&!a&&m&&s.jsxs(H,{onClick:m,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(H,{onClick:x,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(H,{onClick:y,className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),F=l.useCallback(H=>{H.stopPropagation()},[]),q=l.useCallback(H=>{H.stopPropagation()},[]),G=l.useCallback(H=>{H.stopPropagation()},[]),L=l.useCallback(H=>{(H.button===2||H.button===0&&H.ctrlKey)&&(z.current=!0)},[]),le=l.useCallback(H=>{if(H.currentTarget.blur(),z.current){z.current=!1;return}f()},[f]);return s.jsxs("div",{ref:w,style:{transform:gi.Translate.toString(v),transition:I},className:_("relative",D&&"opacity-60"),children:[S?null:s.jsxs(Hr,{open:K,onOpenChange:B,children:[s.jsxs(qr,{render:s.jsx("div",{className:_("text-left group/project select-none",R&&"oc-sidebar-sticky-header sticky top-0 z-20 bg-sidebar before:pointer-events-none before:absolute before:inset-x-0 before:bottom-full before:h-2 before:bg-sidebar"),"data-sidebar-sticky-header":R?"true":void 0,onContextMenu:H=>{a||D||(H.preventDefault(),B(!0))}}),children:[s.jsxs("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:L,onClick:le,...C,className:_(Gr,"flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing"),children:[s.jsx(Ic,{id:e,projectLabel:n,projectPath:r,mobileVariant:c}),A?s.jsx("span",{className:"shrink-0 typography-micro text-subtle-foreground tabular-nums","aria-label":A===1?"1 session":`${A} sessions`,children:A}):null,b?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:b}):null,s.jsx(Ec,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",j&&"invisible",d?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(Ge,{side:"right",sideOffset:8,children:o})]}),a?null:s.jsxs("div",{className:_("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5",j?"right-2":"right-7"),children:[h&&m?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:H=>{H.stopPropagation(),m()},className:_(Aa,d?"opacity-100":Na),"aria-label":"New session",children:s.jsx(P,{name:"add",className:"size-4"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]}):null,s.jsxs(Yt,{open:$,onOpenChange:T,children:[s.jsx(Vt,{asChild:!0,children:s.jsx("button",{type:"button",className:_(Aa,$?"opacity-100 pointer-events-auto bg-interactive-active text-foreground":d?"opacity-100":Na),"aria-label":"Folder menu",onPointerDown:q,onMouseDown:G,onClick:F,children:s.jsx(P,{name:"more-fill",className:"size-4"})})}),s.jsx(Qt,{align:"end",className:"min-w-[180px]",children:E(ft)})]})]})]}),R?s.jsx("span",{"aria-hidden":!0,className:"oc-sidebar-sticky-header-fade pointer-events-none absolute inset-x-0 top-full h-4 bg-gradient-to-b from-sidebar to-transparent"}):null]}),s.jsx(Yr,{className:"min-w-[180px]",children:E(_s)})]}),p]})},qg=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:d}=mi({id:e,disabled:t}),u=l.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:gi.Transform.toString(a),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};l.memo(qg);let Ia=0;const Ln=new Map;let kr=0;const po=(e,t,n)=>{const r={...e};return n?r[t]=n:delete r[t],r},Ea=e=>{Ln.clear(),kr+=1,Ks.setState({runtimeKey:e,entries:{},status:"idle"})},Ks=Is((e,t)=>({runtimeKey:null,entries:{},status:"idle",load:async()=>{const n=lt();t().runtimeKey!==n&&Ea(n);const r=++kr,o=Ia;t().status!=="ready"&&e({status:"loading"});try{const{sessions:i}=await Xi.getSessionShelf({runtimeKey:n});if(r!==kr||lt()!==n)return;const a=t().entries,c={...i};for(const[d,u]of Ln)u<=o||(a[d]?c[d]=a[d]:delete c[d]);e({entries:c,status:"ready"})}catch(i){if(r!==kr||lt()!==n)return;e({status:"failed"}),console.warn("[session-shelf] could not read the session shelf",i)}},update:async(n,r,o)=>{const i=lt();t().runtimeKey!==i&&Ea(i);const a=t().entries[n],c=++Ia;Ln.set(n,c),e({entries:po(t().entries,n,$f(a,r,Date.now()))});try{const d=await Xi.setSessionShelf({sessionId:n,...r},{runtimeKey:i,...o?{directory:o}:{}});if(lt()!==i||Ln.get(n)!==c)return;e({entries:po(t().entries,n,d)})}catch(d){throw lt()===i&&Ln.get(n)===c&&e({entries:po(t().entries,n,a)}),d}}})),Yg=e=>e.session.time?.updated||e.session.time?.created||0,Vg=(e,t)=>{const n={pinned:[],active:[],working:[],snoozed:[],settled:[]},r=new Map,o=new Set;for(const a of e){const c=a.node.session.id,d=t.entries[c],u={entry:d,pinned:a.isPinned,working:t.working.has(c),needsInput:t.needsInput.has(c),updatedAt:Yg(a.node),now:t.now,autoSettleAfterDays:t.autoSettleAfterDays,workingShelf:t.workingShelf},f=Kf(u);r.set(c,f),f!=="snoozed"&&Wf(d,t.now)&&o.add(c);const m=f==="snoozed"?-(d?.snoozedUntil??0):f==="settled"?Gf(u):Hf(u);n[f].push({item:a,key:m})}const i=a=>n[a].sort((c,d)=>d.key-c.key).map(({item:c})=>c);return{pinned:i("pinned"),active:i("active"),working:i("working"),snoozed:i("snoozed"),settled:i("settled"),sectionById:r,wokeIds:o}},Qg=(e,t)=>{const n=(r,o)=>r.length===o.length&&r.every((i,a)=>i===o[a]);if(e.wokeIds.size!==t.wokeIds.size)return!1;for(const r of e.wokeIds)if(!t.wokeIds.has(r))return!1;return n(e.pinned,t.pinned)&&n(e.active,t.active)&&n(e.working,t.working)&&n(e.snoozed,t.snoozed)&&n(e.settled,t.settled)},Jg=6e4,Xg=1500,Zg=(e,t)=>{const[n,r]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!e||typeof document>"u")return;let o=null;const i=()=>{r(Date.now()),o===null&&(o=window.setInterval(()=>r(Date.now()),Jg))},a=()=>{o!==null&&window.clearInterval(o),o=null},c=()=>document.visibilityState==="visible"?i():a();return c(),document.addEventListener("visibilitychange",c),()=>{a(),document.removeEventListener("visibilitychange",c)}},[e]),l.useEffect(()=>{if(!e||t===null)return;const o=Math.min(Math.max(0,t-Date.now())+50,2**31-1),i=window.setTimeout(()=>r(Date.now()),o);return()=>window.clearTimeout(i)},[e,t]),n},eb=(e,t)=>{const n=Ks(o=>o.load);l.useEffect(()=>{if(!e)return;n();const o=()=>{document.visibilityState==="visible"&&n()};document.addEventListener("visibilitychange",o);const i=yn(()=>{n()});return()=>{document.removeEventListener("visibilitychange",o),i()}},[e,n]);const r=l.useRef(t);l.useEffect(()=>{const o=r.current;if(r.current=t,!e)return;let i=!1;for(const c of t)if(!o.has(c)){i=!0;break}if(!i)return;const a=window.setTimeout(()=>{n()},Xg);return()=>window.clearTimeout(a)},[e,t,n])},tb=(e,{enabled:t,workingShelf:n,autoSettleAfterDays:r})=>{const o=Ks(y=>t?y.entries:sb),{working:i,needsInput:a}=qu(t),c=l.useMemo(()=>qf(o,Date.now()),[o]),d=Zg(t,c);eb(t,i);const u=l.useRef(null),f=l.useMemo(()=>{if(!t)return null;const y=Vg(e,{entries:o,working:i,needsInput:a,now:d,autoSettleAfterDays:r,workingShelf:n});return u.current&&Qg(u.current,y)&&u.current.sectionById.size===y.sectionById.size&&[...y.sectionById].every(([h,S])=>u.current.sectionById.get(h)===S)?u.current:y},[t,e,o,i,a,d,r,n]);u.current=f;const m=Me(y=>y.currentSessionId),x=!!(t&&m&&f?.wokeIds.has(m));return l.useEffect(()=>{!x||!m||Ks.getState().update(m,{snoozedUntil:null}).catch(y=>console.warn("[session-shelf] could not clear a finished snooze",y))},[x,m]),f},sb=Object.freeze({}),un=(e,t,n,r)=>{Ks.getState().update(e,t,n??void 0).catch(o=>{console.warn("[session-shelf] update failed",o),ie.error(r)})},Dc=(e,t,n)=>{const r=Vn.getState(),o=!!t&&Qn(r.ids,t??null,e);o&&t&&r.toggle({directory:t,sessionId:e});const i=()=>{if(!o||!t)return;const a=Vn.getState();Qn(a.ids,t,e)||a.toggle({directory:t,sessionId:e})};Ks.getState().update(e,{settled:"settled"},t??void 0).then(()=>{ie.success(`Settled “${n}”`,{action:{label:"Undo",onClick:()=>{i(),un(e,{settled:"active"},t,"Could not un-settle the session")}}})}).catch(a=>{console.warn("[session-shelf] update failed",a),i(),ie.error("Could not settle the session")})},Da={snoozed:"Snoozed",settled:"Settled"},Ra=10,Pa=25,Rc="oc.sidebar.shelves.expanded",nb=()=>{try{const e=on().getItem(Rc),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(n=>n==="snoozed"||n==="settled")):new Set}catch{return new Set}},rb=()=>{const[e,t]=l.useState(nb),n=l.useCallback(r=>{t(o=>{const i=new Set(o);i.has(r)?i.delete(r):i.add(r);try{on().setItem(Rc,JSON.stringify([...i]))}catch{}return i})},[]);return{expanded:e,toggle:n}},li=({target:e,dragging:t,className:n,children:r})=>{const{setNodeRef:o,isOver:i}=il({id:`shelf-drop:${e}`,data:{type:"shelf",target:e}});return s.jsx("div",{ref:o,"data-shelf-drop":e,className:_("rounded-xl transition-colors",t&&"outline outline-1 -outline-offset-1 outline-transparent",t&&i&&"bg-interactive-hover outline-[var(--interactive-border)]",n),children:r})},ob=["snoozed","settled"],Pc=({shelfIds:e,shelves:t,renderItem:n,hasSessionSearchQuery:r,mobileVariant:o,dragging:i=!1,droppable:a=!1,className:c})=>{const{expanded:d,toggle:u}=rb(),f=Me(g=>g.currentSessionId),[m,x]=l.useState(Ra),y=g=>r||d.has(g),p=(g,k)=>{if(y(g)){if(g!=="settled"||r)return k;const b=k.slice(0,m),A=k.find(j=>j.node.session.id===f);return A&&!b.includes(A)?[...b,A]:b}return[]},h=t.settled.length-Math.min(m,t.settled.length),S=e.filter(g=>t[g].length>0||g==="settled"&&i);return S.length===0?null:s.jsx("div",{className:c,children:S.map(g=>{const k=t[g],b=y(g),A=s.jsxs(s.Fragment,{children:[s.jsx(cn,{label:Da[g],count:k.length,expanded:b,onToggle:()=>{g==="settled"&&x(Ra),u(g)}}),p(g,k).map(n),g==="settled"&&b&&!r&&h>0?s.jsx(qt,{icon:"arrow-down-s",mobileVariant:o,onClick:()=>x(j=>j+Pa),children:`Show ${Math.min(Pa,h)} more`}):null]});return s.jsx("section",{"aria-label":Da[g],"data-session-shelf":g,children:g==="settled"&&a?s.jsx(li,{target:"settled",dragging:i,children:A}):A},g)})})},ib=({items:e,shelves:t,renderSessionNode:n,hasSessionSearchQuery:r,mobileVariant:o,emptyState:i,searchEmptyState:a})=>{const[c,d]=l.useState(null),u=_r(fn(rl,{activationConstraint:{distance:8}})),f=l.useMemo(()=>({sectionById:t.sectionById,wokeIds:t.wokeIds}),[t.sectionById,t.wokeIds]),m=b=>s.jsx(l.Fragment,{children:n(b.node,0,b.node.session.directory??b.project.normalizedPath,b.project.id,!1,{projectLabel:b.projectLabel,showFolderLabel:!0,globalSession:b.globalSession},"project")},b.node.session.id),x=b=>{const A=b.active.data.current;if(A?.type!=="session"||!A.sessionId)return;const j=b.active.rect.current.initial?.width;d({sessionId:A.sessionId,title:A.sessionTitle??"Session",width:typeof j=="number"?j:null})},y=b=>{d(null);const A=b.active.data.current,j=b.over?.data.current;if(A?.type!=="session"||!A.sessionId||j?.type!=="shelf"||!j.target)return;const C=A.sessionId,w=A.sessionDirectory??null,v=t.sectionById.get(C);v&&ab(C,w,v,j.target,c?.title??"Session")};if(e.length===0)return s.jsx(s.Fragment,{children:r?a:i});const p=!!c,h=t.pinned.length>0||p,S=t.working.length>0,g=h||S||t.snoozed.length>0||t.settled.length>0,k=s.jsxs("div",{className:"flex min-h-full flex-1 flex-col","data-sidebar-threads":"",children:[h?s.jsxs(li,{target:"pinned",dragging:p,children:[s.jsx(cn,{label:"Pinned",first:!0}),t.pinned.map(m),p&&t.pinned.length===0?s.jsx("div",{className:"px-3 py-2 typography-micro text-subtle-foreground",children:"Drop here to pin"}):null]}):null,S?s.jsxs("section",{"aria-label":"Working","data-session-shelf":"working",children:[s.jsx(cn,{label:"Working",first:!h}),t.working.map(m)]}):null,s.jsxs(li,{target:"active",dragging:p,children:[g?s.jsx(cn,{label:"Recent",first:!h&&!S}):null,t.active.map(m),t.active.length===0&&!r?s.jsx("div",{className:"px-3 py-1.5 typography-micro text-subtle-foreground",children:p?"Drop here to keep it in the list":"Nothing recent. Settled sessions are below."}):null]}),s.jsx(Pc,{shelfIds:ob,shelves:t,renderItem:m,hasSessionSearchQuery:r,mobileVariant:o,dragging:p,droppable:!o,className:"mt-auto border-t border-border pt-1"})]});return s.jsx(Wr.Provider,{value:f,children:o?k:s.jsxs(zr,{sensors:u,collisionDetection:pu,onDragStart:x,onDragCancel:()=>d(null),onDragEnd:y,children:[k,s.jsx(ol,{children:c?s.jsx("div",{style:{width:c.width?`${c.width}px`:"auto"},className:"pointer-events-none flex items-center rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2",children:s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:c.title})}):null})]})})},ab=(e,t,n,r,o)=>{const i=Vn.getState(),a=Qn(i.ids,t,e),c=d=>{!t||a===d||i.toggle({directory:t,sessionId:e})};if(r==="settled"){if(n==="settled")return;Dc(e,t,o);return}n==="snoozed"&&un(e,{snoozedUntil:null},t,"Could not wake the session"),n==="settled"&&un(e,{settled:"active"},t,"Could not un-settle the session"),c(r==="pinned")},lb=l.memo(ib),cb=["snoozed","settled"],Ta=(e,t)=>{let n=!1;const r=e.groups.map(o=>{if(o.isArchivedBucket)return o;const i=o.sessions.filter(a=>!t.has(a.session.id));return i.length===o.sessions.length?o:(n=!0,{...o,sessions:i})});return n?{...e,groups:r}:e},Ma=e=>e.groups.reduce((t,n)=>n.isArchivedBucket?t:t+n.sessions.length,0),Fa="pt-0.5 pb-1",db=({shelves:e=null,sections:t,homeSection:n,homeDirectory:r,collapsedProjects:o,toggleProject:i,hasSessionSearchQuery:a,activeProjectId:c,hideDirectoryControls:d,mobileVariant:u,alwaysShowActions:f,isInlineEditing:m,stickyFolderHeaders:x,renderGroupSessions:y,renderSessionNode:p,getOrderedGroups:h,renderProjectStatusIndicator:S,scrollContainerRef:g,setActiveProjectIdOnly:k,setActiveMainTab:b,setSessionSwitcherOpen:A,openNewSessionDraft:j,openProjectEditDialog:C,removeProject:w,reorderProjects:v,openSidebarMenuKey:I,setOpenSidebarMenuKey:D,onOpenDirectoryDialog:z,emptyState:W,searchEmptyState:$})=>{const K=l.useMemo(()=>{if(!e)return null;const M=new Set;for(const Y of[...e.pinned,...e.snoozed,...e.settled])M.add(Y.node.session.id);return M},[e]),B=l.useMemo(()=>K?t.map(M=>Ta(M,K)):t,[t,K]),R=l.useMemo(()=>K&&n?Ta(n,K):n,[n,K]),T=l.useMemo(()=>e?{sectionById:e.sectionById,wokeIds:e.wokeIds}:null,[e]),E=M=>s.jsx(l.Fragment,{children:p?.(M.node,0,M.node.session.directory??M.project.normalizedPath,M.project.id,!1,{projectLabel:M.projectLabel,showFolderLabel:!0,globalSession:M.globalSession},"project")},M.node.session.id),F=_r(fn(pl,{activationConstraint:{distance:8}}),fn(hl,{activationConstraint:{delay:200,tolerance:6}})),q=B.length>1&&!a&&!m,G=l.useCallback(M=>{if(m||a)return;const{active:Y,over:Q}=M;if(!Q||Y.id===Q.id)return;const ne=ut.getState().projects,ae=ne.findIndex(ge=>ge.id===Y.id),me=ne.findIndex(ge=>ge.id===Q.id);ae<0||me<0||ae===me||v(ae,me)},[m,a,v]),[L,le]=l.useState(5);l.useEffect(()=>{le(5)},[a]);const H=l.useMemo(()=>R?R.groups.filter(M=>!M.isArchivedBucket).flatMap(M=>M.sessions):[],[R]),Ae=a||e?H:H.slice(0,L),Pe=H.length-Ae.length,J=a?!1:o.has("__home__");return B.length===0&&!R?a?$:W:s.jsx(Wr.Provider,{value:T,children:s.jsxs("div",{className:e?"flex min-h-full flex-1 flex-col gap-1":"space-y-1",children:[e&&e.pinned.length>0?s.jsx(Xn.Provider,{value:"card",children:s.jsxs("section",{"aria-label":"Pinned","data-session-shelf":"pinned",children:[s.jsx(cn,{label:"Pinned",first:!0}),e.pinned.map(E)]})}):null,s.jsx(zr,{sensors:F,collisionDetection:pi,onDragEnd:G,children:s.jsx(ul,{items:B.map(M=>M.project.id),strategy:fl,children:B.map(M=>{const Y=M.project,Q=Y.id,ne=er(Y,r),ae=_o(Y.normalizedPath,r),me=a?!1:o.has(Q),ge=me?[]:h(Q,M.groups),ke=me?null:ge.find(De=>De.isMain)??null,ve=me?[]:ke?ge.filter(De=>De.id!==ke.id):ge;return s.jsx(Hg,{id:Q,disabled:!q,projectLabel:ne,projectPath:Y.normalizedPath,projectDescription:ae,isCollapsed:me,hideDirectoryControls:d,mobileVariant:u,alwaysShowActions:f,stickyHeader:x,statusIndicator:me?S?.(Q,M.groups):null,sessionCount:me?Ma(M):null,isEmpty:!!e&&Ma(M)===0,onToggle:()=>i(Q),onNewSession:()=>{Q!==c&&k(Q),b("chat"),u&&A(!1),j({selectedProjectId:Q,directoryOverride:Y.normalizedPath})},onRenameStart:()=>C(Q),onClose:()=>w(Q),openSidebarMenuKey:I,setOpenSidebarMenuKey:D,children:me?null:s.jsxs("div",{className:Fa,children:[ke?y(ke,`${Q}:${ke.id}`,Q,!0,null,void 0,g):null,ve.map(De=>{const xe=`${Q}:${De.id}`,ze=ge.length===1;return s.jsx(l.Fragment,{children:y(De,xe,Q,ze,null,void 0,g)},De.id)})]})},Q)})})}),R?s.jsxs("div",{children:[s.jsx("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:s.jsxs("button",{type:"button","aria-expanded":!J,style:{touchAction:"manipulation"},onClick:()=>i("__home__"),className:`${Gr} flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md`,children:[s.jsx(Ic,{id:"__home__",projectLabel:"No folder",mobileVariant:u}),s.jsx(Ec,{isCollapsed:J,mobileVariant:u})]})}),J?null:s.jsxs("div",{className:Fa,children:[Ae.map(M=>s.jsx(l.Fragment,{children:p?.(M,0,M.session.directory??"~","__home__",!1,{globalSession:!0},"project")},M.session.id)),!a&&Pe>0?s.jsx(qt,{icon:"arrow-down-s",mobileVariant:u,onClick:()=>le(M=>M+7),children:Pe===1?"Show 1 more session":`Show ${Pe} more sessions`}):null,!a&&L>5&&H.length>5?s.jsx(qt,{icon:"arrow-up-s",mobileVariant:u,onClick:()=>le(5),children:"Show fewer sessions"}):null]})]}):null,!d&&z?s.jsx(qt,{icon:"add",mobileVariant:u,onClick:z,children:"Add folder"}):null,e?s.jsx(Xn.Provider,{value:"card",children:s.jsx(Pc,{shelfIds:cb,shelves:e,renderItem:E,hasSessionSearchQuery:a,mobileVariant:u,className:"mt-auto border-t border-border pt-1"})}):null]})})},ub=l.memo(db);function fb(e){Ht("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",n=t==="timeline",r=l.useRef(new Map),o=l.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(b,A)=>{const j=r.current,C=j.get(b);if(C&&C.groups===A)return C.ordered;const w=e.getOrderedGroups(b,A);if(j.set(b,{groups:A,ordered:w}),j.size>256){const v=j.keys().next().value;v!==void 0&&j.delete(v)}return w},a=l.useRef(null),c=t==="threads",d=t==="folder",u=!!(e.isAllFoldersView||n||c||d),f=l.useMemo(()=>{if(!u)return[];const b=[],A=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const j of A){const C=er(j.project,e.homeDirectory);for(const w of j.groups)if(!w.isArchivedBucket)for(const v of w.sessions){const I=e.pinnedSessionIds?Qn(e.pinnedSessionIds,v.session.directory??j.project.normalizedPath,v.session.id):!1,D=v.session.time?.updated||v.session.time?.created||0;b.push({node:v,project:j.project,projectLabel:C,isPinned:I,timestamp:D,globalSession:j===e.allFoldersOnlySection})}}return b.sort((j,C)=>j.isPinned!==C.isPinned?j.isPinned?-1:1:C.timestamp-j.timestamp),b},[e.allFoldersOnlySection,u,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),m=tb(f,{enabled:c||d&&!e.hasSessionSearchQuery,workingShelf:c,autoSettleAfterDays:e.autoSettleAfterDays??null}),[x,y]=l.useState(30);l.useEffect(()=>{y(30)},[e.hasSessionSearchQuery]);const p=l.useMemo(()=>f.slice(0,x),[f,x]),h=l.useMemo(()=>e.timelineBoundaries??Zo(Date.now(),1),[e.timelineBoundaries]),S=l.useMemo(()=>n?wm(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:h}):[],[n,p,h]);if(e.sharedSessionsOnly)return s.jsx(Ls,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const g=(e.isAllFoldersView||t==="timeline"||t==="folder")&&!!e.allFoldersOnlySection;if(e.projectSections.length===0&&!g)return s.jsx(Ls,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!g)return s.jsx(Ls,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:s.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const k=()=>{const b=f.length-p.length;return s.jsxs(s.Fragment,{children:[b>0?s.jsx(qt,{icon:"arrow-down-s",onClick:()=>y(A=>A+30),children:b===1?"Show 1 more session":`Show ${b} more sessions`}):null,x>30&&f.length>30?s.jsx(qt,{icon:"arrow-up-s",onClick:()=>y(30),children:"Show fewer sessions"}):null]})};return s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(Ls,{ref:a,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",children:s.jsxs("div",{className:_((c||d&&m)&&!e.showOnlyMainWorkspace?"flex min-h-full flex-col gap-1 px-2":"space-y-1 px-2"),children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const b=e.sectionsForRender.find(w=>w.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!b)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const A=b.groups.find(w=>w.isMain&&w.sessions.length>0)??b.groups.find(w=>w.sessions.length>0)??b.groups.find(w=>w.isMain)??b.groups[0];if(!A)return s.jsx(qt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:b.project.id,directoryOverride:b.project.normalizedPath}),children:"New session"});const j=b.groups.find(w=>w.isArchivedBucket);return[A,...j&&j.id!==A.id?[j]:[]].map(w=>{const v=`${b.project.id}:${w.id}`,I=w.id===A.id;return s.jsx(l.Fragment,{children:e.renderGroupSessions(w,v,b.project.id,I,null,!0,a)},v)})})()}):c&&m&&e.renderSessionNode?s.jsx(lb,{items:f,shelves:m,renderSessionNode:e.renderSessionNode,hasSessionSearchQuery:e.hasSessionSearchQuery,mobileVariant:e.mobileVariant,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState}):t==="folder"?s.jsx(Xn.Provider,{value:"tree",children:s.jsx(ub,{shelves:m,sections:e.sectionsForRender,homeSection:e.allFoldersOnlySection,homeDirectory:e.homeDirectory,collapsedProjects:e.collapsedProjects,toggleProject:e.toggleProject,hasSessionSearchQuery:e.hasSessionSearchQuery,activeProjectId:e.activeProjectId,hideDirectoryControls:e.hideDirectoryControls,mobileVariant:e.mobileVariant,alwaysShowActions:e.alwaysShowActions,isInlineEditing:e.isInlineEditing,stickyFolderHeaders:e.stickyFolderHeaders,renderGroupSessions:e.renderGroupSessions,renderSessionNode:e.renderSessionNode,getOrderedGroups:i,renderProjectStatusIndicator:e.renderProjectStatusIndicator,scrollContainerRef:a,setActiveProjectIdOnly:e.setActiveProjectIdOnly,setActiveMainTab:e.setActiveMainTab,setSessionSwitcherOpen:e.setSessionSwitcherOpen,openNewSessionDraft:e.openNewSessionDraft,openProjectEditDialog:e.openProjectEditDialog,removeProject:e.removeProject,reorderProjects:e.reorderProjects,openSidebarMenuKey:e.openSidebarMenuKey,setOpenSidebarMenuKey:e.setOpenSidebarMenuKey,onOpenDirectoryDialog:e.onOpenDirectoryDialog,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState})}):t==="timeline"&&e.renderSessionNode?s.jsx("div",{children:f.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[S.map((b,A)=>{const j=bm[b.id];return s.jsxs("section",{"aria-label":j,"data-timeline-bucket":b.id,children:[s.jsx(cn,{label:j,first:A===0}),b.items.map(({node:C,project:w,projectLabel:v,globalSession:I})=>{const D=C.session.directory??w.normalizedPath;return s.jsx(l.Fragment,{children:e.renderSessionNode(C,0,D,w.id,!1,{projectLabel:v,showFolderLabel:!0,globalSession:I},"project")},C.session.id)})]},b.id)}),k()]})}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:f.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[p.map(({node:b,project:A,projectLabel:j,globalSession:C})=>{const w=b.session.directory??A.normalizedPath;return s.jsx(l.Fragment,{children:e.renderSessionNode(b,0,w,A.id,!1,{projectLabel:j,showFolderLabel:!0,globalSession:C},"project")},b.session.id)}),k()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const A=b.project.id,j=i(A,b.groups),C=j.find(v=>v.isMain)??null,w=C?j.filter(v=>v.id!==C.id):j;return s.jsxs("div",{children:[C?e.renderGroupSessions(C,`${A}:${C.id}`,A,!0,null,void 0,a):null,w.map(v=>{const I=`${A}:${v.id}`,D=j.length===1;return s.jsx(l.Fragment,{children:e.renderGroupSessions(v,I,A,D,null,void 0,a)},v.id)})]},A)})})]})})})}const hb=l.memo(fb);let ci=!1;const di=new Set;let La=!1;function pb(){for(const e of di)e()}function Ci(e){ci!==e&&(ci=e,pb())}function mb(e){e.key==="Shift"&&Ci(!0)}function gb(e){e.key==="Shift"&&Ci(!1)}function bb(){Ci(!1)}function xb(){La||typeof window>"u"||(La=!0,window.addEventListener("keydown",mb),window.addEventListener("keyup",gb),window.addEventListener("blur",bb))}function yb(e){return xb(),di.add(e),()=>{di.delete(e)}}function wb(){return ci}function vb(){return!1}function Sb(){return Re.useSyncExternalStore(yb,wb,vb)}const jb=l.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:a,onArchive:c,onDelete:d}){const u=Sb(),f=u?n:t,m=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:i,onMouseDown:a,onClick:m,onKeyDown:x=>x.stopPropagation(),children:s.jsx(P,{name:u?"delete-bin":"archive",className:o})})}),s.jsx(Ge,{side:"left",sideOffset:8,children:f})]})}),kb=l.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:a}){return s.jsx(as,{open:t,onOpenChange:n,children:s.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:"Export Markdown"}),s.jsx(Ns,{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?`})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:o,onChange:c=>i(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),s.jsxs(xn,{children:[s.jsx(Ne,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ne,{type:"button",onClick:()=>{n(!1),a(o)},size:"sm",children:"Export"})]})]})})});function Cb(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:a,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:m,handleOpenMiniChatWindow:x,handleDeleteSession:y,handleRestoreSession:p,shelfActions:h}=e,{Item:S,Separator:g,Sub:k,SubTrigger:b,SubContent:A}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(S,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(S,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),s.jsxs(S,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[i?s.jsx(P,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(P,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),h&&!a?s.jsxs(s.Fragment,{children:[h.section==="settled"?s.jsxs(S,{onClick:h.onUnsettle,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"arrow-go-back",className:"mr-1 h-4 w-4"}),"Un-settle session"]}):s.jsxs(S,{onClick:h.onSettle,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"check",className:"mr-1 h-4 w-4"}),"Settle session"]}),h.section==="snoozed"?s.jsxs(S,{onClick:h.onWake,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"alarm",className:"mr-1 h-4 w-4"}),"Wake session"]}):s.jsxs(k,{children:[s.jsxs(b,{className:"[&>svg:first-child]:mr-1",children:[s.jsx(P,{name:"alarm",className:"mr-1 h-4 w-4"}),"Snooze"]}),s.jsx(A,{className:"min-w-[200px]",children:Yf(new Date).map(j=>s.jsxs(S,{onClick:()=>h.onSnooze(j.snoozedUntil),children:[s.jsx("span",{className:"flex-1",children:j.label}),s.jsx("span",{className:"ml-4 typography-micro text-muted-foreground tabular-nums",children:j.whenLabel})]},j.id))})]})]}):null,s.jsxs(S,{onClick:()=>{m()},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(S,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat window"})]}):null,s.jsx(g,{}),a?null:s.jsxs(S,{className:"[&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:a}),children:[s.jsx(P,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?s.jsxs(S,{className:"[&>svg]:mr-1",onClick:()=>p(n),children:[s.jsx(P,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,s.jsxs(S,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:a,hardDelete:!0}),children:[s.jsx(P,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Ab(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Eo,{children:s.jsx(Do,{className:"app-region-no-drag z-50",children:s.jsx(Ro,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Lo,"min-w-[180px]"),children:Cb(e,{Item:({className:r,...o})=>s.jsx(cl,{className:_(Sl,r),...o}),Separator:({className:r,...o})=>s.jsx(dl,{className:_(jl,r),...o}),Sub:mu,SubTrigger:({className:r,children:o,...i})=>s.jsxs(gu,{className:_(Yu,r),...i,children:[o,s.jsx(P,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:r,children:o,...i})=>s.jsx(Eo,{children:s.jsx(Do,{className:"app-region-no-drag z-50",children:s.jsx(Ro,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:_(Lo,r),...i,children:o})})})})})})})}const mo=new WeakMap,Nb=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;mo.get(n)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,a=null;const c=()=>{i=!0,a!==null&&window.cancelAnimationFrame(a),a=null,mo.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!n.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Ht("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}a=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),mo.set(n,c),a=window.requestAnimationFrame(d)};function Ib(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${i}:${a}`}function Eb(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&n?`${t}/${n}`:n||t}function Db(e){const t=e.info.role==="user"?"User":"Assistant",n=Ib(e.info.time?.created),r=Eb(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
21
|
+
|
|
22
|
+
*${o}*`:`**${t}**`}function Rb(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function Tc(e){const t=Db(e),n=Rb(e.parts).trim();return n?`${t}
|
|
23
|
+
|
|
24
|
+
${n}`:""}function Mc(e,t){const n="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
`,i=e.records.map(Tc).filter(Boolean).join(`
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`),a=[o+i];for(const c of e.children)a.push(Mc(c,t+1));return a.join(`
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`)}function Fc(e,t,n){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
|
|
37
|
+
|
|
38
|
+
*Exported on ${o}*
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
`,a=e.map(Tc).filter(Boolean).join(`
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
`);let c=i+a;if(n&&n.length>0){const d=n.map(u=>Mc(u,1)).join(`
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
`);c+=`
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
`+d}return c}function Lc(e,t){Ih({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(n=>console.warn("[export] Markdown save failed",n))}async function Oc(e,t){const n=await Vf(t,e);return n||null}async function Pb(e){const t=Pl()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await Qf(e)?!0:Tl(e)}function Tb(){return Jf()}function Bc(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 Or=e=>{const t=[],n=r=>{r.children.forEach(o=>{t.push(o.session.id),n(o)})};return n(e),t};function Mb(e,t){const[n,r]=l.useState(!1),[o,i]=l.useState(!0),a=e.session,c=l.useMemo(()=>Or(e).length,[e]),d=l.useCallback(async x=>{const y=[];let p=0;for(const h of x)try{if(!t)throw new Error("Session directory is required for export");const S=[],g=h.session.title||"Untitled Sub-agent",k=typeof h.session.agent=="string"?h.session.agent:void 0,b=await d(h.children);p+=b.skipped,y.push({title:g,agent:k,records:S,children:b.children})}catch{p+=Or(h).length+1}return{children:y,skipped:p}},[t]),u=l.useCallback(x=>{x<=0||ie.warning(x===1?`Exported session, but skipped ${x} sub-agent task that could not be loaded.`:`Exported session, but skipped ${x} sub-agent tasks that could not be loaded.`)},[]),f=l.useCallback(async x=>{if(!t){ie.error("Nothing to export");return}const y=[];if(y.length===0){ie.error("Nothing to export");return}let p,h=0;if(x&&e.children.length>0){const b=await d(e.children);p=b.children,h=b.skipped}const S=Fc(y,a.title??null,p),g=Bc(a.title??null),k=await Oc(S,g);if(k){ie.success("Session exported",{action:{label:Tb(),onClick:()=>{Pb(k).then(b=>{b||ie.error("Failed to reveal path")})}}}),u(h);return}Lc(S,g),ie.success("Session exported"),u(h)},[d,e.children,a.title,t,u]),m=l.useCallback(async()=>{if(e.children.length>0){i(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:n,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,descendantCount:c,handleExportSession:m,doExportSession:f}}const Fb=(e,t)=>{if(!t)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const i=t.get(o);if(i)for(const a of i)r.has(a)||(r.add(a),n.push(a))}return n},bt=Is()((e,t)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{t().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{t().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,o)=>{const i=t(),a=new Set(i.selectedIds);let c=i.scopeKey,d=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(a.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(a.has(n)){for(const x of f)a.delete(x);d===n&&(d=null)}else{for(const x of f)a.add(x);d=n}a.size===0?e({selectedIds:a,scopeKey:null,anchorId:null}):e({selectedIds:a,scopeKey:c,anchorId:d})},setRange:(n,r,o,i,a)=>{const c=t();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),f=o.indexOf(r);if(u<0||f<0)return;const[m,x]=u<=f?[u,f]:[f,u],y=o.slice(m,x+1),p=Fb(y,a),S=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const g of p)S.add(g);e({selectedIds:S,scopeKey:i??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=t();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const i of n)o.delete(i);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),Oa=e=>Ee(e.session.directory??null),Lb=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),Ob=e=>{if(!e.openSidebarMenuKey)return null;const t=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${t}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},mr=e=>e.menuOpenSessionId??Ob(e),gr=(e,t,n)=>t?n.has(e.node.session.id)?!0:hs(e.node,t):!1,ui=(e,t,n,r,o)=>{if(e.session.id!==t.session.id)return!0;const i=o(e);if(n.has(i)!==r.has(i)||e.children.length!==t.children.length)return!0;for(let a=0;a<e.children.length;a+=1)if(ui(e.children[a],t.children[a],n,r,o))return!0;return!1},Bb=(e,t)=>{if(e.hasSessionSearchQuery||t.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=t.archivedBucket?"archived":"active";return ui(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||ui(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${t.renderContext??"project"}:${r}:${o.session.id}`)},_b=(e,t)=>{if(e.node.session.id!==t.node.session.id||e.node.session!==t.node.session||e.depth!==t.depth||e.groupDirectory!==t.groupDirectory||e.projectId!==t.projectId||e.archivedBucket!==t.archivedBucket||(e.renderContext??"project")!==(t.renderContext??"project")||e.mobileVariant!==t.mobileVariant||e.alwaysShowActions!==t.alwaysShowActions||e.allowQuickArchiveAction!==t.allowQuickArchiveAction||e.hasSessionSearchQuery!==t.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==t.normalizedSessionSearchQuery||e.nodeStructureKey!==t.nodeStructureKey||Oa(e.node)!==Oa(t.node)||!Lb(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&uc(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&Bb(e,t)||e.editingId!==t.editingId&&(gr(e,e.editingId,e.subtreeContainsEditing)||gr(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(gr(e,e.editingId,e.subtreeContainsEditing)||gr(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(hs(e.node,e.copiedSessionId)||hs(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=mr(e),r=mr(t);if(hs(e.node,n)||hs(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const n=mr(e),r=mr(t);if(hs(e.node,n)||hs(t.node,r))return!1}return e.setEditingId===t.setEditingId&&e.setEditTitle===t.setEditTitle&&e.handleSaveEdit===t.handleSaveEdit&&e.handleCancelEdit===t.handleCancelEdit&&e.toggleParent===t.toggleParent&&e.handleSessionSelect===t.handleSessionSelect&&e.handleSessionDoubleClick===t.handleSessionDoubleClick&&e.togglePinnedSession===t.togglePinnedSession&&e.handleShareSession===t.handleShareSession&&e.handleCopyShareUrl===t.handleCopyShareUrl&&e.handleCopySessionId===t.handleCopySessionId&&e.handleUnshareSession===t.handleUnshareSession&&e.setOpenSidebarMenuKey===t.setOpenSidebarMenuKey&&e.getFoldersForScope===t.getFoldersForScope&&e.getSessionFolderId===t.getSessionFolderId&&e.removeSessionFromFolder===t.removeSessionFromFolder&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.handleDeleteSession===t.handleDeleteSession&&e.handleRestoreSession===t.handleRestoreSession&&e.renderSessionNode===t.renderSessionNode};function zb({node:e,groupDirectory:t,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:a,hasSessionSearchQuery:c}){const d=e.session,u=Ee(d.directory??null)??Ee(t??null),f=Me(xe=>xe.currentSessionId===d.id),m=Oo(u),x=Vu(u),y=ut(l.useCallback(xe=>{if(r?.projectLabel||!n)return null;const ze=xe.projects.find(X=>X.id===n);return ze?er({label:ze.label,normalizedPath:Ee(ze.path)??ze.path},null):null},[n,r?.projectLabel])),p=r?.projectLabel??y,h=ut(l.useCallback(xe=>n?xe.projects.find(ze=>ze.id===n)?.path??null:null,[n])),S=e.worktree,g=r?.branchLabel??S?.branch??(m&&m!=="HEAD"?m:null),k=Ee(h),b=Oo(k),j=!!k&&u===k||!!g&&g===b,C=j?null:g,w=!j&&(x===!0||!!(g||S)),v=e.children.length,I=d.agent,D=S?.branch?.trim()||g?.trim()||null,z=Ee(S?.path??u),W=l.useMemo(()=>D&&z?Zn(z,D):null,[D,z]),$=hc(W);pc(z,D);const K=$?`var(--pr-${$.visualState})`:void 0,B=l.useMemo(()=>{if(!$)return null;switch($.visualState){case"merged":return"Merged";case"open":return $.canMerge===!0||$.mergeableState==="clean"||$.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return $.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[$]),R=n??u??null,T=bt(xe=>xe.enabled),E=bt(l.useCallback(xe=>xe.selectedIds.has(d.id),[d.id])),F=bt(xe=>xe.toggleSelected),q=bt(xe=>xe.setRange),L=kl(d.id)?.type??"idle",le=L==="busy"||L==="retry",H=Qu(d.id,le),Ae=js(d,"Untitled session"),Pe=e.children.length>0,J=Qn(o,u,d.id),M=c?!0:i.has(a),Y=Ju(d.id);Cl(l.useCallback(xe=>xe.index.session.unseenHasError[d.id]??!1,[d.id]));const Q=Xu(d.id),ne=Zu({pendingInput:Q,isStreaming:le,unseenCount:Y,isActive:f}),ae=Y>0||Al(Q),me=d.time?.updated||d.time?.created||Date.now(),ge=jh(me),ke=l.useMemo(()=>ic(e.forkColorId),[e.forkColorId]),De=l.useMemo(()=>Dm(e.forkColorId,{active:f||E}),[e.forkColorId,f,E]);return{session:d,sessionDirectory:u,prDirectory:z,prBranch:D,prNumber:$?.number??null,isActive:f,tooltipProjectLabel:p,projectPath:h,tooltipBranchLabel:C,isGitRepo:w,subtaskCount:v,agentName:I,prSummary:$,prIconColor:K,prStatusLabel:B,selectionScopeKey:R,selectionModeEnabled:T,isRowSelected:E,toggleRowSelected:F,setRowRange:q,isStreaming:le,hasActivityDuration:H,sessionTitle:Ae,hasChildren:Pe,isPinnedSession:J,isExpanded:M,needsAttention:ae,pendingInput:Q,attention:ne,sessionCompactUpdatedLabel:ge,forkSolid:ke,rowBackground:De}}const Ub=({prDirectory:e,prNumber:t,prStatusLabel:n,prIconColor:r})=>{const o=wl(e);if(!e||!o)return s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",style:r?{color:r}:void 0,title:n?`PR #${t} — ${n}`:`PR #${t}`,children:[s.jsx(P,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]});const i=a=>{a.stopPropagation(),a.preventDefault(),Cc(e,o,t)};return s.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:a=>{a.stopPropagation(),a.preventDefault()},onKeyDown:a=>{if(!(a.key!=="Enter"&&a.key!==" ")){if(a.repeat){a.stopPropagation(),a.preventDefault();return}i(a)}},className:"inline-flex shrink-0 cursor-pointer items-center gap-1 rounded hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",style:r?{color:r}:void 0,title:n?`PR #${t} — ${n}. Open in Pull requests`:`Open PR #${t} in Pull requests`,"aria-label":n?`Open pull request #${t}, ${n}, in Pull requests`:`Open pull request #${t} in Pull requests`,children:[s.jsx(P,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]})};function $b(e){Ht("ui.sidebar_session_node.render");const{node:t,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:a,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,editingId:f,setEditingId:m,editTitle:x,setEditTitle:y,handleSaveEdit:p,handleCancelEdit:h,toggleParent:S,handleSessionSelect:g,handleSessionDoubleClick:k,togglePinnedSession:b,handleShareSession:A,copiedSessionId:j,handleCopyShareUrl:C,handleCopySessionId:w,handleUnshareSession:v,openSidebarMenuKey:I,setOpenSidebarMenuKey:D,renamingFolderId:z,getFoldersForScope:W,getSessionFolderId:$,removeSessionFromFolder:K,addSessionToFolder:B,createFolderAndStartRename:R,handleDeleteSession:T,handleRestoreSession:E,alwaysShowActions:F,allowQuickArchiveAction:q,renderSessionNode:G,secondaryMeta:L,renderContext:le="project",subtreeContainsEditing:H,menuOpenSessionId:Ae,childRenderExtrasFor:Pe}=e,J=l.useContext(Xn)==="tree",M="size-3 shrink-0",Y=l.useMemo(()=>Ml(),[]),Q=!i&&q,ne=l.useRef(!1),ae=l.useRef(f);ae.current=f;const me=l.useRef(null),ge=l.useRef(p);ge.current=p;const[ke,ve]=l.useState(x),De=l.useRef(ke);De.current=ke;const xe=l.useRef(null),ze=l.useRef(null),oe=`${le}:${i?"archived":"active"}:${t.session.id}`,{session:te,sessionDirectory:fe,prDirectory:he,prNumber:_e,isActive:je,tooltipProjectLabel:V,projectPath:we,tooltipBranchLabel:ue,isGitRepo:Se,subtaskCount:Ye,agentName:Ue,prSummary:U,prIconColor:pe,prStatusLabel:se,selectionScopeKey:Le,selectionModeEnabled:ht,isRowSelected:ct,toggleRowSelected:Qe,setRowRange:Dt,isStreaming:Xe,hasActivityDuration:Jt,sessionTitle:wt,hasChildren:tt,isPinnedSession:Rt,isExpanded:Bt,pendingInput:Pt,attention:Tt,sessionCompactUpdatedLabel:cs,forkSolid:ds,rowBackground:rt}=zb({node:t,groupDirectory:r,projectId:o,secondaryMeta:L,pinnedSessionIds:a,expandedParents:c,expansionKey:oe,hasSessionSearchQuery:d}),{exportDialogOpen:pt,setExportDialogOpen:_t,exportIncludeSubtasks:Xt,setExportIncludeSubtasks:us,descendantCount:Ce,handleExportSession:Oe,doExportSession:Ie}=Mb(t,fe),[Be,qe]=l.useState(!1),mt=l.useContext(Wr),st=n===0&&!i?mt?.sectionById.get(te.id)??null:null,Ze=Ks(l.useCallback(re=>st==="snoozed"?re.entries[te.id]?.snoozedUntil??null:null,[st,te.id])),xs=st==="snoozed"||st==="settled",Zt=st!==null&&st!=="snoozed"&&!!mt?.wokeIds.has(te.id),Ve=l.useMemo(()=>{if(!st)return null;const re=fe??null;return{section:st,onSettle:()=>Dc(te.id,re,wt),onUnsettle:()=>un(te.id,{settled:"active"},re,"Could not un-settle the session"),onSnooze:It=>un(te.id,{snoozedUntil:It},re,"Could not snooze the session"),onWake:()=>un(te.id,{snoozedUntil:null},re,"Could not wake the session")}},[st,te.id,fe,wt]),vt=Ve?Ve.section==="snoozed"?{label:"Wake",hint:"Wake now: back to the list",icon:"alarm",run:Ve.onWake}:Ve.section==="settled"?{label:"Un-settle",hint:"Un-settle: back to the list",icon:"arrow-go-back",run:Ve.onUnsettle}:{label:"Settle",hint:"Settle: move to Settled, not archived",icon:"check",run:Ve.onSettle}:null,zt=l.useCallback(()=>{fe&&Kn("desktop_open_session_mini_chat_window",{sessionId:te.id,directory:fe,apiBaseUrl:$o(),clientToken:Uo()}).catch(re=>{console.warn("[session-sidebar] failed to open mini chat window",re)})},[te.id,fe]);l.useEffect(()=>{if(f!==te.id)return;const re=It=>{const Ys=It.target?.closest?.(`[data-session-rename-form="${CSS.escape(te.id)}"]`);ze.current&&!Ys&&ge.current(De.current)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[f,te.id]),l.useLayoutEffect(()=>{if(f!==te.id){xe.current===te.id&&(xe.current=null);return}xe.current!==te.id&&(xe.current=te.id,ve(x))},[f,x,te.id]);const kt=Tt==="needs-input",Ct=kt&&Pt?ef(Pt.kind,Pt.count):null,Es=Tt==="unread",Hs=Ze!==null?Xf(Ze,Date.now()):Zt?"Woke":cs,ys=Xe&&Jt,Ds=Q&&(F||Be),gt=Xe&&!J&&!Ds&&f!==te.id,Mt=!!(L?.showFolderLabel&&V),St=!!ue||Se,es=!!(Ue&&Ue!=="default"),ts=!!U&&_e!=null,at=ys&&!gt,At=Mt&&St||ts||Ye>0||es||at,Rs=re=>ue?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",re?"shrink":"flex-1"),children:[s.jsx(P,{name:"git-branch",className:M,style:pe?{color:pe}:void 0}),s.jsx(zn,{value:ue})]}):Se?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(P,{name:"git-repository",className:M}),s.jsx("span",{children:"git"})]}):null,Ft=Rt,kn=s.jsx(P,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),qs=Ft?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:kn}):null,Cn=tt?s.jsx("button",{type:"button",onClick:re=>{re.stopPropagation(),S(oe)},onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),re.stopPropagation(),S(oe))},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":Bt?"Collapse subsessions":"Expand subsessions",children:Bt?s.jsx(P,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(P,{name:"arrow-right-s",className:"h-3 w-3"})}):null,Ps=re=>{if(!re&&me.current){const{id:It,title:Ts}=me.current;me.current=null,m(It),y(Ts)}},O=re=>{qe(re)},ce=re=>{re.preventDefault(),re.stopPropagation()},ye=re=>{re.preventDefault(),re.stopPropagation()},$e=re=>{re.preventDefault(),re.stopPropagation(),D(null),T(te,{archivedBucket:i})},it=re=>{re.preventDefault(),re.stopPropagation(),D(null),T(te,{archivedBucket:i,hardDelete:!0,skipConfirm:!0})},Je=re=>{if(ne.current){ne.current=!1;return}if(ht){if(re?.preventDefault(),re?.stopPropagation(),re?.shiftKey){const Ts=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Vs=>Vs.getAttribute("data-session-row")).filter(Vs=>typeof Vs=="string"&&Vs.length>0),Ys=bt.getState().anchorId,rr=new Map;rr.set(te.id,Or(t)),Dt(Ys,te.id,Ts,Le,rr);return}Qe(te.id,Le,Or(t));return}re?.currentTarget&&Nb(re.currentTarget),g(te.id,fe)},ss=re=>{re.defaultPrevented||re.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Je(re)},Nt=re=>{(re.button===2||re.button===0&&re.ctrlKey&&!ht)&&(ne.current=!0)},An={session:te,sessionTitle:wt,sessionDirectory:fe,isPinnedSession:Rt,archivedBucket:i,isElectron:Y,renamingFolderId:z,editingIdRef:ae,pendingRenameRef:me,handleCopySessionId:w,togglePinnedSession:b,handleExportSession:Oe,handleOpenMiniChatWindow:zt,handleDeleteSession:T,handleRestoreSession:E,shelfActions:Ve},nr=s.jsx(Ab,{...An});return s.jsxs(l.Fragment,{children:[s.jsx(Xm,{sessionId:te.id,sessionDirectory:fe??null,sessionTitle:wt,children:s.jsxs(al,{open:Be,onOpenChange:O,onOpenChangeComplete:Ps,children:[s.jsxs(ll,{render:s.jsx("div",{"data-session-row":te.id,"data-session-scope":Le??"","data-session-archived":i?"1":"0","data-fork-color":ds?t.forkColorId:void 0,"data-global-session":L?.globalSession?"1":void 0,"data-sidebar-tree-row":J?"":void 0,onClick:ss,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...rt?{backgroundColor:rt}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",J?dc:"my-0.5 rounded-xl py-2",!rt&&n>0?"bg-secondary/30 hover:bg-interactive-hover":rt?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!rt&&je&&!ct&&"bg-interactive-selection",!rt&&ct&&"bg-interactive-selection")}),children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",gt&&"oc-session-row-working-fade"),"data-clear-on-hover":gt&&Q?"true":void 0,"data-working-duration":gt&&ys?"true":void 0,children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",J?Gr:"gap-1.5"),children:[J?s.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:Xe&&!kt?s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,Cn,qs,f===te.id?s.jsxs("form",{ref:ze,"data-session-rename-form":te.id,className:_("flex min-w-0 flex-1 items-center gap-2",J?"min-h-5":"min-h-8"),onPointerDown:re=>re.stopPropagation(),onMouseDown:re=>re.stopPropagation(),onSubmit:re=>{re.preventDefault(),p(ke)},children:[s.jsx("input",{value:ke,onChange:re=>ve(re.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:re=>{re.stopPropagation(),re.key==="Escape"&&h()}}),s.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:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:h,"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:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsxs("button",{type:"button",onMouseDown:Nt,onClick:re=>Je(re),onDoubleClick:re=>{re.stopPropagation(),k(te.id,wt)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[s.jsxs("div",{className:_("flex w-full min-w-0 flex-1 gap-1.5 overflow-hidden",J?"items-center":"items-start"),children:[s.jsx("div",{className:_("min-w-0 flex-1 typography-ui-label",J?"block truncate":"line-clamp-2 text-pretty [overflow-wrap:anywhere]",je?"font-medium text-foreground":"font-normal",!je&&(xs?"text-muted-foreground group-hover:text-foreground":"text-foreground")),children:Sr(wt,u)}),Rt?s.jsx(P,{name:"star-fill",className:_("h-3 w-3 text-primary shrink-0",!J&&"mt-1")}):null,s.jsx("span",{"aria-hidden":"true",className:_("invisible ml-1 min-w-6 shrink-0 whitespace-nowrap typography-micro",(Ze!==null||Zt)&&!Es&&"pl-4"),children:Es?null:Hs})]}),!J&&(Mt||St||At)?s.jsxs("div",{className:_("flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden typography-micro leading-4 font-normal",xs?"text-subtle-foreground":"text-muted-foreground"),children:[Mt?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",At?"max-w-[60%] shrink-0":"flex-1"),children:[we?s.jsx(xi,{directory:we,label:V??"",className:M}):s.jsx(P,{name:"folder",className:M}),s.jsx("span",{className:"truncate",children:V})]}):Rs(!1),At?s.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",Mt?"flex-1":"shrink-0"),children:[Mt?Rs(!0):null,ts?s.jsx(Ub,{prDirectory:he,prNumber:_e,prStatusLabel:se,prIconColor:pe}):null,Ye>0?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(P,{name:"node-tree",className:M}),s.jsx("span",{children:Ye})]}):null,es?s.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:Ue}):null,at?s.jsx(ta,{sessionId:te.id,running:Xe,className:"shrink-0 text-subtle-foreground"}):null]}):null]}):null]})]}),s.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",J?"top-1/2 -translate-y-1/2":"top-2",f===te.id&&"hidden"),children:[s.jsx("div",{className:_("flex items-center justify-end",Ds?"opacity-0":Q?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:kt&&!gt?s.jsx(Vi,{label:Ct??"Needs input"}):Es?s.jsx(kh,{label:"Session complete"}):Ze!==null||Zt?s.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro text-muted-foreground whitespace-nowrap",title:Ze!==null?`Snoozed until ${new Date(Ze).toLocaleString()}`:"Back from snooze",children:[s.jsx(P,{name:"alarm",className:"size-3 shrink-0"}),Hs]}):s.jsx("span",{className:"typography-micro text-subtle-foreground whitespace-nowrap",children:cs})}),Q?s.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",F||Be?"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:vt?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":vt.label,className:"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:ce,onMouseDown:ye,onKeyDown:re=>re.stopPropagation(),onClick:re=>{re.preventDefault(),re.stopPropagation(),D(null),vt.run()},children:s.jsx(P,{name:vt.icon,className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:6,children:vt.hint})]}):s.jsx(jb,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:ce,onMouseDown:ye,onArchive:$e,onDelete:it})}):null]})]}),gt?s.jsxs("span",{"data-session-working":!0,className:_("pointer-events-none absolute inset-y-0 right-0 flex items-center rounded-r-[inherit] pr-3 transition-opacity",Q&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[kt?null:s.jsx("span",{"aria-hidden":"true",className:"oc-session-row-working-aura absolute inset-y-0 right-0 w-24 rounded-r-[inherit] bg-gradient-to-l from-primary/15 to-transparent"}),s.jsxs("span",{className:"relative flex flex-col items-end gap-1",children:[s.jsx("span",{className:"flex h-5 items-center",children:kt?s.jsx("span",{className:"inline-flex size-3 shrink-0 items-center justify-center",children:s.jsx(Vi,{label:Ct??"Needs input"})}):s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}),ys?s.jsx(ta,{sessionId:te.id,running:Xe,className:"typography-micro leading-4"}):null]})]}):null]}),nr]})}),tt&&Bt?t.children.map(re=>{const It=Pe?Pe(re):{subtreeContainsEditing:H,menuOpenSessionId:Ae,nodeStructureKey:""};return s.jsx(l.Fragment,{children:G(re,n+1,fe??r,o,i,L?.globalSession?{globalSession:!0}:void 0,le,It)},re.session.id)}):null,s.jsx(kb,{open:pt,onOpenChange:_t,descendantCount:Ce,exportIncludeSubtasks:Xt,setExportIncludeSubtasks:us,onExport:Ie})]},te.id)}const Kb=l.memo($b,_b),Wb=({open:e,onOpenChange:t,project:n,onSave:r})=>s.jsx(as,{open:e,onOpenChange:t,children:s.jsx(ls,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(Ls,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:s.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&n?s.jsx(Zp,{project:n,onIdentitySave:r}):null})})})});function _c(e){const{showDeletionDialog:t,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:i}=e;return s.jsxs(xn,{className:"w-full sm:items-center sm:justify-between",children:[s.jsxs("button",{type:"button",onClick:()=>n(!t),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":!t,children:[t?s.jsx(P,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(P,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.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"}),s.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:i})]})]})}function Gb(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=c=>js(c);return s.jsx(as,{open:!!t,onOpenChange:c=>{c||n(null)},children:s.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:t?.archivedBucket?"Delete session?":"Archive session?"}),s.jsx(Ns,{children:t&&t.descendantCount>0?t.archivedBucket?t.descendantCount===1?`"${a(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${a(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:t.descendantCount===1?`"${a(t.session)}" and its ${t.descendantCount} sub-task will be archived.`:`"${a(t.session)}" and its ${t.descendantCount} sub-tasks will be archived.`:t?.archivedBucket?`"${t?.session?a(t.session):"Untitled Session"}" will be permanently deleted.`:`"${t?.session?a(t.session):"Untitled Session"}" will be archived.`})]}),s.jsx(_c,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:t?.archivedBucket?"Delete":"Archive"})]})})}function Hb(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=t?.archivedBucket===!0,c=t?.sessionCount??0,d=a?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=a?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 s.jsx(as,{open:!!t,onOpenChange:f=>{f||n(null)},children:s.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:d}),s.jsx(Ns,{children:u})]}),s.jsx(_c,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:a?"Delete":"Archive"})]})})}function qb(e){const{value:t,setValue:n,onConfirm:r}=e,{git:o}=Gs(),[i,a]=l.useState(null),[c,d]=l.useState(!1),[u,f]=l.useState(!1),[m,x]=l.useState(!1),y=t?.worktree.path??null;l.useEffect(()=>{let j=!1;return a(null),d(!1),f(!1),x(!1),!t||!y?()=>{j=!0}:(o.getGitStatus(y).then(C=>{if(!j){if(typeof C?.isClean!="boolean"){d(!0);return}a(C)}}).catch(()=>{j||d(!0)}),()=>{j=!0})},[o,t,y]);const p=i?.isClean===!1,h=(i?.ahead??0)>0,S=h&&!t?.worktree.branch,g=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",k=!!(t&&i&&!c&&!t.hasActiveSession&&(!p&&!S||u)&&!m),b=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",A=async()=>{if(k){x(!0);try{await r({force:p})}finally{x(!1)}}};return s.jsx(as,{open:!!t,onOpenChange:j=>{!j&&!m&&n(null)},children:s.jsxs(ls,{showCloseButton:!1,className:"max-w-md gap-5",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:"Close worktree?"}),s.jsx(Ns,{children:`Closing "${b}" removes its worktree directory. ${g}`})]}),c?s.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:[s.jsx(P,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):i===null?s.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,t?.hasActiveSession?s.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:[s.jsx(P,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,p?s.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(P,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),s.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[s.jsx(Yn,{checked:u,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),s.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,h?s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:i?.ahead===1?`This worktree has 1 unpushed commit. ${g}`:`This worktree has ${i?.ahead} unpushed commits. ${g}`}),S?s.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(P,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),s.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[s.jsx(Yn,{checked:u,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),s.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,s.jsxs(xn,{className:"sm:justify-end",children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:m,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!k,children:m?"Closing…":"Close worktree"})]})]})})}function Yb(e){const{value:t,setValue:n,onConfirm:r}=e;return s.jsx(as,{open:!!t,onOpenChange:o=>{o||n(null)},children:s.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:"Delete folder?"}),s.jsx(Ns,{children:t&&(t.subFolderCount>0||t.sessionCount>0)?t.subFolderCount>0?t.subFolderCount===1?`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted. Sessions inside will not be deleted.`:`"${t?.folderName??""}" will be permanently deleted.`})]}),s.jsxs(xn,{children:[s.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"}),s.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 Vb=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:a,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:m,setDeleteFolderConfirm:x,confirmDeleteFolder:y,closeWorktreeConfirm:p,setCloseWorktreeConfirm:h,confirmCloseWorktree:S,bulkDeleteConfirm:g,setBulkDeleteConfirm:k,confirmBulkDelete:b})=>s.jsxs(s.Fragment,{children:[s.jsx(Ql,{open:e,onOpenChange:t,info:n.info,downloading:n.downloading,downloaded:n.downloaded,progress:n.progress,error:n.error,onDownload:n.downloadUpdate,onRestart:n.restartToUpdate,runtimeType:n.runtimeType}),s.jsx(Wb,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:i}),s.jsx(Gb,{value:a,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),s.jsx(Yb,{value:m,setValue:x,onConfirm:y}),s.jsx(qb,{value:p,setValue:h,onConfirm:S}),s.jsx(Hb,{value:g,setValue:k,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:b})]}),Qb=({directories:e})=>{const t=l.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Ee(o)?.toLowerCase();i&&r.add(i)}),r},[e]),n=Un(r=>{let o=0,i=!1;for(const a of r.catalog.byId.values()){const c=Ee(a.directory)?.toLowerCase();!c||!t.has(c)||(Al(a.pendingInput)?o+=1:(a.lifecycle==="busy"||a.lifecycle==="retry")&&(i=!0))}return{inputCount:o,hasBusySession:i}},(r,o)=>r.inputCount===o.inputCount&&r.hasBusySession===o.hasBusySession,"catalog");if(n.inputCount>0){const r=tf(n.inputCount);return s.jsx("span",{className:"inline-flex items-center","aria-label":r,title:r,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return n.hasBusySession?s.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:s.jsx(Cs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},Jb=e=>{let t=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(t+=r.sessions.length);return t},Xb=e=>{const t=new Map;for(const n of e){let r=0;for(const o of n.groups)o.isArchivedBucket||(r+=o.sessions.length);t.set(n.project.id,r)}return t},Zb=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),ex=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),tx=(e,t)=>{const n=new Map;for(const r of e){const o=new Set;for(const i of r.groups){if(i.isArchivedBucket)continue;if(i.sessions.some(c=>t.has(c.session.id))&&i.directory){const c=Ee(i.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},sx=e=>e.map(t=>t.groups.some(n=>n.isArchivedBucket)?{...t,groups:t.groups.filter(n=>!n.isArchivedBucket)}:t),nx=(e,t,n,r)=>{if(!n)return t;const o=e.find(c=>c.project.id===n);if(!o)return[];const i=Ee(r??o.project.normalizedPath),a=o.groups.find(c=>!c.isArchivedBucket&&Ee(c.directory)===i);return a?[{...o,groups:[a]}]:[]},rx=(e,t)=>{const n=new Map,r=new Map;return e.forEach(o=>{const i=er(o.project,t);o.groups.forEach(a=>{const c=a.branch&&a.branch!=="HEAD"&&a.branch!==i?a.branch:null,d={projectLabel:i,branchLabel:c},u=f=>{f.forEach(m=>{const x=o.project.normalizedPath.length,y=r.get(m.session.id)??-1;x<y||(n.set(m.session.id,{node:m,projectId:o.project.id,groupDirectory:a.directory,secondaryMeta:d}),r.set(m.session.id,x),m.children.length>0&&u(m.children))})};u(a.sessions)})}),n};function ox({projectSections:e,flatSectionsForRender:t,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:a,unreadSessionIdSet:c}){const d=l.useMemo(()=>rx(e,i),[e,i]),u=l.useMemo(()=>sx(t),[t]),f=l.useMemo(()=>nx(n,u,r,o),[n,u,r,o]),m=l.useMemo(()=>Jb(e),[e]),x=l.useMemo(()=>Xb(e),[e]),y=l.useCallback(S=>{const g=e.find(k=>k.project.id===S);return g?Zb(g,a):!1},[a,e]),p=l.useMemo(()=>tx(e,a),[a,e]),h=l.useCallback(S=>{const g=e.find(k=>k.project.id===S);return g?ex(g,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:m,sessionCountByProject:x,hasActiveSessionByProject:y,activeDirectoriesByProject:p,hasUnseenByProject:h}}const ix=({selectedCount:e,archivedBucket:t,onRestore:n,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",a="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 s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border pl-5 pr-3.5 py-1.5",children:[s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[t?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:a,"aria-label":"Restore",children:s.jsx(P,{name:"inbox-unarchive",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Restore"})})]}):null,s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.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":i,children:s.jsx(P,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:i})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:a,"aria-label":"Exit selection",children:s.jsx(P,{name:"close",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Exit selection"})})]})]})]})},ax=e=>{const{isInlineEditing:t,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:a,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:m}=e,x=bt(T=>T.enabled),y=bt(T=>T.selectedIds.size),p=y>0,h=bt(T=>T.selectedIds),S=bt(T=>T.scopeKey),g=l.useCallback(()=>{bt.getState().toggleMode()},[]),k=l.useCallback(()=>{bt.getState().disable()},[]),b=l.useMemo(()=>{if(!p||typeof document>"u")return!1;let T=!1,E=!1;for(const F of h){const q=document.querySelectorAll(`[data-session-row="${CSS.escape(F)}"]`);for(const G of q)G.getAttribute("data-session-archived")==="1"?E=!0:T=!0}return E&&!T},[p,h]),A=l.useMemo(()=>{if(S)return S;if(!p||typeof document>"u")return null;for(const T of h){const F=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(F&&F.length>0)return F}return null},[p,h,S]),j=l.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(E=>E.scopeKey):[A]},[A,o]),C=l.useMemo(()=>j.flatMap(T=>r[T]??[]),[r,j]),w=l.useCallback(T=>{for(const E of j)if((r[E]??[]).some(F=>F.id===T))return E;return null},[r,j]),v=l.useMemo(()=>{if(!p)return!1;for(const T of j)for(const E of r[T]??[])for(const F of E.sessionIds)if(h.has(F))return!0;return!1},[r,j,p,h]),I=l.useCallback((T,E)=>{const F=Array.from(h);for(const q of j)q!==T&&a(q,F);i(T,E,F)},[i,a,h,j]),D=l.useCallback(T=>{if(!p)return;const E=w(T);E&&I(E,T)},[p,I,w]),z=l.useCallback(()=>{const T=j[0];if(!T||!p)return;const E=c(T);E&&I(T,E.id)},[c,p,I,j]),W=l.useCallback(()=>{if(!p)return;const T=Array.from(h);for(const E of j)a(E,T)},[a,h,j,p]),$=l.useCallback(async()=>{const T=Array.from(h);if(T.length!==0){if(b){const{deletedIds:E,failedIds:F}=await f(T);E.length>0&&ie.success(E.length===1?`Deleted ${E.length} session`:`Deleted ${E.length} sessions`),F.length>0&&ie.error(F.length===1?`Failed to delete ${F.length} session`:`Failed to delete ${F.length} sessions`)}else{const{archivedIds:E,failedIds:F}=await d(T);E.length>0&&ie.success(E.length===1?`Archived ${E.length} session`:`Archived ${E.length} sessions`),F.length>0&&ie.error(F.length===1?`Failed to archive ${F.length} session`:`Failed to archive ${F.length} sessions`)}bt.getState().clear()}},[d,b,f,h]),K=l.useCallback(()=>{if(!p)return;const T=h.size;if(!n){$();return}m({sessionCount:T,archivedBucket:b})},[b,$,h,n,m,p]),B=l.useCallback(async()=>{if(!p||!b)return;const T=Array.from(h),{restoredIds:E,failedIds:F}=await u(T);E.length>0&&ie.success(E.length===1?`Restored ${E.length} session`:`Restored ${E.length} sessions`),F.length>0&&ie.error(F.length===1?`Failed to restore ${F.length} session`:`Failed to restore ${F.length} sessions`),bt.getState().clear()},[b,p,h,u]),R=l.useCallback(async()=>{m(null),await $()},[$]);return l.useEffect(()=>{if(!x)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),E=F=>{if(t)return;const q=F.target;if(q&&(q.tagName==="INPUT"||q.tagName==="TEXTAREA"||q.isContentEditable))return;const G=T?F.metaKey:F.ctrlKey;if(F.key==="Escape"){F.preventDefault(),bt.getState().disable();return}if(G&&F.key==="Backspace"){F.preventDefault(),K();return}if(G&&(F.key==="a"||F.key==="A")){const L=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(L.length===0)return;F.preventDefault();const H=bt.getState().scopeKey??L[0]?.getAttribute("data-session-scope")??null,Ae=J=>H?J.getAttribute("data-session-scope")===H:!0,Pe=L.filter(Ae).map(J=>J.getAttribute("data-session-row")).filter(J=>typeof J=="string"&&J.length>0);if(Pe.length===0)return;bt.getState().replaceAll(Pe,H||null)}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[K,t,x]),{selectionModeEnabled:x,hasSelection:p,selectedIdsSize:y,bulkScopeIsArchived:b,derivedSelectionScope:A,bulkScopeFolders:C,bulkCanRemoveFromFolder:v,handleToggleSelectionMode:g,handleExitSelectionMode:k,handleBulkMoveToFolder:D,handleBulkCreateFolderAndMove:z,handleBulkRemoveFromFolder:W,handleBulkDelete:K,handleBulkRestore:B,confirmBulkDelete:R}},lx=(e,t)=>{const n=e??{};return delete n.projectSortOrder,t<4&&delete n.displayMode,t<5&&delete n.sessionGroupingMode,n},Ba=Is()(zl(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:lx})),_a="oc.sessions.projectCollapse",za="oc.sessions.groupOrder",Ua="oc.sessions.groupCollapse",$a="oc.sessions.activeSessionByProject",Ka="oc.sessions.expandedParents.v3",cx=new Set,go=[],Lt=e=>{const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[])},dx=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:a=!1})=>{zo("react.session_sidebar_render"),Ht("ui.session_sidebar.render"),Ht(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),Ht(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=l.useState(!1),[u,f]=l.useState(""),m=l.useRef(null),x=l.useRef(null),[y,p]=l.useState(null),[h,S]=l.useState(""),[g,k]=l.useState(null),[b,A]=l.useState(new Set),j=l.useMemo(()=>on(),[]),[C,w]=l.useState(new Set),v=Xs(N=>N.selectedSpaceId),I=Xs(N=>N.selectedWorktreePath),[D,z]=l.useState(new Map),[W,$]=l.useState(new Map),[K,B]=l.useState(!1),[R,T]=l.useState(null),[E,F]=l.useState(null),[q,G]=l.useState(""),[L,le]=l.useState(null),[H,Ae]=l.useState(null),[Pe,J]=l.useState(null),[M,Y]=l.useState(null),Q=Vn(N=>N.ids),ne=sf(l.useCallback(N=>e?N.rankById:vl,[e])),ae=Un(N=>e?nf(N.catalog):"",void 0,"catalog"),me=l.useMemo(()=>ae?ae.split("|"):go,[ae]),ge=l.useMemo(()=>new Set(me),[me]),ke=Cl(Po(N=>e?Object.entries(N.index.session.unseenCount).filter(([,Z])=>Z>0).map(([Z])=>Z).sort():go)),ve=l.useMemo(()=>new Set(ke),[ke]),De=Vn(N=>N.toggle),[xe,ze]=l.useState(()=>{try{const N=on().getItem(Ua);if(!N)return new Set;const Z=JSON.parse(N);return new Set(Array.isArray(Z)?Z.filter(ee=>typeof ee=="string"):[])}catch{return new Set}}),[X,oe]=l.useState(()=>{try{const N=on().getItem(za);if(!N)return new Map;const Z=JSON.parse(N),ee=new Map;return Object.entries(Z).forEach(([Fe,He])=>{Array.isArray(He)&&ee.set(Fe,He.filter(nt=>typeof nt=="string"))}),ee}catch{return new Map}}),te=l.useMemo(()=>{try{const N=on().getItem($a);if(!N)return new Map;const Z=JSON.parse(N),ee=new Map;return Object.entries(Z).forEach(([Fe,He])=>{typeof He=="string"&&He.length>0&&ee.set(Fe,He)}),ee}catch{return new Map}},[]),fe=l.useCallback(N=>{try{j.setItem($a,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[j]),[he,_e]=l.useState(new Map),je=l.useRef(0),V=mn(N=>N.homeDirectory),we=mn(N=>N.currentDirectory),ue=ut(N=>N.projects),Se=ut(N=>N.activeProjectId),Ye=ut(N=>N.removeProject),Ue=ut(N=>N.setActiveProjectIdOnly),U=ut(N=>N.updateProjectMeta),pe=ut(N=>N.reorderProjects),se=de(N=>N.setActiveMainTab),Le=de(N=>N.setSettingsDialogOpen),ht=de(N=>N.setSettingsPage),ct=de(N=>N.toggleHelpDialog),Qe=de(N=>N.setSessionSwitcherOpen),Dt=de(N=>N.setArchivePageOpen),Xe=de(N=>N.showDeletionDialog),Jt=de(N=>N.setShowDeletionDialog),wt=de(N=>N.sidebarViewMode),tt=i||a||!eh(wt)?"workspace":wt,Rt=de(N=>N.weekStartPreference),Bt=Zf(de(N=>N.sidebarAutoSettleAfterDays)),Pt=l.useMemo(()=>xm(Rt),[Rt]),Tt=Sm(e&&tt==="timeline",Pt),cs=Ba(N=>N.stickyZoneHeaders),ds=rf(u,120),rt=l.useMemo(()=>ds.trim().toLowerCase(),[ds]),pt=rt.length>0,_t=yt(N=>N.collapsedFolderIds),Xt=yt(N=>N.foldersMap),us=yt(N=>N.getFoldersForScope),Ce=yt(N=>N.createFolder),Oe=yt(N=>N.renameFolder),Ie=yt(N=>N.deleteFolder),Be=yt(N=>N.addSessionToFolder),qe=yt(N=>N.addSessionsToFolder),mt=yt(N=>N.removeSessionFromFolder),st=yt(N=>N.removeSessionsFromFolders),Ze=yt(N=>N.toggleFolderCollapse),xs=yt(N=>N.getSessionFolderId);Tm({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:m});const Zt=of(e),{git:Ve}=Gs(),vt=Un(N=>N.connection,void 0,"chrome"),zt=Un(N=>{for(const Z of N.catalog.listStatusByDirectory.values())if(Z==="ready")return!0;return!1},void 0,"catalog"),kt=Fo({archived:!1}),Ct=Fo({archived:!0}),Es=Me(N=>N.setCurrentSession),Hs=Me(N=>N.updateSessionTitle),ys=Me(N=>N.shareSession),Ds=Me(N=>N.unshareSession),gt=Bo(N=>N.projects),Mt=Bo(N=>N.refreshProject),St=l.useMemo(()=>af(ue,{projects:gt}),[ue,gt]),es=l.useMemo(()=>{const N=new Map;for(const Z of ue){const ee=Ee(Z.path);if(!ee)continue;const Fe=gt.get(ee)?.error;Fe&&N.set(ee,Fe)}return N},[ue,gt]);l.useEffect(()=>{if(!v)return;const N=ue.find(ee=>ee.id===v);if(!N){Xs.getState().clearSpaceSelection();return}if(!I)return;(St.get(Ee(N.path)??N.path)??[]).some(ee=>Ee(ee.path)===Ee(I))||(Xs.getState().clearSelectedWorktree(),ie.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[St,ue,v,I]);const ts=Me(N=>N.openNewSessionDraft),at=l.useCallback(N=>{de.getState().closeMainSurfaces(),ts(N),r?.()},[r,ts]),At=xr(Po(N=>({checkForUpdates:N.checkForUpdates,available:N.available,runtimeType:N.runtimeType,info:N.info,downloading:N.downloading,downloaded:N.downloaded,progress:N.progress,error:N.error,downloadUpdate:N.downloadUpdate,restartToUpdate:N.restartToUpdate}))),Rs=l.useMemo(()=>lf(ue,St,{includeWorktrees:!0}),[St,ue]),Ft=l.useMemo(()=>kt.filter(N=>qm(N,Rs,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:V})),[kt,V,Rs]),kn=l.useMemo(()=>[...Ft,...Ct],[Ct,Ft]),qs=lt(),Cn=l.useMemo(()=>`${qs}|${ue.map(N=>`${N.id}:${Ee(N.path)??""}`).join("|")}`,[ue,qs]),Ps=l.useMemo(()=>{const N=new Set;let Z=!0;for(const ee of ue){const Fe=Ee(ee.path);if(!Fe)continue;const He=gt.get(Fe)?.status??"idle";He==="failed"&&N.add(Fe),(He==="idle"||He==="loading")&&(Z=!1)}return{complete:Z,unresolved:N}},[ue,gt]),O=Ps.complete?Cn:null,ce=!Ps.complete,ye=Ps.unresolved,{isTablet:$e}=bn(),it=t||$e,Je=Pm({mobileVariant:t,isTablet:$e}),{buildGroupSearchText:ss,filterSessionNodesForSearch:Nt,buildGroupedSessions:An}=Rm({homeDirectory:V,pinnedSessionIds:Q,sessionOrderRanks:ne}),{scheduleCollapsedProjectsPersist:nr}=Fm({safeStorage:j,keys:{sessionExpanded:Ka,projectCollapse:_a,groupOrder:za,groupCollapse:Ua},groupOrderByProject:X,collapsedGroups:xe,setExpandedParents:A,setCollapsedProjects:w}),re=l.useMemo(()=>cf(Ft,Q,ne),[Q,ne,Ft]),It=l.useMemo(()=>re.map(N=>N.id).join("|"),[re]),Ts=l.useRef(null),Ys=l.useMemo(()=>{const N=Ts.current;if(N&&N.signature===It)return N.map;const Z=new Map(re.map((ee,Fe)=>[ee.id,Fe]));return Ts.current={signature:It,map:Z},Z},[re,It]),rr=l.useMemo(()=>{const N=new Map;re.forEach(ee=>{const Fe=ee.parentID;if(!Fe)return;const He=N.get(Fe)??[];He.push(ee),N.set(Fe,He)});const Z=xl(Q,ne);return N.forEach(ee=>ee.sort(Z)),N},[re,Q,ne]),Vs=l.useMemo(()=>s.jsx(qt,{icon:"chat-new",mobileVariant:t,onClick:()=>at(),children:"New session"}),[t,at]),Wc=l.useMemo(()=>ue.find(N=>N.id===g)??null,[ue,g]),Gc=l.useCallback(N=>{g&&U(g,{label:N.label,defaultModel:N.defaultModel??null})},[g,U]),Hc=l.useCallback(()=>{const N=xr.getState();if(N.available&&N.info){B(!0);return}At.checkForUpdates().then(()=>{const{available:Z,error:ee}=xr.getState();if(ee){ie.error("Failed to check for updates",{description:ee});return}if(!Z){ie.success("You are on the latest version");return}B(!0)})},[At]),Qs=df(),Ai=l.useCallback(()=>{if(t&&Qe(!1),r?.(),Qs?.openSettings){Qs.openSettings();return}Le(!0)},[Qs,t,r,Qe,Le]),qc=At.available&&(At.runtimeType==="desktop"||At.runtimeType==="web"),Yc=Me(N=>N.deleteSession),Ni=Me(N=>N.deleteSessions),Vc=Me(N=>N.archiveSession),Ii=Me(N=>N.archiveSessions),Qc=Me(N=>N.unarchiveSession),Jc=Me(N=>N.unarchiveSessions),{copiedSessionId:Xc,handleSessionSelect:Zc,handleSessionDoubleClick:ed,handleSaveEdit:td,handleCancelEdit:sd,handleShareSession:nd,handleCopyShareUrl:rd,handleCopySessionId:od,handleUnshareSession:id,handleDeleteSession:ad,handleRestoreSession:ld,confirmDeleteSession:cd}=Mm({mobileVariant:t,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:se,setSessionSwitcherOpen:Qe,setCurrentSession:Es,updateSessionTitle:Hs,shareSession:ys,unshareSession:Ds,deleteSession:Yc,deleteSessions:Ni,archiveSession:Vc,archiveSessions:Ii,unarchiveSession:Qc,childrenMap:rr,showDeletionDialog:Xe,setDeleteSessionConfirm:le,deleteSessionConfirm:L,setEditingId:p,setEditTitle:S,editingId:y,editTitle:h}),dd=l.useCallback(()=>{if(!H)return;const{scopeKey:N,folderId:Z}=H;Ae(null),Ie(N,Z)},[H,Ie]),Vr=l.useCallback(()=>{zs.requestDirectoryDialog()},[]),ud=l.useCallback(N=>{A(Z=>{const ee=Ch(Z,N);try{j.setItem(Ka,JSON.stringify(Array.from(ee)))}catch{}return ee})},[j]),Ei=l.useCallback((N,Z)=>{if(!N)return null;Z&&_t.has(Z)&&Ze(Z);const ee=Ce(N,"New folder",Z);return F(ee.id),G(ee.name),ee},[_t,Ze,Ce]),Nn=Lt(Zc),fd=Lt(ed),hd=Lt(td),pd=Lt(sd),md=Lt(nd),gd=Lt(rd),bd=Lt(od),xd=Lt(id),yd=Lt(ad),wd=Lt(ld),Qr=Lt(Ei),Di=l.useCallback((N,Z)=>{$(ee=>{const Fe=new Map(ee);return Fe.set(N,Z+7),Fe})},[]),or=l.useCallback(N=>{$(Z=>{if(!Z.has(N))return Z;const ee=new Map(Z);return ee.delete(N),ee})},[]),Ri=l.useCallback(N=>{$(Z=>{let ee=!1;const Fe=new Map(Z),He=`${N}:`;for(const nt of Fe.keys())nt.startsWith(He)&&(Fe.delete(nt),ee=!0);return ee?Fe:Z})},[]),Jr=l.useCallback(N=>{je.current=Date.now()+150,Ri(N),w(Z=>{const ee=new Set(Z);ee.has(N)?ee.delete(N):ee.add(N);try{j.setItem(_a,JSON.stringify(Array.from(ee)))}catch{}return nr(ee),ee})},[Ri,j,nr]),Pi=l.useRef(null);l.useEffect(()=>{const N=Pi.current;Pi.current=Se,tt==="folder"&&(!N||!Se||N===Se||C.has(Se)&&Jr(Se))},[Se,C,tt,Jr]);const ws=l.useMemo(()=>ue.map(N=>({...N,normalizedPath:Ee(N.path)})).filter(N=>!!N.normalizedPath),[ue]),vd=l.useMemo(()=>ws.map(N=>N.normalizedPath),[ws]),Ti=uf(e?vd:go);Um({enabled:e,normalizedProjects:ws,gitRepoStatus:Ti,setProjectRepoStatus:z,setProjectRootBranches:_e});const Mi=l.useMemo(()=>Vm(Ft,ws,St,Ct),[Ct,St,ws,Ft]);Gm({enabled:e,hasAuthoritativeGlobalSessions:zt,sessions:kn});const{getSessionsForProject:Sd,getArchivedSessionsForProject:jd}=$m({ownership:Mi});jm({enabled:e,normalizedProjects:ws,ownership:Mi,hasAuthoritativeGlobalSessions:zt,isWorktreeTopologyLoading:ce,unresolvedWorktreeProjectPaths:ye,foldersMap:Xt,createFolder:Ce,addSessionToFolder:Be});const Fi=l.useRef(!1);Se&&D.has(Se)&&(Fi.current=!!D.get(Se));const kd=Ba(N=>N.showArchivedSessions),Xr=ut(N=>N.manualProjectOrder),Li=l.useRef(new Set),ir=Ah(Li.current,b,"project");Li.current=ir;const Zr={isVisible:e,mobileVariant:t,onSessionSelected:n,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:a,isTablet:$e,catalogSessions:kt,archivedSessions:Ct,projects:ue,activeProjectId:Se,manualProjectOrder:Xr,currentDirectory:we,availableWorktreesByProject:St,pinnedSessionIds:Q,sessionOrderRanks:ne,foldersMap:Xt,collapsedFolderIds:_t,gitBranches:Zt,gitRepoStatus:Ti,updateStore:At,showArchivedSessions:kd,projectRepoStatus:D,projectRootBranches:he,resolvedWorktreeTopologyKey:O,unresolvedWorktreeProjectPaths:ye,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:y,editTitle:h,editingProjectDialogId:g,expandedParents:b,collapsedProjects:C,visibleSessionCountByGroup:W,updateDialogOpen:K,openSidebarMenuKey:R,renamingFolderId:E,renameFolderDraft:q,deleteSessionConfirm:L,deleteFolderConfirm:H,bulkDeleteConfirm:M,collapsedGroups:xe},Oi=l.useRef(null),Bi=Oi.current;if(Bi){let N=!1;for(const Z of Object.keys(Zr))Object.is(Bi[Z],Zr[Z])||(Ht(`ui.session_sidebar.source.${Z}`),N=!0);N||Ht("ui.session_sidebar.source.parent_or_context")}Oi.current=Zr;const Cd=l.useMemo(()=>{const N=new Map(Xr.map((Z,ee)=>[Z,ee]));return[...ws].sort((Z,ee)=>(N.get(Z.id)??1/0)-(N.get(ee.id)??1/0))},[Xr,ws]),{projectSections:Ut,groupSearchDataByGroup:_i,sectionsForRender:Ad,flatSectionsForRender:eo,searchMatchCount:Nd}=Cm({normalizedProjects:Cd,getSessionsForProject:Sd,getArchivedSessionsForProject:jd,availableWorktreesByProject:St,projectRepoStatus:D,projectRootBranches:he,lastRepoStatus:Fi.current,buildGroupedSessions:An,hasSessionSearchQuery:pt,normalizedSessionSearchQuery:rt,filterSessionNodesForSearch:Nt,buildGroupSearchText:ss,foldersMap:Xt}),In=l.useMemo(()=>{const N=Ft.filter(ee=>Ur($n(ee),V));if(N.length===0)return null;const Z=An(N,"~",[],null,!1).map(ee=>pt?{...ee,sessions:Nt(ee.sessions,rt)}:ee).filter(ee=>ee.sessions.length>0&&!ee.isArchivedBucket);return Z.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Z}},[An,Nt,pt,V,rt,Ft]),Id=l.useMemo(()=>{if(!pt||!In)return 0;const N=Z=>Z.reduce((ee,Fe)=>ee+1+N(Fe.children),0);return In.groups.reduce((Z,ee)=>Z+N(ee.sessions),0)},[In,pt]),Ed=l.useMemo(()=>s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),s.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Dd}=km(X),zi=l.useRef(!1);l.useEffect(()=>{if(zi.current||Ut.length===0)return;const N=Ut.flatMap(Z=>Z.groups.filter(ee=>ee.isArchivedBucket).map(ee=>`${Z.project.id}:${ee.id}`));N.length>0&&ze(Z=>new Set([...Z,...N])),zi.current=!0},[Ut]);const{sectionsForSidebarRender:Rd,filteredSectionsForSidebarRender:Pd,totalSessionCount:Td,sessionCountByProject:Md,hasActiveSessionByProject:Fd,activeDirectoriesByProject:En,hasUnseenByProject:Ld}=ox({projectSections:Ut,flatSectionsForRender:eo,sectionsForRender:Ad,selectedSpaceId:v,selectedWorktreePath:I,homeDirectory:V,activeSessionIdSet:ge,unreadSessionIdSet:ve}),to=l.useCallback(N=>{if(Xs.getState().selectSpace(N),!N)return;Ue(N);const Z=Ut.find(He=>He.project.id===N),ee=Z?.groups.find(He=>He.isMain),Fe=ee?.sessions[0]?.session;Fe?Nn(Fe.id,ee?.directory??Z?.project.normalizedPath??null,{keepPanelOpen:!0}):Z&&at({selectedProjectId:N,directoryOverride:Z.project.normalizedPath})},[at,Ut,Ue,Nn]),Od=t?"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",Bd=t?"size-5":"size-4",ar=Lt((N,Z=0,ee,Fe,He=!1,nt,ns="project",Js)=>s.jsx(Kb,{node:N,depth:Z,groupDirectory:ee,projectId:Fe,archivedBucket:He,pinnedSessionIds:Q,expandedParents:ir,hasSessionSearchQuery:pt,normalizedSessionSearchQuery:rt,editingId:y,setEditingId:p,editTitle:h,setEditTitle:S,handleSaveEdit:hd,handleCancelEdit:pd,toggleParent:ud,handleSessionSelect:Nn,handleSessionDoubleClick:fd,togglePinnedSession:De,handleShareSession:md,copiedSessionId:Xc,handleCopyShareUrl:gd,handleCopySessionId:bd,handleUnshareSession:xd,openSidebarMenuKey:R,setOpenSidebarMenuKey:T,renamingFolderId:E,getFoldersForScope:us,getSessionFolderId:xs,removeSessionFromFolder:mt,addSessionToFolder:Be,createFolderAndStartRename:Qr,handleDeleteSession:yd,handleRestoreSession:wd,mobileVariant:t,alwaysShowActions:it,allowQuickArchiveAction:Je,renderSessionNode:ar,secondaryMeta:nt,renderContext:ns,subtreeContainsEditing:Js?.subtreeContainsEditing??cx,menuOpenSessionId:Js?.menuOpenSessionId??null,nodeStructureKey:Js?.nodeStructureKey??"",childRenderExtrasFor:Js?.childRenderExtrasFor})),_d=l.useMemo(()=>{const N=new Map;return eo.forEach(Z=>{const ee=Z.groups.find(Fe=>!Fe.isArchivedBucket);ee?.folderScopes&&ee.folderScopes.length>0&&N.set(Z.project.id,ee.folderScopes)}),N},[eo]),zd=l.useCallback((N,Z)=>{const ee=[];return Z.forEach(Fe=>{Fe.isArchivedBucket||(ee.push(Fe.directory),Fe.folderScopes?.forEach(He=>ee.push(He.directory)))}),s.jsx(Qb,{directories:ee})},[]),Ui=l.useCallback(N=>{or(N),ze(Z=>{const ee=new Set(Z);return ee.has(N)?ee.delete(N):ee.add(N),ee})},[or]),Ud=l.useCallback((N,Z,ee,Fe,He,nt,ns)=>s.jsx(_g,{group:N,groupKey:Z,projectId:ee,hideGroupLabel:Fe,dragHandleProps:He,compactBodyPadding:nt,hasSessionSearchQuery:pt,normalizedSessionSearchQuery:rt,groupSearchDataByGroup:_i,visibleSessionCount:W.get(Z),collapsedGroups:xe,hideDirectoryControls:i,collapsedFolderIds:_t,toggleFolderCollapse:Ze,renameFolder:Oe,deleteFolder:Ie,showDeletionDialog:Xe,setDeleteFolderConfirm:Ae,renderSessionNode:ar,showMoreGroupSessions:Di,resetGroupSessionLimit:or,mobileVariant:t,alwaysShowActions:it,activeProjectId:Se,setActiveProjectIdOnly:Ue,setActiveMainTab:se,setSessionSwitcherOpen:Qe,openNewSessionDraft:at,addSessionToFolder:Be,createFolderAndStartRename:Qr,renamingFolderId:E,renameFolderDraft:q,setRenameFolderDraft:G,setRenamingFolderId:F,pinnedSessionIds:Q,expandedParents:ir,sessionOrderIndex:Ys,editingId:y,editTitle:h,openSidebarMenuKey:R,activeActivitySessionIds:ge,unreadActivitySessionIds:ve,onToggleCollapsedGroup:Ui,scrollContainerRef:ns}),[pt,rt,_i,W,xe,i,_t,Ze,Oe,Ie,Xe,ar,Di,or,t,it,Se,Ue,se,Qe,at,Be,Qr,E,q,Q,ir,Ys,y,h,R,ge,ve,Ui]),$i=!!(E||y||g),{selectionModeEnabled:so,hasSelection:Ki,selectedIdsSize:$d,bulkScopeIsArchived:Kd,derivedSelectionScope:Wd,bulkScopeFolders:Gd,bulkCanRemoveFromFolder:Hd,handleToggleSelectionMode:qd,handleExitSelectionMode:Yd,handleBulkMoveToFolder:Vd,handleBulkCreateFolderAndMove:Qd,handleBulkRemoveFromFolder:Jd,handleBulkDelete:Xd,handleBulkRestore:Zd,confirmBulkDelete:eu}=ax({isInlineEditing:$i,showDeletionDialog:Xe,foldersMap:Xt,folderScopesByProject:_d,addSessionsToFolder:qe,removeSessionsFromFolders:st,createFolderAndStartRename:Ei,archiveSessions:Ii,unarchiveSessions:Jc,deleteSessions:Ni,setBulkDeleteConfirm:Y}),Wi=l.useCallback(()=>{de.getState().closeMainSurfaces(),se("chat"),t&&Qe(!1),ts(),r?.()},[t,r,ts,se,Qe]),tu=l.useCallback((N,Z)=>{const ee=ue.find(nt=>nt.id===N);if(!ee)return;const Fe=Ee(Z.path)?.toLowerCase(),He=!!(Fe&&En.get(N)?.has(Fe));J({projectId:N,projectPath:ee.path,worktree:Z,hasActiveSession:He})},[En,ue]),su=l.useCallback(async({force:N})=>{const Z=Pe;if(!Z)return;const ee=Ee(Z.worktree.path)?.toLowerCase();if(!!(ee&&En.get(Z.projectId)?.has(ee))){J({...Z,hasActiveSession:!0}),ie.warning("Stop the active session before closing this worktree.");return}if(!Ve.deleteGitWorktree){ie.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Ve.deleteGitWorktree(Z.projectPath,{directory:Z.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let nt=await Mt(Z.projectPath,Ve,{force:!0});const ns=Ee(Z.worktree.path);nt!==null&&ns!==null&&nt.some(ru=>Ee(ru.path)===ns)&&(nt=await Mt(Z.projectPath,Ve,{force:!0}));const Js=ns!==null&&Ee(we)===ns,nu=ns!==null&&v===Z.projectId&&Ee(I)===ns;(Js||nu)&&to(Z.projectId),J(null),nt===null?ie.warning("Worktree closed, but the sidebar could not be refreshed."):ie.success("Worktree closed.")}catch(He){const nt=He instanceof Error?He.message:"Try again.";ie.error("Failed to close worktree.",{description:nt})}},[En,Pe,we,Ve,to,Mt,v,I]);return s.jsx(ff,{delay:400,closeDelay:150,timeout:600,children:s.jsxs("div",{ref:m,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(Nm,{projectSections:Ut,activeProjectId:Se,initialActiveSessionByProject:te,persistActiveSessionByProject:fe,handleSessionSelect:Nn,mobileVariant:t,openNewSessionDraft:ts,setActiveMainTab:se,setSessionSwitcherOpen:Qe}),!i&&!t?s.jsx(Ug,{onNewSession:Wi,showSidebarToggle:!0}):null,s.jsx(zg,{hideDirectoryControls:i,handleOpenDirectoryDialog:Vr,onOpenArchive:()=>{t&&Qe(!1),Dt(!0)},onOpenSettings:t?Ai:void 0,onOpenInstances:t?Qs?.openInstances:void 0,instanceLabel:t?Qs?.instanceLabel:void 0,onOpenUpdate:t?Qs?.openUpdate:void 0,headerActionIconClass:Bd,headerActionButtonClass:Od,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:pt,searchMatchCount:Nd+(tt!=="workspace"||v===null?Id:0),selectionModeEnabled:so,onToggleSelectionMode:qd,mobileVariant:t,onClose:t?()=>Qe(!1):void 0}),vt==="error"||vt==="unavailable"?s.jsx("div",{role:"alert",className:"mx-2 mb-2 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-2 text-xs text-foreground",children:"Unable to reach server"}):null,!i&&Ut.length>0&&tt==="workspace"?s.jsx(Wg,{projects:Ut.map(N=>N.project),selectedProjectId:v,selectedWorktreePath:I,worktreesByProject:St,worktreeErrorsByProject:es,onSelectProject:to,onSelectWorktree:(N,Z)=>{Xs.getState().selectWorktree(N,Z),Ue(N);const He=Ut.find(nt=>nt.project.id===N)?.groups.find(nt=>Ee(nt.directory)===Ee(Z))?.sessions[0]?.session;He?Nn(He.id,Z,{keepPanelOpen:!0}):at({selectedProjectId:N,directoryOverride:Z})},onCloseWorktree:tu,onOpenDirectoryDialog:Vr,onOpenProjectEditDialog:k,onRemoveProject:Ye,totalSessionCount:Td,getSessionCountForProject:N=>Md.get(N)??0,hasActiveSessionByProject:Fd,activeDirectoriesByProject:En,hasUnseenByProject:Ld,homeDirectory:V,mobileVariant:t}):null,s.jsx(hb,{viewMode:tt,timelineBoundaries:Tt,onOpenDirectoryDialog:Vr,stickyFolderHeaders:cs,sectionsForRender:tt==="workspace"?Pd:Rd,allFoldersOnlySection:tt==="workspace"?v===null?In:null:In,isAllFoldersView:tt==="workspace"?v===null:tt==="timeline",projectSections:Ut,activeProjectId:Se,showOnlyMainWorkspace:a,hasSessionSearchQuery:pt,emptyState:Vs,searchEmptyState:Ed,pinnedSessionIds:Q,autoSettleAfterDays:Bt,renderSessionNode:ar,renderGroupSessions:Ud,homeDirectory:V,collapsedProjects:C,hideDirectoryControls:i,projectRepoStatus:D,mobileVariant:t,alwaysShowActions:it,toggleProject:Jr,setActiveProjectIdOnly:Ue,setActiveMainTab:se,setSessionSwitcherOpen:Qe,openNewSessionDraft:at,openProjectEditDialog:k,removeProject:Ye,reorderProjects:pe,getOrderedGroups:Dd,setGroupOrderByProject:oe,renderProjectStatusIndicator:zd,openSidebarMenuKey:R,setOpenSidebarMenuKey:T,isInlineEditing:$i}),t&&!(so&&Ki)?s.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-2",children:[s.jsx(oc,{variant:"mobile"}),s.jsxs(Ne,{type:"button",variant:"default",size:"lg",className:"w-full",onClick:Wi,children:[s.jsx(P,{name:"chat-new",className:"size-4"}),"New session"]})]}):null,so&&Ki?s.jsx(ix,{selectedCount:$d,scopeKey:Wd,scopeFolders:Gd,archivedBucket:Kd,onMoveToFolder:Vd,onCreateFolderAndMove:Qd,onRemoveFromFolder:Jd,canRemoveFromFolder:Hd,onRestore:Zd,onDelete:Xd,onDone:Yd}):null,t?null:s.jsx(Gg,{onOpenSettings:Ai,onOpenShortcuts:ct,onOpenAbout:()=>{ht("about"),Le(!0)},onOpenUpdate:Hc,showRuntimeButtons:!0,showUpdateButton:qc}),s.jsx(Vb,{updateDialogOpen:K,setUpdateDialogOpen:B,updateStore:At,editingProject:Wc,setEditingProjectDialogId:k,handleSaveProjectEdit:Gc,deleteSessionConfirm:L,setDeleteSessionConfirm:le,showDeletionDialog:Xe,setShowDeletionDialog:Jt,confirmDeleteSession:cd,deleteFolderConfirm:H,setDeleteFolderConfirm:Ae,confirmDeleteFolder:dd,closeWorktreeConfirm:Pe,setCloseWorktreeConfirm:J,confirmCloseWorktree:su,bulkDeleteConfirm:M,setBulkDeleteConfirm:Y,confirmBulkDelete:eu})]})})},dv=l.memo(dx),Wa=6,Ot=.18,On=1.2,Bn=.38,Cr=48,ux=(e,t)=>e==="left"?t<0:t>0,uv=(e,t,n)=>Math.min(1,Math.max(0,e==="left"?1+t/n:1-t/n)),fv=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,Ga=(e,t,n,r)=>e==="left"?t?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):t?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),hv=e=>{const{side:t,dx:n,dy:r,dt:o,progress:i,isDragging:a}=e,c=n/Math.max(1,o);if(a){const d=t==="left"?c<-Ot:c>Ot,u=t==="left"?c>Ot:c<-Ot;return d||!u&&i<Bn}return Math.abs(n)>=Cr&&Math.abs(r)<=Math.abs(n)*On&&ux(t,n)},fx=e=>{const{side:t,isOpenAtStart:n,dx:r,dt:o,progress:i}=e,a=r/Math.max(1,o);return t==="left"?n?a<-Ot?!1:a>Ot?!0:i>Bn:a>Ot?!0:a<-Ot?!1:i>Bn:n?a>Ot?!1:a<-Ot?!0:i>Bn:a<-Ot?!0:a>Ot?!1:i>Bn},hx='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',px=(e,t,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const i=e.closest(hx);if(i&&t.contains(i))return!0}else{const i=e.closest("[data-no-drawer-swipe]");if(i&&t.contains(i))return!0}let o=e;for(;o&&o!==t;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const i=getComputedStyle(o).overflowX;if(i==="auto"||i==="scroll")return!0}o=o.parentElement}return!1},Ar=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),fi=512*1024,mx=new TextEncoder,gx=new TextDecoder,bo=e=>{const t=mx.encode(e);if(t.byteLength<=fi)return{text:e,byteLength:t.byteLength};let n=t.byteLength-fi;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:gx.decode(r),byteLength:r.byteLength}},en=(e,t)=>`${e}\0${t}`,xo=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},bx="terminal-store";let Ha=!1,qa=0;const br=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(qa+=1,`tab-${Date.now().toString(36)}-${qa.toString(36)}`),yo=e=>typeof e=="object"&&e!==null,xx=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null};function dt(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const yx=/^Terminal(?: (\d+))?$/,wx=e=>{let t=0;for(const n of e){const r=yx.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},wo=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),vo=e=>({tabs:[e],activeTabId:e.id}),Kt=(e,t)=>e.tabs.findIndex(n=>n.id===t);let So=null,jo=null;const vx=e=>{if(jo&&So?.sessions===e.sessions&&So.nextTabId===e.nextTabId)return jo;const t={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 So={sessions:e.sessions,nextTabId:e.nextTabId},jo=t,t},Sx=()=>{const e=Nh(()=>th());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},be=Is()($r(zl((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=dt(n);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),a=br(),c=wo(a,"Terminal");return i.set(r,vo(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=dt(n);return t().sessions.get(r)},getActiveTab:n=>{const r=dt(n),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(a=>a.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(en(dt(n),r))??Ar,createTab:n=>{const r=dt(n);if(!r)return"tab-invalid";const o=br();return e(i=>{const a=new Map(i.sessions),c=a.get(r),d=i.nextTabId+1,u=wx(c?.tabs??[]),f=wo(o,u);return c?a.set(r,{...c,tabs:[...c.tabs,f]}):a.set(r,vo(f)),{sessions:a,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=dt(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);return!c||c.activeTabId===r||Kt(c,r)<0?i:(a.set(o,{...c,activeTabId:r}),{sessions:a})})},setTabLabel:(n,r,o)=>{const i=dt(n),a=o.trim();a&&e(c=>{const d=new Map(c.sessions),u=d.get(i);if(!u)return c;const f=Kt(u,r);if(f<0||u.tabs[f]?.label===a)return c;const m=[...u.tabs];return m[f]={...m[f],label:a},d.set(i,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const i=dt(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Kt(d,r);if(u<0)return a;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return a;const m=[...d.tabs];return m[u]={...m[u],iconKey:f},c.set(i,{...d,tabs:m}),{sessions:c}})},closeTab:(n,r)=>{const o=dt(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=Kt(c,r);if(d<0)return i;const u=c.tabs.filter(h=>h.id!==r),f=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,h])=>!(h.directory===o&&h.tabId===r))),m=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,x=en(o,r),y=i.buffers.has(x)?xo(i.buffers,h=>h===x):null;if(u.length===0){const h=br(),S=wo(h,"Terminal");return a.set(o,vo(S)),{sessions:a,nextTabId:i.nextTabId+1,...y?{buffers:y}:{},...m?{projectActionRuns:f}:{}}}let p=c.activeTabId;return c.activeTabId===r&&(p=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),a.set(o,{...c,tabs:u,activeTabId:p}),{sessions:a,...y?{buffers:y}:{},...m?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const i=dt(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Kt(d,r);if(u<0)return a;const f=d.tabs[u],m=o!==null&&f.terminalSessionId!==o,x=o?"running":f.terminalSessionId?"exited":f.lifecycle,y={...f,terminalSessionId:o,lifecycle:x,isConnecting:!1},p=en(i,r),h=m&&a.buffers.has(p)?xo(a.buffers,g=>g===p):null,S=[...d.tabs];return S[u]=y,c.set(i,{...d,tabs:S}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(n,r,o)=>{const i=dt(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Kt(d,r);if(u<0)return a;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(i,{...d,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const i=dt(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=Kt(d,r);if(u<0)return a;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(i,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,i)=>{const a=dt(n);e(c=>{const d=c.sessions.get(a);if(!d||Kt(d,r)<0)return c;const u=en(a,r),f=c.buffers.get(u)??Ar;if(f.lastSequence>i)return c;const m=bo(o);if(f.lastSequence===i&&f.byteLength===m.byteLength&&f.chunks.map(p=>p.data).join("")===m.text)return c;const x=c.nextChunkId,y=new Map(c.buffers);return y.set(u,{chunks:m.text?[{id:x,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:i}),{buffers:y,nextChunkId:m.text?x+1:x}})},appendToBuffer:(n,r,o,i,a)=>{if(!o)return;const c=dt(n);e(d=>{const u=d.sessions.get(c);if(!u||Kt(u,r)<0)return d;const f=en(c,r),m=d.buffers.get(f)??Ar;if(i!==void 0&&i<=m.lastSequence)return d;const x=d.nextChunkId,y=bo(o),p=a!==void 0&&a!==o?bo(a).text:void 0,h={id:x,data:y.text,...p!==void 0?{replayData:p}:{},byteLength:y.byteLength},S=[...m.chunks,h];let g=m.byteLength+h.byteLength;for(;g>fi&&S.length>1;){const b=S.shift();if(!b)break;g-=b.byteLength}const k=new Map(d.buffers);return k.set(f,{chunks:S,byteLength:g,lastSequence:i??m.lastSequence}),{buffers:k,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,o,i={})=>{const a=dt(n);e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=Kt(u,r);if(f<0)return c;const m=u.tabs[f],x=i.autoOpened??m.previewAutoOpened,y=i.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===x&&m.previewUrlLocked===y)return c;const p=[...u.tabs];return p[f]={...m,previewUrl:o,previewAutoOpened:x,previewUrlLocked:y},d.set(a,{...u,tabs:p}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=dt(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=Kt(c,r);if(d<0)return i;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return i;const f=[...c.tabs];return f[d]={...u,previewAutoOpened:!0},a.set(o,{...c,tabs:f}),{sessions:a}})},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 i=o.projectActionRuns[n];return!i||i.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...i,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=dt(n);e(o=>{const i=new Map(o.sessions);i.delete(r);const a=en(r,""),c=xo(o.buffers,u=>u.startsWith(a)),d=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:i,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:bx,storage:Sx(),partialize:vx,merge:(e,t)=>{if(!yo(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!yo(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],m=[],x=new Map;for(const S of f){if(!yo(S))continue;const g=typeof S.id=="string"?S.id:null;if(!g)continue;const k=xx(g);k!==null&&(o=Math.max(o,k));const b=k===null?g:br();x.set(g,b),m.push({id:b,label:typeof S.label=="string"?S.label:"Terminal",iconKey:typeof S.iconKey=="string"?S.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof S.createdAt=="number"?S.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const y=typeof u.activeTabId=="string"?u.activeTabId:null,p=y?x.get(y)??y:null,h=p?m.some(S=>S.id===p):!1;r.set(d,{tabs:m,activeTabId:h?p:m[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,a=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:a,hasHydrated:!0}}})));if(typeof window<"u"&&!Ha){Ha=!0;const e=be.persist,t=()=>{be.getState().hasHydrated||be.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}function jx(e){const{colors:t}=e,n=t.syntax.base;return{background:t.surface.background,foreground:n.foreground,cursor:t.interactive.cursor,cursorAccent:t.surface.background,selectionBackground:t.interactive.selection,selectionForeground:t.interactive.selectionForeground,selectionInactiveBackground:t.interactive.selection+"50",black:t.surface.muted,red:t.status.error,green:t.status.success,yellow:t.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:t.status.error,brightGreen:t.status.success,brightYellow:t.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:t.surface.elevatedForeground}}function ko(e,t,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:t,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 kx=(e,t)=>{const n=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},Cx=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),Ax=(e,t,n)=>{if(e.altKey)return null;const r=Cx(e);return t==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?n?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?n?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?n?"copy":"ignore":null},_n=e=>typeof e=="string"&&e.trim().length>0;async function Ya(e){return _n(e)?(await ps(e)).ok:!1}async function Nx(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const Ix=(e,t,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const i=Math.floor((e-n.left)/n.width*r),a=Math.floor((t-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,i)),row:Math.max(0,Math.min(o-1,a))}},Ex=(e,t)=>{const n=Math.max(0,Math.min(e.length-1,t)),r=a=>!!(a&&!/^\s+$/u.test(a));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,i=n;for(;o>0&&r(e[o-1]);)o-=1;for(;i<e.length-1&&r(e[i+1]);)i+=1;return{startColumn:o,endColumn:i}};let Dx=null;const Rx=()=>Dx??=Promise.all([xt(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),xt(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),Px=2e3,Tx=()=>{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(t=>setTimeout(t,Px))]).then(()=>{})},Mx=(e,t,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 ${t}`;const o=r.measureText("M"),i=Math.ceil(o.width),a=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(i<1||a<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/i)),rows:Math.max(1,Math.floor((e.clientHeight-u)/a))}},zc=l.forwardRef(({sessionKey:e,chunks:t,onInput:n,onResize:r,theme:o,fontFamily:i,fontSize:a,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},m)=>{const x=l.useRef(null),y=l.useRef(null),p=l.useRef(null),h=l.useRef(n),S=l.useRef(r),g=l.useRef(o),k=l.useRef(i),b=l.useRef(a),A=l.useRef(null),j=l.useRef(null),C=l.useRef(null),w=l.useRef(""),v=l.useRef(!1),I=l.useRef(0),D=l.useRef(f),z=l.useRef(!1),[W,$]=l.useState(0),[K,B]=l.useState(0),[R,T]=l.useState(!1),[E,F]=l.useState(!1);h.current=n,S.current=r,D.current=f,g.current=o,k.current=i,b.current=a,l.useLayoutEffect(()=>{const J=x.current;if(!J)return;const M=Mx(J,i,a);j.current=M,M&&S.current(M.cols,M.rows)},[i,a]);const q=l.useCallback(()=>{const J=x.current,M=y.current;if(!J||!M||!p.current||!D.current)return;const Y=J.getBoundingClientRect();if(!(Y.width<24||Y.height<24))try{p.current.fit();const Q={cols:M.cols,rows:M.rows};(!A.current||A.current.cols!==Q.cols||A.current.rows!==Q.rows)&&(A.current=Q,S.current(Q.cols,Q.rows)),z.current||(z.current=!0,$(ne=>ne+1))}catch{}},[]),G=l.useCallback(()=>{if(v.current||!w.current||!y.current)return;const J=y.current,M=w.current;if(w.current="",!M)return;v.current=!0;const Y=I.current;J.write(M,()=>{y.current!==J||I.current!==Y||(v.current=!1,w.current&&G())})},[]),L=l.useCallback(()=>{C.current=null,w.current="",v.current=!1,I.current+=1;const J=y.current;if(!J){B(M=>M+1);return}try{J.reset()}catch{B(M=>M+1)}},[]),le=l.useCallback(J=>{J?.preventDefault(),F(_n(y.current?.getSelection())),T(!0)},[]),H=l.useCallback(J=>{J.stopPropagation();const M=y.current,Y=M?.getSelection()??"";M?.focus(),_n(Y)&&Ya(Y)},[]),Ae=l.useCallback(J=>{J.stopPropagation();const M=y.current;M?.focus(),Nx().then(Y=>{Y&&y.current===M&&M&&M.paste(Y)})},[]),Pe=l.useCallback(J=>{J.stopPropagation();const M=y.current;M?.focus();try{M?.selectAll()}catch{}F(_n(M?.getSelection()))},[]);return l.useEffect(()=>{const J=x.current;if(!J)return;let M=!1,Y=null,Q=null,ne=null,ae=null,me=[];const ge=()=>{Y&&D.current&&(Y.options.cursorBlink=!0)},ke=xe=>{xe.relatedTarget instanceof Node&&J.contains(xe.relatedTarget)||Y&&(Y.options.cursorBlink=!1)},ve=()=>{Y&&D.current&&J.contains(document.activeElement)&&(Y.options.cursorBlink=!0)},De=()=>{Y&&(Y.options.cursorBlink=!1)};return J.addEventListener("focusin",ge),J.addEventListener("focusout",ke),window.addEventListener("focus",ve),window.addEventListener("blur",De),Promise.all([Rx(),Tx()]).then(([{Xterm:xe,Fit:ze}])=>{if(M)return;const X=g.current,oe=k.current,te=b.current;Y=new xe.Terminal({...ko(oe,te,X),...j.current??{}});const fe=new ze.FitAddon;Y.loadAddon(fe),Y.open(J),y.current=Y,p.current=fe;const he=typeof navigator>"u"?"other":kx(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),_e=Y;Y.attachCustomKeyEventHandler(je=>{if(je.type!=="keydown")return!0;const V=_e.getSelection(),we=Ax({key:je.key,code:je.code,ctrlKey:je.ctrlKey,shiftKey:je.shiftKey,metaKey:je.metaKey,altKey:je.altKey},he,_n(V));return we==="copy"?(Ya(V),!1):we!=="ignore"}),me=[Y.onData(je=>h.current(je))],Q=new ResizeObserver(()=>{ne&&clearTimeout(ne),ne=setTimeout(q,80)}),Q.observe(J),q(),ae=requestAnimationFrame(q)}),()=>{M=!0;const xe=document.activeElement;xe instanceof HTMLElement&&J.contains(xe)&&(xe.blur(),window.Capacitor?.getPlatform?.()==="android"&&xt(async()=>{const{Keyboard:X}=await import("./vendor-capacitor-keyboard-DO8AIjrZ.js");return{Keyboard:X}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:X})=>X.hide()).catch(()=>{})),Q?.disconnect(),ne&&clearTimeout(ne),ae!==null&&cancelAnimationFrame(ae),J.removeEventListener("focusin",ge),J.removeEventListener("focusout",ke),window.removeEventListener("focus",ve),window.removeEventListener("blur",De),me.forEach(ze=>ze.dispose()),Y?.dispose(),y.current=null,p.current=null,A.current=null,C.current=null,w.current="",v.current=!1,I.current+=1,z.current=!1}},[q,K]),l.useEffect(()=>{const J=y.current;J&&(J.options.theme=ko(i,a,o).theme,J.options.fontFamily=ko(i,a,o).fontFamily,J.options.fontSize=a)},[i,a,o]),l.useEffect(()=>{const J=y.current,M=x.current;!J||!M||(J.options.cursorBlink=f&&document.hasFocus()&&M.contains(document.activeElement))},[f,W]),l.useEffect(()=>{if(!y.current)return;if(t.length===0){C.current!==null&&L();return}const M=C.current;let Y=-1;if(M!==null){for(let ae=t.length-1;ae>=0;ae-=1){const me=t[ae].id;if(me===M){Y=ae;break}if(me<M)break}if(Y<0){L();return}}const Q=Y<0,ne=Y>=0?t.slice(Y+1):t;w.current+=ne.map(ae=>Q?ae.replayData??ae.data:ae.data).join(""),C.current=t.at(-1)?.id??null,G()},[t,G,W,L]),l.useEffect(()=>{if(!u||!f)return;const J=requestAnimationFrame(()=>y.current?.focus());return()=>cancelAnimationFrame(J)},[u,f,W,e]),l.useEffect(()=>{const J=x.current,M=y.current;if(!d||!J||!M)return;let Y=null,Q=null,ne="idle",ae=0,me=0,ge=0,ke=0,ve=null;const De=Math.max(12,a+2),xe=()=>{window.Capacitor?.getPlatform?.()==="android"&&xt(async()=>{const{Keyboard:we}=await import("./vendor-capacitor-keyboard-DO8AIjrZ.js");return{Keyboard:we}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:we})=>we.show()).catch(()=>{})},ze=()=>{Q&&(clearTimeout(Q),Q=null)},X=(V,we)=>{const ue=J.querySelector("canvas");return ue?Ix(V,we,ue.getBoundingClientRect(),M.cols,M.rows):null},oe=(V,we)=>{const ue=J.querySelector("canvas");if(!ue)return;const Se=ue.getBoundingClientRect(),Ye=Se.left+(we.column+.5)/M.cols*Se.width,Ue=Se.top+(we.row+.5)/M.rows*Se.height;ue.dispatchEvent(new MouseEvent(V,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:Ye,clientY:Ue}))},te=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},fe=V=>{V.pointerType!=="touch"||Y!==null||(Y=V.pointerId,ne="pending",ae=V.clientX,me=V.clientY,ge=V.clientY,ke=0,ve=null,J.setPointerCapture(V.pointerId),Q=setTimeout(()=>{if(Q=null,Y!==V.pointerId||ne!=="pending")return;const we=X(ae,me);if(!we)return;const ue=M.buffer.active,Se=Math.max(0,ue.length-M.rows-ue.viewportY+we.row),Ye=ue.getLine(Se),Ue=Array.from({length:M.cols},(se,Le)=>Ye?.getCell(Le)?.getChars()??""),U=Ex(Ue,we.column),pe={column:U.startColumn,row:we.row};ve={column:U.endColumn,row:we.row},ne="selecting",oe("mousedown",pe),oe("mousemove",ve)},350))},he=V=>{if(Y!==V.pointerId)return;if(ne==="selecting"){const Se=X(V.clientX,V.clientY);Se&&(!ve||Se.column!==ve.column||Se.row!==ve.row)&&(ve=Se,oe("mousemove",Se)),V.cancelable&&V.preventDefault();return}if(ne==="pending"){if(Math.hypot(V.clientX-ae,V.clientY-me)<8)return;ze(),ne="scrolling"}if(ne!=="scrolling")return;const we=ge-V.clientY;ge=V.clientY,ke+=we;const ue=Math.trunc(ke/De);ue&&(M.scrollLines(ue),ke-=ue*De),V.cancelable&&V.preventDefault()},_e=V=>{if(Y!==V.pointerId)return;const we=ne==="pending",ue=ne==="selecting";ze(),J.hasPointerCapture(V.pointerId)&&J.releasePointerCapture(V.pointerId),Y=null,ne="idle",ue&&te(),we&&(M.focus(),xe())},je=V=>{if(Y!==V.pointerId)return;const we=ne==="selecting";ze(),J.hasPointerCapture(V.pointerId)&&J.releasePointerCapture(V.pointerId),Y=null,ne="idle",we&&te()};return J.addEventListener("pointerdown",fe),J.addEventListener("pointermove",he,{passive:!1}),J.addEventListener("pointerup",_e),J.addEventListener("pointercancel",je),()=>{ze(),J.removeEventListener("pointerdown",fe),J.removeEventListener("pointermove",he),J.removeEventListener("pointerup",_e),J.removeEventListener("pointercancel",je)}},[d,a,W]),l.useImperativeHandle(m,()=>({focus:()=>y.current?.focus(),fit:q,getSelection:()=>{const J=y.current,M=J?.getSelectionPosition(),Y=J?.getSelection()??"";return!M||!Y.trim()?null:{text:Y,startLine:M.start.y+1,endLine:M.end.y+1}}}),[q]),s.jsxs(Hr,{open:R,onOpenChange:T,children:[s.jsx(qr,{render:s.jsx("div",{ref:x,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:le})}),s.jsxs(Yr,{className:"min-w-[180px]",children:[s.jsxs(_s,{disabled:!E,onClick:H,children:[s.jsx(P,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),s.jsxs(_s,{onClick:Ae,children:[s.jsx(P,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),s.jsx(Ac,{}),s.jsx(_s,{onClick:Pe,children:"Select all"})]})]})});zc.displayName="TerminalViewport";const Fx=({directory:e,tabId:t,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:a,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:m,onInput:x,controllerRef:y})=>{const p=be(b=>e&&t?b.getBuffer(e,t).chunks:Ar.chunks),h=l.useRef(null),S=o&&i,g=l.useCallback(b=>{h.current=b,y&&(y.current=o?b:y.current),!o&&y&&y.current===b&&(y.current=null)},[y,o]);l.useEffect(()=>{if(!o||!i)return;const b=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(b)},[o,i,r,n]);const k=l.useCallback((b,A)=>{if(!o)return;const j=m.current;(!j||j.cols!==b||j.rows!==A)&&(m.current={cols:b,rows:A}),n&&a.resize({sessionId:n,cols:b,rows:A}).catch(()=>{})},[o,m,n,a]);return s.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:s.jsx(zc,{ref:g,sessionKey:r,chunks:p,onInput:x,onResize:k,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:S,isVisible:S},r)})},Va=({items:e,activeId:t,onSelect:n,onClose:r,onCreate:o,disabled:i=!1})=>{const a=e.find(c=>c.id===t)??e[0]??null;return s.jsxs(Yt,{modal:!1,children:[s.jsx(Vt,{asChild:!0,children:s.jsxs(Ne,{type:"button",variant:"ghost",size:"sm",disabled:i,title:a?`Switch terminal, current: ${a.label}`:"Switch terminal","aria-label":a?`Switch terminal, current: ${a.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[a?.icon??s.jsx(P,{name:"terminal",className:"size-4 shrink-0"}),s.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:a?.label??"Terminal"}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),s.jsxs(Qt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(a?.id??t);return s.jsxs(ft,{title:c.title??c.label,onClick:()=>n(c.id),className:"group/tab min-w-0",children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),d?s.jsx(P,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,s.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:u=>{u.preventDefault(),u.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:s.jsx(P,{name:"close",className:"size-3"})})]},c.id)}),s.jsx(hn,{}),s.jsxs(ft,{onClick:o,children:[s.jsx(P,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},Lx=({leading:e,icon:t,title:n,actions:r,className:o})=>s.jsxs("header",{className:_("flex h-11 shrink-0 items-center gap-1 border-b border-border bg-background pl-3 pr-2",o),children:[e,n!=null?typeof n=="string"?s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[typeof t=="string"?s.jsx(P,{name:t,className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):t??null,s.jsx("h2",{className:"truncate typography-ui-label font-medium text-foreground",children:n})]}):s.jsx("div",{className:"min-w-0 flex-1",children:n}):null,r?s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:r}):null]}),Ox=({isTouchTerminal:e,activeModifier:t,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",a=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[s.jsx(P,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Tab"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"chip","aria-pressed":t==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,children:[s.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),s.jsx("span",{className:"sr-only",children:"Control modifier"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"chip","aria-pressed":t==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,children:[s.jsx("span",{className:"text-xs font-medium",children:"Alt"}),s.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[s.jsx(P,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:"Arrow up"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[s.jsx(P,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:"Arrow left"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[s.jsx(P,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:"Arrow down"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[s.jsx(P,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:"Arrow right"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[s.jsx(P,{name:"arrow-go-back"}),s.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Bx="\x1B",_x=new RegExp(`${Bx}\\[[0-9;?]*[ -/]*[@-~]`,"g"),zx=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Ux=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,$x=/Serving HTTP on .*? port (\d{2,5})/i,Kx=new Set([".",",",";",":","!","?"]),Wx=e=>{let t=e;for(;t.length>0;){const n=t[t.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=t.slice(0,-1),i=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,a=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(i>a)break;t=o;continue}if(Kx.has(n)){t=t.slice(0,-1);continue}break}return t},Qa=e=>{let t=Wx(e);return t=t.replace("0.0.0.0","127.0.0.1"),t=t.replace("[::1]","127.0.0.1"),t=t.replace("[::]","127.0.0.1"),t},Gx=e=>{if(!e)return null;const t=e.replace(_x,""),n=t.match($x);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=t.split(`
|
|
55
|
+
`);for(const o of r){if(!Ux.test(o))continue;const i=Array.from(o.matchAll(zx));if(i.length===0)continue;const a=i.find(c=>{try{return!!new URL(Qa(c[1])).port}catch{return!1}});return Qa((a??i[0])[1])}return null},Hx=async(e,t=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,i=window.setTimeout(()=>o.abort(),t);try{const a=await ot("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return a.ok?(await a.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},qx={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Yx=(e,t)=>{if(t&&e.startsWith("arrow-")){const n=t==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return qx[e]},Uc=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},Vx=(e,t)=>e&&(t==="ctrl"?Uc(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),$c={cols:80,rows:24},Ja={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class Qx{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(t,n,r,o){if(!r)return;const i=`${this.tail}${r}`.replace(/\r\n|\r/g,`
|
|
56
|
+
`),a=i.split(`
|
|
57
|
+
`),c=i.endsWith(`
|
|
58
|
+
`)?a.join(`
|
|
59
|
+
`):a.slice(0,-1).join(`
|
|
60
|
+
`);if(this.tail=i.endsWith(`
|
|
61
|
+
`)?"":(a[a.length-1]??"").slice(-1024),!c)return;const d=Gx(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Hx(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const m=be.getState().getDirectoryState(t)?.tabs.find(x=>x.id===n);!m||m.previewUrlLocked||m.previewUrl===d||o(t,n,d,{locked:!1,autoOpened:!1})})}}const Jx=(e,t)=>{if(t!=="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"?Uc(o):null};function Xx({terminal:e,effectiveDirectory:t,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:a,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:m,focusTerminalWhenWindowActive:x,tabs:y}){const p=be(M=>M.ensureDirectory),h=be(M=>M.setTabSessionId),S=be(M=>M.setTabLifecycle),g=be(M=>M.setConnecting),k=be(M=>M.appendToBuffer),b=be(M=>M.replaceBuffer),A=be(M=>M.setTabPreviewUrl),[j,C]=l.useState(null),[w,v]=l.useState(!1),[I,D]=l.useState(!1),z=l.useRef(new Map),W=l.useRef(null),$=l.useRef(n),K=l.useRef(r),B=l.useRef(t),R=l.useRef(null),T=l.useRef(new Set),E=l.useRef(new Map),F=l.useRef(y),q=l.useRef(a),G=l.useRef(i),L=l.useRef(e);F.current=y,q.current=a,G.current=i,L.current=e;const le=l.useCallback(()=>{const M=$.current;M&&E.current.get(M)?.reset()},[]);l.useEffect(()=>{K.current=r},[r]),l.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),l.useEffect(()=>{$.current=n},[n]),l.useEffect(()=>{B.current=t},[t]);const H=l.useCallback(()=>{for(const M of z.current.values())try{M()}catch{}z.current.clear(),W.current=null,D(!1)},[]);l.useEffect(()=>()=>{H(),K.current=null},[H]);const Ae=l.useCallback((M,Y,Q)=>{let ne=E.current.get(Y);ne||(ne=new Qx,E.current.set(Y,ne)),ne.scan(M,Y,Q,A)},[A]),Pe=l.useCallback((M,Y,Q)=>{if(z.current.has(Q)){W.current=Q;return}const ne=Zi(),ae=()=>Zi()===ne&&B.current===M&&be.getState().getDirectoryState(M)?.tabs.find(ge=>ge.id===Y)?.terminalSessionId===Q,me=e.connect(Q,{onEvent:ge=>{if(ae())switch(ge.type){case"snapshot":{$.current===Y&&K.current===Q?(g(M,Y,!1),C(null),v(!1),D(!1),x()):g(M,Y,!1),b(M,Y,ge.data??"",ge.sequence??0),Ae(M,Y,ge.data??""),ge.status==="exited"&&S(M,Y,"exited");break}case"reconnecting":{$.current===Y&&(C(null),v(!1),D(!0));break}case"data":{ge.data&&(k(M,Y,ge.data,ge.sequence,ge.replayData),Ae(M,Y,ge.data));break}case"exit":{const ke=typeof ge.exitCode=="number"?ge.exitCode:null,ve=typeof ge.signal=="number"?ge.signal:null,xe=!!be.getState().getDirectoryState(M)?.tabs.find(ze=>ze.id===Y)?.label?.startsWith("Action:");k(M,Y,`\\r\\n[Process exited${ke!==null?` with code ${ke}`:""}${ve!==null?` (signal ${ve})`:""}]\\r\\n`),S(M,Y,"exited"),$.current===Y&&(g(M,Y,!1),C(xe?null:"Terminal session ended"),v(!1),D(!1));break}}},onError:(ge,ke)=>{if(!ae())return;const ve=$.current===Y;if(!ke){ve&&(C(null),v(!1));return}if(ge.code==="SESSION_NOT_FOUND"&&!be.getState().getDirectoryState(M)?.tabs.find(xe=>xe.id===Y)?.label?.startsWith("Action:")){ve&&(C(null),v(!1),g(M,Y,!1),D(!1)),h(M,Y,null),S(M,Y,"idle");return}ve&&(D(!1),C(`Connection failed: ${ge.message}`),v(!0),g(M,Y,!1),S(M,Y,"exited"),h(M,Y,null))}});z.current.set(Q,()=>me.close()),W.current=Q},[k,x,b,Ae,g,S,h,e]),J=l.useMemo(()=>y.map(M=>`${M.id}:${M.terminalSessionId??""}`).join(","),[y]);return l.useEffect(()=>{if(!a||!i||!t)return;const M=t,Y=new Set;for(const Q of y)Q.terminalSessionId&&(Y.add(Q.terminalSessionId),Pe(M,Q.id,Q.terminalSessionId));for(const[Q,ne]of z.current)if(!Y.has(Q)){try{ne()}catch{}z.current.delete(Q)}},[J,y,t,a,i,Pe]),l.useEffect(()=>sh(()=>{if(!q.current||!G.current)return;const M=B.current;if(!M)return;const Y=[];for(const ne of F.current){if(!ne.terminalSessionId)continue;be.getState().getDirectoryState(M)?.tabs.find(me=>me.id===ne.id)?.terminalSessionId===ne.terminalSessionId&&Y.push({id:ne.id,terminalSessionId:ne.terminalSessionId})}if(z.current.clear(),W.current=null,Y.length===0)return;D(!0),C(null),v(!1);for(const ne of Y)Pe(M,ne.id,ne.terminalSessionId);const Q=R.current;if(Q)for(const ne of Y)L.current.resize({sessionId:ne.terminalSessionId,...Q}).catch(()=>{})}),[Pe]),l.useEffect(()=>{let M=!1;if(!a||!i)return;if(!t){C(m?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const Q=t;if(!B.current||B.current!==Q)return;if(!be.getState().getDirectoryState(Q)){p(Q);return}const ae=be.getState().getDirectoryState(Q);if(!ae||ae.tabs.length===0)return;const me=ae.activeTabId??ae.tabs[0]?.id??null;if(!me)return;const ge=ae.tabs.find(X=>X.id===me)??ae.tabs[0],ke=ge?.terminalSessionId??null,ve=ge?.lifecycle??"idle",De=!!ge?.label?.startsWith("Action:"),xe=be.getState().getBuffer(Q,me),ze=xe.byteLength>0||xe.chunks.length>0;if(!ke){if(ve==="exited"){g(Q,me,!1);return}if(De&&ze){g(Q,me,!1);return}const X=`${Q}\0${me}`;if(T.current.has(X))return;const oe=R.current??$c;T.current.add(X),C(null),v(!1),D(!1),g(Q,me,!0);try{const te=await e.createSession({cwd:Q,sessionId:me,cols:oe.cols,rows:oe.rows,shell:c,loginShell:d,...u.current});if(!be.getState().getDirectoryState(Q)?.tabs.find(_e=>_e.id===me)){try{await e.close(te.sessionId)}catch{}return}h(Q,me,te.sessionId);const he=R.current;he&&(he.cols!==oe.cols||he.rows!==oe.rows)&&e.resize({sessionId:te.sessionId,...he}).catch(()=>{});return}catch(te){const fe=be.getState().getDirectoryState(Q)?.tabs.find(he=>he.id===me);if(!fe||fe.terminalSessionId||(g(Q,me,!1),B.current!==Q||$.current!==me))return;C(te instanceof Error?te.message:"Failed to start terminal session"),v(!0),D(!1);return}finally{T.current.delete(X)}}!ke||M||(K.current=ke)})(),()=>{M=!0}},[m,t,r,o,n,i,f,a,p,g,S,h,e,d,c,u]),{connectionError:j,setConnectionError:C,isFatalError:w,setIsFatalError:v,isReconnectPending:I,setIsReconnectPending:D,terminalIdRef:K,lastViewportSizeRef:R,directoryRef:B,activeTabIdRef:$,disconnectStream:H,resetTerminalPreviewScan:le,startStream:Pe}}function Zx({terminal:e,terminalIdRef:t,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:a,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=l.useState(null),m=l.useRef(null),x=l.useCallback(()=>{d||m.current?.focus()},[d]),y=l.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||m.current?.focus()},[d]);l.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),l.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const p=l.useCallback(b=>{if(!b||n)return;let A=b,j=!1;u&&b.length>0&&(A=Vx(b,u),j=!0);const C=t.current;C&&(e.sendInput(C,A).catch(w=>{n||r(w instanceof Error?w.message:"Failed to send input")}),j&&(f(null),x()))},[u,x,n,r,e,t]),h=l.useCallback((b,A)=>{const j=a.current;if((!j||j.cols!==b||j.rows!==A)&&(a.current={cols:b,rows:A}),!i)return;const C=t.current;C&&e.resize({sessionId:C,cols:b,rows:A}).catch(()=>{})},[i,a,e,t]),S=l.useCallback(b=>{f(A=>A===b?null:b),x()},[x]),g=l.useCallback(b=>{const A=Yx(b,u);A&&(p(A),f(null),x())},[u,x,p]),k=l.useCallback(b=>{if(b.repeat)return;const A=b.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const j=A.length===1?A.toLowerCase():A;if(j in Ja){b.preventDefault(),b.stopPropagation(),g(Ja[j]);return}const C=Jx(b,u);C&&(b.preventDefault(),b.stopPropagation(),p(C),f(null),x())},[u,x,g,p]);return l.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[u,k,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:m,focusTerminalController:x,focusTerminalWhenWindowActive:y,handleViewportInput:p,handleViewportResize:h,handleModifierToggle:S,handleMobileKeyPress:g}}function ey({terminal:e,effectiveDirectory:t,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:a,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:m,startStream:x,setConnectionError:y,setIsFatalError:p,setIsReconnectPending:h}){const S=be(W=>W.createTab),g=be(W=>W.setActiveTab),k=be(W=>W.closeTab),b=be(W=>W.setTabSessionId),A=be(W=>W.setTabLifecycle),[j,C]=l.useState(!1),w=l.useCallback(async()=>{if(!t||j)return;const W=be.getState().getDirectoryState(t),$=n??W?.activeTabId??W?.tabs[0]?.id??null;if(!$)return;const K=W?.tabs.find(B=>B.id===$)?.terminalSessionId??null;if(!(!K||!e.restartSession)){C(!0),y(null),p(!1),h(!1),m();try{const B=c.current??$c,R=await e.restartSession(K,{cwd:t,shell:o,loginShell:i,...B,...a.current});if(be.getState().getDirectoryState(t)?.tabs.find(E=>E.id===$)?.terminalSessionId!==K||(b(t,$,R.sessionId),A(t,$,"running"),d.current!==t||u.current!==$))return;f.current=R.sessionId,x(t,$,R.sessionId)}catch(B){if(be.getState().getDirectoryState(t)?.tabs.find(T=>T.id===$)?.terminalSessionId!==K||d.current!==t||u.current!==$)return;y(B instanceof Error?B.message:"Failed to restart terminal"),p(!1),h(!1),f.current=K,x(t,$,K)}finally{C(!1)}}},[n,u,d,t,r,j,c,m,y,p,h,A,b,x,e,a,f,i,o]),v=l.useCallback(async()=>{await w()},[w]),I=l.useCallback(()=>{if(!t)return;const W=S(t);g(t,W),y(null),p(!1),h(!1)},[S,t,g,y,p,h]),D=l.useCallback(W=>{t&&(g(t,W),y(null),p(!1),h(!1))},[t,g,y,p,h]),z=l.useCallback(W=>{if(!t)return;y(null),p(!1),h(!1);const $=be.getState().getDirectoryState(t)?.tabs.find(K=>K.id===W)?.terminalSessionId;(async()=>{$&&await e.close($),k(t,W)})().catch(K=>y(K instanceof Error?K.message:"Terminal session ended"))},[k,t,y,p,h,e]);return{isRestarting:j,handleRestart:w,handleHardRestart:v,handleCreateTab:I,handleSelectTab:D,handleCloseTab:z}}const pv=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Gs(),{currentTheme:i}=Nl(),a=l.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});a.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=hf(),d=de(se=>se.terminalFontSize),u=de(se=>se.terminalShell),f=de(se=>se.terminalLoginShells.includes(se.terminalShell)),{isMobile:m,isTablet:x,hasTouchOnlyPointer:y}=bn(),p=m||x,h=(p||y)&&o.platform==="web",S=!0,g=de(se=>se.showTerminalQuickKeysOnDesktop),k=p||g,b=Me(se=>se.currentSessionId),A=Me(se=>se.newSessionDraft),j=b!==null||A?.open===!0,C=pf()??null,w=be(se=>C?se.sessions.get(C):void 0),v=be(se=>se.hasHydrated),I=de(se=>se.openContextPreview),D=l.useMemo(()=>w?w.activeTabId??w.tabs[0]?.id??null:null,[w,S]),z=l.useMemo(()=>{if(w)return D?w.tabs.find(se=>se.id===D)??w.tabs[0]:w.tabs[0]},[w,D]),W=l.useMemo(()=>(w?.tabs??[]).map(se=>({icon:(()=>{const Le=se.iconKey?Hn[se.iconKey]??"terminal":"terminal";return s.jsx(P,{name:Le,className:"h-4 w-4"})})(),id:se.id,label:se.label,title:se.label,closeLabel:"Close tab"})),[w?.tabs]),$=z?.terminalSessionId??null,K=z?.lifecycle??"idle",B=l.useMemo(()=>(w?.tabs??[]).map(se=>({id:se.id,terminalSessionId:se.terminalSessionId,label:se.label})),[w?.tabs]),R=z?.isConnecting??!1,T=z?.previewUrl??null,F=de(se=>se.activeMainTab)==="terminal",q=e??F,[G,L]=l.useState(q);l.useEffect(()=>{q&&L(!0)},[q]);const{connectionError:le,setConnectionError:H,isFatalError:Ae,setIsFatalError:Pe,isReconnectPending:J,setIsReconnectPending:M,terminalIdRef:Y,lastViewportSizeRef:Q,directoryRef:ne,activeTabIdRef:ae,resetTerminalPreviewScan:me,startStream:ge}=Xx({terminal:r,effectiveDirectory:C,activeTabId:D,terminalSessionId:$,terminalLifecycle:K,hasOpenedTerminalViewport:G,terminalHydrated:v,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,enableTabs:S,hasActiveContext:j,tabs:B,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&ve.current?.focus()}}),{activeModifier:ke,terminalControllerRef:ve,focusTerminalWhenWindowActive:De,handleViewportInput:xe,handleModifierToggle:ze,handleMobileKeyPress:X}=Zx({terminal:r,terminalIdRef:Y,isReconnectPending:J,setConnectionError:H,showQuickKeys:k,isTerminalVisible:q,lastViewportSizeRef:Q,terminalSessionId:$,useTouchTerminalInput:h}),{isRestarting:oe,handleRestart:te,handleHardRestart:fe,handleCreateTab:he,handleSelectTab:_e,handleCloseTab:je}=ey({terminal:r,effectiveDirectory:C,activeTabId:D,enableTabs:S,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,lastViewportSizeRef:Q,directoryRef:ne,activeTabIdRef:ae,terminalIdRef:Y,resetTerminalPreviewScan:me,startStream:ge,setConnectionError:H,setIsFatalError:Pe,setIsReconnectPending:M});l.useEffect(()=>{if(!q||h)return;if(typeof window>"u"){De();return}const se=window.requestAnimationFrame(()=>{De()});return()=>{window.cancelAnimationFrame(se)}},[D,De,q,h]);const V=l.useMemo(()=>{const se=Dn[ro].stack;if(typeof window>"u")return(Dn[c]??Dn[ro]).stack;const ht=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ht&&ht.trim().length>0?ht.trim():(Dn[c]??Dn[ro]).stack??se},[c]),we=l.useMemo(()=>jx(i),[i]),ue=`${C??"no-dir"}::${D??"no-tab"}`;if(l.useEffect(()=>{if(!q||h)return;const se=ve.current;if(!se)return;const Le=()=>{se.fit()};if(typeof window<"u"){const ht=window.requestAnimationFrame(()=>{Le(),De()}),ct=[220,400].map(Qe=>window.setTimeout(Le,Qe));return()=>{window.cancelAnimationFrame(ht),ct.forEach(Qe=>window.clearTimeout(Qe))}}Le()},[De,q,h,ve,ue,$]),l.useEffect(()=>{if(!q||!h)return;let se=null;const Le=()=>{se!==null&&window.cancelAnimationFrame(se),se=window.requestAnimationFrame(()=>{se=null,ve.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Le),()=>{window.removeEventListener("oc:keyboard-settled",Le),se!==null&&window.cancelAnimationFrame(se)}},[q,ve,ue,h]),!j)return s.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(!C)return s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[s.jsx("p",{children:"No working directory available for this session."}),s.jsx("button",{onClick:te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Se=!$||R||oe||J,Ye=G,Ue=w?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(Va,{items:W,activeId:D,onSelect:_e,onClose:je,onCreate:he})}),s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:he,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"h-4 w-4"})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{te()},disabled:oe,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"h-4 w-4"})}),T?s.jsxs(Ne,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{C&&I(C,T)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,U=s.jsx(Ox,{isTouchTerminal:p,activeModifier:ke,disabled:Se,onKeyPress:X,onModifierToggle:ze}),pe=!n||p||k;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[Ue&&n?bu.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ue}),n):null,p&&Ue&&!n&&w?s.jsx(Lx,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(Va,{items:W,activeId:D,onSelect:_e,onClose:je,onCreate:he})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:he,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"size-4"})}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:()=>{te()},disabled:oe,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"size-4"})}),T?s.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{C&&I(C,T)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"size-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(P,{name:"close",className:"size-4"})}):null]})}):null,!p&&pe?s.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[Ue&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ue,t?s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(P,{name:"close",className:"h-4 w-4"})}):null]}):null,!p&&k&&S&&w?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:U}):null,!p&&k&&!w?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:U}):null]}):null,s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:we.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Ye&&C&&w?w.tabs.map(se=>{const Le=se.id===D;return s.jsx(Fx,{directory:C,tabId:se.id,sessionId:se.terminalSessionId,sessionKey:`${C}::${se.id}`,isActive:Le,isTerminalVisible:q,terminal:r,theme:we,fontFamily:V,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:Q,onInput:xe,controllerRef:ve},se.id)}):null}),!J&&le&&s.jsxs("div",{className:"absolute inset-x-0 bottom-0 border-t border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 text-xs text-foreground flex items-center justify-between gap-2",children:[s.jsx("span",{children:le}),Ae&&p&&s.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:fe,disabled:oe,title:"Force kill and create fresh session",type:"button",children:"Hard restart"})]})]}),p&&k?s.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:s.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:U})}):null]})},hi=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"pull-requests",label:"PRs",icon:"git-pull-request"},{id:"issues",label:"Issues",icon:"task"}],ty=new Set(hi.map(e=>e.id)),sy=e=>typeof e=="string"&&ty.has(e),mv=e=>sy(e)?e:"changes",Kc=e=>e==="pull-requests"||e==="issues",ny=e=>e?hi:hi.filter(t=>!Kc(t.id)),gv=(e,t)=>Kc(e)?"changes":e,ry=48,oy=96,jt=(e,...t)=>{try{e?.(...t)}catch{}},Co=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},bv=(e,t)=>{const n=l.useRef(t);n.current=t;const r=t.enabled;l.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const i=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?oy:ry;let d=!1,u=!1,f=!1,m=null,x=!1,y=0,p=0,h=0,S=0;const g=()=>{d=!1,u=!1,f=!1,m=null},k=()=>{const I=n.current,D=m,z=x;u&&D&&(jt(D==="left"?I.onLeftProgress:I.onRightProgress,z?1:0),jt(I.onDragEnd,D,z)),g()},b=()=>{k(),u||g()},A=I=>{const D=n.current;if(D.enabled===!1){u&&m?k():g();return}if(I.touches.length!==1){u&&m?k():g();return}const z=I.touches[0],W=o.getBoundingClientRect(),$=o.clientWidth,K=!!D.leftOpen,B=!!D.rightOpen,R=T=>px(T,o);if(K||B){if(R(I.target)){g();return}if(K&&B){const T=z.clientX<=W.left+c;z.clientX>=W.right-c?(m="right",x=!0):T?(m="left",x=!0):(m=K?"left":"right",x=!0)}else K?(m="left",x=!0):(m="right",x=!0);S=Co(m==="left"?D.leftWidth:D.rightWidth,$),S<10&&(S=$||window.innerWidth||320),S<10&&(S=320),d=!0}else{if(R(I.target)){g();return}m=null,x=!1,S=0,d=!0}y=z.clientX,p=z.clientY,h=Date.now(),u=!1,f=!1},j=I=>{if(!d)return;if(I.touches.length!==1){b();return}const D=I.touches[0],z=D.clientX-y,W=D.clientY-p;if(!f){if(Math.abs(z)<Wa&&Math.abs(W)<Wa)return;if(Math.abs(W)>Math.abs(z)*On){g();return}if(!m){const B=n.current;m=z>0?"left":"right",S=Co(m==="left"?B.leftWidth:B.rightWidth,o.clientWidth),S<10&&(S=window.innerWidth||320)}if(m==="left"){if(!x&&z<=0){g();return}if(x&&z>=0){g();return}}else{if(!x&&z>=0){g();return}if(x&&z<=0){g();return}}f=!0,u=!0,jt(n.current.onDragStart,m)}if(!u)return;I.cancelable&&I.preventDefault();const $=n.current,K=Ga(m,x,z,S);jt(m==="left"?$.onLeftProgress:$.onRightProgress,K)},C=(I,D)=>{if(!d){g();return}const z=I-y,W=D-p;if(!m&&!x&&Math.abs(z)>=Cr&&Math.abs(W)<=Math.abs(z)*On){const E=n.current;m=z>0?"left":"right",S=Co(m==="left"?E.leftWidth:E.rightWidth,o.clientWidth),S<10&&(S=window.innerWidth||320)}if(!m){g();return}const $=Math.max(1,Date.now()-h),K=n.current;if(!u){const E=Math.abs(z),F=Math.abs(W);E>=Cr&&F<=E*On?m==="left"&&!x&&z>0?(jt(K.onLeftProgress,1),jt(K.onLeftOpen)):m==="right"&&!x&&z<0?(jt(K.onRightProgress,1),jt(K.onRightOpen)):jt(m==="left"?K.onLeftProgress:K.onRightProgress,x?1:0):jt(m==="left"?K.onLeftProgress:K.onRightProgress,x?1:0);const q=m;g(),jt(K.onDragEnd,q);return}const B=Ga(m,x,z,S),R=fx({side:m,isOpenAtStart:x,dx:z,dt:$,progress:B}),T=m;jt(T==="left"?R?K.onLeftOpen:K.onLeftClose:R?K.onRightOpen:K.onRightClose),g(),jt(K.onDragEnd,T,R)},w=I=>{const D=I.changedTouches[0];if(!D){g();return}const z=D.clientX-y,W=D.clientY-p;d&&(u||Math.abs(z)>=Cr&&Math.abs(W)<=Math.abs(z)*On)&&I.cancelable&&I.preventDefault(),C(D.clientX,D.clientY)},v=()=>{b()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",j,{passive:!1}),o.addEventListener("touchend",w,{passive:!1}),o.addEventListener("touchcancel",v,{passive:!0}),()=>{try{u&&m&&k()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",j),o.removeEventListener("touchend",w),o.removeEventListener("touchcancel",v)}},[e,r])};function xv({className:e="h-5 w-5"}){return s.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[s.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),s.jsx(P,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Xa({size:e,className:t,style:n,...r}){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:t,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:s.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 iy=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,ay=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>Ur(t,n)?null:e,Ao=()=>Os.filter(e=>Wo.has(e.id)).map(e=>({...Fl(e)})),ly=()=>{if(typeof window>"u")return Go;const e=window.localStorage.getItem("openInAppId");return e&&Ko(e)?e:Go};let No=!1,tn=!1,vs=!1,Ss=0,qn=null;const Za=()=>{qn&&(clearTimeout(qn),qn=null)},Ms=Is()((e,t)=>({selectedAppId:ly(),availableApps:Ao(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(No||typeof window>"u")return;No=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Ao(),hasLoadedApps:u});return}const f=new Set(d.map(p=>p.name)),m=new Map(d.map(p=>[p.name,p.iconDataUrl??void 0])),y=Os.filter(p=>f.has(p.appName)||Wo.has(p.id)).map(p=>({...Fl(p),iconDataUrl:m.get(p.appName)}));e({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!pn()||!Er()||tn||t().hasLoadedApps&&!d)return;const f=Os.map(m=>m.appName);Za(),tn=!0,vs=!1,e({isScanning:!0});try{const{apps:m,success:x,hasCache:y,isCacheStale:p}=await ea(f,d),h=x&&!y&&m.length===0&&Ss<3;if(e({isCacheStale:y?p:!1}),n(m,x?!h:!1),x){if(h){const g=[800,1600,3200][Ss]??3200;Ss+=1,vs=!0,qn=setTimeout(()=>{r()},g);return}Ss=0,vs=!1;return}if(Ss<3){const g=[1e3,3e3,7e3][Ss]??7e3;Ss+=1,vs=!0,qn=setTimeout(()=>{r()},g)}}finally{tn=!1,vs||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Ko(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},a=d=>{const u=d.detail;Array.isArray(u)&&(Ss=3,vs=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",a),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(No||t().initialize(),!pn()||!Er()||tn||t().hasLoadedApps&&!n)return;const o=Os.map(i=>i.appName);Za(),n&&e({hasLoadedApps:!1}),tn=!0,vs=!1,e({isScanning:!0});try{const{apps:i,hasCache:a,isCacheStale:c}=await ea(o,n),d=new Set(i.map(x=>x.name)),u=new Map(i.map(x=>[x.name,x.iconDataUrl??void 0])),m=Os.filter(x=>d.has(x.appName)||Wo.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:m.length>0?m:Ao(),hasLoadedApps:m.length>0,isCacheStale:a?c:!1})}finally{tn=!1,vs||e({isScanning:!1})}},selectApp:async n=>{Ko(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await Rl({openInAppId:n}))}})),cy="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",dy="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",Io=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?cy:e.id==="terminal"?dy:void 0}),el=({label:e,iconDataUrl:t,fallbackIconDataUrl:n})=>{const[r,o]=l.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",a=t||n;return a&&!r?s.jsx("img",{src:a,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):s.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:i})},uy=({directory:e,className:t})=>{const n=Ms(p=>p.selectedAppId),r=Ms(p=>p.availableApps),o=Ms(p=>p.isCacheStale),i=Ms(p=>p.isScanning),a=Ms(p=>p.initialize),c=Ms(p=>p.loadInstalledApps),d=Ms(p=>p.selectApp);l.useEffect(()=>{a()},[a]);const u=pn()&&Er(),f=l.useMemo(()=>{const p=r.find(h=>h.id===n)??r.find(h=>h.id===Go)??r[0]??Os[0];return Io(p||Os[0])},[r,n]);if(!u||!e||r.length===0)return null;const m=async p=>{await nh(e,p.id,p.appName)||await Tl(e,p.appName)},x=async p=>{await d(p.id),await m(p)},y=async()=>{(await ps(e)).ok&&ie.success("Path copied to clipboard")};return s.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",t),children:[s.jsx("button",{type:"button",onClick:()=>{m(f)},className:_("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",i&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:s.jsx(el,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Yt,{children:[s.jsx(Vt,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y()},children:[s.jsx(P,{name:"file-copy",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy path"})]}),s.jsx(hn,{}),r.map(p=>{const h=Io(p);return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{x(p)},children:[s.jsx(el,{label:p.label,iconDataUrl:p.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:p.label}),f.id===p.id?s.jsx(P,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},p.id)}),o?s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[s.jsx(P,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh apps"})]}):null]})]})]})},fy="\x1B",hy=new RegExp(`${fy}\\[[0-9;?]*[ -/]*[@-~]`,"g"),py=/https?:\/\/[^\s<>'"`]+/gi,Et="__pichamber_auto_discover_preview__",my=15e3,gy=e=>{let t="";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||(t+=e[n])}return t},by=e=>{const t=(e||"").trim();if(!t)return null;const n=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},xy=e=>{const n=e.replace(hy,"").match(py);if(!n||n.length===0)return null;const r=n.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const a=new URL(i);a.port&&a.port.length>0&&o.push({raw:i,parsed:a})}catch{}if(o.length>0){const i=a=>{const{parsed:c}=a,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",m=f.split("/").filter(Boolean).length,x=f==="/"||f==="",y=!!(c.search||c.hash);let p=0;return u&&(p+=50),x&&(p+=30),p-=Math.min(m*5,20),y&&(p-=10),p};return o.sort((a,c)=>i(c)-i(a)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},yy=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],wy=["dev","start","preview","serve"];async function vy(e,t,n){if(!e)return null;const r=ky(t);if(r)return{command:r.command,label:r.name||"Start preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Cy(n);if(o){const i=await Ay(e);return{command:`${i==="npm"?"npm run":i==="yarn"?"yarn":i==="pnpm"?"pnpm":i==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await Sy(e)){const o=await jy(),i=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${i}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${i}/`}}return null}async function Sy(e){const t=`${e}/index.html`,n=await Br(t,e);return typeof n=="string"&&n.trim().length>0}async function jy(){try{const e=await ot("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),n=typeof t?.port=="number"?t.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function ky(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(wy.some(o=>n.includes(o)))return t}return null}function Cy(e){for(const{pattern:t}of yy)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function Ay(e){const t=await Br(`${e}/package.json`,e);if(t)try{const r=JSON.parse(t),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 i=await Br(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function Br(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await ot(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=Pl()?.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 ot(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Ny(e){try{const t=await Br(`${e}/package.json`,e);if(t==null)return null;const r=JSON.parse(t).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Iy=(e,t,n)=>new Promise(r=>{let o=!1,i=null,a=null;const c=d=>{o||(o=!0,a&&clearTimeout(a),i?.close(),r(d))};i=e.connect(t,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?i.close():a=setTimeout(()=>c(!1),n)});function Ey({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=Nl(),{terminal:o}=Gs(),{isMobile:i}=bn(),a=de(X=>X.terminalShell),c=de(X=>X.terminalLoginShells.includes(X.terminalShell)),d=de(X=>X.setSettingsPage),u=de(X=>X.setSettingsDialogOpen),f=de(X=>X.setSettingsProjectsSelectedId),m=de(X=>X.openContextPreview),x=be(X=>X.ensureDirectory),y=be(X=>X.setTabLabel),p=be(X=>X.setTabIconKey),h=be(X=>X.setActiveTab),S=be(X=>X.setConnecting),g=be(X=>X.setTabSessionId),k=be(X=>X.setTabPreviewUrl),b=be(X=>X.projectActionRuns),A=be(X=>X.setProjectActionRun),j=be(X=>X.updateProjectActionRunStatus),C=be(X=>X.removeProjectActionRun),[w,v]=l.useState([]),[I,D]=l.useState(null),[z,W]=l.useState(!1),$=l.useRef({}),K=l.useRef({}),B=l.useRef({}),R=l.useRef({}),T=l.useRef(new Set),E=l.useRef(0),F=e?.id??null,q=e?.path??"",G=l.useMemo(()=>F?{id:F,path:q}:null,[F,q]),L=l.useCallback(async X=>{await ml(X)},[]),le=l.useCallback(async()=>{if(!G)return;const X=E.current+1;E.current=X,W(!0);try{const oe=await To(G);if(E.current!==X)return;const te=oe.actions;v(te),D(fe=>fe===Et||fe&&te.some(he=>he.id===fe)?fe:null)}catch{if(E.current!==X)return}finally{E.current===X&&W(!1)}},[G]),H=l.useMemo(()=>sc(t||G?.path||""),[t,G?.path]),Ae=l.useMemo(()=>I?w.find(X=>X.id===I)??null:null,[w,I]),Pe=l.useMemo(()=>({id:Et,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),J=!i,M=l.useMemo(()=>J?[Pe,...w]:w,[w,Pe,J]);l.useEffect(()=>{le()},[le]),l.useEffect(()=>{if(typeof window>"u")return;const X=oe=>{const te=oe.detail;F&&(te?.projectId&&te.projectId!==F||le())};return window.addEventListener(Jo,X),()=>{window.removeEventListener(Jo,X)}},[le,F]),l.useEffect(()=>{I&&(I===Et&&J||w.some(X=>X.id===I)||D(null))},[w,J,I]),l.useEffect(()=>{const X=()=>{const oe=be.getState(),te=oe.sessions,fe=oe.projectActionRuns;for(const[he,_e]of Object.entries(fe)){const V=te.get(_e.directory)?.tabs.find(Le=>Le.id===_e.tabId);if(!V||V.terminalSessionId!==_e.sessionId){C(he);continue}const we=K.current[he]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};K.current[he]=we;const ue=M.find(Le=>Le.id===_e.actionId),Se=oe.getBuffer(_e.directory,_e.tabId).chunks;if(!ue||Se.length===0)continue;const Ye=Se.filter(Le=>we.lastSeenChunkId===null||Le.id>we.lastSeenChunkId);if(Ye.length===0)continue;const Ue=Ye.map(Le=>Le.data).join(""),U=`${we.tail}${Ue}`,pe=!we.openedUrl&&ue.autoOpenUrl===!0?xy(U):null,se=Ye[Ye.length-1]?.id??we.lastSeenChunkId;if(we.lastSeenChunkId=se,we.tail=U.slice(-512),pe)if(we.openedUrl=!0,we.openInPreview){const Le=fe[he];Le&&(k(Le.directory,Le.tabId,pe,{locked:!1,autoOpened:!1}),Le.status==="waiting-for-preview"&&j(he,"running"),window.clearTimeout(R.current[he]),delete R.current[he],m(Le.directory,pe))}else L(pe),ie.success("Opened URL from action output");K.current[he]=we}for(const he of Object.keys(K.current))fe[he]||(delete K.current[he],window.clearTimeout(R.current[he]),delete R.current[he])};return X(),be.subscribe((oe,te)=>{(oe.sessions!==te.sessions||oe.buffers!==te.buffers)&&X()})},[M,m,L,b,C,k,j]);const Y=l.useCallback(async(X,oe={})=>{if(!H)throw new Error("No active directory");const te=fs(H,X.id);x(H);const fe=be.getState(),he=fe.getDirectoryState(H);let _e=$.current[te]||null;const je=_e?!!he?.tabs.some(ue=>ue.id===_e):!1;(!_e||!je)&&(_e=fe.createTab(H),$.current[te]=_e),y(H,_e,`Action: ${X.name}`),p(H,_e,X.icon||"play"),h(H,_e),oe.revealTerminal!==!1&&de.getState().openContextPanelTab(H,{mode:"terminal"});const we=be.getState().getDirectoryState(H)?.tabs.find(ue=>ue.id===_e);return{key:te,tabId:_e,sessionId:we?.terminalSessionId??null}},[x,H,h,p,y]),Q=l.useCallback(async X=>{if(!n&&i)return;if(!H){ie.error("No active directory for action");return}const oe=fs(H,X.id),te=b[oe];if(!(te&&te.status==="running")&&!T.current.has(oe)){T.current.add(oe);try{const fe=X.id===Et?await(async()=>{const[U,pe]=await Promise.all([To({id:G?.id??"",path:H}),Ny(H)]),se=await vy(H,U.actions,pe);if(!se)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:Et,name:"Auto-discover",command:se.command,icon:"scan-2",autoOpenUrl:!0,openUrl:se.previewUrlHint||""}})():X,he=fe.autoOpenUrl===!0&&(fe.openUrl||"").trim().length>0,_e=!he&&X.id!==Et,{key:je,tabId:V,sessionId:we}=await Y(fe,{revealTerminal:_e});let ue=we;if(!ue){S(H,V,!0);try{ue=(await o.createSession({cwd:H,sessionId:V,shell:a,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,g(H,V,ue)}finally{S(H,V,!1)}}if(!ue)throw new Error("Failed to create terminal session");B.current[je]?.(),S(H,V,!0);const Se=o.connect(ue,{onEvent:U=>{U.type==="snapshot"&&(be.getState().replaceBuffer(H,V,U.data??"",U.sequence??0),be.getState().setConnecting(H,V,!1)),U.type==="data"&&typeof U.data=="string"&&U.data.length>0&&be.getState().appendToBuffer(H,V,U.data,U.sequence,U.replayData),U.type==="exit"&&(be.getState().setTabLifecycle(H,V,"exited"),be.getState().setConnecting(H,V,!1),be.getState().removeProjectActionRun(je),delete K.current[je],B.current[je]?.(),delete B.current[je],window.clearTimeout(R.current[je]),delete R.current[je])},onError:(U,pe)=>{be.getState().setConnecting(H,V,!1),pe&&(be.getState().setTabLifecycle(H,V,"exited"),be.getState().setTabSessionId(H,V,null),be.getState().removeProjectActionRun(je))}});B.current[je]=Se.close;const Ye=fe.autoOpenUrl?by(fe.openUrl):null;A({key:je,directory:H,actionId:fe.id,tabId:V,sessionId:ue,status:fe.id===Et&&!Ye?"waiting-for-preview":"running"}),window.clearTimeout(R.current[je]),delete R.current[je],fe.id===Et&&!Ye&&(R.current[je]=window.setTimeout(()=>{const U=be.getState(),pe=U.projectActionRuns[je];U.updateProjectActionRunStatus(je,"running"),pe&&(U.setActiveTab(pe.directory,pe.tabId),de.getState().openContextPanelTab(pe.directory,{mode:"terminal"})),delete R.current[je]},my)),K.current[je]={lastSeenChunkId:null,openedUrl:!!Ye||he,tail:"",openInPreview:fe.id===Et};const Ue=gy(fe.command.trim().replace(/\r\n|\r/g,`
|
|
62
|
+
`));await o.sendInput(ue,`${Ue}\r`),Ye?(k(H,V,Ye,{locked:!0,autoOpened:!0}),m(H,Ye),ie.success("Opened action URL")):he?(k(H,V,null,{locked:!0}),ie.error("Invalid custom URL format")):k(H,V,null,{locked:!1,autoOpened:!1})}catch(fe){C(oe),delete K.current[oe],B.current[oe]?.(),delete B.current[oe],window.clearTimeout(R.current[oe]),delete R.current[oe],ie.error(fe instanceof Error?fe.message:"Failed to run action")}finally{T.current.delete(oe)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Y,n,i,H,c,a,m,b,C,S,A,k,g,G?.id,o]),ne=l.useCallback(async X=>{const oe=fs(H,X.id),te=b[oe];if(!te)return;j(oe,"stopping");const fe=Iy(o,te.sessionId,1e3);try{await o.sendInput(te.sessionId,"")}catch{}const he=await fe;if(be.getState().getDirectoryState(te.directory)?.tabs.find(V=>V.id===te.tabId)?.terminalSessionId===te.sessionId&&!he){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:te.sessionId})}catch{}else try{await o.close(te.sessionId)}catch{}g(te.directory,te.tabId,null)}C(oe),delete K.current[oe],B.current[oe]?.(),delete B.current[oe],window.clearTimeout(R.current[oe]),delete R.current[oe]},[H,b,C,g,o,j]),ae=l.useCallback(()=>{const X=Ae??M[0];if(!X)return;const oe=fs(H,X.id),te=b[oe];if(te?.status!=="stopping"){if(te){ne(X);return}Q(X)}},[M,H,Q,b,Ae,ne]),me=l.useCallback((X,oe=!1)=>{if(D(X.id),!oe){Q(X);return}const te=fs(H,X.id),fe=b[te];if(fe?.status!=="stopping"){if(fe){ne(X);return}Q(X)}},[H,Q,b,ne]),ge=l.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),ke=Ae??M[0]??null,ve=ke?b[fs(H,ke.id)]:null,De=be(X=>ve?X.sessions.get(ve.directory)?.tabs.find(oe=>oe.id===ve.tabId)?.previewUrl??null:null),xe=!!((n||!i)&&G&&H),ze=Ae??M[0]??null;return{shouldRender:xe,isLoading:z,normalizedDirectory:H,resolvedSelected:ze,displayActions:M,projectActionRuns:b,selectedRunPreviewUrl:De,handlePrimaryClick:ae,handleSelectAction:me,openProjectActionsSettings:ge,openContextPreview:m}}const tl=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:a,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:m,handlePrimaryClick:x,handleSelectAction:y,openProjectActionsSettings:p,openContextPreview:h}=Ey({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const S=d.icon||"play",g=d.id===Et?"scan-2":Hn[S]||"play",k=fs(c,d.id),b=f[k],A=b?.status==="stopping",j=b?.status==="waiting-for-preview",C=!!(b&&m),w=()=>{!b||!m||h(b.directory,m)},v=d.id===Et;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",disabled:a||A,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:x,"aria-label":b?`Stop ${d.name}`:`Run ${d.name}`,children:A||j?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):b?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),v?s.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.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:w,children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,s.jsxs(Yt,{children:[s.jsx(Vt,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(Qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{className:"flex items-center gap-2",onClick:p,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(hn,{}),u.map(I=>{const D=I.icon||"play",z=I.id===Et?"scan-2":Hn[D]||"play",W=fs(c,I.id),$=f[W],K=!!$,B=$?.status==="stopping";return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y(I,!0)},children:[s.jsx(P,{name:z,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:I.name}),B||$?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},I.id)})]})]})]}):s.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:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,disabled:a||A,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":b?`Stop ${d.name}`:`Run ${d.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||j?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):b?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),v?s.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:w,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:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,s.jsxs(Yt,{children:[s.jsx(Vt,{asChild:!0,children:s.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:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ft,{className:"flex items-center gap-2",onClick:p,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(hn,{}),u.map(I=>{const D=I.icon||"play",z=I.id===Et?"scan-2":Hn[D]||"play",W=fs(c,I.id),$=f[W],K=!!$,B=$?.status==="stopping";return s.jsxs(ft,{className:"flex items-center gap-2",onClick:()=>{y(I,!0)},children:[s.jsx(P,{name:z,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:I.name}),B||$?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},I.id)})]})]})]})},Wt={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function Nr(e){return e?.deploymentKind==="docker"?{name:Wt.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:Wt.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:Wt.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:Wt.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:Wt.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:Wt.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:Wt.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:Wt.centos,color:"#932279"}:{name:Wt.linux}:e?.serverPlatform==="darwin"?{name:Wt.darwin}:{name:Wt.unknown}}const Dy=e=>e?.deploymentKind==="docker"?"Docker":e?.serverPlatform==="win32"?"Windows":e?.serverPlatform==="darwin"?"macOS":e?.serverPlatform==="linux"?typeof e.serverDistribution=="string"&&e.serverDistribution.trim()?{ubuntu:"Ubuntu",arch:"Arch Linux",nixos:"NixOS",fedora:"Fedora",debian:"Debian",centos:"CentOS"}[e.serverDistribution]??"Linux":"Linux":"Server";function Ry({open:e,onOpenChange:t}){const[n,r]=l.useState(null),o=l.useCallback(async()=>{const u=et();try{const f=await ot("/api/version");if(!f.ok)throw new Error("Version request failed");const m=await f.json().catch(()=>null);u===et()&&r(m)}catch{u===et()&&r(null)}},[]);l.useEffect(()=>(o(),yn(()=>{o()})),[o]);const i=Nr(n),a=Dy(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Yt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx(Vt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(vn,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),s.jsx(Ge,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(Qt,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx(P,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:a})]}),c?s.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),s.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[s.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),s.jsxs("button",{type:"button",className:"ml-auto flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:`Copy ${d}`,"aria-label":"Copy server address",onClick:()=>{ps(d).then(u=>{u.ok?ie.success("Server address copied"):ie.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),s.jsx(P,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const Py=({isMobile:e})=>{const n=Gs().github??null,r=Kr(i=>i.refresh),o=nm();return l.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(vn,"app-region-no-drag inline-flex w-auto cursor-default gap-1.5 px-2"),title:`${o} via GitHub CLI`,"aria-label":`Signed in to GitHub as ${o} via GitHub CLI`,children:[s.jsx(P,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),s.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},Ty=l.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:m,remoteUpdateError:x,onOpenRemoteUpdate:y}){return s.jsxs(Yt,{open:a,onOpenChange:p=>{c(p),p&&d()},children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx(Vt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(vn,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),s.jsx(Ge,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(Qt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?s.jsxs("div",{children:[o?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:m?"Looking for updates...":x||"This instance is up to date."})]}),f?.available?s.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:y,children:"Update"}):null]})}),s.jsx(mf,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),My=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(as,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ws,{children:[s.jsx(bs,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(Ns,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(xn,{children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Fy=e=>{const t=e.trim();if(!t)return"";const n=t.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),i=`${r} ${o}`.trim();return n.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},Mn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},Ly=l.lazy(()=>xt(()=>import("./SessionSwitcherDropdown-CEw8BEs6.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),yv=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:a=!1})=>{Ht("ui.header.render");const c=de(O=>O.setSessionSwitcherOpen),d=de(O=>O.toggleSidebar),u=de(O=>O.isSidebarOpen),f=de(O=>O.activeMainTab),m=de(O=>O.setActiveMainTab),x=de(O=>O.shortcutOverrides);de(O=>O.timeFormatPreference),Gs();const y=Me(O=>!!O.newSessionDraft?.open),p=Me(O=>O.currentSessionId),h=kl(p??""),S=gf(p),g=l.useMemo(()=>{if(!S)return null;const O=S;return{title:S.title??null,directory:O.directory??null,created:S.time?.created??null,slug:O.slug??null,shareUrl:S.share?.url??null,parentId:S.parentID??null,messageCount:typeof S.messageCount=="number"?S.messageCount:null}},[S]),k=ut(Po(O=>{if(!O.activeProjectId)return null;const ce=O.projects.find(ye=>ye.id===O.activeProjectId);return ce?{id:ce.id,path:ce.path,label:ce.label}:null})),b=mn(O=>O.homeDirectory),A=l.useMemo(()=>k?bf(k):null,[k]),{isMobile:j}=bn(),{enabled:C}=bi(),w=!!(C&&i&&o!==void 0),v=l.useMemo(()=>[...ny(a)],[a]),[I,D]=l.useState(!1),z=l.useRef(null),[W,$]=l.useState(()=>typeof window>"u"?!1:pn()),K=l.useMemo(()=>Ml(),[]),B=xf(),[R,T]=l.useState(!1),E=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),F=Il(),q=l.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const ce=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ce)return null;const ye=Number.parseInt(ce[1],10),$e=Number.parseInt(ce[2],10);return Number.isNaN(ye)?null:ye===10?$e:ye},[]);Re.useEffect(()=>{typeof window>"u"||$(pn())},[]);const G=de(O=>O.isSessionSwitcherOpen),[L,le]=l.useState(!1),[H,Ae]=l.useState("Local"),[Pe,J]=l.useState(!0),[M,Y]=l.useState(()=>Nr(null)),[Q,ne]=l.useState(!1),[ae,me]=l.useState(null),[ge,ke]=l.useState(!1),[ve,De]=l.useState(null),xe=l.useRef(0),ze=l.useMemo(()=>Fy(H),[H]),X=l.useCallback(async()=>{if(typeof window>"u"||!W)return;const O=et(),ce=()=>et()===O;try{const ye=await ot("/api/version");if(!ce())return;const $e=ye.ok?await ye.json().catch(()=>null):null;if(!ce())return;if(Y(Nr($e)),Er()){Ae("Local"),J(!0);return}J(!1);const it=await rh();if(!ce())return;const Je=oh(),ss=ih([ah(Je),...it.hosts]);if(ss.id===lh){Ae("Local"),J(!0);return}Ae(ch(ss.label.trim()||"Instance"))}catch{ce()&&(Ae("Local"),J(!0),Y(Nr(null)))}},[W]);Re.useEffect(()=>(X(),yn(()=>{xe.current+=1,me(null),De(null),ke(!1),ne(!1),X()})),[X]);const oe=l.useCallback(async()=>{const O=xe.current+1;xe.current=O;const ce=et(),ye=()=>xe.current===O&&et()===ce;if(Pe){me(null),De(null);return}ke(!0),De(null);try{const $e=new URLSearchParams({appType:"web",instanceMode:"remote"}),it=await ot(`/api/pi/update-check?${$e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!it.ok)throw new Error(`Server responded with ${it.status}`);const Je=await it.json();if(!ye())return;me({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch($e){if(!ye())return;me(null),De($e instanceof Error?$e.message:"Failed to check remote instance updates")}finally{ye()&&ke(!1)}},[Pe]);l.useEffect(()=>Lp(()=>{Pe||oe()}),[oe,Pe]),l.useEffect(()=>{xe.current+=1,me(null),De(null),ke(!1),ne(!1)},[Pe,H]),l.useEffect(()=>{if(!W||Pe)return;const O=3e3,ce=3600*1e3;let ye=!1,$e=null;const it=Je=>{$e=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){it(ce);return}oe().finally(()=>{ye||it(ce)})},Je)};return it(O),()=>{ye=!0,$e!==null&&window.clearTimeout($e)}},[oe,Pe,H,W]);const te=l.useCallback(()=>{if(ae?.available){ne(!0);return}oe()},[oe,ae?.available]),fe=p?g??null:null,he=l.useRef(null),[_e,je]=l.useState(0);l.useEffect(()=>{if(!p){he.current&&(he.current=null,je($e=>$e+1));return}if(fe){he.current={sessionId:p,session:fe,expiresAt:Date.now()+2e3};return}const O=he.current;if(!O||O.sessionId!==p)return;const ce=O.expiresAt-Date.now();if(ce<=0){he.current=null,je($e=>$e+1);return}const ye=window.setTimeout(()=>{he.current?.sessionId===p&&(he.current=null),je($e=>$e+1)},ce);return()=>{window.clearTimeout(ye)}},[p,fe]);const V=(()=>{if(fe)return fe;if(!p)return null;const O=he.current;return O&&O.sessionId===p&&O.expiresAt>Date.now()?O.session:null})(),we=l.useMemo(()=>{const O=typeof V?.directory=="string"?V.directory:"";return Mn(O||"")},[V?.directory]),ue=Me(O=>O.newSessionDraft?.open?Mn(O.newSessionDraft.directoryOverride??""):""),Se=l.useMemo(()=>iy({sessionDirectory:we,draftDirectory:ue,isNewSessionDraftOpen:y}),[ue,y,we]),Ue=Oo(Se||null),U=l.useMemo(()=>ay({activeProjectLabel:A,openDirectory:Se,homeDirectory:b}),[A,b,Se]),pe=!!(U||Ue),se=l.useMemo(()=>p?js(V,"Untitled session"):U??"PiChamber",[V,p,U]),Le=yf(),ht=Me(O=>O.updateSessionTitle),ct=Me(O=>O.archiveSessions),Qe=Me(O=>O.deleteSessions),[Dt,Xe]=l.useState(!1),[Jt,wt]=l.useState(!1),tt=l.useRef(!1),[Rt,Bt]=l.useState(""),[Pt,Tt]=l.useState(null),cs=l.useRef(null);l.useEffect(()=>{tt.current=!1,wt(!1),Xe(!1),Bt(""),Tt(null)},[p]);const ds=l.useCallback(()=>{p&&(Bt(V?.title?.trim()||se),Xe(!0))},[V?.title,p,se]),rt=l.useCallback(async()=>{if(!p)return;const O=Rt.trim();O&&O!==V?.title?.trim()&&await ht(p,O),Xe(!1)},[V?.title,p,Rt,ht]);l.useEffect(()=>{if(!Dt)return;const O=ce=>{const ye=ce.target;(!ye||!cs.current?.contains(ye))&&rt()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[Dt,rt]);const pt=l.useCallback(()=>{p&&ps(p).then(O=>{ie[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ie.error("Failed to copy session ID"))},[p]),_t=l.useCallback(async()=>{if(!p||!Se){ie.error("Nothing to export");return}try{await Le.syncSession(p)}catch{ie.error("Failed to load the complete session history");return}const O=[];if(O.length===0){ie.error("Nothing to export");return}const ce=Fc(O,V?.title??null),ye=Bc(V?.title??null);await Oc(ce,ye)||Lc(ce,ye),ie.success("Session exported")},[V?.title,p,Se,Le]);h?.type==="busy"||h?.type;const Xt=l.useCallback(async()=>{if(!p||!Pt)return;const O=wf(),ce=[p];for(let Je=0;Je<ce.length;Je+=1){const ss=ce[Je];for(const Nt of O)Nt.parentID===ss&&!ce.includes(Nt.id)&&ce.push(Nt.id)}const ye=Pt;if(Tt(null),(ye==="archive"?await ct(ce):await Qe(ce)).failedIds.length>0){ie.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}ie.success(ye==="archive"?"Session archived":"Session deleted")},[ct,p,Qe,Pt]),us=de(O=>O.isArchivePageOpen),Ce=l.useMemo(()=>us?{title:"Archive",subtitle:null}:null,[us]),Oe=l.useMemo(()=>Mn(Se||k?.path||""),[k?.path,Se]),Ie=l.useCallback(()=>{Oe&&ps(Oe).then(O=>{ie[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ie.error("Failed to copy working directory"))},[Oe]),Be=l.useCallback(()=>{Ue&&ps(Ue).then(O=>{ie[O.ok?"success":"error"](O.ok?"Branch name copied":"Failed to copy branch name")}).catch(()=>ie.error("Failed to copy branch name"))},[Ue]),qe=l.useMemo(()=>k?{id:k.id,path:k.path}:null,[k]),mt=l.useRef(null);l.useEffect(()=>{!qe||!Oe||(mt.current={projectRef:qe,directory:Oe})},[Oe,qe]);const st=l.useMemo(()=>qe&&Oe?{projectRef:qe,directory:Oe}:mt.current,[Oe,qe]),Ze=l.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const ce=O.tagName;(ce==="INPUT"||ce==="TEXTAREA"||ce==="SELECT"||O.isContentEditable)&&O.blur()},[]),xs=l.useCallback(()=>{if(j){Ze(),c(!G);return}d()},[Ze,j,G,c,d]),Zt=l.useCallback(()=>{Kn("desktop_open_draft_mini_chat_window",{directory:Mn(Se||k?.path||""),projectId:k?.id??null,apiBaseUrl:$o(),clientToken:Uo()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[k?.id,k?.path,Se]),Ve=l.useCallback(()=>{if(y){Zt();return}p&&Kn("desktop_open_session_mini_chat_window",{sessionId:p,directory:Mn(Se||k?.path||""),apiBaseUrl:$o(),clientToken:Uo()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[k?.path,p,Zt,y,Se]),vt=vn,zt=fm,kt=l.useMemo(()=>n?"sessions":w?r&&o?o:null:r?"git":f,[f,w,n,r,o]),Ct=l.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&G&&c(!1)},[G,n,e,t,r,c]),Es=l.useCallback(()=>{e?.()},[e]),Hs=l.useCallback(()=>{t?.()},[t]),ys=l.useMemo(()=>W&&E&&!R?"5.5rem":B?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!W||F?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[W,R,E,B,F]);Re.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",ys)},[ys]);const Ds=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",gt=u?"0px":W&&F?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":C?"2.75rem":"2.5rem";Re.useEffect(()=>{if(!W||!E){T(!1);return}let O=!1;const ce=async()=>{try{const $e=await Kn("desktop_is_window_fullscreen");O||T($e===!0)}catch{O||T(!1)}},ye=()=>{ce()};return ce(),window.addEventListener("pichamber:window-resized",ye),()=>{O=!0,window.removeEventListener("pichamber:window-resized",ye)}},[W,E]);const Mt=l.useMemo(()=>!W||!E||q===null?"":q>=26?"h-12":q<=15?"h-14":"",[W,E,q]),St=l.useMemo(()=>{if(!(W&&!F))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))"}},[W,F]),es=l.useCallback(()=>{if(typeof document>"u")return;const O=z.current?.getBoundingClientRect().height;if(O){const ce=`${O}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==ce&&ye.setProperty("--oc-header-height",ce)}},[]);Re.useEffect(()=>{if(typeof window>"u")return;es();const O=z.current;if(!O||typeof ResizeObserver>"u")return()=>{};let ce=0;const ye=()=>{ce||(ce=requestAnimationFrame(()=>{ce=0,es()}))},$e=new ResizeObserver(ye);return $e.observe(O),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{ce&&cancelAnimationFrame(ce),$e.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[es]),Re.useEffect(()=>{es()},[es,j,Mt]);const ts=l.useCallback(async O=>{const ce=O.target;ce.closest(".app-region-no-drag")||ce.closest("button, a, input, select, textarea")||O.button===0&&W&&await vf()},[W]),at=l.useMemo(()=>j?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[j]),At=l.useCallback(O=>yi(Ir(O,x)),[x]);Re.useEffect(()=>{!j&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&m("chat")},[f,j,m]),Re.useEffect(()=>{const O=ce=>{if(dh(ce)&&!ce.shiftKey&&!ce.altKey){const ye=parseInt(ce.key,10);ye>=1&&ye<=at.length&&(ce.preventDefault(),j&&(Ze(),Ct()),m(at[ye-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[Ze,Ct,j,m,at]),Re.useEffect(()=>{const O=ce=>{const ye=Ir("toggle_services_menu",x);if(uh(ce,ye)){ce.preventDefault(),L?le(!1):(le(!0),X());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[x,L,X]);const Rs=O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon,it=O.id==="chat",Je=Nt=>ye?s.jsx(Xa,{size:Nt}):$e?s.jsx(P,{name:$e,className:`h-${Nt/4} w-${Nt/4}`}):null,ss=s.jsxs("button",{type:"button",onClick:()=>m(O.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ce?"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",it&&!j&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":ce,role:"tab",children:[j?Je(20):s.jsxs(s.Fragment,{children:[Je(16),s.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return s.jsx(l.Fragment,{children:ss},O.id)},Ft=s.jsxs(s.Fragment,{children:[s.jsx(uy,{directory:Oe,className:"mr-1"}),W?s.jsx(Ty,{isDesktopApp:W,currentInstanceLabel:H,compactCurrentInstanceLabel:ze,currentInstanceIsLocal:Pe,currentInstanceIcon:M,isDesktopServicesOpen:L,setIsDesktopServicesOpen:le,refreshCurrentInstanceLabel:X,shortcutLabel:At,remoteUpdateInfo:ae,remoteUpdateChecking:ge,remoteUpdateError:ve,onOpenRemoteUpdate:te}):s.jsx(Ry,{open:L,onOpenChange:le}),s.jsx(Py,{isMobile:j})]}),kn=K&&(y||!!p),qs=()=>s.jsxs("div",{onMouseDown:ts,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",Mt),style:St,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:Ds}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:gt}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Ce?s.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:[s.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:Ce.title}),Ce.subtitle?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-subtle-foreground max-w-full",children:Ce.subtitle})]}):null]}):s.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:s.jsx(l.Suspense,{fallback:s.jsx("button",{type:"button",className:vt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(Ly,{align:"start",children:s.jsx("button",{type:"button",className:vt,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Dt?s.jsxs("form",{ref:cs,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),rt()},children:[s.jsx("input",{value:Rt,onChange:O=>Bt(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&Xe(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>Xe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:y?"New session":se}),pe?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-subtle-foreground",children:[U?s.jsx("span",{className:"truncate",children:U}):null,Ue?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(P,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-subtle-foreground"}),s.jsx("span",{className:"truncate",children:Ue})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:p&&!y&&!Dt?s.jsxs(Yt,{open:Jt,onOpenChange:wt,onOpenChangeComplete:O=>{!O&&tt.current&&(tt.current=!1,ds())},children:[s.jsx(Vt,{asChild:!0,children:s.jsx(Ne,{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:s.jsx(P,{name:"more",className:"size-4"})})}),s.jsxs(Qt,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ft,{onClick:()=>{tt.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ft,{onClick:pt,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ft,{onClick:Ie,disabled:!Oe,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),Ue?s.jsxs(ft,{onClick:Be,children:[s.jsx(P,{name:"git-branch",className:"mr-2 size-4"}),"Copy branch name"]}):null,s.jsx(hn,{}),s.jsxs(ft,{onClick:()=>{_t()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(hn,{}),s.jsxs(ft,{onClick:()=>Tt("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ft,{className:"text-destructive focus:text-destructive",onClick:()=>Tt("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),at.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:at.map(O=>Rs(O))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(oc,{}),st?s.jsx(tl,{projectRef:st.projectRef,directory:st.directory,className:"mr-1"}):null,s.jsx(hm,{visible:kn,title:y?"New Mini Chat window":"Open session in Mini Chat",ariaLabel:y?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Ve,className:_(vt,"mr-1"),Icon:"picture-in-picture-2"}),Ft,s.jsx(Sf,{visible:F})]})]})]}),Cn=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[C&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:Ds}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:gt}})]}),!C&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:Es,className:_(zt,kt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(P,{name:"layout-left",className:"h-5 w-5"})}):G?s.jsx("button",{type:"button",onClick:()=>c(!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:s.jsx(P,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:xs,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:s.jsx(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&G&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!G||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!w&&s.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:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.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:at.map(O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon;return s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{j&&(Ze(),Ct()),m(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(zt,"relative rounded-lg",kt===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?s.jsx(Xa,{className:"h-5 w-5"}):$e?s.jsx(P,{name:$e,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),s.jsx(Ge,{children:s.jsx("p",{children:O.label})})]},O.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w&&s.jsxs(s.Fragment,{children:[s.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:v.map(O=>{const ce=r&&o===O.id;return s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{j&&(Ze(),Ct()),D(!1),i?.(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(zt,"relative h-11 w-11 rounded-lg",ce&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:O.icon,className:"h-5 w-5"})})}),s.jsx(Ge,{children:s.jsx("p",{children:O.label})})]},O.id)})}),s.jsx(um,{open:I,onOpenChange:D,currentSessionId:p,effectiveDirectory:Se||null,isNewSessionDraftOpen:y})]}),st&&s.jsx(tl,{projectRef:st.projectRef,directory:st.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!w?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Hs,className:_(zt,"relative",kt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(P,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ge,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Ps=_("header-safe-area relative z-10 bg-background",j&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:z,className:Ps,style:{"--padding-scale":"1"},children:j?Cn():qs()}),s.jsx(My,{action:Pt,onClose:()=>Tt(null),sessionTitle:se,onConfirm:()=>{Xt()}}),s.jsx(Ql,{open:Q,onOpenChange:ne,info:ae,downloading:!1,downloaded:!1,progress:null,error:ve,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},sl="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",Oy="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",wv=()=>{const e=de(y=>y.isSidebarOpen),t=de(y=>y.toggleSidebar),n=de(y=>y.shortcutOverrides),r=l.useRef(null),o=l.useRef(null),i=yi(Ir("toggle_sidebar",n)),a=Il(),{enabled:c}=bi(),d=!e,u=a,f=d||u,m=u,x=l.useCallback(()=>{Kn("desktop_show_app_menu").catch(y=>{console.warn("[titlebar] failed to open app menu",y)})},[]);return l.useEffect(()=>{if(typeof document>"u")return;const y=b=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(b)}px`)},p=b=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(b)}px`)};if(!m)return;const h=o.current,S=r.current;if(!h||!S){y(0),p(0);return}const g=()=>{const b=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(b),p(S.getBoundingClientRect().width)};if(g(),typeof ResizeObserver>"u")return;const k=new ResizeObserver(g);return k.observe(h),k.observe(S),()=>{k.disconnect()}},[m]),f?s.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:s.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(sl,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ge,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?Oy:sl,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(Ge,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},nl=200,By="cubic-bezier(0.22, 1, 0.36, 1)",vv=e=>{const t=l.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=l.useState(e),[o,i]=l.useState(e);return l.useLayoutEffect(()=>{if(t){i(e),r(e);return}if(e){i(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const a=window.setTimeout(()=>i(!1),nl);return()=>window.clearTimeout(a)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${nl}ms ${By}`}},Sv=()=>{Ll()},jv=e=>{Me.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),de.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),be.getState().clearAll(),Ll(),mn.getState().resetForRuntimeSwitch(),jf.getState().resetForRuntimeSwitch(),kf.getState().resetForRuntimeSwitch(),Cf(),fh(),hh(),Df(),Af.getState().resetForRuntimeSwitch(),Gt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ut.getState().resetForRuntimeSwitch(),Nf(),If(),Eh.getState().reset(),ph.getState().resetForRuntimeSwitch(),yl.getState().resetForRuntimeSwitch(e.runtimeKey),Bo.getState().resetForRuntimeSwitch(e.runtimeKey),mh(),Us.getState().resetForRuntimeSwitch(e.runtimeKey),Ef.getState().resetForRuntimeSwitch(),is.getState().resetForRuntimeSwitch(),yt.getState().resetForRuntimeSwitch(e.runtimeKey),gh.getState().resetForRuntimeSwitch(e.runtimeKey),Me.getState().restoreForRuntimeSwitch(e.runtimeKey),de.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=de.getState();Ho({sessionId:Me.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Mp as $,Hw as A,lw as B,Aw as C,Wa as D,Cw as E,ow as F,mw as G,yv as H,vi as I,hw as J,Pp as K,ec as L,rc as M,Gn as N,rw as O,Zp as P,cw as Q,Dp as R,dv as S,pv as T,Ql as U,Fp as V,ew as W,bw as X,Zl as Y,sr as Z,ww as _,um as a,Zw as a$,tr as a0,Xl as a1,gw as a2,aw as a3,Ep as a4,jw as a5,vw as a6,Kr as a7,Sw as a8,kw as a9,Gw as aA,Ww as aB,Dw as aC,$w as aD,Uw as aE,_w as aF,Hr as aG,qr as aH,Yr as aI,_s as aJ,Ac as aK,om as aL,im as aM,da as aN,xv as aO,_h as aP,Ms as aQ,ks as aR,is as aS,Cc as aT,pc as aU,Zn as aV,hc as aW,iw as aX,Xy as aY,Xw as aZ,qw as a_,yw as aa,dw as ab,uw as ac,fw as ad,zw as ae,Yp as af,pw as ag,Jl as ah,up as ai,Rp as aj,tw as ak,fp as al,cp as am,Rw as an,Iw as ao,Nw as ap,Ew as aq,Bw as ar,Ow as as,Tw as at,Pw as au,Mw as av,rm as aw,Lw as ax,Fw as ay,Kw as az,On as b,lv as b0,cv as b1,nm as b2,sv as b3,ev as b4,Vw as b5,tv as b6,rv as b7,ov as b8,iv as b9,av as ba,nv as bb,Jw as bc,Yw as bd,ri as be,Sa as bf,Fs as bg,Tn as bh,jn as bi,vg as bj,Sn as bk,Qw as bl,ux as c,uv as d,Cr as e,ny as f,fv as g,Lx as h,px as i,mv as j,Kc as k,vv as l,bv as m,wv as n,Sv as o,jv as p,sw as q,gv as r,hv as s,nw as t,cm as u,Zy as v,Jy as w,Tp as x,xw as y,Ip as z};
|