@pi-chamber/web 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{CommitSection-BQBmpPVE.js → CommitSection-DPjTv8fA.js} +1 -1
- package/dist/assets/{DiagramEditor-Cp22TGpq.js → DiagramEditor-ChOor9l9.js} +1 -1
- package/dist/assets/{DiagramView-E4HJ4ZPU.js → DiagramView-3hAT86v_.js} +1 -1
- package/dist/assets/{DiffView-d23o9CKP.js → DiffView-D1dyOiw2.js} +2 -2
- package/dist/assets/FilesView-BCzghrc7.js +14 -0
- package/dist/assets/{GitView-CkUONO1-.js → GitView-CYF1E1p4.js} +4 -4
- package/dist/assets/{JsonTreeView-By2oGMNK.js → JsonTreeView-CrJO6LNu.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-DUghE55t.js → MarkdownRendererImpl-BmKjrkGD.js} +2 -2
- package/dist/assets/{PatchDiff-BjN6zMtK.js → PatchDiff-DgvPLx6x.js} +1 -1
- package/dist/assets/{PierreDiffViewer-B38_7NnU.js → PierreDiffViewer-InnT0JVA.js} +2 -2
- package/dist/assets/{SessionSwitcherDropdown-NbVfnqQQ.js → SessionSwitcherDropdown-C0OdvirK.js} +102 -102
- package/dist/assets/{SettingsView-C2dCv0r7.js → SettingsView-JAfC_cBL.js} +1 -1
- package/dist/assets/{SettingsWindow-DsMhdX5H.js → SettingsWindow-BBEsjcJE.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DVesARmI.js → ToolOutputDialog-gzwcb8nI.js} +4 -4
- package/dist/assets/{ToolPartDiffPreview-C2N_oIO-.js → ToolPartDiffPreview-C45V5bhy.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-B7eVR6Pt.js → VirtualizedFileDiff-uKfnkQWb.js} +1 -1
- package/dist/assets/{collapsible-CPkWB1VR.js → collapsible-Bq8sDiKS.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BsZulefS.js → computeVirtualFileMetrics-BPgZ_RSe.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-BmmlK5E3.js → contextFileOpenGuard-CydO7PkI.js} +1 -1
- package/dist/assets/{index-C84KrQoy.js → index-BSuNNtBh.js} +1 -1
- package/dist/assets/{index-BhXma4dv.js → index-CH7o4-_q.js} +1 -1
- package/dist/assets/index-o4Eea60G.css +1 -0
- package/dist/assets/{isDiffPlainText-DsuyxFXo.js → isDiffPlainText-f9b4cKNo.js} +1 -1
- package/dist/assets/{isFilePlainText-CCYoe7us.js → isFilePlainText-BjESb-gU.js} +1 -1
- package/dist/assets/{main-ClYgYVm1.js → main-B508FBXr.js} +2 -2
- package/dist/assets/main-nG4uFyAy.js +133 -0
- package/dist/assets/{markdownCore-D2uqals1.js → markdownCore-BFmf8a-O.js} +2 -2
- package/dist/assets/{miniChat-DmX9SjxM.js → miniChat-BTlz8IPL.js} +2 -2
- package/dist/assets/{mobile-C-PCxN62.js → mobile-DBkrRt80.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-DW3fSR5w.js +1 -0
- package/dist/assets/renderMobileApp-9qkroKty.js +14 -0
- package/dist/assets/{runtimeSurface-CouGjZ3A.js → runtimeSurface-Bec4O8FD.js} +1 -1
- package/dist/assets/{useInlineCommentController-buNJ3xB4.js → useInlineCommentController-CHmIm0Rr.js} +2 -2
- package/dist/assets/usePanelSlide-DCX8qQ4K.js +56 -0
- package/dist/assets/{useWindowTitle-CnF4pKz0.js → useWindowTitle-CE5N_NeU.js} +3 -3
- package/dist/assets/{vendor-codemirror-autocomplete-3xMyV7a2.js → vendor-codemirror-autocomplete-BS2SpSAZ.js} +1 -1
- package/dist/assets/{vendor-codemirror-commands-Bzf12ODH.js → vendor-codemirror-commands-RrgJ8H_6.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-0K6s6cvb.js → vendor-codemirror-lang-angular-ADhO_TUK.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-B0aL03z-.js → vendor-codemirror-lang-cpp-BGCWj7Om.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-C4jEScp7.js → vendor-codemirror-lang-css-Ba8JZ6fp.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-CgrfVBPr.js → vendor-codemirror-lang-go-DyTiHXo4.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-C1Svvdey.js → vendor-codemirror-lang-html-DK27qQri.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-DNPz7_Bx.js → vendor-codemirror-lang-java-CvFfnhPQ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-CrbeaEAU.js → vendor-codemirror-lang-javascript-BUlYhQ3o.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-DL8BR_RG.js → vendor-codemirror-lang-jinja-wBMtAEvT.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-BTvAjwkJ.js → vendor-codemirror-lang-json-CqayksDf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-CPABt6NZ.js → vendor-codemirror-lang-less-Ct3-H1PB.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-BLOLOBMg.js → vendor-codemirror-lang-liquid-XspREksq.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-BloD9GN-.js → vendor-codemirror-lang-markdown-CvO36Y1p.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-FIZMTuWM.js → vendor-codemirror-lang-php-BlUF9cCe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-CR2g6ukK.js → vendor-codemirror-lang-python-_2bIYTiJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-lsPqn4k4.js → vendor-codemirror-lang-rust-BdTYih_U.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-CtECMwzH.js → vendor-codemirror-lang-sass-E6MhfOFk.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-BtmZrrZH.js → vendor-codemirror-lang-sql-B1BRhQSF.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-Br6DrntY.js → vendor-codemirror-lang-vue-BYQJRa1Q.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-DT7IlCnb.js → vendor-codemirror-lang-wast-D706yuyC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-wNr-LZOf.js → vendor-codemirror-lang-xml--MfWU6Dj.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-BTKFwfc2.js → vendor-codemirror-lang-yaml-CRUFIbRX.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-BuDklWi8.js → vendor-codemirror-language-E2vgV9K3.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-qBLdzwMc.js → vendor-codemirror-language-data-q1yHU1R9.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-BzyfPoRb.js → vendor-codemirror-search-8kyQdB3f.js} +1 -1
- package/dist/assets/{vendor-codemirror-state-Wdz6Qsow.js → vendor-codemirror-state-CNWM3Q8V.js} +1 -1
- package/dist/assets/{vendor-codemirror-view-pXtfpqbT.js → vendor-codemirror-view-DSzLbZiS.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-BUqe2Slv.js → vendor-replit-codemirror-vim-BJY5fGLS.js} +1 -1
- package/dist/assets/{web-components-BhO08KaW.js → web-components-CLirSfwt.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/dist/assets/FilesView-DIDB-xK7.js +0 -14
- package/dist/assets/index-BZXqJcua.css +0 -1
- package/dist/assets/main-CmrF_CaW.js +0 -133
- package/dist/assets/renderElectronMiniChatApp-BhXZtZlU.js +0 -1
- package/dist/assets/renderMobileApp-DUSTAPWw.js +0 -23
- package/dist/assets/usePanelSlide-BRwyEEzi.js +0 -47
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-C84KrQoy.js","assets/SessionSwitcherDropdown-NbVfnqQQ.js","assets/index-BhXma4dv.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-BZXqJcua.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-CouGjZ3A.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-base-ui-DwfTg5wD.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BuDklWi8.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-Wdz6Qsow.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-pXtfpqbT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-CrbeaEAU.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-3xMyV7a2.js","assets/vendor-codemirror-lang-json-BTvAjwkJ.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-C4jEScp7.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-C1Svvdey.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-BloD9GN-.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-qBLdzwMc.js","assets/vendor-codemirror-lang-python-CR2g6ukK.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-Bzf12ODH.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-dWA7qvjr.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/computeVirtualFileMetrics-BsZulefS.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-CCYoe7us.js","assets/isDiffPlainText-DsuyxFXo.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-B-cPXHXW.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{_ as Xs}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Ge,j as e,R as o}from"./vendor-react-DYyjh7Q0.js";import{bh as Wi,bi as Js,bj as rc,as as oc,o as Vi,D as hs,C as ps,G as vs,I as j,aC as Ls,bk as Bo,f as E,B as Ve,az as Bs,T as tt,y as st,z as nt,bl as Yi,bm as ic,bn as ac,bo as lc,bp as cc,m as Oe,bq as dc,br as _o,bs as uc,bt as fc,bu as Uo,bv as hc,bw as pc,bx as mc,by as gc,bz as Er,bA as xc,t as ne,aw as qt,ax as Qt,ay as Yt,a1 as nn,bB as bc,bC as yc,bD as vc,bE as wc,bF as zo,h as ts,bG as Sc,bH as jc,bI as Cc,bJ as kc,bK as Nc,bL as Ac,bM as Rr,bN as qi,bO as Qi,bP as Ic,bQ as Dc,bR as Pc,bS as Tc,bT as Ec,bU as Rc,b0 as Mr,r as en,bV as Us,bW as Mc,b2 as zs,b7 as Fc,b8 as Lc,b9 as Oc,ba as Bc,bb as hr,bc as cn,bX as $o,aD as ct,b as Lt,aW as $s,bY as Ji,E as Ds,H as Gs,J as Ks,bZ as _c,b_ as Ys,b$ as Go,c0 as Ko,c1 as un,c2 as Uc,c3 as Zi,c4 as zc,c5 as Xi,e as Wn,c6 as $c,K as Zn,R as ea,c7 as Gc,c8 as Wt,aR as ta,c as Fr,c9 as Kc,ca as Hc,cb as Xn,cc as Un,cd as sa,a3 as gn,a4 as xn,a2 as Wc,ce as Vc,cf as Ho,b1 as na,cg as Yc,ch as ra,b5 as oo,b6 as fn,ci as Wo,cj as er,aA as qc,ck as oa,N as Qc,cl as io,cm as Jc,cn as Zc,p as ia,s as Xc,co as ed,cp as td,q as sd,cq as Lr,w as nd,S as rd,aU as aa,cr as od,cs as id,v as ad,aE as As,ct as ld,cu as cd,cv as dd,d as ud,cw as fd,a as hd,aB as pd,b4 as md,cx as gd,b3 as xd,cy as bd,cz as yd,cA as vd,cB as wd,aj as Sd,cC as Vo,cD as jd,aS as Cd,cE as kd,cF as Nd,cG as In,cH as Yo,i as Ad,cI as Id,cJ as qo,cK as Qo,cL as Dd,aK as la,a8 as Pd,L as Td,cM as ca,u as Ed,cN as Rd,cO as Md,x as Fd,cP as Ld,cQ as da,cR as Od,cS as Bd,cT as _d,cU as Ud,cV as zd,cW as $d,cX as Gd,cY as Jo,cZ as Kd,c_ as Hd,c$ as ua,d0 as Wd,d1 as Vd}from"./SessionSwitcherDropdown-NbVfnqQQ.js";import{M as Zo,N as Yd,O as Xo,P as qd,i as Qd,Q as Jd,L as Zd,r as ss,u as oe,R as bn,b as Xd,K as ys,S as eu,T as gs,U as ao,o as lo,l as Is,V as pt,W as co,X as uo,Y as tu,Z as su,B as nu,_ as ru,$ as ou,a0 as iu,a1 as cs,a2 as Or,a as tr,a3 as au,a4 as lu,a5 as cu,a6 as du,a7 as fa,J as ha,C as hn,F as Br,e as _r,d as Dn,a8 as uu,a9 as fu,aa as dn,ab as pr,ac as pa,A as hu,n as pu,ad as Ur,ae as Os,af as ei,ag as zr,ah as ma,ai as $r,aj as mu,ak as gu,al as xu,t as bu,am as yu}from"./index-BhXma4dv.js";import{C as ga,a as xa,M as Gr,b as Kr,c as Hr,d as ba,S as ya,D as vu,e as wu,f as Su,g as ju,h as Cu,i as ku,j as Nu,k as Au}from"./vendor-base-ui-DwfTg5wD.js";import{c as ws,d as va,p as fo,u as Wr,a as Iu}from"./vendor-zustand-CnsBKjP5.js";import{u as Du}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as sr,d as yn,P as ho,D as nr,e as rr,f as wa,b as Pu,a as Tu,T as Eu,M as Ru}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as po,v as Sa,u as or,a as Mu,h as Fu}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as ir}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as Lu}from"./permissionStore-BRcQ9Jgt.js";const Ou=3;let Vn=0;const ja=[],Bu=()=>Vn<Ou?(Vn+=1,Promise.resolve()):new Promise(t=>{ja.push(t)}),_u=()=>{const t=ja.shift();if(t){t();return}Vn=Math.max(0,Vn-1)},Uu=async t=>{await Bu();try{return await t()}finally{_u()}},zu="chat";function Ca(t){const s=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&s.set(Js.SESSION,t.sessionId),t.isSettingsOpen){const n=t.settingsPath.trim().length>0?t.settingsPath:"home";return s.set(Js.SETTINGS,n),s}return t.tab!==zu&&s.set(Js.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&s.set(Js.FILE,t.diffFile),s}function $u(t,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,i=t.toString();return i?`${r}?${i}`:r}function Gu(t){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Ca(t),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has(Js.SESSION)&&s.set(Js.SESSION,i);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Vr(t,s={}){if(!(typeof window>"u")&&!Wi()&&!(!s.force&&Gu(t)))try{const n=Ca(t),r=$u(n);s.replace?window.history.replaceState({...window.history.state,route:t},"",r):window.history.pushState({route:t},"",r)}catch{}}const Ku=["typescript","javascript","tsx","jsx","json","markdown"],ka={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ti=null;const Na=()=>(ti??=Promise.all([Xs(()=>import("./index-C84KrQoy.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),Xs(()=>import("./workerFactory-tw7cIdmV.js"),[]),Xs(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,8,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([t,s,n])=>({WorkerPoolManager:t.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),ti),vn={},si=new Set,Yr=new Set;let zn={light:"pierre-light",dark:"pierre-dark"};const Hu=()=>{for(const t of Yr)t()},Aa=(t,s)=>{s.setRenderOptions({theme:zn,lineDiffType:ka[t].lineDiffType})},qr=t=>{typeof window>"u"||si.has(t)||(si.add(t),Na().then(s=>{if(vn[t])return;const n=ka[t],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Ku,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),vn[t]=r,Aa(t,r),Hu()}))},Wu=t=>(Yr.add(t),()=>Yr.delete(t)),Vu=t=>{if(!(zn.light===t.light&&zn.dark===t.dark)){zn=t;for(const s of Object.keys(vn)){const n=vn[s];n&&Aa(s,n)}}},Tg=({children:t})=>{const s=rc(),n=Zo(!1),r=Zo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Ge.useEffect(()=>{let d=!1;return Na().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),Vu({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Ge.useEffect(()=>{if(typeof window>"u")return;const d=()=>{qr("unified"),qr("split")};if(typeof window.requestIdleCallback=="function"){const x=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(x)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),e.jsx(e.Fragment,{children:t})},Eg=(t="unified")=>{const s=Ge.useSyncExternalStore(Wu,()=>vn[t],()=>{});return Ge.useEffect(()=>{qr(t)},[t]),s},ni="pichamber.update-install-id";function Yu(){if(!(typeof window>"u"||typeof crypto.randomUUID!="function"))try{const t=window.localStorage.getItem(ni)?.trim();if(t)return t;const s=crypto.randomUUID();return window.localStorage.setItem(ni,s),s}catch{return}}function qu(){if(typeof window>"u")return"unknown";try{const{deviceType:t}=oc();return t}catch{return"unknown"}}function Qu(){const t=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(t==="arm64"||t==="aarch64")return"arm64";if(t==="x64"||t==="amd64"||t==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function Ju(){const t=Xd();if(t==="android"||t==="ios")return t;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function Zu(t){const s=oe.getState().reportUsage,n=new URLSearchParams({reportUsage:s?"true":"false"});if(n.set("deviceClass",qu()),n.set("arch",Qu()),n.set("platform",Ju()),s&&(t==="desktop"||t==="mobile")){const r=Yu();r&&n.set("installId",r)}return t==="desktop"?(n.set("appType","desktop-electron"),n.set("instanceMode",bn()?"local":"remote"),n):t==="mobile"?(n.set("appType","mobile-capacitor"),n.set("instanceMode","remote"),n):(n.set("appType","web"),n.set("instanceMode","unknown"),n)}async function mr(t,s){try{const n=Zu(t);s&&n.set("currentVersion",s);const r=await ss(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function Xu(){return Qd()?"mobile":Jd()?"desktop":Zd()?"web":null}const ri={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},$n=ws()((t,s)=>({...ri,checkForUpdates:async()=>{const n=Xu();if(!n)return null;t({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.2.1",[l,c]=await Promise.allSettled([Xo(),mr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,t({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await mr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await mr("mobile","0.2.1"),i=r?.nextSuggestedCheckInSec??null);return t({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:i}),i}catch(r){return t({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){t({downloading:!0,error:null,progress:null});try{const i=await Xo();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(t(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await qd(l=>{t({progress:l})}))throw new Error("Desktop update only works on Local instance");t({downloading:!1,downloaded:!0})}catch(i){t({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Yd())throw new Error("Desktop restart only works on Local instance")}catch(i){t({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(ri)}})),oi="https://github.com/RyderAsKing/PiChamber/releases";function ef(t){const s=new Date(`${t}T00:00:00`);return Number.isNaN(s.getTime())?t:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function tf(t){return t.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function ii(t){return t.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function sf(t,s){const n=t.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function nf(t){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(t))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??t.length,c=t.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const ai=2e3,rf=600*1e3;async function of(){try{const t=await ss("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return t.ok?{success:!0,autoRestart:(await t.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await t.json().catch(()=>({}))).error||`Server error: ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:void 0}}}async function af(){try{return(await ss("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function lf(t,s=Math.ceil(rf/ai),n=ai){for(let r=0;r<s;r++){try{const i=await ss("/api/pi/update-check?reportUsage=false",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof t=="string"&&a.currentVersion!==t)return!0}else if((i.status===401||i.status===403)&&await af())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Ia=({open:t,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[x,g]=Ge.useState(!1),[v,b]=Ge.useState("idle"),[h,f]=Ge.useState(null),C=n?.version?n.releaseUrl||`${oi}/tag/v${n.version}`:oi,N=n?.downloadUrl||C,A=a?.total?Math.round(a.downloaded/a.total*100):0,S=u==="web",m=u==="mobile",p=n?.updateCommand||"pichamber update";Ge.useEffect(()=>{t||(b("idle"),f(null))},[t]);const I=async()=>{(await Bs(p)).ok&&(g(!0),setTimeout(()=>g(!1),2e3))},R=Ge.useCallback(async G=>{await Vi(G)},[]),D=Ge.useCallback(async()=>{b("updating"),f(null);const G=await of();if(!G.success){b("error"),f(G.error||"Update failed");return}G.autoRestart&&(b("restarting"),await new Promise(ce=>setTimeout(ce,2e3))),b("reconnecting"),await lf(n?.currentVersion)?window.location.reload():(b("error"),f("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),F=Ge.useCallback(()=>{R(N)},[R,N]),T=v!=="idle"&&v!=="error",U=Ge.useMemo(()=>{if(!n?.body)return null;const G=n.body.trim();if(!G)return null;const Y=nf(G);return Y.length===0?{kind:"raw",title:"What's new",content:ii(G)}:{kind:"sections",title:"What's new",sections:[...Y].sort((ae,W)=>sf(ae.version,W.version)).map(ae=>({version:ae.version,dateLabel:ef(ae.date),content:ii(tf(ae.raw)||G)}))}},[n?.body]);return e.jsx(hs,{open:t,onOpenChange:T?void 0:s,children:e.jsxs(ps,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[e.jsxs("div",{className:"flex items-center mb-1",children:[e.jsxs(vs,{className:"flex items-center gap-2.5",children:[e.jsx(j,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),e.jsx("span",{className:"text-lg font-semibold text-foreground",children:v==="restarting"||v==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&e.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&e.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&e.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&e.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),e.jsxs("div",{className:"space-y-2",children:[S&&T&&e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(j,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),e.jsxs("div",{className:"typography-ui-label text-foreground",children:[v==="updating"&&"Installing update...",v==="restarting"&&"Server restarting...",v==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),U&&!T&&e.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:e.jsx(Ls,{className:"max-h-[400px] p-0",fillContainer:!1,children:U.kind==="raw"?e.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:G=>{const ce=G.target.closest("a");ce&&ce.href&&(G.preventDefault(),G.stopPropagation(),R(ce.href))},children:e.jsx(Bo,{content:U.content,disableLinkSafety:!0,enableFileReferences:!1})}):e.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:U.sections.map(G=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",G.version]}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:G.dateLabel})]}),e.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:Y=>{const ae=Y.target.closest("a");ae&&ae.href&&(Y.preventDefault(),Y.stopPropagation(),R(ae.href))},children:e.jsx(Bo,{content:G.content,disableLinkSafety:!0,enableFileReferences:!1})})]},G.version))})})}),S&&v==="error"&&e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(j,{name:"terminal",className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.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:[e.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:p}),e.jsx("button",{onClick:I,className:E("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",x&&"text-[var(--status-success)]"),title:x?"Copied!":"Copy command",children:x?e.jsx(j,{name:"check",className:"h-4 w-4"}):e.jsx(j,{name:"clipboard",className:"h-4 w-4"})})]})]}),!S&&!m&&r&&e.jsxs("div",{className:"space-y-2 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),e.jsxs("span",{className:"font-mono text-foreground",children:[A,"%"]})]}),e.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${A}%`}})})]}),(l||h)&&e.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:e.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||h})})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[e.jsxs("a",{href:C,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:[e.jsx(j,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),e.jsxs("div",{className:"flex-1 flex justify-end",children:[!S&&!m&&!i&&!r&&e.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[e.jsx(j,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!S&&!m&&r&&e.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[e.jsx(j,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!S&&!m&&i&&e.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:[e.jsx(j,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),m&&e.jsxs(Ve,{onClick:F,size:"default",children:[e.jsx(j,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),S&&!T&&e.jsxs("button",{onClick:D,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[e.jsx(j,{name:"download",className:"h-4 w-4"}),"Update Now"]}),S&&T&&e.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[e.jsx(j,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},cf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return e.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":i,className:E("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:e.jsx("span",{"aria-hidden":!0,className:E("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),wn=({children:t,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),e.jsxs(tt,{open:r,onOpenChange:i,children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:E("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:e.jsx(j,{name:"information",className:"h-3.5 w-3.5"})})}),e.jsx(nt,{sideOffset:8,className:E("max-w-sm",n),children:t})]})},Rg="w-full min-w-40 max-w-48",df="settings",uf="w-full min-w-40 max-w-48",Mg="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",ff="w-full max-w-[24rem]",Fg="min-w-0 flex-1",Lg="flex w-full min-w-0 items-center gap-2",Og="typography-meta shrink-0 text-muted-foreground tabular-nums",Da="space-y-3.5",hf="space-y-1.5",Bg="typography-settings-page-title text-muted-foreground",pf="typography-settings-section-title text-foreground",_g="typography-settings-section-title text-foreground",Pa="typography-settings-group-title text-foreground",mo="typography-settings-field-label text-foreground",mf="typography-settings-description text-muted-foreground",Sn="typography-meta text-muted-foreground",Ug="typography-meta font-medium text-foreground",zg="typography-settings-section-title text-foreground",gf=({title:t,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const x=t!=null||s!=null||i!=null||r!=null;return e.jsxs("section",{"data-settings-item":u,className:E("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[x?e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[t!=null?e.jsxs("div",{className:"flex items-center gap-2",children:[typeof t=="string"||typeof t=="number"?e.jsx("h2",{className:pf,children:t}):t,n,r!=null?e.jsx(wn,{children:r}):null]}):null,s!=null?e.jsx("div",{className:mf,children:s}):null]}),i?e.jsx("div",{className:"shrink-0",children:i}):null]}):null,e.jsx("div",{className:E(d),children:a})]})},$g=({children:t,className:s})=>e.jsx("div",{className:E("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:t}),xf=({children:t,className:s,as:n="h3"})=>e.jsx(n,{className:E(Pa,s),children:t}),Gg=({title:t,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>e.jsxs("div",{"data-settings-item":l,className:E("space-y-2",i),children:[t!=null||s!=null||n!=null?e.jsxs("div",{className:"space-y-0.5",children:[t!=null?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(xf,{children:t}),n!=null?e.jsx(wn,{children:n}):null]}):null,s!=null?e.jsx("p",{className:Sn,children:s}):null]}):null,e.jsx("div",{className:E(a),children:r})]}),Zs=({label:t,description:s,info:n,descriptionPlacement:r="before",children:i,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?e.jsx("p",{className:Sn,children:s}):null;return e.jsxs("div",{"data-settings-item":a,className:E("space-y-2",l),children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:mo,children:t}),n!=null?e.jsx(wn,{children:n}):null]}),r==="before"?d:null]}),e.jsx("div",{className:E("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},Kg=({label:t,description:s,info:n,children:r,settingsItem:i,className:a,controlClassName:l,alignEnd:c=!0})=>e.jsxs("div",{"data-settings-item":i,className:E("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[e.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:mo,children:t}),n!=null?e.jsx(wn,{children:n}):null]}),s!=null?e.jsx("p",{className:E(Sn,"mt-0.5"),children:s}):null]}),e.jsx("div",{className:E("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Hg=({children:t,className:s,settingsItem:n})=>e.jsx("div",{"data-settings-item":n,className:E("pt-4",s),children:t}),bf=({checked:t,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const x=()=>{i||s(!t)},g=r!=null;return e.jsxs("div",{"data-settings-item":l,className:E("group flex cursor-pointer gap-2 py-0.5",g?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":t,"aria-disabled":i||void 0,onClick:x,onKeyDown:v=>{(v.key===" "||v.key==="Enter")&&(v.preventDefault(),x())},children:[e.jsx(Yi,{checked:t,onChange:s,disabled:i,ariaLabel:a}),e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx("span",{className:mo,children:n}),d,u!=null?e.jsx(wn,{children:u}):null]}),g?e.jsx("span",{className:Sn,children:r}):null]})]})},Wg=({selected:t,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>e.jsxs("div",{className:E("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":t,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[e.jsx(cf,{checked:t,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:E("typography-settings-field-label font-normal",t?"text-foreground":"text-foreground/50"),children:n}),r!=null?e.jsx("span",{className:Sn,children:r}):null]})]}),Vg=({"aria-label":t,children:s,className:n})=>e.jsx("div",{role:"radiogroup","aria-label":t,className:E(hf,n),children:s});function Yg({value:t,options:s,onChange:n,className:r,"aria-label":i}){return e.jsx("div",{role:"group","aria-label":i,className:E("flex flex-wrap items-center gap-1",r),children:s.map(a=>e.jsx(Ve,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":t===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class yf extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(ic,{className:"w-full max-w-md",children:[e.jsx(ac,{className:"text-center",children:e.jsxs(lc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(j,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),e.jsxs(cc,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),e.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(Ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(j,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function vf(t){return e.jsx(yf,{...t,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 qg=({active:t=!0,readOnly:s=!1})=>{const n=Oe(r=>r.currentSessionId);return e.jsx(vf,{sessionId:n||void 0,children:e.jsx(dc,{active:t,readOnly:s},n??"no-session")})};function wf({onResizeStart:t,ariaLabel:s}){return e.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:t,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:e.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const go=Ge.forwardRef(({className:t,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:x,endSlot:g,...v},b)=>{const h=Ge.useRef(null),f=Ge.useRef(null),[C,N]=Ge.useState(null),A=c??C,S=Ge.useCallback(p=>{const I=h.current;if(!I)return;f.current={startY:p.clientY,startHeight:I.getBoundingClientRect().height};const R=p.currentTarget;R.setPointerCapture(p.pointerId);const D=T=>{const U=f.current;if(!U)return;const G=U.startHeight+(T.clientY-U.startY),Y=Math.max(82,G);d?d(Y):N(Y)},F=()=>{f.current=null,R.removeEventListener("pointermove",D),R.removeEventListener("pointerup",F),R.removeEventListener("pointercancel",F)};R.addEventListener("pointermove",D),R.addEventListener("pointerup",F),R.addEventListener("pointercancel",F),p.preventDefault()},[d]),m=Ge.useCallback(p=>{if(p.target.closest('textarea, button, [role="separator"]'))return;const R=h.current?.querySelector("textarea");R&&document.activeElement!==R&&(p.preventDefault(),R.focus())},[]);return x?e.jsx(Ls,{as:"textarea",ref:b,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:E("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",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...v}):e.jsx("div",{ref:h,onPointerDown:m,style:A!==null?{height:`${A}px`}:void 0,className:E("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:e.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[e.jsx("textarea",{ref:b,className:E("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...v}),e.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[g,e.jsx(wf,{onResizeStart:S,ariaLabel:"Resize textarea"})]})]})})});go.displayName="Textarea";const li=(t,s)=>s.updatedAtMs-t.updatedAtMs,Yn=ws((t,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){t({isLoading:!0,error:null});try{const[n,r]=await Promise.all([pc(),Uo()]),i={};for(const a of r.sort(li))i[a.id]=a;s().listenerReady||await mc(a=>{t(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),t({instances:n.instances,statusesById:i,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){t({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!s().isImportsLoading){t({isImportsLoading:!0,error:null});try{const n=await hc();t({importCandidates:n,isImportsLoading:!1})}catch(n){t({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Uo(),r={};for(const i of n.sort(li))r[i.id]=i;t({statusesById:r})}catch(n){t({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{t({isSaving:!0,error:null});try{await fc({instances:n}),t({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw t({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=gc(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await _o(n).catch(()=>{});const r=s().instances.filter(i=>i.id!==n);await s().setInstances(r),t(i=>{const a={...i.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{t({error:null});try{await uc(n),await s().refreshStatuses()}catch(r){throw t({error:r instanceof Error?r.message:String(r)}),r}},disconnect:async n=>{t({error:null});try{await _o(n),await s().refreshStatuses()}catch(r){throw t({error:r instanceof Error?r.message:String(r)}),r}},retry:async n=>{await s().connect(n)},getStatus:n=>s().statusesById[n]||null,clearError:()=>t({error:null})})),Ta=[{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"}],pn=Object.fromEntries(Ta.map(t=>[t.key,t.Icon])),Qr="pichamber:project-actions-updated",Ea=t=>{const s=(t||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},xs=(t,s)=>`${Ea(t)}::${s}`,Sf=t=>{const s=t.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ci=t=>{if(typeof t!="number"||!Number.isFinite(t))return null;const s=Math.round(t);return s<1||s>65535?null:s},jf=(t,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ci(s.localPort),r=ci(s.remotePort);if(!n||!r)return null;const i=Sf(s.localHost||t.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(t.nickname||t.id||"instance").trim();return{id:`${t.id}::${s.id}`,label:`${l} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},Ra=t=>{const s=[];for(const n of t)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=jf(n,r);i&&s.push(i)}return s},Cf=(t,s)=>{const n=(t||"").trim();return n&&Ra(s).find(a=>a.id===n)?.url||null},kf=ff,Ma=({title:t,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>e.jsx(gf,{title:t,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Jr=t=>t.name.trim().length>0&&t.command.trim().length>0,Nf=t=>t.name.trim().length===0&&t.command.trim().length===0,Af=t=>!Jr(t)&&!Nf(t),If=(t,s)=>t.some(r=>s.has(r.id)&&!Jr(r))?{canPersist:!1,actions:t}:{canPersist:!0,actions:t.filter(Jr)},Df=450,Pf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Tf=()=>({id:Pf(),name:"",command:"",icon:"play"}),Ef=({projectRef:t})=>{const s=o.useMemo(()=>ys(),[]),n=Yn(p=>p.instances),r=Yn(p=>p.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[x,g]=o.useState(new Set),v=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let p=!1;return c(!0),(async()=>{try{const I=await Er(t);if(p)return;a(I.actions),u(JSON.stringify({actions:I.actions})),g(new Set(I.actions.map(R=>R.id)))}catch{if(p)return;a([]),u(JSON.stringify({actions:[]})),g(new Set)}finally{p||c(!1)}})(),()=>{p=!0}},[t]);const b=o.useMemo(()=>s?Ra(n):[],[n,s]),h=o.useMemo(()=>If(i,x),[i,x]),f=o.useMemo(()=>JSON.stringify({actions:h.actions}),[h.actions]),C=d!==null&&h.canPersist&&f!==d,N=o.useCallback(async p=>await xc(t,{actions:p,primaryActionId:null})?(u(JSON.stringify({actions:p})),g(new Set(p.map(R=>R.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Qr,{detail:{projectId:t.id}})),!0):(ne.error("Failed to save actions"),!1),[t]);o.useEffect(()=>{if(!C||l||v.current)return;const p=window.setTimeout(()=>{v.current||(v.current=!0,(async()=>{try{await N(h.actions)}finally{v.current=!1}})())},Df);return()=>{window.clearTimeout(p)}},[C,l,N,h.actions]);const A=o.useCallback(()=>{const p=Tf();a(I=>[...I,p])},[]),S=o.useCallback(p=>{a(I=>I.filter(R=>R.id!==p))},[]),m=o.useCallback((p,I)=>{a(R=>R.map(D=>D.id===p?I(D):D))},[]);return e.jsx(Ma,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:e.jsxs(Ve,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:A,children:[e.jsx(j,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):i.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):e.jsx("div",{className:E("space-y-6",kf),children:i.map((p,I)=>{const R=p.icon||"play",D=pn[R]||"play",F=p.name.trim()||`Action ${I+1}`,T=Af(p);return e.jsxs("div",{className:Da,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:Pa,children:F}),e.jsx(Ve,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>S(p.id),"aria-label":`Delete ${F}`,children:e.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),e.jsxs(Zs,{label:"Name",controlClassName:"w-full max-w-none",children:[e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.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:e.jsx(j,{name:D,className:"h-4 w-4"})})}),e.jsx(Yt,{align:"start",className:"w-56 p-2",children:e.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ta.map(U=>{const G=U.Icon,Y=(p.icon||"play")===U.key;return e.jsx("button",{type:"button",onClick:()=>m(p.id,ce=>({...ce,icon:U.key})),className:E("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",Y&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${U.label}`,children:e.jsx(j,{name:G,className:"h-4 w-4"})},U.key)})})})]}),e.jsx(nn,{value:p.name,onChange:U=>m(p.id,G=>({...G,name:U.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),e.jsx(Zs,{label:"Command",controlClassName:"w-full max-w-none",children:e.jsx(go,{value:p.command,onChange:U=>m(p.id,G=>({...G,command:U.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),T?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,e.jsx(bf,{checked:p.autoOpenUrl===!0,onChange:U=>m(p.id,G=>({...G,...U?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0,desktopOpenSshForward:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${F}`}),p.autoOpenUrl===!0?e.jsxs(e.Fragment,{children:[e.jsx(Zs,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:e.jsx(nn,{value:p.openUrl||"",onChange:U=>m(p.id,G=>({...G,openUrl:U.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?e.jsx(Zs,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:b.length>0?e.jsxs(bc,{value:p.desktopOpenSshForward&&b.some(U=>U.id===p.desktopOpenSshForward)?p.desktopOpenSshForward:"__none__",onValueChange:U=>{m(p.id,G=>({...G,...U==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:U}}))},children:[e.jsx(yc,{size:df,className:"w-full",children:e.jsx(vc,{placeholder:"Use output/manual URL"})}),e.jsxs(wc,{children:[e.jsx(zo,{value:"__none__",children:"Use output/manual URL"}),b.map(U=>e.jsx(zo,{value:U.id,children:U.label},U.id))]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},p.id)})})})},Rf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Mf=({value:t,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=ts(T=>T.providers),d=ts(T=>T.modelsMetadata),u=oe(T=>T.hiddenModels),x=oe(T=>T.providerOrder),g=oe(T=>T.setProviderOrder),v=oe(T=>T.isFavoriteModel),b=oe(T=>T.toggleFavoriteModel),h=oe(T=>T.reorderFavoriteModel),{favoriteModelsList:f,recentModelsList:C}=Sc(),[N,A]=o.useState(!1),[S,m]=o.useState("");o.useEffect(()=>{N||m("")},[N]);const p=t?c.find(T=>T.id===t.providerId):void 0,I=t&&p?(Array.isArray(p.models)?p.models:[]).find(T=>T.id===t.modelId):void 0,R=t?jc(I,t.modelId):s,D=o.useMemo(()=>t?u.filter(T=>!(T.providerID===t.providerId&&T.modelID===t.modelId)):u,[u,t]),F=o.useCallback(T=>{l({providerId:T.providerID,modelId:T.modelID}),A(!1)},[l]);return e.jsxs(qt,{modal:!1,open:N,onOpenChange:T=>{r||A(T)},children:[e.jsx(Qt,{asChild:!0,disabled:r,children:e.jsxs("button",{type:"button","aria-label":n,disabled:r,className:E(kc({size:"default"}),uf,"min-w-0",i),children:[e.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[t?.providerId?e.jsx(Cc,{providerId:t.providerId,className:"size-4 shrink-0"}):null,e.jsx("span",{className:E("truncate",t?"text-foreground":"text-muted-foreground"),children:R})]}),e.jsx(j,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),e.jsx(Yt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:e.jsx(Nc,{providers:c,favoriteModels:f,recentModels:C,modelsMetadata:d,searchQuery:S,onSearchQueryChange:m,onSelect:F,labels:{...Rf,notSelected:s},selectedModel:t?{providerID:t.providerId,modelID:t.modelId}:null,hiddenModels:D,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),A(!1)},disabled:r,autoFocus:!0,onEscape:()=>A(!1),isFavorite:T=>v(T.providerID,T.modelID),onToggleFavorite:T=>b(T.providerID,T.modelID),onReorderFavorite:(T,U)=>h(T.providerID,T.modelID,U.providerID,U.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:x,onReorderProvider:g,reorderProviderTitle:"Drag to reorder provider"})})]})},gr="w-full max-w-none",Ff=({form:t})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=t,l=ts(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?e.jsx(Ma,{title:"Project",divider:!1,children:e.jsxs("div",{className:Da,children:[e.jsx(Zs,{label:"Name",settingsItem:"projects.name",controlClassName:gr,children:e.jsx(nn,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),e.jsx(Zs,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:gr,children:e.jsx(Mf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:gr,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},Lf=t=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!t){n(""),i(void 0);return}n(t.label??""),i(t.defaultModel)},[t]);const a=o.useMemo(()=>Ac(r),[r]),l=!!t&&(s.trim()!==(t?.label??"").trim()||(r??void 0)!==(t?.defaultModel??void 0)),c=o.useCallback((u,x)=>{i(u&&x?`${u}/${x}`:void 0)},[]),d=o.useCallback(async()=>{if(!t)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,t]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:t}},Of=450,Bf=(t,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=t,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{ne.error("Failed to save project settings")}}finally{l.current=!1}})())},Of);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},_f=({project:t,onIdentitySave:s})=>{const n=Lf(t),r=o.useMemo(()=>t?{id:t.id,path:t.path}:null,[t]),i=o.useCallback(async a=>{await s(a)},[s]);return Bf(n,i),!t||!r?null:e.jsxs("div",{className:"space-y-0",children:[e.jsx(Ff,{form:n}),e.jsx(Ef,{projectRef:r})]})};function Uf({...t}){return e.jsx(ga,{...t})}function zf({...t}){return e.jsx(xa,{...t})}function $f({className:t,positionerClassName:s,children:n,style:r,...i}){return e.jsx(Gr,{children:e.jsx(Kr,{className:E("app-region-no-drag z-50",s),children:e.jsx(Hr,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:E(Rr,t),...i,children:n})})})}function di({className:t,...s}){return e.jsx(ba,{className:E(qi,t),...s})}function Gf({className:t,...s}){return e.jsx(ya,{className:E(Qi,t),...s})}const Fs=ws()(va(fo((t,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{t({selectedProfileId:n})},loadProfiles:async()=>{t({isLoading:!0});const n=s().profiles;try{const r=await Rc();return t({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),t({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await Ec();if(n&&n.userName&&n.userEmail){const r={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};t({globalIdentity:r})}else t({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),t({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await Tc();return t({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),t({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const i=r.trim();return i.length>0?i:null};try{let r=null;if(r===null){const i=lo()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await ss("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return t({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await ao({defaultGitIdentityId:i}),t({defaultGitIdentityId:i.length>0?i:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return gs("saving"),await Pc(r),gs("saved"),await s().loadProfiles(),!0}catch(r){return gs("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return gs("saving"),await Dc(n,a),gs("saved"),await s().loadProfiles(),!0}catch(i){return gs("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return gs("saving"),await Ic(n),gs("saved"),s().selectedProfileId===n&&t({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return gs("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:eu(),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Fs);const Kf=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"split",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"content",kind:"split",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"content",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"content",kind:"split",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"Magic Prompts",group:"content",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request"]},{slug:"snippets",title:"Snippets",group:"content",kind:"split",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"]},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Hf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Wf(t){const s=t.trim().toLowerCase();return Kf.find(n=>n.slug===s)??null}function Vf(t){const s=(t??"").trim().toLowerCase();if(!s)return"home";const n=Hf[s];if(n)return n;const r=Wf(s);return r?r.slug:"home"}function Qg(t){switch(t){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"magic-prompts":return"ai-generate-2";case"snippets":return"chat-thread";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const Pn=100;function Jg(){const t=oe(D=>D.isArchivePageOpen),s=oe(D=>D.setArchivePageOpen),n=oe(D=>D.setActiveMainTab),r=Oe(D=>D.setCurrentSession),i=Oe(D=>D.unarchiveSession),a=Is(D=>D.homeDirectory),l=Mr({archived:!0}),[c,d]=o.useState(""),[u,x]=o.useState(null),[g,v]=o.useState(Pn),b=c.trim().toLowerCase(),h=o.useMemo(()=>t?[...l].sort((D,F)=>(F.time?.archived??0)-(D.time?.archived??0)):[],[l,t]),f=o.useMemo(()=>{const D=new Map;for(const F of h){const T=pt(en(F))??"",U=D.get(T);if(U){U.sessions.push(F);continue}D.set(T,{directory:T,label:T?Us(T,a)||T:"other projects",sessions:[F]})}return[...D.values()].sort((F,T)=>T.sessions.length-F.sessions.length)},[a,h]),C=o.useMemo(()=>b?h.filter(D=>(D.title??"").toLowerCase().includes(b)):u===null?h:f.find(D=>D.directory===u)?.sessions??[],[f,b,u,h]),N=C.slice(0,g),A=C.length-N.length,S=l.length,m=o.useCallback(D=>{x(D),v(Pn)},[]),p=o.useCallback(D=>{const F=pt(en(D));r(D.id,F??void 0),n("chat"),s(!1)},[n,r,s]),I=o.useCallback(D=>{i(D.id).then(F=>{F?ne.success("Session restored"):ne.error("Failed to restore session")})},[i]);if(!t)return null;const R=(D,F,T,U,G,Y,ce)=>e.jsxs("div",{className:"group/dir relative",children:[e.jsxs("button",{type:"button",onClick:G,title:Y,className:E("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",ce?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",U?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate",children:F}),e.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:T})]}),ce?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>zs.requestDelete({sessions:ce,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 ${F}`,children:e.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},D);return e.jsx(vu,{open:t,onOpenChange:s,children:e.jsxs(wu,{children:[e.jsx(Su,{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"}),e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:e.jsxs(ju,{className:"pointer-events-auto 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:[e.jsxs("div",{className:"flex h-12 shrink-0 items-center justify-between border-b border-border/70 bg-sidebar px-4",children:[e.jsxs(Cu,{className:"flex items-center gap-2 typography-ui-label font-medium text-foreground",children:[e.jsx(j,{name:"archive",className:"size-4 text-muted-foreground"}),"Archived sessions"]}),e.jsx("button",{type:"button",onClick:()=>s(!1),className:"inline-flex size-8 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":"Close archived sessions",children:e.jsx(j,{name:"close",className:"size-4"})})]}),e.jsx(ku,{className:"sr-only",children:"Browse and restore archived sessions."}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[e.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:e.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[R("__all__","All directories",S,u===null,()=>m(null)),f.map(D=>R(D.directory||"__none__",D.label,D.sessions.length,u===D.directory,()=>m(D.directory),D.directory||void 0,D.sessions))]})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-3 px-6 pt-3",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(j,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx("input",{value:c,onChange:D=>{d(D.target.value),v(Pn)},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"})]}),e.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:C.length===1?`${C.length} archived session`:`${C.length} archived sessions`})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[N.length===0?e.jsx("div",{className:"py-10 text-center text-muted-foreground",children:e.jsx("p",{className:"typography-ui-label font-semibold",children:b?"No matching archived sessions":"No archived sessions"})}):N.map(D=>{const F=pt(en(D))??"",T=F?Us(F,a)||F:null;return e.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:()=>p(D),role:"button",tabIndex:0,onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),p(D))},children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:D.title||"Untitled Session"}),b&&T?e.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:F,children:T}):null,e.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Mc(D.time?.archived??D.time?.updated??D.time?.created??Date.now())}),e.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),I(D)},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 ${D.title||"Untitled Session"}`,children:e.jsx(j,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:U=>{U.stopPropagation(),zs.requestDelete({sessions:[D],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 ${D.title||"Untitled Session"}`,children:e.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},D.id)}),A>0?e.jsx("button",{type:"button",onClick:()=>v(D=>D+Pn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const Yf=()=>{const[t,s]=Ge.useState(!1),[n,r]=Ge.useState(!1);Ge.useEffect(()=>{s(ys()),r(co())},[]);const i=Ge.useCallback(async c=>t?await uo(c):{success:!0,path:c},[t]),a=Ge.useCallback(async c=>t?await tu():{success:!0},[t]),l=Ge.useCallback(async c=>t?await su():{success:!0},[t]);return{isDesktop:t,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},qf=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Qf=({currentBranch:t,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[x,g]=o.useState(""),[v,b]=o.useState(!1),[h,f]=o.useState(!1),[C,N]=o.useState(""),[A,S]=o.useState(!1),m=o.useRef(null),p=o.useCallback(W=>{W.stopPropagation()},[]),I=l.length>1,R=o.useMemo(()=>qf(C),[C]),D=o.useMemo(()=>{const W=x.toLowerCase();return W?s.filter(Q=>Q.toLowerCase().includes(W)):s},[x,s]),F=o.useMemo(()=>{const W=x.toLowerCase();return W?n.filter(Q=>Q.toLowerCase().includes(W)):n},[x,n]),T=W=>{if(W===t){u(!1);return}i(W),u(!1),g("")},U=()=>{b(!0),setTimeout(()=>m.current?.focus(),50)},G=async()=>{if(!(!R||A)){if(I){f(!0);return}S(!0);try{await a(R,l[0]),N(""),b(!1),u(!1)}finally{S(!1)}}},Y=async W=>{if(!(!R||A)){S(!0);try{await a(R,W),N(""),b(!1),f(!1),u(!1)}finally{S(!1)}}},ce=()=>{f(!1)},ae=()=>{N(""),b(!1),f(!1)};return o.useEffect(()=>{d||(g(""),b(!1),f(!1),N(""))},[d]),e.jsxs(qt,{open:d,onOpenChange:u,children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx(Qt,{asChild:!0,children:e.jsxs(Ve,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[e.jsx(j,{name:"git-branch",className:"size-4 text-primary"}),e.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:t||"Detached HEAD"}),e.jsx(j,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),e.jsx(nt,{sideOffset:8,children:"Current branch"})]}),e.jsx(Yt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Fc,{className:"h-full min-h-0",children:[e.jsx(Lc,{placeholder:"Search branches...",value:x,onValueChange:g,onKeyDown:p}),e.jsxs(Oc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Bc,{children:"No branches found."}),e.jsx(hr,{children:h?e.jsxs("div",{className:"px-2 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{type:"button",onClick:ce,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(j,{name:"arrow-left",className:"size-4"})}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",e.jsx("span",{className:"text-foreground font-medium",children:R})," ","Push To Suffix"]})]}),e.jsx("div",{className:"flex flex-col gap-1",children:l.map(W=>e.jsxs("button",{type:"button",onClick:()=>Y(W),disabled:A,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[e.jsxs("span",{className:"typography-ui-label text-foreground",children:[A?e.jsx(j,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,W.name]}),e.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:W.pushUrl})]},W.name))})]}):v?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:m,placeholder:"New branch name",value:C,onChange:W=>N(W.target.value),onClick:W=>W.stopPropagation(),onKeyDown:W=>{p(W),W.key==="Enter"?(W.preventDefault(),G()):W.key==="Escape"&&(W.preventDefault(),ae())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:G,disabled:!R||A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:A?e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(j,{name:"add",className:"size-4"})}),e.jsx("button",{type:"button",onClick:ae,disabled:A,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(j,{name:"close",className:"size-4"})})]}):e.jsxs(cn,{onSelect:U,children:[e.jsx(j,{name:"add",className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx($o,{}),e.jsxs(hr,{heading:"Local branches",children:[D.map(W=>e.jsxs(cn,{onSelect:()=>T(W),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:W}),(r?.[W]?.ahead||r?.[W]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[W].ahead||0," ahead ·"," ",r[W].behind||0," behind"]})]}),t===W&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${W}`)),D.length===0&&e.jsx(cn,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx($o,{}),e.jsxs(hr,{heading:"Remote branches",children:[F.map(W=>e.jsx(cn,{onSelect:()=>T(W),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:W})},`remote-${W}`)),F.length===0&&e.jsx(cn,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Jf=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Zf=({currentBranch:t,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(t||""),[c,d]=o.useState(!1),u=o.useRef(null),x=()=>{!t||!s||(l(t),i(!0),setTimeout(()=>u.current?.focus(),0))},g=async()=>{if(!t||!s||!a.trim())return;const h=Jf(a);if(h===t){i(!1);return}d(!0);try{await s(t,h),i(!1),l("")}finally{d(!1)}},v=()=>{i(!1),l("")},b=h=>{h.key==="Enter"?(h.preventDefault(),g()):h.key==="Escape"&&(h.preventDefault(),v())};return r?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),g()},children:[e.jsx(j,{name:"git-branch",className:"size-4 text-primary"}),e.jsx("input",{ref:u,value:a,onChange:h=>l(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:b,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(j,{name:"check",className:"size-4"})}),e.jsx("button",{type:"button",onClick:v,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(j,{name:"close",className:"size-4"})})]})}):e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(j,{name:"git-branch",className:"size-4 text-primary shrink-0"}),e.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:t||"Detached HEAD"}),n&&s&&t&&e.jsx(Ve,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:x,title:"Rename branch",children:e.jsx(j,{name:"edit",className:"size-4"})})]})]})},Xf=({syncAction:t,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:x=!1})=>{const g=o.useRef(!1),v=!!l,b=s.find(p=>p.name===u)??s[0],h=d>0&&x,f=a||t!==null||v||!b||h,C=a||t!==null||v||s.length===0,N=c>0||d>0,A=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),S=h?"Commit or stash your changes before syncing":b?N?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",m=()=>{b&&r(b)};return e.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("span",{className:"inline-flex",tabIndex:h?0:void 0,children:e.jsxs("button",{type:"button",onClick:m,disabled:f,className:E("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[t==="sync"?e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(j,{name:"refresh",className:"size-4"}),e.jsx("span",{className:"whitespace-nowrap tabular-nums",children:A})]})})}),e.jsx(nt,{sideOffset:8,children:S})]}),e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:E("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:C,"aria-label":"More sync actions",children:e.jsx(j,{name:"arrow-down-s",className:"size-4"})})}),e.jsx(Yt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(p=>e.jsx(ct,{onSelect:I=>{if(g.current){I.preventDefault(),g.current=!1;return}n(p)},children:e.jsxs("div",{className:"flex w-full items-center gap-2",children:[e.jsx(j,{name:"refresh",className:"size-4 text-muted-foreground"}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${p.name}`}),e.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:p.fetchUrl})]})}),i&&p.name!==u?e.jsx(Ve,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:t!==null||v,onPointerDown:I=>{g.current=!0,I.preventDefault(),I.stopPropagation()},onClick:I=>{g.current=!0,I.preventDefault(),I.stopPropagation(),i(p)},"aria-label":`Remove remote ${p.name}`,title:`Remove remote ${p.name}`,children:l===p.name?e.jsx(j,{name:"loader-4",className:"size-3.5 animate-spin"}):e.jsx(j,{name:"close",className:"size-3.5"})}):null]})},p.name))})]})]})},eh={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},th={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Fa(t){return t&&th[t]||"var(--primary)"}const ui=({icon:t,className:s,colorToken:n})=>{const r=eh[t??"branch"]??"user-3";return e.jsx(j,{name:r,className:s,style:{color:Fa(n)}})},La=({activeProfile:t,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return e.jsxs(qt,{children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx(Qt,{asChild:!0,children:e.jsxs(Ve,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:Fa(t?.color)},disabled:a,children:[r?e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):e.jsx(ui,{icon:t?.icon,colorToken:t?.color,className:"size-4"}),!i&&e.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:t?.name||"No identity"}),e.jsx(j,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),e.jsx(nt,{sideOffset:8,children:"Git identity"})]}),e.jsx(Yt,{align:"end",className:"w-64",children:s.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=t?.id===l.id;return e.jsx(ct,{onSelect:()=>n(l),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ui,{icon:l.icon,colorToken:l.color,className:"size-4"}),e.jsxs("span",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?e.jsx(j,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},sh=({comparison:t,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${t.remote}/${t.branch}`,i=t.ahead===0&&t.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return e.jsxs(tt,{delayDuration:n,children:[e.jsx(st,{asChild:!0,children:e.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[e.jsx(j,{name:"git-branch",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?e.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):e.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[t.ahead>0?e.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",t.ahead]}):null,t.behind>0?e.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",t.behind]}):null]})]})}),e.jsx(nt,{sideOffset:8,children:a})]})},Zg=({status:t,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:x,onCreateBranch:g,onRenameBranch:v,activeIdentityProfile:b,availableIdentities:h,onSelectIdentity:f,isApplyingIdentity:C,isWorktreeMode:N,onOpenHistory:A,onOpenGraph:S,onOpenStashes:m,onOpenUpdateBranch:p,onOpenReintegrateCommits:I,pullRequest:R,prChecks:D,onOpenPullRequest:F})=>{if(!t)return null;const T=e.jsx("div",{className:"flex items-center gap-1 shrink-0",children:A||S||m||p?e.jsxs(qt,{children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx(Qt,{asChild:!0,children:e.jsx(Ve,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:e.jsx(j,{name:"more-fill",className:"size-4"})})})}),e.jsx(nt,{sideOffset:8,children:"Repository views"})]}),e.jsxs(Yt,{align:"end",children:[A?e.jsxs(ct,{onSelect:A,children:[e.jsx(j,{name:"history",className:"size-4"}),"History"]}):null,S?e.jsxs(ct,{onSelect:S,children:[e.jsx(j,{name:"git-branch",className:"size-4"}),"Graph"]}):null,m?e.jsxs(ct,{onSelect:m,children:[e.jsx(j,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,p?e.jsxs(ct,{onSelect:p,children:[e.jsx(j,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,I?e.jsxs(ct,{onSelect:I,children:[e.jsx(j,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),U=D?D.state==="success"?"var(--status-success)":D.state==="failure"?"var(--status-error)":"var(--status-warning)":null,G=R?R.state==="merged"?"merged":R.state==="closed"?"closed":R.draft?"draft":D?.state==="failure"||R.mergeable===!1||R.mergeableState==="blocked"||R.mergeableState==="dirty"?"blocked":"open":null,Y=R&&F?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsxs(Ve,{variant:"ghost",size:"sm",onClick:F,className:"h-8 gap-1.5 px-2 typography-micro",children:[e.jsx(j,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${G})`}}),e.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${R.number}`}),U?e.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:U}}):null]})}),e.jsx(nt,{sideOffset:8,children:"Open pull request"})]}):null,ce=e.jsx(Xf,{syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!t,iconOnly:!0,aheadCount:t.ahead,behindCount:t.behind,trackingRemoteName:t.tracking?.split("/")[0],hasUncommittedChanges:(t.files?.length??0)>0}),ae=t.upstreamComparison?e.jsx(sh,{comparison:t.upstreamComparison,trackingBranch:t.tracking,tooltipDelayMs:1e3}):null,W=e.jsx(La,{activeProfile:b,identities:h,onSelect:f,isApplying:C,iconOnly:!0});return e.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[e.jsx("div",{className:"min-w-0 flex-1",children:N?e.jsx(Zf,{currentBranch:t.current,onRename:v}):e.jsx(Qf,{currentBranch:t.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:x,onCreate:g,remotes:a})}),e.jsx("div",{className:"flex shrink-0 items-center gap-1",children:W})]}),e.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[Y?e.jsx("div",{className:"shrink-0",children:Y}):null,e.jsx("div",{className:"min-w-0 flex-1"}),ae?e.jsx("div",{className:"min-w-0 shrink",children:ae}):null,T,e.jsx("div",{className:"shrink-0",children:ce})]})]})},nh=t=>t==="/",tn=t=>t.replace(/\\/g,"/"),rn=t=>{if(!t||nh(t))return t;let s=t;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},sn=t=>t.endsWith("/"),qn=t=>{const s=t.trim();return!s||sn(s)?s:`${s}/`},xo=t=>t.lastIndexOf("/"),Oa=t=>{if(sn(t))return t;const s=xo(t);return s<0?t:t.slice(0,s+1)},Ba=t=>{const s=xo(t);return t.slice(s+1)},_a=t=>{const s=rn(t.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=xo(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Ua=t=>sn(t)&&_a(t)!==null,rh=t=>{if(!Ua(t))return null;const s=rn(t.trim());return Ba(s)||s},oh=(t,s)=>`${Oa(t)}${s}/`,Es=t=>{if(!t)return null;const s=rn(tn(t.trim()));return s?s.toLowerCase():null},fi=(t,s)=>{const n=t.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},ih=(t,s)=>{const n=rn(tn(t.trim())),r=rn(tn(s.trim()));if(!n)return"";if(!r)return qn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:qn(n)},ah=t=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?t.metaKey&&!t.ctrlKey:t.ctrlKey&&!t.metaKey,xr=t=>{if(!t)return;t.focus({preventScroll:!0});const s=t.value.length;t.setSelectionRange(s,s),t.scrollLeft=t.scrollWidth},lh=async()=>iu(),ch=({open:t,onOpenChange:s})=>{const n=Is(P=>P.homeDirectory),r=Lt(P=>P.projects),i=Lt(P=>P.addProject),a=oe(P=>P.setActiveMainTab),l=oe(P=>P.setSessionSwitcherOpen),c=Oe(P=>P.openNewSessionDraft),d=Fs(P=>P.profiles),u=Fs(P=>P.globalIdentity),x=Fs(P=>P.defaultGitIdentityId),g=Fs(P=>P.loadProfiles),v=Fs(P=>P.loadGlobalIdentity),b=Fs(P=>P.loadDefaultGitIdentityId),{canRequestAccess:h,startAccessing:f}=Yf(),{isMobile:C}=$s(),N=o.useRef(null),A=o.useRef(new Map),[S,m]=o.useState(""),[p,I]=o.useState("~/"),[R,D]=o.useState([]),[F,T]=o.useState(!1),[U,G]=o.useState(!1),[Y,ce]=o.useState(null),[ae,W]=o.useState(0),[Q,B]=o.useState(0),[L,J]=o.useState(!1),[fe,$]=o.useState(!1),[Ce,we]=o.useState(!1),[We,$e]=o.useState(""),[Be,Ie]=o.useState(null),[Z,Se]=o.useState(!1),[rt,Ne]=o.useState("right"),ye=o.useRef("~/"),Re=S||n,Qe=o.useMemo(()=>new Set(r.map(P=>Es(P.path)).filter(P=>!!P)),[r]);o.useEffect(()=>{if(!t)return;I("~/"),D([]),B(0),J(!1),$(!1),we(!1),$e(""),Ie(null),Se(!1),ye.current="~/",Ne("right"),requestAnimationFrame(()=>xr(N.current));let P=!1;return(async()=>{const Le=await lh();P||(m(Le||n||""),requestAnimationFrame(()=>xr(N.current)))})(),()=>{P=!0}},[n,t]),o.useEffect(()=>{t&&(g(),v(),b())},[b,g,v,t]);const ze=o.useMemo(()=>{const P=new Map;u&&P.set(u.id,u);for(const Pe of d)P.set(Pe.id,Pe);return Array.from(P.values())},[d,u]);o.useEffect(()=>{if(!t||!Ce||Be!==null)return;const P=typeof x=="string"?x.trim():"";if(P&&ze.some(Le=>Le.id===P)){Ie(P);return}const Pe=ze.find(Le=>Le.authType==="ssh"||Le.sshKey);Pe&&Ie(Pe.id)},[ze,x,Ce,t,Be]);const q=o.useMemo(()=>ze.find(P=>P.id===Be)??null,[ze,Be]),V=o.useMemo(()=>Oa(p),[p]),ge=o.useMemo(()=>sn(p)?"":Ba(p),[p]),H=o.useMemo(()=>Re?fi(V,Re):"",[V,Re]);o.useEffect(()=>{const P=ye.current;P!==V&&(Ne(V.length>=P.length?"right":"left"),ye.current=V)},[V]),o.useEffect(()=>{if(!t||!H){D([]),ce(null);return}let P=!1;return T(!0),G(!1),ce(null),nu(H).then(Pe=>{if(P)return;G(!1),ce(null);const Le=Pe.filter(He=>He.isDirectory).map(He=>({name:He.name,path:tn(He.path)})).sort((He,ut)=>He.name.localeCompare(ut.name));D(Le)}).catch(Pe=>{if(!P){D([]);const Le=ru(Pe)?Pe.reason:"unknown";ce(Le),G(Le==="not-found")}}).finally(()=>{P||T(!1)}),()=>{P=!0}},[H,ae,t]);const xe=o.useMemo(()=>{const P=ge.toLowerCase(),Pe=Z||ge.startsWith(".");return R.filter(Le=>Le.name.toLowerCase().startsWith(P)&&(Pe||!Le.name.startsWith(".")))},[ge,R,Z]),ve=o.useMemo(()=>rh(p),[p]),Me=o.useMemo(()=>_a(p),[p]),Xe=o.useMemo(()=>{const P=[],Pe=Es(H);Ua(p)&&ve&&Me&&P.push({type:"parent",value:"browse:up",name:ve,path:Me,alreadyAdded:!!(Pe&&Qe.has(Pe))});for(const Le of xe){const He=Es(Le.path);P.push({type:"directory",value:`browse:${Le.path}`,name:Le.name,path:Le.path,alreadyAdded:!!(He&&Qe.has(He))})}return P},[Qe,H,ve,xe,Me,p]);o.useEffect(()=>{B(0)},[p,Xe.length]);const at=o.useMemo(()=>Re?rn(fi(p,Re)):"",[Re,p]),dt=Es(at),Ue=!!(dt&&Qe.has(dt)),Ae=o.useMemo(()=>ge?xe.find(P=>P.name===ge)??null:null,[ge,xe]),Je=!!(at&&!Ue&&(Y===null||Y==="not-found")&&(sn(p)&&U||!sn(p)&&ge.trim().length>0&&Ae===null)),it=!L&&!fe&&!Ue&&Y!=="os-permission"&&Y!=="invalid-response"&&Y!=="unknown"&&!!at,wt=it&&We.trim().length>0,yt=Xe[Q]??null,O=!!yt,pe=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",De=Ue?"Already added":Ce?L?"Cloning...":"Clone & add":L?"Adding...":Je?"Create & add":"Add folder",y=Ce?wt:it;o.useLayoutEffect(()=>{const P=N.current;P&&(P.scrollLeft=P.scrollWidth)},[p]),o.useLayoutEffect(()=>{t&&xr(N.current)},[t]),o.useLayoutEffect(()=>{const P=Xe[Q];P&&A.current.get(P.value)?.scrollIntoView({block:"nearest"})},[Q,Xe]);const z=o.useCallback(()=>{s(!1)},[s]),X=o.useCallback((P,Pe)=>{a("chat"),C&&l(!1),c({selectedProjectId:P,directoryOverride:Pe}),z()},[z,C,c,a,l]),ue=o.useCallback(async P=>{if(!P||L)return;const Pe=Es(P);if(Pe&&Qe.has(Pe))return;let Le=P;J(!0);try{const He=!Ce&&Je&&Es(P)===Es(at);if(Ce){const _t=We.trim();if(!_t){ne.error("Enter a repository URL before cloning.");return}const M=await ss("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:_t,destinationPath:P,gitIdentityId:q?.id??null})});if(!M.ok)throw new Error("Failed to clone git repository");Le=(await M.json()).path||P}else if(He&&!(await ss("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:H?{directory:H}:void 0,body:JSON.stringify({path:P})})).ok)throw new Error("Failed to select directory");const ut=i(Le);if(!ut){ne.error("Failed to add folder",{description:"Please select a valid directory path."});return}X(ut.id,ut.path)}catch(He){ne.error("Failed to select directory",{description:He instanceof Error?He.message:"Unknown error occurred."})}finally{J(!1)}},[i,Qe,H,We,Ce,L,X,q?.id,Je,at]),he=o.useCallback(P=>{I(qn(P))},[]),Ee=o.useCallback(P=>{I(oh(p,P.name))},[p]),Ke=o.useCallback(P=>{if(P){if(P.type==="parent"){he(P.path);return}Ee(P)}},[he,Ee]),ft=o.useCallback(async P=>{const Pe=await f(P);if(!Pe.success)return ne.error("Failed to open directory",{description:Pe.error||"Desktop could not grant file access."}),!1;const Le=Re?ih(P,Re):qn(tn(P));return he(Le),!0},[he,Re,f]),At=o.useCallback(async()=>{if(!fe){$(!0);try{if(co()){const Pe=await uo(at);if(!Pe.success||!Pe.path){Pe.error&&Pe.error!=="Directory selection cancelled"&&ne.error("Failed to select directory",{description:Pe.error});return}await ft(Pe.path);return}const P=await ou(at);if(P.status==="cancelled")return;if(P.status!=="picked"){ne.error("Couldn't open a folder picker",{description:P.error});return}await ft(P.path)}catch(P){ne.error("Failed to select directory",{description:P instanceof Error?P.message:"Unknown error occurred."})}finally{$(!1)}}},[ft,fe,at]),Ze=o.useCallback(P=>{if(P.key==="ArrowDown"){P.preventDefault(),B(Pe=>Math.min(Xe.length-1,Pe+1));return}if(P.key==="ArrowUp"){P.preventDefault(),B(Pe=>Math.max(0,Pe-1));return}if(P.key==="Enter"){if(P.preventDefault(),ah(P)){ue(at);return}O&&Ke(yt);return}P.key==="Backspace"&&p===""&&(P.preventDefault(),z())},[Ke,ue,z,O,yt,p,Xe.length,at]),mt=e.jsxs("button",{type:"button",onClick:()=>Se(P=>!P),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[Z?e.jsx(j,{name:"checkbox",className:"h-4 w-4 text-primary"}):e.jsx(j,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),bt=e.jsx("div",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(j,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),e.jsx(nn,{ref:N,value:p,onChange:P=>I(tn(P.target.value)),onKeyDown:Ze,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),e.jsxs(Ve,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:L||fe,onMouseDown:P=>P.preventDefault(),onClick:()=>{At()},title:"Browse location","aria-label":"Browse location",children:[e.jsx(j,{name:"folder-open",className:"h-3.5 w-3.5"}),fe?"Opening...":"Browse"]})]})}),Fe=Xe.some(P=>P.type==="parent"),Ye=e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:e.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[e.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),e.jsxs(Ve,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ce,disabled:L||fe,onClick:()=>we(P=>!P),children:[e.jsx(j,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ce?e.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(nn,{value:We,onChange:P=>$e(P.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(La,{activeProfile:q,identities:ze,onSelect:P=>Ie(P.id),isApplying:L,iconOnly:!0})]})]}):null,Ue?e.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,e.jsx("div",{className:E("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",rt==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:F?e.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):Y&&Y!=="not-found"?e.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[e.jsx("div",{className:"typography-ui-label text-status-error",children:Y==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),e.jsxs("div",{className:"flex items-center gap-2",children:[Y==="os-permission"&&h?e.jsx(Ve,{size:"xs",onClick:()=>{At()},disabled:fe,children:"Grant access"}):null,e.jsx(Ve,{variant:"outline",size:"xs",onClick:()=>W(P=>P+1),children:"Try again"})]})]}):Xe.length===0?e.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):e.jsx("div",{className:"space-y-0.5",children:Xe.map((P,Pe)=>{const Le=Pe===Q,He=P.type==="directory"&&Fe;return e.jsxs("button",{ref:ut=>{ut?A.current.set(P.value,ut):A.current.delete(P.value)},type:"button","aria-label":P.type==="parent"?P.alreadyAdded?`Go back from ${P.name}, already added`:`Go back from ${P.name}`:P.alreadyAdded?`Open ${P.name}, already added`:`Open ${P.name}`,onMouseEnter:()=>B(Pe),onMouseDown:ut=>ut.preventDefault(),onClick:()=>Ke(P),className:E("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Le&&"bg-interactive-selection text-interactive-selection-foreground",!Le&&"hover:bg-interactive-hover/50"),children:[e.jsxs("span",{className:E("flex min-w-0 flex-1 items-center gap-2",He&&"pl-4"),children:[P.type==="parent"?e.jsx(j,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):e.jsx(j,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:P.name})]}),P.alreadyAdded?e.jsx("span",{className:E("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Le?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,P.type==="parent"?e.jsx(j,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):e.jsx(j,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},P.value)})})},V)]})}),St=e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[bt,Ye]}),Ot=e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(j,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),e.jsx(j,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(j,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("span",{children:pe}),e.jsx(j,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),Gt=e.jsx(Ve,{size:C?"xs":"default",onClick:()=>{ue(at)},disabled:!y,className:E(C&&"w-full flex-1"),children:De}),vt=()=>e.jsxs(e.Fragment,{children:[C?null:Ot,e.jsx("div",{className:E("flex w-full flex-row justify-end gap-2 sm:w-auto",C&&"justify-stretch"),children:Gt})]});return C?e.jsx(Ji,{open:t,onClose:z,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:e.jsx("div",{className:"flex flex-col gap-2",children:vt()}),children:e.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[e.jsx("div",{className:"flex justify-end",children:mt}),St]})}):e.jsx(hs,{open:t,onOpenChange:s,children:e.jsxs(ps,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[e.jsx(Ds,{className:"px-5 pb-2 pt-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(vs,{children:"Add folder"}),e.jsx(Gs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),mt]})}),e.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:St}),e.jsx(Ks,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:vt()})]})})},Tn=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,Xg=()=>{const[t,s]=o.useState(!1),[n,r]=o.useState(!1),[i,a]=o.useState(null),[l,c]=o.useState(!1),d=_c,u=Oe(T=>T.deleteSessions),x=oe(T=>T.showDeletionDialog),g=oe(T=>T.setShowDeletionDialog),v=Is(T=>T.isHomeReady),b=Lt(T=>T.projects),{isMobile:h,isTablet:f,hasTouchInput:C}=$s(),N=h||f||C;o.useEffect(()=>{n||!v||b.length>0||(r(!0),s(!0))},[n,v,b.length]);const A=o.useCallback(T=>{a({sessions:T.sessions,dateLabel:T.dateLabel})},[]),S=o.useCallback(()=>{a(null),c(!1)},[]),m=o.useCallback(async T=>{if(T.sessions.length===0)return;if(T.sessions.length===1){const ce=T.sessions[0];await d(ce.id)?ne.success("Session deleted"):ne.error("Failed to delete session");return}const U=T.sessions.map(ce=>ce.id),{deletedIds:G,failedIds:Y}=await u(U);if(G.length>0){const ce=Y.length>0?Y.length===1?`${Y.length} session could not be deleted.`:`${Y.length} sessions could not be deleted.`:T.dateLabel?`Removed all sessions from ${T.dateLabel}.`:void 0;ne.success(G.length===1?"Deleted {count} session":`Deleted ${G.length} sessions`,{description:Tn(ce)})}Y.length>0&&ne.error(Y.length===1?`Failed to delete ${Y.length} session`:`Failed to delete ${Y.length} sessions`,{description:Tn("Please try again in a moment.")})},[d,u]);o.useEffect(()=>zs.onDeleteRequest(T=>{if(!x){m(T);return}A(T)}),[A,x,m]),o.useEffect(()=>zs.onDirectoryRequest(()=>{s(!0)}),[]);const p=o.useCallback(async()=>{if(i){c(!0);try{if(i.sessions.length===1){const T=i.sessions[0];if(!await d(T.id)){ne.error("Failed to delete session"),c(!1);return}ne.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const T=i.sessions.map(ce=>ce.id),U=await u(T),G=U.deletedIds,Y=U.failedIds;if(G.length>0){const ce=Y.length>0?Y.length===1?`${Y.length} session could not be deleted.`:`${Y.length} sessions could not be deleted.`:i.dateLabel?`Removed all sessions from ${i.dateLabel}.`:void 0;ne.success(G.length===1?"Deleted {count} session":`Deleted ${G.length} sessions`,{description:Tn(ce),action:{label:"OK",onClick:()=>{}}})}if(Y.length>0&&(ne.error(Y.length===1?`Failed to delete ${Y.length} session`:`Failed to delete ${Y.length} sessions`,{description:Tn("Please try again in a moment.")}),G.length===0)){c(!1);return}}S()}finally{c(!1)}}},[i,d,u,S]),I=i?i.sessions.length===1?i.dateLabel?`This action permanently removes 1 session from ${i.dateLabel}.`:"This action permanently removes 1 session.":i.dateLabel?`This action permanently removes ${i.sessions.length} sessions from ${i.dateLabel}.`:`This action permanently removes ${i.sessions.length} sessions.`:"",R=i?e.jsxs("div",{className:"space-y-2",children:[i.sessions.length>0&&e.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsxs("ul",{className:"space-y-0.5",children:[i.sessions.slice(0,5).map(T=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:e.jsx("span",{className:"truncate",children:T.title||"Untitled Session"})},T.id)),i.sessions.length>5&&e.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${i.sessions.length-5} more`})]})}),e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,D=e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>g(!x),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":!x,children:[x?e.jsx(j,{name:"checkbox-blank",className:"size-4"}):e.jsx(j,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ve,{variant:"ghost",onClick:S,disabled:l,children:"Cancel"}),e.jsx(Ve,{variant:"destructive",onClick:p,disabled:l,children:l?"Deleting…":i?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),F=i?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[N?e.jsx(Ji,{open:!!i,onClose:()=>{l||S()},title:F,footer:e.jsx("div",{className:"flex justify-end gap-2",children:D}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[I&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:I}),R]})}):e.jsx(hs,{open:!!i,onOpenChange:T=>{if(!T){if(l)return;S()}},children:e.jsxs(ps,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(Ds,{children:[e.jsx(vs,{children:F}),I&&e.jsx(Gs,{children:I})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:R}),e.jsx(Ks,{className:"mt-2 gap-2 pt-1 pb-1",children:D})]})}),e.jsx(ch,{open:t,onOpenChange:s})]})};function ex(){const t=o.useMemo(()=>Wi(),[]),s=o.useRef(!1),n=o.useRef(!1),r=Oe(g=>g.setCurrentSession),i=oe(g=>g.setActiveMainTab),a=oe(g=>g.setSettingsDialogOpen),l=oe(g=>g.setSettingsPage),c=oe(g=>g.navigateToDiff),d=o.useCallback(async g=>{if(!n.current){n.current=!0;try{if(g.sessionId){const v=Oe.getState().currentSessionId,b=Ys().getState().selectedSessionId;if(g.sessionId!==v||g.sessionId!==b){const f=(t&&typeof window<"u"?new URLSearchParams(window.location.search).get("directory"):null)||Oe.getState().getDirectoryForSession(g.sessionId);r(g.sessionId,f)}}if(g.settingsPath){l(Vf(g.settingsPath)),a(!0);return}oe.getState().isSettingsDialogOpen&&a(!1),g.tab&&i(g.tab),g.diffFile&&(g.tab==="diff"||!g.tab)&&c(g.diffFile)}finally{n.current=!1}}},[t,r,i,a,l,c]),u=o.useCallback(()=>{const g=Oe.getState(),v=Ys().getState(),b=oe.getState();return{sessionId:g.currentSessionId??v.selectedSessionId,tab:b.activeMainTab,isSettingsOpen:b.isSettingsDialogOpen,settingsPath:b.settingsPage,diffFile:b.pendingDiffFile}},[]),x=o.useCallback((g={})=>{if(t||n.current)return;const v=u();Vr(v,g)},[t,u]);o.useEffect(()=>{if(s.current||(s.current=!0,!Go()))return;const g=Ko();(async()=>(await d(g),t||Vr({...u(),sessionId:g.sessionId??Oe.getState().currentSessionId??Ys().getState().selectedSessionId,tab:g.tab??oe.getState().activeMainTab,settingsPath:g.settingsPath??oe.getState().settingsPage,diffFile:g.diffFile??oe.getState().pendingDiffFile},{replace:!0,force:!0})))()},[d,u,t]),o.useEffect(()=>{if(t)return;let g=Oe.getState().currentSessionId??Ys().getState().selectedSessionId;const v=f=>{!f||f===g||n.current||(g=f,x({replace:!0}))},b=Oe.subscribe(f=>{v(f.currentSessionId)}),h=Ys().subscribe(()=>{v(Ys().getState().selectedSessionId)});return()=>{b(),h()}},[t,x]),o.useEffect(()=>{if(t)return;let g=oe.getState().activeMainTab,v=oe.getState().isSettingsDialogOpen,b=oe.getState().settingsPage,h=oe.getState().pendingDiffFile;return oe.subscribe(C=>{if(n.current)return;const N=C.activeMainTab!==g,A=C.isSettingsDialogOpen!==v,S=C.settingsPage!==b,m=C.pendingDiffFile!==h&&C.activeMainTab==="diff";g=C.activeMainTab,v=C.isSettingsDialogOpen,b=C.settingsPage,h=C.pendingDiffFile,(N||A||S||m)&&x()})},[t,x]),o.useEffect(()=>{if(typeof window>"u"||t)return;const g=()=>{const v=Ko();if(Go())d(v);else{const b=oe.getState();b.isSettingsDialogOpen&&a(!1),b.activeMainTab!=="chat"&&i("chat")}};return window.addEventListener("popstate",g),()=>{window.removeEventListener("popstate",g)}},[d,t,i,a])}function dh(t=!0){const s=$n(r=>r.checkForUpdates),n=o.useRef(s);o.useEffect(()=>{n.current=s},[s]),o.useEffect(()=>{if(!t)return;const r=3e3,i=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=g=>{const v=Math.round(g*1e3);return Math.max(a,Math.min(l,v))},x=g=>{c||(d=window.setTimeout(async()=>{const v=await n.current(),b=typeof v=="number"&&Number.isFinite(v)?u(v):i;x(b)},g))};return x(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[t])}function tx(){const t=un(s=>s.connection==="ready",void 0,"chrome");return dh(t),null}const hi=12,uh=[{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"}],fh=({isActive:t,burstKey:s=0,className:n,durationMs:r=900,bursts:i=uh,onComplete:a})=>{const l=Ge.useRef(!1);Ge.useEffect(()=>{!t&&l.current&&a?.(),t&&(l.current=!0)},[t,a]);const c=Ge.useMemo(()=>Array.from({length:hi},(d,u)=>{const x=Math.PI*2*u/hi;return{x:Math.cos(x),y:Math.sin(x),delay:u*18}}),[]);return t?e.jsx("div",{className:E("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((x,g)=>{const v=x.x*d.radius,b=x.y*d.radius,h={"--translate-x":`${v}px`,"--translate-y":`${b}px`,"--particle-delay":`${x.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:h},`${d.id}-${g}-${s}`)})},`${d.id}-${s}`)})}):null},hh=({durationMs:t=3400}={})=>{const[s,n]=Ge.useState({isActive:!1,cycle:0}),r=Ge.useRef(null),i=Ge.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Ge.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Ge.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},t)},[i,t]);return Ge.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},za=o.createContext(void 0),sx=({children:t})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=hh(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return e.jsxs(za.Provider,{value:a,children:[t,e.jsx(fh,{isActive:s,burstKey:n})]})},ph={triggerFireworks:()=>{},dismissFireworks:()=>{}},nx=()=>o.useContext(za)??ph,pi=600,mh=1,gh=t=>{const s=t?.directory;return typeof s=="string"&&s.trim()?s:null},xh=({enabled:t=!0,currentSessionId:s,sortedSessions:n,recentSessions:r=[],prefetchSession:i})=>{const a=o.useRef(new Map),l=o.useRef([]),c=o.useRef(new Set),d=o.useRef(0),u=!1,x=o.useCallback(h=>`${h.directory}
|
|
3
|
-
${h.sessionId}`,[]),g=o.useCallback(()=>{d.current+=1,l.current=[],a.current.forEach(h=>window.clearTimeout(h)),a.current.clear()},[]),v=o.useCallback(()=>{if(!(!t||u||typeof window>"u"))for(;c.current.size<mh&&l.current.length>0;){const h=l.current.shift();if(!h)break;h.generation!==d.current||Oe.getState().currentSessionId===h.sessionId||Uc(h.sessionId,h.directory).renderable}},[t,u,i,x]),b=o.useCallback(h=>{const f=h?.id,C=gh(h);if(!t||u||!f||!C||f===s||typeof window>"u")return;const N={sessionId:f,directory:C,generation:d.current};x(N)},[s,t,u,v,x]);o.useEffect(()=>{g()},[g,s,t,u]),o.useEffect(()=>{if(!t||u||!s||n.length===0)return;const h=window.setTimeout(()=>{const f=n.findIndex(C=>C.id===s);f<0||(b(n[f-1]),b(n[f+1]))},pi);return()=>window.clearTimeout(h)},[s,t,u,b,n]),o.useEffect(()=>{if(!t||u||!s||r.length===0)return;const h=window.setTimeout(()=>{const f=r.findIndex(C=>C.id===s);f<0||(b(r[f-1]),b(r[f+1]))},pi);return()=>window.clearTimeout(h)},[s,t,u,r,b]),o.useEffect(()=>g,[g])},bh=t=>{const s=Oe(n=>n.currentSessionId);return xh({...t,currentSessionId:s}),null},yh=t=>{const{normalizedProjects:s,enabled:n=!0,ownership:r,isSessionsLoading:i,hasAuthoritativeGlobalSessions:a,isWorktreeTopologyLoading:l,unresolvedWorktreeProjectPaths:c,foldersMap:d,createFolder:u,addSessionToFolder:x}=t;o.useEffect(()=>{!n||i||!a||l||s.forEach(g=>{if(c.has(g.normalizedPath))return;const v=Zi(g.normalizedPath),b=r.archivedSessionsByProject.get(g.id)??[],h=d[v]??[],f=new Map(h.map(C=>[C.name.toLowerCase(),C]));b.forEach(C=>{const N=zc(C,g.normalizedPath),A=N.toLowerCase();let S=f.get(A);S||(S=u(v,N),f.set(A,S)),S.sessionIds.includes(C.id)||x(v,S.id,C.id)})})},[s,n,r,i,a,l,c,d,u,x])},vh=t=>({getOrderedGroups:o.useCallback((n,r)=>{const i=t.get(n);if(!i||i.length===0)return r;const a=new Map(r.map(u=>[u.id,u])),l=[];i.forEach(u=>{const x=a.get(u);x&&(l.push(x),a.delete(u))});const c=[],d=[];return r.forEach(u=>{a.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[t])}),wh=t=>{const{normalizedProjects:s,getSessionsForProject:n,getArchivedSessionsForProject:r,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:l,buildGroupedSessions:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,filterSessionNodesForSearch:x,buildGroupSearchText:g,foldersMap:v}=t,b=o.useRef(new Map),h=o.useMemo(()=>{const I=b.current,R=new Map;let D=0,F=0;const T=(G,Y)=>G.length===Y.length&&G.every((ce,ae)=>ce===Y[ae]),U=s.map(G=>{const Y=n(G.id),ce=r(G.id),ae=i.has(G.id)?!!i.get(G.id):l,W=a.get(G.id)??null,Q=I.get(G.id);if(Q&&Q.project===G&&T(Q.activeSessions,Y)&&T(Q.archivedSessions,ce)&&Q.rootBranch===W&&Q.isRepo===ae&&Q.buildGroupedSessions===c)return D+=1,R.set(G.id,Q),Q.section;F+=1;const B=Xi([...Y,...ce]),L=c(B,G.normalizedPath,[],W,ae),J={project:G,groups:L};return R.set(G.id,{project:G,activeSessions:Y,archivedSessions:ce,rootBranch:W,isRepo:ae,buildGroupedSessions:c,section:J}),J});return b.current=R,D>0&&cs("ui.sidebar.project_section.reused",D),F>0&&cs("ui.sidebar.project_section.rebuilt",F),U},[s,n,r,i,l,c,a]),f=o.useMemo(()=>h,[h]),C=o.useMemo(()=>{const I=new WeakMap;if(!d)return I;const R=D=>D.reduce((F,T)=>F+1+R(T.children),0);return f.forEach(D=>{D.groups.forEach(F=>{const T=x(F.sessions,u),U=R(T),G=g(F).includes(u),Y=pt(F.directory??null),ae=(Y?v[Y]??[]:[]).filter(W=>W.name.toLowerCase().includes(u)).length;I.set(F,{filteredNodes:T,matchedSessionCount:U,folderNameMatchCount:ae,groupMatches:G,hasMatch:G||U>0||ae>0})})}),I},[d,f,x,u,g,v]),N=o.useMemo(()=>d?f.map(I=>({...I,groups:I.groups.filter(R=>C.get(R)?.hasMatch===!0)})).filter(I=>I.groups.length>0):f,[d,f,C]),A=d?N:f,S=o.useRef(new WeakMap),m=o.useMemo(()=>{const I=S.current;return A.map(R=>{const D=I.get(R);if(D&&D.query===u)return D.section;const F=R.groups.filter(W=>!W.isArchivedBucket),T=R.groups.filter(W=>W.isArchivedBucket),U=F.flatMap(W=>d?C.get(W)?.filteredNodes??[]:W.sessions),G=F.map(W=>({scopeKey:W.folderScopeKey??pt(W.directory??null),directory:W.directory??null})).filter(W=>!!W.scopeKey),Y=F.find(W=>W.isMain)??null,ce={id:"flat",label:Y?.label??"",branch:Y?.branch??null,description:Y?.description??null,isMain:!0,isArchivedBucket:!1,directory:Y?.directory??R.project.normalizedPath,folderScopeKey:Y?.folderScopeKey??R.project.normalizedPath,folderScopes:G,sessions:U};if(d){const W=F.map(Q=>C.get(Q)).filter(Q=>!!Q);C.set(ce,{filteredNodes:U,matchedSessionCount:W.reduce((Q,B)=>Q+B.matchedSessionCount,0),folderNameMatchCount:W.reduce((Q,B)=>Q+B.folderNameMatchCount,0),groupMatches:W.some(Q=>Q.groupMatches),hasMatch:W.some(Q=>Q.hasMatch)})}const ae={project:R.project,groups:[ce,...T]};return I.set(R,{query:u,section:ae}),ae})},[C,d,u,A]),p=o.useMemo(()=>d?A.reduce((I,R)=>I+R.groups.reduce((D,F)=>{const T=C.get(F);if(!T)return D;const U=T.folderNameMatchCount+(T.groupMatches?1:0);return D+T.matchedSessionCount+U},0),0):0,[d,A,C]);return{projectSections:h,visibleProjectSections:f,groupSearchDataByGroup:C,searchableProjectSections:N,sectionsForRender:A,flatSectionsForRender:m,searchMatchCount:p}},Sh=t=>{const{projectSections:s,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:i,currentSessionId:a,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:x,setSessionSwitcherOpen:g}=t,v=o.useMemo(()=>{const h=new Map,f=new Map,C=(N,A,S,m)=>{h.has(N)||h.set(N,new Map);const p=h.get(N);m.forEach(I=>{const R=pt(I.session.directory??S??A);p.set(I.session.id,{directory:R}),f.has(N)||f.set(N,{id:I.session.id,directory:R}),I.children.length>0&&C(N,A,R,I.children)})};return s.forEach(N=>{N.groups.forEach(A=>{C(N.project.id,N.project.normalizedPath,A.directory,A.sessions)})}),{metaByProject:h,firstSessionByProject:f}},[s]),b=o.useRef(null);o.useLayoutEffect(()=>{if(!n)return;if(c){b.current=n;return}if(b.current===n)return;const h=s.find(I=>I.project.id===n);if(!h)return;b.current=n;const f=v.metaByProject.get(n);if(a&&f&&f.has(a)){i(I=>{if(I.get(n)===a)return I;const R=new Map(I);return R.set(n,a),R});return}const C=a?Array.from(v.metaByProject.entries()).some(([I,R])=>I!==n&&R.has(a)):!1;if(a&&f&&!C)return;if(!f||f.size===0){x("chat"),d&&g(!1),u({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath});return}const N=r.get(n),A=N&&f.has(N)?N:null,S=v.firstSessionByProject.get(n)?.id??null,m=A??S;if(!m||m===a)return;const p=f.get(m)?.directory??null;l(m,p,{keepPanelOpen:!0})},[n,r,a,l,c,d,u,s,v,x,g,i]),o.useEffect(()=>{if(!n||!a)return;const h=v.metaByProject.get(n);!h||!h.has(a)||i(f=>{if(f.get(n)===a)return f;const C=new Map(f);return C.set(n,a),C})},[n,a,v,i])},jh=({initialActiveSessionByProject:t,persistActiveSessionByProject:s,...n})=>{const r=Oe(c=>c.currentSessionId),i=Oe(c=>!!c.newSessionDraft?.open),[a,l]=o.useState(()=>new Map(t));return Sh({...n,activeSessionByProject:a,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:i}),o.useEffect(()=>{s(a)},[a,s]),null},En=t=>!!t.time?.archived,Ch=t=>{const s=o.useCallback(a=>[a.label,a.branch??"",a.description??"",a.directory??""].join(" ").toLowerCase(),[]),n=o.useCallback(a=>{const l=pt(a.directory??null)??"";return`${(a.title||"Untitled Session").trim()} ${l}`.toLowerCase()},[]),r=o.useCallback((a,l)=>l?a.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):a,[n]),i=o.useCallback((a,l,c,d,u)=>{const x=pt(l??null),g=Xi(a).sort((S,m)=>Wn(S,m,t.pinnedSessionIds,t.sessionOrderRanks)),v=new Map(g.map(S=>[S.id,S])),b=new Map;g.forEach(S=>{const m=S.parentID;if(!m)return;const p=v.get(m);if(!p||En(p)!==En(S))return;const I=b.get(m)??[];I.push(S),b.set(m,I)}),b.forEach(S=>S.sort((m,p)=>Wn(m,p,t.pinnedSessionIds,t.sessionOrderRanks)));const h=S=>{const m=b.get(S.id)??[];return{session:S,children:m.map(p=>h(p)),worktree:null}},f=g.filter(S=>{const m=S.parentID;if(!m)return!0;const p=v.get(m);return p?En(p)!==En(S):!0}),C=[],N=[];f.forEach(S=>{const m=h(S);S.time?.archived?N.push(m):C.push(m)});const A=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:x?$c(x,t.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:x,folderScopeKey:x,sessions:C}];return N.length>0&&A.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:x?Zi(x):null,sessions:N}),A},[t.homeDirectory,t.pinnedSessionIds,t.sessionOrderRanks]);return{buildGroupSearchText:s,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:i}},kh=({enabled:t=!0,isSessionSearchOpen:s,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:i})=>{o.useEffect(()=>{if(!t||!s||typeof window>"u")return;const a=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(a)},[t,s,r]),o.useEffect(()=>{if(!t||!s||typeof document>"u")return;const a=l=>{i.current&&(i.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[t,s,n,i])},Nh=t=>{const[s,n]=o.useState(null),r=o.useRef(null);o.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const i=o.useCallback((S,m,p)=>{Or("navigation.session_select"),oe.getState().closeMainSurfaces();const I=()=>{!t.isSessionSearchOpen&&t.sessionSearchQuery.length===0||(t.setSessionSearchQuery(""),t.setIsSessionSearchOpen(!1))},R=p?.keepPanelOpen!==!0;if(t.mobileVariant&&(t.setActiveMainTab("chat"),t.setSessionSwitcherOpen(!1)),S===Oe.getState().currentSessionId){t.allowReselect&&R&&t.onSessionSelected?.(S),I();return}Or("navigation.session_state_set"),t.setCurrentSession(S,m??null),R&&t.onSessionSelected?.(S),I()},[t]),a=o.useCallback((S,m)=>{t.setEditingId(S),t.setEditTitle(m)},[t]),l=o.useCallback(async S=>{if(!t.editingId)return;const m=(S??t.editTitle).trim();m&&await t.updateSessionTitle(t.editingId,m),t.setEditingId(null),t.setEditTitle("")},[t]),c=o.useCallback(()=>{t.setEditingId(null),t.setEditTitle("")},[t]),d=o.useCallback(async(S,m)=>{try{return(await Bs(S)).ok?(n(m),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=o.useCallback(async S=>{const m=await t.shareSession(S.id);if(!m?.share?.url){ne.error("Unable to share session");return}const p=await d(m.share.url,S.id);ne[p?"success":"warning"]("Session shared",{description:p?"Share link copied to clipboard.":"Failed to copy URL"})},[t,d]),x=o.useCallback((S,m)=>{d(S,m).then(p=>{p||ne.error("Failed to copy URL")})},[d]),g=o.useCallback(S=>{Bs(S).then(m=>{if(m.ok){ne.success("Session ID copied");return}ne.error("Failed to copy session ID")}).catch(()=>ne.error("Failed to copy session ID"))},[]),v=o.useCallback(async S=>{await t.unshareSession(S)?ne.success("Session unshared"):ne.error("Unable to unshare session")},[t]),b=o.useCallback(S=>{const m=[],p=I=>{(t.childrenMap.get(I)??[]).forEach(D=>{m.push(D),p(D.id)})};return p(S),m},[t.childrenMap]),h=o.useCallback((S,m)=>m?S:S.filter(p=>!p.time?.archived),[]),f=o.useCallback(async(S,m,p)=>{const I=m?.archivedBucket===!0||m?.hardDelete===!0,R=p?.descendantIds??h(b(S.id),I).map(U=>U.id);if(R.length===0){(I?await t.deleteSession(S.id):await t.archiveSession(S.id))?ne.success(I?"Session deleted":"Session archived"):ne.error(I?"Failed to delete session":"Failed to archive session");return}const D=[S.id,...R];if(I){const{deletedIds:U,failedIds:G}=await t.deleteSessions(D);if(G.length===0){const Y=U.length;ne.success(Y===1?`Deleted ${Y} session`:`Deleted ${Y} sessions`)}else ne.error("Failed to delete session");return}const{archivedIds:F,failedIds:T}=await t.archiveSessions(D);F.length>0&&ne.success(F.length===1?`Archived ${F.length} session`:`Archived ${F.length} sessions`),T.length>0&&ne.error(T.length===1?`Failed to archive ${T.length} session`:`Failed to archive ${T.length} sessions`)},[t,b,h]),C=o.useCallback((S,m)=>{const p=m?.archivedBucket===!0||m?.hardDelete===!0,I=h(b(S.id),p).map(R=>R.id);if(!t.showDeletionDialog||m?.skipConfirm===!0){f(S,m,{descendantIds:I});return}t.setDeleteSessionConfirm({session:S,descendantCount:I.length,descendantIds:I,archivedBucket:p})},[t,b,f,h]),N=o.useCallback(async()=>{if(!t.deleteSessionConfirm)return;const{session:S,archivedBucket:m,descendantIds:p}=t.deleteSessionConfirm;t.setDeleteSessionConfirm(null),await f(S,{archivedBucket:m},{descendantIds:p})},[t,f]),A=o.useCallback(async S=>{await t.unarchiveSession(S.id)?ne.success("Session restored"):ne.error("Failed to restore session")},[t]);return{copiedSessionId:s,handleSessionSelect:i,handleSessionDoubleClick:a,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:x,handleCopySessionId:g,handleUnshareSession:v,handleDeleteSession:C,handleRestoreSession:A,confirmDeleteSession:N}},Ah=t=>{const{safeStorage:s,keys:n,groupOrderByProject:r,collapsedGroups:i,setExpandedParents:a,setCollapsedProjects:l}=t,c=o.useRef(null),d=o.useRef(null),u=o.useCallback(()=>{const g=d.current;if(d.current=null,c.current=null,!g)return;const{projects:v}=Lt.getState(),b=v.map(h=>({...h,sidebarCollapsed:g.has(h.id)}));ao({projects:b}).catch(()=>{})},[]),x=o.useCallback(g=>{typeof window>"u"||(d.current=g,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return o.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),o.useEffect(()=>{try{const g=s.getItem(n.sessionExpanded);if(g){const b=JSON.parse(g);Array.isArray(b)&&a(new Set(b.filter(h=>typeof h=="string")))}const v=s.getItem(n.projectCollapse);if(v){const b=JSON.parse(v);Array.isArray(b)&&l(new Set(b.filter(h=>typeof h=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,s,l,a]),o.useEffect(()=>{try{const g=Object.fromEntries(r.entries());s.setItem(n.groupOrder,JSON.stringify(g))}catch{}},[r,n.groupOrder,s]),o.useEffect(()=>{try{s.setItem(n.groupCollapse,JSON.stringify(Array.from(i)))}catch{}},[i,n.groupCollapse,s]),{scheduleCollapsedProjectsPersist:x}},Ih=5*6e4,Dh=t=>{const{normalizedProjects:s,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:i,setProjectRootBranches:a}=t,{git:l}=Zn(),c=ea(g=>g.ensureStatus);o.useEffect(()=>{if(!n||!l||s.length===0){i(new Map);return}s.forEach(g=>{Uu(()=>c(g.normalizedPath,l))})},[n,s,l,c,i]),o.useEffect(()=>{if(!n)return;const g=new Map;s.forEach(v=>{g.set(v.id,r.get(v.normalizedPath)?.isGitRepo??null)}),i(g)},[n,s,r,i]);const d=o.useMemo(()=>s.map(g=>{const v=r.get(g.normalizedPath)?.branch??"";return`${g.id}:${v}`}).join("|"),[s,r]),u=o.useRef(new Map),x=o.useRef(new Map);o.useEffect(()=>{if(!n)return;let g=!1;const v=setTimeout(()=>{(async()=>{const h=new Set(s.map(S=>S.id));for(const S of u.current.keys())h.has(S)||(u.current.delete(S),x.current.delete(S));const f=Date.now();if(s.filter(S=>{const m=r.get(S.normalizedPath);if(m?.isGitRepo===!1)return u.current.delete(S.id),x.current.delete(S.id),!1;if(m?.isGitRepo!==!0||m.branch===null)return!1;const p=m.branch.trim(),I=`${S.normalizedPath}\0${p}`,R=u.current.get(S.id);if(R===I){const D=x.current.get(S.id);return D&&(D.at=f),!1}return!(R!==void 0&&f-(x.current.get(S.id)?.at??0)<Ih)}).length===0)return;const N=[];if(s.forEach(S=>{const m=r.get(S.normalizedPath)?.branch?.trim()??"",p=`${S.normalizedPath}\0${m}`;m&&N.push({id:S.id,inputKey:p,branch:m})}),g||N.length===0)return;const A=Date.now();a(S=>{const m=new Map(S);return N.forEach(({id:p,branch:I})=>{I&&m.set(p,I)}),m}),N.forEach(({id:S,inputKey:m,branch:p})=>{u.current.set(S,m),p&&x.current.set(S,{branch:p,at:A})})})()},150);return()=>{g=!0,clearTimeout(v)}},[n,s,d,r,a])},Ph=t=>{const{ownership:s}=t,n=o.useCallback(i=>s.sessionsByProject.get(i)??[],[s]),r=o.useCallback(i=>s.archivedSessionsByProject.get(i)??[],[s]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Th=t=>{if(t.runtimeKey!==tr()||!t.directory||t.directory==="global"||!t.sessionId)return;const s=au(t.sessionId,t.directory,t.runtimeKey);s&&lu.getState().clearQueue(s),Gc.getState().clearSessionTodos(t.runtimeKey,t.directory,t.sessionId),Wt.getState().removeSessionEverywhere(t.runtimeKey,t.sessionId),ta.getState().clearSessionDrafts(t.runtimeKey,t.directory,t.sessionId),Fr.getState().clearPinnedSession(t.runtimeKey,t.directory,t.sessionId);const n=Kc(t.runtimeKey,t.directory,t.sessionId);n&&Hc(n,!0)},Eh=t=>{const s=new Map;for(const n of t){const r=en(n);r&&s.set(n.id,{directory:r,sessionId:n.id})}return s},Rh=(t,s)=>{if(!t)return[];const n=[];return t.forEach((r,i)=>{s.has(i)||n.push(r)}),n},Mh=t=>{const{enabled:s=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=t,i=o.useRef(null);o.useEffect(()=>{if(!s||!n)return;const a=tr(),l=Eh(r),c=i.current?.runtimeKey===a?i.current.identities:null;for(const d of Rh(c,l))Th({runtimeKey:a,...d});i.current={runtimeKey:a,identities:l}},[s,n,r])},Fh=(t,s)=>t?s.kind!==t.kind?s.kind==="project":s.projectRoot.length!==t.projectRoot.length?s.projectRoot.length>t.projectRoot.length:s.projectId.localeCompare(t.projectId)<0:!0,mi=(t,s,n)=>{Fh(t.get(s),n)&&t.set(s,n)},Lh=t=>{const s=t;return pt(s.directory)??pt(s.project?.worktree)},Oh=t=>{if(t==="/"||/^[A-Z]:$/.test(t))return null;const s=t.lastIndexOf("/");return s<0?null:s===0?"/":s===2&&/^[A-Z]:\//.test(t)?t.slice(0,2):t.slice(0,s)},Bh=(t,s,n,r=[])=>{const i=new Map,a=new Map;for(const b of s){const h=pt(b.normalizedPath);if(!h)continue;const f=a.get(h);(!f||b.id.localeCompare(f.id)<0)&&a.set(h,b),mi(i,h,{projectId:b.id,projectRoot:h,scopeDirectory:h,kind:"project"})}if(n)for(const[b,h]of n){const f=pt(b),C=f?a.get(f):void 0;if(!(!C||!f))for(const N of h||[]){const A=pt(N?.path);A&&mi(i,A,{projectId:C.id,projectRoot:f,scopeDirectory:A,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,x=new Map,g=b=>{if(!b)return null;if(l.has(b))return l.get(b)??null;const h=[];let f=b,C=null;for(;f;){if(l.has(f)){C=l.get(f)??null;break}if(h.push(f),C=i.get(f)??null,C)break;f=Oh(f)}for(const N of h)l.set(N,C);return C},v=(b,h,f)=>{for(const C of b){const N=g(Lh(C));if(!N)continue;c.set(C.id,N);const A=h.get(N.projectId);if(A?A.push(C):h.set(N.projectId,[C]),!f)continue;const S=f.get(N.scopeDirectory);S?S.add(C.id):f.set(N.scopeDirectory,new Set([C.id]))}};return v(t,d,x),v(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:x,directoryResolutions:l.size}},_h=t=>{const{enabled:s=!0,isDesktopShellRuntime:n,projectSections:r,projectHeaderSentinelRefs:i}=t,[a,l]=o.useState(new Set);return o.useEffect(()=>{if(!s||!n){l(x=>x.size===0?x:new Set);return}const d=Array.from(i.current.values()).find(x=>x!==null)?.closest(".oc-sidebar-scroller")??null;if(!d)return;const u=new IntersectionObserver(x=>{l(g=>{const v=new Set(g);let b=!1;for(const h of x){const f=h.target.dataset.projectId;if(!f)continue;const C=h.rootBounds?.top??d.getBoundingClientRect().top,N=!h.isIntersecting&&h.boundingClientRect.top<C;v.has(f)!==N&&(b=!0,N?v.add(f):v.delete(f))}return b?v:g})},{root:d,threshold:0});return i.current.forEach(x=>{x&&u.observe(x)}),()=>u.disconnect()},[s,n,i,r]),a},Uh=({open:t,onOpenChange:s,project:n,onSave:r})=>e.jsx(hs,{open:t,onOpenChange:s,children:e.jsx(ps,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:e.jsx(Ls,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:e.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:t&&n?e.jsx(_f,{project:n,onIdentitySave:r}):null})})})});function $a({state:t,activeLabel:s,unreadLabel:n,className:r}){return t==="unread"?e.jsx("span",{className:E("inline-flex items-center",r),"aria-label":n??s,title:n??s,children:e.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):e.jsx("span",{className:E("inline-flex items-center",r),"aria-label":s,title:s,children:e.jsx(Xn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const zh=({folder:t,displayName:s,sessions:n,subFolderItems:r,isCollapsed:i,collapsedActivityState:a=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:x,groupDirectory:g,projectId:v,mobileVariant:b=!1,alwaysShowActions:h=b,isRenaming:f=!1,renameDraft:C="",onRenameDraftChange:N,onRenameSave:A,onRenameCancel:S,droppableRef:m,isDropTarget:p=!1,onNewSession:I,depth:R=0,hideActions:D=!1,archivedBucket:F=!1})=>{const[T,U]=o.useState(!1),[G,Y]=o.useState(""),ce=o.useRef(null),ae=f||T,W=f?C:G,Q=o.useCallback(()=>{Y(t.name),U(!0)},[t.name]),B=o.useCallback(()=>{const $=W.trim();$&&$!==t.name&&c($),f&&A&&A(),U(!1),Y("")},[W,t.name,f,c,A]),L=o.useCallback(()=>{f&&S&&S(),U(!1),Y("")},[f,S]),J=o.useCallback($=>{f&&N?N($):Y($)},[f,N]);o.useEffect(()=>{if(!f)return;const $=()=>{const We=ce.current;We&&(We.focus(),We.select())},Ce=requestAnimationFrame($),we=window.setTimeout($,0);return()=>{cancelAnimationFrame(Ce),window.clearTimeout(we)}},[f]);const fe=i?"folder":"folder-open";return e.jsxs("div",{className:"oc-folder",children:[e.jsxs("div",{ref:m,className:E("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",p&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:ae?void 0:$=>{$.currentTarget.blur(),l()},role:ae?void 0:"button",tabIndex:ae?void 0:0,onKeyDown:ae?void 0:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),l())},"aria-label":i?`Expand folder ${t.name}`:`Collapse folder ${t.name}`,children:[e.jsxs("div",{className:E("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",F?h?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":h?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[e.jsx(j,{name:fe,className:E(Un,p?"text-primary":"text-muted-foreground")}),ae?e.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onSubmit:$=>{$.preventDefault(),B()},children:[e.jsx("input",{ref:ce,value:W,onChange:$=>J($.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),onKeyDown:$=>{if($.key==="Escape"){$.stopPropagation(),L();return}($.key===" "||$.key==="Enter")&&$.stopPropagation()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),children:e.jsx(j,{name:"check",className:"size-4"})}),e.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),L()},onPointerDown:$=>$.stopPropagation(),onMouseDown:$=>$.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(j,{name:"close",className:"size-4"})})]}):e.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("span",{className:E(sa,p?"text-primary":"text-muted-foreground"),children:s??t.name})}),e.jsx(nt,{side:"right",sideOffset:8,className:"max-w-xs",children:s??t.name})]}),e.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),a?e.jsx($a,{state:a,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,i?e.jsx(j,{name:"arrow-right-s",className:E(Un,"text-muted-foreground")}):e.jsx(j,{name:"arrow-down-s",className:E(Un,"text-muted-foreground")})]})]}),!ae&&(!D||F)?e.jsx("div",{className:E("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",h?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:e.jsxs("div",{className:"flex items-center gap-0.5",children:[!F&&I?e.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),I()},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 ${t.name}`,title:"New session",children:e.jsx(j,{name:"add",className:"size-4"})}):null,F?null:e.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),Q()},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 ${t.name}`,children:e.jsx(j,{name:"pencil-ai",className:"size-4"})}),e.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":F?`Delete archived sessions in folder ${t.name}`:`Delete folder ${t.name}`,children:e.jsx(j,{name:"delete-bin",className:"size-4"})})]})}):null]}),i?null:e.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map($=>e.jsx(o.Fragment,{children:u($,0,g??null,v??null,F,void 0,"project",x?.($))},$.session.id)):r?null:e.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},$h=o.memo(zh),Gh=({sessionId:t,sessionDirectory:s,sessionTitle:n,children:r})=>{const{attributes:i,listeners:a,setNodeRef:l,isDragging:c}=Pu({id:`session-drag:${t}`,data:{type:"session",sessionId:t,sessionDirectory:s,sessionTitle:n}}),d=o.useCallback(u=>{u.stopPropagation(),a?.onPointerDown&&a.onPointerDown(u)},[a]);return e.jsx("div",{ref:l,...i,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Kh=({folderId:t,children:s})=>{const{setNodeRef:n,isOver:r}=Tu({id:`folder-drop:${t}`,data:{type:"folder",folderId:t}});return e.jsx(e.Fragment,{children:s(n,r)})},Hh=({scopeKey:t,hasFolders:s,onSessionDroppedOnFolder:n,children:r})=>{const i=sr(yn(ho,{activationConstraint:{distance:8}})),[a,l]=o.useState(null),[c,d]=o.useState("Session"),[u,x]=o.useState(null),[g,v]=o.useState(null);if(!t)return e.jsx(e.Fragment,{children:r});const b=h=>{l(null),x(null),v(null);const{active:f,over:C}=h;if(!C)return;const N=f.data.current,A=C.data.current;N?.type==="session"&&N.sessionId&&A?.type==="folder"&&A.folderId&&n(N.sessionId,A.folderId)};return e.jsxs(nr,{sensors:i,collisionDetection:rr,onDragStart:h=>{const f=h.active.data.current;if(f?.type==="session"&&f.sessionId){l(f.sessionId),d(f.sessionTitle??"Session");const C=h.active.rect.current.initial?.width,N=h.active.rect.current.initial?.height;x(typeof C=="number"?C:null),v(typeof N=="number"?N:null)}},onDragCancel:()=>{l(null),x(null),v(null)},onDragEnd:b,children:[r,e.jsx(wa,{children:a&&s?e.jsxs("div",{style:{width:u?`${u}px`:"auto",height:g?`${g}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:[e.jsx(j,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),e.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Gn=(t,s)=>{if(!s)return t;const n=t.toLowerCase(),r=s.toLowerCase(),i=r.length;if(i===0)return t;const a=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&a.push(t.slice(l,c));const d=t.slice(c,c+i);a.push(e.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+i,c=n.indexOf(r,l)}return l<t.length&&a.push(t.slice(l)),a.length>0?a:t},_s=({icon:t,children:s,onClick:n,className:r,mobileVariant:i=!1})=>e.jsxs("button",{type:"button",onClick:n,className:E(i?Wc:Vc,r),children:[e.jsx(j,{name:t,className:E(gn(i),"text-muted-foreground")}),e.jsx("span",{className:E(xn(i),"flex-1 text-muted-foreground"),children:s})]}),gi=(t,s,n)=>{if(!s)return;const r=i=>{let a=i.session.id===s;for(const l of i.children)a=r(l)||a;return a&&n.add(i.session.id),a};for(const i of t)r(i)},bs=(t,s)=>{if(!s)return!1;if(t.session.id===s)return!0;for(const n of t.children)if(bs(n,s))return!0;return!1},Wh=(t,s,n)=>{const r=new Map,i=a=>{const l=en(a.session)??n;if(l){const c=r.get(l)??[];c.push(a.session.id),r.set(l,c)}if(!(a===t&&s))for(const c of a.children)i(c)};return i(t),[...r].map(([a,l])=>({directory:a,sessionIDs:l}))},Vh=(t,s)=>{const n=new Set(t);return t.map(r=>s.get(r)).filter(r=>{if(!r)return!1;const i=new Set;let a=r.session.parentID??null;for(;a&&!i.has(a);){if(n.has(a)&&s.has(a))return!1;i.add(a),a=s.get(a)?.session?.parentID??null}return!0})},xi=new WeakMap;let bi=1;const Yh=t=>{const s=xi.get(t);if(s!==void 0)return s;const n=bi;return bi+=1,xi.set(t,n),n},Zr=t=>t.children.length===0?"":t.children.map(n=>{const r=Yh(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${Zr(n)}`}).join("|"),Ga=(t,s,n,r,i,a)=>{const l=tr(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const x=d.session.directory??i,g=u.session.directory??a,v=Ho(l,x??"",d.session.id),b=Ho(l,g??"",u.session.id);return(v?n.has(v):!1)!==(b?r.has(b):!1)?!0:d.children.some((h,f)=>c(h,u.children[f]))};return c(t,s)},Qn=(t,s,n,r)=>{if(!s)return null;const i=r?"archived":"active";let a=null;const l=c=>{if(`${n}:${i}:${c.session.id}`===s)return a=c.session.id,!0;for(const u of c.children)if(l(u))return!0;return!1};return t.forEach(c=>l(c)),a},Ka=(t,s)=>"",qh=ws(()=>({results:{},refresh:async()=>{},load:async()=>{},resetForRuntimeSwitch:()=>{}})),Qh=t=>null,bo=(t,s)=>t==="active"||s==="active"?"active":t==="unread"||s==="unread"?"unread":null,Ha=(t,s,n,r)=>{if(s.has(t.session.id))return"active";let i=null;const a=!!t.session.parentID;n.has(t.session.id)&&(r||!a)&&(i="unread");for(const l of t.children)if(i=bo(i,Ha(l,s,n,r)),i==="active")return i;return i},yi=(t,s,n,r)=>{let i=null;for(const a of t)if(i=bo(i,Ha(a,s,n,r)),i==="active")return i;return i},Jh=50,Zh=28,Rn=(t,s)=>s?t.sessions.some(n=>bs(n,s)):!1,Xh=(t,s,n)=>t.sessions.some(r=>Ga(r,r,s,n,t.directory,t.directory)),ep=(t,s,n)=>{const r=i=>{const a=i.session.id;return s.get(a)!==n.get(a)?!0:i.children.some(r)};return t.sessions.some(r)},vi=(t,s,n)=>{const r=i=>s.has(i.session.id)!==n.has(i.session.id)?!0:i.children.some(r);return t.sessions.some(r)},tp=(t,s)=>{const n=r=>s.has(r.session.id)?!0:r.children.some(n);return t.sessions.some(n)},sp=(t,s,n)=>{const r=t.isArchivedBucket?"archived":"active",i=a=>{const l=`project:${r}:${a.session.id}`;return s.has(l)!==n.has(l)?!0:a.children.some(i)};return t.sessions.some(i)},np=(t,s)=>{if(t.group!==s.group||t.groupKey!==s.groupKey||t.projectId!==s.projectId||t.hideGroupLabel!==s.hideGroupLabel||t.compactBodyPadding!==s.compactBodyPadding||t.groupSearchDataByGroup!==s.groupSearchDataByGroup||t.visibleSessionCount!==s.visibleSessionCount||t.collapsedGroups!==s.collapsedGroups&&t.collapsedGroups.has(t.groupKey)!==s.collapsedGroups.has(s.groupKey)||t.pinnedSessionIds!==s.pinnedSessionIds&&Xh(s.group,t.pinnedSessionIds,s.pinnedSessionIds)||t.expandedParents!==s.expandedParents&&sp(s.group,t.expandedParents,s.expandedParents)||t.sessionOrderIndex!==s.sessionOrderIndex&&ep(s.group,t.sessionOrderIndex,s.sessionOrderIndex)||t.editingId!==s.editingId&&(Rn(t.group,t.editingId)||Rn(s.group,s.editingId))||t.editTitle!==s.editTitle&&(Rn(t.group,t.editingId)||Rn(s.group,s.editingId)))return!1;if(t.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Qn(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket),r=Qn(s.group.sessions,s.openSidebarMenuKey,"project",!!s.group.isArchivedBucket);if(n||r)return!1}return t.activeActivitySessionIds!==s.activeActivitySessionIds&&vi(s.group,t.activeActivitySessionIds,s.activeActivitySessionIds)||t.unreadActivitySessionIds!==s.unreadActivitySessionIds&&vi(s.group,t.unreadActivitySessionIds,s.unreadActivitySessionIds)||t.notifyOnSubtasks!==s.notifyOnSubtasks&&tp(s.group,s.unreadActivitySessionIds)?!1:t.hasSessionSearchQuery===s.hasSessionSearchQuery&&t.normalizedSessionSearchQuery===s.normalizedSessionSearchQuery&&t.hideDirectoryControls===s.hideDirectoryControls&&t.collapsedFolderIds===s.collapsedFolderIds&&t.toggleFolderCollapse===s.toggleFolderCollapse&&t.renameFolder===s.renameFolder&&t.deleteFolder===s.deleteFolder&&t.showDeletionDialog===s.showDeletionDialog&&t.setDeleteFolderConfirm===s.setDeleteFolderConfirm&&t.renderSessionNode===s.renderSessionNode&&t.showMoreGroupSessions===s.showMoreGroupSessions&&t.resetGroupSessionLimit===s.resetGroupSessionLimit&&t.mobileVariant===s.mobileVariant&&t.alwaysShowActions===s.alwaysShowActions&&t.activeProjectId===s.activeProjectId&&t.setActiveProjectIdOnly===s.setActiveProjectIdOnly&&t.setActiveMainTab===s.setActiveMainTab&&t.setSessionSwitcherOpen===s.setSessionSwitcherOpen&&t.openNewSessionDraft===s.openNewSessionDraft&&t.addSessionToFolder===s.addSessionToFolder&&t.createFolderAndStartRename===s.createFolderAndStartRename&&t.renamingFolderId===s.renamingFolderId&&t.renameFolderDraft===s.renameFolderDraft&&t.setRenameFolderDraft===s.setRenameFolderDraft&&t.setRenamingFolderId===s.setRenamingFolderId&&t.onToggleCollapsedGroup===s.onToggleCollapsedGroup&&t.dragHandleProps===s.dragHandleProps&&t.scrollContainerRef===s.scrollContainerRef};function rp(t){const{group:s,groupKey:n,projectId:r,hideGroupLabel:i,hasSessionSearchQuery:a,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:x,collapsedFolderIds:g,toggleFolderCollapse:v,renameFolder:b,deleteFolder:h,showDeletionDialog:f,setDeleteFolderConfirm:C,renderSessionNode:N,showMoreGroupSessions:A,resetGroupSessionLimit:S,mobileVariant:m,alwaysShowActions:p,activeProjectId:I,setActiveProjectIdOnly:R,setActiveMainTab:D,setSessionSwitcherOpen:F,openNewSessionDraft:T,addSessionToFolder:U,createFolderAndStartRename:G,renamingFolderId:Y,renameFolderDraft:ce,setRenameFolderDraft:ae,setRenamingFolderId:W,pinnedSessionIds:Q,expandedParents:B,sessionOrderIndex:L,editingId:J,openSidebarMenuKey:fe,activeActivitySessionIds:$,unreadActivitySessionIds:Ce,notifyOnSubtasks:we,onToggleCollapsedGroup:We,dragHandleProps:$e,compactBodyPadding:Be=!1,scrollContainerRef:Ie}=t,Z=o.useCallback((_,ee)=>{const re=L.get(_.session.id),de=L.get(ee.session.id);if(re!==void 0||de!==void 0){if(re===void 0)return 1;if(de===void 0)return-1;if(re!==de)return re-de}return Wn(_.session,ee.session,Q,na)},[Q,L]),Se=a?c.get(s):null,rt=Wt(_=>_.foldersMap),Ne=a?!1:u.has(n);o.useMemo(()=>{if(s.isMain||s.isArchivedBucket||i)return null;const _=pt(s.directory??null),ee=s.branch?.trim();return _&&ee?Ka():null},[s.branch,s.directory,s.isArchivedBucket,s.isMain,i]);const ye=ra(),Re=o.useMemo(()=>{const _=s.folderScopes?.map(ee=>pt(ee.directory))??[pt(s.directory??null)];return[...new Set(_.filter(ee=>!!ee))]},[s.directory,s.folderScopes]);o.useSyncExternalStore(o.useCallback(_=>Re.length>0?ye.subscribeBootstrap(_):()=>{},[Re.length,ye]),o.useCallback(()=>Re.map(_=>`${_}\0${ye.getBootstrapState(_)??""}\0${ye.getBootstrapFailure(_)??""}`).join(""),[Re,ye]),o.useCallback(()=>"",[]));const Qe=Re.some(_=>{const ee=ye.getBootstrapState(_);return ee==="queued"||ee==="running"}),ze=Re.find(_=>ye.getBootstrapState(_)==="failed")??null,q=ze?ye.getBootstrapFailure(ze):void 0,V=q==="os-permission"&&co(),[ge,H]=o.useState(!1),xe=o.useCallback(()=>{ze&&ye.requestBootstrap({directory:ze,priority:Ne?"visible":"expanded",reason:s.isMain?"project-expanded":"worktree-expanded",force:!0})},[ye,ze,s.isMain,Ne]),ve=o.useCallback(async()=>{if(!(!ze||!V||ge)){H(!0);try{(await uo(ze)).success&&xe()}finally{H(!1)}}},[V,ze,ge,xe]),Me=x?10:5,Xe=Math.max(Me,d??Me),at=a?Se?.groupMatches===!0:!1,dt=a,Ue=o.useMemo(()=>[...dt?Se?.filteredNodes??[]:s.sessions].sort(Z),[Z,s.sessions,Se?.filteredNodes,dt]),Ae=s.folderScopeKey??pt(s.directory??null),Je=o.useMemo(()=>s.folderScopes&&s.folderScopes.length>0?s.folderScopes:Ae?[{scopeKey:Ae,directory:s.directory??null}]:[],[Ae,s.directory,s.folderScopes]),it=o.useMemo(()=>Je.flatMap(({scopeKey:_,directory:ee})=>(rt[_]??[]).map(re=>({folder:re,scopeKey:_,scopeDirectory:ee}))),[Je,rt]),wt=o.useMemo(()=>{const _=new Map,ee=re=>{re.forEach(de=>{_.set(de.session.id,de),de.children.length>0&&ee(de.children)})};return ee(Ue),_},[Ue]),yt=o.useMemo(()=>it.map(({folder:_,scopeKey:ee,scopeDirectory:re})=>{const de=Vh(_.sessionIds,wt).sort(Z);return{folder:_,scopeKey:ee,scopeDirectory:re,nodes:de}}),[it,wt,Z]),O=o.useMemo(()=>{const _=new Map(yt.map(me=>[me.folder.id,me])),ee=new Map;for(const{folder:me}of yt){if(!me.parentId)continue;const ht=ee.get(me.parentId);ht?ht.push(me.id):ee.set(me.parentId,[me.id])}const re=new Map,de=me=>{const ht=re.get(me);if(ht!==void 0)return ht;const Dt=_.get(me);if(!Dt)return re.set(me,!1),!1;const Rt=ee.get(me)??[];if(s.isArchivedBucket&&Dt.nodes.length===0){const Pt=Rt.some(rs=>de(rs));return re.set(me,Pt),Pt}if(!a||Dt.folder.name.toLowerCase().includes(l)||Dt.nodes.length>0)return re.set(me,!0),!0;const is=Rt.some(Pt=>de(Pt));return re.set(me,is),is};return yt.filter(({folder:me})=>de(me.id))},[yt,s.isArchivedBucket,a,l]),pe=o.useMemo(()=>new Set(O.flatMap(_=>_.folder.sessionIds)),[O]),De=o.useMemo(()=>Ue.filter(_=>!pe.has(_.session.id)),[Ue,pe]),y=o.useMemo(()=>O.filter(({folder:_})=>!_.parentId),[O]),z=o.useMemo(()=>{const _=new Map;return O.forEach(ee=>{if(!ee.folder.parentId)return;const re=_.get(ee.folder.parentId)??[];re.push(ee),_.set(ee.folder.parentId,re)}),_},[O]),X=o.useMemo(()=>{const _=new Map(O.map(de=>[de.folder.id,de])),ee=new Map,re=(de,me)=>{const ht=ee.get(de);if(ht!==void 0)return ht;if(me.has(de))return null;me.add(de);const Dt=_.get(de);let Rt=Dt?yi(Dt.nodes,$,Ce,we):null;for(const Zt of z.get(de)??[])if(Rt=bo(Rt,re(Zt.folder.id,me)),Rt==="active")break;return ee.set(de,Rt),Rt};return O.forEach(({folder:de})=>re(de.id,new Set)),ee},[$,O,z,we,Ce]),ue="project",he=o.useMemo(()=>{const _=new Set;return gi(Ue,J,_),O.forEach(({nodes:ee})=>{gi(ee,J,_)}),_},[Ue,O,J]),Ee=o.useMemo(()=>{if(!fe)return null;const _=Qn(Ue,fe,ue,!!s.isArchivedBucket);if(_)return _;for(const{nodes:ee}of O){const re=Qn(ee,fe,ue,!!s.isArchivedBucket);if(re)return re}return null},[fe,Ue,O,s.isArchivedBucket]),Ke=o.useCallback(_=>{const ee=new WeakMap,re=de=>{ee.set(de,Zr(de));for(const me of de.children)re(me)};return _.forEach(re),ee},[]),ft=o.useMemo(()=>Ke(Ue),[Ke,Ue]),At=o.useMemo(()=>{const _=new WeakMap;return O.forEach(({nodes:ee})=>{ee.forEach(re=>_.set(re,Zr(re)))}),_},[O]),Ze=o.useCallback(_=>ft.get(_)??At.get(_)??"",[ft,At]),mt=o.useCallback(_=>({subtreeContainsEditing:he,menuOpenSessionId:Ee,nodeStructureKey:Ze(_)}),[he,Ee,Ze]),bt=De.length,Fe=s.isArchivedBucket||a?De:De.slice(0,Xe),Ye=bt-Fe.length,St=!s.isArchivedBucket&&!a&&bt>Me&&Ye===0,Ot=s.isArchivedBucket===!0&&!a&&Fe.length>=Jh,Gt=s.isArchivedBucket?"archived":"active",vt=Ot&&Fe.some(_=>{if(_.children.length===0)return!1;const ee=`project:${Gt}:${_.session.id}`;return B.has(ee)}),P=o.useRef(null),[Pe,Le]=o.useState(null),[He,ut]=o.useState(0),[,_t]=o.useState(0);o.useEffect(()=>{if(!Ot)return;const _=P.current;if(!_||typeof ResizeObserver>"u")return;const ee=new ResizeObserver(()=>_t(re=>re+1));return ee.observe(_),()=>ee.disconnect()},[Ot]),o.useLayoutEffect(()=>{if(!Ot){Pe!==null&&Le(null),He!==0&&ut(0);return}const _=P.current;if(!_)return;let ee=Pe;const re=Ie?.current??null;if(re&&re.contains(_)){if(ee=re,ee!==Pe){Le(ee);return}}else if(!ee||!ee.contains(_)){let me=_.parentElement;for(;me;){const ht=window.getComputedStyle(me);if(ht.overflowY==="auto"||ht.overflowY==="scroll"){ee=me;break}me=me.parentElement}if(ee!==Pe){Le(ee);return}}if(!ee)return;const de=_.getBoundingClientRect().top-ee.getBoundingClientRect().top+ee.scrollTop;ut(me=>Math.abs(me-de)<1?me:de)});const M=Ot&&Pe!==null,te=Du({count:Fe.length,enabled:M,getScrollElement:()=>Pe,initialOffset:()=>Pe?.scrollTop??0,estimateSize:()=>Zh,overscan:vt?20:8,scrollMargin:He,getItemKey:_=>Fe[_]?.session.id??_}),be=o.useCallback(_=>{const ee=[],re=de=>{de.forEach(me=>{ee.push(me.session),me.children.length>0&&re(me.children)})};return re(_),ee},[]),ot=o.useMemo(()=>be(Ue),[be,Ue]),je=o.useMemo(()=>{if(!s.isArchivedBucket)return new Map;const _=new Map,ee=new Map;for(const{folder:de}of O){if(!de.parentId)continue;const me=ee.get(de.parentId)??[];me.push(de.id),ee.set(de.parentId,me)}const re=(de,me)=>{if(me.has(de))return[];me.add(de);const ht=O.find(({folder:Zt})=>Zt.id===de),Dt=ht?be(ht.nodes):[],Rt=ee.get(de)??[];for(const Zt of Rt)Dt.push(...re(Zt,me));return Dt};for(const{folder:de}of O)_.set(de.id,re(de.id,new Set));return _},[O,be,s.isArchivedBucket]);if(a&&!at&&y.length===0&&De.length===0)return null;const qe=!s.isMain&&!!s.branch,gt=s.branch&&Yc(s.branch,s.label)?{label:s.branch}:null,Et=Ne?yi(Ue,$,Ce,we):null,Ut=Et?e.jsx($a,{state:Et,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,zt=(_,ee)=>{const{folder:re,scopeKey:de,scopeDirectory:me,nodes:ht}=_,Dt=je.get(re.id)??[],Rt=a?!1:g.has(re.id);return e.jsx(Kh,{folderId:re.id,children:(Zt,is)=>e.jsx($h,{folder:re,displayName:ee,sessions:ht,isCollapsed:Rt,collapsedActivityState:Rt?X.get(re.id)??null:null,onToggle:()=>v(re.id),onRename:Pt=>{b(de,re.id,Pt)},onDelete:()=>{if(s.isArchivedBucket){zs.requestDelete({sessions:Dt,mode:"session"});return}if(!f){h(de,re.id);return}const Pt=O.filter(({folder:as})=>as.parentId===re.id).length,rs=ht.length;C({scopeKey:de,folderId:re.id,folderName:re.name,subFolderCount:Pt,sessionCount:rs})},renderSessionNode:N,getRenderExtras:Ze?Pt=>({subtreeContainsEditing:he,menuOpenSessionId:Ee,nodeStructureKey:Ze(Pt),childRenderExtrasFor:mt}):void 0,groupDirectory:me??s.directory,projectId:r,mobileVariant:m,alwaysShowActions:p,isRenaming:Y===re.id,renameDraft:Y===re.id?ce:void 0,onRenameDraftChange:Pt=>ae(Pt),onRenameSave:()=>{const Pt=ce.trim();Pt&&b(de,re.id,Pt),W(null),ae("")},onRenameCancel:()=>{W(null),ae("")},droppableRef:Zt,isDropTarget:is,depth:0,onNewSession:()=>{r&&r!==I&&R(r),D("chat"),m&&F(!1),T({selectedProjectId:r,directoryOverride:me??s.directory,targetFolderId:re.id})},hideActions:!1,archivedBucket:s.isArchivedBucket===!0})},re.id)},ns=()=>{const _=new Map;for(const de of O){const me=de.folder.parentId;if(!me)continue;const ht=_.get(me);ht?ht.push(de):_.set(me,[de])}const ee=[],re=(de,me)=>{const ht=me?`${me} / ${de.folder.name}`:de.folder.name;ee.push(zt(de,ht)),!(!a&&g.has(de.folder.id))&&(_.get(de.folder.id)??[]).forEach(Rt=>re(Rt,ht))};return y.forEach(de=>re(de,"")),ee},Jt=p?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",jt=ze?e.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[q==="os-permission"?"Folder access is required.":"Could not refresh sessions.",V?e.jsx(Ve,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",disabled:ge,onClick:()=>{ve()},children:"Grant access"}):null,e.jsx(Ve,{variant:"link",size:"xs",className:"h-auto p-0 typography-micro",onClick:xe,children:"Try again"})]}):null,It=e.jsxs(Hh,{scopeKey:Je[0]?.scopeKey??Ae,hasFolders:O.length>0,onSessionDroppedOnFolder:(_,ee)=>{const re=O.find(({folder:me})=>me.id===ee);if(!re)return;const de=Wt.getState();for(const{scopeKey:me}of Je)me!==re.scopeKey&&de.getSessionFolderId(me,_)&&de.removeSessionFromFolder(me,_);U(re.scopeKey,ee,_)},children:[ns(),Ot?e.jsx("div",{ref:P,children:M?e.jsx("div",{style:{height:te.getTotalSize(),position:"relative"},children:te.getVirtualItems().map(_=>{const ee=Fe[_.index];return ee?e.jsx("div",{"data-index":_.index,ref:te.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${_.start-He}px)`},children:N(ee,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Ee,nodeStructureKey:Ze(ee),childRenderExtrasFor:mt})},ee.session.id):null})}):Fe.map(_=>e.jsx(o.Fragment,{children:N(_,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Ee,nodeStructureKey:Ze(_),childRenderExtrasFor:mt})},_.session.id))}):Fe.map(_=>e.jsx(o.Fragment,{children:N(_,0,s.directory,r,s.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Ee,nodeStructureKey:Ze(_),childRenderExtrasFor:mt})},_.session.id)),bt===0&&O.length===0?s.isArchivedBucket?e.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):Qe?e.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}),"Loading sessions…"]})}):jt?e.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:jt}):e.jsx(_s,{icon:"chat-new",onClick:()=>{T({selectedProjectId:r,directoryOverride:s.directory})},children:"New session"}):null,bt>0&&jt?e.jsx("div",{className:"py-1 px-3 text-left typography-micro text-status-error",children:jt}):null,Ye>0?e.jsx(_s,{icon:"arrow-down-s",onClick:()=>A(n,Fe.length),children:Ye===1?"Show 1 more session":`Show ${Ye} more sessions`}):null,St?e.jsx(_s,{icon:"arrow-up-s",onClick:()=>S(n),children:"Show fewer sessions"}):null]});return i?e.jsx("div",{className:"oc-group",children:e.jsx("div",{className:"oc-group-body",children:It})}):e.jsxs("div",{className:"oc-group",children:[e.jsxs("div",{className:E("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>We(n),role:"button",tabIndex:0,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),We(n))},"aria-label":Ne?`Expand ${s.label}`:`Collapse ${s.label}`,"aria-expanded":!Ne,children:[e.jsx("div",{ref:$e?.setActivatorNodeRef,className:E("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",Jt),...$e?.listeners??{},children:e.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[e.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:s.isArchivedBucket?e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[e.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[e.jsx(j,{name:"archive",className:E("size-4 shrink-0 text-muted-foreground",p?"hidden":"group-hover/gh:hidden")}),e.jsx("span",{className:E("text-muted-foreground size-4 items-center justify-center",p?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ne?e.jsx(j,{name:"arrow-right-s",className:"size-4"}):e.jsx(j,{name:"arrow-down-s",className:"size-4"})})]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:Gn(s.label,l)}),Ut]}):!s.isMain||s.worktree?e.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[e.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[e.jsx(j,{name:"git-branch",className:E("size-4 shrink-0","text-muted-foreground",p?"hidden":"group-hover/gh:hidden"),style:void 0}),e.jsx("span",{className:E("text-muted-foreground size-4 items-center justify-center",p?"inline-flex":"hidden group-hover/gh:inline-flex"),children:Ne?e.jsx(j,{name:"arrow-right-s",className:"size-4"}):e.jsx(j,{name:"arrow-down-s",className:"size-4"})})]}),e.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:Gn(s.label,l)}),Ut,null]}):e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[e.jsx("span",{className:"min-w-0 truncate",children:Gn(s.label,l)}),Ut]})}),qe&>?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[s.isArchivedBucket?e.jsx(j,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):e.jsx(j,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:gt.label})]}):null]})}),s.isArchivedBucket&&ot.length>0?e.jsx("div",{className:E("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",p?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),zs.requestDelete({sessions:ot,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${s.label}`,children:e.jsx(j,{name:"delete-bin",className:"h-4 w-4"})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Delete archived sessions"})})]})}):null,s.directory?e.jsx("div",{className:E("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",p?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),r&&r!==I&&R(r),D("chat"),m&&F(!1),T({selectedProjectId:r,directoryOverride:s.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${s.label}`,children:e.jsx(j,{name:"add",className:"h-4 w-4"})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New draft session"})})]})}):null]}),Ne?null:e.jsx("div",{className:"oc-group-body",children:It})]})}const op=o.memo(rp,np);function ip(t){const{hideDirectoryControls:s,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:i,onOpenInstances:a,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:x,setIsSessionSearchOpen:g,sessionSearchInputRef:v,sessionSearchQuery:b,setSessionSearchQuery:h,hasSessionSearchQuery:f,searchMatchCount:C,selectionModeEnabled:N,onToggleSelectionMode:A,mobileVariant:S=!1}=t;if(s)return null;const m=E(u,"text-muted-foreground hover:text-foreground",!S&&"hover:bg-transparent");return e.jsx("div",{className:E("select-none flex-shrink-0",S?"px-2":"px-3 py-1"),children:e.jsxs("div",{className:E("flex flex-col",S?"gap-0":"h-auto min-h-8 gap-1"),children:[e.jsxs("div",{className:E("flex items-center justify-between",S?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2"),children:[e.jsxs("div",{className:E("flex min-w-0 items-center",S?"gap-0.5 overflow-x-auto":"gap-1.5"),children:[i?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:i,className:m,"aria-label":"Settings",children:e.jsx(j,{name:"settings-3",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Settings"})})]}):null,a?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:a,className:m,"aria-label":l?`Instances: ${l}`:"Instances",children:e.jsx(j,{name:"server",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:l||"Instances"})})]}):null,c?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:c,className:m,"aria-label":"Update",children:e.jsx(j,{name:"download",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Update"})})]}):null,e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,className:m,"aria-label":"Add project",children:e.jsx(j,{name:"folder-add",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Add project"})})]}),e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:r,className:m,"aria-label":"Archive",children:e.jsx(j,{name:"archive",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Archive"})})]})]}),e.jsxs("div",{className:E("flex shrink-0 items-center",S?"gap-0.5":"gap-1.5"),children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>g(p=>!p),className:m,"aria-label":"Search sessions","aria-expanded":x,children:e.jsx(j,{name:"search",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"Search sessions"})})]}),e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:A,className:E(m,N&&"bg-interactive-hover text-primary"),"aria-label":N?"Exit selection":"Select sessions","aria-pressed":N,children:e.jsx(j,{name:"checkbox-multiple",className:d})})}),e.jsx(nt,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:N?"Exit selection":"Select sessions"})})]})]})]}),x?e.jsxs("div",{className:E(S?"pb-2":"pb-1"),children:[e.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:f?e.jsx("span",{children:C===1?`${C} match`:`${C} matches`}):e.jsx("span",{})}),e.jsxs("div",{className:"relative",children:[e.jsx(j,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx("input",{ref:v,value:b,onChange:p=>h(p.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:p=>{p.key==="Escape"&&(p.stopPropagation(),f?h(""):g(!1))}}),b.length>0?e.jsx("button",{type:"button",onClick:()=>h(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:e.jsx(j,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}function ap(t){const s=oe(i=>i.toggleSidebar),n=oe(i=>i.shortcutOverrides),r=oo(fn("toggle_sidebar",n));return e.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[e.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${Wo})`}}),e.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, ${Wo})))`}}),e.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[e.jsxs("button",{type:"button",onClick:t.onNewSession,className:E("group flex min-w-0 flex-1 items-center gap-1.5 pl-[3px] text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t.touchFriendly&&"min-h-11"),children:[e.jsx(j,{name:"chat-new",className:E(Un,"text-current")}),e.jsx("span",{className:sa,children:"New session"})]}),t.showSidebarToggle?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Hide sessions",children:e.jsx(j,{name:"layout-left",className:"size-4"})})}),e.jsx(nt,{children:e.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}const lp=500,Xr=(t,s)=>E("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",t&&"py-1.5",s?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),cp=({project:t,label:s,isSelected:n,hasActive:r,canDrag:i,onSelect:a,onOpenProjectEditDialog:l,onRemoveProject:c,mobileVariant:d=!1})=>{const{listeners:u,setNodeRef:x,transform:g,transition:v,isDragging:b}=or({id:t.id,disabled:!i}),[h,f]=o.useState(!1),C=o.useRef(null),N=o.useCallback(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null)},[]);o.useEffect(()=>()=>N(),[N]);const A=o.useCallback(()=>{N(),C.current=window.setTimeout(()=>{C.current=null,f(!0)},lp)},[N]);return e.jsx("div",{ref:x,style:{transform:ir.Translate.toString(g),transition:v},className:E(b&&"opacity-60"),children:e.jsxs(Uf,{open:h,onOpenChange:f,children:[e.jsxs(zf,{render:e.jsx("button",{type:"button",onClick:()=>{h||a()},onTouchStart:A,onTouchMove:N,onTouchEnd:N,onTouchCancel:N,style:{touchAction:"manipulation"},className:Xr(d,n),"aria-pressed":n}),children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[e.jsx("span",{className:E("inline-flex size-4 shrink-0 items-center justify-center",i&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":i?`Reorder ${s}`:void 0,...i?u:{},children:e.jsx(j,{name:"folder",className:E(gn(d),"text-muted-foreground")})}),e.jsx("span",{className:xn(d),children:s})]}),e.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?e.jsx(Xn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),e.jsxs($f,{className:"min-w-[160px]",children:[e.jsxs(di,{onClick:()=>l(t.id),children:[e.jsx(j,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),e.jsx("span",{children:"Edit folder"})]}),e.jsx(Gf,{}),e.jsxs(di,{onClick:()=>c(t.id),className:"text-destructive focus:text-destructive",children:[e.jsx(j,{name:"close",className:"mr-2 h-3.5 w-3.5"}),e.jsx("span",{children:"Close folder"})]})]})]})})},dp=({projects:t,selectedProjectId:s,onSelectProject:n,onOpenDirectoryDialog:r,onOpenProjectEditDialog:i,onRemoveProject:a,hasActiveSessionByProject:l,homeDirectory:c,className:d,mobileVariant:u=!1})=>{const x=s===null,g=Lt(f=>f.reorderProjects),v=t.length>1,b=sr(yn(Ru,{activationConstraint:{distance:8}}),yn(Eu,{activationConstraint:{delay:200,tolerance:6}})),h=o.useCallback(f=>{const{active:C,over:N}=f;if(!N||C.id===N.id)return;const A=Lt.getState().projects,S=A.findIndex(p=>p.id===C.id),m=A.findIndex(p=>p.id===N.id);S<0||m<0||g(S,m)},[g]);return e.jsxs("div",{className:E("select-none px-3 pt-1 pb-2 border-b border-border/40 space-y-0.5",d),children:[e.jsx("button",{type:"button",onClick:()=>n(null),className:Xr(u,x),"aria-pressed":x,children:e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[e.jsx(j,{name:"folder",className:gn(u)}),e.jsx("span",{className:xn(u),children:"All Folders"})]})}),e.jsx(nr,{sensors:b,collisionDetection:rr,onDragEnd:h,children:e.jsx(po,{items:t.map(f=>f.id),strategy:Sa,children:t.map(f=>{const C=s===f.id,N=er(f.label?.trim()||Us(f.normalizedPath,c)||f.normalizedPath);return e.jsx(cp,{project:f,label:N,isSelected:C,hasActive:l?.(f.id),canDrag:v,onSelect:()=>n(C?null:f.id),onOpenProjectEditDialog:i,onRemoveProject:a,mobileVariant:u},f.id)})})}),e.jsxs("button",{type:"button",onClick:r,className:Xr(u,!1),children:[e.jsx(j,{name:"add",className:gn(u)}),e.jsx("span",{className:xn(u),children:"Add folder"})]})]})},br="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 up({onOpenSettings:t,onOpenShortcuts:s,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:i=!0,showUpdateButton:a=!0}){return!i&&!a?null:e.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[i?e.jsxs(e.Fragment,{children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,className:br,"aria-label":"Settings",children:e.jsx(j,{name:"settings-3",className:"h-4.5 w-4.5"})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:"Settings"})})]}),e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,className:br,"aria-label":"Shortcuts",children:e.jsx(j,{name:"command",className:"h-4.5 w-4.5"})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:"Shortcuts"})})]}),e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,className:br,"aria-label":"About PiChamber",children:e.jsx(j,{name:"information",className:"h-4.5 w-4.5"})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:"About PiChamber"})})]})]}):null,a?e.jsx(Ve,{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 fp=(t,s)=>{const n=t??{};return delete n.projectSortOrder,s<4&&delete n.displayMode,s<5&&delete n.sessionGroupingMode,n},wi=ws()(fo(t=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>t(s=>({stickyZoneHeaders:!s.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:s=>t({showRecentSection:s}),setShowArchivedSessions:s=>t({showArchivedSessions:s}),toggleRecentSection:()=>t(s=>({showRecentSection:!s.showRecentSection})),toggleArchivedSessions:()=>t(s=>({showArchivedSessions:!s.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:fp})),hp=({projectLabel:t,isCollapsed:s,alwaysShowActions:n=!1,mobileVariant:r=!1})=>{const i=s!==void 0,a=i?n?"hidden":"group-hover/project:hidden group-focus-within/project:hidden":void 0,l=gn(r),c=xn(r);return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:E("inline-flex shrink-0 items-center justify-center",l),children:[i?e.jsx("span",{className:E("items-center justify-center text-muted-foreground",l,n?"inline-flex":"hidden group-hover/project:inline-flex group-focus-within/project:inline-flex"),children:e.jsx(j,{name:s?"arrow-right-s":"arrow-down-s",className:l})}):null,e.jsx(j,{name:"folder",className:E(l,"text-muted-foreground/80",a)})]}),e.jsx("span",{className:E(c,"text-foreground"),children:t})]})},pp=({id:t,disabled:s=!1,children:n})=>{const{listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=or({id:t,disabled:s}),u=o.useMemo(()=>({listeners:r,setActivatorNodeRef:a}),[r,a]);return e.jsx("div",{ref:i,style:{transform:ir.Transform.toString(l),transition:c},className:E("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};o.memo(pp);const mp=48,gp=32,xp=24,Si=(t,s)=>er(t.label?.trim()||Us(t.normalizedPath,s)||t.normalizedPath);function bp(t){cs("ui.sidebar_projects_list.render");const s=t.isDesktopShellRuntime&&t.stickyZoneHeaders,n=o.useRef(new Map),r=o.useRef(t.getOrderedGroups);r.current!==t.getOrderedGroups&&(r.current=t.getOrderedGroups,n.current.clear());const i=(A,S)=>{const m=n.current,p=m.get(A);if(p&&p.groups===S)return p.ordered;const I=t.getOrderedGroups(A,S);if(m.set(A,{groups:S,ordered:I}),m.size>256){const R=m.keys().next().value;R!==void 0&&m.delete(R)}return I},a=o.useRef(null),l=o.useRef(0),c=o.useCallback(A=>{const m=A.scrollTop>1?Math.min(gp+A.scrollTop,mp):0;l.current=m,A.style.setProperty("--scroll-shadow-top-size",`${m}px`),A.style.setProperty("--scroll-shadow-top-clear-size",`${Math.min(Math.max(m-8,0),xp)}px`)},[]),d=o.useCallback(A=>{A.target.closest("[data-overlay-scrollbar-thumb], [data-sidebar-sticky-header]")||A.clientY-A.currentTarget.getBoundingClientRect().top>=l.current||(A.preventDefault(),A.stopPropagation())},[]),u=t.projectSections.length>0&&t.sectionsForRender.length>0;o.useLayoutEffect(()=>{s&&u&&a.current&&c(a.current)},[s,u,c]);let x=null;for(const A of t.projectSections)t.stuckProjectHeaders.has(A.project.id)&&(x=A.project);const g=x??(t.hasSharedSessions?null:t.sectionsForRender[0]?.project??null),v=g?Si(g,t.homeDirectory):null,b=o.useMemo(()=>{if(!t.isAllFoldersView)return[];const A=[];for(const S of t.sectionsForRender){const m=Si(S.project,t.homeDirectory);for(const p of S.groups)if(!p.isArchivedBucket)for(const I of p.sessions){const R=!!t.pinnedSessionIds?.has(I.session.id),D=I.session.time?.updated||I.session.time?.created||0;A.push({node:I,project:S.project,projectLabel:m,isPinned:R,timestamp:D})}}return A.sort((S,m)=>S.isPinned!==m.isPinned?S.isPinned?-1:1:m.timestamp-S.timestamp),A},[t.isAllFoldersView,t.sectionsForRender,t.homeDirectory,t.pinnedSessionIds]),[h,f]=o.useState(30);o.useEffect(()=>{f(30)},[t.hasSessionSearchQuery]);const C=b.slice(0,h),N=b.length-C.length;return t.sharedSessionsOnly?e.jsx(Ls,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:E("pt-2 pb-1",t.mobileVariant&&"pb-20"),children:e.jsxs("div",{className:"space-y-1 px-3",children:[t.topContent,t.hasSharedSessions?null:t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState]})}):t.projectSections.length===0?e.jsx(Ls,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:E("pt-2 pb-1",t.mobileVariant&&"pb-20"),children:e.jsxs("div",{className:"space-y-1 px-3",children:[t.topContent,t.emptyState]})}):t.sectionsForRender.length===0?e.jsx(Ls,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:E("pt-2 pb-1",t.mobileVariant&&"pb-20"),children:e.jsx("div",{className:"space-y-1 px-3",children:t.searchEmptyState})}):e.jsxs("div",{className:"oc-sticky-fade-root relative flex min-h-0 flex-1",onPointerDownCapture:s?d:void 0,onClickCapture:s?d:void 0,onContextMenuCapture:s?d:void 0,children:[e.jsx(Ls,{ref:a,useScrollShadow:!0,hideTopScrollShadow:!s,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:E("oc-sidebar-scroller oc-sticky-fade-scroller pt-2 pb-1 [overflow-anchor:none]",t.mobileVariant&&"pb-20"),style:s?{"--scroll-shadow-top-size":"0px"}:void 0,onScroll:s?A=>c(A.currentTarget):void 0,children:e.jsxs("div",{className:"space-y-1 px-3",children:[t.topContent,t.showOnlyMainWorkspace?e.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const A=t.sectionsForRender.find(I=>I.project.id===t.activeProjectId)??t.sectionsForRender[0];if(!A)return t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState;const S=A.groups.find(I=>I.isMain&&I.sessions.length>0)??A.groups.find(I=>I.sessions.length>0)??A.groups.find(I=>I.isMain)??A.groups[0];if(!S)return e.jsx(_s,{icon:"chat-new",onClick:()=>t.openNewSessionDraft({selectedProjectId:A.project.id,directoryOverride:A.project.normalizedPath}),children:"New session"});const m=A.groups.find(I=>I.isArchivedBucket);return[S,...m&&m.id!==S.id?[m]:[]].map(I=>{const R=`${A.project.id}:${I.id}`,D=I.id===S.id;return e.jsx(o.Fragment,{children:t.renderGroupSessions(I,R,A.project.id,D,null,!0,a)},R)})})()}):t.isAllFoldersView&&t.renderSessionNode?e.jsx("div",{children:b.length===0?t.hasSessionSearchQuery?t.searchEmptyState:t.emptyState:e.jsxs(e.Fragment,{children:[C.map(({node:A,project:S,projectLabel:m})=>{const p=A.session.directory??S.normalizedPath;return e.jsx(o.Fragment,{children:t.renderSessionNode(A,0,p,S.id,!1,{projectLabel:m,showFolderLabel:!0},"project")},A.session.id)}),N>0?e.jsx(_s,{icon:"arrow-down-s",onClick:()=>f(A=>A+30),children:N===1?"Show 1 more session":`Show ${N} more sessions`}):null,h>30&&b.length>30?e.jsx(_s,{icon:"arrow-up-s",onClick:()=>f(30),children:"Show fewer sessions"}):null]})}):e.jsx("div",{children:t.sectionsForRender.map(A=>{const S=A.project.id,m=i(S,A.groups),p=m.find(R=>R.isMain)??null,I=p?m.filter(R=>R.id!==p.id):m;return e.jsxs("div",{children:[p?t.renderGroupSessions(p,`${S}:${p.id}`,S,!0,null,void 0,a):null,I.map(R=>{const D=`${S}:${R.id}`;return e.jsx(o.Fragment,{children:t.renderGroupSessions(R,D,S,!1,null,void 0,a)},R.id)})]},S)})})]})}),s&&g&&v?e.jsx("div",{className:"oc-sticky-fade-overlay pointer-events-none absolute inset-x-0 top-0 z-30 flex items-center gap-1.5 py-1 px-3","aria-hidden":"true",children:e.jsx(hp,{id:g.id,projectLabel:v,mobileVariant:t.mobileVariant})}):null]})}const yp=o.memo(bp);function vp(t){if(typeof t!="number"||!Number.isFinite(t))return"";const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const n=s.toLocaleString("en-US",{month:"short"}),r=s.getDate(),i=s.getFullYear(),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n} ${r}, ${i}, ${a}:${l}`}function wp(t){if(t.info.role==="user")return"";const s=typeof t.info.providerID=="string"?t.info.providerID.trim():"",n=typeof t.info.modelID=="string"?t.info.modelID.trim():"";return s&&n?`${s}/${n}`:n||s}function Sp(t){const s=t.info.role==="user"?"User":"Assistant",n=vp(t.info.time?.created),r=wp(t),i=n&&r?`${n} (${r})`:n||r;return i?`**${s}**
|
|
4
|
-
|
|
5
|
-
*${i}*`:`**${s}**`}function jp(t){return t.filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("")}function Wa(t){const s=Sp(t),n=jp(t.parts).trim();return n?`${s}
|
|
6
|
-
|
|
7
|
-
${n}`:""}function Va(t,s){const n="#".repeat(Math.min(s+1,6)),r=t.agent?` — ${t.agent}`:"",i=`${n} Sub-agent: ${t.title}${r}
|
|
8
|
-
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
`,a=t.records.map(Wa).filter(Boolean).join(`
|
|
12
|
-
|
|
13
|
-
---
|
|
14
|
-
|
|
15
|
-
`),l=[i+a];for(const c of t.children)l.push(Va(c,s+1));return l.join(`
|
|
16
|
-
|
|
17
|
-
---
|
|
18
|
-
|
|
19
|
-
`)}function Ya(t,s,n){const r=s?.trim()||"Session",i=new Date().toISOString().split("T")[0],a=`# ${r}
|
|
20
|
-
|
|
21
|
-
*Exported on ${i}*
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
`,l=t.map(Wa).filter(Boolean).join(`
|
|
26
|
-
|
|
27
|
-
---
|
|
28
|
-
|
|
29
|
-
`);let c=a+l;if(n&&n.length>0){const d=n.map(u=>Va(u,1)).join(`
|
|
30
|
-
|
|
31
|
-
---
|
|
32
|
-
|
|
33
|
-
`);c+=`
|
|
34
|
-
|
|
35
|
-
---
|
|
36
|
-
|
|
37
|
-
`+d}return c}function qa(t,s){const n=new Blob([t],{type:"text/markdown;charset=utf-8"}),r=URL.createObjectURL(n),i=document.createElement("a");i.href=r,i.download=s,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}async function Qa(t,s){const n=await cu(s,t);return n||null}async function Cp(t){const s=lo()?.files;if(s?.revealPath)try{return!!(await s.revealPath(t))?.success}catch{return!1}return await du(t)?!0:fa(t)}function kp(){return qc()}function Ja(t){const r=(t?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",i=new Date().toISOString().split("T")[0];return`${r}-${i}.md`}const Np=(t,s)=>{if(!s)return Array.from(t);const n=[],r=new Set;for(const i of t){r.has(i)||(r.add(i),n.push(i));const a=s.get(i);if(a)for(const l of a)r.has(l)||(r.add(l),n.push(l))}return n},Vt=ws()((t,s)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{s().enabled||t({enabled:!0})},disable:()=>{t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{s().enabled?t({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):t({enabled:!0})},toggleSelected:(n,r,i)=>{const a=s(),l=new Set(a.selectedIds);let c=a.scopeKey,d=a.anchorId;r!==null&&a.scopeKey!==null&&r!==a.scopeKey?(l.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const x=i&&i.length>0?[n,...i]:[n];if(l.has(n)){for(const v of x)l.delete(v);d===n&&(d=null)}else{for(const v of x)l.add(v);d=n}l.size===0?t({selectedIds:l,scopeKey:null,anchorId:null}):t({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,i,a,l)=>{const c=s();if(i.length===0)return;const d=n&&i.includes(n)?n:i[0],u=i.indexOf(d),x=i.indexOf(r);if(u<0||x<0)return;const[g,v]=u<=x?[u,x]:[x,u],b=i.slice(g,v+1),h=Np(b,l),C=a!==null&&c.scopeKey!==null&&a!==c.scopeKey?new Set:new Set(c.selectedIds);for(const N of h)C.add(N);t({selectedIds:C,scopeKey:a??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){t({selectedIds:new Set,scopeKey:null,anchorId:null});return}t({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{t({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=s();if(r.selectedIds.size===0||n.length===0)return;const i=new Set(r.selectedIds);for(const a of n)i.delete(a);i.size!==r.selectedIds.size&&(i.size===0?t({selectedIds:i,scopeKey:null,anchorId:null}):t({selectedIds:i}))}}));let eo=!1;const to=new Set;let ji=!1;function Ap(){for(const t of to)t()}function yo(t){eo!==t&&(eo=t,Ap())}function Ip(t){t.key==="Shift"&&yo(!0)}function Dp(t){t.key==="Shift"&&yo(!1)}function Pp(){yo(!1)}function Tp(){ji||typeof window>"u"||(ji=!0,window.addEventListener("keydown",Ip),window.addEventListener("keyup",Dp),window.addEventListener("blur",Pp))}function Ep(t){return Tp(),to.add(t),()=>{to.delete(t)}}function Rp(){return eo}function Mp(){return!1}function Fp(){return Ge.useSyncExternalStore(Ep,Rp,Mp)}const yr=new WeakMap,Lp=t=>{if(typeof window>"u")return;const s=t.closest("[data-session-row]"),n=s?.closest(".overlay-scrollbar-container");if(!s||!n)return;yr.get(n)?.();const r=s.getBoundingClientRect().top;let i=3,a=!1,l=null;const c=()=>{a=!0,l!==null&&window.cancelAnimationFrame(l),l=null,yr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(a||!s.isConnected||!n.isConnected){c();return}const u=s.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,cs("ui.sidebar.selection_scroll_anchor_adjustment")),i-=1,i<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),yr.set(n,c),l=window.requestAnimationFrame(d)},Op=o.memo(function({archiveLabel:s,deleteLabel:n,buttonSizeClass:r,iconSizeClass:i,onPointerDown:a,onMouseDown:l,onArchive:c,onDelete:d}){const u=Fp(),x=u?n:s,g=v=>{if(u||v.shiftKey){d(v);return}c(v)};return e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",className:E("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":x,onPointerDown:a,onMouseDown:l,onClick:g,onKeyDown:v=>v.stopPropagation(),children:e.jsx(j,{name:u?"delete-bin":"archive",className:i})})}),e.jsx(nt,{side:"left",sideOffset:8,children:x})]})});function Bp(t){cs("ui.sidebar_session_node.render");const{node:s,depth:n=0,groupDirectory:r,projectId:i,archivedBucket:a=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,notifyOnSubtasks:x,editingId:g,setEditingId:v,editTitle:b,setEditTitle:h,handleSaveEdit:f,handleCancelEdit:C,toggleParent:N,handleSessionSelect:A,handleSessionDoubleClick:S,togglePinnedSession:m,handleShareSession:p,copiedSessionId:I,handleCopyShareUrl:R,handleCopySessionId:D,handleUnshareSession:F,openSidebarMenuKey:T,setOpenSidebarMenuKey:U,renamingFolderId:G,getFoldersForScope:Y,getSessionFolderId:ce,removeSessionFromFolder:ae,addSessionToFolder:W,createFolderAndStartRename:Q,openContextPanelTab:B,handleDeleteSession:L,handleRestoreSession:J,mobileVariant:fe,alwaysShowActions:$,renderSessionNode:Ce,secondaryMeta:we,renderContext:We="project",subtreeContainsEditing:$e,menuOpenSessionId:Be,childRenderExtrasFor:Ie}=t,Z=o.useMemo(()=>ha(),[]),Se=!a&&!fe,rt=o.useRef(!1),Ne=o.useRef(g);Ne.current=g;const ye=o.useRef(null),Re=o.useRef(f);Re.current=f;const[Qe,ze]=o.useState(b),q=o.useRef(Qe);q.current=Qe;const V=o.useRef(null),ge=o.useRef(null),H=s.session,xe=H,ve=pt(H.directory??null)??pt(r??null),Me=Oe(K=>K.currentSessionId===H.id),Xe=oa(ve),at=Qc(ve),dt=Lt(o.useCallback(K=>{if(we?.projectLabel||!i)return null;const _e=K.projects.find(lt=>lt.id===i);return _e?_e.label?.trim()||Us(pt(_e.path)??_e.path,null)||_e.path:null},[i,we?.projectLabel])),Ue=we?.projectLabel??(dt?er(dt):null),Ae=we?.branchLabel??s.worktree?.branch??(Xe&&Xe!=="HEAD"?Xe:null),Je=Ae,it=at===!0||!!(Ae||s.worktree),wt=s.children.length,yt=xe.agent;o.useMemo(()=>{const K=s.worktree?.branch?.trim()||Ae?.trim(),_e=pt(s.worktree?.path??ve);return K&&_e?Ka():null},[s.worktree,Ae,ve]);const O=Qh();o.useMemo(()=>null,[O]);const pe=i??ve??null,De=aa(),y=io(),z=Vt(K=>K.enabled),X=Vt(o.useCallback(K=>K.selectedIds.has(H.id),[H.id])),ue=Vt(K=>K.toggleSelected),he=Vt(K=>K.setRange),Ee=o.useCallback(K=>{const _e=[],lt=Ct=>{Ct.children.forEach(kt=>{_e.push(kt.session.id),lt(kt)})};return lt(K),_e},[]);o.useCallback(K=>{const _e=[],lt=Ct=>{Ct.children.forEach(kt=>{_e.push(kt.session),lt(kt)})};return lt(K),_e},[]);const[Ke,ft]=o.useState(!1),[At,Ze]=o.useState(!0),mt=`${We}:${a?"archived":"active"}:${H.id}`,bt=Jc(o.useCallback(K=>!!K.sessionMemoryState.get(Zc(H.id))?.isZombie,[H.id])),Ye=ia(H.id)?.type??"idle",St=Ye==="busy"||Ye==="retry",Ot=Xc(H.id,St),Gt=ed(H.id),vt=xe.title||"Untitled Session",P=s.children.length>0,Pe=td(l,ve,H.id),Le=mt,He=d?!0:c.has(Le);o.useMemo(()=>Wh(s,He,ve),[He,s,ve]);const ut=id(),_t=!!xe.parentID,te=sd(H.id)>0&&(!_t||x),be=xe.time?.updated||xe.time?.created||Date.now(),ot=ad(be),[je,qe]=o.useState(!1),gt=o.useMemo(()=>Ee(s).length,[Ee,s]),Et=o.useCallback(async K=>{const _e=[];let lt=0;for(const Ct of K)try{if(!ve)throw new Error("Session directory is required for export");await y.loadCompleteHistory?.(Ct.session.id,ve);const kt=Lr(De.getState(),Ct.session.id).list,Bt=Ct.session.title||"Untitled Sub-agent",Kt=Ct.session.agent,Ht=await Et(Ct.children);lt+=Ht.skipped,_e.push({title:Bt,agent:Kt,records:kt,children:Ht.children})}catch{lt+=Ee(Ct).length+1}return{children:_e,skipped:lt}},[Ee,De,ve,y]),Ut=o.useCallback(K=>{K<=0||ne.warning(K===1?`Exported session, but skipped ${K} sub-agent task that could not be loaded.`:`Exported session, but skipped ${K} sub-agent tasks that could not be loaded.`)},[]),zt=o.useCallback(async K=>{if(!ve){ne.error("Nothing to export");return}try{await y.loadCompleteHistory?.(H.id,ve)}catch{ne.error("Failed to load the complete session history");return}const _e=Lr(De.getState(),H.id).list;if(_e.length===0){ne.error("Nothing to export");return}let lt,Ct=0;if(K&&s.children.length>0){const Ht=await Et(s.children);lt=Ht.children,Ct=Ht.skipped}const kt=Ya(_e,xe.title??null,lt),Bt=Ja(xe.title??null),Kt=await Qa(kt,Bt);if(Kt){ne.success("Session exported",{action:{label:kp(),onClick:()=>{Cp(Kt).then(Ht=>{Ht||ne.error("Failed to reveal path")})}}}),Ut(Ct);return}qa(kt,Bt),ne.success("Session exported"),Ut(Ct)},[Et,De,s.children,xe.title,H.id,ve,Ut,y]),ns=o.useCallback(async()=>{if(s.children.length>0){Ze(!0),ft(!0);return}await zt(!1)},[zt,s.children.length]),Jt=o.useCallback(()=>{ve&&hn("desktop_open_session_mini_chat_window",{sessionId:H.id,directory:ve,apiBaseUrl:_r(),clientToken:Br()}).catch(K=>{console.warn("[session-sidebar] failed to open mini chat window",K)})},[H.id,ve]);o.useEffect(()=>{if(g!==H.id)return;const K=_e=>{const Ct=_e.target?.closest?.(`[data-session-rename-form="${CSS.escape(H.id)}"]`);ge.current&&!Ct&&Re.current(q.current)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[g,H.id]),o.useLayoutEffect(()=>{if(g!==H.id){V.current===H.id&&(V.current=null);return}V.current!==H.id&&(V.current=H.id,ze(b))},[g,b,H.id]);const jt=Gt.length,It=!St&&te&&!Me,_=St&&Ot,ee=Pe,re=e.jsx(j,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),de=ee?e.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:re}):null,me=P?e.jsx("button",{type:"button",onClick:K=>{K.stopPropagation(),N(Le)},onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),K.stopPropagation(),N(Le))},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":He?"Collapse subsessions":"Expand subsessions",children:He?e.jsx(j,{name:"arrow-down-s",className:"h-3 w-3"}):e.jsx(j,{name:"arrow-right-s",className:"h-3 w-3"})}):null,ht=bt?e.jsx(j,{name:"error-warning",className:"h-4 w-4 text-status-warning"}):null,Dt=K=>{if(!K&&ye.current){const{id:_e,title:lt}=ye.current;ye.current=null,v(_e),h(lt)}},Rt=K=>{qe(K)},Zt=K=>{K.preventDefault(),K.stopPropagation()},is=K=>{K.preventDefault(),K.stopPropagation()},Pt=K=>{K.preventDefault(),K.stopPropagation(),U(null),L(H,{archivedBucket:a})},rs=K=>{K.preventDefault(),K.stopPropagation(),U(null),L(H,{archivedBucket:a,hardDelete:!0,skipConfirm:!0})},as=K=>{if(rt.current){rt.current=!1;return}if(z){if(K?.preventDefault(),K?.stopPropagation(),K?.shiftKey){const lt=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(Bt=>Bt.getAttribute("data-session-row")).filter(Bt=>typeof Bt=="string"&&Bt.length>0),Ct=Vt.getState().anchorId,kt=new Map;kt.set(H.id,Ee(s)),he(Ct,H.id,lt,pe,kt);return}ue(H.id,pe,Ee(s));return}K?.currentTarget&&Lp(K.currentTarget),A(H.id,ve)},ds=K=>{K.defaultPrevented||K.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||as(K)},on=K=>{(K.button===2||K.button===0&&K.ctrlKey&&!z)&&(rt.current=!0)},Hs=({Item:K,Separator:_e,Sub:lt,SubTrigger:Ct,SubContent:kt})=>e.jsxs(e.Fragment,{children:[e.jsxs(K,{onClick:()=>{ye.current={id:H.id,title:vt}},className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),e.jsxs(K,{onClick:()=>D(H.id),className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),e.jsxs(K,{onClick:()=>ve&&m({directory:ve,sessionId:H.id}),className:"[&>svg]:mr-1",children:[Pe?e.jsx(j,{name:"unpin",className:"mr-1 h-4 w-4"}):e.jsx(j,{name:"pushpin",className:"mr-1 h-4 w-4"}),Pe?"Unpin session":"Pin session"]}),xe.share?e.jsxs(e.Fragment,{children:[e.jsx(K,{onClick:()=>{xe.share?.url&&R(xe.share.url,H.id)},className:"[&>svg]:mr-1",children:I===H.id?e.jsxs(e.Fragment,{children:[e.jsx(j,{name:"check",className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(j,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(K,{onClick:()=>F(H.id),className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"link-unlink-m",className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(K,{onClick:()=>p(xe),className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"share-2",className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(K,{onClick:()=>{ns()},className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),ve&&!a?(()=>{const Bt=[],Kt=Nt=>{const Mt=pt(Nt??null);Mt&&!Bt.includes(Mt)&&Bt.push(Mt)};if(i){const Nt=Lt.getState().projects.find(Ss=>Ss.id===i),Mt=pt(Nt?.path??null);Kt(Mt)}Kt(ve);const Ht=Bt.flatMap(Nt=>Y(Nt).map(Mt=>({scope:Nt,folder:Mt}))),Xt=Ht.find(({scope:Nt,folder:Mt})=>ce(Nt,H.id)===Mt.id)??null,Ps=Bt[0]??ve;return e.jsxs(e.Fragment,{children:[e.jsx(_e,{}),e.jsxs(lt,{children:[e.jsxs(Ct,{className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"folder",className:"h-4 w-4"}),"Move to folder"]}),e.jsxs(kt,{className:"min-w-[180px]",children:[Ht.length===0?e.jsx(K,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):Ht.map(({scope:Nt,folder:Mt})=>{const Ss=Xt?.folder.id===Mt.id;return e.jsxs(K,{onClick:()=>{if(Ss){ae(Nt,H.id);return}Xt&&Xt.scope!==Nt&&ae(Xt.scope,H.id),W(Nt,Mt.id,H.id)},children:[e.jsx("span",{className:"flex-1 truncate",children:Mt.name}),Ss?e.jsx(j,{name:"check",className:"ml-2 h-3.5 w-3.5 text-primary flex-shrink-0"}):null]},Mt.id)}),e.jsx(_e,{}),e.jsxs(K,{onClick:()=>{const Nt=Q(Ps);Nt&&(Xt&&Xt.scope!==Ps&&ae(Xt.scope,H.id),W(Ps,Nt.id,H.id))},children:[e.jsx(j,{name:"add",className:"mr-1 h-4 w-4"}),"New folder..."]}),Xt?e.jsxs(K,{onClick:()=>{ae(Xt.scope,H.id)},className:"text-destructive focus:text-destructive",children:[e.jsx(j,{name:"close",className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]})]})})():null,e.jsxs(K,{disabled:!ve,onClick:()=>{ve&&B(ve,{mode:"chat",dedupeKey:`session:${H.id}`,label:vt,sessionTitleFallback:vt})},className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"chat-4",className:"mr-1 h-4 w-4"}),e.jsx("span",{className:"truncate",children:"Open in Side Panel"}),e.jsx("span",{className:"shrink-0 typography-micro px-1 rounded leading-none pb-px text-[var(--status-warning)] bg-[var(--status-warning)]/10",children:"beta"})]}),Z?e.jsxs(K,{disabled:!ve,onClick:Jt,className:"[&>svg]:mr-1",children:[e.jsx(j,{name:"window",className:"mr-1 h-4 w-4"}),e.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,e.jsx(_e,{}),a?null:e.jsxs(K,{className:"[&>svg]:mr-1",onClick:()=>L(H,{archivedBucket:a}),children:[e.jsx(j,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?e.jsxs(K,{className:"[&>svg]:mr-1",onClick:()=>J(H),children:[e.jsx(j,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,e.jsxs(K,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>L(H,{archivedBucket:a,hardDelete:!0}),children:[e.jsx(j,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]});Yt,Hs({Item:ct,Separator:As,Sub:ld,SubTrigger:cd,SubContent:dd});const Ws=e.jsx(Gr,{children:e.jsx(Kr,{className:"app-region-no-drag z-50",children:e.jsx(Hr,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(G||Ne.current),style:{color:"var(--surface-elevated-foreground)"},className:E(Rr,"min-w-[180px]"),children:Hs({Item:({className:K,..._e})=>e.jsx(ba,{className:E(qi,K),..._e}),Separator:({className:K,..._e})=>e.jsx(ya,{className:E(Qi,K),..._e}),Sub:Nu,SubTrigger:({className:K,children:_e,...lt})=>e.jsxs(Au,{className:E(od,K),...lt,children:[_e,e.jsx(j,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:K,children:_e,...lt})=>e.jsx(Gr,{children:e.jsx(Kr,{className:"app-region-no-drag z-50",children:e.jsx(Hr,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:E(Rr,K),...lt,children:_e})})})})})})});return e.jsxs(o.Fragment,{children:[e.jsx(Gh,{sessionId:H.id,sessionDirectory:ve??null,sessionTitle:vt,children:e.jsxs(ga,{open:je,onOpenChange:Rt,onOpenChangeComplete:Dt,children:[e.jsxs(xa,{render:e.jsx("div",{"data-session-row":H.id,"data-session-scope":pe??"","data-session-archived":a?"1":"0",onClick:ds,style:n>0?{marginLeft:`${n*14}px`}:void 0,className:E("group relative my-0.5 flex cursor-pointer items-center rounded-xl px-3 py-2 transition-colors",n>0?"bg-secondary/30 hover:bg-interactive-hover":"hover:bg-interactive-hover",Me&&!X&&"bg-interactive-selection",X&&"bg-interactive-selection")}),children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[me,de,g===H.id?e.jsxs("form",{ref:ge,"data-session-rename-form":H.id,className:"flex min-h-8 min-w-0 flex-1 items-center gap-2",onPointerDown:K=>K.stopPropagation(),onMouseDown:K=>K.stopPropagation(),onSubmit:K=>{K.preventDefault(),f(Qe)},children:[e.jsx("input",{value:Qe,onChange:K=>ze(K.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:K=>{K.stopPropagation(),K.key==="Escape"&&C()}}),e.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:e.jsx(j,{name:"check",className:"size-4"})}),e.jsx("button",{type:"button",onClick:C,"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:e.jsx(j,{name:"close",className:"size-4"})})]}):e.jsxs("button",{type:"button",onMouseDown:on,onClick:K=>as(K),onDoubleClick:K=>{K.stopPropagation(),S(H.id,vt)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-0.5 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[e.jsx("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:e.jsx("div",{className:E("block min-w-0 flex-1 truncate font-normal typography-ui-label",te?"text-foreground":"text-foreground/90"),children:Gn(vt,u)})}),we?.showFolderLabel&&Ue||Je||it||O||wt>0||yt&&yt!=="default"||_||jt>0||ut>0?e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-2 overflow-hidden pt-0.5 typography-ui-label font-normal text-muted-foreground",children:[we?.showFolderLabel&&Ue?e.jsx("span",{className:"min-w-0 max-w-[110px] shrink-0 truncate",children:Ue}):null,Je?e.jsxs("span",{className:"inline-flex min-w-0 max-w-[160px] shrink-0 items-center gap-1",children:[e.jsx(j,{name:"git-branch",className:E("size-3.5 shrink-0","text-muted-foreground"),style:void 0}),e.jsx("span",{className:"truncate",children:Je})]}):it?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[e.jsx(j,{name:"git-repository",className:"size-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:"git"})]}):null,null,wt>0?e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[e.jsx(j,{name:"node-tree",className:"size-3.5 shrink-0"}),e.jsx("span",{children:wt})]}):null,yt&&yt!=="default"?e.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:yt}):null,_?e.jsx(nd,{sessionId:H.id,running:St,className:"text-muted-foreground/70"}):null,jt>0?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-destructive shrink-0","aria-label":"Permission required",children:[e.jsx(j,{name:"shield",className:"size-3.5"}),e.jsx("span",{children:jt})]}):null,null]}):null]})]}),Pe?e.jsx(j,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,e.jsxs("div",{className:"relative ml-1 flex h-6 min-w-6 shrink-0 items-center justify-end",children:[e.jsx("div",{className:E("flex items-center justify-end",Se&&($||je)?"opacity-0":Se?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:St?e.jsx(Xn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):It?e.jsx(rd,{label:"Session complete"}):e.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:ot})}),Se?e.jsx("div",{className:E("absolute inset-0 flex items-center justify-end",$||je?"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:e.jsx(Op,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Zt,onMouseDown:is,onArchive:Pt,onDelete:rs})}):null]}),ht&&!fe?e.jsx("div",{className:"absolute right-0 top-1/2 -translate-y-1/2 z-10",children:ht}):null]}),Ws]})}),P&&He?s.children.map(K=>{const _e=Ie?Ie(K):{subtreeContainsEditing:$e,menuOpenSessionId:Be,nodeStructureKey:""};return e.jsx(o.Fragment,{children:Ce(K,n+1,ve??r,i,a,void 0,We,_e)},K.session.id)}):null,e.jsx(hs,{open:Ke,onOpenChange:ft,children:e.jsxs(ps,{showCloseButton:!1,className:"max-w-sm gap-5",children:[e.jsxs(Ds,{children:[e.jsx(vs,{children:"Export Markdown"}),e.jsx(Gs,{children:gt===1?`This session has ${gt} sub-agent task. Include it in the export?`:`This session has ${gt} sub-agent tasks. Include them in the export?`})]}),e.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:At,onChange:K=>Ze(K.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),e.jsxs(Ks,{children:[e.jsx(Ve,{type:"button",onClick:()=>ft(!1),variant:"outline",size:"sm",children:"Cancel"}),e.jsx(Ve,{type:"button",onClick:()=>{ft(!1),zt(At)},size:"sm",children:"Export"})]})]})})]},H.id)}const Ci=t=>pt(t.session.directory??null),_p=(t,s)=>(t?.projectLabel??null)===(s?.projectLabel??null)&&(t?.branchLabel??null)===(s?.branchLabel??null)&&(t?.showFolderLabel??!1)===(s?.showFolderLabel??!1),Up=t=>{if(!t.openSidebarMenuKey)return null;const s=t.archivedBucket?"archived":"active",n=`${t.renderContext??"project"}:${s}:`;return t.openSidebarMenuKey.startsWith(n)?t.openSidebarMenuKey.slice(n.length):null},Mn=t=>t.menuOpenSessionId??Up(t),Fn=(t,s,n)=>s?n.has(t.node.session.id)?!0:bs(t.node,s):!1,so=(t,s,n,r,i)=>{if(t.session.id!==s.session.id)return!0;const a=i(t);if(n.has(a)!==r.has(a)||t.children.length!==s.children.length)return!0;for(let l=0;l<t.children.length;l+=1)if(so(t.children[l],s.children[l],n,r,i))return!0;return!1},zp=(t,s)=>{if(t.hasSessionSearchQuery||s.hasSessionSearchQuery)return!1;const n=t.archivedBucket?"archived":"active",r=s.archivedBucket?"archived":"active";return so(t.node,s.node,t.expandedParents,s.expandedParents,i=>`${t.renderContext??"project"}:${n}:${i.session.id}`)||so(t.node,s.node,t.expandedParents,s.expandedParents,i=>`${s.renderContext??"project"}:${r}:${i.session.id}`)},$p=(t,s)=>{if(t.node.session.id!==s.node.session.id||t.node.session!==s.node.session||t.depth!==s.depth||t.groupDirectory!==s.groupDirectory||t.projectId!==s.projectId||t.archivedBucket!==s.archivedBucket||(t.renderContext??"project")!==(s.renderContext??"project")||t.mobileVariant!==s.mobileVariant||t.alwaysShowActions!==s.alwaysShowActions||t.hasSessionSearchQuery!==s.hasSessionSearchQuery||t.normalizedSessionSearchQuery!==s.normalizedSessionSearchQuery||t.notifyOnSubtasks!==s.notifyOnSubtasks||t.nodeStructureKey!==s.nodeStructureKey||Ci(t.node)!==Ci(s.node)||!_p(t.secondaryMeta,s.secondaryMeta)||t.pinnedSessionIds!==s.pinnedSessionIds&&Ga(t.node,s.node,t.pinnedSessionIds,s.pinnedSessionIds,t.groupDirectory,s.groupDirectory)||t.expandedParents!==s.expandedParents&&zp(t,s)||t.editingId!==s.editingId&&(Fn(t,t.editingId,t.subtreeContainsEditing)||Fn(s,s.editingId,s.subtreeContainsEditing))||t.editTitle!==s.editTitle&&(Fn(t,t.editingId,t.subtreeContainsEditing)||Fn(s,s.editingId,s.subtreeContainsEditing))||t.copiedSessionId!==s.copiedSessionId&&(bs(t.node,t.copiedSessionId)||bs(s.node,s.copiedSessionId)))return!1;if(t.openSidebarMenuKey!==s.openSidebarMenuKey){const n=Mn(t),r=Mn(s);if(bs(t.node,n)||bs(s.node,r))return!1}if(t.renamingFolderId!==s.renamingFolderId){const n=Mn(t),r=Mn(s);if(bs(t.node,n)||bs(s.node,r))return!1}return t.setEditingId===s.setEditingId&&t.setEditTitle===s.setEditTitle&&t.handleSaveEdit===s.handleSaveEdit&&t.handleCancelEdit===s.handleCancelEdit&&t.toggleParent===s.toggleParent&&t.handleSessionSelect===s.handleSessionSelect&&t.handleSessionDoubleClick===s.handleSessionDoubleClick&&t.togglePinnedSession===s.togglePinnedSession&&t.handleShareSession===s.handleShareSession&&t.handleCopyShareUrl===s.handleCopyShareUrl&&t.handleCopySessionId===s.handleCopySessionId&&t.handleUnshareSession===s.handleUnshareSession&&t.setOpenSidebarMenuKey===s.setOpenSidebarMenuKey&&t.getFoldersForScope===s.getFoldersForScope&&t.getSessionFolderId===s.getSessionFolderId&&t.removeSessionFromFolder===s.removeSessionFromFolder&&t.addSessionToFolder===s.addSessionToFolder&&t.createFolderAndStartRename===s.createFolderAndStartRename&&t.openContextPanelTab===s.openContextPanelTab&&t.handleDeleteSession===s.handleDeleteSession&&t.handleRestoreSession===s.handleRestoreSession&&t.renderSessionNode===s.renderSessionNode},Gp=o.memo(Bp,$p),ki={selected:0,"active-project":1,expanded:2,visible:3,background:4};function Kp(t){const s=new Map,n=(r,i,a)=>{const l=pt(r??null);if(!l)return;const c=s.get(l);c&&ki[c.priority]<=ki[i]||s.set(l,{directory:l,priority:i,reason:a})};for(const r of t.projectSections){const i=!t.collapsedProjects.has(r.project.id);let a="background";r.project.id===t.activeProjectId?a="active-project":i&&(a="expanded"),n(r.project.normalizedPath,a,i?"project-expanded":"known-project");for(const l of r.groups){if(!l.directory||l.isArchivedBucket||l.isMain)continue;const c=i&&!t.collapsedGroups.has(`${r.project.id}:${l.id}`);let d="background";c?d="expanded":i&&(d="visible"),n(l.directory,d,c?"worktree-expanded":"known-worktree")}}return n(t.currentDirectory,"selected","current-directory"),n(t.currentSessionDirectory,"selected","selected-session"),[...s.values()]}function Hp(t){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=t,l="Untitled Session";return e.jsx(hs,{open:!!s,onOpenChange:c=>{c||n(null)},children:e.jsxs(ps,{showCloseButton:!1,className:"max-w-sm gap-5",children:[e.jsxs(Ds,{children:[e.jsx(vs,{children:s?.archivedBucket?"Delete session?":"Archive session?"}),e.jsx(Gs,{children:s&&s.descendantCount>0?s.archivedBucket?s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be permanently deleted.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be permanently deleted.`:s.descendantCount===1?`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-task will be archived.`:`\\"${s.session.title||l}\\" and its ${s.descendantCount} sub-tasks will be archived.`:s?.archivedBucket?`\\"${s?.session.title||l}\\" will be permanently deleted.`:`\\"${s?.session.title||l}\\" will be archived.`})]}),e.jsxs(Ks,{className:"w-full sm:items-center sm:justify-between",children:[e.jsxs("button",{type:"button",onClick:()=>i(!r),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!r,children:[r?e.jsx(j,{name:"checkbox-blank",className:"h-4 w-4"}):e.jsx(j,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.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"}),e.jsx("button",{type:"button",onClick:()=>{a()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:s?.archivedBucket?"Delete":"Archive"})]})]})]})})}function Wp(t){const{value:s,setValue:n,showDeletionDialog:r,setShowDeletionDialog:i,onConfirm:a}=t,l=s?.archivedBucket===!0,c=s?.sessionCount??0,d=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=l?c===1?`${c} session will be permanently deleted.`:`${c} sessions will be permanently deleted.`:c===1?`${c} session will be archived.`:`${c} sessions will be archived.`;return e.jsx(hs,{open:!!s,onOpenChange:x=>{x||n(null)},children:e.jsxs(ps,{showCloseButton:!1,className:"max-w-sm gap-5",children:[e.jsxs(Ds,{children:[e.jsx(vs,{children:d}),e.jsx(Gs,{children:u})]}),e.jsxs(Ks,{className:"w-full sm:items-center sm:justify-between",children:[e.jsxs("button",{type:"button",onClick:()=>i(!r),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!r,children:[r?e.jsx(j,{name:"checkbox-blank",className:"h-4 w-4"}):e.jsx(j,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.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"}),e.jsx("button",{type:"button",onClick:()=>{a()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:l?"Delete":"Archive"})]})]})]})})}function Vp(t){const{value:s,setValue:n,onConfirm:r}=t;return e.jsx(hs,{open:!!s,onOpenChange:i=>{i||n(null)},children:e.jsxs(ps,{showCloseButton:!1,className:"max-w-sm gap-5",children:[e.jsxs(Ds,{children:[e.jsx(vs,{children:"Delete folder?"}),e.jsx(Gs,{children:s&&(s.subFolderCount>0||s.sessionCount>0)?s.subFolderCount>0?s.subFolderCount===1?`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted along with ${s.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`\\"${s.folderName}\\" will be deleted. Sessions inside will not be deleted.`:`\\"${s?.folderName??""}\\" will be permanently deleted.`})]}),e.jsxs(Ks,{children:[e.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"}),e.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 Yp=({selectedCount:t,scopeKey:s,scopeFolders:n,archivedBucket:r,onMoveToFolder:i,onCreateFolderAndMove:a,onRemoveFromFolder:l,canRemoveFromFolder:c,onRestore:d,onDelete:u,onDone:x})=>{const g=!!s&&!r,v=r?"Delete":"Archive",b="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 e.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border px-3 py-1.5",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${t} selected`}),e.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[g?e.jsxs(qt,{children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:b,"aria-label":"Move to folder",children:e.jsx(j,{name:"folder",className:"h-4 w-4"})})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:"Move to folder"})})]}),e.jsxs(Yt,{align:"end",className:"min-w-[180px]",children:[n.length===0?e.jsx(ct,{disabled:!0,className:"text-muted-foreground",children:"No folders yet"}):n.map(f=>e.jsx(ct,{onClick:()=>i(f.id),children:e.jsx("span",{className:"flex-1 truncate",children:f.name})},f.id)),e.jsx(As,{}),e.jsxs(ct,{onClick:a,children:[e.jsx(j,{name:"add",className:"mr-1 h-4 w-4"}),"New folder..."]}),c?e.jsxs(ct,{onClick:l,className:"text-destructive focus:text-destructive",children:[e.jsx(j,{name:"close",className:"mr-1 h-4 w-4"}),"Remove from folder"]}):null]})]}):null,r?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:d,className:b,"aria-label":"Restore",children:e.jsx(j,{name:"inbox-unarchive",className:"h-4 w-4"})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:"Restore"})})]}):null,e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:u,className:E("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":v,children:e.jsx(j,{name:"delete-bin",className:"h-4 w-4"})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:v})})]}),e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:x,className:b,"aria-label":"Exit selection",children:e.jsx(j,{name:"close",className:"h-4 w-4"})})}),e.jsx(nt,{side:"top",sideOffset:4,children:e.jsx("p",{children:"Exit selection"})})]})]})]})},qp=t=>{const{isInlineEditing:s,showDeletionDialog:n,foldersMap:r,folderScopesByProject:i,addSessionsToFolder:a,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:x,setBulkDeleteConfirm:g}=t,v=Vt(Q=>Q.enabled),b=Vt(Q=>Q.selectedIds.size),h=b>0,f=Vt(Q=>Q.selectedIds),C=Vt(Q=>Q.scopeKey),N=o.useCallback(()=>{Vt.getState().toggleMode()},[]),A=o.useCallback(()=>{Vt.getState().disable()},[]),S=o.useMemo(()=>{if(!h||typeof document>"u")return!1;let Q=!1,B=!1;for(const L of f){const J=document.querySelectorAll(`[data-session-row="${CSS.escape(L)}"]`);for(const fe of J)fe.getAttribute("data-session-archived")==="1"?B=!0:Q=!0}return B&&!Q},[h,f]),m=o.useMemo(()=>{if(C)return C;if(!h||typeof document>"u")return null;for(const Q of f){const L=document.querySelector(`[data-session-row="${CSS.escape(Q)}"]`)?.getAttribute("data-session-scope");if(L&&L.length>0)return L}return null},[h,f,C]),p=o.useMemo(()=>{if(!m)return[];const Q=i.get(m);return Q&&Q.length>0?Q.map(B=>B.scopeKey):[m]},[m,i]),I=o.useMemo(()=>p.flatMap(Q=>r[Q]??[]),[r,p]),R=o.useCallback(Q=>{for(const B of p)if((r[B]??[]).some(L=>L.id===Q))return B;return null},[r,p]),D=o.useMemo(()=>{if(!h)return!1;for(const Q of p)for(const B of r[Q]??[])for(const L of B.sessionIds)if(f.has(L))return!0;return!1},[r,p,h,f]),F=o.useCallback((Q,B)=>{const L=Array.from(f);for(const J of p)J!==Q&&l(J,L);a(Q,B,L)},[a,l,f,p]),T=o.useCallback(Q=>{if(!h)return;const B=R(Q);B&&F(B,Q)},[h,F,R]),U=o.useCallback(()=>{const Q=p[0];if(!Q||!h)return;const B=c(Q);B&&F(Q,B.id)},[c,h,F,p]),G=o.useCallback(()=>{if(!h)return;const Q=Array.from(f);for(const B of p)l(B,Q)},[l,f,p,h]),Y=o.useCallback(async()=>{const Q=Array.from(f);if(Q.length!==0){if(S){const{deletedIds:B,failedIds:L}=await x(Q);B.length>0&&ne.success(B.length===1?`Deleted ${B.length} session`:`Deleted ${B.length} sessions`),L.length>0&&ne.error(L.length===1?`Failed to delete ${L.length} session`:`Failed to delete ${L.length} sessions`)}else{const{archivedIds:B,failedIds:L}=await d(Q);B.length>0&&ne.success(B.length===1?`Archived ${B.length} session`:`Archived ${B.length} sessions`),L.length>0&&ne.error(L.length===1?`Failed to archive ${L.length} session`:`Failed to archive ${L.length} sessions`)}Vt.getState().clear()}},[d,S,x,f]),ce=o.useCallback(()=>{if(!h)return;const Q=f.size;if(!n){Y();return}g({sessionCount:Q,archivedBucket:S})},[S,Y,f,n,g,h]),ae=o.useCallback(async()=>{if(!h||!S)return;const Q=Array.from(f),{restoredIds:B,failedIds:L}=await u(Q);B.length>0&&ne.success(B.length===1?`Restored ${B.length} session`:`Restored ${B.length} sessions`),L.length>0&&ne.error(L.length===1?`Failed to restore ${L.length} session`:`Failed to restore ${L.length} sessions`),Vt.getState().clear()},[S,h,f,u]),W=o.useCallback(async()=>{g(null),await Y()},[Y]);return o.useEffect(()=>{if(!v)return;const Q=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),B=L=>{if(s)return;const J=L.target;if(J&&(J.tagName==="INPUT"||J.tagName==="TEXTAREA"||J.isContentEditable))return;const fe=Q?L.metaKey:L.ctrlKey;if(L.key==="Escape"){L.preventDefault(),Vt.getState().disable();return}if(fe&&L.key==="Backspace"){L.preventDefault(),ce();return}if(fe&&(L.key==="a"||L.key==="A")){const $=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if($.length===0)return;L.preventDefault();const we=Vt.getState().scopeKey??$[0]?.getAttribute("data-session-scope")??null,We=Be=>we?Be.getAttribute("data-session-scope")===we:!0,$e=$.filter(We).map(Be=>Be.getAttribute("data-session-row")).filter(Be=>typeof Be=="string"&&Be.length>0);if($e.length===0)return;Vt.getState().replaceAll($e,we||null)}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[ce,s,v]),{selectionModeEnabled:v,hasSelection:h,selectedIdsSize:b,bulkScopeIsArchived:S,derivedSelectionScope:m,bulkScopeFolders:I,bulkCanRemoveFromFolder:D,handleToggleSelectionMode:N,handleExitSelectionMode:A,handleBulkMoveToFolder:T,handleBulkCreateFolderAndMove:U,handleBulkRemoveFromFolder:G,handleBulkDelete:ce,handleBulkRestore:ae,confirmBulkDelete:W}},Ni="oc.sessions.projectCollapse",Ai="oc.sessions.groupOrder",Ii="oc.sessions.groupCollapse",Di="oc.sessions.activeSessionByProject",Pi="oc.sessions.expandedParents.v3",Qp=(t,s,n)=>{if(t.time?.archived)return!0;const r=Vo(en(t));if(!r)return n?.allowUnknownDirectory??!0;if(s.size===0)return n?.allowEmptyDirectorySet??!0;for(const i of s)if(Vo(i)===r)return!0;return!1},Jp=new Set,vr=[],os=t=>{const s=o.useRef(t);return s.current=t,o.useCallback((...n)=>s.current(...n),[])},Zp=({owner:t,childStores:s,projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l})=>{const c=Oe(d=>d.currentSessionDirectory);return o.useEffect(()=>{s.setBootstrapDemand(t,Kp({projectSections:n,activeProjectId:r,collapsedProjects:i,collapsedGroups:a,currentDirectory:l,currentSessionDirectory:c}))},[r,s,a,i,l,c,t,n]),o.useEffect(()=>()=>s.clearBootstrapDemand(t),[s,t]),null},Xp=({directories:t})=>{const s=o.useMemo(()=>{const r=new Set;return t.forEach(i=>{const a=pt(i)?.toLowerCase();a&&r.add(a)}),r},[t]);return un(r=>{for(const i of r.catalog.byId.values()){if(i.lifecycle!=="busy"&&i.lifecycle!=="retry")continue;const a=pt(i.directory)?.toLowerCase();if(a&&s.has(a))return!0}return!1},void 0,"catalog")?e.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:e.jsx(Xn,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},em=({isVisible:t=!0,mobileVariant:s=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:i=!1,hideDirectoryControls:a=!1,showOnlyMainWorkspace:l=!1})=>{Or("react.session_sidebar_render"),cs("ui.session_sidebar.render"),cs(`ui.session_sidebar.render.${s?"mobile":"desktop"}`),cs(`ui.session_sidebar.render.${t?"visible":"hidden"}`);const[c,d]=o.useState(!1),[u,x]=o.useState(""),g=o.useRef(null),v=o.useRef(null),[b,h]=o.useState(null),[f,C]=o.useState(""),[N,A]=o.useState(null),[S,m]=o.useState(new Set),p=o.useMemo(()=>Dn(),[]),[I,R]=o.useState(new Set),[D,F]=o.useState(null),[T,U]=o.useState(new Map),[G,Y]=o.useState(new Map),[ce,ae]=o.useState(!1),[W,Q]=o.useState(null),[B,L]=o.useState(null),[J,fe]=o.useState(""),[$,Ce]=o.useState(null),[we,We]=o.useState(null),[$e,Be]=o.useState(null),Ie=Fr(w=>w.ids),Z=ud(o.useCallback(w=>t?w.rankById:na,[t])),Se=un(w=>t?fd(w.catalog):"",void 0,"catalog"),rt=o.useMemo(()=>Se?Se.split("|"):vr,[Se]),Ne=o.useMemo(()=>new Set(rt),[rt]),ye=hd(Wr(w=>t?Object.entries(w.index.session.unseenCount).filter(([,ie])=>ie>0).map(([ie])=>ie).sort():vr)),Re=o.useMemo(()=>new Set(ye),[ye]),Qe=Fr(w=>w.toggle),[ze,q]=o.useState(()=>{try{const w=Dn().getItem(Ii);if(!w)return new Set;const ie=JSON.parse(w);return new Set(Array.isArray(ie)?ie.filter(se=>typeof se=="string"):[])}catch{return new Set}}),[V,ge]=o.useState(()=>{try{const w=Dn().getItem(Ai);if(!w)return new Map;const ie=JSON.parse(w),se=new Map;return Object.entries(ie).forEach(([et,Tt])=>{Array.isArray(Tt)&&se.set(et,Tt.filter(fs=>typeof fs=="string"))}),se}catch{return new Map}}),H=o.useMemo(()=>{try{const w=Dn().getItem(Di);if(!w)return new Map;const ie=JSON.parse(w),se=new Map;return Object.entries(ie).forEach(([et,Tt])=>{typeof Tt=="string"&&Tt.length>0&&se.set(et,Tt)}),se}catch{return new Map}},[]),xe=o.useCallback(w=>{try{p.setItem(Di,JSON.stringify(Object.fromEntries(w.entries())))}catch{}},[p]),[ve,Me]=o.useState(new Map),Xe=o.useRef(new Map),at=o.useRef(0),dt=Is(w=>w.homeDirectory),Ue=Is(w=>w.currentDirectory),Ae=Lt(w=>w.projects),Je=Lt(w=>w.activeProjectId),it=Lt(w=>w.removeProject),wt=Lt(w=>w.setActiveProjectIdOnly),yt=Lt(w=>w.updateProjectMeta),O=Lt(w=>w.reorderProjects),pe=oe(w=>w.setActiveMainTab),De=oe(w=>w.openContextPanelTab),y=oe(w=>w.setSettingsDialogOpen),z=oe(w=>w.setSettingsPage),X=oe(w=>w.toggleHelpDialog),ue=oe(w=>w.setSessionSwitcherOpen),he=oe(w=>w.setArchivePageOpen),Ee=oe(w=>w.notifyOnSubtasks),Ke=oe(w=>w.showDeletionDialog),ft=oe(w=>w.setShowDeletionDialog),At=pd(u,120),Ze=o.useMemo(()=>At.trim().toLowerCase(),[At]),mt=Ze.length>0,bt=Wt(w=>w.collapsedFolderIds),Fe=Wt(w=>w.foldersMap),Ye=Wt(w=>w.getFoldersForScope),St=Wt(w=>w.createFolder),Ot=Wt(w=>w.renameFolder),Gt=Wt(w=>w.deleteFolder),vt=Wt(w=>w.addSessionToFolder),P=Wt(w=>w.addSessionsToFolder),Pe=Wt(w=>w.removeSessionFromFolder),Le=Wt(w=>w.removeSessionsFromFolders),He=Wt(w=>w.toggleFolderCollapse),ut=Wt(w=>w.getSessionFolderId);kh({enabled:t,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:v,sessionSearchContainerRef:g});const _t=md(t),M=io(),te=ra(),be=un(w=>w.connection,void 0,"chrome"),ot=un(w=>{for(const ie of w.catalog.listStatusByDirectory.values())if(ie==="ready")return!0;return!1},void 0,"catalog"),je=Mr({archived:!1}),qe=Mr({archived:!0}),gt=`session-sidebar:${o.useId()}`,Et=Oe(w=>w.setCurrentSession),Ut=Oe(w=>w.updateSessionTitle),zt=Oe(w=>w.shareSession),ns=Oe(w=>w.unshareSession),Jt=Oe(w=>w.availableWorktreesByProject)??new Map,jt=Oe(w=>w.openNewSessionDraft),It=o.useCallback(w=>{oe.getState().closeMainSurfaces(),jt(w),r?.()},[r,jt]),_=$n(Wr(w=>({checkForUpdates:w.checkForUpdates,available:w.available,runtimeType:w.runtimeType,info:w.info,downloading:w.downloading,downloaded:w.downloaded,progress:w.progress,error:w.error,downloadUpdate:w.downloadUpdate,restartToUpdate:w.restartToUpdate}))),ee=o.useMemo(()=>gd(Ae,Jt,{includeWorktrees:!0}),[Jt,Ae]),re=o.useMemo(()=>je.filter(w=>Qp(w,ee,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0})),[je,ee]),de=o.useMemo(()=>[...re,...qe],[qe,re]),me=tr(),ht=o.useMemo(()=>`${me}|${Ae.map(w=>`${w.id}:${pt(w.path)??""}`).join("|")}`,[Ae,me]),[Dt,Rt]=o.useState(null),Zt=Dt!==ht,[is,Pt]=o.useState(new Set),rs=o.useMemo(()=>ys(),[]),{isTablet:as}=$s(),ds=s||as,{buildGroupSearchText:on,filterSessionNodesForSearch:Hs,buildGroupedSessions:Ws}=Ch({homeDirectory:dt,pinnedSessionIds:Ie,sessionOrderRanks:Z}),{scheduleCollapsedProjectsPersist:K}=Ah({safeStorage:p,keys:{sessionExpanded:Pi,projectCollapse:Ni,groupOrder:Ai,groupCollapse:Ii},groupOrderByProject:V,collapsedGroups:ze,setExpandedParents:m,setCollapsedProjects:R}),_e=o.useMemo(()=>xd(re,Ie,Z),[Ie,Z,re]),lt=o.useMemo(()=>_e.map(w=>w.id).join("|"),[_e]),Ct=o.useRef(null),kt=o.useMemo(()=>{const w=Ct.current;if(w&&w.signature===lt)return w.map;const ie=new Map(_e.map((se,et)=>[se.id,et]));return Ct.current={signature:lt,map:ie},ie},[_e,lt]),Bt=o.useMemo(()=>{const w=new Map;return _e.forEach(ie=>{const se=ie.parentID;if(!se)return;const et=w.get(se)??[];et.push(ie),w.set(se,et)}),w.forEach(ie=>ie.sort((se,et)=>Wn(se,et,Ie,Z))),w},[_e,Ie,Z]),Kt=o.useMemo(()=>e.jsx(_s,{icon:"chat-new",mobileVariant:s,onClick:()=>It(),children:"New session"}),[s,It]),Ht=o.useMemo(()=>Ae.find(w=>w.id===N)??null,[Ae,N]),Xt=o.useCallback(w=>{N&&yt(N,{label:w.label,defaultModel:w.defaultModel??null})},[N,yt]),Ps=o.useCallback(()=>{const w=$n.getState();if(w.available&&w.info){ae(!0);return}_.checkForUpdates().then(()=>{const{available:ie,error:se}=$n.getState();if(se){ne.error("Failed to check for updates",{description:se});return}if(!ie){ne.success("You are on the latest version");return}ae(!0)})},[_]),Nt=bd(),Mt=o.useCallback(()=>{if(s&&ue(!1),r?.(),Nt?.openSettings){Nt.openSettings();return}y(!0)},[Nt,s,r,ue,y]),Ss=_.available&&(_.runtimeType==="desktop"||_.runtimeType==="web"),lr=Oe(w=>w.deleteSession),jn=Oe(w=>w.deleteSessions),k=Oe(w=>w.archiveSession),le=Oe(w=>w.archiveSessions),ke=Oe(w=>w.unarchiveSession),xt=Oe(w=>w.unarchiveSessions),{copiedSessionId:js,handleSessionSelect:us,handleSessionDoubleClick:an,handleSaveEdit:ms,handleCancelEdit:tl,handleShareSession:sl,handleCopyShareUrl:nl,handleCopySessionId:rl,handleUnshareSession:ol,handleDeleteSession:il,handleRestoreSession:al,confirmDeleteSession:ll}=Nh({mobileVariant:s,allowReselect:i,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:x,setIsSessionSearchOpen:d,setActiveMainTab:pe,setSessionSwitcherOpen:ue,setCurrentSession:Et,updateSessionTitle:Ut,shareSession:zt,unshareSession:ns,deleteSession:lr,deleteSessions:jn,archiveSession:k,archiveSessions:le,unarchiveSession:ke,childrenMap:Bt,showDeletionDialog:Ke,setDeleteSessionConfirm:Ce,deleteSessionConfirm:$,setEditingId:h,setEditTitle:C,editingId:b,editTitle:f}),cl=o.useCallback(()=>{if(!we)return;const{scopeKey:w,folderId:ie}=we;We(null),Gt(w,ie)},[we,Gt]),vo=o.useCallback(()=>{zs.requestDirectoryDialog()},[]),dl=o.useCallback(w=>{m(ie=>{const se=yd(ie,w);try{p.setItem(Pi,JSON.stringify(Array.from(se)))}catch{}return se})},[p]),wo=o.useCallback((w,ie)=>{if(!w)return null;ie&&bt.has(ie)&&He(ie);const se=St(w,"New folder",ie);return L(se.id),fe(se.name),se},[bt,He,St]),So=os(us),ul=os(an),fl=os(ms),hl=os(tl),pl=os(sl),ml=os(nl),gl=os(rl),xl=os(ol),bl=os(il),yl=os(al),cr=os(wo),jo=o.useCallback((w,ie)=>{Y(se=>{const et=new Map(se);return et.set(w,ie+7),et})},[]),Cn=o.useCallback(w=>{Y(ie=>{if(!ie.has(w))return ie;const se=new Map(ie);return se.delete(w),se})},[]),Co=o.useCallback(w=>{Y(ie=>{let se=!1;const et=new Map(ie),Tt=`${w}:`;for(const fs of et.keys())fs.startsWith(Tt)&&(et.delete(fs),se=!0);return se?et:ie})},[]),vl=o.useCallback(w=>{at.current=Date.now()+150,Co(w),R(ie=>{const se=new Set(ie);se.has(w)?se.delete(w):se.add(w);try{p.setItem(Ni,JSON.stringify(Array.from(se)))}catch{}return K(se),se})},[Co,p,K]),Cs=o.useMemo(()=>Ae.map(w=>({...w,normalizedPath:pt(w.path)})).filter(w=>!!w.normalizedPath),[Ae]),wl=o.useMemo(()=>Cs.map(w=>w.normalizedPath),[Cs]),ko=vd(t?wl:vr);Dh({enabled:t,normalizedProjects:Cs,gitRepoStatus:ko,setProjectRepoStatus:U,setProjectRootBranches:Me});const Sl=Oe(w=>w.isLoading),No=o.useMemo(()=>Bh(re,Cs,Jt,qe),[qe,Jt,Cs,re]);Mh({enabled:t,hasAuthoritativeGlobalSessions:ot,sessions:de});const{getSessionsForProject:jl,getArchivedSessionsForProject:Cl}=Ph({ownership:No});yh({enabled:t,normalizedProjects:Cs,ownership:No,isSessionsLoading:Sl,hasAuthoritativeGlobalSessions:ot,isWorktreeTopologyLoading:Zt,unresolvedWorktreeProjectPaths:is,foldersMap:Fe,createFolder:St,addSessionToFolder:vt});const Ao=o.useRef(!1);Je&&T.has(Je)&&(Ao.current=!!T.get(Je));const kl=wi(w=>w.showArchivedSessions),Io=wi(w=>w.stickyZoneHeaders),dr=Lt(w=>w.manualProjectOrder),Do=o.useRef(new Set),kn=wd(Do.current,S,"project");Do.current=kn;const ur={isVisible:t,mobileVariant:s,onSessionSelected:n,allowReselect:i,hideDirectoryControls:a,showOnlyMainWorkspace:l,isTablet:as,catalogSessions:je,archivedSessions:qe,projects:Ae,activeProjectId:Je,manualProjectOrder:dr,currentDirectory:Ue,availableWorktreesByProject:Jt,pinnedSessionIds:Ie,sessionOrderRanks:Z,foldersMap:Fe,collapsedFolderIds:bt,gitBranches:_t,gitRepoStatus:ko,updateStore:_,showArchivedSessions:kl,projectRepoStatus:T,projectRootBranches:ve,resolvedWorktreeTopologyKey:Dt,unresolvedWorktreeProjectPaths:is,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:b,editTitle:f,editingProjectDialogId:N,expandedParents:S,collapsedProjects:I,visibleSessionCountByGroup:G,updateDialogOpen:ce,openSidebarMenuKey:W,renamingFolderId:B,renameFolderDraft:J,deleteSessionConfirm:$,deleteFolderConfirm:we,bulkDeleteConfirm:$e,collapsedGroups:ze},Po=o.useRef(null),To=Po.current;if(To){let w=!1;for(const ie of Object.keys(ur))Object.is(To[ie],ur[ie])||(cs(`ui.session_sidebar.source.${ie}`),w=!0);w||cs("ui.session_sidebar.source.parent_or_context")}Po.current=ur;const Nl=o.useMemo(()=>{const w=new Map(dr.map((ie,se)=>[ie,se]));return[...Cs].sort((ie,se)=>(w.get(ie.id)??1/0)-(w.get(se.id)??1/0))},[dr,Cs]),{projectSections:Ft,groupSearchDataByGroup:Eo,flatSectionsForRender:Nn,searchMatchCount:Al}=wh({normalizedProjects:Nl,getSessionsForProject:jl,getArchivedSessionsForProject:Cl,projectRepoStatus:T,projectRootBranches:ve,lastRepoStatus:Ao.current,buildGroupedSessions:Ws,hasSessionSearchQuery:mt,normalizedSessionSearchQuery:Ze,filterSessionNodesForSearch:Hs,buildGroupSearchText:on,foldersMap:Fe}),Il=o.useMemo(()=>e.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),e.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:Dl}=vh(V),Ro=o.useRef(!1);o.useEffect(()=>{if(Ro.current||Ft.length===0)return;const w=Ft.flatMap(ie=>ie.groups.filter(se=>se.isArchivedBucket).map(se=>`${ie.project.id}:${se.id}`));w.length>0&&q(ie=>new Set([...ie,...w])),Ro.current=!0},[Ft]),o.useMemo(()=>{const w=new Map,ie=new Map;return Ft.forEach(se=>{const et=er(se.project.label?.trim()||Us(se.project.normalizedPath,dt)||se.project.normalizedPath);se.groups.forEach(Tt=>{const fs=Tt.branch&&Tt.branch!=="HEAD"&&Tt.branch!==et?Tt.branch:null,ln={projectLabel:et,branchLabel:fs},Ts=sc=>{sc.forEach(Vs=>{const Oo=se.project.normalizedPath.length,nc=ie.get(Vs.session.id)??-1;Oo<nc||(w.set(Vs.session.id,{node:Vs,projectId:se.project.id,groupDirectory:Tt.directory,secondaryMeta:ln}),ie.set(Vs.session.id,Oo),Vs.children.length>0&&Ts(Vs.children))})};Ts(Tt.sessions)})}),w},[Ft,dt]);const fr=o.useMemo(()=>Nn.map(w=>w.groups.some(ie=>ie.isArchivedBucket)?{...w,groups:w.groups.filter(ie=>!ie.isArchivedBucket)}:w),[Nn]),Pl=o.useMemo(()=>D?fr.filter(w=>w.project.id===D):fr,[fr,D]),Tl=o.useMemo(()=>{let w=0;for(const ie of Ft)for(const se of ie.groups)se.isArchivedBucket||(w+=se.sessions.length);return w},[Ft]),El=o.useMemo(()=>{const w=new Map;for(const ie of Ft){let se=0;for(const et of ie.groups)et.isArchivedBucket||(se+=et.sessions.length);w.set(ie.project.id,se)}return w},[Ft]),Rl=o.useCallback(w=>{const ie=Ft.find(se=>se.project.id===w);return ie?ie.groups.some(se=>se.isArchivedBucket?!1:se.sessions.some(et=>Ne.has(et.session.id))):!1},[Ne,Ft]),Ml=o.useCallback(w=>{const ie=Ft.find(se=>se.project.id===w);return ie?ie.groups.some(se=>se.isArchivedBucket?!1:se.sessions.some(et=>Re.has(et.session.id))):!1},[Ft,Re]),Fl=s?"flex size-9 shrink-0 items-center justify-center rounded-full leading-none text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",Ll=s?"size-4":"h-4.5 w-4.5",Ol=_h({enabled:t&&Io,isDesktopShellRuntime:rs,projectSections:Ft,projectHeaderSentinelRefs:Xe}),An=os((w,ie=0,se,et,Tt=!1,fs,ln="project",Ts)=>e.jsx(Gp,{node:w,depth:ie,groupDirectory:se,projectId:et,archivedBucket:Tt,pinnedSessionIds:Ie,expandedParents:kn,hasSessionSearchQuery:mt,normalizedSessionSearchQuery:Ze,notifyOnSubtasks:Ee,editingId:b,setEditingId:h,editTitle:f,setEditTitle:C,handleSaveEdit:fl,handleCancelEdit:hl,toggleParent:dl,handleSessionSelect:So,handleSessionDoubleClick:ul,togglePinnedSession:Qe,handleShareSession:pl,copiedSessionId:js,handleCopyShareUrl:ml,handleCopySessionId:gl,handleUnshareSession:xl,openSidebarMenuKey:W,setOpenSidebarMenuKey:Q,renamingFolderId:B,getFoldersForScope:Ye,getSessionFolderId:ut,removeSessionFromFolder:Pe,addSessionToFolder:vt,createFolderAndStartRename:cr,openContextPanelTab:De,handleDeleteSession:bl,handleRestoreSession:yl,mobileVariant:s,alwaysShowActions:ds,renderSessionNode:An,secondaryMeta:fs,renderContext:ln,subtreeContainsEditing:Ts?.subtreeContainsEditing??Jp,menuOpenSessionId:Ts?.menuOpenSessionId??null,nodeStructureKey:Ts?.nodeStructureKey??"",childRenderExtrasFor:Ts?.childRenderExtrasFor})),Bl=o.useMemo(()=>{const w=new Map;return Nn.forEach(ie=>{const se=ie.groups.find(et=>!et.isArchivedBucket);se?.folderScopes&&se.folderScopes.length>0&&w.set(ie.project.id,se.folderScopes)}),w},[Nn]),_l=o.useCallback((w,ie)=>{const se=[];return ie.forEach(et=>{et.isArchivedBucket||(se.push(et.directory),et.folderScopes?.forEach(Tt=>se.push(Tt.directory)))}),e.jsx(Xp,{directories:se})},[]),Mo=o.useCallback(w=>{Cn(w),q(ie=>{const se=new Set(ie);return se.has(w)?se.delete(w):se.add(w),se})},[Cn]),Ul=o.useCallback((w,ie,se,et,Tt,fs,ln)=>e.jsx(op,{group:w,groupKey:ie,projectId:se,hideGroupLabel:et,dragHandleProps:Tt,compactBodyPadding:fs,hasSessionSearchQuery:mt,normalizedSessionSearchQuery:Ze,groupSearchDataByGroup:Eo,visibleSessionCount:G.get(ie),collapsedGroups:ze,hideDirectoryControls:a,collapsedFolderIds:bt,toggleFolderCollapse:He,renameFolder:Ot,deleteFolder:Gt,showDeletionDialog:Ke,setDeleteFolderConfirm:We,renderSessionNode:An,showMoreGroupSessions:jo,resetGroupSessionLimit:Cn,mobileVariant:s,alwaysShowActions:ds,activeProjectId:Je,setActiveProjectIdOnly:wt,setActiveMainTab:pe,setSessionSwitcherOpen:ue,openNewSessionDraft:It,addSessionToFolder:vt,createFolderAndStartRename:cr,renamingFolderId:B,renameFolderDraft:J,setRenameFolderDraft:fe,setRenamingFolderId:L,pinnedSessionIds:Ie,expandedParents:kn,sessionOrderIndex:kt,editingId:b,editTitle:f,openSidebarMenuKey:W,activeActivitySessionIds:Ne,unreadActivitySessionIds:Re,notifyOnSubtasks:Ee,onToggleCollapsedGroup:Mo,scrollContainerRef:ln}),[mt,Ze,Eo,G,ze,a,bt,He,Ot,Gt,Ke,An,jo,Cn,s,ds,Je,wt,pe,ue,It,vt,cr,B,J,Ie,kn,kt,b,f,W,Ne,Re,Ee,Mo]),Fo=!!(B||b||N),{selectionModeEnabled:Lo,hasSelection:zl,selectedIdsSize:$l,bulkScopeIsArchived:Gl,derivedSelectionScope:Kl,bulkScopeFolders:Hl,bulkCanRemoveFromFolder:Wl,handleToggleSelectionMode:Vl,handleExitSelectionMode:Yl,handleBulkMoveToFolder:ql,handleBulkCreateFolderAndMove:Ql,handleBulkRemoveFromFolder:Jl,handleBulkDelete:Zl,handleBulkRestore:Xl,confirmBulkDelete:ec}=qp({isInlineEditing:Fo,showDeletionDialog:Ke,foldersMap:Fe,folderScopesByProject:Bl,addSessionsToFolder:P,removeSessionsFromFolders:Le,createFolderAndStartRename:wo,archiveSessions:le,unarchiveSessions:xt,deleteSessions:jn,setBulkDeleteConfirm:Be}),tc=o.useCallback(()=>{oe.getState().closeMainSurfaces(),pe("chat"),s&&ue(!1),jt(),r?.()},[s,r,jt,pe,ue]);return e.jsx(Sd,{delay:400,closeDelay:150,timeout:600,children:e.jsxs("div",{ref:g,className:E("relative flex h-full flex-col text-foreground overflow-x-hidden",s?"":"bg-transparent"),children:[e.jsx(Zp,{owner:gt,childStores:te,projectSections:Ft,activeProjectId:Je,collapsedProjects:I,collapsedGroups:ze,currentDirectory:Ue}),e.jsx(jh,{projectSections:Ft,activeProjectId:Je,initialActiveSessionByProject:H,persistActiveSessionByProject:xe,handleSessionSelect:So,mobileVariant:s,openNewSessionDraft:jt,setActiveMainTab:pe,setSessionSwitcherOpen:ue}),e.jsx(bh,{enabled:t,sortedSessions:_e,prefetchSession:async w=>{await M.syncSession(w)}}),!a&&!s?e.jsx(ap,{onNewSession:tc,showSidebarToggle:!0}):null,e.jsx(ip,{hideDirectoryControls:a,handleOpenDirectoryDialog:vo,onOpenArchive:()=>{s&&ue(!1),he(!0)},onOpenSettings:s?Mt:void 0,onOpenInstances:s?Nt?.openInstances:void 0,instanceLabel:s?Nt?.instanceLabel:void 0,onOpenUpdate:s?Nt?.openUpdate:void 0,headerActionIconClass:Ll,headerActionButtonClass:Fl,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:v,sessionSearchQuery:u,setSessionSearchQuery:x,hasSessionSearchQuery:mt,searchMatchCount:Al,selectionModeEnabled:Lo,onToggleSelectionMode:Vl,mobileVariant:s}),be==="error"||be==="unavailable"?e.jsx("div",{role:"alert",className:"mx-3 mb-2 rounded bg-[var(--status-error-background)] p-2 text-xs text-[var(--status-error-foreground)]",children:"Unable to reach server"}):null,!a&&Ft.length>0?e.jsx(dp,{projects:Ft.map(w=>w.project),selectedProjectId:D,onSelectProject:w=>{F(w),w&&wt(w)},onOpenDirectoryDialog:vo,onOpenProjectEditDialog:A,onRemoveProject:it,totalSessionCount:Tl,getSessionCountForProject:w=>El.get(w)??0,hasActiveSessionByProject:Rl,hasUnseenByProject:Ml,homeDirectory:dt,mobileVariant:s}):null,e.jsx(yp,{sectionsForRender:Pl,projectSections:Ft,activeProjectId:Je,showOnlyMainWorkspace:l,hasSessionSearchQuery:mt,emptyState:Kt,searchEmptyState:Il,isAllFoldersView:D===null,pinnedSessionIds:Ie,renderSessionNode:An,renderGroupSessions:Ul,homeDirectory:dt,collapsedProjects:I,hideDirectoryControls:a,projectRepoStatus:T,isDesktopShellRuntime:rs,stickyZoneHeaders:Io,stuckProjectHeaders:Ol,mobileVariant:s,alwaysShowActions:ds,toggleProject:vl,setActiveProjectIdOnly:wt,setActiveMainTab:pe,setSessionSwitcherOpen:ue,openNewSessionDraft:It,openProjectEditDialog:A,removeProject:it,projectHeaderSentinelRefs:Xe,reorderProjects:O,getOrderedGroups:Dl,setGroupOrderByProject:ge,renderProjectStatusIndicator:_l,openSidebarMenuKey:W,setOpenSidebarMenuKey:Q,isInlineEditing:Fo}),Lo&&zl?e.jsx(Yp,{selectedCount:$l,scopeKey:Kl,scopeFolders:Hl,archivedBucket:Gl,onMoveToFolder:ql,onCreateFolderAndMove:Ql,onRemoveFromFolder:Jl,canRemoveFromFolder:Wl,onRestore:Xl,onDelete:Zl,onDone:Yl}):null,s?null:e.jsx(up,{onOpenSettings:Mt,onOpenShortcuts:X,onOpenAbout:()=>{z("about"),y(!0)},onOpenUpdate:Ps,showRuntimeButtons:!0,showUpdateButton:Ss}),e.jsx(Ia,{open:ce,onOpenChange:ae,info:_.info,downloading:_.downloading,downloaded:_.downloaded,progress:_.progress,error:_.error,onDownload:_.downloadUpdate,onRestart:_.restartToUpdate,runtimeType:_.runtimeType}),e.jsx(Uh,{open:!!Ht,onOpenChange:w=>{w||A(null)},project:Ht,onSave:Xt}),e.jsx(Hp,{value:$,setValue:Ce,showDeletionDialog:Ke,setShowDeletionDialog:ft,onConfirm:ll}),e.jsx(Vp,{value:we,setValue:We,onConfirm:cl}),e.jsx(Wp,{value:$e,setValue:Be,showDeletionDialog:Ke,setShowDeletionDialog:ft,onConfirm:ec})]})})},rx=o.memo(em),tm=({value:t,options:s,disabled:n,onChange:r})=>{const i=t||"Default",a=e.jsxs("div",{className:E("flex h-6 w-fit items-center gap-1.5 rounded-lg border border-border/20 bg-interactive-selection/20 px-2",n?"cursor-not-allowed opacity-60":"cursor-pointer hover:bg-interactive-hover/30"),children:[e.jsx("span",{className:"typography-micro whitespace-nowrap font-medium capitalize",children:i}),e.jsx(j,{name:"arrow-down-s",className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]});return n?a:e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:a}),e.jsxs(Yt,{align:"start",className:"max-w-[220px]",portalToBody:!0,children:[e.jsx(ct,{className:"typography-meta",onSelect:()=>r(""),children:e.jsx("span",{className:E("font-medium",!t&&"text-primary"),children:"Default"})}),s.map(l=>e.jsx(ct,{className:"typography-meta",onSelect:()=>r(l),children:e.jsx("span",{className:E("font-medium capitalize",t===l&&"text-primary"),children:l})},l))]})]})},Ti=t=>({providerID:t.providerID,modelID:t.modelID,variant:t.variant,agent:t.agent});function sm(t){const{open:s,onOpenChange:n,projectDirectory:r,submitting:i=!1,onConfirm:a}=t,l=ts(m=>m.loadProviders),c=ts(m=>m.loadAgents),d=ts(m=>m.providers),u=ts(m=>m.currentProviderId),x=ts(m=>m.currentModelId),g=ts(m=>m.currentVariant||""),v=ts(m=>m.currentAgentName||""),[b,h]=o.useState(()=>Ti({providerID:u,modelID:x,variant:g,agent:v}));o.useEffect(()=>{s&&(l({directory:r,source:"todoSendDialog"}),c({directory:r}))},[s,l,c,r]),o.useEffect(()=>{s&&h(Ti({providerID:u,modelID:x,variant:g,agent:v}))},[s,u,x,g,v]),o.useEffect(()=>{if(!s||d.length===0)return;const m=d.find(D=>D.id===b.providerID)??d[0],p=Array.isArray(m?.models)?m.models:[],I=p.some(D=>D.id===b.modelID),R=p[0]?.id??"";m?.id===b.providerID&&I||h(D=>({...D,providerID:typeof m?.id=="string"?m.id:"",modelID:typeof R=="string"?I?D.modelID:R:"",variant:""}))},[s,d,b.providerID,b.modelID]),o.useCallback(m=>jd(m.mode),[]);const f=o.useMemo(()=>{const p=d.find(I=>I.id===b.providerID)?.models?.find(I=>I.id===b.modelID);return p?.variants?Object.keys(p.variants):[]},[d,b.providerID,b.modelID]),C=f.length>0;o.useEffect(()=>{C||!b.variant||h(m=>({...m,variant:""}))},[C,b.variant]);const N=b.providerID.trim().length>0&&b.modelID.trim().length>0,A=o.useCallback(()=>{!N||i||a(b)},[N,i,a,b]);return o.useEffect(()=>{if(!s)return;const m=p=>{(p.metaKey||p.ctrlKey)&&p.key==="Enter"&&(p.preventDefault(),A())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[s,A]),e.jsx(hs,{open:s,onOpenChange:m=>{i||n(m)},children:e.jsxs(ps,{className:"max-w-md overflow-visible",children:[e.jsx(Ds,{children:e.jsx(vs,{children:"Send to new session"})}),e.jsx("div",{className:"flex flex-col gap-4",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Thinking level"}),e.jsx(tm,{value:b.variant,options:f,disabled:!C,onChange:m=>h(p=>({...p,variant:m}))})]})}),e.jsx("div",{className:"flex items-center justify-end gap-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(Ve,{variant:"ghost",size:"sm",onClick:()=>n(!1),disabled:i,children:"Cancel"}),e.jsx(Ve,{size:"sm",onClick:A,disabled:!N||i,children:i?"Sending":"Send"})]})})]})})}const no=5,Za=15,Ln=new Map,Kn=t=>{const s=Math.sqrt(t/100),n=12*s,r=24*s;return Math.ceil(n+r+1)},nm=(t,s)=>{const n=Kn(s);return Math.max(n*no,Math.min(n*Za,n*t))},rm=async(t,s)=>{const n=await Dd(t.path);return{...t,title:n?.title||t.path.split("/").pop()||s}},om=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`todo_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Ei=t=>[...t.filter(s=>!s.completed),...t.filter(s=>s.completed)],Ri=(t,s)=>{const n=t.findIndex(r=>r.completed);return n===-1?[...t,s]:[...t.slice(0,n),s,...t.slice(n)]},im=({id:t,children:s})=>{const{attributes:n,listeners:r,setNodeRef:i,setActivatorNodeRef:a,transform:l,transition:c,isDragging:d}=or({id:t});return e.jsx("li",{ref:i,style:{transform:ir.Transform.toString(l),transition:c},className:E(d&&"opacity-60"),children:s({attributes:n,listeners:r,setActivatorNodeRef:a,isDragging:d})})},am=({projectRef:t,projectLabel:s,onActionComplete:n,className:r})=>{const[i,a]=o.useState(!1),[l,c]=o.useState(""),[d,u]=o.useState([]),[x,g]=o.useState(""),[v,b]=o.useState(null),[h,f]=o.useState(()=>new Set),[C,N]=o.useState([]),[A,S]=o.useState(null),[m,p]=o.useState(!1),[I,R]=o.useState(0),D=o.useRef(!1),F=o.useRef(""),T=o.useRef(null),U=oe(y=>y.todoPanelHeight),G=oe(y=>y.setTodoPanelHeight),Y=oe(y=>y.notesPanelHeight),ce=oe(y=>y.setNotesPanelHeight),[ae,W]=o.useState(!1),Q=o.useRef(0),B=o.useRef(U),L=Oe(y=>y.currentSessionId),J=Oe(y=>y.createSession),fe=Oe(y=>y.initializeNewPiChamberSession),$=Oe(y=>y.sendMessage),Ce=Oe(y=>y.setCurrentSession),we=Cd(y=>y.setPendingInputText),We=Is(y=>y.currentDirectory),$e=oe(y=>y.openContextPanelTab),Be=oe(y=>y.setActiveMainTab),Ie=oe(y=>y.setSessionSwitcherOpen),Z=oe(y=>y.padding),Se=o.useCallback(async(y,z)=>{if(!t)return!1;const X=t.id,he=(Ln.get(X)??Promise.resolve()).catch(()=>{}).then(()=>kd(t,{notes:y,todos:z}));Ln.set(X,he);try{const Ee=await he;return Ee||ne.error("Failed to save project notes"),Ee}finally{Ln.get(X)===he&&Ln.delete(X)}},[t]);o.useEffect(()=>{if(!t){c(""),u([]),N([]),g(""),f(new Set);return}let y=!1;return a(!0),(async()=>{try{const z=await Nd(t),X=await Promise.all(z.plans.map(ue=>rm(ue,"Plan")));if(y)return;c(z.notes),u(Ei(z.todos)),N(X),F.current=z.notes,D.current=!0,g(""),f(new Set)}catch{y||(ne.error("Failed to load project notes"),c(""),u([]),N([]),F.current="",D.current=!0)}finally{y||a(!1)}})(),()=>{y=!0}},[I,t]),o.useEffect(()=>{if(!t)return;const y=z=>{const X=z.detail;X?.projectId&&X.projectId!==t.id||R(ue=>ue+1)};return window.addEventListener("pichamber:project-plan-saved",y),window.addEventListener("pichamber:project-notes-updated",y),()=>{window.removeEventListener("pichamber:project-plan-saved",y),window.removeEventListener("pichamber:project-notes-updated",y)}},[t]),o.useEffect(()=>{if(d.length<7)return;const y=nm(d.length,Z),z=Kn(Z)*no;U!==y&&(U<z||U>y)&&G(y)},[d.length,Z,U,G]),o.useEffect(()=>{if(!ae)return;const y=X=>{const ue=X.clientY-Q.current,he=Math.min(Kn(Z)*Za,Math.max(Kn(Z)*no,B.current+ue));G(he)},z=()=>{W(!1)};return window.addEventListener("pointermove",y),window.addEventListener("pointerup",z,{once:!0}),window.addEventListener("pointercancel",z,{once:!0}),()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",z),window.removeEventListener("pointercancel",z)}},[ae,Z,G]);const rt=o.useCallback(y=>{W(!0),Q.current=y.clientY,B.current=U,y.preventDefault()},[U]),Ne=o.useCallback(()=>{T.current!==null&&(window.clearTimeout(T.current),T.current=null)},[]),ye=o.useCallback(()=>{Ne(),F.current=l,Se(l,d)},[Ne,l,Se,d]);o.useEffect(()=>{if(!(!t||!D.current)&&l!==F.current)return T.current=window.setTimeout(()=>{T.current=null,F.current=l,Se(l,d)},400),()=>{Ne()}},[Ne,l,Se,t,d]),o.useEffect(()=>()=>Ne(),[Ne]);const Re=o.useCallback(()=>{const y=x.trim();if(!y)return;const z=Ri(d,{id:om(),text:y.slice(0,In),completed:!1,createdAt:Date.now()});u(z),g(""),Se(l,z)},[x,l,Se,d]),Qe=o.useCallback(y=>{f(z=>{const X=new Set(z);return X.has(y)?X.delete(y):X.add(y),X})},[]),ze=o.useCallback((y,z)=>{const X=d.find(Ke=>Ke.id===y);if(!X||X.completed===z)return;const ue=d.filter(Ke=>Ke.id!==y),he={...X,completed:z},Ee=z?[...ue,he]:Ri(ue,he);u(Ee),Se(l,Ee)},[l,Se,d]),q=o.useCallback(y=>{const z=d.filter(X=>X.id!==y);u(z),Se(l,z)},[l,Se,d]),V=o.useCallback(()=>{const y=d.filter(z=>!z.completed);y.length!==d.length&&(u(y),Se(l,y))},[l,Se,d]),ge=o.useCallback(y=>{const{active:z,over:X}=y;if(!X||z.id===X.id)return;const ue=d.findIndex(Ke=>Ke.id===z.id),he=d.findIndex(Ke=>Ke.id===X.id);if(ue===-1||he===-1)return;const Ee=Ei(Mu(d,ue,he));u(Ee),Se(l,Ee)},[l,Se,d]),H=sr(yn(ho,{activationConstraint:{distance:8}})),xe=x.slice(0,In),ve=d.reduce((y,z)=>y+(z.completed?1:0),0),Me=o.useCallback(()=>{Be("chat"),Ie(!1)},[Be,Ie]),Xe=o.useCallback((y,z)=>{!t||v!==null||S({todoId:y,todoText:z})},[t,v]),at=o.useCallback(y=>{if(!L){ne.error("No active session selected");return}Me();const z=`\`\`\`md
|
|
38
|
-
${y}
|
|
39
|
-
\`\`\``;we(z,"append"),ne.success("Todo sent to current session"),n?.()},[L,n,Me,we]),dt=o.useCallback(async y=>{if(!t||!A)return;const z=await Yo("plan.todo.visible",{todo_text:A.todoText}),ue=[{synthetic:!0,text:await Yo("plan.todo.instructions",{todo_text:A.todoText})}];p(!0),b(A.todoId);try{Me();const he=await J(void 0,t.path,null);if(!he?.id){ne.error("Failed to create session");return}const Ee=he.id,Ke=he.directory??t.path;fe(he.id,ts.getState().agents??[]);const ft=Ad.getState();ft.saveSessionModelSelection(Ee,y.providerID,y.modelID),y.agent.trim()&&(ft.saveSessionAgentSelection(Ee,y.agent),ft.saveAgentModelForSession(Ee,y.agent,y.providerID,y.modelID),ft.saveAgentModelVariantForSession(Ee,y.agent,y.providerID,y.modelID,y.variant||void 0)),Ce(Ee,Ke),await $(z,y.providerID,y.modelID,y.agent.trim()||void 0,void 0,void 0,ue,y.variant||void 0),ne.success("Todo sent to new session"),S(null),n?.()}catch{ne.error("Failed to send note")}finally{p(!1),b(null)}},[J,fe,n,A,t,Me,$,Ce]),Ue=o.useRef(null),[Ae,Je]=o.useState(!1),[it,wt]=o.useState(null),yt=o.useCallback(async y=>{if(!(!t||it)){wt(y);try{if(!await Id(t,y)){ne.error("Failed to delete plan");return}N(X=>X.filter(ue=>ue.id!==y)),window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:t.id}}))}finally{wt(null)}}},[it,t]),O=o.useCallback(async()=>{if(!t||Ae)return;const y=await uu({defaultPath:t.path,filters:[{name:"Plan files",extensions:["md","markdown","txt"]},{name:"All files",extensions:["*"]}]});if(y.success&&y.path){Je(!0);try{const z=new URLSearchParams({path:y.path,allowOutsideWorkspace:"true"});y.outsideFileGrant&&z.set("outsideFileGrant",y.outsideFileGrant);const X=await ss(`/api/fs/read?${z.toString()}`,{cache:"no-store"});if(!X.ok){ne.error("Failed to read plan file");return}const ue=await X.text();if(!ue.trim()){ne.error("Plan file is empty");return}const he=y.path.split("/").pop()?.replace(/\.(md|markdown|txt)$/i,"").trim()||"";if(!await qo(t,ue,he)){ne.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:t.id}})),ne.success("Plan imported")}catch(z){const X=z instanceof Error?z.message:void 0;ne.error("Failed to read plan file",X?{description:X}:void 0)}finally{Je(!1)}}else y.error==="Native file picker not available"&&Ue.current?.click()},[Ae,t]),pe=o.useCallback(async y=>{if(!(!t||!y)){Je(!0);try{const z=await y.text();if(!z.trim()){ne.error("Plan file is empty");return}const X=y.name.replace(/\.(md|markdown|txt)$/i,"").trim();if(!await qo(t,z,X)){ne.error("Failed to import plan");return}window.dispatchEvent(new CustomEvent("pichamber:project-plan-saved",{detail:{projectId:t.id}})),ne.success("Plan imported")}catch(z){const X=z instanceof Error?z.message:void 0;ne.error("Failed to read plan file",X?{description:X}:void 0)}finally{Je(!1)}}},[t]),De=o.useCallback(y=>{const z=t?.path?.trim(),X=We?.trim()||z;X&&$e(X,{mode:"file",targetPath:y.path,dedupeKey:y.path,label:y.title})},[We,$e,t]);return t?e.jsxs("div",{className:E("w-full min-w-0 space-y-3 p-3",r),children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h3",{className:"min-w-0 truncate typography-ui-label font-semibold text-foreground",title:t.path,children:`Quick notes - ${s?.trim()||t.path.split("/").filter(Boolean).pop()||t.path}`}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length,"/",Qo]})]}),e.jsx(go,{value:l,onChange:y=>c(y.target.value.slice(0,Qo)),onBlur:ye,placeholder:"Capture context, reminders, or links",resizedHeight:Y,onResizeHeightChange:ce,useScrollShadow:!0,scrollShadowSize:56,disabled:i})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Todo"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:d.length===1?`${d.length} item`:`${d.length} items`}),e.jsx("button",{type:"button",onClick:V,disabled:i||ve===0,className:"typography-meta rounded-md px-1.5 py-0.5 text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",children:"Clear completed"})]}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[xe.length,"/",In]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(nn,{value:xe,onChange:y=>g(y.target.value.slice(0,In)),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),Re())},placeholder:"Add a todo",disabled:i,className:"h-8"}),e.jsx("button",{type:"button",onClick:Re,disabled:i||xe.trim().length===0,className:"inline-flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Add todo",title:"Add todo",children:e.jsx(j,{name:"add",className:"h-4 w-4"})})]}),e.jsx("div",{className:E("overflow-y-auto rounded-lg border border-border/60 bg-background/40",ae&&"transition-none"),style:d.length<7?void 0:{height:`${U}px`,maxHeight:`${U}px`},children:d.length===0?e.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No todos yet. Add a small checklist for this project."}):e.jsx(nr,{sensors:H,collisionDetection:rr,onDragEnd:ge,children:e.jsx(po,{items:d.map(y=>y.id),strategy:Sa,children:e.jsx("ul",{className:"divide-y divide-border/50",children:d.map(y=>{const z=h.has(y.id);return e.jsx(im,{id:y.id,children:X=>e.jsxs("div",{className:E("flex gap-1.5 px-2.5 py-1.5",z?"items-start":"items-center"),children:[e.jsx("button",{type:"button",ref:X.setActivatorNodeRef,...X.attributes,...X.listeners,onClick:ue=>{ue.preventDefault(),ue.stopPropagation()},className:"flex h-6 w-4 flex-shrink-0 touch-none items-center justify-center text-muted-foreground hover:text-foreground","aria-label":`Reorder \\"${y.text}\\"`,title:`Reorder \\"${y.text}\\"`,children:e.jsx(j,{name:"draggable",className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex h-6 items-center",children:e.jsx(Yi,{checked:y.completed,onChange:ue=>ze(y.id,ue),ariaLabel:`Mark \\"${y.text}\\" complete`})}),e.jsx("button",{type:"button",onClick:()=>Qe(y.id),className:E("block min-h-6 min-w-0 flex-1 bg-transparent p-0 text-left typography-ui-label leading-normal text-foreground",z?"whitespace-normal break-words":"overflow-hidden text-ellipsis whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",y.completed&&"text-muted-foreground line-through"),title:z?void 0:y.text,"aria-label":z?`Collapse todo \\"${y.text}\\"`:`Expand todo \\"${y.text}\\"`,children:y.text}),e.jsxs("div",{className:"flex h-6 items-center gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>q(y.id),className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete \\"${y.text}\\"`,title:`Delete \\"${y.text}\\"`,children:e.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})}),e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",disabled:v===y.id,className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Send \\"${y.text}\\"`,title:`Send \\"${y.text}\\"`,children:e.jsx(j,{name:"send-plane",className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-56",children:[e.jsx(ct,{onClick:()=>at(y.text),children:"Send to current session"}),e.jsx(ct,{onClick:()=>Xe(y.id,y.text),children:"Send to new session"})]})]})]})]})},y.id)})})})})}),d.length>=7&&e.jsx("div",{className:E("h-[3px] w-full cursor-row-resize hover:bg-[var(--interactive-border)]/80 transition-colors",ae&&"bg-[var(--interactive-border)]"),onPointerDown:rt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize todo list"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:"Plans"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:C.length===1?`${C.length} file`:`${C.length} files`})]}),e.jsx("input",{ref:Ue,type:"file",accept:".md,.markdown,.txt,text/markdown,text/plain",className:"hidden",onChange:y=>{const z=y.target.files?.[0]??null;pe(z),y.currentTarget.value=""}}),e.jsx("button",{type:"button",onClick:O,disabled:!t||Ae,className:"inline-flex h-6 w-6 items-center justify-center rounded-md border border-border/70 text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Import plan from file",title:"Import plan from file",children:e.jsx(j,{name:"add",className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"max-h-56 overflow-y-auto rounded-lg border border-border/60 bg-background/40",children:C.length===0?e.jsx("p",{className:"px-3 py-3 typography-meta text-muted-foreground",children:"No saved plans yet."}):e.jsx("ul",{className:"divide-y divide-border/50",children:C.map(y=>e.jsxs("li",{className:"flex items-center gap-1.5 px-2.5 py-1.5",children:[e.jsxs("button",{type:"button",onClick:()=>De(y),className:"flex min-w-0 flex-1 items-center justify-between gap-3 rounded-md px-1.5 py-1 text-left hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"min-w-0 truncate typography-ui-label text-foreground",children:y.title}),e.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:new Date(y.createdAt).toLocaleDateString("en-US")})]}),e.jsx("button",{type:"button",onClick:()=>{yt(y.id)},disabled:it===y.id,className:"inline-flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed disabled:opacity-50",title:"Delete plan","aria-label":`Delete plan \\"${y.title}\\"`,children:e.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},y.id))})})]}),e.jsx(sm,{open:A!==null,onOpenChange:y=>{!y&&!m&&S(null)},projectDirectory:t?.path??null,submitting:m,onConfirm:dt})]}):e.jsx("div",{className:E("w-full min-w-0 p-3",r),children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to add notes and todos."})})},ox=({onActionComplete:t})=>{const s=Lt(c=>c.activeProjectId),n=Lt(c=>c.projects),r=Is(c=>c.homeDirectory),i=o.useMemo(()=>s?n.find(c=>c.id===s)??n[0]??null:n[0]??null,[s,n]),a=o.useMemo(()=>i?{id:i.id,path:i.path}:null,[i]),l=o.useMemo(()=>i?i.label?.trim()||Us(i.path,r)||i.path:null,[i,r]);return e.jsx("div",{className:"h-full min-h-0 overflow-auto bg-transparent",children:e.jsx(am,{projectRef:a,projectLabel:l,onActionComplete:t})})},Hn=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),ro=512*1024,lm=new TextEncoder,cm=new TextDecoder,wr=t=>{const s=lm.encode(t);if(s.byteLength<=ro)return{text:t,byteLength:s.byteLength};let n=s.byteLength-ro;for(;n<s.byteLength&&(s[n]&192)===128;)n+=1;const r=s.subarray(n);return{text:cm.decode(r),byteLength:r.byteLength}},qs=(t,s)=>`${t}\0${s}`,Sr=(t,s)=>{let n=null;for(const r of t.keys())s(r)&&(n??=new Map(t),n.delete(r));return n},dm="terminal-store";let Mi=!1,Fi=0;const On=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(Fi+=1,`tab-${Date.now().toString(36)}-${Fi.toString(36)}`),jr=t=>typeof t=="object"&&t!==null,um=t=>{const s=/^tab-(\d+)$/.exec(t);if(!s)return null;const n=Number(s[1]);return Number.isFinite(n)?n:null};function $t(t){let s=t.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const fm=/^Terminal(?: (\d+))?$/,hm=t=>{let s=0;for(const n of t){const r=fm.exec(n.label);if(!r)continue;const i=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(i)&&(s=Math.max(s,i))}return s===0?"Terminal":`Terminal ${s+1}`},Cr=(t,s)=>({id:t,terminalSessionId:null,lifecycle:"idle",label:s,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),kr=t=>({tabs:[t],activeTabId:t.id}),ls=(t,s)=>t.tabs.findIndex(n=>n.id===s);let Nr=null,Ar=null;const pm=t=>{if(Ar&&Nr?.sessions===t.sessions&&Nr.nextTabId===t.nextTabId)return Ar;const s={sessions:Array.from(t.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(i=>({id:i.id,label:i.label,iconKey:i.iconKey,createdAt:i.createdAt}))}]),nextTabId:t.nextTabId};return Nr={sessions:t.sessions,nextTabId:t.nextTabId},Ar=s,s},mm=()=>{const t=Iu(()=>fu());if(!t)return;let s=null;return{getItem:n=>t.getItem(n),setItem:(n,r)=>{if(r.state!==s)return s=r.state,t.setItem(n,r)},removeItem:n=>(s=null,t.removeItem(n))}},Te=ws()(va(fo((t,s)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=$t(n);r&&t(i=>{if(i.sessions.has(r))return i;const a=new Map(i.sessions),l=On(),c=Cr(l,"Terminal");return a.set(r,kr(c)),{sessions:a,nextTabId:i.nextTabId+1}})},getDirectoryState:n=>{const r=$t(n);return s().sessions.get(r)},getActiveTab:n=>{const r=$t(n),i=s().sessions.get(r);if(!i)return;const a=i.activeTabId;return a?i.tabs.find(l=>l.id===a)??i.tabs[0]:i.tabs[0]},getBuffer:(n,r)=>s().buffers.get(qs($t(n),r))??Hn,createTab:n=>{const r=$t(n);if(!r)return"tab-invalid";const i=On();return t(a=>{const l=new Map(a.sessions),c=l.get(r),d=a.nextTabId+1,u=hm(c?.tabs??[]),x=Cr(i,u);return c?l.set(r,{...c,tabs:[...c.tabs,x]}):l.set(r,kr(x)),{sessions:l,nextTabId:d}}),i},setActiveTab:(n,r)=>{const i=$t(n);t(a=>{const l=new Map(a.sessions),c=l.get(i);return!c||c.activeTabId===r||ls(c,r)<0?a:(l.set(i,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,i)=>{const a=$t(n),l=i.trim();l&&t(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const x=ls(u,r);if(x<0||u.tabs[x]?.label===l)return c;const g=[...u.tabs];return g[x]={...g[x],label:l},d.set(a,{...u,tabs:g}),{sessions:d}})},setTabIconKey:(n,r,i)=>{const a=$t(n);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ls(d,r);if(u<0)return l;const x=i?.trim()||null;if(d.tabs[u]?.iconKey===x)return l;const g=[...d.tabs];return g[u]={...g[u],iconKey:x},c.set(a,{...d,tabs:g}),{sessions:c}})},closeTab:(n,r)=>{const i=$t(n);t(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=ls(c,r);if(d<0)return a;const u=c.tabs.filter(f=>f.id!==r),x=Object.fromEntries(Object.entries(a.projectActionRuns).filter(([,f])=>!(f.directory===i&&f.tabId===r))),g=Object.keys(x).length!==Object.keys(a.projectActionRuns).length,v=qs(i,r),b=a.buffers.has(v)?Sr(a.buffers,f=>f===v):null;if(u.length===0){const f=On(),C=Cr(f,"Terminal");return l.set(i,kr(C)),{sessions:l,nextTabId:a.nextTabId+1,...b?{buffers:b}:{},...g?{projectActionRuns:x}:{}}}let h=c.activeTabId;return c.activeTabId===r&&(h=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(i,{...c,tabs:u,activeTabId:h}),{sessions:l,...b?{buffers:b}:{},...g?{projectActionRuns:x}:{}}})},setTabSessionId:(n,r,i)=>{const a=$t(n);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ls(d,r);if(u<0)return l;const x=d.tabs[u],g=i!==null&&x.terminalSessionId!==i,v=i?"running":x.terminalSessionId?"exited":x.lifecycle,b={...x,terminalSessionId:i,lifecycle:v,isConnecting:!1},h=qs(a,r),f=g&&l.buffers.has(h)?Sr(l.buffers,N=>N===h):null,C=[...d.tabs];return C[u]=b,c.set(a,{...d,tabs:C}),{sessions:c,...f?{buffers:f}:{}}})},setTabLifecycle:(n,r,i)=>{const a=$t(n);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ls(d,r);if(u<0)return l;const x=[...d.tabs];return x[u]={...x[u],lifecycle:i,isConnecting:!1},c.set(a,{...d,tabs:x}),{sessions:c}})},setConnecting:(n,r,i)=>{const a=$t(n);t(l=>{const c=new Map(l.sessions),d=c.get(a);if(!d)return l;const u=ls(d,r);if(u<0)return l;const x=[...d.tabs];return x[u]={...x[u],isConnecting:i},c.set(a,{...d,tabs:x}),{sessions:c}})},replaceBuffer:(n,r,i,a)=>{const l=$t(n);t(c=>{const d=c.sessions.get(l);if(!d||ls(d,r)<0)return c;const u=qs(l,r),x=c.buffers.get(u)??Hn;if(x.lastSequence>a)return c;const g=wr(i);if(x.lastSequence===a&&x.byteLength===g.byteLength&&x.chunks.map(h=>h.data).join("")===g.text)return c;const v=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:g.text?[{id:v,data:g.text,byteLength:g.byteLength}]:[],byteLength:g.byteLength,lastSequence:a}),{buffers:b,nextChunkId:g.text?v+1:v}})},appendToBuffer:(n,r,i,a,l)=>{if(!i)return;const c=$t(n);t(d=>{const u=d.sessions.get(c);if(!u||ls(u,r)<0)return d;const x=qs(c,r),g=d.buffers.get(x)??Hn;if(a!==void 0&&a<=g.lastSequence)return d;const v=d.nextChunkId,b=wr(i),h=l!==void 0&&l!==i?wr(l).text:void 0,f={id:v,data:b.text,...h!==void 0?{replayData:h}:{},byteLength:b.byteLength},C=[...g.chunks,f];let N=g.byteLength+f.byteLength;for(;N>ro&&C.length>1;){const S=C.shift();if(!S)break;N-=S.byteLength}const A=new Map(d.buffers);return A.set(x,{chunks:C,byteLength:N,lastSequence:a??g.lastSequence}),{buffers:A,nextChunkId:v+1}})},setTabPreviewUrl:(n,r,i,a={})=>{const l=$t(n);t(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const x=ls(u,r);if(x<0)return c;const g=u.tabs[x],v=a.autoOpened??g.previewAutoOpened,b=a.locked??g.previewUrlLocked;if(g.previewUrl===i&&g.previewAutoOpened===v&&g.previewUrlLocked===b)return c;const h=[...u.tabs];return h[x]={...g,previewUrl:i,previewAutoOpened:v,previewUrlLocked:b},d.set(l,{...u,tabs:h}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const i=$t(n);t(a=>{const l=new Map(a.sessions),c=l.get(i);if(!c)return a;const d=ls(c,r);if(d<0)return a;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return a;const x=[...c.tabs];return x[d]={...u,previewAutoOpened:!0},l.set(i,{...c,tabs:x}),{sessions:l}})},setProjectActionRun:n=>{t(r=>{const i=r.projectActionRuns[n.key];return i&&i.directory===n.directory&&i.actionId===n.actionId&&i.tabId===n.tabId&&i.sessionId===n.sessionId&&i.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{t(i=>{const a=i.projectActionRuns[n];return!a||a.status===r?i:{projectActionRuns:{...i.projectActionRuns,[n]:{...a,status:r}}}})},removeProjectActionRun:n=>{t(r=>{if(!r.projectActionRuns[n])return r;const i={...r.projectActionRuns};return delete i[n],{projectActionRuns:i}})},removeDirectory:n=>{const r=$t(n);t(i=>{const a=new Map(i.sessions);a.delete(r);const l=qs(r,""),c=Sr(i.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:a,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{t({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:dm,storage:mm(),partialize:pm,merge:(t,s)=>{if(!jr(t))return s;const n=Array.isArray(t.sessions)?t.sessions:[],r=new Map;let i=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!jr(u))continue;const x=Array.isArray(u.tabs)?u.tabs:[],g=[],v=new Map;for(const C of x){if(!jr(C))continue;const N=typeof C.id=="string"?C.id:null;if(!N)continue;const A=um(N);A!==null&&(i=Math.max(i,A));const S=A===null?N:On();v.set(N,S),g.push({id:S,label:typeof C.label=="string"?C.label:"Terminal",iconKey:typeof C.iconKey=="string"?C.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof C.createdAt=="number"?C.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(g.length===0)continue;const b=typeof u.activeTabId=="string"?u.activeTabId:null,h=b?v.get(b)??b:null,f=h?g.some(C=>C.id===h):!1;r.set(d,{tabs:g,activeTabId:f?h:g[0].id})}const a=typeof t.nextTabId=="number"&&Number.isFinite(t.nextTabId)?t.nextTabId:1,l=Math.max(s.nextTabId,a,i+1);return{...s,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!Mi){Mi=!0;const t=Te.persist,s=()=>{Te.getState().hasHydrated||Te.setState({hasHydrated:!0})};t?.hasHydrated?.()?s():t?.onFinishHydration?t.onFinishHydration(s):s()}function gm(t){const{colors:s}=t,n=s.syntax.base;return{background:s.surface.background,foreground:n.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:s.surface.elevatedForeground}}function xm(t,s,n,r,i=!1){const l=`${t}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",fontSize:s,fontFamily:l,allowTransparency:!1,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite},scrollback:1e4,ghostty:r,disableStdin:i}}const Ir=["\x1B[0m","\x1B[m"],bm=t=>{const s=t.trim(),n=/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(s)?.[1];if(n){const a=n.length<=4?n.slice(0,3).split("").map(l=>l+l).join(""):n.slice(0,6);return[Number.parseInt(a.slice(0,2),16),Number.parseInt(a.slice(2,4),16),Number.parseInt(a.slice(4,6),16)]}const r=/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+)?\s*\)$/i.exec(s);if(!r)return null;const i=r.slice(1,4).map(Number);return i.some(a=>a<0||a>255)?null:i},Li=t=>{const s=bm(t);return s?`\x1B[0;48;2;${s[0]};${s[1]};${s[2]}m`:null},ym=(t,s,n)=>{const r=s+t;if(!n)return{data:r,carry:""};let i=0;const a=Math.max(...Ir.map(d=>d.length))-1;for(let d=1;d<=Math.min(a,r.length);d+=1){const u=r.slice(-d);Ir.some(x=>x.length>u.length&&x.startsWith(u))&&(i=d)}const l=i>0?r.slice(-i):"";let c=i>0?r.slice(0,-i):r;for(const d of Ir)c=c.replaceAll(d,n);return{data:c,carry:l}},vm=(t,s,n,r,i)=>{if(n.width<=0||n.height<=0||r<=0||i<=0)return null;const a=Math.floor((t-n.left)/n.width*r),l=Math.floor((s-n.top)/n.height*i);return{column:Math.max(0,Math.min(r-1,a)),row:Math.max(0,Math.min(i-1,l))}},wm=(t,s)=>{const n=Math.max(0,Math.min(t.length-1,s)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(t[n]))return{startColumn:n,endColumn:n};let i=n,a=n;for(;i>0&&r(t[i-1]);)i-=1;for(;a<t.length-1&&r(t[a+1]);)a+=1;return{startColumn:i,endColumn:a}};let Sm=null;const jm=()=>Sm??=Xs(()=>import("./vendor-ghostty-web-CrxinGGH.js"),__vite__mapDeps([112,8])).then(async t=>({module:t,ghostty:await t.Ghostty.load()})),Cm=2e3,km=()=>{if(typeof window>"u")return Promise.resolve();const t=window.__pichamberEnsureNerdFonts;return typeof t!="function"?Promise.resolve():Promise.race([Promise.resolve(t()).catch(()=>{}),new Promise(s=>setTimeout(s,Cm))]).then(()=>{})},Nm=(t,s,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||t.clientWidth<24||t.clientHeight<24)return null;r.font=`${n}px ${s}`;const i=r.measureText("M"),a=Math.ceil(i.width),l=Math.ceil((i.actualBoundingBoxAscent||n*.8)+(i.actualBoundingBoxDescent||n*.2))+2;if(a<1||l<1)return null;const c=window.getComputedStyle(t),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((t.clientWidth-d-15)/a)),rows:Math.max(1,Math.floor((t.clientHeight-u)/l))}},Xa=o.forwardRef(({sessionKey:t,chunks:s,onInput:n,onResize:r,theme:i,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:x=!0},g)=>{const v=o.useRef(null),b=o.useRef(null),h=o.useRef(null),f=o.useRef(n),C=o.useRef(r),N=o.useRef(null),A=o.useRef(null),S=o.useRef(null),m=o.useRef(""),p=o.useRef(""),I=o.useRef(Li(i.background)),R=o.useRef(!1),D=o.useRef(0),F=o.useRef(x),T=o.useRef(!1),[U,G]=o.useState(0),[Y,ce]=o.useState(0);f.current=n,C.current=r,F.current=x,I.current=Li(i.background),o.useLayoutEffect(()=>{const B=v.current;if(!B)return;const L=Nm(B,a,l);A.current=L,L&&C.current(L.cols,L.rows)},[a,l]);const ae=o.useCallback(()=>{const B=v.current,L=b.current;if(!B||!L||!h.current||!F.current)return;const J=B.getBoundingClientRect();if(!(J.width<24||J.height<24))try{h.current.fit();const fe={cols:L.cols,rows:L.rows};(!N.current||N.current.cols!==fe.cols||N.current.rows!==fe.rows)&&(N.current=fe,C.current(fe.cols,fe.rows)),T.current||(T.current=!0,G($=>$+1))}catch{}},[]),W=o.useCallback(()=>{if(R.current||!m.current||!b.current)return;const B=b.current,L=m.current;m.current="";const J=ym(L,p.current,I.current);if(p.current=J.carry,!J.data){m.current&&W();return}R.current=!0;const fe=D.current;B.write(J.data,()=>{b.current!==B||D.current!==fe||(R.current=!1,m.current&&W())})},[]),Q=o.useCallback(()=>{S.current=null,m.current="",p.current="",R.current=!1,D.current+=1;const B=b.current;if(!B){ce(L=>L+1);return}try{B.reset();const L=I.current;L&&B.write(`${L}\x1B[2J\x1B[H`)}catch{ce(L=>L+1)}},[]);return o.useEffect(()=>{const B=v.current;if(!B)return;let L=!1,J=null,fe=null,$=null,Ce=null,we=[];const We=()=>{J&&F.current&&(J.options.cursorBlink=!0)},$e=Z=>{Z.relatedTarget instanceof Node&&B.contains(Z.relatedTarget)||J&&(J.options.cursorBlink=!1)},Be=()=>{J&&F.current&&B.contains(document.activeElement)&&(J.options.cursorBlink=!0)},Ie=()=>{J&&(J.options.cursorBlink=!1)};return B.addEventListener("focusin",We),B.addEventListener("focusout",$e),window.addEventListener("focus",Be),window.addEventListener("blur",Ie),Promise.all([jm(),km()]).then(([{module:Z,ghostty:Se}])=>{if(L)return;J=new Z.Terminal({...xm(a,l,i,Se,!1),...A.current??{}});const rt=new Z.FitAddon;J.loadAddon(rt),J.open(B),b.current=J,h.current=rt,we=[J.onData(ye=>f.current(ye))],fe=new ResizeObserver(()=>{$&&clearTimeout($),$=setTimeout(ae,80)}),fe.observe(B),ae();const Ne=I.current;Ne&&J.write(`${Ne}\x1B[2J\x1B[H`),Ce=requestAnimationFrame(ae)}),()=>{L=!0;const Z=document.activeElement;Z instanceof HTMLElement&&B.contains(Z)&&(Z.blur(),window.Capacitor?.getPlatform?.()==="android"&&Xs(async()=>{const{Keyboard:rt}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:rt}},__vite__mapDeps([113,114])).then(({Keyboard:rt})=>rt.hide()).catch(()=>{})),fe?.disconnect(),$&&clearTimeout($),Ce!==null&&cancelAnimationFrame(Ce),B.removeEventListener("focusin",We),B.removeEventListener("focusout",$e),window.removeEventListener("focus",Be),window.removeEventListener("blur",Ie),we.forEach(Se=>Se.dispose()),J?.dispose(),b.current=null,h.current=null,N.current=null,S.current=null,m.current="",p.current="",R.current=!1,D.current+=1,T.current=!1}},[ae,a,l,Y,i]),o.useEffect(()=>{const B=b.current,L=v.current;!B||!L||(B.options.cursorBlink=x&&document.hasFocus()&&L.contains(document.activeElement))},[x,U]),o.useEffect(()=>{if(!b.current)return;if(s.length===0){S.current!==null&&Q();return}const L=S.current;let J=-1;if(L!==null){for(let Ce=s.length-1;Ce>=0;Ce-=1){const we=s[Ce].id;if(we===L){J=Ce;break}if(we<L)break}if(J<0){Q();return}}const fe=J<0,$=J>=0?s.slice(J+1):s;m.current+=$.map(Ce=>fe?Ce.replayData??Ce.data:Ce.data).join(""),S.current=s.at(-1)?.id??null,W()},[s,W,U,Q]),o.useEffect(()=>{if(!u||!x)return;const B=requestAnimationFrame(()=>b.current?.focus());return()=>cancelAnimationFrame(B)},[u,x,U,t]),o.useEffect(()=>{const B=v.current;if(!d||!B)return;const L=J=>{const fe=J;if(!fe.isComposing)switch(fe.inputType){case"insertText":fe.data&&f.current(fe.data);break;case"insertLineBreak":case"insertParagraph":f.current("\r");break;case"deleteContentBackward":f.current("");break}};return B.addEventListener("beforeinput",L),()=>B.removeEventListener("beforeinput",L)},[d,U]),o.useEffect(()=>{const B=v.current,L=b.current;if(!d||!B||!L)return;let J=null,fe=null,$="idle",Ce=0,we=0,We=0,$e=0,Be=null;const Ie=Math.max(12,l+2),Z=()=>{window.Capacitor?.getPlatform?.()==="android"&&Xs(async()=>{const{Keyboard:ge}=await import("./vendor-capacitor-keyboard-CYccoJjr.js");return{Keyboard:ge}},__vite__mapDeps([113,114])).then(({Keyboard:ge})=>ge.show()).catch(()=>{})},Se=()=>{fe&&(clearTimeout(fe),fe=null)},rt=(V,ge)=>{const H=B.querySelector("canvas");return H?vm(V,ge,H.getBoundingClientRect(),L.cols,L.rows):null},Ne=(V,ge)=>{const H=B.querySelector("canvas");if(!H)return;const xe=H.getBoundingClientRect(),ve=xe.left+(ge.column+.5)/L.cols*xe.width,Me=xe.top+(ge.row+.5)/L.rows*xe.height;H.dispatchEvent(new MouseEvent(V,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:ve,clientY:Me}))},ye=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},Re=V=>{V.pointerType!=="touch"||J!==null||(J=V.pointerId,$="pending",Ce=V.clientX,we=V.clientY,We=V.clientY,$e=0,Be=null,B.setPointerCapture(V.pointerId),fe=setTimeout(()=>{if(fe=null,J!==V.pointerId||$!=="pending")return;const ge=rt(Ce,we);if(!ge)return;const H=L.buffer.active,xe=Math.max(0,H.length-L.rows-H.viewportY+ge.row),ve=H.getLine(xe),Me=Array.from({length:L.cols},(dt,Ue)=>ve?.getCell(Ue)?.getChars()??""),Xe=wm(Me,ge.column),at={column:Xe.startColumn,row:ge.row};Be={column:Xe.endColumn,row:ge.row},$="selecting",Ne("mousedown",at),Ne("mousemove",Be)},350))},Qe=V=>{if(J!==V.pointerId)return;if($==="selecting"){const xe=rt(V.clientX,V.clientY);xe&&(!Be||xe.column!==Be.column||xe.row!==Be.row)&&(Be=xe,Ne("mousemove",xe)),V.cancelable&&V.preventDefault();return}if($==="pending"){if(Math.hypot(V.clientX-Ce,V.clientY-we)<8)return;Se(),$="scrolling"}if($!=="scrolling")return;const ge=We-V.clientY;We=V.clientY,$e+=ge;const H=Math.trunc($e/Ie);H&&(L.scrollLines(H),$e-=H*Ie),V.cancelable&&V.preventDefault()},ze=V=>{if(J!==V.pointerId)return;const ge=$==="pending",H=$==="selecting";Se(),B.hasPointerCapture(V.pointerId)&&B.releasePointerCapture(V.pointerId),J=null,$="idle",H&&ye(),ge&&(L.focus(),Z())},q=V=>{if(J!==V.pointerId)return;const ge=$==="selecting";Se(),B.hasPointerCapture(V.pointerId)&&B.releasePointerCapture(V.pointerId),J=null,$="idle",ge&&ye()};return B.addEventListener("pointerdown",Re),B.addEventListener("pointermove",Qe,{passive:!1}),B.addEventListener("pointerup",ze),B.addEventListener("pointercancel",q),()=>{Se(),B.removeEventListener("pointerdown",Re),B.removeEventListener("pointermove",Qe),B.removeEventListener("pointerup",ze),B.removeEventListener("pointercancel",q)}},[d,l,U]),o.useImperativeHandle(g,()=>({focus:()=>b.current?.focus(),fit:ae,getSelection:()=>{const B=b.current,L=B?.getSelectionPosition(),J=B?.getSelection()??"";return!L||!J.trim()?null:{text:J,startLine:L.start.y+1,endLine:L.end.y+1}}}),[ae]),e.jsx("div",{ref:v,"data-terminal-owner":"main",className:E("terminal-viewport-container h-full w-full overflow-hidden touch-none",c)})});Xa.displayName="TerminalViewport";const Am=280,Oi=4,Im=({transform:t})=>({...t,y:0}),Dm=({id:t,children:s,className:n})=>{const{attributes:r,listeners:i,setNodeRef:a,transform:l,transition:c,isDragging:d}=or({id:t});return e.jsx("div",{ref:a,"data-sortable-tab-id":t,style:{transform:ir.Transform.toString(l),transition:c},className:E("h-full rounded-md",n,d&&"opacity-50"),...r,...i,children:s})},Pm=({id:t,children:s,className:n})=>e.jsx("div",{className:E("h-full",n),"data-sortable-tab-id":t,children:s}),Tm=({items:t,activeId:s,onSelect:n,onClose:r,onReorder:i,layoutMode:a="scrollable",variant:l="default",activePillInsetClassName:c,activePillButtonClassName:d,inactiveTabsIconOnly:u=!1,animateActivePill:x,activePillLowercase:g=!0,nonCompositedIndicator:v=!1,className:b})=>{const h=oe(q=>q.isMobile),{isTablet:f}=$s(),C=h||f,N=o.useRef(null),[A,S]=o.useState({left:!1,right:!1}),m=o.useMemo(()=>t.map(q=>q.id),[t]),p=a==="scrollable",I=l==="default",R=l==="active-pill",F=R||l==="animated",T=I,U=F||T,G=R&&p,Y=F,ce=x??F,ae=typeof i=="function",W=ae?Dm:Pm,Q=o.useRef(new Map),[B,L]=o.useState(null),[J,fe]=o.useState(!1),[$,Ce]=o.useState(null),we=o.useRef(!1),We=o.useRef(0),$e=o.useRef(s),Be=o.useRef(null),Ie=o.useMemo(()=>{if(!U||!$||!s||$===s)return 0;const q=t.findIndex(ge=>ge.id===$),V=t.findIndex(ge=>ge.id===s);return q<0||V<0?0:q>V?Oi:-Oi},[s,t,$,U]),Z=sr(yn(ho,{activationConstraint:{distance:8}})),Se=o.useCallback((q,V)=>!q||!V?q===V:Math.abs(q.left-V.left)<.5&&Math.abs(q.top-V.top)<.5&&Math.abs(q.width-V.width)<.5&&Math.abs(q.height-V.height)<.5,[]),rt=o.useCallback((q,V)=>{if(V){Q.current.set(q,V);return}Q.current.delete(q)},[]),Ne=o.useCallback(()=>{if(!U||!s){L(Me=>Me===null?Me:null);return}const q=N.current,V=Q.current.get(s);if(!q||!V){L(Me=>Me===null?Me:null);return}let ge=0,H=0,xe=V;for(;xe&&xe!==q;)ge+=xe.offsetLeft,H+=xe.offsetTop,xe=xe.offsetParent;const ve={left:ge,top:H,width:V.offsetWidth,height:V.offsetHeight};L(Me=>Se(Me,ve)?Me:ve)},[s,Se,U]),ye=o.useCallback(()=>{if(!p){S({left:!1,right:!1});return}const q=N.current;if(!q){S({left:!1,right:!1});return}S({left:q.scrollLeft>2,right:q.scrollLeft+q.clientWidth<q.scrollWidth-2})},[p]);o.useEffect(()=>{if(!p){S({left:!1,right:!1});return}const q=N.current;if(!q)return;ye(),q.addEventListener("scroll",ye,{passive:!0});const V=new ResizeObserver(ye);return V.observe(q),()=>{q.removeEventListener("scroll",ye),V.disconnect()}},[p,t.length,ye]),o.useEffect(()=>{if(!U){L(null);return}Ne();const q=N.current;if(!q)return;const V=new ResizeObserver(()=>{performance.now()-We.current>Am&&fe(!1),Ne()});if(V.observe(q),s){const ge=Q.current.get(s);ge&&V.observe(ge)}return()=>{V.disconnect()}},[s,t.length,Ne,U]),o.useLayoutEffect(()=>{Ne()});const Re=m.join("\0");o.useLayoutEffect(()=>{if(!U){we.current=!1,fe(!1);return}const q=Be.current!==Re;if(Be.current=Re,!we.current){we.current=!0,$e.current=s;return}const V=$e.current!==s;if($e.current=s,!V||q){fe(!1);return}We.current=performance.now(),fe(!0)},[s,Re,U]),o.useEffect(()=>{if(!p||!s)return;const q=N.current;if(!q)return;const V=window.requestAnimationFrame(()=>{const ge=typeof window.CSS?.escape=="function"?window.CSS.escape(s):s.replace(/"/g,'\\"'),H=q.querySelector(`[data-sortable-tab-id="${ge}"]`);H&&(H.scrollIntoView({block:"nearest",inline:"nearest"}),ye())});return()=>{window.cancelAnimationFrame(V)}},[s,p,t.length,ye]);const Qe=o.useCallback(q=>{if(!i)return;const{active:V,over:ge}=q;!ge||V.id===ge.id||i(String(V.id),String(ge.id))},[i]),ze=e.jsxs("div",{className:E("relative flex h-full min-w-0 flex-1",b),children:[p&&A.left?e.jsx("div",{className:E("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",F?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,p&&A.right?e.jsx("div",{className:E("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",F?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e.jsxs("div",{ref:N,className:E("relative flex h-full min-w-0 flex-1",F?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",F&&"@container/pill-tabs",F&&"pill-tabs__track",F&&(c??"gap-0.5 py-0.5"),T&&"items-center overflow-y-hidden",Y&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",p?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:p?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[F&&B?e.jsx("div",{className:E("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",ce&&J&&(v?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:v?{left:`${B.left+Ie}px`,top:`${B.top}px`,width:`${B.width}px`,height:`${B.height}px`}:{transform:`translate3d(${B.left+Ie}px, ${B.top}px, 0)`,width:`${B.width}px`,height:`${B.height}px`}}):null,T&&B?e.jsx("div",{className:E("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",J&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${B.left+Ie}px, 0, 0)`,width:`${B.width}px`},"aria-hidden":!0}):null,t.map(q=>{const V=q.id===s,ge=u&&F&&!V&&!!q.icon,H=!ge,xe=!!q.icon,ve=u&&F&&V&&!p&&!G,Me=q.closable!==!1&&!!r,Xe=Me&&!!q.icon,at=p||G?void 0:F?ve?"flex-none basis-auto":h?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",dt=Me?Ae=>{Ae.button===1&&(Ae.preventDefault(),Ae.stopPropagation(),r?.(q.id))}:void 0,Ue=Me?Ae=>{Ae.button===1&&Ae.preventDefault()}:void 0;return e.jsx(W,{id:q.id,className:at,children:e.jsxs("div",{ref:Ae=>rt(q.id,Ae),onAuxClick:dt,onMouseDown:Ue,className:E("group flex h-full min-w-0 flex-nowrap items-center",p||G?"shrink-0":F?"w-full":"w-full min-w-0",F?"relative z-10 bg-transparent":V?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":V,"aria-label":ge?q.title??q.label:void 0,onClick:()=>n(q.id),onPointerDown:U?()=>{fe(!0),Ce(q.id)}:void 0,onPointerUp:U?()=>Ce(null):void 0,onPointerLeave:U?()=>Ce(null):void 0,onPointerCancel:U?()=>Ce(null):void 0,className:E(F?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",F&&g?"lowercase":null,F&&(ge?"gap-0":"gap-1.5"),F?G?"shrink-0 whitespace-nowrap px-3 text-center":p?"max-w-56 shrink-0 px-3 text-center":ge?"px-2 !min-w-0 text-center":ve?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":p?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",F?d??(R?h?"h-[38px]":"h-[31px]":"h-7"):null,F?V?"text-foreground":"text-muted-foreground hover:text-foreground":null,F?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:q.title??q.label,children:F?e.jsxs(e.Fragment,{children:[xe?e.jsxs("span",{className:"relative flex h-4 w-4 shrink-0 items-center justify-center",children:[e.jsx("span",{className:E("flex items-center justify-center transition-opacity",Xe&&(C?"opacity-0":"group-hover:opacity-0")),children:q.icon}),Xe?e.jsx("span",{role:"button",tabIndex:-1,className:E("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",C?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Ae=>{Ae.stopPropagation()},onClick:Ae=>{Ae.stopPropagation(),r?.(q.id)},"aria-label":q.closeLabel??`Close ${q.label} tab`,title:q.closeLabel??`Close ${q.label} tab`,children:e.jsx(j,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,H?e.jsx("span",{className:"animated-tabs__label truncate",children:q.label}):null]}):e.jsxs("span",{className:E("flex min-w-0 flex-nowrap items-center gap-1.5",!p&&"justify-center"),children:[xe?e.jsxs("span",{className:E("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",V?"text-[var(--primary-base)]":"text-muted-foreground"),children:[e.jsx("span",{className:E("flex items-center justify-center transition-opacity",Xe&&(C?"opacity-0":"group-hover:opacity-0")),children:q.icon}),Xe?e.jsx("span",{role:"button",tabIndex:-1,className:E("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",C?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:Ae=>{Ae.stopPropagation()},onClick:Ae=>{Ae.stopPropagation(),r?.(q.id)},"aria-label":q.closeLabel??`Close ${q.label} tab`,title:q.closeLabel??`Close ${q.label} tab`,children:e.jsx(j,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null,e.jsx("span",{className:"truncate leading-[1.2]",children:q.label})]})}),Me&&!Xe?e.jsx("button",{type:"button",onPointerDown:Ae=>{Ae.stopPropagation()},onClick:Ae=>{Ae.stopPropagation(),r?.(q.id)},className:E("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",F?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",F?V?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":V?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":q.closeLabel??`Close ${q.label} tab`,title:q.closeLabel??`Close ${q.label} tab`,children:e.jsx(j,{name:"close",className:"h-3 w-3"})}):null]})},q.id)})]})]});return ae?e.jsxs(nr,{sensors:Z,collisionDetection:rr,onDragEnd:Qe,modifiers:[Im],children:[e.jsx(po,{items:m,strategy:Fu,children:ze}),e.jsx(wa,{dropAnimation:null})]}):ze},Em="\x1B",Rm=new RegExp(`${Em}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Mm=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Fm=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Lm=/Serving HTTP on .*? port (\d{2,5})/i,Om=new Set([".",",",";",":","!","?"]),Bm=t=>{let s=t;for(;s.length>0;){const n=s[s.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",i=s.slice(0,-1),a=(i.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(i.match(new RegExp(`\\${n}`,"g"))||[]).length;if(a>l)break;s=i;continue}if(Om.has(n)){s=s.slice(0,-1);continue}break}return s},Bi=t=>{let s=Bm(t);return s=s.replace("0.0.0.0","127.0.0.1"),s=s.replace("[::1]","127.0.0.1"),s=s.replace("[::]","127.0.0.1"),s},_m=t=>{if(!t)return null;const s=t.replace(Rm,""),n=s.match(Lm);if(n?.[1]){const i=Number.parseInt(n[1],10);if(Number.isFinite(i)&&i>0&&i<=65535)return`http://127.0.0.1:${i}/`}const r=s.split(`
|
|
40
|
-
`);for(const i of r){if(!Fm.test(i))continue;const a=Array.from(i.matchAll(Mm));if(a.length===0)continue;const l=a.find(c=>{try{return!!new URL(Bi(c[1])).port}catch{return!1}});return Bi((l??a[0])[1])}return null},Um=async(t,s=1500)=>{if(!t||typeof window>"u")return!1;let n;try{n=new URL(t)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const i=new AbortController,a=window.setTimeout(()=>i.abort(),s);try{const l=await ss("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:i.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(a)}},zm={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},$m=(t,s)=>{if(s&&t.startsWith("arrow-")){const n=s==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[t];return`\x1B[1;${n}${r}`}return zm[t]},el=t=>{const s=t[0]?.toUpperCase();return!s||s<"A"||s>"Z"?null:String.fromCharCode(s.charCodeAt(0)&31)},Gm=(t,s)=>t&&(s==="ctrl"?el(t)??t:t.length===1&&t!=="\x1B"?`\x1B${t}`:t),_i={cols:80,rows:24},ix=({visible:t})=>{const{terminal:s,runtime:n}=Zn(),{currentTheme:r}=la(),i=o.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});i.current={themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground};const{monoFont:a}=Pd(),l=oe(M=>M.terminalFontSize),c=oe(M=>M.terminalShell),d=oe(M=>M.terminalLoginShells.includes(M.terminalShell)),{isMobile:u,isTablet:x,hasTouchOnlyPointer:g}=$s(),v=u||x,b=(v||g)&&n.platform==="web",h=!0,f=oe(M=>M.showTerminalQuickKeysOnDesktop),C=v||f,N=Oe(M=>M.currentSessionId),A=Oe(M=>M.newSessionDraft),S=N!==null||A?.open===!0,m=Td()??null,p=Te(M=>m?M.sessions.get(m):void 0),I=Te(M=>M.hasHydrated),R=Te(M=>M.ensureDirectory),D=Te(M=>M.createTab),F=Te(M=>M.setActiveTab),T=Te(M=>M.closeTab),U=Te(M=>M.setTabSessionId),G=Te(M=>M.setTabLifecycle),Y=Te(M=>M.setConnecting),ce=Te(M=>M.appendToBuffer),ae=Te(M=>M.replaceBuffer),W=Te(M=>M.setTabPreviewUrl),Q=ta(M=>M.addDraft),B=oe(M=>M.openContextPreview),L=o.useMemo(()=>p?p.activeTabId??p.tabs[0]?.id??null:null,[p,h]),J=o.useMemo(()=>{if(p)return L?p.tabs.find(M=>M.id===L)??p.tabs[0]:p.tabs[0]},[p,L]),fe=o.useMemo(()=>(p?.tabs??[]).map(M=>({icon:(()=>{const te=M.iconKey?pn[M.iconKey]??"terminal":"terminal";return e.jsx(j,{name:te,className:"h-4 w-4"})})(),id:M.id,label:M.label,title:M.label,closeLabel:"Close tab"})),[p?.tabs]),$=J?.terminalSessionId??null,Ce=J?.lifecycle??"idle",we=Te(M=>m&&L?M.getBuffer(m,L).chunks:Hn.chunks),We=J?.isConnecting??!1,$e=J?.previewUrl??null,[Be,Ie]=o.useState(null),[Z,Se]=o.useState(!1),[rt,Ne]=o.useState(!1),[ye,Re]=o.useState(null),[Qe,ze]=o.useState(!1),q=o.useRef(null),V=o.useRef(null),ge=o.useRef(L),H=o.useRef($),xe=o.useRef(m),ve=o.useRef(null),Me=o.useRef(null),Xe=o.useRef(new Set),at=o.useRef(""),dt=o.useRef(new Set),Ue=o.useRef(0),Ae=o.useCallback(()=>{at.current="",dt.current.clear(),Ue.current+=1},[]),Je=o.useCallback(()=>{b||typeof document<"u"&&!document.hasFocus()||ve.current?.focus()},[b]),it=o.useCallback(()=>{b||ve.current?.focus()},[b]),yt=oe(M=>M.activeMainTab)==="terminal",O=t??yt,[pe,De]=o.useState(O);o.useEffect(()=>{O&&De(!0)},[O]),o.useEffect(()=>{H.current=$},[$]),o.useEffect(()=>{!$||!s.updateAppearance||s.updateAppearance($,i.current).catch(()=>{})},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,s,$]),o.useEffect(()=>{ge.current=L,Ae()},[L,Ae]),o.useEffect(()=>{xe.current=m},[m]),o.useEffect(()=>{!C&&ye!==null&&Re(null)},[C,ye,Re]),o.useEffect(()=>{!$&&ye!==null&&Re(null)},[$,ye,Re]);const y=o.useCallback(()=>{q.current?.(),q.current=null,V.current=null,Ne(!1)},[]);o.useEffect(()=>()=>{y(),H.current=null},[y]);const z=o.useCallback((M,te,be)=>{if(!be)return;const ot=`${at.current}${be}`.replace(/\r\n|\r/g,`
|
|
41
|
-
`),je=ot.split(`
|
|
42
|
-
`),qe=ot.endsWith(`
|
|
43
|
-
`)?je.join(`
|
|
44
|
-
`):je.slice(0,-1).join(`
|
|
45
|
-
`);if(at.current=ot.endsWith(`
|
|
46
|
-
`)?"":(je[je.length-1]??"").slice(-1024),!qe)return;const gt=_m(qe);if(!gt||dt.current.has(gt))return;const Et=Ue.current;dt.current.add(gt),Um(gt).then(Ut=>{if(dt.current.delete(gt),!Ut||Ue.current!==Et)return;const zt=Te.getState().getDirectoryState(M)?.tabs.find(ns=>ns.id===te);!zt||zt.previewUrlLocked||zt.previewUrl===gt||W(M,te,gt,{locked:!1,autoOpened:!1})})},[W]),X=o.useCallback((M,te,be)=>{if(V.current===be)return;y(),V.current=be;const ot=s.connect(be,{onEvent:je=>{if(V.current===be)switch(je.type){case"snapshot":{Y(M,te,!1),Ie(null),Se(!1),Ne(!1),Je(),ae(M,te,je.data??"",je.sequence??0),z(M,te,je.data??""),je.status==="exited"&&G(M,te,"exited");break}case"reconnecting":{Ie(null),Se(!1),Ne(!0);break}case"data":{je.data&&(ce(M,te,je.data,je.sequence,je.replayData),z(M,te,je.data));break}case"exit":{const qe=typeof je.exitCode=="number"?je.exitCode:null,gt=typeof je.signal=="number"?je.signal:null,Ut=!!Te.getState().getDirectoryState(M)?.tabs.find(zt=>zt.id===te)?.label?.startsWith("Action:");ce(M,te,`\\r\\n[Process exited${qe!==null?` with code ${qe}`:""}${gt!==null?` (signal ${gt})`:""}]\\r\\n`),G(M,te,"exited"),Y(M,te,!1),Ie(Ut?null:"Terminal session ended"),Se(!1),Ne(!1),y();break}}},onError:(je,qe)=>{if(V.current===be){if(!qe){Ie(null),Se(!1);return}if(Ne(!1),je.code==="SESSION_NOT_FOUND"&&!Te.getState().getDirectoryState(M)?.tabs.find(Et=>Et.id===te)?.label?.startsWith("Action:")){Ie(null),Se(!1),Y(M,te,!1),U(M,te,null),G(M,te,"idle"),y();return}Ie(`Connection failed: ${je.message}`),Se(!0),Y(M,te,!1),G(M,te,"exited"),U(M,te,null),y()}}});q.current=()=>{ot.close(),V.current=null}},[ce,ae,y,Je,z,Y,G,U,s]);o.useEffect(()=>{let M=!1;if(!I||!pe)return;if(!m){Ie(S?"No working directory available for terminal.":"Select a session to open the terminal."),y();return}return(async()=>{const be=m;if(!xe.current||xe.current!==be)return;if(!Te.getState().getDirectoryState(be)){R(be);return}const je=Te.getState().getDirectoryState(be);if(!je||je.tabs.length===0)return;const qe=je.activeTabId??je.tabs[0]?.id??null;if(!qe)return;const gt=je.tabs.find(jt=>jt.id===qe)??je.tabs[0],Et=gt?.terminalSessionId??null,Ut=gt?.lifecycle??"idle",zt=!!gt?.label?.startsWith("Action:"),ns=Te.getState().getBuffer(be,qe),Jt=ns.byteLength>0||ns.chunks.length>0;if(!Et){if(Ut==="exited"){Y(be,qe,!1);return}if(zt&&Jt){Y(be,qe,!1);return}const jt=`${be}\0${qe}`;if(Xe.current.has(jt))return;const It=Me.current??_i;Xe.current.add(jt),Ie(null),Se(!1),Ne(!1),Y(be,qe,!0);try{const _=await s.createSession({cwd:be,sessionId:qe,cols:It.cols,rows:It.rows,shell:c,loginShell:d,...i.current}),ee=!M&&xe.current===be&&ge.current===qe;if(!Te.getState().getDirectoryState(be)?.tabs.find(me=>me.id===qe)){try{await s.close(_.sessionId)}catch{}return}if(U(be,qe,_.sessionId),!ee)return;const de=Me.current;de&&(de.cols!==It.cols||de.rows!==It.rows)&&s.resize({sessionId:_.sessionId,...de}).catch(()=>{});return}catch(_){const ee=Te.getState().getDirectoryState(be)?.tabs.find(re=>re.id===qe);if(!ee||ee.terminalSessionId||(Y(be,qe,!1),xe.current!==be||ge.current!==qe))return;Ie(_ instanceof Error?_.message:"Failed to start terminal session"),Se(!0),Ne(!1);return}finally{Xe.current.delete(jt)}}!Et||M||(H.current=Et,X(be,qe,Et))})(),()=>{M=!0,H.current=null,y()}},[S,m,$,Ce,L,pe,h,I,R,Y,G,U,X,y,s,d,c]),o.useEffect(()=>{if(!O||b)return;if(typeof window>"u"){Je();return}const M=window.requestAnimationFrame(()=>{Je()});return()=>{window.cancelAnimationFrame(M)}},[L,Je,O,b]);const ue=o.useCallback(async()=>{if(!m||Qe)return;const M=Te.getState().getDirectoryState(m),te=L??M?.activeTabId??M?.tabs[0]?.id??null;if(!te)return;const be=M?.tabs.find(ot=>ot.id===te)?.terminalSessionId??null;if(!(!be||!s.restartSession)){ze(!0),Ie(null),Se(!1),Ne(!1),y(),Ae();try{const ot=Me.current??_i,je=await s.restartSession(be,{cwd:m,shell:c,loginShell:d,...ot,...i.current});if(Te.getState().getDirectoryState(m)?.tabs.find(gt=>gt.id===te)?.terminalSessionId!==be||(U(m,te,je.sessionId),G(m,te,"running"),xe.current!==m||ge.current!==te))return;H.current=je.sessionId,X(m,te,je.sessionId)}catch(ot){if(Te.getState().getDirectoryState(m)?.tabs.find(qe=>qe.id===te)?.terminalSessionId!==be||xe.current!==m||ge.current!==te)return;Ie(ot instanceof Error?ot.message:"Failed to restart terminal"),Se(!1),Ne(!1),H.current=be,X(m,te,be)}finally{ze(!1)}}},[L,y,m,h,Qe,Ae,G,U,X,s,d,c]),he=o.useCallback(async()=>{await ue()},[ue]),Ee=o.useCallback(()=>{if(!m)return;const M=D(m);F(m,M),Ie(null),Se(!1),Ne(!1),y()},[D,y,m,F]),Ke=o.useCallback(()=>{const M=ve.current?.getSelection(),te=N??(A?.open?"draft":null);!M||!te||!J||!m||Q({directory:m,sessionKey:te},{source:"terminal",fileLabel:J.label,startLine:M.startLine,endLine:M.endLine,code:M.text,language:J.terminalSessionId??J.id,text:""})},[J,Q,N,m,A?.open]),ft=o.useCallback(M=>{m&&(F(m,M),Ie(null),Se(!1),Ne(!1),y())},[y,m,F]),At=o.useCallback(M=>{if(!m)return;M===L&&y(),Ie(null),Se(!1),Ne(!1);const te=Te.getState().getDirectoryState(m)?.tabs.find(be=>be.id===M)?.terminalSessionId;(async()=>{te&&await s.close(te),T(m,M)})().catch(be=>Ie(be instanceof Error?be.message:"Terminal session ended"))},[L,T,y,m,s]),Ze=o.useCallback(M=>{if(!M||rt)return;let te=M,be=!1;ye&&M.length>0&&(te=Gm(M,ye),be=!0);const ot=H.current;ot&&(s.sendInput(ot,te).catch(je=>{rt||Ie(je instanceof Error?je.message:"Failed to send input")}),be&&(Re(null),it()))},[ye,it,rt,Re,s]),mt=o.useCallback((M,te)=>{const be=Me.current;if((!be||be.cols!==M||be.rows!==te)&&(Me.current={cols:M,rows:te}),!O)return;const ot=H.current;ot&&s.resize({sessionId:ot,cols:M,rows:te}).catch(()=>{})},[O,s]),bt=o.useCallback(M=>{Re(te=>te===M?null:M),it()},[it,Re]),Fe=o.useCallback(M=>{const te=$m(M,ye);te&&(Ze(te),Re(null),it())},[ye,it,Ze,Re]),Ye=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),St=o.useCallback(M=>{if(M.repeat)return;const te=M.key;if(!te||te==="Control"||te==="Meta"||te==="Alt"||te==="Shift")return;const be=te.length===1?te.toLowerCase():te;if(be in Ye){M.preventDefault(),M.stopPropagation(),Fe(Ye[be]);return}if(ye!=="ctrl")return;const ot=M.code??"",je=te.length===1&&/[a-zA-Z]/.test(te)?te.toUpperCase():ot.startsWith("Key")&&ot.length===4?ot.slice(3).toUpperCase():null;if(je&&je.length===1&&je>="A"&&je<="Z"){const qe=el(je);if(!qe)return;M.preventDefault(),M.stopPropagation(),Ze(qe),Re(null),it()}},[ye,it,Fe,Ze,Ye,Re]);o.useEffect(()=>{if(!(!C||!ye||!$))return window.addEventListener("keydown",St),()=>window.removeEventListener("keydown",St)},[ye,St,C,$]);const Ot=o.useMemo(()=>{const M=dn[pr].stack;if(typeof window>"u")return(dn[a]??dn[pr]).stack;const be=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return be&&be.trim().length>0?be.trim():(dn[a]??dn[pr]).stack??M},[a]),Gt=o.useMemo(()=>gm(r),[r]),vt=`${m??"no-dir"}::${L??"no-tab"}`;if(o.useEffect(()=>{if(!O||b)return;const M=ve.current;if(!M)return;const te=()=>{M.fit()};if(typeof window<"u"){const be=window.requestAnimationFrame(()=>{te(),Je()}),ot=[220,400].map(je=>window.setTimeout(te,je));return()=>{window.cancelAnimationFrame(be),ot.forEach(je=>window.clearTimeout(je))}}te()},[Je,O,b,vt,$]),o.useEffect(()=>{if(!O||!b)return;let M=null;const te=()=>{M!==null&&window.cancelAnimationFrame(M),M=window.requestAnimationFrame(()=>{M=null,ve.current?.fit()})};return window.addEventListener("oc:keyboard-settled",te),()=>{window.removeEventListener("oc:keyboard-settled",te),M!==null&&window.cancelAnimationFrame(M)}},[O,vt,b]),!S)return e.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(!m)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[e.jsx("p",{children:"No working directory available for this session."}),e.jsx("button",{onClick:ue,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const P=!$||We||Qe||rt,Pe=pe,Le=v?"lg":"xs",He=v?"w-10 p-0":"w-9 p-0",ut=M=>{v&&M.preventDefault()},_t=e.jsxs(e.Fragment,{children:[e.jsx(Ve,{type:"button",size:Le,variant:"outline",onPointerDown:ut,onClick:()=>Fe("esc"),disabled:P,children:"Esc"}),e.jsxs(Ve,{type:"button",size:Le,variant:"outline",className:He,onPointerDown:ut,onClick:()=>Fe("tab"),disabled:P,children:[e.jsx(j,{name:"arrow-right",className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"chip","aria-pressed":ye==="ctrl",className:v?"px-3":"px-2",onPointerDown:ut,onClick:()=>bt("ctrl"),disabled:P,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"chip","aria-pressed":ye==="alt",className:v?"px-3":"px-2",onPointerDown:ut,onClick:()=>bt("alt"),disabled:P,children:[e.jsx("span",{className:"text-xs font-medium",children:"Alt"}),e.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"outline",className:He,onPointerDown:ut,onClick:()=>Fe("arrow-up"),disabled:P,children:[e.jsx(j,{name:"arrow-up"}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"outline",className:He,onPointerDown:ut,onClick:()=>Fe("arrow-left"),disabled:P,children:[e.jsx(j,{name:"arrow-left"}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"outline",className:He,onPointerDown:ut,onClick:()=>Fe("arrow-down"),disabled:P,children:[e.jsx(j,{name:"arrow-down"}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"outline",className:He,onPointerDown:ut,onClick:()=>Fe("arrow-right"),disabled:P,children:[e.jsx(j,{name:"arrow-right"}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ve,{type:"button",size:Le,variant:"outline",className:He,onPointerDown:ut,onClick:()=>Fe("enter"),disabled:P,children:[e.jsx(j,{name:"arrow-go-back"}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[e.jsxs("div",{className:E("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",v?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[p?e.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[e.jsx("div",{className:E("min-w-0 flex-1",v?"h-8":"h-7"),children:e.jsx(Tm,{items:fe,activeId:L,onSelect:ft,onClose:At,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),e.jsx(Ve,{type:"button",size:"xs",variant:"ghost",className:E("shrink-0",v?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Ee,title:"New tab",children:e.jsx(j,{name:"add",className:`${v?"h-[18px] w-[18px]":"h-4 w-4"}`})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[e.jsx(Ve,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ue()},disabled:Qe,title:"Restart terminal","aria-label":"Restart terminal",children:e.jsx(j,{name:"restart",className:"h-4 w-4"})}),e.jsx(Ve,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:Ke,title:"Attach selected output","aria-label":"Attach selected output",children:e.jsx(j,{name:"attachment-2",className:"h-4 w-4"})}),$e?e.jsxs(Ve,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{m&&B(m,$e)},title:"Open preview pane",children:[e.jsx(j,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!v&&C&&h&&p?e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:_t}):null,!v&&C&&!p?e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:_t}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Gt.background},children:[e.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:Pe?e.jsx(Xa,{ref:M=>{ve.current=M},sessionKey:vt,chunks:we,onInput:Ze,onResize:mt,theme:Gt,fontFamily:Ot,fontSize:l,enableTouchScroll:b,autoFocus:O,isVisible:O},vt):null}),!rt&&Be&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[e.jsx("span",{children:Be}),Z&&v&&e.jsx(Ve,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:he,disabled:Qe,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),v&&C?e.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",children:e.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:_t})}):null]})},Km=ws(()=>({statusById:new Map})),ax=()=>{pa(),ca()},lx=t=>{Oe.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),oe.getState().prepareForRuntimeSwitch(t.previousRuntimeKey),pa(),Te.getState().clearAll(),Is.getState().resetForRuntimeSwitch(),ts.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),Lt.getState().resetForRuntimeSwitch(),Ed.getState().resetForRuntimeSwitch(),Km.setState({statusById:new Map}),Rd(),Md(),Lu.getState().reset(),hu.getState().resetForRuntimeSwitch(),ea.getState().resetForRuntimeSwitch(t.runtimeKey),qh.getState().resetForRuntimeSwitch(),Wt.getState().resetForRuntimeSwitch(t.runtimeKey),pu.getState().resetForRuntimeSwitch(t.runtimeKey),Oe.getState().restoreForRuntimeSwitch(t.runtimeKey),oe.getState().restoreForRuntimeSwitch(t.runtimeKey);const s=oe.getState();Vr({sessionId:Oe.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),ca()};function cx({className:t="h-5 w-5"}){return e.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${t}`,children:[e.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),e.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),e.jsx(j,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Ui({size:t,className:s,style:n,...r}){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof t=="number"?`${t}px`:t,height:typeof t=="number"?`${t}px`:t,...n},...r,children:e.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 Dr=()=>Os.filter(t=>zr.has(t.id)).map(t=>({...ma(t)})),Hm=()=>{if(typeof window>"u")return $r;const t=window.localStorage.getItem("openInAppId");return t&&Ur(t)?t:$r};let Pr=!1,Qs=!1,ks=!1,Ns=0,mn=null;const zi=()=>{mn&&(clearTimeout(mn),mn=null)},Rs=ws()((t,s)=>({selectedAppId:Hm(),availableApps:Dr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Pr||typeof window>"u")return;Pr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){t({availableApps:Dr(),hasLoadedApps:u});return}const x=new Set(d.map(h=>h.name)),g=new Map(d.map(h=>[h.name,h.iconDataUrl??void 0])),b=Os.filter(h=>x.has(h.appName)||zr.has(h.id)).map(h=>({...ma(h),iconDataUrl:g.get(h.appName)}));t({availableApps:b,hasLoadedApps:!0})},r=async d=>{if(!ys()||!bn()||Qs||s().hasLoadedApps&&!d)return;const x=Os.map(g=>g.appName);zi(),Qs=!0,ks=!1,t({isScanning:!0});try{const{apps:g,success:v,hasCache:b,isCacheStale:h}=await ei(x,d),f=v&&!b&&g.length===0&&Ns<3;if(t({isCacheStale:b?h:!1}),n(g,v?!f:!1),v){if(f){const N=[800,1600,3200][Ns]??3200;Ns+=1,ks=!0,mn=setTimeout(()=>{r()},N);return}Ns=0,ks=!1;return}if(Ns<3){const N=[1e3,3e3,7e3][Ns]??7e3;Ns+=1,ks=!0,mn=setTimeout(()=>{r()},N)}}finally{Qs=!1,ks||t({isScanning:!1})}};r();const i=d=>{const u=d.detail,x=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Ur(u.openInAppId)?u.openInAppId:null;x&&(window.localStorage.setItem("openInAppId",x),t({selectedAppId:x}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(Ns=3,ks=!1,t({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",i),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Pr||s().initialize(),!ys()||!bn()||Qs||s().hasLoadedApps&&!n)return;const i=Os.map(a=>a.appName);zi(),n&&t({hasLoadedApps:!1}),Qs=!0,ks=!1,t({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await ei(i,n),d=new Set(a.map(v=>v.name)),u=new Map(a.map(v=>[v.name,v.iconDataUrl??void 0])),g=Os.filter(v=>d.has(v.appName)||zr.has(v.id)).map(v=>({...v,iconDataUrl:u.get(v.appName)}));t({availableApps:g.length>0?g:Dr(),hasLoadedApps:g.length>0,isCacheStale:l?c:!1})}finally{Qs=!1,ks||t({isScanning:!1})}},selectApp:async n=>{Ur(n)&&(t({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await ao({openInAppId:n}))}})),Wm="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",Vm="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",Tr=t=>({...t,fallbackIconDataUrl:t.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Wm:t.id==="terminal"?Vm:void 0}),$i=({label:t,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,i]=o.useState(!1),a=t.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?e.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>i(!0)}):e.jsx("span",{className:E("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},Ym=({directory:t,className:s})=>{const n=Rs(h=>h.selectedAppId),r=Rs(h=>h.availableApps),i=Rs(h=>h.isCacheStale),a=Rs(h=>h.isScanning),l=Rs(h=>h.initialize),c=Rs(h=>h.loadInstalledApps),d=Rs(h=>h.selectApp);o.useEffect(()=>{l()},[l]);const u=ys()&&bn(),x=o.useMemo(()=>{const h=r.find(f=>f.id===n)??r.find(f=>f.id===$r)??r[0]??Os[0];return Tr(h||Os[0])},[r,n]);if(!u||!t||r.length===0)return null;const g=async h=>{await mu(t,h.id,h.appName)||await fa(t,h.appName)},v=async h=>{await d(h.id),await g(h)},b=async()=>{(await Bs(t)).ok&&ne.success("Path copied to clipboard")};return e.jsxs("div",{className:E("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[e.jsx("button",{type:"button",onClick:()=>{g(x)},className:E("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${x.label}`,children:e.jsx($i,{label:x.label,iconDataUrl:x.iconDataUrl,fallbackIconDataUrl:x.fallbackIconDataUrl})}),e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:E("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:e.jsx(j,{name:"arrow-down-s",className:"h-4 w-4"})})}),e.jsxs(Yt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[e.jsxs(ct,{className:"flex items-center gap-2",onClick:()=>{b()},children:[e.jsx(j,{name:"file-copy",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),e.jsx(As,{}),r.map(h=>{const f=Tr(h);return e.jsxs(ct,{className:"flex items-center gap-2",onClick:()=>{v(h)},children:[e.jsx($i,{label:h.label,iconDataUrl:h.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl}),e.jsx("span",{className:"typography-ui-label text-foreground",children:h.label}),x.id===h.id?e.jsx(j,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},h.id)}),i?e.jsxs(ct,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[e.jsx(j,{name:"refresh",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},qm=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],Qm=["dev","start","preview","serve"];async function Jm(t,s,n){if(!t)return null;const r=eg(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=tg(n);if(i){const a=await sg(t);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${i}`,label:`Start (${i})`}}}if(await Zm(t)){const i=await Xm(),a=typeof i=="number"&&Number.isFinite(i)&&i>0?i:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function Zm(t){const s=`${t}/index.html`,n=await Jn(s,t);return typeof n=="string"&&n.trim().length>0}async function Xm(){try{const t=await ss("/api/system/free-port",{cache:"no-store"});if(!t.ok)return null;const s=await t.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function eg(t){for(const s of t){const n=`${s.name} ${s.command}`.toLowerCase();if(Qm.some(i=>n.includes(i)))return s}return null}function tg(t){for(const{pattern:s}of qm)for(const n of Object.keys(t))if(s.test(n))return n;return null}async function sg(t){const s=await Jn(`${t}/package.json`,t);if(s)try{const r=JSON.parse(s),i=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(i.startsWith("bun@"))return"bun";if(i.startsWith("pnpm@"))return"pnpm";if(i.startsWith("yarn@"))return"yarn";if(i.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,i]of n){const a=await Jn(`${t}/${r}`,t);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function Jn(t,s){if(s?.trim())try{const r=new URLSearchParams({path:t,directory:s,optional:"true"}),i=await ss(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=lo()?.files;if(n?.readFile)try{const r=await n.readFile(t,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await ss(`/api/fs/read?path=${encodeURIComponent(t)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function ng(t){try{const s=await Jn(`${t}/package.json`,t);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const rg=(t,s,n)=>new Promise(r=>{let i=!1,a=null,l=null;const c=d=>{i||(i=!0,l&&clearTimeout(l),a?.close(),r(d))};a=t.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),i?a.close():l=setTimeout(()=>c(!1),n)}),og="\x1B",ig=new RegExp(`${og}\\[[0-9;?]*[ -/]*[@-~]`,"g"),ag=/https?:\/\/[^\s<>'"`]+/gi,es="__pichamber_auto_discover_preview__",lg=15e3,cg=t=>{let s="";for(let n=0;n<t.length;n+=1){const r=t.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=t[n])}return s},dg=t=>{const s=(t||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},ug=t=>{const n=t.replace(ig,"").match(ag);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const i=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&i.push({raw:a,parsed:l})}catch{}if(i.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",x=c.pathname||"/",g=x.split("/").filter(Boolean).length,v=x==="/"||x==="",b=!!(c.search||c.hash);let h=0;return u&&(h+=50),v&&(h+=30),h-=Math.min(g*5,20),b&&(h-=10),h};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},Gi=({projectRef:t,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=la(),{terminal:l}=Zn(),{isMobile:c}=$s(),d=o.useMemo(()=>ys(),[]),u=Yn(O=>O.instances),x=Yn(O=>O.load),g=oe(O=>O.terminalShell),v=oe(O=>O.terminalLoginShells.includes(O.terminalShell)),b=oe(O=>O.setSettingsPage),h=oe(O=>O.setSettingsDialogOpen),f=oe(O=>O.setSettingsProjectsSelectedId),C=oe(O=>O.openContextPreview),N=Te(O=>O.ensureDirectory),A=Te(O=>O.setTabLabel),S=Te(O=>O.setTabIconKey),m=Te(O=>O.setActiveTab),p=Te(O=>O.setConnecting),I=Te(O=>O.setTabSessionId),R=Te(O=>O.setTabPreviewUrl),D=Te(O=>O.projectActionRuns),F=Te(O=>O.setProjectActionRun),T=Te(O=>O.updateProjectActionRunStatus),U=Te(O=>O.removeProjectActionRun),[G,Y]=o.useState([]),[ce,ae]=o.useState(null),[W,Q]=o.useState(!1),B=o.useRef({}),L=o.useRef({}),J=o.useRef({}),fe=o.useRef({}),$=o.useRef(new Set),Ce=o.useRef(0),we=t?.id??null,We=t?.path??"",$e=o.useMemo(()=>we?{id:we,path:We}:null,[we,We]);o.useEffect(()=>{d&&x().catch(()=>{})},[d,x]);const Be=o.useCallback(async O=>{await Vi(O)},[]),Ie=o.useCallback(async()=>{if(!$e)return;const O=Ce.current+1;Ce.current=O,Q(!0);try{const pe=await Er($e);if(Ce.current!==O)return;const De=pe.actions;Y(De),ae(y=>y===es||y&&De.some(z=>z.id===y)?y:null)}catch{if(Ce.current!==O)return}finally{Ce.current===O&&Q(!1)}},[$e]),Z=o.useMemo(()=>Ea(s||$e?.path||""),[s,$e?.path]),Se=o.useMemo(()=>ce?G.find(O=>O.id===ce)??null:null,[G,ce]),rt=o.useMemo(()=>({id:es,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Ne=!c,ye=o.useMemo(()=>Ne?[rt,...G]:G,[G,rt,Ne]);o.useEffect(()=>{Ie()},[Ie]),o.useEffect(()=>{if(typeof window>"u")return;const O=pe=>{const De=pe.detail;we&&(De?.projectId&&De.projectId!==we||Ie())};return window.addEventListener(Qr,O),()=>{window.removeEventListener(Qr,O)}},[Ie,we]),o.useEffect(()=>{ce&&(ce===es&&Ne||G.some(O=>O.id===ce)||ae(null))},[G,Ne,ce]),o.useEffect(()=>{const O=()=>{const pe=Te.getState(),De=pe.sessions,y=pe.projectActionRuns;for(const[z,X]of Object.entries(y)){const he=De.get(X.directory)?.tabs.find(Ye=>Ye.id===X.tabId);if(!he||he.terminalSessionId!==X.sessionId){U(z);continue}const Ee=L.current[z]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};L.current[z]=Ee;const Ke=ye.find(Ye=>Ye.id===X.actionId),ft=pe.getBuffer(X.directory,X.tabId).chunks;if(!Ke||ft.length===0)continue;const At=ft.filter(Ye=>Ee.lastSeenChunkId===null||Ye.id>Ee.lastSeenChunkId);if(At.length===0)continue;const Ze=At.map(Ye=>Ye.data).join(""),mt=`${Ee.tail}${Ze}`,bt=!Ee.openedUrl&&Ke.autoOpenUrl===!0?ug(mt):null,Fe=At[At.length-1]?.id??Ee.lastSeenChunkId;if(Ee.lastSeenChunkId=Fe,Ee.tail=mt.slice(-512),bt)if(Ee.openedUrl=!0,Ee.openInPreview){const Ye=y[z];Ye&&(R(Ye.directory,Ye.tabId,bt,{locked:!1,autoOpened:!1}),Ye.status==="waiting-for-preview"&&T(z,"running"),window.clearTimeout(fe.current[z]),delete fe.current[z],C(Ye.directory,bt))}else Be(bt),ne.success("Opened URL from action output");L.current[z]=Ee}for(const z of Object.keys(L.current))y[z]||(delete L.current[z],window.clearTimeout(fe.current[z]),delete fe.current[z])};return O(),Te.subscribe((pe,De)=>{(pe.sessions!==De.sessions||pe.buffers!==De.buffers)&&O()})},[ye,C,Be,D,U,R,T]);const Re=o.useCallback(async(O,pe={})=>{if(!Z)throw new Error("No active directory");const De=xs(Z,O.id);N(Z);const y=Te.getState(),z=y.getDirectoryState(Z);let X=B.current[De]||null;const ue=X?!!z?.tabs.some(Ke=>Ke.id===X):!1;(!X||!ue)&&(X=y.createTab(Z),B.current[De]=X),A(Z,X,`Action: ${O.name}`),S(Z,X,O.icon||"play"),m(Z,X),pe.revealTerminal!==!1&&oe.getState().openContextPanelTab(Z,{mode:"terminal"});const Ee=Te.getState().getDirectoryState(Z)?.tabs.find(Ke=>Ke.id===X);return{key:De,tabId:X,sessionId:Ee?.terminalSessionId??null}},[N,Z,m,S,A]),Qe=o.useCallback(async O=>{if(!i&&c)return;if(!Z){ne.error("No active directory for action");return}const pe=xs(Z,O.id),De=D[pe];if(!(De&&De.status==="running")&&!$.current.has(pe)){$.current.add(pe);try{const y=O.id===es?await(async()=>{const[Fe,Ye]=await Promise.all([Er({id:$e?.id??"",path:Z}),ng(Z)]),St=await Jm(Z,Fe.actions,Ye);if(!St)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:es,name:"Auto-discover",command:St.command,icon:"scan-2",autoOpenUrl:!0,openUrl:St.previewUrlHint||""}})():O,z=y.autoOpenUrl===!0&&(y.openUrl||"").trim().length>0,X=!z&&O.id!==es,{key:ue,tabId:he,sessionId:Ee}=await Re(y,{revealTerminal:X});let Ke=Ee;if(!Ke){p(Z,he,!0);try{Ke=(await l.createSession({cwd:Z,sessionId:he,shell:g,loginShell:v,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,I(Z,he,Ke)}finally{p(Z,he,!1)}}if(!Ke)throw new Error("Failed to create terminal session");J.current[ue]?.(),p(Z,he,!0);const ft=l.connect(Ke,{onEvent:Fe=>{Fe.type==="snapshot"&&(Te.getState().replaceBuffer(Z,he,Fe.data??"",Fe.sequence??0),Te.getState().setConnecting(Z,he,!1)),Fe.type==="data"&&typeof Fe.data=="string"&&Fe.data.length>0&&Te.getState().appendToBuffer(Z,he,Fe.data,Fe.sequence,Fe.replayData),Fe.type==="exit"&&(Te.getState().setTabLifecycle(Z,he,"exited"),Te.getState().setConnecting(Z,he,!1),Te.getState().removeProjectActionRun(ue),delete L.current[ue],J.current[ue]?.(),delete J.current[ue],window.clearTimeout(fe.current[ue]),delete fe.current[ue])},onError:(Fe,Ye)=>{Te.getState().setConnecting(Z,he,!1),Ye&&(Te.getState().setTabLifecycle(Z,he,"exited"),Te.getState().setTabSessionId(Z,he,null),Te.getState().removeProjectActionRun(ue))}});J.current[ue]=ft.close;const At=y.autoOpenUrl===!0&&d&&(y.desktopOpenSshForward||"").trim().length>0,Ze=y.autoOpenUrl?dg(y.openUrl):null,mt=y.autoOpenUrl&&d?Cf(y.desktopOpenSshForward,u):null;F({key:ue,directory:Z,actionId:y.id,tabId:he,sessionId:Ke,status:y.id===es&&!Ze?"waiting-for-preview":"running"}),window.clearTimeout(fe.current[ue]),delete fe.current[ue],y.id===es&&!Ze&&(fe.current[ue]=window.setTimeout(()=>{const Fe=Te.getState(),Ye=Fe.projectActionRuns[ue];Fe.updateProjectActionRunStatus(ue,"running"),Ye&&(Fe.setActiveTab(Ye.directory,Ye.tabId),oe.getState().openContextPanelTab(Ye.directory,{mode:"terminal"})),delete fe.current[ue]},lg)),L.current[ue]={lastSeenChunkId:null,openedUrl:!!mt||!!Ze||z,tail:"",openInPreview:y.id===es};const bt=cg(y.command.trim().replace(/\r\n|\r/g,`
|
|
47
|
-
`));await l.sendInput(Ke,`${bt}\r`),mt?(R(Z,he,null,{locked:!0}),Be(mt),ne.success("Opened forwarded URL")):Ze?(R(Z,he,Ze,{locked:!0,autoOpened:!0}),C(Z,Ze),ne.success("Opened action URL")):z?(R(Z,he,null,{locked:!0}),ne.error("Invalid custom URL format")):At?(R(Z,he,null,{locked:!0}),ne.error("Selected desktop SSH forward is unavailable")):R(Z,he,null,{locked:!1,autoOpened:!1})}catch(y){U(pe),delete L.current[pe],J.current[pe]?.(),delete J.current[pe],window.clearTimeout(fe.current[pe]),delete fe.current[pe],ne.error(y instanceof Error?y.message:"Failed to run action")}finally{$.current.delete(pe)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,Re,i,c,d,Z,v,g,Be,C,D,U,p,F,R,I,$e?.id,l]),ze=o.useCallback(async O=>{const pe=xs(Z,O.id),De=D[pe];if(!De)return;T(pe,"stopping");const y=rg(l,De.sessionId,1e3);try{await l.sendInput(De.sessionId,"")}catch{}const z=await y;if(Te.getState().getDirectoryState(De.directory)?.tabs.find(he=>he.id===De.tabId)?.terminalSessionId===De.sessionId&&!z){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:De.sessionId})}catch{}else try{await l.close(De.sessionId)}catch{}I(De.directory,De.tabId,null)}U(pe),delete L.current[pe],J.current[pe]?.(),delete J.current[pe],window.clearTimeout(fe.current[pe]),delete fe.current[pe]},[Z,D,U,I,l,T]),q=o.useCallback(()=>{const O=Se??ye[0];if(!O)return;const pe=xs(Z,O.id),De=D[pe];if(De?.status!=="stopping"){if(De){ze(O);return}Qe(O)}},[ye,Z,Qe,D,Se,ze]),V=o.useCallback((O,pe=!1)=>{if(ae(O.id),!pe){Qe(O);return}const De=xs(Z,O.id),y=D[De];if(y?.status!=="stopping"){if(y){ze(O);return}Qe(O)}},[Z,Qe,D,ze]),ge=o.useCallback(()=>{$e?.id&&(f($e.id),b("projects"),h(!0))},[h,b,f,$e?.id]),H=Se??ye[0]??null,xe=H?D[xs(Z,H.id)]:null,ve=Te(O=>xe?O.sessions.get(xe.directory)?.tabs.find(pe=>pe.id===xe.tabId)?.previewUrl??null:null);if(!i&&c||!$e||!Z)return null;const Me=Se??ye[0]??null;if(!Me)return null;const Xe=Me.icon||"play",at=Me.id===es?"scan-2":pn[Xe]||"play",dt=xs(Z,Me.id),Ue=D[dt],Ae=Ue?.status==="stopping",Je=Ue?.status==="waiting-for-preview",it=!!(Ue&&ve),wt=()=>{!Ue||!ve||C(Ue.directory,ve)},yt=Me.id===es;return r?e.jsxs("div",{className:"inline-flex items-center",children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",disabled:W||Ae,className:E("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:q,"aria-label":Ue?`Stop ${Me.name}`:`Run ${Me.name}`,children:Ae||Je?e.jsx(j,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):Ue?e.jsx(j,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):e.jsx(j,{name:at,className:"h-5 w-5"})})}),yt?e.jsx(nt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),it?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.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:wt,children:e.jsx(j,{name:"global",className:"h-4 w-4"})})}),e.jsx(nt,{sideOffset:6,children:"Open Preview"})]}):null,e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.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:e.jsx(j,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[e.jsxs(ct,{className:"flex items-center gap-2",onClick:ge,children:[e.jsx(j,{name:"add",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),e.jsx(As,{}),ye.map(O=>{const pe=O.icon||"play",De=O.id===es?"scan-2":pn[pe]||"play",y=xs(Z,O.id),z=D[y],X=!!z,ue=z?.status==="stopping";return e.jsxs(ct,{className:"flex items-center gap-2",onClick:()=>{V(O,!0)},children:[e.jsx(j,{name:De,className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),ue||z?.status==="waiting-for-preview"?e.jsx(j,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):X?e.jsx(j,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]}):e.jsxs("div",{className:E("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:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:q,disabled:W||Ae,className:E("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":Ue?`Stop ${Me.name}`:`Run ${Me.name}`,children:e.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:Ae||Je?e.jsx(j,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):Ue?e.jsx(j,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):e.jsx(j,{name:at,className:"h-4 w-4"})})})}),yt?e.jsx(nt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),it?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:wt,className:E(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:e.jsx(j,{name:"global",className:"h-4 w-4"})})}),e.jsx(nt,{sideOffset:6,children:"Open Preview"})]}):null,e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:E(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:e.jsx(j,{name:"arrow-down-s",className:"h-4 w-4"})})}),e.jsxs(Yt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[e.jsxs(ct,{className:"flex items-center gap-2",onClick:ge,children:[e.jsx(j,{name:"add",className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),e.jsx(As,{}),ye.map(O=>{const pe=O.icon||"play",De=O.id===es?"scan-2":pn[pe]||"play",y=xs(Z,O.id),z=D[y],X=!!z,ue=z?.status==="stopping";return e.jsxs(ct,{className:"flex items-center gap-2",onClick:()=>{V(O,!0)},children:[e.jsx(j,{name:De,className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),ue||z?.status==="waiting-for-preview"?e.jsx(j,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):X?e.jsx(j,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]})},ar="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",fg="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",hg=o.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:i,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:E(a??ar,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:e.jsx(j,{name:l,className:c??"h-[18px] w-[18px]"})})}),e.jsx(nt,{children:e.jsx("p",{children:n})})]}):null}),pg=o.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:i,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?e.jsxs(qt,{children:[e.jsx(Qt,{asChild:!0,children:e.jsx("button",{type:"button",className:E(ar,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:i?e.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(j,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),e.jsxs(Yt,{align:"end",className:"w-64",children:[e.jsx(Vd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),e.jsx(As,{}),r.map(d=>{const u=d.user,x=!!d.current,g=d.source==="gh-cli"?"CLI":"OAuth";return e.jsxs(ct,{className:"gap-2",disabled:l,onSelect:()=>{x||c(d.id)},children:[u?.avatarUrl?e.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:e.jsx(j,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?e.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:u.login}),e.jsx("span",{className:"mx-1 opacity-50",children:"·"}),e.jsx("span",{children:g})]}):null]}),x?e.jsx(j,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):e.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:i?e.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx(j,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),mg=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:x,remoteUpdateError:g,onOpenRemoteUpdate:v}){return e.jsxs(qt,{open:a,onOpenChange:b=>{l(b),b&&c()},children:[e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx(Qt,{asChild:!0,children:e.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:E(ar,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[e.jsx(j,{name:"server",className:"h-[18px] w-[18px]"}),s?e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),e.jsx(nt,{children:e.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),e.jsx(Yt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?e.jsxs("div",{children:[i?null:e.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:x?"Looking for updates...":g||"This instance is up to date."})]}),u?.available?e.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:v,children:"Update"}):null]})}),e.jsx(Wd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),gg=(t,s)=>t===s?!0:!t||!s?!1:t.totalTokens===s.totalTokens&&t.percentage===s.percentage&&t.contextLimit===s.contextLimit&&(t.outputLimit??0)===(s.outputLimit??0)&&(t.normalizedOutput??0)===(s.normalizedOutput??0)&&t.thresholdLimit===s.thresholdLimit&&(t.lastMessageId??"")===(s.lastMessageId??""),xg=t=>{const s=t.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],i=n[1].slice(0,3),a=`${r} ${i}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},Ms=t=>{if(!t)return"";const s=t.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ki=t=>!t?.isOpen||!Array.isArray(t.tabs)||t.tabs.length===0?null:(t.tabs.find(n=>n.id===t.activeTabId)??t.tabs[t.tabs.length-1])?.mode??null,dx=({onToggleLeftDrawer:t,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r})=>{cs("ui.header.render");const i=oe(k=>k.setSessionSwitcherOpen),a=oe(k=>k.toggleSidebar),l=oe(k=>k.isSidebarOpen),c=oe(k=>k.openContextOverview),d=oe(k=>k.closeContextPanel),u=oe(k=>k.activeMainTab),x=oe(k=>k.setActiveMainTab),g=oe(k=>k.shortcutOverrides);oe(k=>k.timeFormatPreference);const v=ts(k=>k.getCurrentModel);Zn();const b=Oe(k=>k.getContextUsage),h=Oe(k=>!!k.newSessionDraft?.open),f=Oe(k=>k.currentSessionId),C=$d(),N=ia(f??""),A=Fd(f),S=o.useMemo(()=>{if(!A)return null;const k=A;return{title:A.title??null,directory:k.directory??null,created:A.time?.created??null,slug:k.slug??null,shareUrl:A.share?.url??null,parentId:A.parentID??null}},[A]),m=Lt(Wr(k=>{if(!k.activeProjectId)return null;const le=k.projects.find(ke=>ke.id===k.activeProjectId);return le?{id:le.id,path:le.path,label:le.label}:null})),p=o.useMemo(()=>{if(!m)return null;const k=m.label?.trim();if(k)return k;const le=m.path.split(/[\\/]/).filter(Boolean);return le[le.length-1]??null},[m]),{isMobile:I}=$s(),R=null,D=o.useRef(null),[F,T]=o.useState(()=>typeof window>"u"?!1:ys()),U=o.useMemo(()=>ha(),[]),G=Ld(),[Y,ce]=o.useState(!1),ae=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:W,side:Q}=da(),B=o.useMemo(()=>{if(typeof window>"u")return null;const k=window.__PICHAMBER_MACOS_MAJOR__;if(typeof k=="number"&&Number.isFinite(k)&&k>0)return k;if(typeof navigator>"u")return null;const le=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!le)return null;const ke=Number.parseInt(le[1],10),xt=Number.parseInt(le[2],10);return Number.isNaN(ke)?null:ke===10?xt:ke},[]);Ge.useEffect(()=>{typeof window>"u"||T(ys())},[]);const L=v(),J=L&&typeof L.limit=="object"&&L.limit!==null?L.limit:null,fe=J&&typeof J.context=="number"?J.context:0,$=J&&typeof J.output=="number"?J.output:0,Ce=b(fe,$),[we,We]=o.useState(null),$e=!f||C;Ge.useEffect(()=>{if(!f){We(k=>k===null?k:null);return}if(Ce&&Ce.totalTokens>0){We(k=>gg(k,Ce)?k:Ce);return}We(k=>k===null?k:null)},[Ce,f,$e]);const Be=oe(k=>k.isSessionSwitcherOpen),Ie=null,Z=null,Se=[],[rt,Ne]=o.useState(!1),[ye,Re]=o.useState(!1),[Qe,ze]=o.useState("Local"),[q,V]=o.useState(!0),[ge,H]=o.useState(!1),[xe,ve]=o.useState(null),[Me,Xe]=o.useState(!1),[at,dt]=o.useState(null),Ue=o.useMemo(()=>xg(Qe),[Qe]),Ae=u==="chat"&&!!we&&we.totalTokens>0,Je=we&&we.contextLimit>0?Math.min(999,we.totalTokens/we.contextLimit*100):0,it=o.useCallback(async()=>{if(!(typeof window>"u"||!F))try{if(bn()){ze("Local"),V(!0);return}V(!1);const k=await gu(),le=Od(),ke=Bd([_d(le),...k.hosts]);if(ke.id===Ud){ze("Local"),V(!0);return}ze(xu(ke.label.trim()||"Instance"))}catch{ze("Local"),V(!0)}},[F]);Ge.useEffect(()=>(it(),bu(()=>{it()})),[it]);const wt=o.useCallback(async()=>{if(q){ve(null),dt(null);return}Xe(!0),dt(null);try{const k=new URLSearchParams({appType:"web",instanceMode:"remote",reportUsage:"false"}),le=await ss(`/api/pi/update-check?${k.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!le.ok)throw new Error(`Server responded with ${le.status}`);const ke=await le.json();ve({available:ke.available??!1,version:ke.version,currentVersion:ke.currentVersion??"unknown",body:ke.body,nextSuggestedCheckInSec:typeof ke.nextSuggestedCheckInSec=="number"?ke.nextSuggestedCheckInSec:void 0,packageManager:ke.packageManager,updateCommand:ke.updateCommand})}catch(k){ve(null),dt(k instanceof Error?k.message:"Failed to check remote instance updates")}finally{Xe(!1)}},[q]);o.useEffect(()=>{ve(null),dt(null),H(!1)},[q,Qe]),o.useEffect(()=>{if(!F||q)return;const k=3e3,le=3600*1e3;let ke=!1,xt=null;const js=us=>{xt=window.setTimeout(()=>{if(ke||typeof document<"u"&&document.visibilityState!=="visible"){js(le);return}wt().finally(()=>{ke||js(le)})},us)};return js(k),()=>{ke=!0,xt!==null&&window.clearTimeout(xt)}},[wt,q,Qe,F]);const yt=o.useCallback(()=>{if(xe?.available){H(!0);return}wt()},[wt,xe?.available]),O=f?S??null:null,pe=o.useRef(null),[De,y]=o.useState(0);o.useEffect(()=>{if(!f){pe.current&&(pe.current=null,y(xt=>xt+1));return}if(O){pe.current={sessionId:f,session:O,expiresAt:Date.now()+2e3};return}const k=pe.current;if(!k||k.sessionId!==f)return;const le=k.expiresAt-Date.now();if(le<=0){pe.current=null,y(xt=>xt+1);return}const ke=window.setTimeout(()=>{pe.current?.sessionId===f&&(pe.current=null),y(xt=>xt+1)},le);return()=>{window.clearTimeout(ke)}},[f,O]);const z=(()=>{if(O)return O;if(!f)return null;const k=pe.current;return k&&k.sessionId===f&&k.expiresAt>Date.now()?k.session:null})(),X=o.useMemo(()=>{const k=typeof z?.directory=="string"?z.directory:"";return Ms(k||"")},[z?.directory]),ue=Oe(k=>k.newSessionDraft?.open?Ms(k.newSessionDraft.directoryOverride??""):""),he=o.useMemo(()=>X||ue,[ue,X]),Ee=oe(o.useCallback(k=>{const le=Ms(he||"");return le?Ki(k.contextPanelByDirectory[le]):null},[he])),ft=oa(he||null),At=!!(p||ft),Ze=o.useMemo(()=>{if(!f)return p??"PiChamber";const k=z?.title?.trim();return k&&k.length>0?k:"Untitled Session"},[p,z?.title,f]),mt=aa(),bt=io(),Fe=Oe(k=>k.updateSessionTitle),Ye=Oe(k=>k.shareSession),St=Oe(k=>k.unshareSession),Ot=Oe(k=>k.archiveSessions),Gt=Oe(k=>k.deleteSessions),[vt,P]=o.useState(!1),[Pe,Le]=o.useState(!1),He=o.useRef(!1),[ut,_t]=o.useState(""),[M,te]=o.useState(null),be=o.useRef(null);o.useEffect(()=>{He.current=!1,Le(!1),P(!1),_t(""),te(null)},[f]);const ot=o.useCallback(()=>{f&&(_t(z?.title?.trim()||Ze),P(!0))},[z?.title,f,Ze]),je=o.useCallback(async()=>{if(!f)return;const k=ut.trim();k&&k!==z?.title?.trim()&&await Fe(f,k),P(!1)},[z?.title,f,ut,Fe]);o.useEffect(()=>{if(!vt)return;const k=le=>{const ke=le.target;(!ke||!be.current?.contains(ke))&&je()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[vt,je]);const qe=o.useCallback(()=>{f&&Bs(f).then(k=>{ne[k.ok?"success":"error"](k.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ne.error("Failed to copy session ID"))},[f]),gt=o.useCallback(async()=>{if(!f)return;const k=await Ye(f),le=k?.share?.url??k?.url;if(le){const ke=await Bs(le);ne[ke.ok?"success":"warning"]("Session shared",{description:ke.ok?"Share link copied to clipboard.":"Failed to copy URL"});return}ne.error("Unable to share session")},[f,Ye]),Et=o.useCallback(()=>{const k=z?.shareUrl;k&&Bs(k).then(le=>{ne[le.ok?"success":"error"](le.ok?"Copied":"Failed to copy URL")}).catch(()=>ne.error("Failed to copy URL"))},[z?.shareUrl]),Ut=o.useCallback(async()=>{if(!f)return;const k=await St(f);ne[k?"success":"error"](k?"Session unshared":"Unable to unshare session")},[f,St]),zt=o.useCallback(async()=>{if(!f||!he){ne.error("Nothing to export");return}try{await bt.syncSession(f)}catch{ne.error("Failed to load the complete session history");return}const k=Lr(mt.getState()).list;if(k.length===0){ne.error("Nothing to export");return}const le=Ya(k,z?.title??null),ke=Ja(z?.title??null);await Qa(le,ke)||qa(le,ke),ne.success("Session exported")},[z?.title,f,mt,he,bt]);N?.type==="busy"||N?.type;const ns=o.useCallback(async()=>{if(!f||!M)return;const k=zd(),le=[f];for(let us=0;us<le.length;us+=1){const an=le[us];for(const ms of k)ms.parentID===an&&!le.includes(ms.id)&&le.push(ms.id)}const ke=M;if(te(null),(ke==="archive"?await Ot(le):await Gt(le)).failedIds.length>0){ne.error(ke==="archive"?"Failed to archive session":"Failed to delete session");return}ne.success(ke==="archive"?"Session archived":"Session deleted")},[Ot,f,Gt,M]),Jt=oe(k=>k.isArchivePageOpen),jt=o.useMemo(()=>Jt?{title:"Archive",subtitle:null}:null,[Jt]),It=o.useMemo(()=>Ms(he||m?.path||""),[m?.path,he]),_=o.useMemo(()=>m?{id:m.id,path:m.path}:null,[m]),ee=o.useRef(null);o.useEffect(()=>{!_||!It||(ee.current={projectRef:_,directory:It})},[It,_]);const re=o.useMemo(()=>_&&It?{projectRef:_,directory:It}:ee.current,[It,_]),de=o.useCallback(async k=>{},[]),me=o.useCallback(()=>{if(typeof document>"u")return;const k=document.activeElement;if(!k)return;const le=k.tagName;(le==="INPUT"||le==="TEXTAREA"||le==="SELECT"||k.isContentEditable)&&k.blur()},[]),ht=o.useCallback(()=>{if(I){me(),i(!Be);return}a()},[me,I,Be,i,a]),Dt=o.useCallback(()=>{hn("desktop_open_draft_mini_chat_window",{directory:Ms(he||m?.path||""),projectId:m?.id??null,apiBaseUrl:_r(),clientToken:Br()}).catch(k=>{console.warn("[header] failed to open draft mini chat window",k)})},[m?.id,m?.path,he]),Rt=o.useCallback(()=>{if(h){Dt();return}f&&hn("desktop_open_session_mini_chat_window",{sessionId:f,directory:Ms(he||m?.path||""),apiBaseUrl:_r(),clientToken:Br()}).catch(k=>{console.warn("[header] failed to open session mini chat window",k)})},[m?.path,f,Dt,h,he]),Zt=o.useCallback(()=>{const k=Ms(he||"");if(!k)return;const le=oe.getState().contextPanelByDirectory[k];if(Ki(le)==="context"){d(k);return}c(k)},[d,c,he]),is=Ee==="context",Pt=ar,rs=fg,as=o.useMemo(()=>n?"sessions":r?"git":u,[u,n,r]),ds=o.useCallback(()=>{n&&t&&t(),r&&s&&s(),!t&&Be&&i(!1)},[Be,n,t,s,r,i]),on=o.useCallback(()=>{t?.()},[t]),Hs=o.useCallback(()=>{s?.()},[s]),Ws=o.useMemo(()=>F&&ae&&!Y?"5.5rem":G?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!F||W?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[F,Y,ae,G,W]);Ge.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Ws)},[Ws]);const K=l?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",_e=l?"0px":"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)";Ge.useEffect(()=>{if(!F||!ae){ce(!1);return}let k=!1;const le=async()=>{try{const xt=await hn("desktop_is_window_fullscreen");k||ce(xt===!0)}catch{k||ce(!1)}},ke=()=>{le()};return le(),window.addEventListener("pichamber:window-resized",ke),()=>{k=!0,window.removeEventListener("pichamber:window-resized",ke)}},[F,ae]);const lt=o.useMemo(()=>!F||!ae||B===null?"":B>=26?"h-12":B<=15?"h-14":"",[F,ae,B]),Ct=o.useMemo(()=>{if(!(F&&!W))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))"}},[F,W]),kt=o.useCallback(()=>{if(typeof document>"u")return;const k=D.current?.getBoundingClientRect().height;k&&document.documentElement.style.setProperty("--oc-header-height",`${k}px`)},[]);Ge.useEffect(()=>{if(typeof window>"u")return;kt();const k=D.current;if(!k||typeof ResizeObserver>"u")return()=>{};let le=0;const ke=()=>{le||(le=requestAnimationFrame(()=>{le=0,kt()}))},xt=new ResizeObserver(ke);return xt.observe(k),window.addEventListener("resize",ke),window.addEventListener("orientationchange",ke),()=>{le&&cancelAnimationFrame(le),xt.disconnect(),window.removeEventListener("resize",ke),window.removeEventListener("orientationchange",ke)}},[kt]),Ge.useEffect(()=>{kt()},[kt,I,lt]);const Bt=o.useCallback(async k=>{const le=k.target;le.closest(".app-region-no-drag")||le.closest("button, a, input, select, textarea")||k.button===0&&F&&await yu()},[F]),Kt=o.useMemo(()=>I?[{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"}]:[],[I]),Ht=o.useCallback(k=>oo(fn(k,g)),[g]);Ge.useEffect(()=>{!I&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&x("chat")},[u,I,x]);const Xt=o.useMemo(()=>{const k=[];return F&&k.push({value:"instance",label:"Instance",icon:e.jsx(j,{name:"server",className:"h-3.5 w-3.5"})}),k},[F]);Ge.useEffect(()=>{const k=le=>{if(Gd(le)&&!le.shiftKey&&!le.altKey){const ke=parseInt(le.key,10);ke>=1&&ke<=Kt.length&&(le.preventDefault(),I&&(me(),ds()),x(Kt[ke-1].id))}};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[me,ds,I,x,Kt]),Ge.useEffect(()=>{const k=le=>{const ke=fn("toggle_services_menu",g);if(Jo(le,ke)){le.preventDefault(),ye?Re(!1):(Re(!0),it());return}const xt=fn("cycle_services_tab",g);if(Jo(le,xt)){if(le.preventDefault(),Xt.length===0)return;Re(!0),it();return}};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[g,ye,Xt,it]);const Ps=k=>{const le=u===k.id,ke=k.icon==="diff",xt=ke?null:k.icon,js=k.id==="chat",us=ms=>ke?e.jsx(Ui,{size:ms}):xt?e.jsx(j,{name:xt,className:`h-${ms/4} w-${ms/4}`}):null,an=e.jsxs("button",{type:"button",onClick:()=>x(k.id),className:E("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",le?"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",js&&!I&&"min-w-[100px] justify-center"),"aria-label":k.label,"aria-selected":le,role:"tab",children:[I?us(20):e.jsxs(e.Fragment,{children:[us(16),e.jsx("span",{className:"header-tab-label",children:k.label})]}),k.badge!==void 0&&k.badge>0&&e.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:k.badge})]});return e.jsx(o.Fragment,{children:an},k.id)},Nt=e.jsxs(e.Fragment,{children:[e.jsx(Ym,{directory:It,className:"mr-1"}),F?e.jsx(mg,{isDesktopApp:F,currentInstanceLabel:Qe,compactCurrentInstanceLabel:Ue,currentInstanceIsLocal:q,isDesktopServicesOpen:ye,setIsDesktopServicesOpen:Re,refreshCurrentInstanceLabel:it,shortcutLabel:Ht,remoteUpdateInfo:xe,remoteUpdateChecking:Me,remoteUpdateError:at,onOpenRemoteUpdate:yt}):null,e.jsx(pg,{isMobile:I,githubAuthStatus:R,githubAccounts:Se,githubAvatarUrl:Ie,githubLogin:Z,isSwitchingGitHubAccount:rt,handleGitHubAccountSwitch:de})]}),Mt=U&&(h||!!f),Ss=()=>e.jsxs("div",{onMouseDown:Bt,className:E("app-region-drag relative flex h-12 select-none items-center pr-3",lt),style:Ct,role:"tablist","aria-label":"Main navigation",children:[e.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:K}}),e.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",style:{width:_e}}),e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[jt?e.jsxs("div",{className:"mr-3 flex min-w-0 flex-col items-start px-1 py-0.5 -my-0.5 text-left",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:jt.title}),jt.subtitle?e.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:jt.subtitle}):null]}):e.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:[l?null:e.jsx(Kd,{align:"start",children:e.jsx("button",{type:"button",className:Pt,"aria-label":"Open session switcher",children:e.jsx(j,{name:"history",className:"h-[18px] w-[18px]"})})}),e.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[vt?e.jsxs("form",{ref:be,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:k=>{k.preventDefault(),je()},children:[e.jsx("input",{value:ut,onChange:k=>_t(k.target.value),autoFocus:!0,onKeyDown:k=>{k.stopPropagation(),k.key==="Escape"&&P(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(j,{name:"check",className:"size-4"})}),e.jsx("button",{type:"button",onClick:()=>P(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(j,{name:"close",className:"size-4"})})]}):e.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:h?"New session":Ze}),At?e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[p?e.jsx("span",{className:"truncate",children:p}):null,ft?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(j,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:ft})]}):null]}):null]}),e.jsx("div",{className:E("flex h-[18px] shrink-0 items-center justify-center",At?"self-start":"self-center"),children:f&&!h&&!vt?e.jsxs(qt,{open:Pe,onOpenChange:Le,onOpenChangeComplete:k=>{!k&&He.current&&(He.current=!1,ot())},children:[e.jsx(Qt,{asChild:!0,children:e.jsx(Ve,{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:e.jsx(j,{name:"more",className:"size-4"})})}),e.jsxs(Yt,{align:"end",className:"min-w-[190px]",children:[e.jsxs(ct,{onClick:()=>{He.current=!0},children:[e.jsx(j,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),e.jsxs(ct,{onClick:qe,children:[e.jsx(j,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),e.jsx(As,{}),z?.shareUrl?e.jsxs(e.Fragment,{children:[e.jsxs(ct,{onClick:Et,children:[e.jsx(j,{name:"file-copy",className:"mr-2 size-4"}),"Copy link"]}),e.jsxs(ct,{onClick:()=>{Ut()},children:[e.jsx(j,{name:"link-unlink-m",className:"mr-2 size-4"}),"Unshare"]})]}):e.jsxs(ct,{onClick:()=>{gt()},children:[e.jsx(j,{name:"share-2",className:"mr-2 size-4"}),"Share"]}),e.jsxs(ct,{onClick:()=>{zt()},children:[e.jsx(j,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),e.jsx(As,{}),e.jsxs(ct,{onClick:()=>te("archive"),children:[e.jsx(j,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),e.jsxs(ct,{className:"text-destructive focus:text-destructive",onClick:()=>te("delete"),children:[e.jsx(j,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Kt.length>0&&e.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Kt.map(k=>Ps(k))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[re?e.jsx(Gi,{projectRef:re.projectRef,directory:re.directory,className:"mr-1"}):null,Ae&&we?e.jsx(Hd,{totalTokens:we.totalTokens,percentage:Je,colorPercentage:we.percentage,contextLimit:we.contextLimit,outputLimit:we.outputLimit??0,size:"compact",hideIcon:!0,showPercentIcon:!0,onClick:Zt,pressed:is,className:Mt?"":"mr-3.5",valueClassName:"typography-ui-label font-medium leading-none text-foreground",percentIconClassName:"h-4.5 w-4.5"}):null,e.jsx(hg,{visible:Mt,title:h?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:h?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Rt,className:E(Pt,"mr-1"),Icon:"picture-in-picture-2"}),Nt,e.jsx(ua,{visible:W&&Q==="right",position:"right"})]})]})]}),lr=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t?e.jsx("button",{type:"button",onClick:on,className:E(rs,as==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:e.jsx(j,{name:"layout-left",className:"h-5 w-5"})}):Be?e.jsx("button",{type:"button",onClick:()=>i(!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:e.jsx(j,{name:"arrow-left-s",className:"h-5 w-5"})}):e.jsx("button",{type:"button",onClick:ht,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:e.jsx(j,{name:"play-list-add",className:"h-5 w-5"})}),!t&&Be&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!Be||!!t)&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:e.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain",children:e.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:e.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:Kt.map(k=>{const le=u===k.id,ke=k.icon==="diff",xt=ke?null:k.icon;return e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{I&&(me(),ds()),x(k.id)},"aria-label":k.label,"aria-selected":le,role:"tab",className:E(rs,"relative rounded-lg",as===k.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ke?e.jsx(Ui,{className:"h-5 w-5"}):xt?e.jsx(j,{name:xt,className:"h-5 w-5"}):null,k.badge!==void 0&&k.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:k.badge}),k.showDot&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),e.jsx(nt,{children:e.jsx("p",{children:k.label})})]},k.id)})})})})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[re&&e.jsx(Gi,{projectRef:re.projectRef,directory:re.directory,compact:!0,allowMobile:!0,className:"h-9"}),s?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:Hs,className:E(rs,"relative",as==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:e.jsx(j,{name:"layout-right",className:"h-5 w-5"})})}),e.jsx(nt,{children:e.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),jn=E("header-safe-area relative z-10 bg-background",I&&"border-b border-border/50");return e.jsxs(e.Fragment,{children:[e.jsx("header",{ref:D,className:jn,style:{"--padding-scale":"1"},children:I?lr():Ss()}),e.jsx(hs,{open:M!==null,onOpenChange:k=>{k||te(null)},children:e.jsxs(ps,{showCloseButton:!1,className:"max-w-sm gap-5",children:[e.jsxs(Ds,{children:[e.jsx(vs,{children:M==="delete"?"Delete session?":"Archive session?"}),e.jsx(Gs,{children:M==="delete"?`\\"${Ze}\\" will be permanently deleted.`:`\\"${Ze}\\" will be archived.`})]}),e.jsxs(Ks,{children:[e.jsx(Ve,{variant:"outline",size:"sm",onClick:()=>te(null),children:"Cancel"}),e.jsx(Ve,{variant:"destructive",size:"sm",onClick:()=>{ns()},children:M==="delete"?"Delete":"Archive"})]})]})}),e.jsx(Ia,{open:ge,onOpenChange:H,info:xe,downloading:!1,downloaded:!1,progress:null,error:at,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Hi="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",ux=()=>{const t=oe(b=>b.isSidebarOpen),s=oe(b=>b.toggleSidebar),n=oe(b=>b.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=oo(fn("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=da(),d=!t,u=l&&c==="left",x=l,g=d||u||x,v=o.useCallback(()=>{hn("desktop_show_app_menu").catch(b=>{console.warn("[titlebar] failed to open app menu",b)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const b=S=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(S)}px`)},h=S=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(S)}px`)};if(!g){b(0),h(0);return}const f=i.current,C=r.current;if(!f||!C){b(0),h(0);return}const N=()=>{const S=Math.max(f.getBoundingClientRect().width,f.scrollWidth);b(S),h(C.getBoundingClientRect().width)};if(N(),typeof ResizeObserver>"u")return;const A=new ResizeObserver(N);return A.observe(f),A.observe(C),()=>{A.disconnect()}},[g,d,u,x]),g?e.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 top-0 z-40 flex select-none items-center pr-2",style:{height:"var(--oc-header-height, 3rem)",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:e.jsxs("div",{ref:i,className:"flex items-center gap-2",children:[u?e.jsx(ua,{visible:!0,position:"left"}):null,x?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:v,"aria-label":"Open PiChamber menu",className:E(Hi,"shrink-0"),children:e.jsx(j,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),e.jsx(nt,{children:e.jsx("p",{children:"PiChamber menu"})})]}):null,d?e.jsxs(tt,{children:[e.jsx(st,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:E(Hi,"shrink-0"),children:e.jsx(j,{name:"layout-left",className:"h-[18px] w-[18px]"})})}),e.jsx(nt,{children:e.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Bn=200,_n="cubic-bezier(0.22, 1, 0.36, 1)",fx=t=>{const s=o.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=o.useState(t);return o.useLayoutEffect(()=>{if(s){r(t);return}if(t){r(!1);let i=0;const a=window.requestAnimationFrame(()=>{i=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(a),window.cancelAnimationFrame(i)}}r(!1)},[t,s]),{slidIn:n,prefersReducedMotion:s,transition:s?"none":`transform ${Bn}ms ${_n}, width ${Bn}ms ${_n}, min-width ${Bn}ms ${_n}, max-width ${Bn}ms ${_n}`}};export{Fs as $,Jg as A,_f as B,qg as C,tx as D,Yn as E,sx as F,xf as G,dx as H,wn as I,df as J,Da as K,Sn as L,Zs as M,ff as N,Mg as O,ox as P,Kg as Q,cf as R,rx as S,ix as T,Ia as U,uf as V,hf as W,Gg as X,Vg as Y,Wg as Z,bf as _,Xf as a,$g as a0,Hg as a1,Yg as a2,Rg as a3,Fg as a4,Lg as a5,Og as a6,Mf as a7,Ug as a8,Wf as a9,Vf as aa,pf as ab,Eg as ac,nx as ad,Zg as ae,lx as b,ex as c,Xg as d,fx as e,ux as f,Tg as g,Uf as h,zf as i,$f as j,di as k,Gf as l,Tm as m,cx as n,Kf as o,Qg as p,Rs as q,ax as r,zg as s,gf as t,$n as u,mo as v,Bg as w,mf as x,go as y,_g as z};
|